yum-slop/yummers.dev

source code for https://yummers.dev

git clone https://git.yummers.dev/yum-slop/yummers.dev

yumadd scripts for inline ToC and image dimensioning49b768a

master
1.8 KiB75 linesraw
1-- Replace an empty `::: {.article-toc}` block with the current article's
2-- table of contents. The block can appear anywhere in the article.
3
4local function escape_html(text)
5  return text:gsub("&", "&")
6             :gsub("<", "&lt;")
7             :gsub(">", "&gt;")
8             :gsub('"', "&quot;")
9             :gsub("'", "&#39;")
10end
11
12local function make_toc(entries)
13  if #entries == 0 then
14    return nil
15  end
16
17  local lines = {
18    '<nav class="article-toc" aria-label="Table of contents">',
19    '<h2>Contents</h2>',
20    '<ul>',
21  }
22  for _, entry in ipairs(entries) do
23    table.insert(lines, string.format(
24      '<li class="toc-level-%d"><a href="#%s">%s</a></li>',
25      entry.level, escape_html(entry.id), escape_html(entry.title)))
26  end
27  table.insert(lines, '</ul>')
28  table.insert(lines, '</nav>')
29  return pandoc.RawBlock('html', table.concat(lines, '\n'))
30end
31
32function Pandoc(doc)
33  local output = pandoc.List()
34  local article = pandoc.List()
35
36  local function flush_article()
37    if #article == 0 then
38      return
39    end
40
41    local entries = pandoc.List()
42    for _, block in ipairs(article) do
43      if block.t == 'Header' and block.level == 2 then
44        entries:insert({
45          level = block.level,
46          id = block.identifier,
47          title = pandoc.utils.stringify(block.content),
48        })
49      end
50    end
51
52    for _, block in ipairs(article) do
53      if block.t == 'Div' and block.classes:includes('article-toc') then
54        local toc = make_toc(entries)
55        if toc then
56          output:insert(toc)
57        end
58      else
59        output:insert(block)
60      end
61    end
62  end
63
64  for _, block in ipairs(doc.blocks) do
65    if block.t == 'Header' and block.level == 1 then
66      flush_article()
67      article = pandoc.List()
68    end
69    article:insert(block)
70  end
71  flush_article()
72
73  doc.blocks = output
74  return doc
75end