Simple indenter

Q&A's, tips, howto's
Locked
echeam
Posts: 1
Joined: Mon Nov 03, 2008 3:02 pm

Simple indenter

Post by echeam »

wrote a simple script to indent lisp code, useful to check syntax and aid comprehension.
Comments or improvements most welcome...

Code: Select all

#!/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][/quote]

cormullion
Posts: 2038
Joined: Tue Nov 29, 2005 8:28 pm
Location: latiitude 50N longitude 3W
Contact:

Post by cormullion »

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... :):

Code: Select all

#!/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)

Locked