Simple indenter

Started by echeam, November 04, 2008, 04:13:31 AM

Previous topic - Next topic

echeam

wrote a simple script to indent lisp code, useful to check syntax and aid comprehension.

Comments or improvements most welcome...



#!/usr/bin/newlisp
; Simple indenter filter for lisp like code
;
; Usage: newlisp lispindent.lsp <scripttoindent> output]
; or in Vim eg.   :%!newlisp lispindent.lsp      
 
(set 'indent "    ") ; try 0, 2, 4, 8 spaces, tab ....
(set 'level 0)
(while (read-line)
   (if (< level 0)(println "ERROR! Too many close-parenthesis. " level))
   (letn ((ln (trim (current-line))) (fc (first ln)))  
; Note newLISP trim does not remove tabs by default, expandtab first
      (if (!= fc ")") (println (dup indent level) ln))  ; (indent & print
      (if (and (!= fc ";") (!= fc "#"))     ; don't count if line starts with ; or #
           (set 'level (+ level (apply - (count (explode "()")
                                                                (explode (current-line)))))))
      (if (= fc ")") (println (dup indent level) ln)))  ; (dedent if close-parenthesis
)
(if (!= level 0) (println "ERROR! Parenthesis not balanced. " level))
Quote

cormullion

#1
That's really nice - thanks. So far it works a treat! A couple of changes required to make it into a BBEdit/TextWrangler filter (I'm not clever enough to use Vim... :):


#!/usr/bin/env newlisp

(set 'indent "    ") ; try 0, 2, 4, 8 spaces, tab ....
(set 'level 0)

(set 'file (open ((main-args) 2) "read"))
(while (read-line file)
    (if (< level 0) (println "ERROR! Too many close-parenthesis. " level))
    (letn ((ln (trim (current-line))) (fc (first ln)))
        ; Note newLISP trim does not remove tabs by default, expandtab first
        (if (!= fc ")") (println (dup indent level) ln))  ; (indent & print
        (if (and (!= fc ";") (!= fc "#"))     ; don't count if line starts with ; or #
            (set 'level
              (+ level (apply - (count (explode "()") (explode (current-line)))))))
        (if (= fc ")") (println (dup indent level) ln)))  ; (dedent if close-parenthesis
)
(if (!= level 0) (println "ERROR! Parenthesis not balanced. " level))
(exit)