Shammer's Philosophy

My private adversaria

ソースコードをHTML表示用に整形するLISPver1.0

ソースコードをHTML表示用に整形するLISPver0.4 - Shammerismの継続にして、これをバージョン1.0にしよう。とりあえず、半角スペースと <> とダブルクォート、&の対応は済ませた。ソースコードでよく使用するのはとりあえずこれくらいだろうか。あとは、行数を右揃えにするとか、予約語のハイライトとか、いくつか候補はあるが、とりあえず最低限はこれくらいで。

(defun tr (&rest contents)
  (let ((line "<tr>"))
    (cond ((typep contents 'string)
	   (setf line (concatenate 'string line contents)))
	  ((typep contents 'list)
	   (dolist (x contents)
	     (setf line (concatenate 'string line x)))))
    (concatenate 'string line "</tr>~%")))
       
(defun td (contents &optional is-first-line rows)
  (let ((line "<td"))
    (when is-first-line
      (setf line
	    (concatenate 'string
			 line
			 " rowspan=\""
			 rows
			 "\" style=\"width: 1pm; height: 12px; background-color:green;\"")))
    (setf line (concatenate 'string line ">" contents "</td>"))))

(defun escape-html-character (contents)
  (if (typep contents 'string)
	(let ((return-contents (make-array 0 :element-type 'character :fill-pointer 0 :adjustable t)))
	  (labels ((vpe (s)
		      (dolist (x (coerce s 'list))
			(vector-push-extend x return-contents))))
	    (dolist (x (coerce contents 'list))
	      (cond ((string-equal x " ")
		     (vpe "&nbsp;"))
		    ((string-equal x "<")
		     (vpe "&lt;"))
		    ((string-equal x ">")
		     (vpe "&gt;"))
		    ((string-equal x "\"")
		     (vpe "&quot;"))
		    ((string-equal x "&")
		     (vpe "&amp;"))
		    (t
		     (vector-push-extend (coerce x 'character) return-contents)))))
	  (coerce return-contents 'string))
    contents))

(let ((line-list nil)
      (file-name (first *unprocessed-command-line-arguments*)))
  (format t "<table border='0'>~%")
  (with-open-file (input-stream file-name :direction :input)
		  ;;;; Reading file and structure list by all lines
		  (loop
		   (let ((line (read-line input-stream nil 'eof)))
		     (if (eql line 'eof) (return))
		     (setf line-list
			   (append line-list
				   (cons (escape-html-character line)
					 nil)))))
		  ;;;; output all lines as html
		  (do ((i 1 (+ i 1)))
		      ((null line-list))
		    (format t (tr (td (write-to-string i))
				  (when (equal i 1)
				    (td ""
					t
					(write-to-string (length line-list))))
				  (td (first line-list))))
		    (setf line-list (cdr line-list)))
		  (format t "</table>~%")))
(quit)