Added course's notes

This commit is contained in:
MatsuneMikuroi committed 2026-09-25 13:33:30 +02:00
1 parent e07993262c
commit dcd2c072ae
191 files changed
+42866 -12

No files matched your search

+21
View File
@@ -0,0 +1,21 @@
5450bea48cd978a098105317ad733839 README.md
c7a6d67f7241268c6ba80e59824b7720 _extension.yml
40495613a91f62b4caa736a8bebeafe0 calc-notes.css
3754c29ead80b6c334397953e0636be4 calc-notes.js
4488fd02675637ec10179a4e96aaa558 calc-notes.lua
9460f3985b27b3107182599992985adf exo.css
1b1c35a5488c4e695a34b1f9efaeab4f exo.js
0bb15846fbb2bc9be2bde88d77698de8 exo.lua
62e03d6d5bd4f62830d71eadb66aa5ed fenced-divs.lua
8f938997710ad5d77e5d378735db451d glossary.css
6144abf4ad62088ab51409542e5f28e1 glossary.js
3dd15747646f60632313c8a1cacf7fe9 glossary.lua
2aa159cbe6bfe1ee35e18d4290d67425 handin.sh
691f5e66397d855e951c37a953701913 i18n.lua
061f762946d63ea672d4f989f762baf7 latex-tables.css
bab632a49553476bc5275b9c583f457e latex-tables.lua
6242f20acbe379c1da37d4b698de317e quiz.css
79e94885bf370abe27eeb6df81666946 quiz.js
1695d57dcb6deb45f4fb2303dee6aa09 quiz.lua
2b8ca7ff531d30903bc41240e8b77691 si-mathjax.lua
d32141259df2ce229400779c2ed284d9 sync.sh
+125
View File
@@ -0,0 +1,125 @@
# notes — Quarto extension for course notes
The same copy lives in every course (`<course>/_extensions/notes/`). Each filter
documents its syntax in the comment at its top; this page is the overview.
| File | What it does |
|---|---|
| `calc-notes.lua` | `\begin{calc}` / `calc*` derivations with `\note{}` / `\mnote{}`; label with `$$ … $$ {#eq-x}` |
| `exo.lua` | `::::{.exo}` exercises with `.hint` and `.solution` placed where written; hand-in mode |
| `quiz.lua` | `::::{.quiz}` tick-box self-checks with a **Check** button and per-option `.why` |
| `glossary.lua` | `.gls-def`, `\gls{key}`, `[term]{.gls}`, `::: {.glossary}`; resolves across chapters |
| `latex-tables.lua` | `tabular` environments rendered as HTML tables |
| `i18n.lua` | one source, several languages: `::: {.de}`, `[…]{.fr}`, `@tr{key}` |
| `si-mathjax.lua` | `\SI`, `\si`, `\num`, `\ang` in HTML (PDF uses siunitx) |
| `fenced-divs.lua` | repairs `:::` divs indented deeper than pandoc accepts (in numbered parts) |
## Options (in `_quarto.yml`)
```yaml
notecolor: "#B45309" # accent colour of notes, exercises, hints
exo:
pdf-solutions: inline # PDF: solutions in place (default: end of chapter)
label: "Exercice" # labels follow `lang` (en/fr/de); override any of
hint: "Indice" # label, hint, solution, solutions, part, page
quiz:
pdf-answers: inline # PDF: answers under the quiz (default: end of chapter)
label: "Quiz" # labels follow `lang` (en/fr/de); override any of
question: "Question" # label, question, answers, answer, check, reset,
check: "Vérifier" # right, wrong, score, true, false, hint, page
siunitx-html: mathjax # leave \SI & co. to a MathJax siunitx extension
glossary-page: glossary.html
glossary-back: "→ definition in context" # follows `lang` (en/fr/de) by default
```
## Exercises
```markdown
::::{.exo title="Stefan-Boltzmann law"}
Statement.
1. First part.
:::{.hint}
A hint for this part.
:::
:::{.solution}
Solution of part 1.
:::
2. Second part.
:::{.solution}
Solution of part 2.
:::
::::
```
Each solution is labelled with its part ("Solution (Part 2)"). Override with
`:::{.solution part="b"}`. Empty solutions (placeholders) are not shown.
## Quizzes
```markdown
::::{.quiz title="Landau notation"}
::: {.question}
Decide which statements are true.
- [x] $n + 2 = o(n^2)$
- [ ] $n = \mathcal{O}(\log^2 n)$
:::{.why}
$n$ eventually outgrows every power of $\log n$.
:::
:::
::::
```
`- [x]` is a true statement, `- [ ]` a false one. A `.why` inside an option
explains that option; a `.why` written directly in the question explains the
question as a whole. Both are shown only to a reader who got it wrong.
A quiz holds any number of `::: {.question}` divs (a quiz with none is read as
a single question). Numbering is chapter.n, as for exercises.
In HTML the options are real checkboxes and one **Check** button at the end of
the quiz marks every option, reveals the explanations for the mistakes and
scores the quiz; **Reset** clears it. A question counts as correct only when
*all* of its options are in the right state — the exam's multiple-true-false
rule.
In the PDF the boxes are empty, to tick with a pen, and the answers are
printed at the end of the chapter with a page reference back to the quiz
(`quiz: pdf-answers: inline` keeps them in place).
Correct answers are part of the built HTML, as solutions are: the quiz is a
self-check, not an assessment.
## Tools
**Hand in solutions.** Renders only the chosen exercises to `_handin/`, and
lists each one with any empty solution:
```bash
_extensions/notes/handin.sh 1.3 1.5 --subtitle "Series 2"
_extensions/notes/handin.sh 2 --no-statement # all of chapter 2, solutions only
_extensions/notes/handin.sh 1.2 --profile fr # a language of a multilingual book
_extensions/notes/handin.sh --help
```
**Keep every course on the same version.** After changing the extension in
one course, push it to all the others:
```bash
_extensions/notes/sync.sh --dry-run # what would change
_extensions/notes/sync.sh
```
A copy that was edited in place (or has a higher `version:`) is skipped with a
diff, so nothing is overwritten silently. Bump `version:` in `_extension.yml`
when you change something.
+29
View File
@@ -0,0 +1,29 @@
title: notes
author: Matsune
version: 2.3.0
quarto-required: ">=1.4.0"
contributes:
filters:
# pre-ast: before Quarto reads the document into its own AST, in this order
# - fenced-divs: rebuild ::: divs indented deeper than pandoc accepts
# - i18n: keep the active language, fill the term=/title= the others read
# - exo: place hints and solutions where they are written, before Quarto
# turns ::: {.solution} into its own proof block
# - quiz: build the tick boxes and the answer boxes, after fenced-divs
# has rebuilt the ::: {.why} divs nested in the options
- path: fenced-divs.lua
at: pre-ast
- path: i18n.lua
at: pre-ast
- path: exo.lua
at: pre-ast
- path: quiz.lua
at: pre-ast
- si-mathjax.lua
- latex-tables.lua
# post-quarto: after Quarto's crossref, so {#eq-...} labels on calc blocks
# resolve; glossary last, so \gls{} inside a calc block is linked too
- path: calc-notes.lua
at: post-quarto
- path: glossary.lua
at: post-quarto
+100
View File
@@ -0,0 +1,100 @@
/* calc-notes — HTML layout for the calc / calc* environments */
.calc {
display: grid;
/* lhs | rhs | notes | equation number */
grid-template-columns: max-content max-content minmax(8rem, 1fr) auto;
column-gap: 0.35rem;
row-gap: 0.6rem;
align-items: baseline;
margin: 1rem 0 1.4rem;
/* allow horizontal scrolling for very wide equations, but never show a
vertical bar (Firefox computes phantom vertical overflow otherwise) */
overflow-x: auto;
overflow-y: hidden;
padding-bottom: 0.4em; /* keep descenders clear of a horizontal bar */
}
.calc-row { display: contents; }
.calc-lhs { grid-column: 1; justify-self: end; }
.calc-rhs { grid-column: 2; justify-self: start; }
.calc-full { grid-column: 1 / 3; justify-self: start; }
/* ---- notes ------------------------------------------------------- */
.calc-notes {
grid-column: 3;
display: flex;
flex-wrap: wrap;
gap: 0.35rem 0.75rem;
align-items: baseline;
min-width: 0;
padding-left: 0.9rem;
}
.calc-note {
color: var(--calc-notecolor, #B45309);
font-size: 0.85em;
line-height: 1.35;
}
.calc-note > summary {
cursor: pointer;
list-style: none; /* remove the default triangle ... */
user-select: none;
opacity: 0.7;
font-style: italic;
}
.calc-note > summary::-webkit-details-marker { display: none; }
.calc-note > summary::before { content: "▸ "; font-style: normal; }
.calc-note[open] > summary::before { content: "▾ "; }
.calc-note > summary:hover { opacity: 1; }
.calc-note[open] {
background: color-mix(in srgb, var(--calc-notecolor, #B45309) 8%, transparent);
border-left: 2px solid var(--calc-notecolor, #B45309);
border-radius: 0.25rem;
padding: 0.15rem 0.45rem;
}
.calc-note-body { margin-top: 0.1rem; }
.calc-note-body p { margin: 0; }
/* \mnote: math note (no extra styling needed — body is typeset math) */
.calc-note-math .calc-note-body { padding: 0.1rem 0; }
/* ---- calc*: boxed final result ----------------------------------- */
.calc-box {
display: inline-block;
border: 1.5px solid currentColor;
border-radius: 0.3em;
padding: 0.3em 0.65em;
margin-top: 0.15em;
background: color-mix(in srgb, currentColor 4%, transparent);
}
/* ---- labelled blocks: equation number on the last line ----------- */
.calc-tag {
grid-column: 4;
justify-self: end;
padding-left: 1rem;
white-space: nowrap;
}
/* ---- printing: show notes unfolded, like the PDF ------------------ */
@media print {
.calc-note > summary { display: none; }
.calc-note[open] { background: none; border: none; padding: 0; }
}
/* small screens: notes drop under the equation line */
@media (max-width: 560px) {
.calc { grid-template-columns: max-content 1fr; }
.calc-notes { grid-column: 1 / 3; padding-left: 1.5rem; }
.calc-full { grid-column: 1 / 3; }
.calc-tag { grid-column: 1 / -1; }
}
+15
View File
@@ -0,0 +1,15 @@
// calc-notes — open every note before printing, restore afterwards
(function () {
window.addEventListener("beforeprint", function () {
document.querySelectorAll("details.calc-note").forEach(function (d) {
d.dataset.calcWasOpen = d.open ? "1" : "0";
d.open = true;
});
});
window.addEventListener("afterprint", function () {
document.querySelectorAll("details.calc-note").forEach(function (d) {
d.open = d.dataset.calcWasOpen === "1";
delete d.dataset.calcWasOpen;
});
});
})();
+406
View File
@@ -0,0 +1,406 @@
-- calc-notes.lua
-- "calc" / "calc*" derivation environments for Quarto (HTML + PDF).
--
-- \begin{calc}
-- f(x) &= (x+1)^2 \note{expand the square}\\
-- &= x^2 + 2x + 1 \mnote{$(a+b)^2 = a^2+2ab+b^2$}
-- \end{calc}
--
-- \note{...} -> inline note next to the line (foldable in HTML, plain colored text in PDF)
-- \mnote{...} -> math note: content is raw math, no $...$ needed; may contain
-- aligned lines like "f &= ma \\\\ &= m\\dot{v}"
-- calc* -> the last line is boxed to highlight the final result
--
-- Label a block to reference it like any equation (numbered on its last line):
-- $$
-- \begin{calc*} ... \end{calc*}
-- $$ {#eq-name} -> @eq-name
-- This filter runs after Quarto's crossref (`at: post-quarto` in _extension.yml),
-- so the label is already indexed and numbered. Hovering a reference to a calc*
-- block previews only its boxed result; a plain calc block previews in full.
--
-- Rename the environment here if you want something other than "calc":
local ENV = "calc"
local DEFAULT_COLOR = "#B45309" -- overridden by `notecolor:` in the document metadata
local notecolor = DEFAULT_COLOR
------------------------------------------------------------------ utils
local function trim(s)
return (s:gsub("^%s+", ""):gsub("%s+$", ""))
end
-- Works both under Quarto and plain pandoc.
local function fmt_is(name)
if quarto and quarto.doc and quarto.doc.is_format then
return quarto.doc.is_format(name)
end
return FORMAT ~= nil and FORMAT:match(name) ~= nil
end
-- Split `s` on every occurrence of the literal `sep` that sits at brace
-- depth 0 AND outside any nested environment, so neither "\\" inside
-- \text{...} nor the row/column separators of a nested \begin{pmatrix},
-- \begin{cases}, \begin{array}... ever split a calc line.
local function split_top(s, sep)
local parts, depth, env, i, start = {}, 0, 0, 1, 1
local n, k = #s, #sep
while i <= n do
if depth == 0 and env == 0 and s:sub(i, i + k - 1) == sep then
parts[#parts + 1] = s:sub(start, i - 1)
i = i + k
start = i
else
local c = s:sub(i, i)
if c == "\\" then
if s:find("^\\begin%s*{", i) then
env = env + 1
i = i + 6
elseif s:find("^\\end%s*{", i) then
env = math.max(0, env - 1)
i = i + 4
else
i = i + 2 -- skip escaped char / start of a control sequence
end
else
if c == "{" then
depth = depth + 1
elseif c == "}" then
depth = math.max(0, depth - 1)
end
i = i + 1
end
end
end
parts[#parts + 1] = s:sub(start)
return parts
end
-- s:sub(open_idx) == "{"; returns index of the matching "}".
local function find_balanced_close(s, open_idx)
local depth, i, n = 0, open_idx, #s
while i <= n do
local c = s:sub(i, i)
if c == "\\" then
i = i + 2
else
if c == "{" then
depth = depth + 1
elseif c == "}" then
depth = depth - 1
if depth == 0 then return i end
end
i = i + 1
end
end
return nil
end
-- Remove every \cmd{...} from `line`; return (cleaned line, {contents...}).
local function extract_cmd(line, cmd)
local found = {}
while true do
local st, brace = line:find("\\" .. cmd .. "%s*{")
if not st then break end
local close = find_balanced_close(line, brace)
if not close then break end
found[#found + 1] = line:sub(brace + 1, close - 1)
line = line:sub(1, st - 1) .. line:sub(close + 1)
end
return line, found
end
-- \mnote content is raw math; wrap multi-line/aligned content in aligned.
-- `opt` is the aligned position option ("[t]" for LaTeX, "" for MathJax).
local function wrap_mnote(txt, opt)
if #split_top(txt, "\\\\") > 1 or #split_top(txt, "&") > 1 then
return "\\begin{aligned}" .. opt .. " " .. txt .. " \\end{aligned}"
end
return txt
end
------------------------------------------------------------------ parse
local function parse_body(body)
local lines = {}
for _, raw in ipairs(split_top(body, "\\\\")) do
local l = trim(raw)
-- drop an optional spacing argument left over from "\\[1ex]"
l = trim(l:gsub("^%[[^%]]*%]", ""))
if l ~= "" then
local m, notes = extract_cmd(l, "note")
local m2, mnotes = extract_cmd(m, "mnote")
lines[#lines + 1] = { math = trim(m2), notes = notes, mnotes = mnotes }
end
end
return lines
end
------------------------------------------------------------------ HTML
-- Note contents are parsed as LaTeX so `$...$` inside a note renders as math.
local function note_inlines(txt)
local ok, doc = pcall(pandoc.read, txt, "latex")
if ok and doc and #doc.blocks > 0 then
return pandoc.utils.blocks_to_inlines(doc.blocks)
end
return pandoc.Inlines { pandoc.Str(txt) }
end
local function details_blocks(content, kind)
local b = pandoc.Blocks({})
b:insert(pandoc.RawBlock("html",
'<details class="calc-note calc-note-' .. kind .. '"><summary>note</summary><div class="calc-note-body">'))
if kind == "math" then
-- \mnote content is raw math — no $...$ needed
b:insert(pandoc.Plain {
pandoc.Math("InlineMath", wrap_mnote(content, ""))
})
else
b:insert(pandoc.Plain(note_inlines(content)))
end
b:insert(pandoc.RawBlock("html", "</div></details>"))
return b
end
local function math_div(cls, tex)
return pandoc.Div(
pandoc.Plain { pandoc.Math("InlineMath", "\\displaystyle " .. tex) },
pandoc.Attr("", { cls }))
end
local function html_env(lines, star, label)
local rows = pandoc.Blocks({})
for idx, L in ipairs(lines) do
local final = star and idx == #lines
local cells = pandoc.Blocks({})
if final then
-- boxed final result: render the whole line (alignment "&" stripped)
local flat = trim(table.concat(split_top(L.math, "&"), " "))
cells:insert(pandoc.Div(
pandoc.Plain {
pandoc.RawInline("html", '<span class="calc-box">'),
pandoc.Math("InlineMath", "\\displaystyle {} " .. flat),
pandoc.RawInline("html", "</span>"),
},
-- a labelled calc* carries its id here: hover previews show only the box
pandoc.Attr(label and label.id or "", { "calc-full" })))
else
local parts = split_top(L.math, "&")
if #parts == 1 then
cells:insert(math_div("calc-full", parts[1]))
else
local lhs = trim(parts[1])
local rhs = trim(table.concat(parts, " ", 2))
if lhs ~= "" then
cells:insert(math_div("calc-lhs", lhs))
end
-- leading "{}" keeps correct spacing for a line starting with "= ..."
cells:insert(math_div("calc-rhs", "{} " .. rhs))
end
end
local nb = pandoc.Blocks({})
for _, t in ipairs(L.notes) do nb:extend(details_blocks(t, "inline")) end
for _, t in ipairs(L.mnotes) do nb:extend(details_blocks(t, "math")) end
if #nb > 0 then
cells:insert(pandoc.Div(nb, pandoc.Attr("", { "calc-notes" })))
end
if label and label.tag and idx == #lines then
-- typeset like MathJax's own \tag so numbers match plain equations
cells:insert(pandoc.Div(pandoc.Plain { pandoc.Math("InlineMath", "(\\text{" .. label.tag .. "})") },
pandoc.Attr("", { "calc-tag" })))
end
local rowcls = { "calc-row" }
if final then rowcls[#rowcls + 1] = "calc-final" end
rows:insert(pandoc.Div(cells, pandoc.Attr("", rowcls)))
end
local cls = star and { "calc", "calc-star" } or { "calc" }
local env = pandoc.Div(rows, pandoc.Attr("", cls))
if label and not star then
-- hover previews show the inner HTML of the element with the id,
-- so wrap the grid to keep its layout in the preview
env = pandoc.Div(env, pandoc.Attr(label.id, { "calc-ref" }))
end
return pandoc.Blocks { env }
end
------------------------------------------------------------------ LaTeX
-- \Aboxed{lhs & rhs} splits at the first "&" it sees, even one inside a
-- pmatrix/cases/...: braces around each nested environment hide those.
local function brace_envs(s)
local out, env, i, last, start = {}, 0, 1, 1, nil
while i <= #s do
if s:find("^\\begin%s*{", i) then
if env == 0 then start = i end
env = env + 1
i = i + 6
elseif s:find("^\\end%s*{", i) then
env = math.max(0, env - 1)
local close = s:find("}", i, true)
if env == 0 and start ~= nil and close ~= nil then
out[#out + 1] = s:sub(last, start - 1) .. "{" .. s:sub(start, close) .. "}"
last, i, start = close + 1, close + 1, nil
else
i = i + 4
end
elseif s:sub(i, i) == "\\" then
i = i + 2
else
i = i + 1
end
end
out[#out + 1] = s:sub(last)
return table.concat(out)
end
local function latex_env(lines, star, label)
local out = {}
for idx, L in ipairs(lines) do
local seg = L.math
if star and idx == #lines then
if #split_top(seg, "&") > 1 then
seg = "\\Aboxed{" .. brace_envs(seg) .. "}" -- boxes across the alignment point (mathtools)
else
seg = "\\boxed{" .. seg .. "}"
end
end
for _, t in ipairs(L.notes) do
seg = seg .. " \\quad {\\color{notecolor}\\text{\\small " .. t .. "}}"
end
for _, t in ipairs(L.mnotes) do
-- math note: content is math already; \text{\small$..$} scales it down
seg = seg .. " \\quad {\\color{notecolor}\\text{\\small$"
.. wrap_mnote(t, "[t]") .. "$}}"
end
if label then
seg = seg .. (idx == #lines and (" \\label{" .. label.id .. "}") or " \\nonumber")
end
out[#out + 1] = " " .. seg
end
local env = label and "align" or "align*"
return pandoc.Blocks {
pandoc.RawBlock("latex",
"\\begin{" .. env .. "}\n" .. table.concat(out, " \\\\\n") .. "\n\\end{" .. env .. "}")
}
end
------------------------------------------------------------------ filter
-- `id`: label of an equation already processed by Quarto's crossref; in HTML
-- Quarto has appended its number to the math as \tag{n}.
local function transform(txt, id)
local label
if id then
local tag
txt = txt:gsub("%s*\\tag%s*(%b{})%s*$", function(b) tag = b:sub(2, -2); return "" end)
label = { id = id, tag = tag }
end
local star, body = txt:match(
"^%s*\\begin{" .. ENV .. "(%*?)}(.-)\\end{" .. ENV .. "%*?}%s*$")
if body == nil then return nil end
local lines = parse_body(body)
if #lines == 0 then return nil end
local isstar = (star == "*")
if fmt_is("latex") then
return latex_env(lines, isstar, label)
elseif fmt_is("html") then
return html_env(lines, isstar, label)
end
return nil
end
function RawBlock(el)
if el.format ~= "tex" and el.format ~= "latex" then return nil end
return transform(el.text)
end
-- also catch the env when it's wrapped in $$ ... $$
-- The math may share its paragraph with other text (a line touching the
-- fence, a trailing character, an inline "$$...$$" in a sentence). Split
-- the paragraph: text before/after stays as text, the env becomes blocks.
local function is_ws(it)
return it.t == "Space" or it.t == "SoftBreak" or it.t == "LineBreak"
or (it.t == "Str" and it.text:match("^%s*$") ~= nil)
end
local function flush(cur, out, ctor)
local only_ws = true
for _, it in ipairs(cur) do
if not is_ws(it) then only_ws = false; break end
end
if not only_ws then out:insert(ctor(cur)) end
end
local function is_eq_span(it)
return it and it.t == "Span" and it.identifier:match("^eq%-") ~= nil and #it.content == 1
end
local function block_with_math(el, ctor)
local out = pandoc.Blocks({})
local cur = pandoc.Inlines({})
local found = false
local items = el.content
local i = 1
while i <= #items do
local it = items[i]
local res, used = nil, 1
if it.t == "Math" and it.mathtype == "DisplayMath" then
res = transform(it.text)
elseif is_eq_span(it) and it.content[1].t == "Math" then
-- labelled equation, HTML: Span#eq-x [ Math "... \tag{n}" ]
res = transform(it.content[1].text, it.identifier)
elseif it.t == "RawInline" and it.text == "\\begin{equation}" and is_eq_span(items[i + 1])
and items[i + 1].content[1].t == "RawInline" and items[i + 2]
and items[i + 2].t == "RawInline" and items[i + 2].text == "\\end{equation}" then
-- labelled equation, LaTeX: \begin{equation} Span#eq-x [ RawInline ] \end{equation}
res = transform(items[i + 1].content[1].text, items[i + 1].identifier)
used = 3
end
if res ~= nil then
found = true
flush(cur, out, ctor)
cur = pandoc.Inlines({})
out:extend(res)
else
cur:insert(it)
used = 1
end
i = i + used
end
if not found then return nil end
flush(cur, out, ctor)
return out
end
function Para(el) return block_with_math(el, pandoc.Para) end
function Plain(el) return block_with_math(el, pandoc.Plain) end
function Meta(m)
if m.notecolor then
notecolor = pandoc.utils.stringify(m.notecolor)
end
if quarto == nil or quarto.doc == nil then return end -- plain pandoc: skip injection
if fmt_is("html") then
quarto.doc.add_html_dependency({
name = "calc-notes",
version = "1.0.0",
stylesheets = { "calc-notes.css" },
scripts = { "calc-notes.js" },
})
quarto.doc.include_text("in-header",
"<style>:root { --calc-notecolor: " .. notecolor .. "; }</style>")
elseif fmt_is("latex") then
quarto.doc.use_latex_package("mathtools") -- \Aboxed
quarto.doc.use_latex_package("xcolor")
local hex = notecolor:gsub("^#", "")
quarto.doc.include_text("in-header", table.concat({
"\\definecolor{notecolor}{HTML}{" .. hex .. "}",
}, "\n"))
end
end
+86
View File
@@ -0,0 +1,86 @@
/* exo — exercise cards, hint folds (sequential unlock), solution fold */
.exo {
margin: 1.2rem 0;
padding: 0.6rem 0.9rem;
border: 1px solid color-mix(in srgb, var(--calc-notecolor, #B45309) 35%, transparent);
border-left: 3px solid var(--calc-notecolor, #B45309);
border-radius: 0.35rem;
scroll-margin-top: 5rem;
}
/* keep wide content inside the card: display math (and tables/code) scroll
on their own rather than spilling past the border. overflow-y stays hidden
so Firefox doesn't add a phantom vertical bar, as in .calc */
.exo mjx-container[display="true"],
.exo .katex-display {
max-width: 100%;
overflow-x: auto;
overflow-y: hidden;
padding-bottom: 0.35em; /* keep descenders clear of a horizontal bar */
/* a centred overflowing box clips its left side out of reach, so centre
only while the formula fits (browsers without `safe` keep plain centring) */
display: flex;
justify-content: center;
justify-content: safe center;
}
.exo .math.display { display: block; max-width: 100%; }
.exo :is(pre, table) { max-width: 100%; overflow-x: auto; }
.exo img, .exo svg { max-width: 100%; }
.exo-head p { margin: 0 0 0.4rem; }
.exo-head strong { color: var(--calc-notecolor, #B45309); }
.exo details {
margin: 0.45rem 0;
border-radius: 0.3rem;
}
.exo details > summary {
cursor: pointer;
list-style: none;
user-select: none;
font-size: 0.9em;
font-weight: 600;
}
.exo details > summary::-webkit-details-marker { display: none; }
.exo details > summary::before { content: "▸ "; }
.exo details[open] > summary::before { content: "▾ "; }
/* hints: small highlight boxes */
.exo-hint {
background: color-mix(in srgb, var(--calc-notecolor, #B45309) 6%, transparent);
border: 1px solid color-mix(in srgb, var(--calc-notecolor, #B45309) 30%, transparent);
padding: 0.25rem 0.6rem;
}
.exo-hint > summary { color: var(--calc-notecolor, #B45309); }
/* locked hints: unlock one by one */
.exo-hint.exo-locked > summary {
cursor: not-allowed;
opacity: 0.45;
}
.exo-hint.exo-locked > summary::before { content: "🔒 "; }
/* solution: closed by default, visually separated */
.exo-sol {
border-top: 1px dashed color-mix(in srgb, var(--calc-notecolor, #B45309) 40%, transparent);
padding: 0.35rem 0.1rem 0.1rem;
scroll-margin-top: 5rem;
}
/* in a numbered part, the fold lines up with the part's text */
.exo li > details { margin-left: 0; }
/* hand-in extracts (handin.sh, html output) */
.exo-handin-sol, .exo-handin-hint {
margin: 0.6rem 0;
padding: 0.2rem 0 0.2rem 0.8rem;
border-left: 2px solid var(--calc-notecolor, #B45309);
}
.exo-fold-body { margin-top: 0.3rem; }
.exo-fold-body > p:first-child { margin-top: 0; }
.exo-fold-body > p:last-child { margin-bottom: 0; }
@media print {
.exo details > summary::before { content: ""; }
.exo-hint.exo-locked > summary { opacity: 1; cursor: default; }
}
+39
View File
@@ -0,0 +1,39 @@
// exo — hints unlock one by one within a part; everything unfolds for printing
(function () {
// block opening a locked hint
document.addEventListener("click", function (e) {
var s = e.target.closest ? e.target.closest("details.exo-hint.exo-locked > summary") : null;
if (s) e.preventDefault();
});
// opening hint n of a part unlocks hint n+1 of the same part, wherever it
// sits in the exercise (toggle doesn't bubble: use capture)
document.addEventListener("toggle", function (e) {
var d = e.target;
if (!d.classList || !d.classList.contains("exo-hint") || !d.open) return;
var chain = d.getAttribute("data-exo-chain");
var n = parseInt(d.getAttribute("data-exo-hint"), 10);
if (!chain || isNaN(n)) return;
var hints = document.querySelectorAll("details.exo-hint[data-exo-chain]");
for (var i = 0; i < hints.length; i++) {
if (hints[i].getAttribute("data-exo-chain") === chain &&
parseInt(hints[i].getAttribute("data-exo-hint"), 10) === n + 1) {
hints[i].classList.remove("exo-locked");
}
}
}, true);
// print: open all hints/solutions, restore afterwards
window.addEventListener("beforeprint", function () {
document.querySelectorAll(".exo details").forEach(function (d) {
d.dataset.exoWasOpen = d.open ? "1" : "0";
d.open = true;
});
});
window.addEventListener("afterprint", function () {
document.querySelectorAll(".exo details").forEach(function (d) {
d.open = d.dataset.exoWasOpen === "1";
delete d.dataset.exoWasOpen;
});
});
})();
+596
View File
@@ -0,0 +1,596 @@
-- exo.lua — numbered exercise environments for Quarto (HTML + PDF)
--
-- :::: {.exo title="Stefan-Boltzmann law"}
-- Statement, figures, anything...
--
-- 1. First part.
--
-- ::: {.hint}
-- A hint for this part.
-- :::
--
-- ::: {.solution}
-- Solution of part 1.
-- :::
--
-- 2. Second part.
--
-- ::: {.solution}
-- Solution of part 2.
-- :::
-- ::::
--
-- Hints and solutions stay exactly where they are written: in a numbered
-- part, between two paragraphs of the statement, anywhere in the exercise.
-- (fenced-divs.lua makes the indented ::: fences above work.)
--
-- Numbering is chapter.n, n restarting in every chapter (1.1, 1.2, 2.1, ...);
-- the chapter is the book's chapter number. Outside a chapter it is just n.
--
-- Parts: when an exercise has several solutions, each is labelled with the
-- numbered item it sits in (or follows), "Solution (Part 2)", falling back to
-- 1, 2, 3... when the items don't tell them apart. Set it by hand with
-- ::: {.solution part="b"}.
--
-- HTML: hints are numbered folds. Within a part (hints up to the next
-- solution) they unlock one by one. A solution is a fold, closed by
-- default.
-- PDF: hints are small boxes. A solution leaves a link where it is written
-- ("Solution 1.3 (Part 2) -> p. 12") and is printed in a "Solutions"
-- section at the end of the chapter, linking back to the exercise and
-- to its page. `exo: pdf-solutions: inline` keeps
-- it in place instead.
-- A solution that is still empty (a placeholder) renders nothing.
--
-- Metadata (labels default to the document `lang`: en, fr or de):
-- exo:
-- pdf-solutions: inline # default: end (of the chapter)
-- label: "Exercice"
-- hint: "Indice"
-- solution: "Solution"
-- solutions: "Solutions"
-- part: "Partie"
-- page: "p."
--
-- Hand-in mode, used by handin.sh (flat keys, so `quarto render -M` can set
-- them): only the selected exercises are kept, each with its statement and
-- its solutions in place, ready to hand back.
-- exo-handin: "1.3 1.5" exercises; also "2" (a chapter),
-- "2.Light.qmd" (a file), "#my-id", "all"
-- exo-handin-statement: false solutions only
-- exo-handin-hints: true keep the hints
-- exo-handin-subtitle: "..." subtitle of the title page
--
-- Runs at pre-ast (see _extension.yml): hints and solutions are handled
-- before Quarto turns ::: {.solution} into its own proof block.
local LABELS = {
en = { label = "Exercise", hint = "Hint", solution = "Solution",
solutions = "Solutions", part = "Part", page = "p." },
fr = { label = "Exercice", hint = "Indice", solution = "Solution",
solutions = "Solutions", part = "Partie", page = "p." },
de = { label = "Aufgabe", hint = "Hinweis", solution = "Lösung",
solutions = "Lösungen", part = "Teil", page = "S." },
}
local labels = {}
local opts = {
pdf_solutions = "end",
handin = nil, -- selection, see parse_selection
statement = true,
hints = false,
subtitle = nil,
}
local function fmt_is(name)
if quarto and quarto.doc and quarto.doc.is_format then
return quarto.doc.is_format(name)
end
return FORMAT ~= nil and FORMAT:match(name) ~= nil
end
local function str(v)
if v == nil then return nil end
if type(v) == "boolean" then return tostring(v) end
return pandoc.utils.stringify(v)
end
local function bool(v, default)
local s = str(v)
if s == nil or s == "" then return default end
s = s:lower()
return s == "true" or s == "yes" or s == "1"
end
local function esc_html(s)
return (s:gsub("&", "&amp;"):gsub("<", "&lt;"):gsub(">", "&gt;"):gsub('"', "&quot;"))
end
local function basename(path)
return path and path:match("([^/\\]+)$") or nil
end
------------------------------------------------------------------ meta
local function parse_selection(s)
local sel = { all = false, nums = {}, chapters = {}, files = {}, ids = {}, tokens = {} }
for tok in s:gmatch("[^,%s]+") do
sel.tokens[#sel.tokens + 1] = tok
if tok == "all" then
sel.all = true
elseif tok:sub(1, 1) == "#" then
sel.ids[tok:sub(2)] = tok
elseif tok:match("%.q?md$") then
sel.files[basename(tok)] = tok
elseif tok:match("^%w+%.%d+$") then
sel.nums[tok] = tok
elseif tok:match("^%w+$") then
sel.chapters[tok] = tok
else
io.stderr:write("[exo] hand-in: don't know what '" .. tok .. "' selects"
.. " (use 1.3, 2, 2.File.qmd, #id or all)\n")
end
end
return sel
end
local function read_meta(meta)
local lang = (str(meta.lang) or "en"):lower():gsub("[_-].*$", "")
for k, v in pairs(LABELS[lang] or LABELS.en) do labels[k] = v end
if type(meta.exo) == "table" then
for k in pairs(labels) do
if meta.exo[k] ~= nil then labels[k] = str(meta.exo[k]) end
end
if meta.exo["pdf-solutions"] ~= nil then
opts.pdf_solutions = str(meta.exo["pdf-solutions"])
end
end
local handin = str(meta["exo-handin"])
if handin ~= nil and handin ~= "" then
opts.handin = parse_selection(handin)
opts.statement = bool(meta["exo-handin-statement"], true)
opts.hints = bool(meta["exo-handin-hints"], false)
opts.subtitle = str(meta["exo-handin-subtitle"])
end
if quarto ~= nil and quarto.doc ~= nil then
if fmt_is("html") then
quarto.doc.add_html_dependency({
name = "calc-exo",
version = "2.0.0",
stylesheets = { "exo.css" },
scripts = { "exo.js" },
})
elseif fmt_is("latex") then
-- same options as Quarto's callouts, so the two never clash
quarto.doc.use_latex_package("tcolorbox", "skins,breakable")
end
end
return meta
end
------------------------------------------------------------------ traversal
local function is_hint(b)
return b.t == "Div" and b.classes:includes("hint")
end
local function is_solution(b)
return b.t == "Div" and (b.classes:includes("solution") or b.classes:includes("sol"))
end
-- Rebuild `blocks` in document order, replacing every hint / solution div,
-- at any depth, by what fns.hint / fns.solution return. ctx.part follows the
-- exercise's own numbered items: inside item n, and after it, it is "n".
local function map_blocks(blocks, fns, ctx, depth)
local out = pandoc.Blocks({})
for _, b in ipairs(blocks) do
if is_hint(b) then
out:extend(fns.hint(b))
elseif is_solution(b) then
out:extend(fns.solution(b))
elseif b.t == "OrderedList" or b.t == "BulletList" then
local items = {}
for i, item in ipairs(b.content) do
if depth == 0 and b.t == "OrderedList" then
ctx.part = tostring(b.start + i - 1)
end
items[i] = map_blocks(item, fns, ctx, depth + 1)
end
b.content = items
out:insert(b)
elseif b.t == "Div" or b.t == "BlockQuote" then
b.content = map_blocks(b.content, fns, ctx, depth + 1)
out:insert(b)
elseif b.t == "DefinitionList" then
for _, item in ipairs(b.content) do
for j, def in ipairs(item[2]) do
item[2][j] = map_blocks(def, fns, ctx, depth + 1)
end
end
out:insert(b)
else
out:insert(b)
end
end
return out
end
-- one entry per solution: explicit part=, part inferred from the items, empty?
local function scan_solutions(el)
local sols, ctx = {}, {}
local keep = function(div) return { div } end
map_blocks(el.content:clone(), {
hint = keep,
solution = function(div)
sols[#sols + 1] = {
explicit = div.attributes.part,
inferred = ctx.part,
empty = #div.content == 0,
}
return { div }
end,
}, ctx, 0)
return sols
end
-- the part shown for each solution (nil: a lone solution needs none)
local function part_labels(sols)
local parts = {}
if #sols < 2 then
for i, s in ipairs(sols) do parts[i] = s.explicit end
return parts
end
local seen, inferred_ok = {}, true
for _, s in ipairs(sols) do
local p = s.explicit or s.inferred
if p == nil or seen[p] then inferred_ok = false; break end
seen[p] = true
end
for i, s in ipairs(sols) do
parts[i] = s.explicit or (inferred_ok and s.inferred) or tostring(i)
end
return parts
end
------------------------------------------------------------------ pieces
-- an en space; LaTeX fonts often lack the U+2002 glyph, so use \enspace there
local function enspace()
if fmt_is("latex") then return pandoc.RawInline("latex", "\\enspace{}") end
return pandoc.Str("\u{2002}")
end
local function head_inlines(num, title)
local ins = pandoc.Inlines({ pandoc.Str(labels.label .. " " .. num) })
if title ~= nil then
ins:extend({ enspace(), pandoc.Str("—"), enspace() })
ins:insert(pandoc.Emph(pandoc.Inlines({ pandoc.Str(title) })))
end
return ins
end
-- "Solution (Part 2)"; with num: "Solution 1.3 (Part 2)"
local function sol_title(num, part)
local s = labels.solution
if num ~= nil then s = s .. " " .. num end
if part ~= nil then s = s .. " (" .. labels.part .. " " .. part .. ")" end
return s
end
local function sol_id(num, part)
local id = "exo-" .. num .. "-sol"
if part ~= nil then id = id .. "-" .. part:gsub("[^%w]", "") end
return id
end
local function latex_hint_box(title, content)
local b = pandoc.Blocks({ pandoc.RawBlock("latex",
"\\begin{tcolorbox}[colback=notecolor!5!white,colframe=notecolor!40!white,"
.. "colbacktitle=notecolor!15!white,coltitle=black,fonttitle=\\small\\bfseries,"
.. "title={" .. title .. "},left=1.5mm,right=1.5mm,top=1mm,bottom=1mm]") })
b:extend(content)
b:insert(pandoc.RawBlock("latex", "\\end{tcolorbox}"))
return b
end
-- a solution printed in place: a titled box with a rule on the left
local function latex_sol_box(title, content)
local b = pandoc.Blocks({ pandoc.RawBlock("latex",
"\\begin{tcolorbox}[enhanced jigsaw,breakable,frame hidden,colback=white,"
.. "borderline west={1.5pt}{0pt}{notecolor!70!white},arc=0pt,outer arc=0pt,"
.. "colbacktitle=white,coltitle=notecolor!85!black,fonttitle=\\small\\bfseries,"
.. "titlerule=0pt,toptitle=0.5mm,bottomtitle=0mm,"
.. "title={" .. title .. "},left=2mm,right=1mm,top=0.5mm,bottom=1mm]") })
b:extend(content)
b:insert(pandoc.RawBlock("latex", "\\end{tcolorbox}"))
return b
end
local function html_fold(cls, attrs, summary, content)
local b = pandoc.Blocks({ pandoc.RawBlock("html",
'<details class="' .. cls .. '"' .. attrs .. '><summary>' .. esc_html(summary)
.. '</summary><div class="exo-fold-body">') })
b:extend(content)
b:insert(pandoc.RawBlock("html", "</div></details>"))
return b
end
-- a labelled block for formats without boxes or folds (docx, ...)
local function plain_labelled(cls, title, content)
local b = pandoc.Blocks({ pandoc.Para({ pandoc.Strong({ pandoc.Str(title .. ".") }) }) })
b:extend(content)
return pandoc.Blocks({ pandoc.Div(b, pandoc.Attr("", { cls })) })
end
------------------------------------------------------------------ notes
-- state shared by the hint/solution handlers of one exercise
local function new_state(el)
local sols = scan_solutions(el)
return { parts = part_labels(sols), sols = sols, sol = 0, chain = 1, hint = 0 }
end
local function next_hint(st)
st.hint = st.hint + 1
return st.hint
end
local function next_solution(st)
st.sol = st.sol + 1
st.chain, st.hint = st.chain + 1, 0 -- a solution closes its part's hints
return st.parts[st.sol], st.sols[st.sol].empty
end
local function html_exo(el, num, title)
local st = new_state(el)
local fns = {
hint = function(div)
local i = next_hint(st)
return html_fold("exo-hint" .. (i > 1 and " exo-locked" or ""),
' data-exo-chain="' .. esc_html(num .. "-" .. st.chain)
.. '" data-exo-hint="' .. i .. '"',
labels.hint .. " " .. i, div.content)
end,
solution = function(div)
local part, empty = next_solution(st)
if empty then return {} end
return html_fold("exo-sol", ' id="' .. esc_html(sol_id(num, part)) .. '"',
sol_title(nil, part), div.content)
end,
}
local blocks = pandoc.Blocks({ pandoc.Div(
pandoc.Blocks({ pandoc.Para({ pandoc.Strong(head_inlines(num, title)) }) }),
pandoc.Attr("", { "exo-head" })) })
blocks:extend(map_blocks(el.content, fns, {}, 0))
return pandoc.Blocks({ pandoc.Div(blocks, pandoc.Attr("exo-" .. num, { "exo" })) })
end
-- `pending` collects the solutions printed at the end of the chapter
local function latex_exo(el, num, title, pending)
local st = new_state(el)
local fns = {
hint = function(div)
return latex_hint_box(labels.hint .. " " .. next_hint(st), div.content)
end,
solution = function(div)
local part, empty = next_solution(st)
if empty then return {} end
if opts.pdf_solutions == "inline" then
return latex_sol_box(sol_title(nil, part), div.content)
end
local id = sol_id(num, part)
local collected = pandoc.Blocks({ pandoc.Para({
pandoc.RawInline("latex", "\\hypertarget{" .. id .. "}{}\\label{" .. id .. "}"),
pandoc.Strong({ pandoc.Str(sol_title(num, part)) }),
enspace(),
pandoc.RawInline("latex", "{\\small\\hyperlink{exo-" .. num .. "}{$\\leftarrow$ "
.. labels.label .. " " .. num .. ", " .. labels.page
.. "\\,\\pageref{exo-" .. num .. "}}}"),
}) })
collected:extend(div.content)
pending[#pending + 1] = collected
return { pandoc.Para({ pandoc.RawInline("latex",
"{\\small\\itshape\\hyperlink{" .. id .. "}{" .. sol_title(num, part)
.. " $\\to$ " .. labels.page .. "\\,\\pageref{" .. id .. "}}}") }) }
end,
}
local blocks = pandoc.Blocks({ pandoc.Para({
-- \\label so the collected solution can print the exercise's page
pandoc.RawInline("latex", "\\hypertarget{exo-" .. num .. "}{}\\label{exo-" .. num .. "}"),
pandoc.Strong(head_inlines(num, title)),
}) })
blocks:extend(map_blocks(el.content, fns, {}, 0))
return blocks
end
------------------------------------------------------------------ hand-in
local function handin_box(kind, title, content)
if fmt_is("latex") then
return kind == "hint" and latex_hint_box(title, content) or latex_sol_box(title, content)
end
return plain_labelled("exo-handin-" .. kind, title, content)
end
-- returns blocks + a one-line report for the console
local function handin_exo(el, num, title)
local st = new_state(el)
local solutions = pandoc.Blocks({})
local fns = {
hint = function(div)
local i = next_hint(st)
if not opts.hints then return {} end
return handin_box("hint", labels.hint .. " " .. i, div.content)
end,
solution = function(div)
local part = next_solution(st)
local box = handin_box("sol", sol_title(nil, part), div.content)
if opts.statement then return box end
solutions:extend(box)
return {}
end,
}
local blocks = pandoc.Blocks({ pandoc.Header(2, head_inlines(num, title),
pandoc.Attr("exo-" .. num, { "unnumbered", "unlisted", "exo-handin" })) })
local body = map_blocks(el.content, fns, {}, 0)
blocks:extend(opts.statement and body or solutions)
local report = labels.label .. " " .. num
if #st.sols == 0 then
report = report .. ": no solution"
else
local empty = {}
for i, s in ipairs(st.sols) do
if s.empty then empty[#empty + 1] = st.parts[i] or "" end
end
if #empty > 0 then
local which = table.concat(empty, ", ")
report = report .. ": EMPTY solution" .. (which ~= "" and (" (" .. labels.part .. " " .. which .. ")") or "")
else
report = report .. ": ok"
end
end
return blocks, report
end
------------------------------------------------------------------ walk
-- Quarto marks where each chapter file starts in a book's merged PDF source
local function file_marker(b)
local txt
if b.t == "RawBlock" and b.format == "html" then
txt = b.text
elseif b.t == "Para" and #b.content == 1 and b.content[1].t == "RawInline" then
txt = b.content[1].text
end
if txt == nil then return nil end
local enc = txt:match("^%s*<!%-%- quarto%-file%-metadata: ([%w%+/=]+) %-%->%s*$")
if enc == nil or quarto == nil or quarto.base64 == nil or quarto.json == nil then return nil end
local ok, data = pcall(function() return quarto.json.decode(quarto.base64.decode(enc)) end)
if ok and type(data) == "table" and data.bookItemFile ~= nil then return data end
return nil
end
local function chapter_label(n)
if type(n) == "number" then return tostring(math.floor(n)) end
if type(n) == "string" and n ~= "" then return n end
return nil
end
-- HTML books render one chapter per run: its number comes from the book
local function book_number_of_input(meta)
if quarto == nil or quarto.doc == nil or quarto.doc.input_file == nil then return nil end
if meta.book == nil or meta.book.render == nil then return nil end
local input = quarto.doc.input_file:gsub("\\", "/")
for _, item in ipairs(meta.book.render) do
local file = str(item.file)
if file ~= nil and (input == file or input:sub(-#file - 1) == "/" .. file) then
return item.number ~= nil and str(item.number) or nil
end
end
return nil
end
local function walk(doc)
local is_latex, is_html = fmt_is("latex"), fmt_is("html")
local sel = opts.handin
-- an HTML chapter arrives without its # title (Quarto made it the page
-- title): its number comes from the book. The merged PDF source has all
-- the titles, each after a marker carrying its number.
local next_number = book_number_of_input(doc.meta)
local chapter, chapter_n, cnt = next_number, tonumber(next_number) or 0, 0
local file = quarto and quarto.doc and basename(quarto.doc.input_file) or nil
local pending, reports, matched, nums = {}, {}, {}, {}
local out = pandoc.Blocks({})
local function flush()
if #pending == 0 then return end
out:insert(pandoc.Header(2, pandoc.Inlines({ pandoc.Str(labels.solutions) }),
pandoc.Attr("", { "unnumbered" })))
for _, s in ipairs(pending) do out:extend(s) end
pending = {}
end
local function selected(num, id)
local hit = false
for _, key in ipairs({ { sel.nums, num }, { sel.chapters, chapter }, { sel.files, file }, { sel.ids, id } }) do
local tok = key[2] ~= nil and key[1][key[2]] or nil
if tok ~= nil then matched[tok] = true; hit = true end
end
return sel.all or hit
end
for _, b in ipairs(doc.blocks) do
local marker = file_marker(b)
if marker ~= nil then
if is_latex then flush() end
file = basename(marker.bookItemFile)
next_number = chapter_label(marker.bookItemNumber)
chapter, cnt = nil, 0
out:insert(b)
elseif b.t == "Header" and b.level == 1 then
if is_latex then flush() end
if not b.classes:includes("unnumbered") then -- prefaces etc. don't count
if next_number ~= nil then
chapter = next_number
chapter_n = tonumber(next_number) or chapter_n
next_number = nil
else
chapter_n = chapter_n + 1
chapter = tostring(chapter_n)
end
cnt = 0
end
if sel == nil then out:insert(b) end
elseif b.t == "Div" and b.classes:includes("exo") then
cnt = cnt + 1
local num = chapter ~= nil and (chapter .. "." .. cnt) or tostring(cnt)
local title = b.attributes.title
if sel ~= nil then
if selected(num, b.identifier) then
local blocks, report = handin_exo(b, num, title)
out:extend(blocks)
reports[#reports + 1] = report
nums[#nums + 1] = num
end
elseif is_latex then
out:extend(latex_exo(b, num, title, pending))
elseif is_html then
out:extend(html_exo(b, num, title))
else
out:insert(b)
end
elseif sel == nil then
out:insert(b)
end
end
if is_latex then flush() end
if sel ~= nil then
for _, tok in ipairs(sel.tokens) do
if tok ~= "all" and not matched[tok] then
io.stderr:write("[exo] hand-in: nothing matches '" .. tok .. "'\n")
end
end
for _, r in ipairs(reports) do io.stderr:write("[exo] hand-in: " .. r .. "\n") end
if #reports == 0 then
io.stderr:write("[exo] hand-in: no exercise selected\n")
out:insert(pandoc.Para({ pandoc.Str("(no exercise selected)") }))
end
doc.meta.subtitle = pandoc.Inlines({ pandoc.Str(opts.subtitle or
(labels.solutions .. " — " .. labels.label .. " " .. table.concat(nums, ", "))) })
doc.meta.abstract = nil
if doc.meta.book ~= nil then doc.meta.book.abstract = nil end
end
doc.blocks = out
return doc
end
return {
{ Meta = read_meta },
{ Pandoc = walk },
}
+225
View File
@@ -0,0 +1,225 @@
-- fenced-divs.lua — rebuild ::: divs that pandoc left as plain text
--
-- Pandoc only recognises a ::: fence nested in a list item when it starts
-- exactly at the item's text column: 3 spaces after "1. ", 2 after "- ".
-- Indented one step further (the usual 4 spaces), the fence is read as
-- paragraph text and the div is lost:
--
-- 1. First part.
--
-- :::{.hint} <- 4 spaces: printed as ":::{.hint}"
-- A hint.
-- :::
--
-- This filter finds such literal fence lines and rebuilds the divs from what
-- lies between them, so a div works at any indentation. The content keeps its
-- formatting and maths. A list inside such a div needs a blank line before it
-- (as anywhere in markdown). Unbalanced fences are left as they are, with a
-- warning.
--
-- Runs at pre-ast (see _extension.yml), before every filter that reads divs.
local warned = false
local function warn(msg)
if warned then return end
warned = true
io.stderr:write("[notes] " .. msg .. "\n")
end
------------------------------------------------------------------ fence lines
-- attributes of an opening fence: "{.hint}", "{.solution part=b}", "hint"
local function parse_attr(rest)
local src
if rest:match("^%b{}$") then
src = rest
elseif rest:match("^[%w_%-]+$") then
src = "{." .. rest .. "}"
else
return nil
end
local ok, doc = pcall(pandoc.read, "[x]" .. src, "markdown")
if not ok or #doc.blocks ~= 1 then return nil end
local ins = doc.blocks[1].content
if #ins ~= 1 or ins[1].t ~= "Span" then return nil end
return ins[1].attr
end
-- nil, or { close = true }, or { open = true, attr = Attr }
local function fence_of(line)
local buf = {}
for _, it in ipairs(line) do
if it.t == "Str" then
buf[#buf + 1] = it.text
elseif it.t == "Space" then
buf[#buf + 1] = " "
elseif it.t == "Quoted" then -- smart quotes ate the quotes of title="..."
local q = it.quotetype == "DoubleQuote" and '"' or "'"
buf[#buf + 1] = q .. pandoc.utils.stringify(it.content) .. q
else
return nil
end
end
local rest = table.concat(buf):match("^:::+%s*(.-)%s*$")
if rest == nil then return nil end
rest = rest:gsub("%s*:+$", "") -- "::: {.hint} :::" is allowed
if rest == "" then return { close = true } end
local attr = parse_attr(rest)
if attr == nil then return nil end
return { open = true, attr = attr }
end
local function split_lines(inlines)
local lines, cur = {}, pandoc.Inlines({})
for _, it in ipairs(inlines) do
if it.t == "SoftBreak" or it.t == "LineBreak" then
lines[#lines + 1] = cur
cur = pandoc.Inlines({})
else
cur:insert(it)
end
end
lines[#lines + 1] = cur
return lines
end
------------------------------------------------------------------ rebuild
local repair_blocks
-- tokens of a Para/Plain: its text lines, split around fence lines
local function para_tokens(b, toks)
local lines = split_lines(b.content)
local fences = {}
for i, l in ipairs(lines) do fences[i] = fence_of(l) end
if next(fences) == nil then
toks[#toks + 1] = { block = b }
return false
end
local chunk = pandoc.Inlines({})
local ctor = b.t == "Plain" and pandoc.Plain or pandoc.Para
local function flush()
if #chunk > 0 then toks[#toks + 1] = { block = ctor(chunk) } end
chunk = pandoc.Inlines({})
end
for i, l in ipairs(lines) do
if fences[i] then
flush()
toks[#toks + 1] = fences[i]
else
if #chunk > 0 then chunk:insert(pandoc.SoftBreak()) end
chunk:extend(l)
end
end
flush()
return true
end
-- A fence line right after a list item or quote is swallowed by it (lazy
-- continuation): its unmatched closing fences are handed back ("hoisted")
-- to the enclosing level, where their opening fence is.
local function container_tokens(b, toks)
local changed = false
if b.t == "BulletList" or b.t == "OrderedList" then
local items = {}
for i, item in ipairs(b.content) do
local nb, hoist, ch = repair_blocks(item)
if hoist > 0 and i < #b.content then return nil end
items[i] = nb
changed = changed or ch
if i == #b.content and hoist > 0 then
b.content = items
toks[#toks + 1] = { block = b }
for _ = 1, hoist do toks[#toks + 1] = { close = true } end
return true
end
end
if changed then b.content = items end
elseif b.t == "BlockQuote" or b.t == "Div" then
local nb, hoist, ch = repair_blocks(b.content)
if hoist > 0 and b.t == "Div" then return nil end
if ch then b.content = nb; changed = true end
toks[#toks + 1] = { block = b }
for _ = 1, hoist do toks[#toks + 1] = { close = true } end
return changed or hoist > 0
end
toks[#toks + 1] = { block = b }
return changed
end
-- returns new blocks, number of unmatched trailing closing fences, changed?
function repair_blocks(blocks)
local toks, changed = {}, false
for _, b in ipairs(blocks) do
local ch
if b.t == "Para" or b.t == "Plain" then
ch = para_tokens(b, toks)
else
ch = container_tokens(b, toks)
if ch == nil then
warn("unbalanced ::: fences inside a list; start them at the item's text column")
return blocks, 0, false
end
end
changed = changed or ch
end
if not changed then return blocks, 0, false end
local last_content = 0 -- closing fences after this token can be hoisted
for i, t in ipairs(toks) do
if not t.close then last_content = i end
end
local root = { blocks = pandoc.Blocks({}) }
local stack = { root }
local hoist = 0
for i, t in ipairs(toks) do
local top = stack[#stack]
if t.block then
top.blocks:insert(t.block)
elseif t.open then
stack[#stack + 1] = { attr = t.attr, blocks = pandoc.Blocks({}) }
elseif #stack > 1 then
stack[#stack] = nil
stack[#stack].blocks:insert(pandoc.Div(top.blocks, top.attr))
elseif i > last_content then
hoist = hoist + 1
else
warn("a ::: closing fence has no opening fence; left as text")
return blocks, 0, false
end
end
if #stack > 1 then
warn("a ::: fence is never closed; left as text")
return blocks, 0, false
end
return root.blocks, hoist, true
end
------------------------------------------------------------------ filter
local function has_literal_fence(doc)
local found = false
doc:walk({
Str = function(s)
if not found and s.text:sub(1, 3) == ":::" then found = true end
end,
})
return found
end
return {
{
Pandoc = function(doc)
if not has_literal_fence(doc) then return nil end
local blocks, hoist, changed = repair_blocks(doc.blocks)
if hoist > 0 then
warn("a ::: closing fence has no opening fence; left as text")
return nil
end
if not changed then return nil end
doc.blocks = blocks
return doc
end,
},
}
+77
View File
@@ -0,0 +1,77 @@
/* glossary — usages, entries, hover tooltip */
/* usages: dotted underline, keep math color */
a.gls-sym,
mjx-container a {
color: inherit;
text-decoration: none;
}
.gls-sym {
border-bottom: 1px dotted currentColor;
cursor: help;
}
/* rendered glossary list */
.glossary .gls-entry {
margin: 0.8rem 0;
padding: 0.35rem 0.7rem;
border-left: 3px solid var(--calc-notecolor, #B45309);
scroll-margin-top: 5rem; /* don't hide behind Quarto's sticky header */
}
.glossary .gls-entry p { margin: 0 0 0.2rem; }
.glossary .gls-entry:target {
background: color-mix(in srgb, var(--calc-notecolor, #B45309) 10%, transparent);
border-radius: 0.25rem;
}
/* floating hover tooltip (filled by glossary.js) */
.gls-float {
position: absolute;
z-index: 1000;
max-width: 26rem;
padding: 0.5rem 0.75rem;
border: 1px solid var(--calc-notecolor, #B45309);
border-radius: 0.4rem;
background: var(--bs-body-bg, #fff);
color: var(--bs-body-color, #1a1a1a);
box-shadow: 0 4px 14px rgba(0, 0, 0, 0.15);
font-size: 0.9em;
line-height: 1.4;
}
.gls-float p { margin: 0 0 0.25rem; }
.gls-float p:last-child { margin-bottom: 0; }
/* in-place definition cards and property sub-entries */
.gls-inline {
margin: 1rem 0;
padding: 0.4rem 0.8rem;
border-left: 3px solid var(--calc-notecolor, #B45309);
scroll-margin-top: 5rem;
}
.gls-inline p { margin: 0 0 0.3rem; }
.gls-inline:target,
.gls-prop-entry:target {
background: color-mix(in srgb, var(--calc-notecolor, #B45309) 10%, transparent);
border-radius: 0.25rem;
}
.gls-prop-entry {
margin: 0.5rem 0 0.5rem 1.2rem;
padding: 0.25rem 0.6rem;
border-left: 2px solid color-mix(in srgb, var(--calc-notecolor, #B45309) 45%, transparent);
font-size: 0.95em;
scroll-margin-top: 5rem;
}
.gls-back {
font-size: 0.85em;
opacity: 0.75;
}
/* standalone property cards keep the section flow (no indent) */
.gls-prop-entry.gls-standalone {
margin-left: 0;
font-size: 1em;
}
.glossary .gls-prop-line {
margin: 0.1rem 0 0.1rem 1.2rem;
font-size: 0.9em;
}
+68
View File
@@ -0,0 +1,68 @@
// glossary — hover tooltip for .gls-sym usages (prose links and MathJax \class nodes)
(function () {
var tip = null;
function ensureTip() {
if (tip === null) {
tip = document.createElement("div");
tip.className = "gls-float";
tip.style.display = "none";
document.body.appendChild(tip);
}
return tip;
}
function keyOf(el) {
if (el.dataset && el.dataset.glsKey) return el.dataset.glsKey;
for (var i = 0; i < el.classList.length; i++) {
var c = el.classList[i];
if (c.indexOf("gls-key-") === 0) return c.slice(8);
}
return null;
}
function show(target) {
var key = keyOf(target);
if (!key) return;
var entry = document.getElementById("gls-" + key);
var t = ensureTip();
if (entry) {
// for a main entry, don't drag every property into the popup
var node = entry.cloneNode(true);
node.querySelectorAll(".gls-prop-entry").forEach(function (n) { n.remove(); });
t.innerHTML = node.innerHTML;
} else if (window.__glsData && window.__glsData[key]) {
// entry lives on another page (book chapters render separately)
t.innerHTML = window.__glsData[key];
} else {
return;
}
t.style.display = "block";
if (window.MathJax && window.MathJax.typesetPromise) {
window.MathJax.typesetPromise([t]).catch(function () {});
}
var r = target.getBoundingClientRect();
var x = r.left + window.scrollX;
var y = r.bottom + window.scrollY + 6;
// keep it on screen horizontally
var w = t.offsetWidth;
var maxX = window.scrollX + document.documentElement.clientWidth - w - 12;
t.style.left = Math.max(window.scrollX + 8, Math.min(x, maxX)) + "px";
t.style.top = y + "px";
}
function hide() {
if (tip !== null) tip.style.display = "none";
}
document.addEventListener("mouseover", function (e) {
var el = e.target.closest ? e.target.closest(".gls-sym") : null;
if (el) show(el);
});
document.addEventListener("mouseout", function (e) {
var el = e.target.closest ? e.target.closest(".gls-sym") : null;
if (el) hide();
});
document.addEventListener("click", hide);
window.addEventListener("scroll", hide, { passive: true });
})();
+685
View File
@@ -0,0 +1,685 @@
-- glossary.lua — clickable/hoverable glossary for Quarto (HTML + PDF)
--
-- Entries can be defined two ways:
--
-- (1) in metadata (document or _quarto.yml), rendered by the glossary list:
--
-- glossary:
-- laplacian:
-- symbol: "$\\nabla^2$"
-- term: "Laplacian"
-- def: "Divergence of the gradient."
-- props: # optional sub-entries
-- linearity:
-- term: "linearity"
-- def: "$\\nabla^2(af+bg) = a\\nabla^2 f + b\\nabla^2 g$"
--
-- (2) inline, at the natural place in the document flow:
--
-- :::: {.gls-def key=laplacian symbol="$\nabla^2$" term="Laplacian"}
-- Divergence of the gradient: $\nabla^2 f = \nabla\cdot\nabla f$.
--
-- ::: {.gls-prop key=linearity term="linearity"}
-- $\nabla^2(af + bg) = a\,\nabla^2 f + b\,\nabla^2 g$.
-- :::
-- ::::
--
-- The div renders in place as the definition card AND registers the
-- entry; usages link back to this spot.
--
-- Usage (works for entries and properties):
-- in math: \gls{laplacian} \gls{laplacian.linearity}
-- in prose: [laplacian]{.gls} [by linearity]{.gls key=laplacian.linearity}
-- the list: ::: {.glossary}\n:::
--
-- HTML: usages are links with hover popups. PDF: hyperref links.
--
-- The link from the list back to the definition follows the document `lang`
-- (en/fr/de); `glossary-back: "..."` in metadata overrides its text.
-- the link from the glossary list back to where a term was defined
local LABELS = {
en = { back = "→ definition in context" },
fr = { back = "→ définition en contexte" },
de = { back = "→ Definition im Kontext" },
}
local labels = LABELS.en
local glossary = {} -- key -> entry
local keys = {} -- sorted list of top-level keys
local glossary_page = nil -- e.g. "glossary.html": where metadata entries live
local cache_path = nil -- .gls-cache-<lang>.lua in the project directory
local current_page = nil -- e.g. "ch1.html": the page being rendered
-- entry = { sym, term = Inlines, def = Blocks, inline = bool,
-- props = { pkey -> {sym, term = Inlines, def = Blocks} },
-- porder = { pkey... } }
local function fmt_is(name)
if quarto and quarto.doc and quarto.doc.is_format then
return quarto.doc.is_format(name)
end
return FORMAT ~= nil and FORMAT:match(name) ~= nil
end
------------------------------------------------------------------ helpers
-- first Math element's text within a metadata value / inline list
local function math_of(v)
if v == nil then return nil end
local inlines = v
if pandoc.utils.type(v) == "Blocks" then
inlines = pandoc.utils.blocks_to_inlines(v)
end
for _, it in ipairs(inlines) do
if it.t == "Math" then return it.text end
end
return nil
end
-- math text out of an attribute string like "$\nabla^2$" (or bare "\nabla^2")
local function math_of_attr(s)
if s == nil then return nil end
local inner = s:match("^%s*%$(.-)%$%s*$")
return inner or s
end
local function to_inlines(v)
if v == nil then return pandoc.Inlines({}) end
if pandoc.utils.type(v) == "Blocks" then
return pandoc.utils.blocks_to_inlines(v)
end
return v
end
local function to_blocks(v)
if v == nil then return pandoc.Blocks({}) end
if pandoc.utils.type(v) == "Blocks" then return v end
return pandoc.Blocks({ pandoc.Plain(v) })
end
local function anchor(key) return "gls-" .. key end
-- resolve "key" or "key.prop"; returns display info + anchor or nil
-- Entries defined inline live on this page; entries that come from
-- metadata live wherever the ::: {.glossary} list is rendered. In a book
-- each chapter is a separate HTML page, so those need a page-qualified
-- link (set `glossary-page:` in metadata).
local function href_of(base, id)
local e = glossary[base]
if e ~= nil and e.remote and e.page ~= nil then
return e.page .. "#" .. id
end
if e ~= nil and e.inline then return "#" .. id end
if glossary_page ~= nil and fmt_is("html") then
return glossary_page .. "#" .. id
end
return "#" .. id
end
local function resolve(full)
local base, prop = full:match("^([^%.]+)%.(.+)$")
base = base or full
local e = glossary[base]
if e == nil then return nil end
local id = anchor(full)
if prop ~= nil then
local p = e.props[prop]
if p == nil then return nil end
return { sym = p.sym, term = p.term, id = id, href = href_of(base, id) }
end
return { sym = e.sym, term = e.term, id = id, href = href_of(base, id) }
end
-- what \gls{...} displays in math mode
local function math_display(r)
return r.sym or ("\\text{" .. pandoc.utils.stringify(r.term) .. "}")
end
local function warn_key(key)
io.stderr:write("[glossary] unknown key: " .. key
.. " (if it is defined with ::: {.gls-def} in another chapter, note that"
.. " HTML book chapters render separately - define shared terms in"
.. " metadata / glossary.yml instead)\n")
end
------------------------------------------------------------------ cross-file cache
-- HTML books render each chapter in a separate pandoc process, so an inline
-- ::: {.gls-def} in one chapter is invisible to the others. We persist those
-- definitions to a small Lua file in the project directory and read it back
-- on every chapter, so \gls{} resolves across files (like LaTeX's .aux, a
-- definition added *after* a use resolves on the next render).
-- One cache per language: a multilingual book (i18n.lua) renders the same
-- chapters once per `lang`, and their definitions must not mix.
local function page_of_input()
local f = nil
if quarto ~= nil and quarto.doc ~= nil then f = quarto.doc.input_file end
if f == nil then return nil end
local base = f:match("([^/\\]+)$") or f
return (base:gsub("%.%w+$", "")) .. ".html"
end
local function read_cache(lang)
if quarto == nil or quarto.project == nil then return end
local dir = quarto.project.directory or "."
cache_path = dir .. "/.gls-cache" .. (lang and ("-" .. lang) or "") .. ".lua"
current_page = page_of_input()
local chunk = loadfile(cache_path)
if chunk == nil then return end
local ok, data = pcall(chunk)
if not ok or type(data) ~= "table" then return end
for key, c in pairs(data) do
-- entries from *this* page get re-registered below; skip them
if c.page ~= current_page and glossary[key] == nil then
local props, porder = {}, {}
for pk, p in pairs(c.props or {}) do
props[pk] = {
sym = p.sym,
term = pandoc.Inlines({ pandoc.Str(p.term or pk) }),
def = pandoc.Blocks({ pandoc.RawBlock("html", p.def_html or "") }),
standalone = true,
}
porder[#porder + 1] = pk
end
table.sort(porder)
glossary[key] = {
sym = c.sym,
term = pandoc.Inlines({ pandoc.Str(c.term or key) }),
def = pandoc.Blocks({ pandoc.RawBlock("html", c.def_html or "") }),
inline = true, remote = true, page = c.page,
props = props, porder = porder,
}
keys[#keys + 1] = key
end
end
end
------------------------------------------------------------------ pass 1: metadata
local function parse_meta_entry(v)
local entry = {
sym = math_of(v.symbol),
term = to_inlines(v.term),
def = to_blocks(v.def),
inline = false,
props = {},
porder = {},
}
if v.props ~= nil then
for pk, pv in pairs(v.props) do
entry.props[pk] = {
sym = math_of(pv.symbol),
term = #to_inlines(pv.term) > 0 and to_inlines(pv.term)
or pandoc.Inlines({ pandoc.Str(pk) }),
def = to_blocks(pv.def),
}
entry.porder[#entry.porder + 1] = pk
end
table.sort(entry.porder)
end
return entry
end
local function read_meta(meta)
local lang = (meta.lang and pandoc.utils.stringify(meta.lang) or "en")
:lower():gsub("[_-].*$", "")
labels = LABELS[lang] or LABELS.en
if meta["glossary-back"] ~= nil then
labels = { back = pandoc.utils.stringify(meta["glossary-back"]) }
end
if meta["glossary-page"] ~= nil then
glossary_page = pandoc.utils.stringify(meta["glossary-page"])
end
if meta.glossary ~= nil then
for k, v in pairs(meta.glossary) do
local entry = parse_meta_entry(v)
if #entry.term == 0 then
entry.term = pandoc.Inlines({ pandoc.Str(k) })
end
glossary[k] = entry
keys[#keys + 1] = k
end
end
if fmt_is("html") then
read_cache(meta.lang and pandoc.utils.stringify(meta.lang):gsub("[^%w_-]", "") or nil)
end
if quarto ~= nil and quarto.doc ~= nil and fmt_is("html") then
quarto.doc.add_html_dependency({
name = "calc-glossary",
version = "2.0.0",
stylesheets = { "glossary.css" },
scripts = { "glossary.js" },
})
end
return meta
end
------------------------------------------------------------------ pass 2: inline defs
local pending_props = {}
-- standalone property: ::: {.gls-prop key=div.linearity} (or key=linearity of=div)
local function register_standalone_prop(el)
local key = el.attributes.key
local base, prop
if el.attributes.of ~= nil then
base, prop = el.attributes.of, key
elseif key ~= nil then
base, prop = key:match("^([^%.]+)%.(.+)$")
end
if base == nil then return false end -- plain key: nested style, parent scans it
pending_props[#pending_props + 1] = {
base = base,
prop = prop,
sym = math_of_attr(el.attributes.symbol),
term = el.attributes.term ~= nil
and pandoc.Inlines({ pandoc.Str(el.attributes.term) })
or pandoc.Inlines({ pandoc.Str(prop) }),
def = el.content:clone(),
}
return true
end
-- attach standalone props once every .gls-def has been registered
local function attach_pending(doc)
for _, p in ipairs(pending_props) do
local e = glossary[p.base]
if e == nil then
io.stderr:write("[glossary] property " .. p.base .. "." .. p.prop
.. " has no matching .gls-def for '" .. p.base .. "'\n")
e = { sym = nil, term = pandoc.Inlines({ pandoc.Str(p.base) }),
def = pandoc.Blocks({}), inline = true, props = {}, porder = {} }
glossary[p.base] = e
keys[#keys + 1] = p.base
end
if e.props[p.prop] ~= nil then
io.stderr:write("[glossary] duplicate property: " .. p.base .. "." .. p.prop .. "\n")
else
e.props[p.prop] = { sym = p.sym, term = p.term, def = p.def,
standalone = true }
e.porder[#e.porder + 1] = p.prop
end
end
return doc
end
local function register_inline(el)
if el.classes:includes("gls-prop") then
register_standalone_prop(el)
return nil
end
if not el.classes:includes("gls-def") then return nil end
local key = el.attributes.key
if key == nil then
io.stderr:write("[glossary] .gls-def without key= attribute\n")
return nil
end
local entry = {
sym = math_of_attr(el.attributes.symbol),
term = el.attributes.term ~= nil
and pandoc.Inlines({ pandoc.Str(el.attributes.term) })
or pandoc.Inlines({ pandoc.Str(key) }),
def = pandoc.Blocks({}),
inline = true,
props = {},
porder = {},
}
for _, b in ipairs(el.content) do
if b.t == "Div" and b.classes:includes("gls-prop") then
local pk = b.attributes.key
if pk == nil then
io.stderr:write("[glossary] .gls-prop without key= (in " .. key .. ")\n")
else
entry.props[pk] = {
sym = math_of_attr(b.attributes.symbol),
term = b.attributes.term ~= nil
and pandoc.Inlines({ pandoc.Str(b.attributes.term) })
or pandoc.Inlines({ pandoc.Str(pk) }),
def = b.content:clone(),
}
entry.porder[#entry.porder + 1] = pk
end
else
entry.def:insert(b)
end
end
if glossary[key] ~= nil then
io.stderr:write("[glossary] duplicate key: " .. key .. "\n")
else
keys[#keys + 1] = key
end
glossary[key] = entry
return nil -- registration only; pass 3 transforms
end
------------------------------------------------------------------ pass 3: usages & rendering
-- rewrite \gls{...} occurrences inside a TeX/math string
local function replace_gls(txt, target)
return (txt:gsub("\\gls(%b{})", function(braced)
local key = braced:sub(2, -2)
local r = resolve(key)
if r == nil then
warn_key(key)
return "\\text{??" .. key .. "??}"
end
local disp = math_display(r)
if target == "latex" then
return "\\hyperlink{" .. r.id .. "}{" .. disp .. "}"
else
return "\\href{" .. r.href .. "}{\\class{gls-sym gls-key-" .. key .. "}{" .. disp .. "}}"
end
end))
end
local function Math(el)
if not el.text:find("\\gls") then return nil end
el.text = replace_gls(el.text, fmt_is("latex") and "latex" or "html")
return el
end
local function RawBlock(el)
if el.format ~= "tex" and el.format ~= "latex" then return nil end
if not el.text:find("\\gls") then return nil end
if fmt_is("latex") then
return pandoc.RawBlock(el.format, replace_gls(el.text, "latex"))
end
return nil
end
local function usage(key, display)
local r = resolve(key)
if r == nil then
warn_key(key)
return nil
end
local out = pandoc.Inlines({})
if fmt_is("latex") then
out:insert(pandoc.RawInline("latex", "\\hyperlink{" .. r.id .. "}{"))
out:extend(display)
out:insert(pandoc.RawInline("latex", "}"))
elseif fmt_is("html") then
out:insert(pandoc.RawInline("html",
'<a class="gls-sym" data-gls-key="' .. key .. '" href="' .. r.href .. '">'))
out:extend(display)
out:insert(pandoc.RawInline("html", "</a>"))
else
return display
end
return out
end
local function Span(el)
-- pandoc's LaTeX reader turns \gls{key} into this span (glossaries pkg)
local acr = el.attributes["acronym-label"]
if acr ~= nil then
local r = resolve(acr)
if r == nil then
warn_key(acr)
return nil
end
return usage(acr, pandoc.Inlines({ pandoc.Math("InlineMath", math_display(r)) }))
end
if not el.classes:includes("gls") then return nil end
local key = el.attributes.key or pandoc.utils.stringify(el.content)
local display
if el.attributes.key ~= nil then
display = el.content
else
local r = resolve(key)
display = r and r.term:clone() or el.content
end
return usage(key, display)
end
local function RawInline(el)
if el.format ~= "tex" and el.format ~= "latex" then return nil end
local key = el.text:match("^\\gls%s*{(.-)}$")
if key == nil then return nil end
local r = resolve(key)
if r == nil then return nil end
return usage(key, pandoc.Inlines({ pandoc.Math("InlineMath", math_display(r)) }))
end
-- head line "sym — **term**" (+ latex hypertarget when with_anchor)
local function head_line(id, sym, term, with_anchor)
local head = pandoc.Inlines({})
if with_anchor and fmt_is("latex") then
head:insert(pandoc.RawInline("latex", "\\hypertarget{" .. id .. "}{}"))
end
if sym ~= nil then
head:insert(pandoc.Math("InlineMath", sym))
head:insert(pandoc.Str("\u{2002}—\u{2002}"))
end
head:insert(pandoc.Strong(term:clone()))
return pandoc.Para(head)
end
local function prop_div(base, pk, p, with_anchor)
local id = anchor(base .. "." .. pk)
local blocks = pandoc.Blocks({ head_line(id, p.sym, p.term, with_anchor) })
blocks:extend(p.def:clone())
return pandoc.Div(blocks,
pandoc.Attr(with_anchor and id or "", { "gls-entry", "gls-prop-entry" }))
end
-- transform an in-place .gls-def into its rendered definition card
local function render_inline_def(el)
local key = el.attributes.key
if key == nil then return nil end
local e = glossary[key]
if e == nil or not e.inline then return nil end
local id = anchor(key)
local blocks = pandoc.Blocks({ head_line(id, e.sym, e.term, true) })
blocks:extend(e.def:clone())
for _, pk in ipairs(e.porder) do
if not e.props[pk].standalone then -- standalone props render at their own spot
blocks:insert(prop_div(key, pk, e.props[pk], true))
end
end
return pandoc.Div(blocks, pandoc.Attr(id, { "gls-entry", "gls-inline" }))
end
-- ::: {.glossary} ::: -> rendered list
local function render_list(el)
table.sort(keys)
local blocks = pandoc.Blocks({})
for _, key in ipairs(keys) do
local e = glossary[key]
local id = anchor(key)
-- inline-defined entries keep their canonical anchor in the flow;
-- the list clone links back instead of re-anchoring
local with_anchor = not e.inline
local entry = pandoc.Blocks({ head_line(id, e.sym, e.term, with_anchor) })
entry:extend(e.def:clone())
if e.inline then
for _, pk in ipairs(e.porder) do
local p = e.props[pk]
local line = pandoc.Inlines({})
local pid = anchor(key .. "." .. pk)
if fmt_is("latex") then
line:insert(pandoc.RawInline("latex", "\\hyperlink{" .. pid .. "}{"))
elseif fmt_is("html") then
line:insert(pandoc.RawInline("html",
'<a class="gls-back" href="' .. href_of(key, pid) .. '">'))
end
if p.sym ~= nil then
line:insert(pandoc.Math("InlineMath", p.sym))
line:insert(pandoc.Str("\u{2002}"))
end
line:extend(p.term:clone())
if fmt_is("latex") then
line:insert(pandoc.RawInline("latex", "}"))
elseif fmt_is("html") then
line:insert(pandoc.RawInline("html", "</a>"))
end
entry:insert(pandoc.Div(pandoc.Blocks({ pandoc.Plain(line) }),
pandoc.Attr("", { "gls-prop-line" })))
end
local back = pandoc.Inlines({})
if fmt_is("latex") then
back:insert(pandoc.RawInline("latex", "\\hyperlink{" .. id .. "}{"))
back:insert(pandoc.Str(labels.back))
back:insert(pandoc.RawInline("latex", "}"))
else
back:insert(pandoc.RawInline("html",
'<a class="gls-back" href="' .. href_of(key, id) .. '">'))
back:insert(pandoc.Str(labels.back))
back:insert(pandoc.RawInline("html", "</a>"))
end
entry:insert(pandoc.Para(back))
else
for _, pk in ipairs(e.porder) do
entry:insert(prop_div(key, pk, e.props[pk], true))
end
end
blocks:insert(pandoc.Div(entry,
pandoc.Attr(with_anchor and id or "", { "gls-entry" })))
end
return pandoc.Div(blocks, pandoc.Attr(el.identifier, { "glossary" }))
end
-- transform a standalone .gls-prop into its rendered card
local function render_standalone_prop(el)
local key = el.attributes.key
local base, prop
if el.attributes.of ~= nil then
base, prop = el.attributes.of, el.attributes.key
elseif key ~= nil then
base, prop = key:match("^([^%.]+)%.(.+)$")
end
if base == nil then return nil end -- nested style: parent handles it
local e = glossary[base]
local p = e and e.props[prop]
if p == nil then return nil end
local d = prop_div(base, prop, p, true)
d.classes:insert("gls-standalone")
return d
end
------------------------------------------------------------------ tooltip data
local function js_escape(s)
s = s:gsub("\\", "\\\\"):gsub('"', '\\"')
s = s:gsub("\n", "\\n"):gsub("\r", ""):gsub("<%/", "<\\/")
return s
end
local function blocks_to_html(blocks)
if blocks == nil or #blocks == 0 then return "" end
-- keep math as \(...\) for MathJax: the tooltip typesets it (glossary.js)
local ok, html = pcall(pandoc.write, pandoc.Pandoc(blocks), "html",
{ html_math_method = "mathjax" })
if not ok then return "" end
return html
end
local function head_html(sym, term)
local ins = pandoc.Inlines({})
if sym ~= nil then
ins:insert(pandoc.Math("InlineMath", sym))
ins:insert(pandoc.Str("\u{2002}\u{2014}\u{2002}"))
end
ins:extend(term:clone())
return blocks_to_html(pandoc.Blocks({ pandoc.Para(ins) }))
end
-- write this page's inline definitions back to the cache
local function write_cache()
if not fmt_is("html") then return end
if cache_path == nil or current_page == nil then return end
local entries = {}
-- keep what other pages contributed
local chunk = loadfile(cache_path)
if chunk ~= nil then
local ok, data = pcall(chunk)
if ok and type(data) == "table" then
for k, c in pairs(data) do
if c.page ~= current_page then entries[k] = c end
end
end
end
-- (re)record everything defined inline on this page
for key, e in pairs(glossary) do
if e.inline and not e.remote then
local props = {}
for pk, p in pairs(e.props) do
props[pk] = { sym = p.sym,
term = pandoc.utils.stringify(p.term),
def_html = blocks_to_html(p.def) }
end
entries[key] = { sym = e.sym,
term = pandoc.utils.stringify(e.term),
def_html = blocks_to_html(e.def),
page = current_page,
props = props }
end
end
local buf = { "return {" }
for key, c in pairs(entries) do
local props = { "props={" }
for pk, p in pairs(c.props or {}) do
props[#props + 1] = string.format("[%q]={sym=%s,term=%q,def_html=%q},",
pk, p.sym and string.format("%q", p.sym) or "nil",
p.term or pk, p.def_html or "")
end
props[#props + 1] = "}"
buf[#buf + 1] = string.format("[%q]={sym=%s,term=%q,def_html=%q,page=%q,%s},",
key, c.sym and string.format("%q", c.sym) or "nil",
c.term or key, c.def_html or "", c.page or "",
table.concat(props))
end
buf[#buf + 1] = "}"
local fh = io.open(cache_path, "w")
if fh == nil then return end
fh:write(table.concat(buf, "\n"))
fh:close()
end
-- make every entry's definition available to the tooltip on any page
local function inject_data(doc)
if not fmt_is("html") then return doc end
write_cache()
if quarto == nil or quarto.doc == nil then return doc end
local parts = {}
for key, e in pairs(glossary) do
parts[#parts + 1] = '"' .. js_escape(key) .. '":"'
.. js_escape(head_html(e.sym, e.term) .. blocks_to_html(e.def)) .. '"'
for pk, p in pairs(e.props) do
parts[#parts + 1] = '"' .. js_escape(key .. "." .. pk) .. '":"'
.. js_escape(head_html(p.sym, p.term) .. blocks_to_html(p.def)) .. '"'
end
end
if #parts == 0 then return doc end
quarto.doc.include_text("after-body",
"<script>window.__glsData = {" .. table.concat(parts, ",") .. "};</script>")
return doc
end
local function Div(el)
if el.classes:includes("gls-def") then
return render_inline_def(el)
elseif el.classes:includes("gls-prop") then
return render_standalone_prop(el)
elseif el.classes:includes("glossary") then
return render_list(el)
end
return nil
end
return {
{ Meta = read_meta },
{ Div = register_inline, Pandoc = attach_pending },
{
Math = Math,
RawBlock = RawBlock,
RawInline = RawInline,
Span = Span,
Div = Div,
Pandoc = inject_data,
},
}
+85
View File
@@ -0,0 +1,85 @@
#!/usr/bin/env bash
# handin.sh — extract exercises and their solutions into a PDF to hand back
#
# _extensions/notes/handin.sh [options] SELECTION...
#
# SELECTION (any mix):
# 1.3 an exercise, numbered as in the notes
# 2 every exercise of chapter 2
# 2.Light.qmd every exercise of that chapter file
# '#my-id' the exercise written ::::{.exo #my-id}
# all every exercise of the book
#
# Options:
# -o, --output FILE where to write it (default: _handin/solutions-<selection>.pdf)
# --no-statement only the solutions, not the exercise statements
# --hints keep the hints (dropped by default)
# --subtitle TEXT title page subtitle (default: "Solutions — Exercise 1.3, ...")
# --profile NAME Quarto profile, e.g. the language of a multilingual book
# --to pdf|docx output format (default: pdf)
#
# The whole book is rendered as usual (same config, figures, glossary,
# language), into a temporary folder: _book/ is not touched. Only the selected
# exercises are kept, statements with solutions in place, one part after the
# other. The console lists every extracted exercise and flags empty solutions.
#
# Example: _extensions/notes/handin.sh 1.3 1.5 --subtitle "Series 2"
set -euo pipefail
usage() { sed -n '2,/^$/{s/^# \{0,1\}//;p}' "$0"; }
project="$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)"
[ -f "$project/_quarto.yml" ] || { echo "handin: no _quarto.yml in $project" >&2; exit 1; }
output="" statement=true hints=false subtitle="" profile="" to=pdf
selection=()
while [ $# -gt 0 ]; do
case "$1" in
-h|--help) usage; exit 0 ;;
-o|--output) output="$2"; shift ;;
--no-statement) statement=false ;;
--hints) hints=true ;;
--subtitle) subtitle="$2"; shift ;;
--profile) profile="$2"; shift ;;
--to) to="$2"; shift ;;
-*) echo "handin: unknown option $1 (see --help)" >&2; exit 1 ;;
*) selection+=("$1") ;;
esac
shift
done
[ ${#selection[@]} -gt 0 ] || { usage; exit 1; }
case "$to" in pdf|docx) ;; *) echo "handin: --to must be pdf or docx" >&2; exit 1 ;; esac
if [ -z "$output" ]; then
name="$(printf '%s_' "${selection[@]}" | tr -c 'A-Za-z0-9._-' '_' | sed 's/_*$//')"
output="$project/_handin/solutions-$name.$to"
fi
case "$output" in /*) ;; *) output="$PWD/$output" ;; esac
tmp="$(mktemp -d)"
trap 'rm -rf "$tmp"' EXIT
# YAML double-quoted string
yq() { local s="${1//\\/\\\\}"; s="${s//\"/\\\"}"; printf '"%s"' "$s"; }
{
echo "exo-handin: $(yq "${selection[*]}")"
echo "exo-handin-statement: $statement"
echo "exo-handin-hints: $hints"
[ -n "$subtitle" ] && echo "exo-handin-subtitle: $(yq "$subtitle")"
echo "toc: false"
echo "lof: false"
echo "lot: false"
} > "$tmp/handin.yml"
cd "$project"
args=(render --to "$to" --no-clean --metadata-file "$tmp/handin.yml" --output-dir "$tmp/out")
[ -n "$profile" ] && args+=(--profile "$profile")
quarto "${args[@]}"
result="$(find "$tmp/out" -maxdepth 1 -name "*.$to" | head -n 1)"
[ -n "$result" ] || { echo "handin: quarto produced no .$to file" >&2; exit 1; }
mkdir -p "$(dirname "$output")"
cp "$result" "$output"
echo
echo "handin: wrote $output"
+180
View File
@@ -0,0 +1,180 @@
-- i18n.lua ------------------------------------------------------------
--
-- Single-source multilingual notes. One .qmd per chapter holds every
-- language; the maths is written once, only the prose is split. The active
-- language comes from `lang:` in _quarto.yml (or a profile that overrides it),
-- so `quarto render --profile fr` produces the French book.
--
-- Two mechanisms, deliberately kept apart:
--
-- 1. PROSE -- a div or span carrying a language class is kept when it
-- matches the active language and dropped otherwise. The wrapper itself
-- disappears, so it adds no markup to the output.
--
-- ::: {.de}
-- Wir rechnen
-- :::
-- ::: {.fr}
-- Nous calculons
-- :::
--
-- ## [Die natürlichen Zahlen]{.de}[Les entiers naturels]{.fr} $\mathbb{N}$
--
-- 2. SHORT STRINGS -- an `@tr{key}` token is replaced by the translation of
-- `key`, looked up in the `i18n:` map of i18n.yml. Works inside maths,
-- raw HTML, attribute values, image paths and ordinary text, i.e. all the
-- places a div cannot reach:
--
-- $$ \underset{\text{@tr{prime}}}{2} $$
-- :::{.gls-def key=N term="@tr{term-N}"}
-- ![...](figures/induktion-dominos-@tr{langcode})
--
-- Frontmatter titles follow the same suffix rule as any metadata key: a
-- `title-de:` / `title-fr:` / `title-en:` set collapses to `title:`.
--
-- MUST run before glossary.lua and exo.lua, which read the `term=` and
-- `title=` attributes this filter fills in. See _extension.yml.
local LANGS = { de = true, fr = true, en = true }
local active = nil -- e.g. "de"
local dict = {} -- key -> translated string, for `active` only
local missing = {} -- keys reported once each, to keep the log readable
------------------------------------------------------------------ helpers
local function base_lang(s)
if s == nil then return nil end
-- "de-CH" and "fr_CA" both reduce to the bare language subtag
return (tostring(s):lower():gsub("[_-].*$", ""))
end
-- @tr{key} -> translation, anywhere in a plain string
local function subst(s)
if s == nil or not s:find("@tr{", 1, true) then return s end
return (s:gsub("@tr%{([%w%._%-]+)%}", function(key)
local v = dict[key]
if v ~= nil then return v end
if not missing[key] then
missing[key] = true
io.stderr:write(
"i18n: no '" .. active .. "' translation for key '" .. key ..
"' -- add it to i18n.yml\n")
end
return "@tr{" .. key .. "}" -- leave the token visible rather than blank
end))
end
local function subst_attrs(attrs)
if attrs == nil then return attrs end
for k, v in pairs(attrs) do
if type(v) == "string" then attrs[k] = subst(v) end
end
return attrs
end
-- the language class on an element, if any
local function lang_class(el)
if el.classes == nil then return nil end
for _, c in ipairs(el.classes) do
if LANGS[c] then return c end
end
return nil
end
------------------------------------------------------------------ metadata
local function read_meta(meta)
active = base_lang(meta.lang and pandoc.utils.stringify(meta.lang)) or "en"
if not LANGS[active] then
io.stderr:write(
"i18n: lang '" .. active .. "' is not one of de/fr/en; " ..
"language divs will all be dropped\n")
end
-- build the lookup table for the active language only
if meta.i18n ~= nil then
for key, per_lang in pairs(meta.i18n) do
if per_lang ~= nil and per_lang[active] ~= nil then
dict[key] = pandoc.utils.stringify(per_lang[active])
end
end
end
-- `title-de:` / `title-fr:` / ... collapse onto `title:`; same for any key
local drop = {}
for k, v in pairs(meta) do
local base, suffix = tostring(k):match("^(.-)%-(%a%a)$")
if base and base ~= "" and LANGS[suffix] then
if suffix == active then meta[base] = v end
drop[#drop + 1] = k
end
end
for _, k in ipairs(drop) do meta[k] = nil end
return meta
end
------------------------------------------------------------------ content
local function Div(el)
local l = lang_class(el)
if l then
if l == active then return el.content end
return {}
end
el.attributes = subst_attrs(el.attributes)
return el
end
local function Span(el)
local l = lang_class(el)
if l then
if l == active then return el.content end
return {}
end
el.attributes = subst_attrs(el.attributes)
return el
end
local function Header(el)
el.attributes = subst_attrs(el.attributes)
return el
end
local function Image(el)
-- the markdown reader percent-encodes the braces of a link destination,
-- so figures/x-@tr{lang} arrives as figures/x-@tr%7Blang%7D
local src = el.src:gsub("@tr%%7[Bb]([%w%._%-]+)%%7[Dd]", "@tr{%1}")
el.src = subst(src)
el.attributes = subst_attrs(el.attributes)
return el
end
-- an html comment is documentation, not content: `@tr{key}` written there as
-- an example must stay as typed
local function is_comment(s) return s:match("^%s*<!%-%-") ~= nil end
local function Math(el) el.text = subst(el.text); return el end
local function Str(el) el.text = subst(el.text); return el end
local function RawBlock(el)
if not is_comment(el.text) then el.text = subst(el.text) end
return el
end
local function RawInline(el)
if not is_comment(el.text) then el.text = subst(el.text) end
return el
end
local function Code(el) el.attributes = subst_attrs(el.attributes); return el end
local function CodeBlock(el)el.attributes = subst_attrs(el.attributes); return el end
return {
{ Meta = read_meta },
{
Div = Div, Span = Span, Header = Header, Image = Image,
Math = Math, Str = Str, RawBlock = RawBlock, RawInline = RawInline,
Code = Code, CodeBlock = CodeBlock,
},
}
+45
View File
@@ -0,0 +1,45 @@
/* latex-tables — HTML rendering of LaTeX tabular environments */
.ltx-table {
border-collapse: collapse;
margin: 1rem auto;
max-width: 100%;
overflow-x: auto;
display: table;
}
.ltx-table th,
.ltx-table td {
padding: 0.35em 0.7em;
vertical-align: top;
line-height: 1.4;
}
.ltx-table th {
font-weight: 600;
}
/* alignment */
.ltx-l { text-align: left; }
.ltx-c { text-align: center; }
.ltx-r { text-align: right; }
/* vertical rules (from | in the column spec) */
.ltx-bl { border-left: 1px solid currentColor; }
.ltx-br { border-right: 1px solid currentColor; }
/* horizontal rules: t = above the row, b = below.
1 = \hline / \midrule / \cline, 2 = booktabs \toprule / \bottomrule,
d = doubled rule (\hline\hline) */
.ltx-t1 { border-top: 1px solid currentColor; }
.ltx-b1 { border-bottom: 1px solid currentColor; }
.ltx-t2 { border-top: 1.6px solid currentColor; }
.ltx-b2 { border-bottom: 1.6px solid currentColor; }
.ltx-td { border-top: 3px double currentColor; }
.ltx-bd { border-bottom: 3px double currentColor; }
/* keep wide tables usable on narrow screens */
@media (max-width: 700px) {
.ltx-table { font-size: 0.9em; }
.ltx-table th, .ltx-table td { padding: 0.25em 0.45em; }
}
+563
View File
@@ -0,0 +1,563 @@
-- latex-tables.lua — write tables in LaTeX, render them in HTML too.
--
-- \begin{tabular}{|l|c|r|}
-- \hline
-- Quantity & Symbol & Unit \\
-- \hline
-- pressure & $p$ & Pa \\
-- density & $\rho$ & kg/m$^3$ \\
-- \hline
-- \end{tabular}
--
-- Supported: l c r, p{w} m{w} b{w}, X (tabularx), *{n}{...} repetition,
-- @{...} and >{...}<{...} (ignored), | vertical rules, \hline, \cline{a-b},
-- booktabs \toprule \midrule \bottomrule \cmidrule{a-b}, \multicolumn,
-- \multirow, and the \begin{table} float wrapper with \caption and \label.
--
-- PDF: passed through untouched (it is already LaTeX).
-- HTML: converted to a real <table>; cell contents are parsed as LaTeX, so
-- $math$, \textbf{...} etc. work.
--
-- Header rows: everything above the first rule that follows row 1 becomes
-- <thead>. Put "% no-header" inside the environment to disable that.
local ENVS = { tabular = true, tabularx = true, longtable = true,
["tabular*"] = true }
local function fmt_is(name)
if quarto and quarto.doc and quarto.doc.is_format then
return quarto.doc.is_format(name)
end
return FORMAT ~= nil and FORMAT:match(name) ~= nil
end
------------------------------------------------------------------ utils
local function trim(s)
return (s:gsub("^%s+", ""):gsub("%s+$", ""))
end
-- index of the "}" matching the "{" at open_idx
local function find_close(s, open_idx)
local depth, i, n = 0, open_idx, #s
while i <= n do
local c = s:sub(i, i)
if c == "\\" then
i = i + 2
else
if c == "{" then
depth = depth + 1
elseif c == "}" then
depth = depth - 1
if depth == 0 then return i end
end
i = i + 1
end
end
return nil
end
-- split on every literal `sep` sitting at brace depth 0 and outside any
-- nested environment (so \\ and & inside \begin{cases}/{array}/{pmatrix}
-- in a cell are left alone)
local function split_top(s, sep)
local parts, depth, env, i, start = {}, 0, 0, 1, 1
local n, k = #s, #sep
while i <= n do
if depth == 0 and env == 0 and s:sub(i, i + k - 1) == sep then
parts[#parts + 1] = s:sub(start, i - 1)
i = i + k
start = i
else
local c = s:sub(i, i)
if c == "\\" then
if s:find("^\\begin%s*{", i) then
env = env + 1
i = i + 6
elseif s:find("^\\end%s*{", i) then
env = math.max(0, env - 1)
i = i + 4
else
i = i + 2
end
else
if c == "{" then
depth = depth + 1
elseif c == "}" then
depth = math.max(0, depth - 1)
end
i = i + 1
end
end
end
parts[#parts + 1] = s:sub(start)
return parts
end
-- strip % comments (but keep \%)
local function strip_comments(s)
local out, i, n = {}, 1, #s
while i <= n do
local c = s:sub(i, i)
if c == "\\" then
out[#out + 1] = s:sub(i, i + 1)
i = i + 2
elseif c == "%" then
local nl = s:find("\n", i, true)
if nl == nil then break end
i = nl -- keep the newline
else
out[#out + 1] = c
i = i + 1
end
end
return table.concat(out)
end
-- LaTeX length -> CSS length
local function css_len(w)
w = trim(w)
local frac, rel = w:match("^([%d%.]+)\\(%a+)$")
if frac ~= nil and (rel == "textwidth" or rel == "linewidth"
or rel == "columnwidth") then
return string.format("%.4g%%", tonumber(frac) * 100)
end
if w:match("^\\%a+$") then return "100%" end
local num, unit = w:match("^([%-%d%.]+)%s*(%a+)$")
if num ~= nil then
if unit == "pt" then return num .. "pt" end
if unit == "cm" or unit == "mm" or unit == "in"
or unit == "em" or unit == "ex" then
return num .. unit
end
end
return nil
end
------------------------------------------------------------------ colspec
-- *{3}{c|} -> c|c|c|
local function expand_star(spec)
local guard = 0
while guard < 20 do
guard = guard + 1
local st, _, cnt, body = spec:find("%*%s*(%b{})%s*(%b{})")
if st == nil then break end
local n = tonumber(cnt:sub(2, -2))
local inner = body:sub(2, -2)
if n == nil then break end
spec = spec:sub(1, st - 1) .. string.rep(inner, n)
.. spec:sub(st + #cnt + #body + (spec:sub(st + 1, st + 1) == " " and 1 or 0))
-- recompute safely: rebuild from the matched span
local _, en = spec:find(inner, st, true)
if en == nil then break end
end
return spec
end
-- returns list of { align, left, right, width }
local function parse_colspec(spec)
spec = expand_star(spec)
local cols, pending, i, n = {}, 0, 1, #spec
while i <= n do
local c = spec:sub(i, i)
if c == "|" then
pending = pending + 1
i = i + 1
elseif c == " " or c == "\n" or c == "\t" then
i = i + 1
elseif c == "@" or c == "!" or c == ">" or c == "<" then
local br = spec:find("{", i, true)
local close = br and find_close(spec, br)
i = close and (close + 1) or (i + 1)
elseif c == "l" or c == "c" or c == "r" then
cols[#cols + 1] = { align = c, left = pending, right = 0 }
pending = 0
i = i + 1
elseif c == "p" or c == "m" or c == "b" then
local br = spec:find("{", i, true)
local close = br and find_close(spec, br)
local w = close and spec:sub(br + 1, close - 1) or nil
cols[#cols + 1] = { align = "l", left = pending, right = 0,
width = w and css_len(w) or nil }
pending = 0
i = close and (close + 1) or (i + 1)
elseif c == "X" then
cols[#cols + 1] = { align = "l", left = pending, right = 0, width = "auto" }
pending = 0
i = i + 1
else
i = i + 1
end
end
if #cols > 0 and pending > 0 then cols[#cols].right = pending end
return cols
end
------------------------------------------------------------------ rows
local RULE_PAT = {
{ pat = "^\\toprule%s*(%b[])?", kind = "thick" },
{ pat = "^\\toprule", kind = "thick" },
{ pat = "^\\bottomrule", kind = "thick" },
{ pat = "^\\midrule", kind = "thin" },
{ pat = "^\\hline", kind = "thin" },
}
-- pull leading rule commands off a row segment
local function take_rules(seg)
local rules = { all = nil, ranges = {}, count = 0 }
local changed = true
while changed do
changed = false
seg = seg:gsub("^%s+", "")
-- \noalign{...} / \addlinespace / spacing args: drop
local br = seg:match("^\\noalign%s*%b{}")
if br then seg = seg:sub(#br + 1); changed = true end
local al = seg:match("^\\addlinespace%s*%b[]") or seg:match("^\\addlinespace")
if al then seg = seg:sub(#al + 1); changed = true end
local opt = seg:match("^%b[]")
if opt then seg = seg:sub(#opt + 1); changed = true end
for _, r in ipairs(RULE_PAT) do
local m = seg:match(r.pat)
if m then
rules.count = rules.count + 1
rules.all = (rules.all == "thick" or r.kind == "thick") and "thick" or "thin"
if rules.count > 1 then rules.all = "double" end
seg = seg:sub(#m + 1)
changed = true
break
end
end
-- \cline{a-b} and \cmidrule(lr){a-b}
local head, range = seg:match("^(\\cline%s*(%b{}))")
if head == nil then
local h2, _, r2 = seg:match("^(\\cmidrule%s*(%b())%s*(%b{}))")
if h2 then head, range = h2, r2 end
end
if head == nil then
local h3, r3 = seg:match("^(\\cmidrule%s*(%b{}))")
if h3 then head, range = h3, r3 end
end
if head ~= nil and range ~= nil then
local a, b = range:sub(2, -2):match("^%s*(%d+)%s*%-%s*(%d+)%s*$")
if a then
rules.ranges[#rules.ranges + 1] = { tonumber(a), tonumber(b) }
end
seg = seg:sub(#head + 1)
changed = true
end
end
return seg, rules
end
local function has_rule(rules)
return rules.all ~= nil or #rules.ranges > 0
end
-- \multicolumn{n}{spec}{content} / \multirow{n}{w}{content}
local function parse_cell(txt)
local cell = { colspan = 1, rowspan = 1, body = txt, spec = nil }
local t = trim(txt)
local head, a, b = t:match("^(\\multicolumn%s*(%b{})%s*(%b{}))")
if head then
local br = t:find("{", #head + 1, true)
local close = br and find_close(t, br)
if close then
cell.colspan = tonumber(a:sub(2, -2)) or 1
cell.spec = b:sub(2, -2)
cell.body = t:sub(br + 1, close - 1)
t = trim(t:sub(close + 1))
if t ~= "" then cell.body = cell.body .. " " .. t end
return cell
end
end
local mhead, mn = t:match("^(\\multirow%s*(%b{}))")
if mhead then
-- optional [vpos], then {width}{content}
local rest = t:sub(#mhead + 1)
local opt = rest:match("^%b[]")
if opt then rest = rest:sub(#opt + 1) end
local w = rest:match("^%s*%b{}")
if w then
rest = rest:sub(#rest:match("^%s*") + #w + 1)
local br = rest:find("{", 1, true)
local close = br and find_close(rest, br)
if close then
cell.rowspan = tonumber(mn:sub(2, -2)) or 1
cell.body = rest:sub(br + 1, close - 1)
return cell
end
end
end
return cell
end
local function parse_body(body)
local rows, trailing = {}, nil
local segs = split_top(body, "\\\\")
for idx, raw in ipairs(segs) do
local seg, rules = take_rules(raw)
seg = trim(seg)
if seg == "" then
if idx == #segs then
trailing = rules
elseif #rows > 0 and has_rule(rules) then
-- a rule on its own line between rows: attach below previous row
rows[#rows].below = rules
end
else
local cells = {}
for _, c in ipairs(split_top(seg, "&")) do
cells[#cells + 1] = parse_cell(c)
end
rows[#rows + 1] = { cells = cells, above = rules }
end
end
return rows, trailing
end
------------------------------------------------------------------ html
local function cell_inlines(txt)
txt = trim(txt)
if txt == "" then return pandoc.Inlines({}) end
local ok, doc = pcall(pandoc.read, txt, "latex")
if ok and doc and #doc.blocks > 0 then
return pandoc.utils.blocks_to_inlines(doc.blocks)
end
return pandoc.Inlines({ pandoc.Str(txt) })
end
local function rule_class(kind, where)
if kind == "thick" then return "ltx-" .. where .. "2" end
if kind == "double" then return "ltx-" .. where .. "d" end
if kind == "thin" then return "ltx-" .. where .. "1" end
return nil
end
local ALIGN = { l = "AlignLeft", c = "AlignCenter", r = "AlignRight" }
-- build one pandoc.Row.
-- `pending` maps column -> number of further rows still covered by a
-- \multirow above. LaTeX writes an empty placeholder cell for those, but
-- HTML's rowspan already covers them, so they must be consumed, not emitted.
local function build_row(cols, row, ri, nrows, trailing, pending)
local cells = pandoc.List({})
local ci = 1
local input, k = row.cells, 1
while k <= #input do
-- skip columns still covered from above
while (pending[ci] or 0) > 0 do
pending[ci] = pending[ci] - 1
ci = ci + 1
if trim(input[k].body) == "" and input[k].colspan == 1
and input[k].rowspan == 1 then
k = k + 1 -- eat the placeholder
if k > #input then break end
end
end
if k > #input then break end
local cell = input[k]
k = k + 1
local col = cols[ci] or { align = "l", left = 0, right = 0 }
local last = cols[math.min(ci + cell.colspan - 1, #cols)] or col
local align, left, right = col.align, col.left, last.right
local width = col.width
if cell.spec ~= nil then
local sub = parse_colspec(cell.spec)
if #sub > 0 then
align = sub[1].align
left = sub[1].left
right = sub[#sub].right
end
end
local cls = pandoc.List({ "ltx-" .. align })
if left > 0 then cls:insert("ltx-bl") end
if right > 0 then cls:insert("ltx-br") end
local ra = row.above
if ra.all then
cls:insert(rule_class(ra.all, "t"))
else
for _, rg in ipairs(ra.ranges) do
if ci >= rg[1] and ci <= rg[2] then cls:insert("ltx-t1") break end
end
end
local rb = row.below or (ri == nrows and trailing or nil)
if rb then
if rb.all then
cls:insert(rule_class(rb.all, "b"))
else
for _, rg in ipairs(rb.ranges) do
if ci >= rg[1] and ci <= rg[2] then cls:insert("ltx-b1") break end
end
end
end
local attrs = {}
if width and width ~= "auto" then attrs.style = "width:" .. width end
local content = pandoc.Blocks({ pandoc.Plain(cell_inlines(cell.body)) })
cells:insert(pandoc.Cell(content, ALIGN[align] or "AlignDefault",
cell.rowspan, cell.colspan, pandoc.Attr("", cls, attrs)))
if cell.rowspan > 1 then
for c = ci, ci + cell.colspan - 1 do
pending[c] = (pending[c] or 0) + cell.rowspan - 1
end
end
ci = ci + cell.colspan
end
return pandoc.Row(cells)
end
local function render_table(cols, rows, trailing, header_end, id, caption)
local colspecs = pandoc.List({})
for _, c in ipairs(cols) do
colspecs:insert({ ALIGN[c.align] or "AlignDefault", nil })
end
local head_rows, body_rows = pandoc.List({}), pandoc.List({})
local pending = {}
for ri, row in ipairs(rows) do
local r = build_row(cols, row, ri, #rows, trailing, pending)
if header_end and ri <= header_end then
head_rows:insert(r)
else
body_rows:insert(r)
end
end
local cap = pandoc.Caption({})
if caption ~= nil then
cap = pandoc.Caption(pandoc.Blocks({ pandoc.Plain(cell_inlines(caption)) }))
end
return pandoc.Table(
cap,
colspecs,
pandoc.TableHead(head_rows),
{ { attr = pandoc.Attr(), body = body_rows,
head = pandoc.List({}), row_head_columns = 0 } },
pandoc.TableFoot(),
pandoc.Attr(id or "", { "ltx-table" })
)
end
------------------------------------------------------------------ transform
local function find_env(txt, name)
local st = txt:find("\\begin%s*{" .. name .. "}")
if st == nil then return nil end
local _, be = txt:find("\\begin%s*{" .. name .. "}", st)
local es, ee = txt:find("\\end%s*{" .. name .. "}", be)
if es == nil then return nil end
return st, be, es, ee
end
local function tabular_to_table(txt, id, caption)
local name
for env in pairs(ENVS) do
if txt:find("\\begin%s*{" .. env:gsub("%*", "%%*") .. "}") then
name = env
break
end
end
if name == nil then return nil end
local esc_name = name:gsub("%*", "%%*")
local _, be, es = find_env(txt, esc_name)
if be == nil then return nil end
local rest = txt:sub(be + 1)
local inner_end = es - be - 1
local inner = rest:sub(1, inner_end)
-- tabularx/tabular* take a width argument first
if name == "tabularx" or name == "tabular*" then
local w = inner:match("^%s*%b{}")
if w then inner = inner:sub(#inner:match("^%s*") + #w + 1) end
end
-- optional [t]/[b] positioning
local pos = inner:match("^%s*%b[]")
if pos then inner = inner:sub(#inner:match("^%s*") + #pos + 1) end
local specm = inner:match("^%s*%b{}")
if specm == nil then return nil end
local body = inner:sub(#inner:match("^%s*") + #specm + 1)
local spec = specm:sub(2, -2)
local no_header = body:find("no%-header") ~= nil
body = strip_comments(body)
local cols = parse_colspec(spec)
if #cols == 0 then return nil end
local rows, trailing = parse_body(body)
if #rows == 0 then return nil end
local header_end = 0
if not no_header then
for i = 2, #rows do
if has_rule(rows[i].above) or (rows[i - 1].below and has_rule(rows[i - 1].below)) then
header_end = i - 1
break
end
end
end
return render_table(cols, rows, trailing, header_end, id, caption)
end
-- \begin{table} ... \caption{...} \label{...} ... \end{table}
local function float_parts(txt)
if not txt:find("\\begin%s*{table%*?}") then return nil end
local cap = nil
local cs = txt:find("\\caption")
if cs then
local br = txt:find("{", cs, true)
local close = br and find_close(txt, br)
if close then cap = txt:sub(br + 1, close - 1) end
end
local lab = txt:match("\\label%s*{(.-)}")
return { caption = cap, label = lab }
end
local function RawBlock(el)
if el.format ~= "tex" and el.format ~= "latex" then return nil end
local txt = el.text
local has_tab = false
for env in pairs(ENVS) do
if txt:find("\\begin%s*{" .. env:gsub("%*", "%%*") .. "}") then
has_tab = true
break
end
end
if not has_tab then return nil end
if fmt_is("latex") then return nil end -- PDF: it is already LaTeX
if not fmt_is("html") then return nil end
local float = float_parts(txt) or {}
local tbl = tabular_to_table(txt, float.label, float.caption)
if tbl == nil then
io.stderr:write("[latex-tables] could not parse a tabular; left as-is\n")
return nil
end
return tbl
end
local function read_meta(meta)
if quarto ~= nil and quarto.doc ~= nil then
if fmt_is("html") then
quarto.doc.add_html_dependency({
name = "calc-latex-tables",
version = "1.0.0",
stylesheets = { "latex-tables.css" },
})
elseif fmt_is("latex") then
quarto.doc.use_latex_package("booktabs") -- \toprule etc.
quarto.doc.use_latex_package("multirow") -- \multirow
quarto.doc.use_latex_package("array")
end
end
return meta
end
return {
{ Meta = read_meta },
{ RawBlock = RawBlock },
}
+180
View File
@@ -0,0 +1,180 @@
/* quiz — tick-box self-checks: options, per-option explanations, score bar
*
* The card borrows .exo's frame so a quiz and an exercise look related.
* Green and red are reserved for the verdict: nothing else on the page uses
* them, so a colour here always means "this answer was judged".
*/
.quiz {
--quiz-ok: #1a7f5a;
--quiz-bad: #a3324a;
--quiz-ink: #5a6879;
margin: 1.4rem 0;
padding: 0.7rem 1rem 0.85rem;
border: 1px solid color-mix(in srgb, var(--calc-notecolor, #B45309) 35%, transparent);
border-left: 3px solid var(--calc-notecolor, #B45309);
border-radius: 0.35rem;
scroll-margin-top: 5rem;
}
/* keep wide content inside the card, as in .calc and .exo */
.quiz mjx-container[display="true"],
.quiz .katex-display {
max-width: 100%;
overflow-x: auto;
overflow-y: hidden;
padding-bottom: 0.35em;
display: flex;
justify-content: center;
justify-content: safe center;
}
.quiz .math.display { display: block; max-width: 100%; }
.quiz :is(pre, table) { max-width: 100%; overflow-x: auto; }
.quiz img, .quiz svg { max-width: 100%; }
.quiz-head { margin: 0 0 0.45rem; }
.quiz-head strong { color: var(--calc-notecolor, #B45309); }
.quiz-tip {
margin: 0 0 0.7rem;
font-size: 0.82rem;
color: var(--quiz-ink);
}
/* ---- questions ------------------------------------------------------ */
.quiz-q + .quiz-q {
margin-top: 1.1rem;
padding-top: 0.9rem;
border-top: 1px dashed color-mix(in srgb, var(--calc-notecolor, #B45309) 30%, transparent);
}
.quiz-q-head { margin: 0 0 0.35rem; font-size: 0.9em; }
/* ---- options -------------------------------------------------------- */
.quiz-opts {
list-style: none;
margin: 0.55rem 0 0;
padding: 0;
}
.quiz-opt {
margin: 0;
padding: 0.22rem 0.4rem;
border-radius: 0.25rem;
border-left: 2px solid transparent;
}
.quiz-opt + .quiz-opt { margin-top: 0.15rem; }
/* the whole row is the click target, so a long formula is still easy to tick */
.quiz-label {
display: flex;
align-items: baseline;
gap: 0.55rem;
cursor: pointer;
}
.quiz-box {
flex: 0 0 auto;
width: 1rem;
height: 1rem;
margin: 0;
/* baseline-align the box with the first line of the option text */
transform: translateY(0.15rem);
accent-color: var(--calc-notecolor, #B45309);
cursor: pointer;
}
.quiz-opt-text { min-width: 0; }
.quiz-opt-text > :first-child { margin-top: 0; }
.quiz-opt-text > :last-child { margin-bottom: 0; }
/* judged options */
.quiz-opt.quiz-ok {
background: color-mix(in srgb, var(--quiz-ok) 8%, transparent);
border-left-color: var(--quiz-ok);
}
.quiz-opt.quiz-bad {
background: color-mix(in srgb, var(--quiz-bad) 8%, transparent);
border-left-color: var(--quiz-bad);
}
/* ---- explanations --------------------------------------------------- */
.quiz-why {
margin: 0.35rem 0 0.15rem 1.55rem;
padding: 0.3rem 0 0.3rem 0.7rem;
border-left: 2px solid var(--quiz-bad);
font-size: 0.88rem;
}
.quiz-why > :first-child { margin-top: 0; }
.quiz-why > :last-child { margin-bottom: 0; }
.quiz-why-q {
margin-left: 0;
margin-top: 0.5rem;
}
/* ---- verdict and bar ------------------------------------------------ */
.quiz-verdict {
margin: 0.5rem 0 0;
font-size: 0.85rem;
font-weight: 600;
}
.quiz-verdict.quiz-ok { color: var(--quiz-ok); }
.quiz-verdict.quiz-bad { color: var(--quiz-bad); }
.quiz-bar {
display: flex;
align-items: center;
gap: 0.6rem;
flex-wrap: wrap;
margin-top: 1rem;
padding-top: 0.7rem;
border-top: 1px solid color-mix(in srgb, var(--calc-notecolor, #B45309) 25%, transparent);
}
.quiz-bar button {
font: inherit;
font-size: 0.84rem;
padding: 0.2rem 0.85rem;
cursor: pointer;
border: 1px solid color-mix(in srgb, var(--calc-notecolor, #B45309) 45%, transparent);
border-radius: 999px;
background: transparent;
color: var(--calc-notecolor, #B45309);
}
.quiz-bar button:hover {
background: color-mix(in srgb, var(--calc-notecolor, #B45309) 10%, transparent);
}
.quiz-bar button.quiz-reset {
border-color: color-mix(in srgb, var(--quiz-ink) 40%, transparent);
color: var(--quiz-ink);
}
.quiz-bar button.quiz-reset:hover {
background: color-mix(in srgb, var(--quiz-ink) 10%, transparent);
}
.quiz-score {
font-size: 0.84rem;
color: var(--quiz-ink);
}
.quiz-score b { color: var(--calc-notecolor, #B45309); font-weight: 600; }
/* ---- dark theme ----------------------------------------------------- */
@media (prefers-color-scheme: dark) {
.quiz {
--quiz-ok: #4cb08a;
--quiz-bad: #e2798f;
--quiz-ink: #8b98a8;
}
}
/* ---- print ----------------------------------------------------------
* Printing the HTML is a fallback (the pdf format is the real print path).
* A printed quiz is one to fill in with a pen: the bar goes, the boxes stay
* empty, and anything already revealed on screen is kept so a checked quiz
* prints as it looks.
*/
@media print {
.quiz-bar { display: none; }
.quiz-opt.quiz-ok, .quiz-opt.quiz-bad { background: none; }
}
+126
View File
@@ -0,0 +1,126 @@
// quiz — judge the tick boxes of one quiz, explain what went wrong
//
// Every label the reader sees is written into the markup by quiz.lua, so the
// wording follows the book's language and nothing is translated twice. A
// quiz carries:
// data-quiz-score "{n} of {m} questions correct" ({n}/{m} substituted)
// data-quiz-right verdict of a question answered correctly
// data-quiz-wrong verdict of a question answered wrongly
//
// A question is right only when every one of its options is in the right
// state: ticked when true, left empty when false. That is the "multiple
// true/false" rule of the exam, and it is why a half-ticked question counts
// as wrong.
(function () {
"use strict";
function options(quiz) {
return quiz.querySelectorAll(".quiz-opt");
}
function judge(quiz) {
var questions = quiz.querySelectorAll(".quiz-q");
var right = 0;
questions.forEach(function (q) {
var ok = true;
q.querySelectorAll(".quiz-opt").forEach(function (opt) {
var box = opt.querySelector(".quiz-box");
if (!box) return;
var want = opt.dataset.correct === "1";
var hit = box.checked === want;
opt.classList.toggle("quiz-ok", hit);
opt.classList.toggle("quiz-bad", !hit);
// the explanation of an option is for the reader who got it wrong
var why = opt.querySelector(".quiz-why");
if (why) why.hidden = hit;
if (!hit) ok = false;
});
var verdict = q.querySelector(".quiz-verdict");
if (verdict) {
verdict.hidden = false;
verdict.textContent = ok
? (quiz.dataset.quizRight || "Correct")
: (quiz.dataset.quizWrong || "Not quite");
verdict.classList.toggle("quiz-ok", ok);
verdict.classList.toggle("quiz-bad", !ok);
}
// a question-level explanation backs up a wrong answer as a whole
var qwhy = q.querySelector(".quiz-why-q");
if (qwhy) qwhy.hidden = ok;
if (ok) right++;
});
var score = quiz.querySelector(".quiz-score");
if (score) {
var template = quiz.dataset.quizScore || "{n}/{m}";
score.innerHTML = "";
// built as nodes, not markup: the template comes from metadata
var parts = template.split(/\{n\}|\{m\}/);
var values = [];
(template.match(/\{n\}|\{m\}/g) || []).forEach(function (token) {
values.push(token === "{n}" ? right : questions.length);
});
parts.forEach(function (text, i) {
score.appendChild(document.createTextNode(text));
if (i < values.length) {
var b = document.createElement("b");
b.textContent = String(values[i]);
score.appendChild(b);
}
});
}
}
function reset(quiz) {
options(quiz).forEach(function (opt) {
var box = opt.querySelector(".quiz-box");
if (box) box.checked = false;
opt.classList.remove("quiz-ok", "quiz-bad");
var why = opt.querySelector(".quiz-why");
if (why) why.hidden = true;
});
quiz.querySelectorAll(".quiz-verdict").forEach(function (v) {
v.hidden = true;
v.textContent = "";
v.classList.remove("quiz-ok", "quiz-bad");
});
quiz.querySelectorAll(".quiz-why-q").forEach(function (w) { w.hidden = true; });
var score = quiz.querySelector(".quiz-score");
if (score) score.textContent = "";
}
document.addEventListener("click", function (event) {
var target = event.target;
if (!target.closest) return;
var check = target.closest(".quiz .quiz-check");
if (check) {
judge(check.closest(".quiz"));
return;
}
var again = target.closest(".quiz .quiz-reset");
if (again) {
reset(again.closest(".quiz"));
}
});
// re-ticking a box after checking clears that row's verdict, so a stale
// green or red never sits next to a box the reader has just changed
document.addEventListener("change", function (event) {
var box = event.target;
if (!box.closest || !box.classList || !box.classList.contains("quiz-box")) return;
var opt = box.closest(".quiz-opt");
if (!opt) return;
opt.classList.remove("quiz-ok", "quiz-bad");
var why = opt.querySelector(".quiz-why");
if (why) why.hidden = true;
});
})();
+540
View File
@@ -0,0 +1,540 @@
-- quiz.lua — self-check quizzes with tick boxes (HTML + PDF)
--
-- :::: {.quiz title="Landau notation"}
-- Optional introduction.
--
-- ::: {.question}
-- Decide which statements are true.
--
-- - [x] $n + 2 = o(n^2)$
-- - [ ] $n = \mathcal{O}(\log^2 n)$
--
-- ::: {.why}
-- $n$ eventually outgrows every power of $\log n$.
-- :::
-- :::
-- ::::
--
-- An option is an ordinary markdown task-list item: `- [x]` is true, `- [ ]`
-- is false. A `::: {.why}` div inside an option explains that one option; a
-- `.why` written directly in the question explains the question as a whole.
-- Both are shown only to a reader who got that option (or question) wrong —
-- which is the point of the exercise. (fenced-divs.lua makes the indented
-- ::: fences above work.)
--
-- A quiz holds one or more `::: {.question}` divs. Numbering is chapter.n,
-- n restarting in every chapter (1.1, 1.2, 2.1, ...), as in exo.lua; outside
-- a chapter it is just n. Questions are numbered 1..n inside their quiz.
--
-- HTML: real checkboxes, one **Check** button at the end of the quiz, and a
-- **Reset**. Check marks every option right or wrong, reveals the
-- explanations for what went wrong, and scores the quiz. Nothing is
-- revealed before the button is pressed.
-- PDF: empty boxes to tick with a pen. The answers are printed under a
-- "Quiz answers" heading at the end of the chapter, with a page
-- reference where the quiz was; `quiz: pdf-answers: inline` keeps them
-- in place instead.
--
-- Metadata (labels default to the document `lang`: en, fr or de):
-- quiz:
-- pdf-answers: inline # default: end (of the chapter)
-- label: "Quiz"
-- question: "Question"
-- check: "Vérifier"
-- true: "vrai"
-- ... (any key of LABELS below)
--
-- Runs at pre-ast (see _extension.yml), after fenced-divs.lua and i18n.lua:
-- the `.why` divs must already be divs and the language divs already
-- resolved.
local LABELS = {
en = { label = "Quiz", question = "Question", answers = "Quiz answers",
answer = "Answers", check = "Check", reset = "Reset",
right = "Correct", wrong = "Not quite",
score = "{n} of {m} questions correct",
["true"] = "true", ["false"] = "false",
hint = "Tick every statement you think is true.", page = "p." },
fr = { label = "Quiz", question = "Question", answers = "Réponses du quiz",
answer = "Réponses", check = "Vérifier", reset = "Réinitialiser",
right = "Correct", wrong = "Pas tout à fait",
score = "{n} question(s) correcte(s) sur {m}",
["true"] = "vrai", ["false"] = "faux",
hint = "Cochez chaque énoncé que vous pensez vrai.", page = "p." },
de = { label = "Quiz", question = "Frage", answers = "Quiz-Lösungen",
answer = "Lösungen", check = "Prüfen", reset = "Zurücksetzen",
right = "Richtig", wrong = "Nicht ganz",
score = "{n} von {m} Fragen richtig",
["true"] = "wahr", ["false"] = "falsch",
hint = "Kreuzen Sie jede Aussage an, die Sie für wahr halten.", page = "S." },
}
local labels = {}
local opts = { pdf_answers = "end" }
local TICKED, EMPTY = "\u{2612}", "\u{2610}" -- ☒ ☐, what pandoc's task_lists writes
------------------------------------------------------------------ helpers
local function fmt_is(name)
if quarto and quarto.doc and quarto.doc.is_format then
return quarto.doc.is_format(name)
end
return FORMAT ~= nil and FORMAT:match(name) ~= nil
end
local function str(v)
if v == nil then return nil end
if type(v) == "boolean" then return tostring(v) end
return pandoc.utils.stringify(v)
end
local function esc_html(s)
return (s:gsub("&", "&amp;"):gsub("<", "&lt;"):gsub(">", "&gt;"):gsub('"', "&quot;"))
end
-- LaTeX-escape a label coming from metadata (titles are prose, not code)
local function esc_tex(s)
return (s:gsub("([%%%$&#_{}])", "\\%1"))
end
local function basename(path)
return path and path:match("([^/\\]+)$") or nil
end
local function fill(template, n, m)
return (template:gsub("{n}", tostring(n)):gsub("{m}", tostring(m)))
end
------------------------------------------------------------------ meta
local function read_meta(meta)
local lang = (str(meta.lang) or "en"):lower():gsub("[_-].*$", "")
for k, v in pairs(LABELS[lang] or LABELS.en) do labels[k] = v end
if type(meta.quiz) == "table" then
for k in pairs(labels) do
if meta.quiz[k] ~= nil then labels[k] = str(meta.quiz[k]) end
end
if meta.quiz["pdf-answers"] ~= nil then
opts.pdf_answers = str(meta.quiz["pdf-answers"])
end
end
if quarto ~= nil and quarto.doc ~= nil then
if fmt_is("html") then
quarto.doc.add_html_dependency({
name = "calc-quiz",
version = "1.0.0",
stylesheets = { "quiz.css" },
scripts = { "quiz.js" },
})
elseif fmt_is("latex") then
-- same options as Quarto's callouts and exo.lua's boxes
quarto.doc.use_latex_package("tcolorbox", "skins,breakable")
-- the options are a list whose marker is the tick box, so the default
-- bullet has to go: that is what enumitem's label={} is for
quarto.doc.use_latex_package("enumitem")
end
end
return meta
end
------------------------------------------------------------------ parsing
local function is_why(b)
return b.t == "Div" and (b.classes:includes("why") or b.classes:includes("because"))
end
local function is_question(b)
return b.t == "Div" and (b.classes:includes("question") or b.classes:includes("q"))
end
-- the ☒/☐ a task-list item starts with, or nil if it is not one.
-- Returns the marker and the item's blocks with the marker stripped.
local function task_marker(item)
local first = item[1]
if first == nil or (first.t ~= "Para" and first.t ~= "Plain") then return nil end
local ins = first.content
if #ins == 0 or ins[1].t ~= "Str" then return nil end
local mark = ins[1].text
if mark ~= TICKED and mark ~= EMPTY then return nil end
local rest = pandoc.Inlines({})
for i = 2, #ins do
if not (i == 2 and ins[i].t == "Space") then rest:insert(ins[i]) end
end
local blocks = pandoc.Blocks({})
-- a one-paragraph option stays inline, so it sits on the label's line
blocks:insert(pandoc.Plain(rest))
for i = 2, #item do blocks:insert(item[i]) end
return mark, blocks
end
-- pull the .why divs out of an option's blocks
local function split_why(blocks)
local body, why = pandoc.Blocks({}), pandoc.Blocks({})
for _, b in ipairs(blocks) do
if is_why(b) then why:extend(b.content) else body:insert(b) end
end
return body, why
end
-- one question -> { statement = Blocks, options = { {ok, body, why} }, why = Blocks }
local function parse_question(div)
local statement, options, qwhy = pandoc.Blocks({}), {}, pandoc.Blocks({})
for _, b in ipairs(div.content) do
if is_why(b) then
qwhy:extend(b.content)
elseif b.t == "BulletList" then
local consumed = true
local found = {}
for _, item in ipairs(b.content) do
local mark, blocks = task_marker(item)
if mark == nil then consumed = false; break end
local body, why = split_why(blocks)
found[#found + 1] = { ok = (mark == TICKED), body = body, why = why }
end
if consumed and #found > 0 then
for _, o in ipairs(found) do options[#options + 1] = o end
else
statement:insert(b) -- an ordinary bullet list belongs to the statement
end
else
statement:insert(b)
end
end
return { statement = statement, options = options, why = qwhy }
end
local function parse_quiz(el)
local intro, questions = pandoc.Blocks({}), {}
for _, b in ipairs(el.content) do
if is_question(b) then
questions[#questions + 1] = parse_question(b)
else
intro:insert(b)
end
end
-- a quiz written without ::: {.question} is one question
if #questions == 0 then
local single = parse_question(el)
if #single.options > 0 then
return pandoc.Blocks({}), { single }
end
end
return intro, questions
end
------------------------------------------------------------------ pieces
local function enspace()
if fmt_is("latex") then return pandoc.RawInline("latex", "\\enspace{}") end
return pandoc.Str("\u{2002}")
end
local function head_inlines(num, title)
local ins = pandoc.Inlines({ pandoc.Str(labels.label .. " " .. num) })
if title ~= nil then
ins:extend({ enspace(), pandoc.Str("—"), enspace() })
ins:insert(pandoc.Emph(pandoc.Inlines({ pandoc.Str(title) })))
end
return ins
end
local function raw(fmt, text) return pandoc.RawBlock(fmt, text) end
------------------------------------------------------------------ html
local function html_question(q, i, total)
local out = pandoc.Blocks({ raw("html", '<div class="quiz-q">') })
if total > 1 then
out:insert(raw("html", '<p class="quiz-q-head"><strong>'
.. esc_html(labels.question .. " " .. i) .. "</strong></p>"))
end
out:extend(q.statement)
out:insert(raw("html", '<ul class="quiz-opts">'))
for _, o in ipairs(q.options) do
out:insert(raw("html", '<li class="quiz-opt" data-correct="'
.. (o.ok and "1" or "0") .. '"><label class="quiz-label">'
.. '<input type="checkbox" class="quiz-box">'
.. '<span class="quiz-opt-text">'))
out:extend(o.body)
out:insert(raw("html", "</span></label>"))
if #o.why > 0 then
out:insert(raw("html", '<div class="quiz-why" hidden>'))
out:extend(o.why)
out:insert(raw("html", "</div>"))
end
out:insert(raw("html", "</li>"))
end
out:insert(raw("html", "</ul>"))
out:insert(raw("html", '<p class="quiz-verdict" hidden></p>'))
if #q.why > 0 then
out:insert(raw("html", '<div class="quiz-why quiz-why-q" hidden>'))
out:extend(q.why)
out:insert(raw("html", "</div>"))
end
out:insert(raw("html", "</div>"))
return out
end
local function html_quiz(num, title, intro, questions)
local out = pandoc.Blocks({ raw("html",
'<div class="quiz" id="quiz-' .. esc_html(num) .. '"'
.. ' data-quiz-score="' .. esc_html(labels.score) .. '"'
.. ' data-quiz-right="' .. esc_html(labels.right) .. '"'
.. ' data-quiz-wrong="' .. esc_html(labels.wrong) .. '">') })
out:insert(raw("html", '<p class="quiz-head"><strong>'
.. esc_html(labels.label .. " " .. num) .. "</strong>"
.. (title and ("\u{2002}—\u{2002}<em>" .. esc_html(title) .. "</em>") or "")
.. "</p>"))
out:extend(intro)
out:insert(raw("html", '<p class="quiz-tip">' .. esc_html(labels.hint) .. "</p>"))
for i, q in ipairs(questions) do
out:extend(html_question(q, i, #questions))
end
out:insert(raw("html",
'<div class="quiz-bar">'
.. '<button type="button" class="quiz-check">' .. esc_html(labels.check) .. "</button>"
.. '<button type="button" class="quiz-reset">' .. esc_html(labels.reset) .. "</button>"
.. '<span class="quiz-score" role="status" aria-live="polite"></span>'
.. "</div></div>"))
return out
end
------------------------------------------------------------------ latex
-- an empty tick box, drawn from primitives so no extra package is needed
local function tex_box()
return pandoc.RawInline("latex",
"\\raisebox{-0.15ex}{\\framebox[1.5ex]{\\rule{0pt}{1.05ex}}}\\enspace{}")
end
local function latex_question(q, i, total)
local out = pandoc.Blocks({})
if total > 1 then
out:insert(pandoc.Para({ pandoc.Strong({ pandoc.Str(labels.question .. " " .. i) }) }))
end
out:extend(q.statement)
-- Each option on its own line, marked by a box to tick. The list is
-- written out rather than built as a BulletList: the tick box *is* the
-- marker, so a bullet next to it would be one marker too many.
out:insert(raw("latex", "\\begin{itemize}[label={},leftmargin=1.9em,"
.. "itemsep=0.15em,topsep=0.35em,parsep=0pt]"))
for _, o in ipairs(q.options) do
local blocks = o.body:clone()
local lead = pandoc.Inlines({ pandoc.RawInline("latex", "\\item "), tex_box() })
local first = blocks[1]
if first ~= nil and (first.t == "Plain" or first.t == "Para") then
lead:extend(first.content)
blocks[1] = pandoc.Plain(lead)
else
blocks:insert(1, pandoc.Plain(lead))
end
out:extend(blocks)
end
out:insert(raw("latex", "\\end{itemize}"))
return out
end
-- the answers of one quiz: what was true, and why the false ones are false
local function latex_answers(num, title, questions)
local out = pandoc.Blocks({})
for i, q in ipairs(questions) do
if #questions > 1 then
out:insert(pandoc.Para({ pandoc.Emph({
pandoc.Str(labels.question .. " " .. i) }) }))
end
local items = {}
for j, o in ipairs(q.options) do
local blocks = pandoc.Blocks({})
local verdict = pandoc.Strong({ pandoc.Str(o.ok and labels["true"] or labels["false"]) })
local first = o.body[1]
local ins = pandoc.Inlines({ verdict, pandoc.Str(" \u{2014} ") })
if first ~= nil and (first.t == "Plain" or first.t == "Para") then
ins:extend(first.content)
blocks:insert(pandoc.Plain(ins))
for k = 2, #o.body do blocks:insert(o.body[k]) end
else
blocks:insert(pandoc.Plain(ins))
blocks:extend(o.body)
end
blocks:extend(o.why)
items[j] = blocks
end
out:insert(pandoc.BulletList(items))
out:extend(q.why)
end
return out
end
local function latex_box(title, content, tint)
local b = pandoc.Blocks({ raw("latex",
"\\begin{tcolorbox}[enhanced jigsaw,breakable,frame hidden,"
.. "colback=notecolor!" .. (tint or 4) .. "!white,"
.. "borderline west={1.5pt}{0pt}{notecolor!70!white},arc=0pt,outer arc=0pt,"
.. "colbacktitle=white,coltitle=notecolor!85!black,fonttitle=\\small\\bfseries,"
.. "titlerule=0pt,toptitle=0.5mm,bottomtitle=0mm,"
.. "title={" .. title .. "},left=2mm,right=1.5mm,top=0.5mm,bottom=1mm]") })
b:extend(content)
b:insert(raw("latex", "\\end{tcolorbox}"))
return b
end
-- `pending` collects the answer boxes printed at the end of the chapter
local function latex_quiz(num, title, intro, questions, pending)
local head = labels.label .. " " .. esc_tex(num)
if title ~= nil then head = head .. " \\enspace---\\enspace \\emph{" .. esc_tex(title) .. "}" end
local body = pandoc.Blocks({})
body:extend(intro)
body:insert(pandoc.Para({ pandoc.Emph({ pandoc.Str(labels.hint) }) }))
for i, q in ipairs(questions) do
body:extend(latex_question(q, i, #questions))
end
local answers = latex_answers(num, title, questions)
local atitle = labels.answer .. " \u{2014} " .. labels.label .. " " .. esc_tex(num)
if opts.pdf_answers == "inline" then
local out = latex_box(head, body)
out:extend(latex_box(esc_tex(labels.answer), answers, 0))
return out
end
local id = "quiz-" .. num:gsub("[^%w]", "-") .. "-ans"
body:insert(pandoc.Para({ pandoc.RawInline("latex",
"{\\small\\itshape\\hyperlink{" .. id .. "}{" .. esc_tex(labels.answer)
.. " $\\to$ " .. labels.page .. "\\,\\pageref{" .. id .. "}}}") }))
local collected = pandoc.Blocks({ pandoc.Para({
pandoc.RawInline("latex", "\\hypertarget{" .. id .. "}{}\\label{" .. id .. "}"),
pandoc.Strong({ pandoc.Str(labels.label .. " " .. num) }),
enspace(),
pandoc.RawInline("latex", "{\\small\\hyperlink{quiz-" .. num:gsub("[^%w]", "-")
.. "}{$\\leftarrow$ " .. labels.page .. "\\,\\pageref{quiz-"
.. num:gsub("[^%w]", "-") .. "}}}"),
}) })
collected:extend(answers)
pending[#pending + 1] = collected
local out = pandoc.Blocks({ pandoc.Para({ pandoc.RawInline("latex",
"\\hypertarget{quiz-" .. num:gsub("[^%w]", "-") .. "}{}\\label{quiz-"
.. num:gsub("[^%w]", "-") .. "}") }) })
out:extend(latex_box(head, body))
return out
end
------------------------------------------------------------------ walk
-- Quarto marks where each chapter file starts in a book's merged PDF source
local function file_marker(b)
local txt
if b.t == "RawBlock" and b.format == "html" then
txt = b.text
elseif b.t == "Para" and #b.content == 1 and b.content[1].t == "RawInline" then
txt = b.content[1].text
end
if txt == nil then return nil end
local enc = txt:match("^%s*<!%-%- quarto%-file%-metadata: ([%w%+/=]+) %-%->%s*$")
if enc == nil or quarto == nil or quarto.base64 == nil or quarto.json == nil then return nil end
local ok, data = pcall(function() return quarto.json.decode(quarto.base64.decode(enc)) end)
if ok and type(data) == "table" and data.bookItemFile ~= nil then return data end
return nil
end
local function chapter_label(n)
if type(n) == "number" then return tostring(math.floor(n)) end
if type(n) == "string" and n ~= "" then return n end
return nil
end
-- HTML books render one chapter per run: its number comes from the book
local function book_number_of_input(meta)
if quarto == nil or quarto.doc == nil or quarto.doc.input_file == nil then return nil end
if meta.book == nil or meta.book.render == nil then return nil end
local input = quarto.doc.input_file:gsub("\\", "/")
for _, item in ipairs(meta.book.render) do
local file = str(item.file)
if file ~= nil and (input == file or input:sub(-#file - 1) == "/" .. file) then
return item.number ~= nil and str(item.number) or nil
end
end
return nil
end
local function walk(doc)
local is_latex, is_html = fmt_is("latex"), fmt_is("html")
local next_number = book_number_of_input(doc.meta)
local chapter, chapter_n, cnt = next_number, tonumber(next_number) or 0, 0
local pending = {}
local out = pandoc.Blocks({})
local function flush()
if #pending == 0 then return end
out:insert(pandoc.Header(2, pandoc.Inlines({ pandoc.Str(labels.answers) }),
pandoc.Attr("", { "unnumbered" })))
for _, a in ipairs(pending) do out:extend(a) end
pending = {}
end
for _, b in ipairs(doc.blocks) do
local marker = file_marker(b)
if marker ~= nil then
if is_latex then flush() end
next_number = chapter_label(marker.bookItemNumber)
chapter, cnt = nil, 0
out:insert(b)
elseif b.t == "Header" and b.level == 1 then
if is_latex then flush() end
if not b.classes:includes("unnumbered") then
if next_number ~= nil then
chapter = next_number
chapter_n = tonumber(next_number) or chapter_n
next_number = nil
else
chapter_n = chapter_n + 1
chapter = tostring(chapter_n)
end
cnt = 0
end
out:insert(b)
elseif b.t == "Div" and b.classes:includes("quiz") then
cnt = cnt + 1
local num = chapter ~= nil and (chapter .. "." .. cnt) or tostring(cnt)
local title = b.attributes.title
local intro, questions = parse_quiz(b)
if #questions == 0 then
io.stderr:write("[quiz] " .. labels.label .. " " .. num
.. ": no question with options — write the options as a task list"
.. " (- [x] / - [ ])\n")
out:insert(b)
elseif is_latex then
out:extend(latex_quiz(num, title, intro, questions, pending))
elseif is_html then
out:extend(html_quiz(num, title, intro, questions))
else
out:insert(b)
end
else
out:insert(b)
end
end
if is_latex then flush() end
doc.blocks = out
return doc
end
return {
{ Meta = read_meta },
{ Pandoc = walk },
}
+272
View File
@@ -0,0 +1,272 @@
--[[
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,
},
}
+93
View File
@@ -0,0 +1,93 @@
#!/usr/bin/env bash
# sync.sh — copy this notes extension to every other course
#
# _extensions/notes/sync.sh [--dry-run] [--force]
#
# Run it from the course where you changed the extension: its
# _extensions/notes/ is copied to the Notes folder's own _extensions/notes/
# and to <every course>/_extensions/notes/ (the Notes folder is the one
# holding _course/).
#
# Each copy keeps a .sync-manifest: the checksums of what it received. A copy
# whose files no longer match it was edited in place; sync.sh then skips it
# and shows what differs, so a change made in another course is never lost.
# Bring that change here first, or overwrite it with --force.
# A copy with a higher `version:` in _extension.yml is skipped the same way.
#
# --dry-run only report what would happen
# --force overwrite edited or newer copies too
set -euo pipefail
dry=false force=false
for a in "$@"; do
case "$a" in
--dry-run) dry=true ;;
--force) force=true ;;
-h|--help) sed -n '2,/^$/{s/^# \{0,1\}//;p}' "$0"; exit 0 ;;
*) echo "sync: unknown option $a" >&2; exit 1 ;;
esac
done
src="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
MANIFEST=.sync-manifest
root="$src"
while [ "$root" != "/" ] && [ ! -d "$root/_course" ]; do root="$(dirname "$root")"; done
[ -d "$root/_course" ] || { echo "sync: no folder holding _course/ above $src" >&2; exit 1; }
# checksums of an extension copy, manifest excluded
sums() { (cd "$1" && find . -type f ! -name "$MANIFEST" -printf '%P\n' | LC_ALL=C sort | xargs -d '\n' md5sum); }
version() { sed -n 's/^version:[[:space:]]*//p' "$1/_extension.yml" 2>/dev/null | tr -d '"'"'"; }
newer() { [ "$1" != "$2" ] && [ "$(printf '%s\n%s\n' "$1" "$2" | sort -V | tail -n 1)" = "$1" ]; }
src_sums="$(sums "$src")"
src_version="$(version "$src")"
$dry || printf '%s\n' "$src_sums" > "$src/$MANIFEST"
targets=()
[ -d "$root/_extensions/notes" ] && targets+=("$root/_extensions/notes")
for d in "$root"/*/_extensions/notes; do [ -d "$d" ] && targets+=("$d"); done
status=0
for t in "${targets[@]}"; do
t="$(cd "$t" && pwd)"
[ "$t" = "$src" ] && continue
name="${t#"$root"/}"
cur="$(sums "$t")"
if [ "$cur" = "$src_sums" ]; then
echo "up to date $name"
$dry || printf '%s\n' "$src_sums" > "$t/$MANIFEST"
continue
fi
reason=""
if [ ! -f "$t/$MANIFEST" ]; then
reason="never synced, may hold its own changes"
elif [ "$cur" != "$(cat "$t/$MANIFEST")" ]; then
reason="edited since its last sync"
elif newer "$(version "$t")" "$src_version"; then
reason="has a newer version ($(version "$t") > $src_version)"
fi
if [ -n "$reason" ] && ! $force; then
echo "SKIPPED $name: $reason"
diff -rq --exclude="$MANIFEST" "$src" "$t" | sed "s|$root/||g; s|^| |" || true
status=1
continue
fi
if $dry; then
echo "would update $name${reason:+ (forced: $reason)}"
continue
fi
# mirror: drop files the source no longer has, then copy everything over
(cd "$t" && find . -type f ! -name "$MANIFEST" -printf '%P\n') | while IFS= read -r f; do
[ -e "$src/$f" ] || rm -f "$t/$f"
done
cp -a "$src/." "$t/"
printf '%s\n' "$src_sums" > "$t/$MANIFEST"
echo "updated $name${reason:+ (forced: $reason)}"
done
[ $status -eq 0 ] || echo "some copies were skipped: bring their changes here, or rerun with --force"
exit $status