santoku
santoku

santoku

A Lua framework for building applications end to end

Lua 5.1 from the build system to the server to the browser. Every example on this site runs in your browser. Edit one and run it.


santoku targets Lua 5.1, because 5.1 is the version its platforms actually share. LuaJIT implements 5.1 and OpenResty embeds LuaJIT, so server code, client code and the build harness all run the same language. Compiled to WebAssembly, the 5.1 core is smaller to embed, and its single number type sidesteps the integer and float split introduced in 5.3, which keeps numeric values crossing the JavaScript boundary simple. Support for newer versions is meant to come from compatibility shims layered over the 5.1 core rather than version branches in the tree; contributions and design ideas for that layer are welcome.

santoku-lpeg

View on LuaRocks

parsing and text transformation on a vendored LPeg: PEG strings, scanners, minifiers, a comment stripper, a highlighter and a formatter

santoku-lpeg does parsing and text transformation in three layers. A vendored LPeg 1.1.0 engine ships as the C module santoku.re.core. santoku.re compiles PEG pattern strings on top of it. santoku.lpeg exports finished parsers: scanners for JSON lines, CSV, XML and HTML, an HTML tree, minifiers, a comment stripper, a highlighter and a formatter.

Details
  • The engine is renamed to santoku.re.core so it can coexist with an external lpeg rock. require("lpeg") doesn't reach it, and fails unless some other rock supplies that name.
  • santoku.re is the re grammar frontend: PEG pattern strings with match, find and gsub.
  • santoku.re also has a second, state-free parallel tier (check, tags, pmatch) that accepts only structure-reading patterns.
ModuleWhat it does
santoku.lpegscanning helpers that stream named fields out of JSON lines, parse CSV, stream XML events, and scan, extract, rewrite and minify HTML
santoku.lpeg.htmlan editable HTML tree that counts text offsets the way browser Selection does
santoku.lpeg.stripa subsequence-safe comment stripper for a dozen languages
santoku.lpeg.unitreads systemd unit and quadlet files into sections and entries
santoku.lpeg.highlightturns Lua, C and nginx source into Prism-compatible token markup
santoku.lpeg.formatreindents HTML templates with mustache, XML, CSS, Lua and nginx config
  • santoku.lpeg exports finished parsers only. A new parser goes against santoku.re or santoku.re.core, and leaves santoku.lpeg as it is.
  • Choose santoku.re when the grammar reads better as a PEG string and every transform is a literal.
  • Choose santoku.re.core when captures need Lua functions, when code assembles the rules from data, or when you hold and reuse the compiled pattern.
  • Both notations describe the same patterns and can be mixed, since re.compile returns a santoku.re.core pattern.
ConsumerUses
toku web buildsminify_html and transform_inline, to minify shipped HTML
the component frameworkcomponent_parts, to split fragments
search indexinghtml_text and json_fields, to reduce documents to indexable text
commit hooksstrip, for comment policy enforcement
  • The sections run from basics to advanced.

re pattern strings

Literals and classes

re.match(subject, pattern) compiles a PEG pattern string and matches it. Without captures it returns the position one past the match, and on failure it returns nil.

local re = require("santoku.re")
print("literal:", re.match("hello", "'hello'"))
print("capture:", re.match("hello world", "{%a+}"))
print("after digits:", re.match("123abc", "%d+ {%a+}"))
print("no match:", re.match("hello", "%d+"))
return re.match("hello world", "{%a+}")
Details
  • {...} adds a value capture.
  • Character classes are the familiar %a %d %s %w set, and 'quoted' text matches literally.

Predicates and bounded repetition

PEG predicates consume nothing. &p succeeds only if p matches here, and !p succeeds only if it does not.

local re = require("santoku.re")
print("hex:", re.match("c0ffee", "{[0-9a-f]+}"))
print("complement:", re.match("xyz", "{[^aeiou]+}"))
print("exactly 3:", re.match("aaaa", "%a^3 {}"))
print("at least 2:", re.match("aaaa", "%a^+2 {}"))
print("at most 2:", re.match("aaaa", "%a^-2 {}"))
print("lookahead:", re.match("foobar", "&'foo' {%a+}"))
print("negation:", re.match("bar", "!'foo' {%a+}"))
print("guarded:", re.match("foo", "!'foo' %a+"))
print("until comma:", re.match("a b,c", "{ (!',' .)* }"))
return re.match("a b,c", "{ (!',' .)* }")
Details
  • The idiom (!stop .)* consumes up to a delimiter without eating it.
  • Bracket classes [0-9a-f] and complements [^aeiou] compile to set patterns.
  • Repetition is bounded three ways, and the counts differ from LPeg combinators.
SuffixMeans
^nexactly n concatenated copies
^+nat least n
^-nat most n

Capture forms

{} captures the current position, {| ... |} collects into a table, and {:name: ... :} names an entry inside that table. {~ ... ~} is a substitution capture that rewrites matched text in place.

local re = require("santoku.re")
print("pos:", re.match("abc", ". . {}"))
local d = re.match("2026-08-25",
  "{| {:y: %d+ :} '-' {:m: %d+ :} '-' {:d: %d+ :} |}")
print("date:", d.y, d.m, d.d)
print("subst:", re.match("a b c", "{~ (%s -> '_' / .)* ~}"))
print("transform:", re.match("x", "'x' -> 'Y'"))
return d.y
Details
  • This fork keeps only literal string and number transforms (patt -> 'x').
  • Function transforms and user definition tables were dropped, so %custom raises and -> f is a syntax error.

re.find and re.gsub

re.find searches for the pattern anywhere in the subject, and returns the start and inclusive end positions. re.gsub replaces every match, and a string replacement can reference captures with %1.

local re = require("santoku.re")
print("find:", re.find("hello 123 world", "%d+"))
print("gsub:", re.gsub("hello world", "%s+", "_"))
print("gsub caps:", re.gsub("ab cd", "{%a+}", "<%1>"))
return re.gsub("hello world", "%s+", "_")
Details
  • re.match, re.find and re.gsub memoize their compiled patterns, so repeated calls with the same pattern string are cheap.

Back-references

=name re-matches the text that a prior named group captured. Use it for doubled words, matching delimiters and heredoc-style constructs.

local re = require("santoku.re")
print("doubled:", re.match("boo boo", "{:w: %a+ :} ' ' =w"))
print("differs:", re.match("boo baa", "{:w: %a+ :} ' ' =w"))
return re.match("boo boo", "{:w: %a+ :} ' ' =w")
Details

Recursive grammars

A pattern of the form name <- expression defines a grammar rule. Rules can refer to themselves, so a grammar matches balanced, nested structure that a regex cannot.

local re = require("santoku.re")
local balanced = "b <- '(' b* ')'"
print("nested:", re.match("(()())", balanced))
print("deep:", re.match("(((())))", balanced))
print("unbalanced:", re.match("((", balanced))
return re.match("(()())", balanced)
Details
  • One line matches arbitrarily nested parentheses, as the code shows.

A multi-rule parser

Rules compose into a real parser. Here a two-rule grammar parses a key=value list straight into nested Lua tables.

