Files
ProcessControl/_extensions/notes/si-mathjax.lua
T
2026-09-25 13:33:30 +02:00

273 lines
8.5 KiB
Lua

--[[
si-mathjax.lua
----------------------------------------------------------------------
Quarto/Pandoc filter: translates a practical subset of siunitx syntax
(\SI, \si, \num, \ang) into plain LaTeX that MathJax can render natively.
- HTML output : \SI{9.8}{\metre\per\square\second} -> 9.8\,\mathrm{m}\,\mathrm{s}^{-2}
- PDF/LaTeX : left completely untouched (real siunitx package handles it)
Supports:
* macro-based units : \kilo\gram\per\cubic\metre , \newton\per\square\metre
* compact-string units: kg.m.s^{-1} , N/m^2 , kg/m^3
* \num{1.5e-3} / \num{6.022e23} -> scientific notation
* \ang{45} / \ang{45;30;15} -> degrees / DMS
* optional [options] blocks after \SI / \si (ignored, just skipped)
* works both inside math ($...$, $$...$$) and inside raw LaTeX text
Add more units/prefixes to the tables below as your notes need them.
Turn it off when MathJax itself loads a siunitx extension (e.g. siunitx-pcc
in include-in-header), so that extension sees the original commands:
siunitx-html: mathjax # default: filter
]]
-- ============ unit tables (extend as needed) ============
local prefixes = {
yotta="Y", zetta="Z", exa="E", peta="P", tera="T", giga="G", mega="M", kilo="k",
hecto="h", deca="da", deka="da", deci="d", centi="c", milli="m", micro="\\mu ",
nano="n", pico="p", femto="f", atto="a", zepto="z", yocto="y",
}
local baseunits = {
metre="m", meter="m", gram="g", second="s", ampere="A", kelvin="K", mole="mol", candela="cd",
hertz="Hz", newton="N", pascal="Pa", joule="J", watt="W", coulomb="C", volt="V", farad="F",
ohm="\\Omega ", siemens="S", weber="Wb", tesla="T", henry="H",
degreeCelsius="{}^{\\circ}C", lumen="lm", lux="lx", becquerel="Bq", gray="Gy", sievert="Sv",
katal="kat", radian="rad", steradian="sr", percent="\\%", degree="{}^{\\circ}",
litre="L", liter="L", minute="min", hour="h", day="d", year="yr",
electronvolt="eV", dalton="u", astronomicalunit="au", bar="bar", bel="B", decibel="dB",
angstrom="\\AA ", are="a", hectare="ha", tonne="t", knot="kn",
}
-- ============ small helpers ============
local function extract_braces(s, i)
local depth = 0
for j = i, #s do
local c = s:sub(j, j)
if c == "{" then depth = depth + 1
elseif c == "}" then
depth = depth - 1
if depth == 0 then return s:sub(i + 1, j - 1), j end
end
end
return nil, i
end
local function skip_optional_brackets(s, i)
-- skips a siunitx-style [options] block if present, returns new index
if s:sub(i, i) == "[" then
local j = s:find("]", i, true)
if j then return j + 1 end
end
return i
end
local function split(s, sep)
local out = {}
for piece in (s .. sep):gmatch("([^" .. sep .. "]*)" .. sep) do
table.insert(out, piece)
end
return out
end
local function trim(s) return s:match("^%s*(.-)%s*$") end
-- ============ \num{} ============
local function format_num(val)
local mantissa, exp = val:match("^([%-%+]?[%d%.]+)[eE]([%-%+]?%d+)$")
if mantissa then
if mantissa == "1" then return "10^{" .. exp .. "}" end
return mantissa .. " \\times 10^{" .. exp .. "}"
end
return val
end
-- ============ \ang{} ============
local function format_ang(val)
local parts = split(val, ";")
if #parts == 1 then
return parts[1] .. "^{\\circ}"
elseif #parts == 2 then
return parts[1] .. "^{\\circ}" .. parts[2] .. "'"
else
return parts[1] .. "^{\\circ}" .. parts[2] .. "'" .. parts[3] .. "''"
end
end
-- ============ macro-based unit parsing: \kilo\gram\per\cubic\metre ============
local function parse_unit_macros(s)
local tokens = {}
local sign = 1
local pendingPrefix = ""
local pendingPower = 1
local i = 1
while i <= #s do
if s:sub(i, i) == "\\" then
local name = s:sub(i + 1):match("^(%a+)")
if not name then
i = i + 1
else
local afterpos = i + 1 + #name
if name == "per" then
sign = -sign
elseif name == "square" then
pendingPower = 2
elseif name == "cubic" then
pendingPower = 3
elseif name == "raiseto" or name == "tothe" then
if s:sub(afterpos, afterpos) == "{" then
local n, endpos = extract_braces(s, afterpos)
pendingPower = tonumber(n) or 1
afterpos = endpos + 1
end
elseif prefixes[name] then
pendingPrefix = pendingPrefix .. prefixes[name]
elseif baseunits[name] then
table.insert(tokens, { sym = pendingPrefix .. baseunits[name], exp = pendingPower * sign })
pendingPrefix = ""
pendingPower = 1
else
table.insert(tokens, { sym = pendingPrefix .. name, exp = pendingPower * sign })
pendingPrefix = ""
pendingPower = 1
end
i = afterpos
end
else
i = i + 1
end
end
return tokens
end
-- ============ compact-string unit parsing: kg.m.s^{-1} | m/s^2 | N.m^-2 ============
local function parse_unit_compact(s)
s = trim(s)
local num, den = s, nil
local slashpos = s:find("/")
if slashpos then
num = s:sub(1, slashpos - 1)
den = s:sub(slashpos + 1)
end
local function tokenize_group(group, signMul)
local out = {}
if not group or trim(group) == "" then return out end
group = group:gsub("%s+", ".")
for tok in (group .. "."):gmatch("([^%.]*)%.") do
if trim(tok) ~= "" then
local sym, exp = tok:match("^([%a%%°]+)%^?%{?(%-?%d*)%}?$")
if not sym then sym = tok exp = "" end
exp = (exp ~= "" and tonumber(exp)) or 1
table.insert(out, { sym = sym, exp = exp * signMul })
end
end
return out
end
local tokens = tokenize_group(num, 1)
for _, t in ipairs(tokenize_group(den, -1)) do table.insert(tokens, t) end
return tokens
end
local function format_unit(unit)
unit = trim(unit)
local tokens = unit:find("\\") and parse_unit_macros(unit) or parse_unit_compact(unit)
local parts = {}
for _, t in ipairs(tokens) do
local piece = "\\mathrm{" .. t.sym .. "}"
if t.exp ~= 1 then piece = piece .. "^{" .. t.exp .. "}" end
table.insert(parts, piece)
end
return table.concat(parts, "\\,")
end
-- ============ top-level scanner: replaces \SI \si \num \ang in a string ============
local COMMANDS = { "SI", "si", "numlist", "num", "ang" }
local function process(s)
local out = {}
local i = 1
while i <= #s do
local matched = false
for _, cmd in ipairs(COMMANDS) do
local pat = "\\" .. cmd
if s:sub(i, i + #pat - 1) == pat then
local nextc = s:sub(i + #pat, i + #pat)
if not nextc:match("%a") then
local pos = skip_optional_brackets(s, i + #pat)
if s:sub(pos, pos) == "{" then
local arg1, end1 = extract_braces(s, pos)
if arg1 then
if cmd == "SI" and s:sub(end1 + 1, end1 + 1) == "{" then
local arg2, end2 = extract_braces(s, end1 + 1)
table.insert(out, format_num(arg1) .. "\\," .. format_unit(arg2))
i = end2 + 1
matched = true
elseif cmd == "si" then
table.insert(out, format_unit(arg1))
i = end1 + 1
matched = true
elseif cmd == "num" or cmd == "numlist" then
table.insert(out, format_num(arg1))
i = end1 + 1
matched = true
elseif cmd == "ang" then
table.insert(out, format_ang(arg1))
i = end1 + 1
matched = true
end
end
end
end
end
if matched then break end
end
if not matched then
table.insert(out, s:sub(i, i))
i = i + 1
end
end
return table.concat(out)
end
-- ============ Pandoc hooks (HTML output only) ============
local is_html = FORMAT and FORMAT:match("html")
if not is_html then
-- PDF/LaTeX: real siunitx handles this, don't touch anything.
return {}
end
local enabled = true
return {
{
Meta = function(meta)
local mode = meta["siunitx-html"]
enabled = mode == nil or pandoc.utils.stringify(mode) ~= "mathjax"
end,
},
{
Math = function(el)
if not enabled then return nil end
el.text = process(el.text)
return el
end,
RawInline = function(el)
if enabled and (el.format == "tex" or el.format == "latex") then
el.text = process(el.text)
return el
end
end,
RawBlock = function(el)
if enabled and (el.format == "tex" or el.format == "latex") then
el.text = process(el.text)
return el
end
end,
},
}