summaryrefslogtreecommitdiff
path: root/src/clarktown/parsers/code_block.clj
blob: c6ecfea3225b90dba75f00eff0f779c4be4ff5e1 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
(ns clarktown.parsers.code-block
  (:require
    [clojure.string :as string]))


(defn is?
  "Determines whether we're dealing with a code block."
  [block]
  (and (string/starts-with? block "```")
       (string/ends-with? block "```")))


(defn render
  "Renders the code block."
  [block _]
  (let [language (->> block
                      (re-find #"\`\`\`(\w+)")
                      second)
        lines (string/split-lines block)
        block* (->> (next lines)
                    (take (- (count lines) 2))
                    (string/join \newline))
        code (-> block*
                 (string/replace #"&" "&")
                 (string/replace #"<" "&lt;")
                 (string/replace #">" "&gt;")
                 string/trim)]
    (if language
      (str "<pre><code class=\"language-" language "\">" code "</code></pre>")
      (str "<pre><code>" code "</code></pre>"))))