Skip to content

Instantly share code, notes, and snippets.

@oranenj
Created July 5, 2009 19:12
Show Gist options
  • Save oranenj/141085 to your computer and use it in GitHub Desktop.
Save oranenj/141085 to your computer and use it in GitHub Desktop.
(use '(clojure.contrib monads str-utils))
(defn tag* [the-tag & attrs]
(let [attrs (map (fn [[k v]]
(format "%s=\"%s\"" (name k) v)) (partition 2 attrs))
opening (apply str "<" the-tag (when (seq attrs) " ") (concat attrs [">"]))
closing (str "</" the-tag ">")]
{:opening opening
:closing closing}))
; I want to generate literals :P
(defmacro tag [the-tag & attrs]
(apply tag* the-tag attrs))
(def *ansi-html-mapping*
{;0 close all open tags
1 (tag b)
4 (tag u)
5 (tag blink)
7 (tag i)
30 (tag font color black)
31 (tag font color red)
32 (tag font color green)
33 (tag font color yellow)
34 (tag font color blue)
35 (tag font color purple)
36 (tag font color cyan)
37 (tag font color white)})
(defn extract-ansi-code
[ansi-sequence]
(let [[_ code] (re-matches #"\[(\d*)m" ansi-sequence)]
(try
(Integer/parseInt code)
(catch NumberFormatException e
0))))
(defn transform-ansi-code [code]
(domonad state-m
[:let [{:keys [opening closing]}
(*ansi-html-mapping* code)]
old-state (fetch-state)
text (if (zero? code)
(m-result (apply str old-state))
(m-result opening))
_ (set-state (if closing
(conj old-state closing)
'()))]
text))
(defn process-partition
[mv [text-chunk ansi-seq]]
(domonad state-m
[the-chunk (m-result text-chunk)
v mv
text (if ansi-seq
(transform-ansi-code (extract-ansi-code ansi-seq))
(m-result ""))]
(str v the-chunk text)))
(defn split-string [string]
(partition 2 2 [nil] (re-partition #"\[\d*m" string)))
(defn feed-string [mv string]
(reduce process-partition mv (split-string string)))
; lift the final string out of the monad
(defn finalize [mv]
(let [[text leftover] (mv '())]
(apply str text leftover)))
(def empty-processor
(fn [s] ["" '()]))
(finalize (feed-string empty-processor "foowhiteboldbar"))
(-> empty-processor
(feed-string "foobar")
(feed-string "zonk")
finalize)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment