commit ae804b8

myu be you  ·  2026-11-17 17:56:58 +0000 UTC
parent ae804b8
super duper late init
13 files changed,  +1795, -0
+87, -0
 1@@ -0,0 +1,87 @@
 2+.Dd $Mdocdate$
 3+.Dt MIG 1
 4+.Os
 5+.Sh NAME
 6+.Nm MIG
 7+.Nd Mu's Idiotic Generator
 8+.Sh SYNOPSIS
 9+.Nm ./build.lua
10+.Sh DESCRIPTION
11+the
12+.Nm MIG
13+utility is my personal static site generator. it was used for
14+.Lk https://xorg.fyi
15+.Pp
16+.Nm
17+is written in lua, if you couldn't tell. mostly because i couldn't bear with
18+.Pa /bin/sh
19+anymore (won't say
20+.Em just
21+.Dq sh
22+because that's le problematic media)
23+and also for funsies.
24+.Pp
25+the configuration is read from
26+.Pa config.lua
27+and it must return a table
28+.Pp
29+all string variables in the config can reference any other variable using the
30+{VARIABLE} (one curly brace on each side instead of two) syntax. this is le good because you can reference
31+.Va TITLE
32+inside
33+.Va FOOTER
34+or anywhere else in the config.
35+.Pp
36+the config variables are:
37+.Bl -tag -width Ds
38+.It Va TITLE
39+the title of the site. supports any variable from
40+.Pa config.lua
41+.It Va FOOTER
42+the html content to display in the footer. supports any variable from
43+.Pa config.lua
44+.It Va INPUT
45+the source directory containing markdown files and templates. defaults to
46+.Pa template
47+.It Va OUTPUT
48+the destination directory for generated html files. defaults to
49+.Pa public
50+.It Va NAVIGNORE
51+an array of filenames or directories to exclude from the generated navbar
52+.It Va LINK
53+the format string used for nav links
54+.It Va LINKCURR
55+the format string used for the currently active nav link
56+.It Va AFTER
57+an array of shell commands to ruun after a successful build
58+.El
59+.Sh TEMPLATES
60+.Nm
61+reads markdown files and puts the rendered html into
62+.Pa template.html
63+located in the
64+.Va INPUT
65+directory
66+.Pp
67+the templating "engine" supports:
68+.Bl -tag -width Ds
69+.It Li {{CONTENT}}
70+replaced by the rendered markdown content
71+.It Li {{NAV}}
72+replaced by the automatically generated nav menu aka "le heckin werc sidebar"
73+.It Li {{FOOTER}}
74+replaced by the
75+.Va FOOTER
76+variable from the config
77+.It Li {{include \&"file.html\&"}}
78+includes the specified file into the template
79+.It Li {{if VARIABLE}} ... {{end}}
80+conditionally renders the block if the variable is defined and not empty or false
81+.It Li {{if not VARIABLE}} ... {{end}}
82+conditionally renders the block if the variable is undefined, empty, or false (i have not tested the conditionals. that's on you)
83+.It Li {{VARIABLE}}
84+replaced by the corresponding variable from
85+.Pa config.lua
86+.El
87+.Sh SEE ALSO
88+.Xr lua 1
+436, -0
  1@@ -0,0 +1,436 @@
  2+#!/usr/bin/env lua
  3+
  4+local sDir = (function()
  5+  local src = debug.getinfo(1, "S").source
  6+  src = src:sub(2)
  7+  local d = src:match("^(.*)/[^/]+$")
  8+  if d and d ~= "" then return d .. "/" end
  9+  return "./"
 10+end)()
 11+
 12+package.cpath = package.cpath .. ";" .. sDir .. "/lib/?.so"
 13+package.path = package.path .. ";" .. sDir .. "/lib/?.lua"
 14+
 15+local lfs = require("lfs")
 16+local mk = require("markdown")
 17+
 18+local cfg, buf = {}, {}
 19+local chg = false
 20+local exp = {}
 21+
 22+local lg = function(msg) table.insert(buf, msg) end
 23+
 24+local er = function(msg)
 25+  io.stderr:write(":: [error] " .. msg .. "\n")
 26+  os.exit(1)
 27+end
 28+
 29+local ePath = function(p)
 30+  if p:sub(1, 1) == "~" then return (os.getenv("HOME") or "") .. p:sub(2)
 31+  elseif p:sub(1, 1) == "/" then return p
 32+  else return sDir .. p end
 33+end
 34+
 35+local sub = function(s, vars)
 36+  if type(s) ~= "string" then return s end
 37+  return s:gsub("{(%u+)}", function(k)
 38+    if vars[k] ~= nil then return tostring(vars[k]) end
 39+    return "{" .. k .. "}"
 40+  end)
 41+end
 42+
 43+local mDir = function(path)
 44+  path = path:gsub("/+$", "")
 45+  if path == "" then return end
 46+  local pfx = ""
 47+  if path:sub(1, 1) == "/" then
 48+    pfx = "/"
 49+    path = path:sub(2)
 50+  end
 51+  local cur = pfx
 52+  for p in path:gmatch("[^/]+") do
 53+    cur = cur .. p .. "/"
 54+    if lfs.attributes(cur, "mode") ~= "directory" then lfs.mkdir(cur) end
 55+  end
 56+end
 57+
 58+local rFile = function(path)
 59+  local f = io.open(path, "r")
 60+  if not f then return nil end
 61+  local cnt = f:read("*a")
 62+  f:close()
 63+  return cnt
 64+end
 65+
 66+local sCheck = function(path, cnt, srcPath)
 67+  local sz = lfs.attributes(path, "size")
 68+  if not sz or sz ~= #cnt then return false end
 69+  if srcPath then
 70+    local srcM = lfs.attributes(srcPath, "modification")
 71+    local dstM = lfs.attributes(path, "modification")
 72+    if srcM and dstM and dstM >= srcM then return true end
 73+  end
 74+  local f = io.open(path, "rb")
 75+  if not f then return false end
 76+  local existing = f:read("*a")
 77+  f:close()
 78+  return existing == cnt
 79+end
 80+
 81+local wFile = function(path, cnt, srcPath)
 82+  if sCheck(path, cnt, srcPath) then return false end
 83+  local par = path:match("^(.*)/[^/]+$")
 84+  if par and par ~= "" then mDir(par) end
 85+  local f = io.open(path, "w")
 86+  if not f then er("cannot write " .. path) end
 87+  f:write(cnt)
 88+  f:close()
 89+  return true
 90+end
 91+
 92+local mn = function()
 93+  local cPath = sDir .. "config.lua"
 94+  local chk, eMsg = loadfile(cPath)
 95+  if not chk then er("cant load " .. (eMsg or "?")) end
 96+  for k, v in pairs(chk()) do cfg[k] = v end
 97+
 98+  local rsv
 99+  rsv = function(val, seen)
100+    if type(val) ~= "string" then return val end
101+    return val:gsub("{(%u+)}", function(name)
102+      if seen[name] then return "{" .. name .. "}" end
103+      local v = cfg[name]
104+      if v == nil then return "{" .. name .. "}" end
105+      local nSeen = {}
106+      for k in pairs(seen) do nSeen[k] = true end
107+      nSeen[name] = true
108+      local r = rsv(v, nSeen)
109+      if type(r) == "string" then return r end
110+      return tostring(r)
111+    end)
112+  end
113+  for k, v in pairs(cfg) do cfg[k] = rsv(v, {}) end
114+
115+  cfg.NAVIGNORE = cfg.NAVIGNORE or {}
116+  local igs = {}
117+  for _, v in ipairs(cfg.NAVIGNORE) do igs[v] = true end
118+  local ign = function(n) return igs[n] == true end
119+
120+  cfg.INPUT = ePath(cfg.INPUT):gsub("/+$", "")
121+  cfg.OUTPUT = ePath(cfg.OUTPUT):gsub("/+$", "")
122+
123+  local tpl = rFile(cfg.INPUT .. "/template.html")
124+  local cfgM = lfs.attributes(cPath, "modification") or 0
125+  local mdM = lfs.attributes(sDir .. "lib/markdown.lua", "modification") or 0
126+  local tplM = lfs.attributes(cfg.INPUT .. "/template.html", "modification") or 0
127+  local incM = 0
128+  for incPath in tpl:gmatch('{{%s*include%s+"([^"]+)"%s*}}') do
129+    local m = lfs.attributes(cfg.INPUT .. "/" .. incPath, "modification") or 0
130+    if m > incM then incM = m end
131+  end
132+
133+  local navM = 0
134+  local pMts
135+  pMts = function(dir)
136+    for name in lfs.dir(dir) do
137+      if name ~= "." and name ~= ".." then
138+        local f = dir .. "/" .. name
139+        if lfs.attributes(f, "mode") == "directory" then
140+          pMts(f)
141+        elseif name:match("%.md$") then
142+          local m = lfs.attributes(f, "modification") or 0
143+          if m > navM then navM = m end
144+        end
145+      end
146+    end
147+  end
148+  pMts(cfg.INPUT)
149+
150+  local stale = false
151+  local pStale
152+  pStale = function(dir)
153+    for name in lfs.dir(dir) do
154+      if name ~= "." and name ~= ".." then
155+        local p = dir .. "/" .. name
156+        local mode = lfs.attributes(p, "mode")
157+        if mode == "directory" then
158+          pStale(p)
159+        elseif mode == "file" and name:match("%.html$") then
160+          local rel = p:sub(#cfg.OUTPUT + 2)
161+          local src = cfg.INPUT .. "/" .. rel
162+          local sMode = lfs.attributes(src, "mode")
163+          local sMd = lfs.attributes(src:gsub("%.html$", ".md"), "mode")
164+          if sMode ~= "file" and sMd ~= "file" then stale = true end
165+        end
166+      end
167+    end
168+  end
169+  if lfs.attributes(cfg.OUTPUT, "mode") == "directory" then pStale(cfg.OUTPUT) end
170+
171+  local attrCache = {}
172+  local attrGet = function(path, mode)
173+    local key = path .. "\0" .. (mode or "mode")
174+    local v = attrCache[key]
175+    if v == nil then
176+      v = lfs.attributes(path, mode)
177+      if v == nil then v = false end
178+      attrCache[key] = v
179+    end
180+    if v == false then return nil end
181+    return v
182+  end
183+
184+  mDir(cfg.OUTPUT)
185+
186+  lg(":: copying el files from " .. cfg.INPUT)
187+  local cFiles
188+  cFiles = function(dir)
189+    for name in lfs.dir(dir) do
190+      if name ~= "." and name ~= ".." then
191+        local f = dir .. "/" .. name
192+        local mode = lfs.attributes(f, "mode")
193+        if mode == "directory" then
194+          cFiles(f)
195+        elseif mode == "file" then
196+          if not (name:match("%.md$") or f:match("/template%.html$")) then
197+            local rel = f:sub(#cfg.INPUT + 2)
198+            local dst = cfg.OUTPUT .. "/" .. rel
199+            exp[dst] = true
200+            if wFile(dst, rFile(f), f) then
201+              chg = true
202+              lg(f .. " -> " .. dst)
203+            end
204+          end
205+        end
206+      end
207+    end
208+  end
209+  cFiles(cfg.INPUT)
210+
211+  local pCond
212+  pCond = function(s, vars)
213+    local fEnd = function(s, sPos)
214+      local dpt = 1
215+      local pos = sPos
216+      while pos <= #s do
217+        local tStart = s:find("{{", pos, true)
218+        if not tStart then return nil end
219+        local tEnd = s:find("}}", tStart, true)
220+        if not tEnd then return nil end
221+        local tag = s:sub(tStart + 2, tEnd - 1):gsub("^%s+", ""):gsub("%s+$", "")
222+        if tag:match("^if%s") then dpt = dpt + 1
223+        elseif tag == "end" then
224+          dpt = dpt - 1
225+          if dpt == 0 then return tStart, tEnd + 2 end
226+        end
227+        pos = tEnd + 2
228+      end
229+      return nil
230+    end
231+
232+    local out, pos = {}, 1
233+    while pos <= #s do
234+      local tStart = s:find("{{", pos, true)
235+      if not tStart then
236+        table.insert(out, s:sub(pos))
237+        break
238+      end
239+      table.insert(out, s:sub(pos, tStart - 1))
240+      local tEnd = s:find("}}", tStart, true)
241+      if not tEnd then
242+        table.insert(out, s:sub(tStart))
243+        break
244+      end
245+      local tag = s:sub(tStart + 2, tEnd - 1):gsub("^%s+", ""):gsub("%s+$", "")
246+      if tag:match("^if%s") then
247+        local cond = tag:match("^if%s+(.+)$") or ""
248+        local mStart, mEnd = fEnd(s, tEnd + 2)
249+        if not mStart then pos = tEnd + 2
250+        else
251+          local body = s:sub(tEnd + 2, mStart - 1)
252+          local neg, var = cond:match("^not%s+(.+)$")
253+          if not neg then var = cond end
254+          local val = vars[var]
255+          local tru = (val ~= nil and val ~= "" and val ~= false)
256+          if neg then tru = not tru end
257+          if tru then table.insert(out, pCond(body, vars)) end
258+          pos = mEnd
259+        end
260+      else
261+        table.insert(out, "{{" .. tag .. "}}")
262+        pos = tEnd + 2
263+      end
264+    end
265+    return table.concat(out, "")
266+  end
267+
268+  local tRender
269+  tRender = function(txt, vars)
270+    txt = txt:gsub('{{%s*include%s+"([^"]+)"%s*}}', function(path)
271+      local full
272+      if path:sub(1, 1) == "/" then full = path else full = cfg.INPUT .. "/" .. path end
273+      local c = rFile(full)
274+      if c then return tRender(c, vars) end
275+      return ""
276+    end)
277+
278+    txt = pCond(txt, vars)
279+
280+    txt = txt:gsub("{{%s*([%w_]+)%s*}}", function(name)
281+      if vars[name] ~= nil then return tostring(vars[name]) end
282+      return ""
283+    end)
284+
285+    return txt
286+  end
287+
288+  local bNav
289+  bNav = function(cur)
290+    local fLabel = function(r, t)
291+      local l
292+      if "/" .. r == cur then
293+        if cfg.LINKCURR:find("{CURR}", 1, true) then l = cfg.LINKCURR:gsub("{CURR}", function() return t end) else l = cfg.LINKCURR .. t end
294+        return '<a href="/' .. r .. '" class="aPage"><span class="aIndicator">' .. l .. '</span></a>'
295+      end
296+      if cfg.LINK:find("{CURR}", 1, true) then l = cfg.LINK:gsub("{CURR}", function() return t end) else l = cfg.LINK .. t end
297+      return '<a href="/' .. r .. '">' .. l .. '</a>'
298+    end
299+
300+    local pDir
301+    pDir = function(dir)
302+      local out, nms = {}, {}
303+      for name in lfs.dir(dir) do if name ~= "." and name ~= ".." and not ign(name) then table.insert(nms, name) end end
304+      table.sort(nms)
305+
306+      for _, name in ipairs(nms) do
307+        local itm = dir .. "/" .. name
308+        local mode = attrGet(itm, "mode")
309+        if mode == "file" and name:match("%.md$") then
310+          if name ~= "index.md" then
311+            local rel = itm:sub(#cfg.INPUT + 2):gsub("%.md$", ".html")
312+            local ttl = name:gsub("%.md$", ""):gsub("-", " ")
313+            table.insert(out, '<li>' .. fLabel(rel, ttl) .. '</li>')
314+          end
315+        elseif mode == "directory" then
316+          local sub = pDir(itm)
317+          if #sub > 0 then
318+            table.insert(out, '<li>' .. name .. '/<ul>\n' .. table.concat(sub, "\n") .. '\n</ul></li>')
319+          end
320+        end
321+      end
322+
323+      return out
324+    end
325+
326+    return table.concat(pDir(cfg.INPUT), "\n")
327+  end
328+
329+  local pMd
330+  pMd = function(dir)
331+    for name in lfs.dir(dir) do
332+      if name ~= "." and name ~= ".." then
333+        local f = dir .. "/" .. name
334+        local mode = lfs.attributes(f, "mode")
335+        if mode == "directory" then
336+          pMd(f)
337+        elseif mode == "file" and name:match("%.md$") then
338+          local rel = f:sub(#cfg.INPUT + 2):gsub("%.md$", ".html")
339+          local dst = cfg.OUTPUT .. "/" .. rel
340+          exp[dst] = true
341+
342+          local srcM = lfs.attributes(f, "modification") or 0
343+          local maxM = srcM
344+          if cfgM > maxM then maxM = cfgM end
345+          if mdM > maxM then maxM = mdM end
346+          if tplM > maxM then maxM = tplM end
347+          if incM > maxM then maxM = incM end
348+          if navM > maxM then maxM = navM end
349+          local dstM = lfs.attributes(dst, "modification") or 0
350+
351+          if stale or not (dstM > 0 and dstM >= maxM) then
352+            local raw = rFile(f) or ""
353+            local html = mk(raw)
354+
355+            local cur = "/" .. rel
356+            local base = name:gsub("%.md$", "")
357+            local pVars = { CURR = base }
358+            local pTitle = sub(cfg.TITLE, pVars)
359+            local pFooter = sub(cfg.FOOTER, pVars)
360+            
361+            local pLinks = function(txt)
362+              return txt:gsub("<a(.-)>(.-)</a>", function(attrs, inner)
363+                if inner:find("<img", 1, true) or inner == "" then return "<a" .. attrs .. ">" .. inner .. "</a>" end
364+                local href = attrs:match("href=['\"](.-)['\"]") or ""
365+                local isCur = (href == cur) or ("/" .. href == cur)
366+                local l
367+                if isCur then
368+                  if cfg.LINKCURR:find("{CURR}", 1, true) then l = cfg.LINKCURR:gsub("{CURR}", function() return inner end) else l = cfg.LINKCURR .. inner end
369+                  local nAttrs = attrs:gsub('class=["\'][^"\']*["\']', "") .. ' class="aPage"'
370+                  return '<a' .. nAttrs .. '><span class="aIndicator">' .. l .. '</span></a>'
371+                end
372+                if cfg.LINK:find("{CURR}", 1, true) then l = cfg.LINK:gsub("{CURR}", function() return inner end) else l = cfg.LINK .. inner end
373+                return '<a' .. attrs .. '>' .. l .. '</a>'
374+              end)
375+            end
376+
377+            html = pLinks(html)
378+            pFooter = pLinks(pFooter)
379+
380+            local nav = "<ul>\n" .. bNav(cur) .. "\n</ul>"
381+            local vars = { CURR = base }
382+            for k, v in pairs(cfg) do
383+              if type(v) == "string" then vars[k] = sub(v, pVars)
384+              elseif type(v) == "number" then vars[k] = tostring(v) end
385+            end
386+            vars.TITLE = pTitle
387+            vars.NAV = nav
388+            vars.CONTENT = html
389+            vars.FOOTER = pFooter
390+            local out = tRender(tpl, vars)
391+            if wFile(dst, out) then
392+              chg = true
393+              lg("wrote " .. dst)
394+            end
395+          end
396+        end
397+      end
398+    end
399+  end
400+
401+  pMd(cfg.INPUT)
402+
403+  local rem = {}
404+  local rDel
405+  rDel = function(dir)
406+    local nms = {}
407+    for name in lfs.dir(dir) do if name ~= "." and name ~= ".." then table.insert(nms, name) end end
408+    for _, name in ipairs(nms) do
409+      local p = dir .. "/" .. name
410+      local lMode = lfs.symlinkattributes(p, "mode")
411+      if lMode == "link" then
412+        if not exp[p] then if os.remove(p) then table.insert(rem, p) end end
413+      elseif lMode == "directory" then
414+        rDel(p)
415+        local cnt = 0
416+        for _ in lfs.dir(p) do cnt = cnt + 1 end
417+        if cnt == 2 then if lfs.rmdir(p) then table.insert(rem, p .. "/") end end
418+      elseif lMode == "file" then
419+        if not exp[p] then if os.remove(p) then table.insert(rem, p) end end
420+      end
421+    end
422+  end
423+  rDel(cfg.OUTPUT)
424+
425+  if #rem > 0 then chg = true end
426+  for _, p in ipairs(rem) do lg("removed " .. p) end
427+
428+  if chg then
429+    for _, m in ipairs(buf) do print(m) end
430+    print("build le done")
431+    if cfg.AFTER then for _, cmd in ipairs(cfg.AFTER) do os.execute(cmd) end end
432+  else
433+    print("no changes made; skipping el buildo")
434+  end
435+end
436+
437+mn()
+12, -0
 1@@ -0,0 +1,12 @@
 2+return {
 3+  TITLE = "{CURR} :)",
 4+  FOOTER = "built with <a href='https://srcdump.net/myu/mig'>mig</a> | last updated: " .. os.date("!%Y-%m-%d %H:%M UTC") .. " | {VERYCOOLCUSTOMVARIABLE}",
 5+  INPUT = "template",
 6+  OUTPUT = "public",
 7+  NAVIGNORE = { "assets" },
 8+  LINK = "[{CURR}]",
 9+  LINKCURR = "[ {CURR} ]",
10+  AFTER = { 'echo "bazinga"' },
11+
12+  VERYCOOLCUSTOMVARIABLE = "hello from noble verycoolcustomvariable of the config.lua house"
13+}
+0, -0
+1220, -0
   1@@ -0,0 +1,1220 @@
   2+#!/usr/bin/env lua
   3+
   4+--[[
   5+
   6+i got this script from https://github.com/mpeterv/markdown
   7+all other functionality aside from this script and luafilesystem (lfs.so) is all my stuff.
   8+- with love myu be you
   9+
  10+]]
  11+
  12+----------------------------------------------------------------------
  13+-- Utility functions
  14+----------------------------------------------------------------------
  15+
  16+local unpack = table.unpack or unpack
  17+
  18+-- Returns the result of mapping the values in table t through the function f
  19+local function map(t, f)
  20+   local out = {}
  21+   for k,v in pairs(t) do out[k] = f(v,k) end
  22+   return out
  23+end
  24+
  25+-- Functional style if statement. (NOTE: no short circuit evaluation)
  26+local function iff(t, a, b) if t then return a else return b end end
  27+
  28+-- Splits the text into an array of separate lines.
  29+local function split(text, sep)
  30+   sep = sep or "\n"
  31+   local lines = {}
  32+   local pos = 1
  33+   while true do
  34+      local b,e = text:find(sep, pos)
  35+      if not b then table.insert(lines, text:sub(pos)) break end
  36+      table.insert(lines, text:sub(pos, b-1))
  37+      pos = e + 1
  38+   end
  39+   return lines
  40+end
  41+
  42+-- Converts tabs to spaces
  43+local function detab(text)
  44+   local tab_width = 4
  45+   local function rep(match)
  46+      local spaces = -match:len()
  47+      while spaces<1 do spaces = spaces + tab_width end
  48+      return match .. string.rep(" ", spaces)
  49+   end
  50+   text = text:gsub("([^\n]-)\t", rep)
  51+   return text
  52+end
  53+
  54+-- Applies string.find for every pattern in the list and returns the first match
  55+local function find_first(s, patterns, index)
  56+   local res = {}
  57+   for _,p in ipairs(patterns) do
  58+      local match = {s:find(p, index)}
  59+      if #match>0 and (#res==0 or match[1] < res[1]) then res = match end
  60+   end
  61+   return unpack(res)
  62+end
  63+
  64+-- If a replacement array is specified, the range [start, stop] in the array is replaced
  65+-- with the replacement array and the resulting array is returned. Without a replacement
  66+-- array the section of the array between start and stop is returned.
  67+local function splice(array, start, stop, replacement)
  68+   if replacement then
  69+      local n = stop - start + 1
  70+      while n > 0 do
  71+         table.remove(array, start)
  72+         n = n - 1
  73+      end
  74+      for _,v in ipairs(replacement) do
  75+         table.insert(array, start, v)
  76+      end
  77+      return array
  78+   else
  79+      local res = {}
  80+      for i = start,stop do
  81+         table.insert(res, array[i])
  82+      end
  83+      return res
  84+   end
  85+end
  86+
  87+-- Outdents the text one step.
  88+local function outdent(text)
  89+   text = "\n" .. text
  90+   text = text:gsub("\n  ? ? ?", "\n")
  91+   text = text:sub(2)
  92+   return text
  93+end
  94+
  95+-- Indents the text one step.
  96+local function indent(text)
  97+   text = text:gsub("\n", "\n    ")
  98+   return text
  99+end
 100+
 101+-- Does a simple tokenization of html data. Returns the data as a list of tokens.
 102+-- Each token is a table with a type field (which is either "tag" or "text") and
 103+-- a text field (which contains the original token data).
 104+local function tokenize_html(html)
 105+   local tokens = {}
 106+   local pos = 1
 107+   while true do
 108+      local start = find_first(html, {"<!%-%-", "<[a-z/!$]", "<%?"}, pos)
 109+      if not start then
 110+         table.insert(tokens, {type="text", text=html:sub(pos)})
 111+         break
 112+      end
 113+      if start ~= pos then table.insert(tokens, {type="text", text = html:sub(pos, start-1)}) end
 114+
 115+      local _, stop
 116+      if html:match("^<!%-%-", start) then
 117+         _,stop = html:find("%-%->", start)
 118+      elseif html:match("^<%?", start) then
 119+         _,stop = html:find("?>", start)
 120+      else
 121+         _,stop = html:find("%b<>", start)
 122+      end
 123+      if not stop then
 124+         -- error("Could not match html tag " .. html:sub(start,start+30))
 125+         table.insert(tokens, {type="text", text=html:sub(start, start)})
 126+         pos = start + 1
 127+      else
 128+         table.insert(tokens, {type="tag", text=html:sub(start, stop)})
 129+         pos = stop + 1
 130+      end
 131+   end
 132+   return tokens
 133+end
 134+
 135+----------------------------------------------------------------------
 136+-- Hash
 137+----------------------------------------------------------------------
 138+
 139+-- This is used to "hash" data into alphanumeric strings that are unique
 140+-- in the document. (Note that this is not cryptographic hash, the hash
 141+-- function is not one-way.) The hash procedure is used to protect parts
 142+-- of the document from further processing.
 143+
 144+local HASH = {
 145+   -- Has the hash been inited.
 146+   inited = false,
 147+
 148+   -- The unique string prepended to all hash values. This is to ensure
 149+   -- that hash values do not accidently coincide with an actual existing
 150+   -- string in the document.
 151+   identifier = "",
 152+
 153+   -- Counter that counts up for each new hash instance.
 154+   counter = 0,
 155+
 156+   -- Hash table.
 157+   table = {}
 158+}
 159+
 160+-- Inits hashing. Creates a hash_identifier that doesn't occur anywhere
 161+-- in the text.
 162+local function init_hash(text)
 163+   HASH.inited = true
 164+   HASH.identifier = ""
 165+   HASH.counter = 0
 166+   HASH.table = {}
 167+
 168+   local s = "HASH"
 169+   local counter = 0
 170+   local id
 171+   while true do
 172+      id  = s .. counter
 173+      if not text:find(id, 1, true) then break end
 174+      counter = counter + 1
 175+   end
 176+   HASH.identifier = id
 177+end
 178+
 179+-- Returns the hashed value for s.
 180+local function hash(s)
 181+   assert(HASH.inited)
 182+   if not HASH.table[s] then
 183+      HASH.counter = HASH.counter + 1
 184+      local id = HASH.identifier .. HASH.counter .. "X"
 185+      HASH.table[s] = id
 186+   end
 187+   return HASH.table[s]
 188+end
 189+
 190+----------------------------------------------------------------------
 191+-- Protection
 192+----------------------------------------------------------------------
 193+
 194+-- The protection module is used to "protect" parts of a document
 195+-- so that they are not modified by subsequent processing steps.
 196+-- Protected parts are saved in a table for later unprotection
 197+
 198+-- Protection data
 199+local PD = {
 200+   -- Saved blocks that have been converted
 201+   blocks = {},
 202+
 203+   -- Block level tags that will be protected
 204+   tags = {"p", "div", "h1", "h2", "h3", "h4", "h5", "h6", "blockquote",
 205+   "pre", "table", "dl", "ol", "ul", "script", "noscript", "form", "fieldset",
 206+   "iframe", "math", "ins", "del"}
 207+}
 208+
 209+-- Pattern for matching a block tag that begins and ends in the leftmost
 210+-- column and may contain indented subtags, i.e.
 211+-- <div>
 212+--    A nested block.
 213+--    <div>
 214+--        Nested data.
 215+--     </div>
 216+-- </div>
 217+local function block_pattern(tag)
 218+   return "\n<" .. tag .. ".-\n</" .. tag .. ">[ \t]*\n"
 219+end
 220+
 221+-- Pattern for matching a block tag that begins and ends with a newline
 222+local function line_pattern(tag)
 223+   return "\n<" .. tag .. ".-</" .. tag .. ">[ \t]*\n"
 224+end
 225+
 226+-- Protects the range of characters from start to stop in the text and
 227+-- returns the protected string.
 228+local function protect_range(text, start, stop)
 229+   local s = text:sub(start, stop)
 230+   local h = hash(s)
 231+   PD.blocks[h] = s
 232+   text = text:sub(1,start) .. h .. text:sub(stop)
 233+   return text
 234+end
 235+
 236+-- Protect every part of the text that matches any of the patterns. The first
 237+-- matching pattern is protected first, etc.
 238+local function protect_matches(text, patterns)
 239+   while true do
 240+      local start, stop = find_first(text, patterns)
 241+      if not start then break end
 242+      text = protect_range(text, start, stop)
 243+   end
 244+   return text
 245+end
 246+
 247+-- Protects blocklevel tags in the specified text
 248+local function protect(text)
 249+   -- First protect potentially nested block tags
 250+   text = protect_matches(text, map(PD.tags, block_pattern))
 251+   -- Then protect block tags at the line level.
 252+   text = protect_matches(text, map(PD.tags, line_pattern))
 253+   -- Protect <hr> and comment tags
 254+   text = protect_matches(text, {"\n<hr[^>]->[ \t]*\n"})
 255+   text = protect_matches(text, {"\n<!%-%-.-%-%->[ \t]*\n"})
 256+   return text
 257+end
 258+
 259+-- Returns true if the string s is a hash resulting from protection
 260+local function is_protected(s)
 261+   return PD.blocks[s]
 262+end
 263+
 264+-- Unprotects the specified text by expanding all the nonces
 265+local function unprotect(text)
 266+   for k,v in pairs(PD.blocks) do
 267+      v = v:gsub("%%", "%%%%")
 268+      text = text:gsub(k, v)
 269+   end
 270+   return text
 271+end
 272+
 273+
 274+----------------------------------------------------------------------
 275+-- Block transform
 276+----------------------------------------------------------------------
 277+
 278+-- The block transform functions transform the text on the block level.
 279+-- They work with the text as an array of lines rather than as individual
 280+-- characters.
 281+
 282+-- Returns true if the line is a ruler of (char) characters.
 283+-- The line must contain at least three char characters and contain only spaces and
 284+-- char characters.
 285+local function is_ruler_of(line, char)
 286+   if not line:match("^[ %" .. char .. "]*$") then return false end
 287+   if not line:match("%" .. char .. ".*%" .. char .. ".*%" .. char) then return false end
 288+   return true
 289+end
 290+
 291+-- Identifies the block level formatting present in the line
 292+local function classify(line)
 293+   local info = {line = line, text = line}
 294+
 295+   if line:match("^    ") then
 296+      info.type = "indented"
 297+      info.outdented = line:sub(5)
 298+      return info
 299+   end
 300+
 301+   for _,c in ipairs({'*', '-', '_', '='}) do
 302+      if is_ruler_of(line, c) then
 303+         info.type = "ruler"
 304+         info.ruler_char = c
 305+         return info
 306+      end
 307+   end
 308+
 309+   if line == "" then
 310+      info.type = "blank"
 311+      return info
 312+   end
 313+
 314+   if line:match("^(#+)[ \t]*(.-)[ \t]*#*[ \t]*$") then
 315+      local m1, m2 = line:match("^(#+)[ \t]*(.-)[ \t]*#*[ \t]*$")
 316+      info.type = "header"
 317+      info.level = m1:len()
 318+      info.text = m2
 319+      return info
 320+   end
 321+
 322+   if line:match("^ ? ? ?(%d+)%.[ \t]+(.+)") then
 323+      local number, text = line:match("^ ? ? ?(%d+)%.[ \t]+(.+)")
 324+      info.type = "list_item"
 325+      info.list_type = "numeric"
 326+      info.number = 0 + number
 327+      info.text = text
 328+      return info
 329+   end
 330+
 331+   if line:match("^ ? ? ?([%*%+%-])[ \t]+(.+)") then
 332+      local bullet, text = line:match("^ ? ? ?([%*%+%-])[ \t]+(.+)")
 333+      info.type = "list_item"
 334+      info.list_type = "bullet"
 335+      info.bullet = bullet
 336+      info.text= text
 337+      return info
 338+   end
 339+
 340+   if line:match("^>[ \t]?(.*)") then
 341+      info.type = "blockquote"
 342+      info.text = line:match("^>[ \t]?(.*)")
 343+      return info
 344+   end
 345+
 346+   if is_protected(line) then
 347+      info.type = "raw"
 348+      info.html = unprotect(line)
 349+      return info
 350+   end
 351+
 352+   info.type = "normal"
 353+   return info
 354+end
 355+
 356+-- Find headers constisting of a normal line followed by a ruler and converts them to
 357+-- header entries.
 358+local function headers(array)
 359+   local i = 1
 360+   while i <= #array - 1 do
 361+      if array[i].type  == "normal" and array[i+1].type == "ruler" and
 362+         (array[i+1].ruler_char == "-" or array[i+1].ruler_char == "=") then
 363+         local info = {line = array[i].line}
 364+         info.text = info.line
 365+         info.type = "header"
 366+         info.level = iff(array[i+1].ruler_char == "=", 1, 2)
 367+         table.remove(array, i+1)
 368+         array[i] = info
 369+      end
 370+      i = i + 1
 371+   end
 372+   return array
 373+end
 374+
 375+-- Forward declarations
 376+local block_transform, span_transform, encode_code
 377+
 378+-- Convert lines to html code
 379+local function blocks_to_html(lines, no_paragraphs)
 380+   local out = {}
 381+   local i = 1
 382+   while i <= #lines do
 383+      local line = lines[i]
 384+      if line.type == "ruler" then
 385+         table.insert(out, "<hr/>")
 386+      elseif line.type == "raw" then
 387+         table.insert(out, line.html)
 388+      elseif line.type == "normal" then
 389+         local s = line.line
 390+
 391+         while i+1 <= #lines and lines[i+1].type == "normal" do
 392+            i = i + 1
 393+            s = s .. "\n" .. lines[i].line
 394+         end
 395+
 396+         if no_paragraphs then
 397+            table.insert(out, span_transform(s))
 398+         else
 399+            table.insert(out, "<p>" .. span_transform(s) .. "</p>")
 400+         end
 401+      elseif line.type == "header" then
 402+         local s = "<h" .. line.level .. ">" .. span_transform(line.text) .. "</h" .. line.level .. ">"
 403+         table.insert(out, s)
 404+      else
 405+         table.insert(out, line.line)
 406+      end
 407+      i = i + 1
 408+   end
 409+   return out
 410+end
 411+
 412+-- Find list blocks and convert them to protected data blocks
 413+local function lists(array, sublist)
 414+   local function process_list(arr)
 415+      local function any_blanks(arr)
 416+         for i = 1, #arr do
 417+            if arr[i].type == "blank" then return true end
 418+         end
 419+         return false
 420+      end
 421+
 422+      local function split_list_items(arr)
 423+         local acc = {arr[1]}
 424+         local res = {}
 425+         for i=2,#arr do
 426+            if arr[i].type == "list_item" then
 427+               table.insert(res, acc)
 428+               acc = {arr[i]}
 429+            else
 430+               table.insert(acc, arr[i])
 431+            end
 432+         end
 433+         table.insert(res, acc)
 434+         return res
 435+      end
 436+
 437+      local function process_list_item(lines, block)
 438+         while lines[#lines].type == "blank" do
 439+            table.remove(lines)
 440+         end
 441+
 442+         local itemtext = lines[1].text
 443+         for i=2,#lines do
 444+            itemtext = itemtext .. "\n" .. outdent(lines[i].line)
 445+         end
 446+         if block then
 447+            itemtext = block_transform(itemtext, true)
 448+            if not itemtext:find("<pre>") then itemtext = indent(itemtext) end
 449+            return "    <li>" .. itemtext .. "</li>"
 450+         else
 451+            local lines = split(itemtext)
 452+            lines = map(lines, classify)
 453+            lines = lists(lines, true)
 454+            lines = blocks_to_html(lines, true)
 455+            itemtext = table.concat(lines, "\n")
 456+            if not itemtext:find("<pre>") then itemtext = indent(itemtext) end
 457+            return "    <li>" .. itemtext .. "</li>"
 458+         end
 459+      end
 460+
 461+      local block_list = any_blanks(arr)
 462+      local items = split_list_items(arr)
 463+      local out = ""
 464+      for _, item in ipairs(items) do
 465+         out = out .. process_list_item(item, block_list) .. "\n"
 466+      end
 467+      if arr[1].list_type == "numeric" then
 468+         return "<ol>\n" .. out .. "</ol>"
 469+      else
 470+         return "<ul>\n" .. out .. "</ul>"
 471+      end
 472+   end
 473+
 474+   -- Finds the range of lines composing the first list in the array. A list
 475+   -- starts with (^ list_item) or (blank list_item) and ends with
 476+   -- (blank* $) or (blank normal).
 477+   --
 478+   -- A sublist can start with just (list_item) does not need a blank...
 479+   local function find_list(array, sublist)
 480+      local function find_list_start(array, sublist)
 481+         if array[1].type == "list_item" then return 1 end
 482+         if sublist then
 483+            for i = 1,#array do
 484+               if array[i].type == "list_item" then return i end
 485+            end
 486+         else
 487+            for i = 1, #array-1 do
 488+               if array[i].type == "blank" and array[i+1].type == "list_item" then
 489+                  return i+1
 490+               end
 491+            end
 492+         end
 493+         return nil
 494+      end
 495+      local function find_list_end(array, start)
 496+         local pos = #array
 497+         for i = start, #array-1 do
 498+            if array[i].type == "blank" and array[i+1].type ~= "list_item"
 499+               and array[i+1].type ~= "indented" and array[i+1].type ~= "blank" then
 500+               pos = i-1
 501+               break
 502+            end
 503+         end
 504+         while pos > start and array[pos].type == "blank" do
 505+            pos = pos - 1
 506+         end
 507+         return pos
 508+      end
 509+
 510+      local start = find_list_start(array, sublist)
 511+      if not start then return nil end
 512+      return start, find_list_end(array, start)
 513+   end
 514+
 515+   while true do
 516+      local start, stop = find_list(array, sublist)
 517+      if not start then break end
 518+      local text = process_list(splice(array, start, stop))
 519+      local info = {
 520+         line = text,
 521+         type = "raw",
 522+         html = text
 523+      }
 524+      array = splice(array, start, stop, {info})
 525+   end
 526+
 527+   -- Convert any remaining list items to normal
 528+   for _,line in ipairs(array) do
 529+      if line.type == "list_item" then line.type = "normal" end
 530+   end
 531+
 532+   return array
 533+end
 534+
 535+-- Find and convert blockquote markers.
 536+local function blockquotes(lines)
 537+   local function find_blockquote(lines)
 538+      local start
 539+      for i,line in ipairs(lines) do
 540+         if line.type == "blockquote" then
 541+            start = i
 542+            break
 543+         end
 544+      end
 545+      if not start then return nil end
 546+
 547+      local stop = #lines
 548+      for i = start+1, #lines do
 549+         if lines[i].type == "blank" or lines[i].type == "blockquote" then
 550+         elseif lines[i].type == "normal" then
 551+            if lines[i-1].type == "blank" then stop = i-1 break end
 552+         else
 553+            stop = i-1 break
 554+         end
 555+      end
 556+      while lines[stop].type == "blank" do stop = stop - 1 end
 557+      return start, stop
 558+   end
 559+
 560+   local function process_blockquote(lines)
 561+      local raw = lines[1].text
 562+      for i = 2,#lines do
 563+         raw = raw .. "\n" .. lines[i].text
 564+      end
 565+      local bt = block_transform(raw)
 566+      if not bt:find("<pre>") then bt = indent(bt) end
 567+      return "<blockquote>\n    " .. bt ..
 568+         "\n</blockquote>"
 569+   end
 570+
 571+   while true do
 572+      local start, stop = find_blockquote(lines)
 573+      if not start then break end
 574+      local text = process_blockquote(splice(lines, start, stop))
 575+      local info = {
 576+         line = text,
 577+         type = "raw",
 578+         html = text
 579+      }
 580+      lines = splice(lines, start, stop, {info})
 581+   end
 582+   return lines
 583+end
 584+
 585+-- Find and convert codeblocks.
 586+local function codeblocks(lines)
 587+   local function find_codeblock(lines)
 588+      local start
 589+      for i,line in ipairs(lines) do
 590+         if line.type == "indented" then start = i break end
 591+      end
 592+      if not start then return nil end
 593+
 594+      local stop = #lines
 595+      for i = start+1, #lines do
 596+         if lines[i].type ~= "indented" and lines[i].type ~= "blank" then
 597+            stop = i-1
 598+            break
 599+         end
 600+      end
 601+      while lines[stop].type == "blank" do stop = stop - 1 end
 602+      return start, stop
 603+   end
 604+
 605+   local function process_codeblock(lines)
 606+      local raw = detab(encode_code(outdent(lines[1].line)))
 607+      for i = 2,#lines do
 608+         raw = raw .. "\n" .. detab(encode_code(outdent(lines[i].line)))
 609+      end
 610+      return "<pre><code>" .. raw .. "\n</code></pre>"
 611+   end
 612+
 613+   while true do
 614+      local start, stop = find_codeblock(lines)
 615+      if not start then break end
 616+      local text = process_codeblock(splice(lines, start, stop))
 617+      local info = {
 618+         line = text,
 619+         type = "raw",
 620+         html = text
 621+      }
 622+      lines = splice(lines, start, stop, {info})
 623+   end
 624+   return lines
 625+end
 626+
 627+-- Perform all the block level transforms
 628+function block_transform(text, sublist)
 629+   local lines = split(text)
 630+   lines = map(lines, classify)
 631+   lines = headers(lines)
 632+   lines = lists(lines, sublist)
 633+   lines = codeblocks(lines)
 634+   lines = blockquotes(lines)
 635+   lines = blocks_to_html(lines)
 636+   local text = table.concat(lines, "\n")
 637+   return text
 638+end
 639+
 640+----------------------------------------------------------------------
 641+-- Span transform
 642+----------------------------------------------------------------------
 643+
 644+-- Functions for transforming the text at the span level.
 645+
 646+-- These characters may need to be escaped because they have a special
 647+-- meaning in markdown.
 648+local escape_chars = "'\\`*_{}[]()>#+-.!'"
 649+local escape_table = {}
 650+
 651+local function init_escape_table()
 652+   escape_table = {}
 653+   for i = 1,#escape_chars do
 654+      local c = escape_chars:sub(i,i)
 655+      escape_table[c] = hash(c)
 656+   end
 657+end
 658+
 659+-- Adds a new escape to the escape table.
 660+local function add_escape(text)
 661+   if not escape_table[text] then
 662+      escape_table[text] = hash(text)
 663+   end
 664+   return escape_table[text]
 665+end
 666+
 667+-- Encode backspace-escaped characters in the markdown source.
 668+local function encode_backslash_escapes(t)
 669+   for i=1,escape_chars:len() do
 670+      local c = escape_chars:sub(i,i)
 671+      t = t:gsub("\\%" .. c, escape_table[c])
 672+   end
 673+   return t
 674+end
 675+
 676+-- Escape characters that should not be disturbed by markdown.
 677+local function escape_special_chars(text)
 678+   local tokens = tokenize_html(text)
 679+
 680+   local out = ""
 681+   for _, token in ipairs(tokens) do
 682+      local t = token.text
 683+      if token.type == "tag" then
 684+         -- In tags, encode * and _ so they don't conflict with their use in markdown.
 685+         t = t:gsub("%*", escape_table["*"])
 686+         t = t:gsub("%_", escape_table["_"])
 687+      else
 688+         t = encode_backslash_escapes(t)
 689+      end
 690+      out = out .. t
 691+   end
 692+   return out
 693+end
 694+
 695+-- Unescape characters that have been encoded.
 696+local function unescape_special_chars(t)
 697+   local tin = t
 698+   for k,v in pairs(escape_table) do
 699+      k = k:gsub("%%", "%%%%")
 700+      t = t:gsub(v,k)
 701+   end
 702+   if t ~= tin then t = unescape_special_chars(t) end
 703+   return t
 704+end
 705+
 706+-- Encode/escape certain characters inside Markdown code runs.
 707+-- The point is that in code, these characters are literals,
 708+-- and lose their special Markdown meanings.
 709+function encode_code(s)
 710+   s = s:gsub("%&", "&amp;")
 711+   s = s:gsub("<", "&lt;")
 712+   s = s:gsub(">", "&gt;")
 713+   for k,v in pairs(escape_table) do
 714+      s = s:gsub("%"..k, v)
 715+   end
 716+   return s
 717+end
 718+
 719+-- Handle backtick blocks.
 720+local function code_spans(s)
 721+   s = s:gsub("\\\\", escape_table["\\"])
 722+   s = s:gsub("\\`", escape_table["`"])
 723+
 724+   local pos = 1
 725+   while true do
 726+      local start, stop = s:find("`+", pos)
 727+      if not start then return s end
 728+      local count = stop - start + 1
 729+      -- Find a matching numbert of backticks
 730+      local estart, estop = s:find(string.rep("`", count), stop+1)
 731+      local brstart = s:find("\n", stop+1)
 732+      if estart and (not brstart or estart < brstart) then
 733+         local code = s:sub(stop+1, estart-1)
 734+         code = code:gsub("^[ \t]+", "")
 735+         code = code:gsub("[ \t]+$", "")
 736+         code = code:gsub(escape_table["\\"], escape_table["\\"] .. escape_table["\\"])
 737+         code = code:gsub(escape_table["`"], escape_table["\\"] .. escape_table["`"])
 738+         code = "<code>" .. encode_code(code) .. "</code>"
 739+         code = add_escape(code)
 740+         s = s:sub(1, start-1) .. code .. s:sub(estop+1)
 741+         pos = start + code:len()
 742+      else
 743+         pos = stop + 1
 744+      end
 745+   end
 746+   return s
 747+end
 748+
 749+-- Encode alt text... enodes &, and ".
 750+local function encode_alt(s)
 751+   if not s then return s end
 752+   s = s:gsub('&', '&amp;')
 753+   s = s:gsub('"', '&quot;')
 754+   s = s:gsub('<', '&lt;')
 755+   return s
 756+end
 757+
 758+-- Forward declaration for link_db as returned by strip_link_definitions.
 759+local link_database
 760+
 761+-- Handle image references
 762+local function images(text)
 763+   local function reference_link(alt, id)
 764+      alt = encode_alt(alt:match("%b[]"):sub(2,-2))
 765+      id = id:match("%[(.*)%]"):lower()
 766+      if id == "" then id = text:lower() end
 767+      link_database[id] = link_database[id] or {}
 768+      if not link_database[id].url then return nil end
 769+      local url = link_database[id].url or id
 770+      url = encode_alt(url)
 771+      local title = encode_alt(link_database[id].title)
 772+      if title then title = " title=\"" .. title .. "\"" else title = "" end
 773+      return add_escape ('<img src="' .. url .. '" alt="' .. alt .. '"' .. title .. "/>")
 774+   end
 775+
 776+   local function inline_link(alt, link)
 777+      alt = encode_alt(alt:match("%b[]"):sub(2,-2))
 778+      local url, title = link:match("%(<?(.-)>?[ \t]*['\"](.+)['\"]")
 779+      url = url or link:match("%(<?(.-)>?%)")
 780+      url = encode_alt(url)
 781+      title = encode_alt(title)
 782+      if title then
 783+         return add_escape('<img src="' .. url .. '" alt="' .. alt .. '" title="' .. title .. '"/>')
 784+      else
 785+         return add_escape('<img src="' .. url .. '" alt="' .. alt .. '"/>')
 786+      end
 787+   end
 788+
 789+   text = text:gsub("!(%b[])[ \t]*\n?[ \t]*(%b[])", reference_link)
 790+   text = text:gsub("!(%b[])(%b())", inline_link)
 791+   return text
 792+end
 793+
 794+-- Handle anchor references
 795+local function anchors(text)
 796+   local function reference_link(text, id)
 797+      text = text:match("%b[]"):sub(2,-2)
 798+      id = id:match("%b[]"):sub(2,-2):lower()
 799+      if id == "" then id = text:lower() end
 800+      link_database[id] = link_database[id] or {}
 801+      if not link_database[id].url then return nil end
 802+      local url = link_database[id].url or id
 803+      url = encode_alt(url)
 804+      local title = encode_alt(link_database[id].title)
 805+      if title then title = " title=\"" .. title .. "\"" else title = "" end
 806+      return add_escape("<a href=\"" .. url .. "\"" .. title .. ">") .. text .. add_escape("</a>")
 807+   end
 808+
 809+   local function inline_link(text, link)
 810+      text = text:match("%b[]"):sub(2,-2)
 811+      local url, title = link:match("%(<?(.-)>?[ \t]*['\"](.+)['\"]")
 812+      title = encode_alt(title)
 813+      url  = url or  link:match("%(<?(.-)>?%)") or ""
 814+      url = encode_alt(url)
 815+      if title then
 816+         return add_escape("<a href=\"" .. url .. "\" title=\"" .. title .. "\">") .. text .. "</a>"
 817+      else
 818+         return add_escape("<a href=\"" .. url .. "\">") .. text .. add_escape("</a>")
 819+      end
 820+   end
 821+
 822+   text = text:gsub("(%b[])[ \t]*\n?[ \t]*(%b[])", reference_link)
 823+   text = text:gsub("(%b[])(%b())", inline_link)
 824+   return text
 825+end
 826+
 827+-- Handle auto links, i.e. <http://www.google.com/>.
 828+local function auto_links(text)
 829+   local function link(s)
 830+      return add_escape("<a href=\"" .. s .. "\">") .. s .. "</a>"
 831+   end
 832+   -- Encode chars as a mix of dec and hex entitites to (perhaps) fool
 833+   -- spambots.
 834+   local function encode_email_address(s)
 835+      -- Use a deterministic encoding to make unit testing possible.
 836+      -- Code 45% hex, 45% dec, 10% plain.
 837+      local hex = {code = function(c) return "&#x" .. string.format("%x", c:byte()) .. ";" end, count = 1, rate = 0.45}
 838+      local dec = {code = function(c) return "&#" .. c:byte() .. ";" end, count = 0, rate = 0.45}
 839+      local plain = {code = function(c) return c end, count = 0, rate = 0.1}
 840+      local codes = {hex, dec, plain}
 841+      local function swap(t,k1,k2) local temp = t[k2] t[k2] = t[k1] t[k1] = temp end
 842+
 843+      local out = ""
 844+      for i = 1,s:len() do
 845+         for _,code in ipairs(codes) do code.count = code.count + code.rate end
 846+         if codes[1].count < codes[2].count then swap(codes,1,2) end
 847+         if codes[2].count < codes[3].count then swap(codes,2,3) end
 848+         if codes[1].count < codes[2].count then swap(codes,1,2) end
 849+
 850+         local code = codes[1]
 851+         local c = s:sub(i,i)
 852+         -- Force encoding of "@" to make email address more invisible.
 853+         if c == "@" and code == plain then code = codes[2] end
 854+         out = out .. code.code(c)
 855+         code.count = code.count - 1
 856+      end
 857+      return out
 858+   end
 859+   local function mail(s)
 860+      s = unescape_special_chars(s)
 861+      local address = encode_email_address("mailto:" .. s)
 862+      local text = encode_email_address(s)
 863+      return add_escape("<a href=\"" .. address .. "\">") .. text .. "</a>"
 864+   end
 865+   -- links
 866+   text = text:gsub("<(https?:[^'\">%s]+)>", link)
 867+   text = text:gsub("<(ftp:[^'\">%s]+)>", link)
 868+
 869+   -- mail
 870+   text = text:gsub("<mailto:([^'\">%s]+)>", mail)
 871+   text = text:gsub("<([-.%w]+%@[-.%w]+)>", mail)
 872+   return text
 873+end
 874+
 875+-- Encode free standing amps (&) and angles (<)... note that this does not
 876+-- encode free >.
 877+local function amps_and_angles(s)
 878+   -- encode amps not part of &..; expression
 879+   local pos = 1
 880+   while true do
 881+      local amp = s:find("&", pos)
 882+      if not amp then break end
 883+      local semi = s:find(";", amp+1)
 884+      local stop = s:find("[ \t\n&]", amp+1)
 885+      if not semi or (stop and stop < semi) or (semi - amp) > 15 then
 886+         s = s:sub(1,amp-1) .. "&amp;" .. s:sub(amp+1)
 887+         pos = amp+1
 888+      else
 889+         pos = amp+1
 890+      end
 891+   end
 892+
 893+   -- encode naked <'s
 894+   s = s:gsub("<([^a-zA-Z/?$!])", "&lt;%1")
 895+   s = s:gsub("<$", "&lt;")
 896+
 897+   -- what about >, nothing done in the original markdown source to handle them
 898+   return s
 899+end
 900+
 901+-- Handles emphasis markers (* and _) in the text.
 902+local function emphasis(text)
 903+   for _, s in ipairs {"%*%*", "%_%_"} do
 904+      text = text:gsub(s .. "([^%s][%*%_]?)" .. s, "<strong>%1</strong>")
 905+      text = text:gsub(s .. "([^%s][^<>]-[^%s][%*%_]?)" .. s, "<strong>%1</strong>")
 906+   end
 907+   for _, s in ipairs {"%*", "%_"} do
 908+      text = text:gsub(s .. "([^%s_])" .. s, "<em>%1</em>")
 909+      text = text:gsub(s .. "(<strong>[^%s_]</strong>)" .. s, "<em>%1</em>")
 910+      text = text:gsub(s .. "([^%s_][^<>_]-[^%s_])" .. s, "<em>%1</em>")
 911+      text = text:gsub(s .. "([^<>_]-<strong>[^<>_]-</strong>[^<>_]-)" .. s, "<em>%1</em>")
 912+   end
 913+   return text
 914+end
 915+
 916+-- Handles line break markers in the text.
 917+local function line_breaks(text)
 918+   return text:gsub("  +\n", " <br/>\n")
 919+end
 920+
 921+-- Perform all span level transforms.
 922+function span_transform(text)
 923+   text = code_spans(text)
 924+   text = escape_special_chars(text)
 925+   text = images(text)
 926+   text = anchors(text)
 927+   text = auto_links(text)
 928+   text = amps_and_angles(text)
 929+   text = emphasis(text)
 930+   text = line_breaks(text)
 931+   return text
 932+end
 933+
 934+----------------------------------------------------------------------
 935+-- Markdown
 936+----------------------------------------------------------------------
 937+
 938+-- Cleanup the text by normalizing some possible variations to make further
 939+-- processing easier.
 940+local function cleanup(text)
 941+   -- Standardize line endings
 942+   text = text:gsub("\r\n", "\n")  -- DOS to UNIX
 943+   text = text:gsub("\r", "\n")    -- Mac to UNIX
 944+
 945+   -- Convert all tabs to spaces
 946+   text = detab(text)
 947+
 948+   -- Strip lines with only spaces and tabs
 949+   while true do
 950+      local subs
 951+      text, subs = text:gsub("\n[ \t]+\n", "\n\n")
 952+      if subs == 0 then break end
 953+   end
 954+
 955+   return "\n" .. text .. "\n"
 956+end
 957+
 958+-- Strips link definitions from the text and stores the data in a lookup table.
 959+local function strip_link_definitions(text)
 960+   local linkdb = {}
 961+
 962+   local function link_def(id, url, title)
 963+      id = id:match("%[(.+)%]"):lower()
 964+      linkdb[id] = linkdb[id] or {}
 965+      linkdb[id].url = url or linkdb[id].url
 966+      linkdb[id].title = title or linkdb[id].title
 967+      return ""
 968+   end
 969+
 970+   local def_no_title = "\n ? ? ?(%b[]):[ \t]*\n?[ \t]*<?([^%s>]+)>?[ \t]*"
 971+   local def_title1 = def_no_title .. "[ \t]+\n?[ \t]*[\"'(]([^\n]+)[\"')][ \t]*"
 972+   local def_title2 = def_no_title .. "[ \t]*\n[ \t]*[\"'(]([^\n]+)[\"')][ \t]*"
 973+   local def_title3 = def_no_title .. "[ \t]*\n?[ \t]+[\"'(]([^\n]+)[\"')][ \t]*"
 974+
 975+   text = text:gsub(def_title1, link_def)
 976+   text = text:gsub(def_title2, link_def)
 977+   text = text:gsub(def_title3, link_def)
 978+   text = text:gsub(def_no_title, link_def)
 979+   return text, linkdb
 980+end
 981+
 982+-- Main markdown processing function
 983+local function markdown(text)
 984+   init_hash(text)
 985+   init_escape_table()
 986+
 987+   text = cleanup(text)
 988+   text = protect(text)
 989+   text, link_database = strip_link_definitions(text)
 990+   text = block_transform(text)
 991+   text = unescape_special_chars(text)
 992+   return text
 993+end
 994+
 995+----------------------------------------------------------------------
 996+-- End of module
 997+----------------------------------------------------------------------
 998+
 999+-- For compatibility, set markdown function as a global
1000+_G.markdown = markdown
1001+
1002+-- Class for parsing command-line options
1003+local OptionParser = {}
1004+OptionParser.__index = OptionParser
1005+
1006+-- Creates a new option parser
1007+function OptionParser:new()
1008+   local o = {short = {}, long = {}}
1009+   setmetatable(o, self)
1010+   return o
1011+end
1012+
1013+-- Calls f() whenever a flag with specified short and long name is encountered
1014+function OptionParser:flag(short, long, f)
1015+   local info = {type = "flag", f = f}
1016+   if short then self.short[short] = info end
1017+   if long then self.long[long] = info end
1018+end
1019+
1020+-- Calls f(param) whenever a parameter flag with specified short and long name is encountered
1021+function OptionParser:param(short, long, f)
1022+   local info = {type = "param", f = f}
1023+   if short then self.short[short] = info end
1024+   if long then self.long[long] = info end
1025+end
1026+
1027+-- Calls f(v) for each non-flag argument
1028+function OptionParser:arg(f)
1029+   self.arg = f
1030+end
1031+
1032+-- Runs the option parser for the specified set of arguments. Returns true if all arguments
1033+-- where successfully parsed and false otherwise.
1034+function OptionParser:run(args)
1035+   local pos = 1
1036+   while pos <= #args do
1037+      local arg = args[pos]
1038+      if arg == "--" then
1039+         for i=pos+1,#args do
1040+            if self.arg then self.arg(args[i]) end
1041+            return true
1042+         end
1043+      end
1044+      if arg:match("^%-%-") then
1045+         local info = self.long[arg:sub(3)]
1046+         if not info then print("Unknown flag: " .. arg) return false end
1047+         if info.type == "flag" then
1048+            info.f()
1049+            pos = pos + 1
1050+         else
1051+            local param = args[pos+1]
1052+            if not param then print("No parameter for flag: " .. arg) return false end
1053+            info.f(param)
1054+            pos = pos+2
1055+         end
1056+      elseif arg:match("^%-") then
1057+         for i=2,arg:len() do
1058+            local c = arg:sub(i,i)
1059+            local info = self.short[c]
1060+            if not info then print("Unknown flag: -" .. c) return false end
1061+            if info.type == "flag" then
1062+               info.f()
1063+            else
1064+               if i == arg:len() then
1065+                  local param = args[pos+1]
1066+                  if not param then print("No parameter for flag: -" .. c) return false end
1067+                  info.f(param)
1068+                  pos = pos + 1
1069+               else
1070+                  local param = arg:sub(i+1)
1071+                  info.f(param)
1072+               end
1073+               break
1074+            end
1075+         end
1076+         pos = pos + 1
1077+      else
1078+         if self.arg then self.arg(arg) end
1079+         pos = pos + 1
1080+      end
1081+   end
1082+   return true
1083+end
1084+
1085+local function read_file(path, descr)
1086+   local file = io.open(path) or error("Could not open " .. descr .. " file: " .. path)
1087+   local contents = file:read("*a") or error("Could not read " .. descr .. " from " .. path)
1088+   file:close()
1089+   return contents
1090+end
1091+
1092+-- Handles the case when markdown is run from the command line
1093+local function run_command_line(arg)
1094+   -- Generate output for input s given options
1095+   local function run(s, options)
1096+      s = markdown(s)
1097+      if not options.wrap_header then return s end
1098+      local header
1099+      if options.header then
1100+         header = read_file(options.header, "header")
1101+      else
1102+         header = [[
1103+<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
1104+<html>
1105+<head>
1106+    <meta http-equiv="content-type" content="text/html; charset=CHARSET" />
1107+    <title>TITLE</title>
1108+    <link rel="stylesheet" type="text/css" href="STYLESHEET" />
1109+</head>
1110+<body>
1111+]]
1112+         local title = options.title or s:match("<h1>(.-)</h1>") or s:match("<h2>(.-)</h2>") or
1113+            s:match("<h3>(.-)</h3>") or "Untitled"
1114+         header = header:gsub("TITLE", title)
1115+         if options.inline_style then
1116+            local style = read_file(options.stylesheet, "style sheet")
1117+            header = header:gsub('<link rel="stylesheet" type="text/css" href="STYLESHEET" />',
1118+               "<style type=\"text/css\"><!--\n" .. style .. "\n--></style>")
1119+         else
1120+            header = header:gsub("STYLESHEET", options.stylesheet)
1121+         end
1122+         header = header:gsub("CHARSET", options.charset)
1123+      end
1124+      local footer = "</body></html>"
1125+      if options.footer then
1126+         footer = read_file(options.footer, "footer")
1127+      end
1128+      return header .. s .. footer
1129+   end
1130+
1131+   -- Generate output path name from input path name given options.
1132+   local function outpath(path, options)
1133+      if options.append then return path .. ".html" end
1134+      local m = path:match("^(.+%.html)[^/\\]+$") if m then return m end
1135+      m = path:match("^(.+%.)[^/\\]*$") if m and path ~= m .. "html" then return m .. "html" end
1136+      return path .. ".html"
1137+   end
1138+
1139+   -- Default commandline options
1140+   local options = {
1141+      wrap_header = true,
1142+      header = nil,
1143+      footer = nil,
1144+      charset = "utf-8",
1145+      title = nil,
1146+      stylesheet = "default.css",
1147+      inline_style = false
1148+   }
1149+   local help = [[
1150+Usage: markdown.lua [OPTION] [FILE]
1151+Runs the markdown text markup to HTML converter on each file specified on the
1152+command line. If no files are specified, runs on standard input.
1153+
1154+No header:
1155+    -n, --no-wrap        Don't wrap the output in <html>... tags.
1156+Custom header:
1157+    -e, --header FILE    Use content of FILE for header.
1158+    -f, --footer FILE    Use content of FILE for footer.
1159+Generated header:
1160+    -c, --charset SET    Specifies charset (default utf-8).
1161+    -i, --title TITLE    Specifies title (default from first <h1> tag).
1162+    -s, --style STYLE    Specifies style sheet file (default default.css).
1163+    -l, --inline-style   Include the style sheet file inline in the header.
1164+Generated files:
1165+    -a, --append         Append .html extension (instead of replacing).
1166+Other options:
1167+    -h, --help           Print this help text.
1168+    -t, --test           Run the unit tests.
1169+]]
1170+
1171+   local run_stdin = true
1172+   local op = OptionParser:new()
1173+   op:flag("n", "no-wrap", function () options.wrap_header = false end)
1174+   op:param("e", "header", function (x) options.header = x end)
1175+   op:param("f", "footer", function (x) options.footer = x end)
1176+   op:param("c", "charset", function (x) options.charset = x end)
1177+   op:param("i", "title", function(x) options.title = x end)
1178+   op:param("s", "style", function(x) options.stylesheet = x end)
1179+   op:flag("l", "inline-style", function() options.inline_style = true end)
1180+   op:flag("a", "append", function() options.append = true end)
1181+   op:flag("t", "test", function()
1182+      local n = arg[0]:gsub("markdown%.lua", "markdown-tests.lua")
1183+      local f = io.open(n)
1184+      if f then
1185+         f:close()
1186+         package.loaded.markdown = markdown
1187+         dofile(n)
1188+      else
1189+         error("Cannot find markdown-tests.lua")
1190+      end
1191+      run_stdin = false
1192+   end)
1193+   op:flag("h", "help", function() print(help) run_stdin = false end)
1194+   op:arg(function(path)
1195+      local s = read_file(path, "input")
1196+      s = run(s, options)
1197+      local file = io.open(outpath(path, options), "w") or error("Could not open output file: " .. outpath(path, options))
1198+      file:write(s)
1199+      file:close()
1200+      run_stdin = false
1201+   end
1202+   )
1203+
1204+   if not op:run(arg) then
1205+      print(help)
1206+      run_stdin = false
1207+   end
1208+
1209+   if run_stdin then
1210+      local s = io.read("*a")
1211+      s = run(s, options)
1212+      io.write(s)
1213+   end
1214+end
1215+
1216+-- If we are being run from the command-line, act accordingly
1217+if arg and arg[0]:find("markdown%.lua$") then
1218+   run_command_line(arg)
1219+else
1220+   return markdown
1221+end
+1, -0
1@@ -0,0 +1 @@
2+body { font-family: monospace; }
+1, -0
1@@ -0,0 +1 @@
2+<meta name="gay" content="true">
+1, -0
1@@ -0,0 +1 @@
2+<p>- with love, Myu be You</p>
+7, -0
1@@ -0,0 +1,7 @@
2+hallo. this template has a very bare style.css if you haven't noticed.  
3+write your own, because everyone has different needs.
4+
5+> lovely,  
6+> i know.
7+
8+visit <https://xorg.fyi> for an example of css usage.
+2, -0
1@@ -0,0 +1,2 @@
2+no info for you.  
3+asshole.
+3, -0
1@@ -0,0 +1,3 @@
2+hello.  
3+i am big S.  
4+- big S
+24, -0
 1@@ -0,0 +1,24 @@
 2+<!DOCTYPE html>
 3+<html>
 4+  <head>
 5+    <meta charset="utf-8">
 6+    <title>{{CURR}}</title>
 7+    <link rel="stylesheet" href="/assets/style.css">
 8+    {{include "inc/head.html"}}
 9+  </head>
10+  <body>
11+    <nav>
12+      <h3><a href="/">>root</a></h3>
13+      {{NAV}}
14+    </nav>
15+    <main>
16+      {{if CONTENT}}
17+      {{CONTENT}}
18+      {{end}}
19+      {{if not HIDDEN}}
20+      {{include "inc/note.html"}}
21+      {{end}}
22+    </main>
23+    <footer>{{FOOTER}}</footer>
24+  </body>
25+</html>
+1, -0
1@@ -0,0 +1 @@
2+whois who?