about summary refs log tree commit diff
path: root/src/preproc.lua
blob: 4d5805354fca8f9e70bf4930340222b54e416eb5 (plain) (blame)
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
---@diagnostic disable: undefined-global
-- see https://pandoc.org/lua-filters.html
return {
	Link = function(link)
		-- set target="_blank" for outgoing links (open them in new tab)
		if string.match(link.target, "gzr.im") == nil then
			table.insert(link.attributes, { "target", "_blank" })
		end
		return link
	end,
	Pandoc = function(doc)
		local front = pandoc.List()
		local doc_filename = pandoc.path.filename(PANDOC_STATE.input_files[1])

		-- add a comment
		front:extend({
			pandoc.RawBlock("html5", "<!-- Generated file, you may edit and discard " .. doc_filename .. " :) -->"),
		})

		local toc = pandoc.structure.table_of_contents(doc)
		if doc.meta.toc and toc then
			front:extend({
				pandoc.RawBlock("html5", '<nav class="table-of-contents capital">'),
				pandoc.RawBlock("html5", "<ol>"),
				-- insert jump to top
				pandoc.RawBlock("html5", "<li>"),
				pandoc.Link("back to top", "#top"),
				pandoc.RawBlock("html5", "</li>"),
			})
			-- create custom toc
			toc:walk({
				Link = function(e)
					-- check if the section title matches the doc title and dont
					-- add it to the TOC, it's probably the h1 heading
					if string.find(doc_filename, pandoc.utils.stringify(e.content) .. ".md", 1, true) == 1 then
						return
					end

					front:extend({
						pandoc.RawBlock("html5", "<li>"),
						e,
						pandoc.RawBlock("html5", "</li>"),
					})
				end,
			})
			front:extend({
				pandoc.RawBlock("html5", "</ol>"),
				pandoc.RawBlock("html5", "</nav>"),
			})
		end

		-- insert date blocks
		if doc.meta.date then
			front:extend({
				pandoc.RawBlock("html5", '<span class="date">'),
				doc.meta.date,
				pandoc.RawBlock("html5", "</span>"),
			})
		end

		-- prepend front stuffs
		front:extend(doc.blocks)
		doc.blocks = front

		-- return finished ast
		return doc
	end,
}