(import chicken scheme)
(use colorize irregex srfi-13 files)
(define *file* (cadr (argv)))
(define *file-contents* (read-string))
(define (guess-type-by-file-extension filename)
(and-let* ((extension (pathname-extension (make-pathname "" filename))))
(case (string->symbol extension)
((scm) 'scheme)
((lisp) 'lisp)
((el) 'elisp)
((c h) 'c)
((cpp) 'c++)
((java) 'java)
((m) 'objective-c)
((erl) 'erlang)
((py) 'python)
((rb) 'ruby)
((hs) 'haskell)
((diff) 'diff)
((css) 'css)
((xml) 'xml)
((xhtml) 'xhtml)
((html) 'html)
(else #f))))
(define (guess-type-by-emacs-major-mode-variable file-contents)
(define (file-local-variables file-contents)
(and-let* ((match (irregex-search (irregex "^.*-\\*-.+-\\*-") file-contents)))
(irregex-search (irregex "-\\*-.+-\\*-") (irregex-match-substring match))))
(define (single-word-mode-line vars)
(irregex-match (irregex "\\s*\\w+\\s*") vars))
(define (mode-variable vars)
(irregex-search (irregex "mode:\\s*\\w+") vars))
(case (and-let* ((vars-match (file-local-variables file-contents))
(var-string (irregex-match-substring vars-match))
(vars (string-downcase
(substring var-string 3 (- (string-length var-string) 3)))))
(cond (#f #f)
((single-word-mode-line vars) =>
(compose string->symbol string-trim-both irregex-match-substring))
((mode-variable vars) =>
(lambda (match)
;; remove mode: and trim
(string->symbol
(string-trim-both (substring (irregex-match-substring match) 5)))))
(else #f)))
((scheme) 'scheme)
((lisp) 'lisp)
((common-lisp) 'common-lisp)
((emacs-lisp) 'elisp)
((c h) 'c)
((c++) 'c++)
((java) 'java)
((erlang) 'erlang)
((python) 'python)
((ruby) 'ruby)
((haskell) 'haskell)
((diff) 'diff)
((css) 'css)
((xml) 'xml)
((xhtml) 'xhtml)
((html) 'html)
(else #f)))
(let ((type (or (guess-type-by-emacs-major-mode-variable *file-contents*)
(guess-type-by-file-extension *file*))))
(if (not type)
(begin (display *file-contents*) (exit 0))
(begin
(display
"")
(display "")
(display
(html-colorize type *file-contents*))
(display ""))))
(exit 0)