1 #!/usr/local/bin/newlisp
3 # Stream filter that reads css and writes it out stylished. run with
5 # newlisp humancss.lsp < bad.css > good.css
7 # Not actually pretty-printing, but merely adding indentation and newlines.
9 ;(signal 2 (fn (x) (exit 0)))
13 ;; Load the CSS file as an array of single-character strings
14 (while (setf LINE (read-line)) (extend IN (explode LINE) '("\n")))
15 (setf IN (array (length IN) IN)) ; This should speed of indexed access
16 (setf LAST (- (length IN) 1))
18 ;; Coalsce comments and strings into units
19 (define (coalesce START END) ; exclusive
20 (when (< END (length IN))
21 (setf (IN START) (join (array-list (START (- END START) IN))))
22 (while (< (inc START) END) (setf (IN START) ""))))
24 (define (coalesce-block-comment i)
25 (let ((STAR nil) (END nil))
26 (for (j (+ 2 i) LAST 1 END)
27 (if STAR (if (= "/" (IN j)) (setf END j) (setf STAR nil))
28 (= "*" (IN j)) (setf STAR true)))
29 (when END (coalesce i (+ 1 END)))))
31 (define (coalesce-line-comment i)
32 (let ((END (find "\n" IN nil i)))
33 (when END (coalesce i (+ 1 END)))))
35 (define (index-of-any OPTS START)
36 (if (> START LAST) nil
37 (if (find OPTS (START IN) (fn (X Y) (member Y X))) (+ START $it))))
39 (define (coalesce-string i) ; (IN i) is the string character
41 (for (j (+ 1 i) LAST 1 END)
42 (if (= "\\" (IN j)) (coalesce j (+ 2 j))
43 (= (IN i) (IN j)) (setf END (+ 1 j))))
44 (when END (coalesce i END))))
46 ; Coalesce comments, meta-quotes and strings
49 (if (= "\\" (IN i)) (begin (coalesce i (+ 2 i)) (setf SLASH nil))
50 SLASH (begin (case (IN i)
51 ("*" (coalesce-block-comment (- i 1)))
52 ("/" (coalesce-line-comment (- i 1)))
55 (= "/" (IN i)) (setf SLASH true)
56 (= "\"" (IN i)) (coalesce-string i)
57 (= "'" (IN i)) (coalesce-string i)
60 (define (indent TXT n)
61 (join (clean empty? (parse TXT "\n")) (string "\n" (dup " " n))))
63 ; Coalesce blocks recursively, adding a newline to it
64 (define (coalesce-block i (DEPTH 0))
65 ;(write-line 2 (string "block level " DEPTH " from " i))
66 (let ((j 0) (END nil))
67 (for (j (+ 1 i) LAST 1 END)
69 ("{" (coalesce-block j (+ 1 DEPTH)))
75 (setf (IN i) (indent (IN i) DEPTH))
76 (extend (IN i) (if (ends-with (IN i) "\n") "}\n" "\n}\n"))
80 (for (i 0 LAST) (when (= ";" (IN i)) (setf (IN i) ";\n")))
82 (for (i 0 LAST) (when (= "{" (IN i)) (coalesce-block i 1)))
84 (write 1 (join (array-list IN)))