summaryrefslogtreecommitdiff
path: root/src/clarktown/parsers/heading_block.clj
blob: def2394ccdc8fb4828a50b0a45ea891ec073b24f (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
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
(ns clarktown.parsers.heading-block
  (:require
    [clojure.string :as string]))


(defn is-hashbang-heading?
  "Determines whether the given block is a hashbang heading."
  [block]
  (-> (string/replace block #"\n" "")
      string/trim
      (string/starts-with? "#")))


(defn is-settext-heading?
  "Determines whether the given block is a settext heading."
  [block]
  (let [lines (-> (string/split-lines block))
        chars (-> (last lines)
                  string/trim
                  (string/split #""))]
    (and (> (count lines) 1)
         (every? #{"-" "="} chars))))


(defn is?
  "Determines whether the given block is a heading block."
  [block]
  (or (is-hashbang-heading? block)
      (is-settext-heading? block)))


(defn render-hashbang-heading
  "Renders the hashbang heading block."
  [block]
  (let [single-line-block (-> (string/replace block #"\n" "")
                              string/trim)
        size (-> (string/split single-line-block #" ")
                 first
                 string/trim
                 count)
        value (->> (string/split single-line-block #" ")
                   next
                   (string/join " ")
                   string/trim)]
    (str "<h" size ">" value "</h" size ">")))


(defn render-settext-heading
  "Renders the settext heading block."
  [block]
  (let [lines (string/split-lines block)
        value (->> (split-at (- (count lines) 1) lines)
                   first
                   (string/join "\n"))
        h1? (= "=" (-> (last lines)
                       string/trim
                       (string/split #"")
                       first))]
    (if h1?
      (str "<h1>" value "</h1>")
      (str "<h2>" value "</h2>"))))


(render-settext-heading "Hello world\nAnd you too\n===")


(defn render
  "Renders the heading block."
  [block _]
  (if (is-hashbang-heading? block)
    (render-hashbang-heading block)
    (render-settext-heading block)))