-- Markdown for the text editor's preview: md.parse reads CommonMark and
-- GitHub's additions (tables, task lists, ~~strike~~, bare links) into
-- blocks, md.markup turns a block's inline text into Pango markup, and
-- md.build makes the widgets. Raw HTML isn't shown: its tags are
-- dropped and its text kept, as a reader of the source would read it.
local md = {}
local function trim(s)
return (s:gsub("^%s+", ""):gsub("%s+$", ""))
end
-- Tabs to spaces, stopping every 4 columns, as CommonMark counts them
local function detab(line)
if not line:find("\t", 1, true) then
return line
end
local out, col = {}, 0
for ch in line:gmatch(".") do
if ch == "\t" then
local n = 4 - col % 4
out[#out + 1] = (" "):rep(n)
col = col + n
else
out[#out + 1] = ch
col = col + 1
end
end
return table.concat(out)
end
local function indent_of(line)
return #line:match("^ *")
end
local function blank(line)
return line:match("^%s*$") ~= nil
end
-- Takes up to n columns of indentation off
local function dedent(line, n)
local have = indent_of(line)
return line:sub(math.min(have, n) + 1)
end
-- Line kinds that start a block
local function fence_of(line)
local ind, fence, info = line:match("^( ? ? ?)(```+)([^`]*)$")
if not fence then
ind, fence, info = line:match("^( ? ? ?)(~~~+)(.*)$")
end
if fence then
return #ind, fence, trim(info)
end
end
local function heading_of(line)
local hashes, text = line:match("^ ? ? ?(#+)%s+(.-)%s*$")
if not hashes then
hashes = line:match("^ ? ? ?(#+)%s*$")
text = ""
end
if hashes and #hashes <= 6 then
-- A closing run of #s goes, unless it is the whole text
text = text:gsub("%s+#+$", ""):gsub("^#+$", "")
return #hashes, text
end
end
local function is_rule(line)
local s = line:match("^ ? ? ?([-*_][-*_ \t]*)$")
if not s then
return false
end
local c = s:sub(1, 1)
local bare = s:gsub("[ \t]", "")
return #bare >= 3 and not bare:find("[^" .. (c == "-" and "%-" or c == "*"
and "%*" or "_") .. "]")
end
-- A list item's marker: what kind, its number, and the indent its
-- content has
local function item_of(line)
local ind, bullet, gap, rest = line:match("^( ? ? ?)([-+*])( *)(.*)$")
local kind, number
if bullet then
kind = bullet
else
local digits, delim
ind, digits, delim, gap, rest =
line:match("^( ? ? ?)(%d%d?%d?%d?%d?%d?%d?%d?%d?)([.)])( *)(.*)$")
if not digits then
return nil
end
kind, number = delim, tonumber(digits)
bullet = digits .. delim
end
if gap == "" and rest ~= "" then
return nil -- "-foo" and "1.5" aren't items
end
local width = #ind + #bullet
if rest == "" then
gap = " "
elseif #gap > 4 then
-- Indented code in an item: the marker counts one space
rest = (" "):rep(#gap - 1) .. rest
gap = " "
end
return kind, number, width + #gap, rest
end
local function is_html_start(line)
return line:match("^ ? ? ?<[/!?%a]") ~= nil
end
-- A GitHub table's second line: |:--|--:|; how many cells and how each
-- is aligned
local function delimiter_row(line)
local s = trim(line)
if not s:find("-", 1, true) or s:find("[^|:%- ]") then
return nil
end
s = s:gsub("^|", ""):gsub("|$", "")
local align = {}
for cell in (s .. "|"):gmatch("([^|]*)|") do
cell = trim(cell)
if not cell:match("^:?%-+:?$") then
return nil
end
local l, r = cell:sub(1, 1) == ":", cell:sub(-1) == ":"
-- false, not nil, for none: a nil would leave a hole
align[#align + 1] = l and r and "center" or r and "right" or
l and "left" or false
end
return align
end
-- A table row's cells, split on | that isn't escaped or in code
local function split_row(line)
local s = trim(line)
if s:sub(1, 1) == "|" then
s = s:sub(2)
end
if s:sub(-1) == "|" and s:sub(-2, -2) ~= "\\" then
s = s:sub(1, -2)
end
local cells, cur, i, tick = {}, {}, 1, nil
while i <= #s do
local c = s:sub(i, i)
if c == "\\" and s:sub(i + 1, i + 1) == "|" then
cur[#cur + 1] = "|"
i = i + 2
else
if c == "`" then
local run = s:match("^`+", i)
if tick == nil then
tick = run
elseif tick == run then
tick = nil
end
cur[#cur + 1] = run
i = i + #run
else
if c == "|" and not tick then
cells[#cells + 1] = trim(table.concat(cur))
cur = {}
else
cur[#cur + 1] = c
end
i = i + 1
end
end
end
cells[#cells + 1] = trim(table.concat(cur))
return cells
end
-- Whether a line ends a paragraph by starting something else
local function interrupts(line)
if blank(line) or fence_of(line) or heading_of(line) or is_rule(line)
or line:match("^ ? ? ?>") or is_html_start(line) then
return true
end
local kind, number, _, rest = item_of(line)
-- Only a list starting at 1, with something in it, breaks in
return kind ~= nil and rest ~= "" and (number == nil or number == 1)
end
local function norm_label(s)
return trim(s):gsub("%s+", " "):lower()
end
local parse_lines
-- Blocks from lines (already detabbed); refs collects [label]: url
function parse_lines(lines, refs)
local blocks = {}
local i, n = 1, #lines
local para -- the paragraph being read, its lines
local function end_para()
if not para then
return
end
-- Link definitions at its start aren't shown
local text = table.concat(para, "\n")
while true do
local label, url, rest = text:match(
"^ ? ? ?%[([^%]]+)%]:%s*<?([^%s>]+)>?[^\n]*\n?(.*)$")
if not label then
break
end
local key = norm_label(label)
if refs[key] == nil then
refs[key] = url
end
text = rest
end
if trim(text) ~= "" then
blocks[#blocks + 1] = { type = "para", text = text }
end
para = nil
end
while i <= n do
local line = lines[i]
local level, htext = heading_of(line)
local find, fence, info = fence_of(line)
local kind, number, content, first = item_of(line)
local align = not para and line:find("|", 1, true) and lines[i + 1]
and delimiter_row(lines[i + 1])
if blank(line) then
end_para()
i = i + 1
elseif para and (line:match("^ ? ? ?=+%s*$") or
line:match("^ ? ? ?%-+%s*$")) then
-- Setext: the paragraph above was a heading
local text = table.concat(para, "\n")
para = nil
blocks[#blocks + 1] = { type = "heading",
level = line:find("=", 1, true) and 1 or 2, text = trim(text) }
i = i + 1
elseif para and indent_of(line) >= 4 then
para[#para + 1] = line -- a lazy line, not code
i = i + 1
elseif indent_of(line) >= 4 then
local code = {}
while i <= n and (indent_of(lines[i]) >= 4 or blank(lines[i])) do
code[#code + 1] = dedent(lines[i], 4)
i = i + 1
end
while #code > 0 and blank(code[#code]) do
code[#code] = nil
end
blocks[#blocks + 1] = { type = "code", text = table.concat(code, "\n") }
elseif fence then
end_para()
local code = {}
i = i + 1
while i <= n do
local l = lines[i]
local _, close, rest = fence_of(l)
if close and close:sub(1, 1) == fence:sub(1, 1) and
#close >= #fence and rest == "" then
i = i + 1
break
end
code[#code + 1] = dedent(l, find)
i = i + 1
end
blocks[#blocks + 1] = { type = "code", lang = info:match("^(%S+)"),
text = table.concat(code, "\n") }
elseif level then
end_para()
blocks[#blocks + 1] = { type = "heading", level = level, text = htext }
i = i + 1
elseif is_rule(line) then
end_para()
blocks[#blocks + 1] = { type = "rule" }
i = i + 1
elseif line:match("^ ? ? ?>") then
end_para()
local inner = {}
while i <= n do
local l = lines[i]
local q = l:match("^ ? ? ?> ?(.*)$")
if q then
inner[#inner + 1] = q
elseif not blank(l) and #inner > 0 and not blank(inner[#inner])
and not interrupts(l) then
inner[#inner + 1] = l -- lazy continuation
else
break
end
i = i + 1
end
blocks[#blocks + 1] = { type = "quote",
blocks = parse_lines(inner, refs) }
elseif kind and not (para and (first == "" or
(number and number ~= 1))) then
end_para()
local list = { type = "list", ordered = number ~= nil,
start = number, items = {}, tight = true }
local gap_before = false
while i <= n do
local k, _, c, f = item_of(lines[i])
if k ~= kind or (k and is_rule(lines[i])) then
break
end
if gap_before then
list.tight = false
end
local inner = { f }
i = i + 1
local last_blank = false
while i <= n do
local l = lines[i]
if blank(l) then
inner[#inner + 1] = ""
last_blank = true
elseif indent_of(l) >= c then
inner[#inner + 1] = dedent(l, c)
last_blank = false
elseif not last_blank and not interrupts(l) and
not item_of(l) then
inner[#inner + 1] = l -- lazy continuation
else
break
end
i = i + 1
end
-- Blank lines at its end belong between the items
gap_before = false
while #inner > 1 and inner[#inner] == "" do
inner[#inner] = nil
gap_before = true
end
local item = { }
local task, rest = inner[1]:match("^%[([ xX])%]%s+(.*)$")
if task then
item.task = task ~= " "
inner[1] = rest
end
-- A blank line between two of its blocks makes it loose
for j = 2, #inner - 1 do
if inner[j] == "" and inner[j + 1] ~= "" and
inner[j - 1] ~= "" then
list.tight = false
end
end
item.blocks = parse_lines(inner, refs)
list.items[#list.items + 1] = item
if gap_before and not (i <= n and item_of(lines[i]) == kind) then
break
end
end
blocks[#blocks + 1] = list
elseif is_html_start(line) and not para then
local html = {}
while i <= n and not blank(lines[i]) do
html[#html + 1] = lines[i]
i = i + 1
end
blocks[#blocks + 1] = { type = "html", text = table.concat(html, "\n") }
elseif align then
local head = split_row(line)
if #head == #align then
local tbl = { type = "table", align = align, head = head, rows = {} }
i = i + 2
while i <= n and not blank(lines[i]) and not interrupts(lines[i]) do
local row = split_row(lines[i])
for j = #row + 1, #head do
row[j] = ""
end
for j = #head + 1, #row do
row[j] = nil
end
tbl.rows[#tbl.rows + 1] = row
i = i + 1
end
blocks[#blocks + 1] = tbl
else
para = { trim(line) }
i = i + 1
end
else
para = para or {}
para[#para + 1] = line:gsub("^%s+", "")
i = i + 1
end
end
end_para()
return blocks
end
-- { blocks, refs } from a document's text
function md.parse(text)
local lines = {}
text = text:gsub("\r\n?", "\n")
for line in (text .. "\n"):gmatch("([^\n]*)\n") do
lines[#lines + 1] = detab(line)
end
local refs = {}
return { blocks = parse_lines(lines, refs), refs = refs }
end
-- Inline text to Pango markup
local function esc(s)
return (s:gsub("[&<>\"']", { ["&"] = "&", ["<"] = "<",
[">"] = ">", ['"'] = """, ["'"] = "'" }))
end
md.escape = esc
local function hex(rgb)
return string.format("#%06x", rgb or 0)
end
local PUNCT = "[!\"#$%%&'()*+,%-./:;<=>?@%[\\%]^_`{|}~]"
-- Where a link's destination and title end: (url "title"); returns the
-- url and the index after the )
local function link_tail(s, i)
if s:sub(i, i) ~= "(" then
return nil
end
local j = i + 1
j = s:match("^%s*()", j)
local url
if s:sub(j, j) == "<" then
local close = s:find(">", j, true)
if not close then
return nil
end
url = s:sub(j + 1, close - 1)
j = close + 1
else
local depth, k = 0, j
while k <= #s do
local c = s:sub(k, k)
if c == "\\" then
k = k + 1
elseif c == "(" then
depth = depth + 1
elseif c == ")" then
if depth == 0 then
break
end
depth = depth - 1
elseif c:match("%s") then
break
end
k = k + 1
end
url = s:sub(j, k - 1)
j = math.min(k, #s + 1) -- a \ at the very end steps past it
end
j = s:match("^%s*()", j)
local q = s:sub(j, j)
if q == '"' or q == "'" or q == "(" then
local close = s:find(q == "(" and ")" or q, j + 1, true)
if not close then
return nil
end
j = s:match("^%s*()", close + 1)
end
if s:sub(j, j) ~= ")" then
return nil
end
return url:gsub("\\(" .. PUNCT .. ")", "%1"), j + 1
end
-- The ] that closes the [ at i, skipping code and escapes
local function close_bracket(s, i)
local depth, k = 0, i
while k <= #s do
local c = s:sub(k, k)
if c == "\\" then
k = k + 1
elseif c == "`" then
local run = s:match("^`+", k)
local close = s:find(run, k + #run, true)
if close then
k = close + #run - 1
end
elseif c == "[" then
depth = depth + 1
elseif c == "]" then
depth = depth - 1
if depth == 0 then
return k
end
end
k = k + 1
end
end
local inline
-- Nodes: { raw = markup } or { delim = "*", n, open, close }
local function nodes_of(s, ctx, in_link)
local nodes, buf = {}, {}
local function flush()
if #buf > 0 then
nodes[#nodes + 1] = { raw = esc(table.concat(buf)) }
buf = {}
end
end
local function raw(m)
flush()
nodes[#nodes + 1] = { raw = m }
end
-- c8.rich's own link: underlined, in the accent, clickable
local function link(inner_markup, url)
ctx.links[#ctx.links + 1] = url
raw(string.format('<a href="%s">%s</a>', esc(url), inner_markup))
end
local i = 1
while i <= #s do
local c = s:sub(i, i)
if c == "\\" then
local nx = s:sub(i + 1, i + 1)
if nx == "\n" then
raw("\n")
i = i + 2
elseif nx:match(PUNCT) then
buf[#buf + 1] = nx
i = i + 2
else
buf[#buf + 1] = c
i = i + 1
end
elseif c == "`" then
local run = s:match("^`+", i)
local close = i + #run
local found
while true do
local a, b = s:find("`+", close)
if not a then
break
end
if b - a + 1 == #run then
found = a
break
end
close = b + 1
end
if found then
local code = s:sub(i + #run, found - 1):gsub("\n", " ")
if code:match("^ .* $") and code:find("[^ ]") then
code = code:sub(2, -2)
end
raw(string.format('<span font_family="monospace" '
.. 'background="%s" bgalpha="12%%">%s</span>',
hex(ctx.fg), esc(code)))
i = found + #run
else
buf[#buf + 1] = run
i = i + #run
end
elseif c == "!" and s:sub(i + 1, i + 1) == "[" then
local close = close_bracket(s, i + 1)
local url, after
if close then
url, after = link_tail(s, close + 1)
end
if url then
-- Inline, a picture is its words
local alt = s:sub(i + 2, close - 1)
raw("<i>" .. esc(alt) .. "</i>")
i = after
else
buf[#buf + 1] = c
i = i + 1
end
elseif c == "[" and not in_link then
local close = close_bracket(s, i)
local url, after
if close then
url, after = link_tail(s, close + 1)
if not url then
-- [text][label], [label][] and [label]
local label = s:match("^%[([^%]]*)%]", close + 1)
local key = label and label ~= "" and label or
s:sub(i + 1, close - 1)
url = ctx.refs[norm_label(key)]
after = close + 1 + (label and #label + 2 or 0)
end
end
if url then
link(inline(s:sub(i + 1, close - 1), ctx, true), url)
i = after
else
buf[#buf + 1] = c
i = i + 1
end
elseif c == "<" then
local auto = s:match("^<(%a[%w+.%-]+:[^%s<>]*)>", i) or
s:match("^<([%w.!#$%%&'*+/=?^_`{|}~%-]+@[%w%-]+%.[%w.%-]+)>", i)
local tag = s:match("^</?%a[%w%-]*[^>]*>", i) or
s:match("^<!%-%-.-%-%->", i)
if auto then
link(esc(auto), auto)
i = i + #auto + 2
elseif tag then
-- Raw HTML: a <br> breaks the line, other tags go
if tag:lower():match("^<br") then
raw("\n")
end
i = i + #tag
else
buf[#buf + 1] = c
i = i + 1
end
elseif c == "\n" then
-- Two spaces at a line's end break it; otherwise a space
local hard = #buf >= 2 and buf[#buf] == " " and buf[#buf - 1] == " "
while buf[#buf] == " " do
buf[#buf] = nil
end
if hard then
raw("\n")
else
buf[#buf + 1] = " "
end
i = i + 1
elseif c == "*" or c == "_" or c == "~" then
local run = s:match("^%" .. c .. "+", i)
local before = i > 1 and s:sub(i - 1, i - 1) or " "
local after = s:sub(i + #run, i + #run)
if after == "" then
after = " "
end
local ws_after, ws_before = after:match("%s"), before:match("%s")
local p_after, p_before = after:match(PUNCT), before:match(PUNCT)
local left = not ws_after and (not p_after or ws_before or p_before)
local right = not ws_before and (not p_before or ws_after or p_after)
local open, close = left, right
if c == "_" then
open = left and (not right or p_before)
close = right and (not left or p_after)
end
if c == "~" and #run > 2 then
open, close = false, false
end
flush()
nodes[#nodes + 1] = { delim = c, n = #run, orig = #run,
open = open, close = close, pre = {}, post = {} }
i = i + #run
elseif not in_link and (c == "h" or c == "w") and
(i == 1 or s:sub(i - 1, i - 1):match("[%s(*_~]")) and
(s:match("^https?://", i) or s:match("^www%.", i)) then
-- A bare address, as GitHub links them
local url = s:match("^[^%s<]+", i)
url = url:gsub("[?!.,:*_~'\"]+$", "")
-- A ) closes one only if there are more ( than ) in it
local _, opens = url:gsub("%(", "")
local _, closes = url:gsub("%)", "")
while closes > opens and url:sub(-1) == ")" do
url = url:sub(1, -2)
closes = closes - 1
end
link(esc(url), url:match("^www%.") and "http://" .. url or url)
i = i + #url
else
buf[#buf + 1] = c
i = i + 1
end
end
flush()
return nodes
end
local TAGS = { ["*"] = { "<i>", "</i>", "<b>", "</b>" },
["_"] = { "<i>", "</i>", "<b>", "</b>" },
["~"] = { "<s>", "</s>", "<s>", "</s>" } }
-- Pairs emphasis runs, closers looking back for the nearest opener
local function emphasis(nodes)
for ci, closer in ipairs(nodes) do
if closer.delim and closer.close then
local oi = ci - 1
while oi >= 1 and closer.n > 0 do
local opener = nodes[oi]
local fits = opener.delim == closer.delim and opener.open and
opener.n > 0
-- The rule of 3: one that can both open and close can't
-- pair with a run whose sizes add to a multiple of 3
if fits and (opener.close or closer.open) and
(opener.orig + closer.orig) % 3 == 0 and
not (opener.orig % 3 == 0 and closer.orig % 3 == 0) then
fits = false
end
if fits and closer.delim == "~" and opener.n ~= closer.n then
fits = false
end
if fits then
local use = (opener.n >= 2 and closer.n >= 2) and 2 or 1
if closer.delim == "~" then
use = opener.n
end
local t = TAGS[closer.delim]
local a, b = use == 2 and t[3] or t[1], use == 2 and t[4] or t[2]
if closer.delim == "~" then
a, b = t[1], t[2]
end
table.insert(opener.post, 1, a)
closer.pre[#closer.pre + 1] = b
opener.n = opener.n - use
closer.n = closer.n - use
-- Runs between them can't pair across this one
for k = oi + 1, ci - 1 do
if nodes[k].delim then
nodes[k].open = false
nodes[k].close = false
end
end
else
oi = oi - 1
end
end
end
end
local out = {}
for _, node in ipairs(nodes) do
if node.raw then
out[#out + 1] = node.raw
else
out[#out + 1] = table.concat(node.pre)
out[#out + 1] = node.delim:rep(node.n)
out[#out + 1] = table.concat(node.post)
end
end
return table.concat(out)
end
function inline(s, ctx, in_link)
return emphasis(nodes_of(s, ctx, in_link))
end
-- Markup for some inline text. ctx: { refs, accent, fg, links = {} }
function md.markup(text, ctx)
ctx.links = ctx.links or {}
ctx.refs = ctx.refs or {}
return inline(trim(text), ctx)
end
-- An HTML block as text: its tags dropped
local ENTITIES = { amp = "&", lt = "<", gt = ">", quot = '"', apos = "'",
nbsp = " " }
-- HTML's text without its tags, entities read
local function html_words(s)
s = s:gsub("<!%-%-.-%-%->", "")
s = s:gsub("<[bB][rR][^>]*>", "\n")
s = s:gsub("</?%a[^>]*>", "")
s = s:gsub("&(#?)(%w+);", function(num, name)
if num == "#" then
local n = name:match("^[xX](%x+)$")
n = n and tonumber(n, 16) or tonumber(name)
return n and n < 0x110000 and utf8.char(n) or nil
end
return ENTITIES[name]
end)
return s
end
local function html_text(s)
return trim(html_words(s))
end
md.html_text = html_text
-- An HTML block as markup: its text, with its <a href> kept as links
local function html_markup(s)
local out, pos = {}, 1
while true do
local a, b, href, inner = s:find(
"<[aA]%s[^>]-href%s*=%s*[\"']([^\"']*)[\"'][^>]*>(.-)</[aA]>", pos)
if not a then
break
end
out[#out + 1] = esc(html_words(s:sub(pos, a - 1)))
out[#out + 1] = string.format('<a href="%s">%s</a>',
esc(html_words(href)), esc(html_words(inner)))
pos = b + 1
end
out[#out + 1] = esc(html_words(s:sub(pos)))
return trim(table.concat(out))
end
md.html_markup = html_markup
-- A heading's anchor as GitHub makes it: its words in lower case, no
-- punctuation, spaces as hyphens
local function slug(markup)
local text = html_words(markup):lower()
text = text:gsub("[^%w%s_%-\128-\255]", "")
return (text:gsub("%s", "-"))
end
md.slug = slug
-- A paragraph that is only a picture (maybe as a link): its address
-- and words
local function lone_picture(text)
local t = trim(text)
local alt, url = t:match("^!%[([^%]]*)%]%(%s*<?([^%s)>]+)>?[^)]*%)$")
local link
if not alt then
alt, url, link = t:match(
"^%[!%[([^%]]*)%]%(%s*<?([^%s)>]+)>?[^)]*%)%]%(%s*<?([^%s)>]+)>?[^)]*%)$")
end
return url, alt, link
end
md.lone_picture = lone_picture
-- Widgets
local BODY = 11 * 96 / 72 -- px
-- Each heading's size as a part of the body's, Metro's light ones
-- above
local HEADINGS = { { 2.2, 300 }, { 1.7, 300 }, { 1.35, 350 },
{ 1.15, 600 }, { 1, 600 }, { 1, 600 } }
local function path_of(src, base)
if src:match("^%a[%w+.%-]*:") and not src:match("^file:") then
return nil -- not on this PC; nothing is fetched for a preview
end
src = src:gsub("^file://", ""):gsub("%%(%x%x)", function(h)
return string.char(tonumber(h, 16))
end)
if src:sub(1, 1) ~= "/" and base then
src = base .. "/" .. src
end
return src
end
-- The widgets for a parsed document, added to box. opts: { c8, colors =
-- w:colors(), base = the document's folder, family, on_link(uri) };
-- returns its headings' widgets by their anchors ("#my-heading")
function md.build(box, doc, opts)
local c8 = opts.c8
local colors = opts.colors or { fg = 0, bg = 0xffffff, accent = 0x1ba1e2 }
local ctx = { refs = doc.refs, accent = colors.accent, fg = colors.fg }
local family = opts.family
local add_blocks
local anchors, seen = {}, {}
local function rich(markup, size, extra)
local t = { markup = markup, family = family, size = size or BODY,
fill = true, line_spacing = 1.15 }
for k, v in pairs(extra or {}) do
t[k] = v
end
if opts.on_link and markup:find("<a ", 1, true) then
t.on_link = function(_, uri) opts.on_link(uri) end
end
return c8.rich(t)
end
-- A line beside what's quoted, in the text's colour, faint
local function bar()
return c8.canvas { width = 4, fill = true, draw = function(g, x, y, w, h)
g:rect(x, y, w, h, g.fg, 0.25)
end }
end
local function picture(url, alt)
local path = path_of(url, opts.base)
-- c8.picture's max scales up as well as down, so only for big ones
local pic = path and c8.picture(path)
if pic then
local w, h = pic:size()
if math.max(w, h) > 1600 then
pic = c8.picture(path, 1600)
w, h = pic:size()
end
return c8.viewbox { align = "start",
c8.image { image = pic, width = w, height = h } }
end
return rich("<i>" .. esc(alt ~= "" and alt or url) .. "</i>",
nil, { color = colors.fg })
end
local function add(parent, b, tight)
if b.type == "heading" then
local h = HEADINGS[b.level]
local markup = md.markup(b.text, ctx)
local w = rich(string.format('<span weight="%d">%s</span>', h[2],
markup), BODY * h[1])
parent:add(w)
-- The same words again get -1, -2... as on GitHub
local id = slug(markup)
local n = seen[id]
seen[id] = (n or 0) + 1
anchors[n and (id .. "-" .. n) or id] = w
elseif b.type == "para" then
local url, alt, link = lone_picture(b.text)
if url and link and opts.on_link then
parent:add(c8.item { tap = "invoke", align = "start",
tooltip = link, picture(url, alt),
on_invoke = function() opts.on_link(link) end })
elseif url then
parent:add(picture(url, alt))
else
parent:add(rich(md.markup(b.text, ctx)))
end
elseif b.type == "html" then
local text = html_text(b.text)
local src = b.text:match("<[iI][mM][gG][^>]-src=[\"']([^\"']+)")
if src then
parent:add(picture(src, text))
elseif text ~= "" then
parent:add(rich(html_markup(b.text)))
end
elseif b.type == "code" then
-- A shade of the text's colour, so it suits dark and light
local bg = colors.bg
local f = 0.07
local mix = 0
for shift = 0, 16, 8 do
local a = (bg >> shift) & 0xff
local z = (colors.fg >> shift) & 0xff
mix = mix | (math.floor(a + (z - a) * f + 0.5) << shift)
end
parent:add(c8.column { fill = true, padding = { 16, 12, 16, 12 },
background = mix,
c8.rich { markup = esc(b.text), family = "monospace",
size = BODY * 0.95, fill = true } })
elseif b.type == "rule" then
parent:add(c8.separator { fill = true })
elseif b.type == "quote" then
local inner = c8.column { spacing = 12, expand = true }
add_blocks(inner, b.blocks)
parent:add(c8.row { spacing = 16, fill = true, bar(), inner })
elseif b.type == "list" then
local list = c8.column { spacing = b.tight and 4 or 12, fill = true }
local widest = #tostring((b.start or 1) + #b.items - 1)
for k, item in ipairs(b.items) do
local mark
if item.task ~= nil then
mark = item.task and "☑" or "☐"
elseif b.ordered then
mark = tostring((b.start or 1) + k - 1) .. "."
else
mark = "•"
end
local inner = c8.column { spacing = b.tight and 4 or 12,
expand = true }
add_blocks(inner, item.blocks, b.tight)
list:add(c8.row { spacing = 6, fill = true,
rich(esc(mark), nil, { width = b.ordered and
12 + 9 * widest or 20, fill = false }),
inner })
end
parent:add(list)
elseif b.type == "table" then
local grid = c8.grid { columns = #b.head, column_spacing = 24,
row_spacing = 8 }
for _, cell in ipairs(b.head) do
grid:add(rich("<b>" .. md.markup(cell, ctx) .. "</b>", nil,
{ fill = false }))
end
for _, row in ipairs(b.rows) do
for _, cell in ipairs(row) do
grid:add(rich(md.markup(cell, ctx), nil, { fill = false }))
end
end
-- Wide tables scroll sideways rather than squeeze
parent:add(c8.scroll { horizontal = true, vertical = false,
fill = true, grid })
end
end
function add_blocks(parent, blocks, tight)
for _, b in ipairs(blocks) do
add(parent, b, tight)
end
end
add_blocks(box, doc.blocks)
return anchors
end
return md