Add docstring and support for creating links for header id attributes

- this method will now look for both of the following references, this
  commit adds support for (2)

(1) <h1><a name="href">Reference Text</a></h1>
and
(2) <h1 id="href">Reference Text</h1>
This commit is contained in:
Adam Tankanow 2015-01-09 07:16:22 -05:00
parent b3bad2e279
commit 5609772cd3

View file

@ -18,16 +18,26 @@
headings)))
[] content))
(defn make-links [headings]
(defn make-links
"Create a table of contents from the given headings. This function will look
for either:
(1) headings with a child anchor with a non-nil name attribute, e.g.
<h1><a name=\"reference\">Reference Title</a></h1>
or
(2) headings with an id attribute, e.g. <h1 id=\"reference\">Reference Title</h1>
In both cases above, the anchor reference becomes \"#reference\" and the
anchor text is \"Reference Title\"."
[headings]
(loop [items headings acc nil _last nil]
(if-let [{tag :tag [{{name :name} :attrs} title] :content} (first items)]
(if (nil? name) (recur (rest items) acc nil)
(let [entry [:li [:a {:href (str "#" name)} title]]
(if-let [{tag :tag {id :id} :attrs [{{name :name} :attrs} title :as htext] :content} (first items)]
(let [anchor (or id name)]
(if (nil? anchor) (recur (rest items) acc nil)
(let [entry [:li [:a {:href (str "#" anchor)} (or title (first htext))]]
jump (compare_index _last tag)]
(cond (> jump 0) (recur (rest items) (str acc "<ol>" (hiccup/html entry)) tag)
(= jump 0) (recur (rest items) (str acc (hiccup/html entry)) tag)
(< jump 0) (recur (rest items) (str acc (apply str (repeat (* -1 jump) "</ol>"))
(hiccup/html entry)) tag))))
(hiccup/html entry)) tag)))))
(str acc "</ol>"))))
(defn generate-toc [html]