How to make *balanced* indent

Started by ssqq, January 05, 2015, 01:32:06 AM

Previous topic - Next topic

ssqq

I used Vim to write newLISP code, How to set following indent:



     (define (sub-name args)

            (built-in-sub args)

     )



     (if (= expr nil)

             (dosth)

      )



if last parenthesis is first char of line, have same indent with his corresponding start parenthesis. Just like *{ ... }* in C-like indent.

ssqq

#1
;; indent-newlisp.lsp
;; Author: ssqq
;; http://www.newlisp.cn
;; usage:
;; ~> newlisp indent-newlisp.lsp your-script.lsp 4 > output.lsp

(define (indent-code input-file (indent 2))
    (local (v-level new-level file-txt file-lines indent-line indent-lines)
        (setq v-level 0)
        (setq file-text (read-file input-file))
        (setq file-lines (map trim (parse file-text "n")))
        (dolist (v-line file-lines)
            (setq new-level (get-new-level v-line v-level))
            (if (starts-with v-line ")")
                (setq indent-line (get-indent-line new-level v-line indent))
                (setq indent-line (get-indent-line v-level v-line indent))
            )
            (push indent-line indent-lines -1)
            (setq v-level new-level)
        )
        (println (join indent-lines "n"))
    )
)

(define (get-new-level v-line v-level)
    (local (close-amount open-amount freeze-line)
        (setq freeze-str (replace {".*?[^\]"}   v-line "" 0))
        (setq freeze-str (replace {{.*?[^\]}}   v-line "" 0))
        (setq freeze-str (replace {[.*?[^\]]} v-line "" 0))
        (setq freeze-str (replace {(?:^|s)(?:;|#).*?$} v-line "" 0))
        (find-all {(} freeze-str)
        (setq open-amount $count)
        (setq v-level (+ open-amount v-level))
        (find-all {)} freeze-str)
        (setq close-amount $count)
        (setq v-level (- v-level close-amount))
    )
)

(define (get-indent-line v-level v-line indent)
    (let (indent-space {})
        (setq indent-space (dup " " (mul v-level (int indent))))
        (append indent-space v-line)
    )
)

(setq input-file (main-args 2))
(setq indent (main-args 3))
(indent-code input-file indent)

(exit)