summaryrefslogtreecommitdiff
path: root/src/clarktown/parsers/link_and_image.clj
blob: 3be2efe6230e123583423e6de94ba2898efa74ea (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
(ns clarktown.parsers.link-and-image
  (:require
    [clojure.string :as string]))


(defn encode-href
  [href]
  (-> href
      (string/replace "_" "_")))


(defn render
  "Renders all occurring links and images."
  [block _]
  (loop [block block
         matches (-> (re-seq #"\!?\[([a-zA-Z0-9\-\.\,]+( [a-zA-Z0-9\-\.\,]+)*)\]\((.*?)\)" block)
                     distinct)]
    (if (empty? matches)
      block
      (let [[whole-match label _ href] (first matches)
            image? (string/starts-with? whole-match "!")
            image (str "<img src=\"" (encode-href href) "\" alt=\"" label "\">")
            link (str "<a href=\"" (encode-href href) "\">" label "</a>")]
        (recur (if image?
                 (string/replace block whole-match image)
                 (string/replace block whole-match link))
               (drop 1 matches))))))