local re = require("santoku.re")
local p = [=[
  pairs <- {| pair (',' pair)* |}
  pair <- {| {:key: %a+ :} '=' {:val: %d+ :} |}
]=]
local t = re.match("a=1,b=22,c=3", p)
print("count:", #t)
print("first:", t[1].key, t[1].val)
print("second:", t[2].key, t[2].val)
return t[3].key .. "=" .. t[3].val
Details
  • The outer rule collects pairs into an array, and the inner rule names each key and value.
  • santoku.lpeg uses the same grammar structure internally to skip whole JSON values.

Precedence by layering

The classic PEG precedence technique has one rule per precedence level, each defined as a list of the next tighter one. Multiplication then groups before addition with no precedence table.

local re = require("santoku.re")
local p = [=[
  sum <- {| prod ('+' prod)* |}
  prod <- {| num ('*' num)* |}
  num <- {%d+}
]=]
local t = re.match("1+2*3+4", p)
print("terms:", #t)
print("middle term factors:", t[2][1], t[2][2])
print("outer terms:", t[1][1], t[3][1])
return #t
Details
  • sum is prods joined by +, and prod is nums joined by *.
  • No separate AST pass is needed. The capture tables mirror the grouping directly.
  • 1+2*3+4 parses to three terms, and only the middle term holds two factors.

The parallel tier

Beyond the serial matcher, santoku.re compiles patterns to state-free programs that can run without a Lua state, for parallel scans from C. That tier reads structure only.

local re = require("santoku.re")
print("plain:", re.check("%a+"))
print("named group:", re.check("{:w: %a+ :}"))
print("value cap:", re.check("{%a+}"))
print("backref:", re.check("{:g: %a :} =g"))
local t = re.tags("{:caps: %u+ :} / {:num: %d+ :}")
print("tags:", t.caps, t.num)
print("reused name:", re.check("{:w: %a :} {:w: %d :}"))
print("pmatch:", re.pmatch("%a+", "hello123"))
print("pmatch init:", re.pmatch("%d+", "ab12", 3))
print("prog:", type(re.prog("[A-Za-z0-9]+")))
local ok, e = require("santoku.error").pcall(re.prog, "{%a+}")
print("prog rejects:", ok, require("santoku.string").match(tostring(e), "santoku%.re: .*"))
return re.pmatch("%a+", "hello123")
Details
  • Position and named-group captures pass. Value and match-time captures are rejected.
  • re.check reports acceptance.
  • re.tags returns dense ids for named groups in order of first appearance.
  • Each named group needs a unique name. re.check returns nil and a message for a reused name, and re.tags raises.
  • re.prog compiles a pattern to that program, and returns it as an opaque userdata for C consumers such as santoku-learn's extractors.
  • re.prog raises "santoku.re: " plus the reason for a pattern the tier rejects.
  • re.pmatch runs the state-free matcher. It returns the match's inclusive end offset and a capture count.
  • The argument orders differ. pmatch takes (pattern, subject, init), and match takes (subject, pattern, init).

The combinator API

santoku.re.core

santoku.re.core is the vendored engine, and a new grammar starts here. Patterns carry the module table as their __index, so p:match(subject, init) and match(p, subject, init) are the same call.

local lpeg = require("santoku.re.core")
local arr = require("santoku.array")
local names = {}
for k in pairs(lpeg) do
  names[#names + 1] = k
end
arr.sort(names)
print("exports:", arr.concat(names, " "))
print("version:", lpeg.version)
print("type:", lpeg.type(lpeg.P("x")), lpeg.type("x"))
print("match:", lpeg.match(lpeg.P("ab"), "abc"))
print("method form:", lpeg.P("ab"):match("abc"))
print("from init:", lpeg.P("bc"):match("abc", 2))
return lpeg.version
Details
  • The module is santoku.re.core, so require("lpeg") isn't the entry point. The rename lets a project depend on an external lpeg rock at the same time.
GroupExported names
pattern constructorsP, S, R, B, V and utfR
the capture familyC, Cc, Cp, Cs, Ct, Cg, Cb, Cf, Cmt and Carg
the matchermatch
other functionslocale, type and setmaxstack
the debug printersptree and pcode
the parallel tier, which santoku.re wraps_prog, _check, _tags and _pmatch
  • version is a string field, so read lpeg.version without a call.

Constructors and operators

P, S and R build patterns, and operators compose them. Without captures a match returns the position one past the match, and nil on failure.

local lpeg = require("santoku.re.core")
local P, S, R, B = lpeg.P, lpeg.S, lpeg.R, lpeg.B
local digit = R("09")
print("sequence:", (P("a") * P("b")):match("abc"))
print("ordered choice:", (P("ab") + P("a")):match("ac"))
print("zero or more:", (digit ^ 0):match("12x"))
print("at least two:", (digit ^ 2):match("1x"))
print("at most two:", (digit ^ -2):match("1234"))
print("difference:", ((P(1) - S(",;")) ^ 1):match("ab,c"))
print("negative lookahead:", (-P("foo") * P(1) ^ 1):match("bar"))
print("positive lookahead:", (#P("foo") * P(1) ^ 1):match("foobar"))
print("look-behind:", (P(1) * B(P("a")) * P("b")):match("ab"))
print("always, never:", P(true):match("x"), P(false):match("x"))
return (digit ^ 1):match("2026ad")
Details
P(x) withMatches
a stringthat string literally
a non-negative numberexactly that many bytes
true or falsealways or never
a tablethe grammar the table defines
  • S is a set of bytes, and R is one or more inclusive byte ranges.
OperatorMeaning
p1 * p2sequence
p1 + p2ordered choice: the first alternative that matches wins, with no backtracking into it
p ^ nat least n repetitions
p ^ -nat most n repetitions
p1 - p2p1 only where p2 does not match
-pa negative lookahead, which consumes nothing
#pa positive lookahead, which consumes nothing
  • B(p) looks behind instead. p must have a fixed length and carry no captures.

Combinator captures

C captures the matched text, Cp the current position and Cc a constant. Ct collects the captures below it into a table, and Cg(p, name) names an entry inside that table.

local lpeg = require("santoku.re.core")
local P, R = lpeg.P, lpeg.R
local C, Cc, Cp, Cs, Ct, Cg =
  lpeg.C, lpeg.Cc, lpeg.Cp, lpeg.Cs, lpeg.Ct, lpeg.Cg
local word = C(R("az") ^ 1)
print("text:", word:match("abc"))
print("position:", (P("ab") * Cp()):match("abc"))
print("constant:", (P("yes") * Cc(true)):match("yes"))
local pair = Ct(word * P(",") * word)
print("table:", pair:match("ab,cd")[1], pair:match("ab,cd")[2])
local named = Ct(Cg(word, "first") * P(",") * Cg(word, "second"))
local t = named:match("ab,cd")
print("named:", t.first, t.second)
print("substitution:", Cs((P(" ") / "_" + P(1)) ^ 0):match("a b c"))
local n = (C(R("09") ^ 1) / tonumber):match("42")
print("function:", n, type(n))
print("select:", ((word * P("=") * word) / 2):match("k=v"))
return named:match("ab,cd").second
Details
  • Cs is a substitution capture: the matched text with each inner capture replaced by its value.
  • p / x transforms captures. x may be a function, a table, a string with %n references, or a number that selects one capture.
  • Every capture form here has a re string counterpart. The two notations differ in spelling, and they can express the same things.

Folds, back-references and match-time

Cf(p, f) folds the captures of p left to right, with the first as the seed. Cmt(p, f) runs f(subject, position, captures...) at match time.

local lpeg = require("santoku.re.core")
local P, R, C, Cf, Cg, Cb, Cmt, Carg =
  lpeg.P, lpeg.R, lpeg.C, lpeg.Cf,
  lpeg.Cg, lpeg.Cb, lpeg.Cmt, lpeg.Carg
local num = C(R("09")) / tonumber
local function add (a, b) return a + b end
print("fold:", Cf(num * (P("+") * num) ^ 0, add):match("1+2+3"))
print("accumulate:", (num * (P("+") * num % add) ^ 0):match("1+2+3"))
local word = C(R("az") ^ 1)
print("back-reference:", (Cg(word, "w") * P(" ") * Cb("w")):match("ab cd"))
local long = Cmt(word, function (s, i, w)
  if #w > 2 then return i, #w end
end)
print("match-time:", long:match("abcd"), long:match("ab"))
print("argument:", (Carg(1) * word):match("abc", 1, "tag"))
return (num * (P("+") * num % add) ^ 0):match("1+2+3")
Details
  • p % f is the accumulator form of the same idea, and it makes iterative grammars readable. Whatever precedes it supplies the running value, and each match of p folds into it.
  • Cb(name) re-reads a capture named earlier by Cg in the same match.
The Cmt function returnsEffect
nil or falsethe match fails
truethe position stays
a numberthe match moves to that position
further valuesthey become captures
  • Carg(n) pulls the nth extra argument passed to match.
  • The parallel tier rejects Cmt and every value capture (C, Ct, p / f and the folds). So re.check returns nil and a message that names the reason for any pattern built on them.
  • Cp and Cg pass.

Grammar tables and V

A grammar is a table passed to P. Its rules are keyed by name, V(name) refers to a rule, and element 1 names the initial rule or is the initial rule itself.

local lpeg = require("santoku.re.core")
local P, S, R, C, Ct, V =
  lpeg.P, lpeg.S, lpeg.R, lpeg.C, lpeg.Ct, lpeg.V
local ws = S(" \t") ^ 0
local word = C(R("az") ^ 1)
local list = P({ "list",
  list = P("(") * ws *
    Ct(((word + V("list")) * ws) ^ 0) * P(")"),
})
local t = list:match("(ab (cd ef) gh)")
print("nested:", t[1], t[2][1], t[2][2], t[3])
local expr = P({ "sum",
  sum = Ct(V("prod") * (P("+") * V("prod")) ^ 0),
  prod = Ct(V("num") * (P("*") * V("num")) ^ 0),
  num = C(R("09") ^ 1),
})
local e = expr:match("1+2*3+4")
print("terms:", #e)
print("middle term factors:", e[2][1], e[2][2])
return t[2][2]
Details
  • Recursion through V lets a grammar match balanced, nested structure.
  • Rule names can be any non-nil value, so code can generate rules from data.
  • Left recursion is rejected when the pattern is compiled, so it never loops at match time.
  • The second grammar in the code layers one rule per precedence level. It's the combinator form of the re precedence card: https://santoku.dev/santoku-lpeg#santoku-lpeg--precedence-by-layering

Byte classes and utfR

locale() returns a fresh table of eleven character classes, each a set of bytes. utfR(first, last) is the one UTF-8 aware constructor, and matches a single codepoint in the inclusive range.

local lpeg = require("santoku.re.core")
local P, C, Ct = lpeg.P, lpeg.C, lpeg.Ct
local cls = lpeg.locale()
print("alpha run:", C(cls.alpha ^ 1):match("abc123"))
print("stops at a multi-byte char:",
  C(cls.alpha ^ 1):match("na\195\175ve"))
local codepoint = lpeg.utfR(0x80, 0x10FFFF) + P(1)
local chars = Ct(C(codepoint) ^ 0)
local t = chars:match("na\195\175ve")
print("characters:", #t)
print("third:", t[3], #t[3])
return #t
Details
  • The classes are alnum, alpha, cntrl, digit, graph, lower, print, punct, space, upper and xdigit. Each one tests the C library predicate over every byte value.
  • Under the C locale the classes cover ASCII only, and stop at the first byte of a multi-byte character.
  • The same classes back the %a %d %s %w names in re pattern strings.
  • utfR compiles to a plain byte set when the range fits in ASCII, and to a multi-byte matcher otherwise.
  • utfR gives codepoint boundaries. It does no case mapping and knows no character properties.
  • Lua 5.1 has no \x escape, so the code writes non-ASCII bytes as decimal escapes.

Scanners

lp.json_fields

lp.json_fields(line, names) streams named top-level fields out of a JSON line as byte ranges, with no document tree. Search pipelines use it to pull indexable text out of JSONL without a full JSON parse per line.

local lp = require("santoku.lpeg")
local arr = require("santoku.array")
local line =
  '{"title":"Dune","tags":["scifi","classic"],"meta":{"title":"nope"},"year":1965}'
local out = {}
for s, e in lp.json_fields(line, { "title", "tags" }) do
  out[#out + 1] = line:sub(s, e)
  print(line:sub(s, e))
end
return arr.concat(out, ", ")
Details
  • String values yield their inner range, quotes excluded.
  • Arrays yield each string element.
  • Nested objects are skipped entirely.
  • Empty strings are not yielded.

lp.csv

lp.csv(text) is a small CSV parser that returns an array of row arrays. Admin data imports use it where a spreadsheet export is the source of truth.

local lp = require("santoku.lpeg")
local arr = require("santoku.array")
local text = arr.concat({
  'name,qty\r\n',
  '"Smith, J.",2\r\n',
  '"say ""hi""",3\r\n',
})
local rows = lp.csv(text)
print("rows:", #rows)
print("quoted comma:", rows[2][1], rows[2][2])
print("escaped quote:", rows[3][1])
return rows[2][1]
Details
  • Quoted fields may contain commas and newlines.
  • Doubled quotes unescape to one.
  • CRLF and lone LF both delimit records.
  • A UTF-8 BOM is stripped.
  • Fully blank records are dropped.

lp.xml_events

xml_events(s) returns a streaming iterator over a whole XML document held in one string. Each step yields one event: "start", name, attrs, ns, or "text", text, or "end", name.

local lp = require("santoku.lpeg")
local arr = require("santoku.array")
local str = require("santoku.string")
local feed = arr.concat({
  "<?xml version=\"1.0\"?>\r\n",
  "<rss xmlns:dc=\"http://purl.org/dc/elements/1.1/\">\r\n",
  "<item id=\"7\"><title>Caf&#xe9; &amp; chips &#163;5</title>",
  "<dc:creator>Ann</dc:creator><br/>",
  "<![CDATA[<b>raw</b>]]> &lt;ok&gt;<!-- note --> end</item>\r\n",
  "</rss>",
})
local depth = 0
for kind, a, b, c in lp.xml_events(feed) do
  if kind == "start" then
    print(str.rep("  ", depth) .. "start", a, b.id or "", c.dc or "")
    depth = depth + 1
  elseif kind == "text" then
    print(str.rep("  ", depth) .. "text", (str.gsub(a, "\n", "\\n")))
  else
    depth = depth - 1
    print(str.rep("  ", depth) .. "end", a)
  end
end
return depth
Details
  • A self-closing element yields start then end.
  • attrs maps each raw attribute name, xmlns declarations included, to its decoded value.
  • ns maps every prefix in scope to its URI, with "" for the default namespace and xml always bound.
  • An element that declares no namespace shares its parent's ns table, so treat ns as read-only.
  • Whitespace inside the root element is text, and whitespace outside it is skipped.
  • Each run of character data is one text event, joined across CDATA sections, comments and processing instructions.
  • CRLF and lone CR become LF.
  • The five predefined entities and numeric character references decode.
  • The XML declaration, processing instructions, comments, a UTF-8 BOM and the DOCTYPE are skipped.
  • Entities that the DOCTYPE declares never expand.
  • Input is bytes only. There's no encoding conversion, so UTF-8 text passes through unchanged.

XML errors

xml_events raises during iteration, so the events before the fault have already arrived. The error is err.error("xml_events", offset, msg).

local lp = require("santoku.lpeg")
local err = require("santoku.error")
local str = require("santoku.string")
local function first_error (s)
  local seen = 0
  local ok, tag, at, msg = err.pcall(function ()
    for _ in lp.xml_events(s) do
      seen = seen + 1
    end
  end)
  print(ok, tag, at, msg, "after " .. seen .. " events")
end
first_error("<a><b></a>")
first_error("<a>caf&eacute;</a>")
first_error("<!DOCTYPE a [<!ENTITY e \"boom\">]><a>&e;</a>")
first_error("<a/><b/>")
local ok, msg = pcall(function ()
  for _ in lp.xml_events("<a>1 < 2</a>") do end
end)
print(ok, str.match(tostring(msg), "xml_events: .*"))
return ok
Details
  • err.pcall returns false, "xml_events", the 1-based byte offset and the message.
  • An uncaught error reads "xml_events: <offset>: <msg>".
xml_events raises for
mismatched or unclosed tags
a duplicate attribute
an unknown entity, such as &eacute;
content after the root element
malformed markup
  • An entity the DOCTYPE declares raises as unknown, because the DOCTYPE is never expanded.

lp.html_text

lp.html_text(html) iterates the visible text runs of an HTML fragment. It drops tags, comments and the entire contents of script and style.

local lp = require("santoku.lpeg")
local html =
  '<ul><li>alpha</li><li>beta</li></ul><script>track()</script><p>done</p>'
local n = 0
for text in lp.html_text(html) do
  n = n + 1
  print(n, text)
end
return n
Details
  • Block-level elements flush the current run, so structure boundaries become run boundaries.
  • Each run decodes character references with santoku.string's unescape_html.
  • The runs concatenate to html_extract's text.
  • html_text is the first stage that reduces stored HTML descriptions to tokenizable text for search indexing.

lp.html_extract and lp.html_inject

html_extract strips tags to plain text and returns tag records. Edit the records, then html_inject rebuilds markup around the text.

local lp = require("santoku.lpeg")
local html = 'hello <span class="author">J. Smith &amp; Co</span> world'
local text, tags = lp.html_extract(html)
print("text:", text)
print("tag:", tags[1].name, tags[1].attrs.class)
print("covers:", text:sub(tags[1].s, tags[1].e))
tags[1].text = "John Smith & Co"
return lp.html_inject(text, tags)
Details
  • A tag record carries the element name, the attribute table, and the 1-based inclusive s, e range the element covers in the stripped text.
  • Text decodes with str.unescape_html and attribute values with str.unescape_html_attr, so s and e index the decoded text.
  • In the code, a text override canonicalizes the author name.
  • html_inject escapes text with str.escape_html_text and attribute values with str.escape_html. It treats a text override as plain text.

Tag records from scratch

Tag records don't have to come from html_extract. Build them directly, and html_inject wraps ranges of plain text in markup.

local lp = require("santoku.lpeg")
local text = "hello Germany world"
local tags = { {
  name = "span", s = 7, e = 13,
  attrs = { class = "country", id = "276" },
} }
return lp.html_inject(text, tags, { "class", "id" })
Details
  • The third argument of html_inject fixes the attribute order, which makes the output deterministic. Attribute tables otherwise iterate in hash order.
  • Unlisted attributes follow the ordered ones.

lp.html_tags

lp.html_tags(html) iterates elements with their attributes and byte positions in the original HTML. Each step yields name, attrs, open_s, open_e, close_s, close_e.

local lp = require("santoku.lpeg")
local html = '<b>bold</b> and <i x="1">italic</i>'
for name, attrs, os_, oe, cs, ce in lp.html_tags(html) do
  print(name, attrs.x, html:sub(os_, oe), html:sub(cs, ce))
end
return html
Details
  • The open range covers the opening tag, and the close range covers the closing tag.
  • attrs decode as in html_extract.
  • These positions index the raw input, unlike html_extract's s and e.

lp.html_match_tags and lp.html_spans

html_match_tags builds span tag records for html_inject from parallel id, start and end vectors. Search hit highlighting and entity annotation render from matcher offsets this way.

local lp = require("santoku.lpeg")
local ivec = require("santoku.ivec")
local text = "Ada met Rome"
local ids = ivec.create({ 1, 2 })
local starts = ivec.create({ 0, 8 })
local ends = ivec.create({ 3, 12 })
local tags = lp.html_match_tags(ids, starts, ends,
  { [1] = "per", [2] = "loc" }, "hl-")
print("tags:", #tags, tags[1].attrs.class, tags[2].attrs.class)
print("spans:", lp.html_spans(tags):size())
return lp.html_inject(text, tags)
Details
  • The vectors hold 0-based offsets. Anything with :size() and :get(i) works, which santoku.ivec satisfies.
  • Class names map through a names table and an optional prefix.
  • html_spans goes the other way. It converts tag records to a santoku.pvec of (s-1, e) pairs for span algebra.
  • santoku.pvec comes from santoku-matrix, which santoku-lpeg depends on.

The HTML tree

An editable HTML tree

santoku.lpeg.html's parse turns an HTML fragment into a tree. serialize writes the tree back the way a browser's innerHTML does, and the rest of the module edits it.

local html = require("santoku.lpeg.html")
local tree = html.parse('<p class="note">Hello <b>big</b> world<br></p>')
local p = tree.c[1]
print("tag:", p.tag, html.get(p, "class"), #p.c)
local b = html.all(tree, function (n) return n.tag == "b" end)[1]
html.class_add(b, "em")
html.set(b, "title", "say \"hi\"")
html.insert_after(b, html.text("!"))
print("text:", html.text_content(tree))
return html.serialize(tree)
Details
Node fieldHolds
k"e" (element), "t" (text), "c" (comment) or "f" (fragment)
cthe children
pthe parent
vthe text
tagthe name
ns"svg" or "math" in foreign content
athe attributes, as an ordered list of { name, value } pairs
  • Names lowercase outside foreign content.
  • The first duplicate attribute wins.
  • Void elements take no children, and self-closing tags close in svg.
  • script and style keep their text raw.
FunctionsJob
el, text, frag, append, insert, insert_after, remove, unwrap, before, after and indexmove nodes
get, set, unset and hasread and write attributes
has_class, class_add, class_rm and class_toggleedit the class list
all, closest, contains, clone and text_contentquery
  • Implicit end tags and table fostering are not modeled, so the input should close its own tags.

Text offsets and extract

Text offsets count UTF-16 code units across the tree's text nodes in document order. That's the unit browser Selection and Range offsets use, so an astral character counts 2.

local html = require("santoku.lpeg.html")
local tree = html.parse("<b>caf\195\169 \240\159\152\128</b> ok")
local segs, total = html.segments(tree)
print("lengths:", segs[1].len, segs[2].len, "total:", total)
print("after <b>:", html.point_offset(tree, tree, 2))
local node, at = html.locate(tree, 7)
print("offset 7:", node.v, at, (html.char_before(tree, 7)))
local cut, parent, i = html.extract(tree, 3, 8)
print("cut:", html.serialize(cut), "left:", html.serialize(tree))
html.insert_at(parent, i, cut)
html.normalize(tree)
return html.serialize(tree)
Details
  • segments lists each text node with its start and length.
  • point_offset turns a (parent, 1-based child index) point into an offset. offset_of does the same for a text node and a local offset.
  • locate goes back from an offset, and prefers the end of the earlier text node at a boundary.
  • char_before and char_after return the whole character on either side of an offset.
  • extract(tree, a, b) cuts the range into a fragment the way Range.extractContents does, and clones partly selected elements. It returns the parent and index where the cut was.
  • insert_at puts a fragment back, and normalize merges adjacent text nodes.
  • u16 and u16_sub measure and slice UTF-8 strings in the same units.

An allowlist sanitizer

html.sanitizer(policy) returns a function that makes stored markup safe to print. Allowed elements and attributes come through, and other tags drop the way a browser hides them.

local html = require("santoku.lpeg.html")
local clean = html.sanitizer({
  schemes = { "http", "https", "mailto" },
  tags = { a = { href = "url" }, span = { class = true }, b = {} },
})
print(clean('<span class="author">Ann</span> <a href="javascript:x()" onclick="x()">x</a>'))
print(clean("<b>bold <script>x()</script>"))
return clean('<a href="/deals/?id=1">deal</a> <blink>z</blink> <iframe src="x"></iframe>')
Details
  • policy.tags maps each allowed element to its attribute rules.
RuleKeeps the attribute when
truealways
"url"the URL is relative or its scheme is in policy.schemes
a tablethe value is a key set to true
a functionthe function returns a truthy value for the value
  • Scheme checks ignore whitespace and control characters, and run after character references decode.
  • A disallowed element drops its start and end tags and keeps its content, the way a browser renders an unknown element.
  • Tag boundaries follow a browser's tokenizer: a quoted value runs to its closing quote and may hold < and >, and an attribute name may hold < or a quote. A start tag the parse grammar reads differently drops, or comes out bare when its name is allowed.
  • A tag cut off by the end of the input drops.
  • script, style and the other raw text elements always come out escaped, content included. A policy that lists one raises.
  • Comments, doctypes, processing instructions and stray end tags drop. Open allowed elements close at the end.
  • Text decodes and escapes again, and attribute values come out double-quoted.

Minifiers and rewriters

lp.minify_lua

minify_lua(src, opts) parses Lua 5.1, and returns the smallest equivalent source plus an info table. santoku-bundle runs it over the bundled Lua when given a minify option.

local lp = require("santoku.lpeg")
local err = require("santoku.error")
local src = "-- add two\nlocal function add (left, right)\n  return left + right\nend\nreturn add(1, 2)"
local out, info = lp.minify_lua(src)
print(out)
print("names:", info.names)
print((lp.minify_lua("use('a') local x = nil return x", { calls = true, nils = true })))
local o2, i2 = lp.minify_lua("local value = 1 return debug.getlocal(1, 1), value")
print(o2, i2.names, i2.introspection[1].hook, i2.introspection[1].kind)
local whole = "local t = { used = 1, unused = 2 } return t.used"
local o3, i3 = lp.minify_lua(whole, { fields = true, shake = true })
print(o3, "dropped:", i3.shake.dropped[1].key)
print(err.pcall(lp.minify_lua, "x = 3x"))
return #out
Details
  • minify_lua drops comments, a shebang and whitespace the lexer doesn't need.
  • minify_lua renames locals and parameters, never globals or fields.
OptionEffect
rename = falsekeeps names
namespicks the naming strategy: "stable", "freq" or "order"
cost = function (out)tries all three strategies and keeps the cheapest
introspection = "rename"renames despite a live introspection call
introspection = "error"raises on a live introspection call
calls = truedrops call parentheses around a lone string or table argument
nils = truedrops = nil initializers
fields = truewhole-program: renames table fields it proves private
keep = { names }exempts some fields from fields = true
shake = truewhole-program: drops fields nothing reads
  • info.names reports the strategy used, or false.
  • A live debug.getlocal, setlocal, getupvalue or setupvalue turns renaming off, and info.introspection lists it.
  • fields and shake report in info.fields and info.shake.
  • A syntax error raises "minify_lua", the byte offset and the message.
  • santoku-make passes minify_lua the descriptor's minify.lua table.

lp.minify_html

lp.minify_html(html, opts) collapses whitespace runs and drops comments, and keeps pre, textarea, script and style bodies unchanged. It runs over every HTML asset in toku web release builds.

local lp = require("santoku.lpeg")
local arr = require("santoku.array")
local html = arr.concat({
  "<!-- build note -->\n",
  "<div>\n  hello   world\n</div>\n",
  "<pre>  keep   this  </pre>",
})
local tpl = arr.concat({
  "<ul>\n",
  "  {{#items}}\n",
  "  <li>{{name}}</li>\n",
  "  {{/items}}\n",
  "</ul>\n",
  "<p>\n  {{> note}}\n</p>",
})
print(lp.minify_html(tpl, { mustache = true, partials = { note = "<b>{{text}}</b>\n" } }))
return lp.minify_html(html)
Details
  • Pass { mustache = true } to minify a santoku.mustache template before it renders.
  • With mustache, a section, inverted or comment tag alone on its line takes the line with it, the way the renderer drops it.
  • Comment tags are dropped.
  • Variable, {{{...}}} and & tags space like text, with their names trimmed.
  • The space a section's content needs moves inside the section.
  • Add partials, a table of partial sources keyed by name. Then a {{> name}} alone on its line takes the line too.
  • The space around that {{> name}} follows the partial's own first and last elements.
  • A delimiter change raises an error, and so does an unclosed or mismatched tag.
  • A section that opens and closes on opposite sides of an HTML tag, comment or raw text element raises an error.

lp.transform_inline

lp.transform_inline(html, opts) rewrites inline script and style bodies through js and css transform functions. Scripts with a src attribute stay untouched.

local lp = require("santoku.lpeg")
local arr = require("santoku.array")
local str = require("santoku.string")
local html = arr.concat({
  '<style>.a { color: red }</style>',
  '<script src="x.js">keep</script>',
  '<script>var x = 1;</script>',
})
return lp.transform_inline(html, {
  js = str.upper,
  css = str.upper,
})
Details
  • In release builds the transforms are the JS and CSS minifiers. The code uses str.upper to make the rewrite visible.

lp.component_parts

lp.component_parts(html) splits an HTML component fragment into its pieces. It's the loader behind the web component framework, with one file per component.

local lp = require("santoku.lpeg")
local arr = require("santoku.array")
local parts = lp.component_parts(arr.concat({
  '<style>.card { color: red }</style>\n',
  '<div class="card">hi</div>\n',
  '<script src="lib.js"></script>\n',
  '<script>setup()</script>',
}))
print("dep:", parts.deps[1])
print("style:", parts.style)
print("init:", parts.init)
return parts.body
Details
Piece
the external deps (script src attributes)
the style body
the inline init script
an optional destroy script (script type="destroy")
the remaining body markup

The comment stripper

The Lua stripper

strip.strip_lua(src) removes Lua comments. Its output is always a byte-subsequence of the input, so it can only delete comment bytes and never mutate code.

local strip = require("santoku.lpeg.strip")
local arr = require("santoku.array")
local src = arr.concat({
  'local x = 1 -- setup\n',
  '-- whole line\n',
  'local s = "-- not a comment"\n',
  'local l = [==[ ]] -- inside ]==]\n',
  'a --[[ short block ]] b\n',
  'return x -- luacheck: ignore\n',
})
local out, bailed = strip.strip_lua(src)
print("bailed:", bailed)
return out
Details
  • The byte-subsequence rule is the stripper's core guarantee.
  • On any ambiguity the stripper returns the input unchanged with bailed true.
  • Comment markers inside short and leveled long strings survive.
  • Long comments are removed, and token separation stays.
  • Whole-line comments vanish without leaving blanks.
  • Functional directives such as luacheck: are kept.

One stripper per language

Each language gets its own strip function, with a grammar that covers that language's hazards.

local strip = require("santoku.lpeg.strip")
print((strip.strip_c('int x; // note\nint y; /* z */\n')))
print((strip.strip_js("var r = /ab\\/c/g;\n")))
print((strip.strip_js("var x = a / b // gone\n")))
print((strip.strip_js("x; // @ts-ignore\n")))
print((strip.strip_css(".a { color: red } /* c */\n")))
print((strip.strip_conf('add_header X "# not a comment";\n')))
print((strip.strip_xml("<r><!-- c --><![CDATA[<!-- kept -->]]></r>")))
return (strip.strip_html("<div>a<!-- c -->b</div>"))
Details
  • strip_c handles both C comment styles and keeps NOLINT-style directives.
  • strip_js tells regex literals from division, and leaves backtick templates and @ts- directives alone.
  • strip_css strips only block comments outside strings.
  • strip_conf strips nginx hash comments but not hashes inside quoted values.
  • The other exports are strip_sh, strip_hcl, strip_python, strip_yaml, strip_dockerfile, strip_unit and strip_html.
  • Since santoku-lpeg 3.0.1, strip_el strips Emacs Lisp, and .el files dispatch to it.
  • strip_el keeps a -*- cookie line when it's the first line or follows a shebang. It also keeps an ###autoload cookie and tk: directives.
  • strip_el treats semicolons inside strings and character literals such as "?;" as code.
  • Since santoku-lpeg 3.4.0, strip_xml strips XML, and .xml and .svg files dispatch to it.
  • strip_xml removes comments. It keeps the XML declaration, processing instructions, the DOCTYPE with its internal subset, and CDATA sections as written.
  • Since santoku-lpeg 3.4.0, strip.coverage returns checked for .xml and .svg.

Safety rules

strip's safety rules make it fit for a commit hook. Opaque regions are never scanned, anything unprovable bails, and a leading license head passes through untouched.

local strip = require("santoku.lpeg.strip")
local arr = require("santoku.array")
local sh = arr.concat({
  "#!/bin/sh\n",
  "cat <<'CONF'\n",
  "# keep: heredoc body\n",
  "CONF\n",
  "echo done # gone\n",
})
print((strip.strip_sh(sh)))
local _, bailed = strip.strip_sh("cat <<EOF\n# keep\n")
print("unterminated heredoc bails:", bailed)
local tsrc = "a /* c <% x() %> d */ b\n"
local tout, tbailed = strip.strip_template(tsrc, "c")
print("comment spanning a block bails:", tbailed, tout == tsrc)
local spdx = "-- SPDX-License-Identifier: MIT\n-- SPDX-FileCopyrightText: 2026 Example Co\nlocal x = 1\n"
print("license span:", strip.license_span(spdx, "mod.lua"))
local lic = "-- Copyright 2026 Example Co\n\nlocal x = 1 -- gone\n"
return (strip.strip(lic, "mod.lua"))
Details
  • Opaque regions are shell and HCL heredocs, Python docstrings, YAML block scalars and JS template literals. strip never scans them for comment markers.
  • So a hash inside a heredoc body survives, and the comment after the terminator goes.
  • Anything unprovable bails, and returns the input unchanged with bailed true.
Bails on
an unterminated heredoc
a block comment that spans a <% %> template block
output that stops being a byte-subsequence
  • A license head is a leading comment run that contains Copyright, SPDX-License-Identifier, or a permission notice. It passes through untouched before stripping starts.
  • A notice lost anywhere else bails, so strip never deletes it.
  • strip.license_at(src, filename, lines) is the writing side. It wraps lines in the file's comment syntax, and returns that text with the byte position it belongs at.
  • That position comes after any shebang or tk directive. license_at returns nil for a language strip doesn't know.
  • Since santoku-lpeg 3.0.1, the position also skips a first line (after any shebang) that starts with punctuation and holds -*-. The cookie on that line must stay first.
  • Examples of that first line are an Emacs Lisp header and Python's # -*- coding: utf-8 -*-.
  • Since santoku-lpeg 3.0.1, .el files get ";;" comments.
  • toku license uses license_at.
  • Since santoku-lpeg 3.4.0, license_at returns nil for .xml and .svg, which take no header.
  • Since santoku-lpeg 3.4.0, strip.license_span(src, filename) is the reading side. It returns the first and last byte of an SPDX header at that position.
  • An SPDX header is an SPDX-License-Identifier line followed within two lines by an SPDX-FileCopyrightText line. license_span returns nil when the position holds none.

Dispatch, templates and coverage

strip.strip(src, filename) picks the language from the extension, name or shebang, and returns out plus bailed. Binary and data formats pass through untouched.

local strip = require("santoku.lpeg.strip")
print(strip.strip("local x = 1 -- note\nreturn x\n", "mod.lua"))
print(strip.strip("<% foo() -- done %>", "mod.tk.lua"))
print(strip.strip("a = 1\n\n\n\nb = 2\n", "x.lua"))
print(strip.strip_template("a -- gone\n<% z() %>\n", "lua"))
print("lua:", strip.coverage("x = 1\n", "a.lua"))
print("png:", strip.coverage("", "logo.png"))
print("xyz:", strip.coverage("", "notes.xyz"))
print("language:", strip.language("<p>x</p>", "page.tk.html"))
print("language:", strip.language("local c = <% return 1 %>\n", "m.tk.browser.wasm.lua"))
local runs = strip.scan("x = 1 -- c\n", "lua")
print("scan:", #runs, runs[2][1], runs[2][2], runs[2][3])
local tk = strip.scan("x = <% y -- c %>\n", "lua", true)
print("scan tk:", #tk, tk[2][1], tk[2][2], tk[2][3])
return (strip.strip("local x = 1 -- note\nreturn x\n", "mod.lua"))
Details
  • After stripping, runs of blank lines outside protected regions collapse to one. The protected regions are long strings, heredocs, block scalars and template blocks.
  • A .tk.<ext> template file is handled twice over. Literal text is stripped with the output language's grammar.
  • The Lua of each <% ... %> block is stripped too, and the delimiters stay.
  • Since santoku-lpeg 3.4.1, a .tk. segment anywhere in the file name marks a template, and the last extension sets its language. So m.tk.browser.wasm.lua is a Lua template.
  • strip.coverage classifies a file as checked, ignored or unknown. A commit hook uses it to decide whether a file participates in comment policy at all.
  • Since santoku-lpeg 3.2.0, strip.language(src, filename) returns the language strip.strip would pick, and whether the file is a template.
  • Since santoku-lpeg 3.2.0, strip.scan(src, lang) returns that grammar's token list. Each run is one { kind, s, e }, with e one past the last byte.
  • strip.scan returns nil for a language it doesn't know or a source it bails on.
  • Since santoku-lpeg 3.3.0, strip.scan(src, lang, true) scans with the .tk template grammar, where each <% %> block is one code run.

The unit file parser

santoku.lpeg.unit since santoku-lpeg 3.8.0

unit.parse(src) reads a systemd unit or podman quadlet file, such as a .service or .container file. It returns the sections in file order, each as { name = "Service", entries = { { key, value }, ... } }.

local unit = require("santoku.lpeg.unit")
local arr = require("santoku.array")
local sections = unit.parse(arr.concat({
  "# api container\n",
  "[Container]\n",
  "Image=docker.io/library/alpine\n",
  "Volume=data.volume:/data\n",
  "Volume=./conf:/conf:ro\n",
  "Exec=sh -c \\\n",
  "  \"echo hi\"\n",
  "[Install]\n",
  "WantedBy=default.target\n",
}))
for _, s in ipairs(sections) do
  for _, e in ipairs(s.entries) do
    print(s.name, e[1], e[2])
  end
end
return #sections
Details
  • Entries keep file order, so a repeated key such as Environment= or Volume= appears once per line. An empty value stays as "", and the caller decides whether it resets a list.
  • A repeated section header starts a new section in the result.
  • parse splits each line at the first =, then trims the key and the value. It doesn't interpret quotes or escapes.
  • Lines whose first non-blank character is # or ; are comments. A # or ; later in a line stays in the value.
  • A backslash at the end of a line becomes a space, and the next line joins the value with its leading whitespace. An escaped backslash, \\, at the end of a line stays as text.
  • Comment lines inside a continuation are skipped, and a blank line ends it.
  • parse reads LF and CRLF line endings and a file without a final newline.
  • parse raises on a key before the first section, a line that is neither a [Section] header nor key=value, and an argument that isn't a string. The error names the line number.
  • santoku.lpeg.strip handles the same files for comment stripping, through strip_unit.

The highlighter

santoku.lpeg.highlight

highlight(code, lang) turns Lua, C or nginx source into token markup. Each token becomes <span class="token TYPE"> with the class names Prism uses, so a Prism theme styles it unchanged.

local hl = require("santoku.lpeg.highlight")
print(hl.highlight_lua("local n = #t -- size"))
print(hl.highlight_c("int x = 0x1F;"))
print(hl.highlight_nginx("gzip on;"))
print(hl.highlight("a < b & c", "text"))
return hl.highlight("return f(x)", "lua")
Details
  • highlight picks the grammar by language name. highlight_lua, highlight_c and highlight_nginx call one grammar directly.
  • Any other language name gets escaped text: & and < are escaped, and a no-break space becomes a space. The result can go straight into innerHTML.
  • On every card of this site the output equals Prism 1.30.0's.
  • The known difference is a ..5, which highlight reads as .. then 5, as the Lua lexer does.
  • This site highlights its cards with it at build time, and the live editor calls it on each keystroke.

The formatter

HTML, XML and CSS

santoku.lpeg.format's format(src, filename, opts) reindents HTML templates with mustache sections, XML and CSS in one style. It returns the output and a refused flag.

local fmt = require("santoku.lpeg.format")
local arr = require("santoku.array")
local src = arr.concat({
  "<ul>\n",
  "{{#items}}\n",
  "\t<li>{{name}}</li>   \n",
  "{{/items}}\n",
  "</ul><p>a <b>b</b></p>",
})
local out, refused = fmt.format(src, "list.html", { css = "" })
print("refused:", refused)
print(fmt.coverage("", "list.html"), fmt.coverage("", "app.lua"))
print(arr.concat(fmt.tokens("<p>a <b>b</b></p>", "x.html"), "|"))
print(fmt.format("{{#a}}<div>{{/a}}</div>", "x.html", { css = "" }))
print(fmt.format("<div><p>a</p></div>", "x.html", { css = "" }))
print(fmt.format("<div> <p>a</p> </div>", "x.html", { css = "" }))
print(fmt.format("<template> {{#r}} <div>a</div> {{/r}} </template>", "t.html", { css = "" }))
print(fmt.format("a {\n\tb: <% return c %>;\n}\n", "a.tk.css"))
print(fmt.format("<div>\n<p class=\"a   b  \n    c\"\n  title=\"x\n  y\">z</p>\n</div>\n", "x.html", { css = "" }))
print(select(3, fmt.format("<p>a\0b</p>", "x.html")))
return out
Details
  • The style is a 2-space indent, with section content one level deeper than its tags.
  • Script and style bodies sit 2 deeper than their tag, and no indentation tabs or trailing whitespace remain.
  • format picks the language the way strip does.
  • On refusal format returns the source unchanged, true and a reason.
  • format refuses whenever the layout is ambiguous.
Ambiguous layout
an element opened in one section and closed in another
unbalanced markup
an unterminated tag
a delimiter change
  • Since santoku-lpeg 3.3.0, format only rewrites whitespace runs that already exist. It never adds or removes a gap between two tokens.
  • So <div><p>x</p></div> stays on one line, and an empty <template> stays empty.
  • A run beside a block element, including one at a <template>'s inner edge, becomes a line break.
  • A run that holds a line break is reindented, and any other run stays as written.
  • Inside a tag, a run with no line break shrinks to one space.
  • Since santoku-lpeg 3.4.1, a line break inside a tag, between attributes or inside a class or style value, stays where it is. The whitespace before it goes.
  • Each continuation line keeps its offset from the indentation of the line the tag starts on, so it moves with the tag.
  • Other attribute values stay exactly as written, line breaks and indentation included.
  • format refuses an HTML or XML source that holds a NUL byte.
  • opts.css, the stylesheet text the page loads, decides which elements stay block.
  • Without opts.css every element counts as inline, so format only reindents the line breaks already there.
  • format leaves pre, textarea and white-space:pre elements as written. It does the same for scripts that hold mustache tags and scripts that aren't JavaScript.
  • tokens(src, filename, opts) is the matching check. It returns the non-whitespace tokens, plus one " " for each whitespace run outside pre content, whatever its length.
  • tokens adds one "\n" for a run inside a tag that holds a line break.
  • Every output format returns has the same tokens as its source and the same non-whitespace bytes. It parses, and formats to itself.
  • format refuses when it can't return such an output.
  • coverage returns checked for HTML, XML, CSS, Lua and nginx files, .tk variants included. It returns ignored for any other file strip.coverage classifies, and unknown otherwise.
  • format_html, format_xml and format_css call one formatter directly.
  • Since santoku-lpeg 3.4.0, format_css(src, { tk = true }) reads each <% %> block as opaque text inside strings, values and url(). It refuses a block that spans lines.
  • format uses format_css with tk = true for .tk.css files.
  • Since santoku-lpeg 3.4.0, format_html, format_css, format_lua and format_nginx keep the SPDX header that toku license writes unchanged, trailing whitespace included.
  • format on those files keeps the header too. The formatters refuse with "formatting moved the license header" when the output loses it.
  • XML gets no header from toku license, so format_xml formats a comment there like any other.

Lua and .tk.lua since santoku-lpeg 3.3.0

format(src, "x.lua") reindents Lua from its block structure, 2 spaces per level. Line breaks stay where the author put them.

local fmt = require("santoku.lpeg.format")
local arr = require("santoku.array")
local src = arr.concat({
  "local function f(a,b)\n",
  "\tif a then\n",
  "return {a,b}   \n",
  "        end\n",
  "end\n\n\n",
  "return f\n",
})
local out, refused = fmt.format(src, "f.lua")
print("refused:", refused)
print(fmt.coverage("", "f.lua"), fmt.coverage("", "f.tk.lua"))
print(#fmt.tokens("g(f\n(x))", "f.lua"), #fmt.tokens("g(f(x))", "f.lua"))
print(fmt.format("local s = f\n(x)\n", "f.lua"))
print(fmt.format("if a then\n<% push(x) %>\nend\n<% pop() %>\n", "f.tk.lua"))
return out
Details
  • A level is a function, if, elseif, else, for, while, repeat or do body, a table constructor, or call arguments.
  • format replaces indentation tabs, removes trailing whitespace, collapses each run of blank lines to one, and ends the file with one newline.
  • A continuation line, and any line inside an if, for or while header, keeps its offset from the line its statement starts on.
  • format adds a space after a comma, around =, inside non-empty braces, and between function and ( in an anonymous function. It never removes one.
  • Strings, long strings and long comments keep their text.
  • A line comment or directive such as -- luacheck: loses only its trailing whitespace.
  • In a .tk.lua file, a <% return ... %> block reads as a statement where Lua expects one, and as a name where an expression goes.
  • A line that holds only a push(), pop() or other code-only block keeps its indentation.
  • format refuses source that loadstring rejects, including f\n(x).
  • format refuses a .tk.lua file whose template blocks hide the Lua structure.
Refused .tk.lua layout
a push() region that crosses a Lua block
a value joined to a name
a value where neither a statement nor an expression fits, such as after a table field with no comma
a code-only block that shares a line with Lua code or sits inside an expression
  • tokens(src, "x.lua") returns the code tokens without whitespace, every literal and comment, and a "\n" token before a ( that starts a new line.
  • So a join of f\n(x) into f(x) changes the tokens.
  • Every output format returns has the same tokens as its source and the same non-whitespace bytes. It parses, and formats to itself.
  • format_lua(src, { tk = true }) calls the formatter directly.

nginx config since santoku-lpeg 3.4.0

format_nginx(src, opts) reindents nginx config from its blocks, and each block brace adds 2 spaces. format picks it for a .conf file that it recognizes as nginx config.

local fmt = require("santoku.lpeg.format")
local arr = require("santoku.array")
local src = arr.concat({
  "http {\n",
  "\tgzip on; gzip_vary on;   \n",
  "server {\n",
  "listen {{port}};\n",
  "location / {\n",
  "content_by_lua_block {\n",
  "local n = 1\n",
  "if n then\n",
  "ngx.say(n)\n",
  "end\n",
  "}\n",
  "}\n",
  "}\n",
  "}\n",
})
local out, refused = fmt.format(src, "nginx.conf")
print("refused:", refused)
print(fmt.coverage("", "nginx.conf"), fmt.coverage("http {\n}\n", "site.conf"), fmt.coverage("a=1\n", "x.conf"))
print(fmt.format("http {\n  gzip on\n}\n", "nginx.conf"))
print(fmt.format_nginx("listen <% return port %>;\n", { tk = true }))
return out
Details
  • format picks format_nginx for a .conf file whose name holds nginx, or whose path has a directory named nginx.
  • format also picks it for a .conf file with a line that opens an events, http or stream block, or an upstream or location block.
  • coverage returns checked for those files, and ignored for any other .conf.
  • Indentation tabs, trailing whitespace and leading blank lines go. Each run of blank lines collapses to one, and the file ends with one newline.
  • A whitespace run between two directives of a multi-line block becomes a line break.
  • A one-line block, and directives with no run between them, stay as written.
  • A continuation line keeps its offset from the line its directive starts on.
  • A comment keeps its text at its line's indent, and a trailing comment stays on its line.
  • Quoted strings, ${var}, escapes and a } inside a word stay as written.
  • A multi-line *_by_lua_block body is reindented from its Lua structure, as format_lua indents it.
  • A one-line Lua body, or one that holds mustache or template tags, stays as written.
  • Mustache section and partial tags take their block's indent without a new level. Tags inside a directive count as part of its words.
  • In a .tk.conf file, or with opts.tk, a push() or pop() line takes its block's indent the same way.
  • There a <% return ... %> value can sit inside a word, and a multi-line block stays as written.
format refuses
an unclosed or stray brace
a directive with no ;
a stray ; or {
a quoted string joined to a word
an unterminated string or mustache tag
a delimiter change
a mustache section or push() region that crosses a block or a directive
a Lua body that doesn't parse or never closes
a carriage return
  • tokens counts each whitespace run as one " " token.
  • Inside a Lua body each gap between Lua tokens becomes "\n" when it holds a line break, and " " otherwise.
  • So a reindent keeps the tokens, and a join of f\n(x) changes them.