-- 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("&", "&"):gsub("<", "<"):gsub(">", ">"):gsub('"', """)) 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", '
' .. esc_html(summary) .. '
') }) b:extend(content) b:insert(pandoc.RawBlock("html", "
")) 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*%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 }, }