-- 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.", qpoints = "{n}/{m} points", totalpoints = "{n} of {m} points", avail = "{m} points" }, 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.", qpoints = "{n}/{m} points", totalpoints = "{n} points sur {m}", avail = "{m} points" }, 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.", qpoints = "{n}/{m} Punkte", totalpoints = "{n} von {m} Punkten", avail = "{m} Punkte" }, } local labels = {} local opts = { pdf_answers = "end", points = 3, penalty = 1 } 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("&", "&"):gsub("<", "<"):gsub(">", ">"):gsub('"', """)) 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 -- numeric, so they go through tonumber and never through the label loop -- above: a label is a string, and arithmetic on a string fails silently. if meta.quiz.points ~= nil then opts.points = tonumber(str(meta.quiz.points)) or opts.points end if meta.quiz.penalty ~= nil then opts.penalty = tonumber(str(meta.quiz.penalty)) or opts.penalty end end if quarto ~= nil and quarto.doc ~= nil then if fmt_is("html") then quarto.doc.add_html_dependency({ name = "calc-quiz", version = dofile(quarto.utils.resolve_path("version.lua")), 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, options = { {ok, body, why} }, why, points, penalty } -- `dflt` is what the quiz div (or the book metadata) set; a question may override -- either number with its own points= / penalty= attribute. local function parse_question(div, dflt) 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 -- Every item has to be a task item for the list to be the options. A -- list that is PARTLY ticked is almost always a typo rather than an -- ordinary bullet list in the statement, and silently swallowing it -- costs the author a whole question, so say so. local found, plain = {}, 0 for _, item in ipairs(b.content) do local mark, blocks = task_marker(item) if mark == nil then plain = plain + 1 else local body, why = split_why(blocks) found[#found + 1] = { ok = (mark == TICKED), body = body, why = why } end end if plain == 0 and #found > 0 then for _, o in ipairs(found) do options[#options + 1] = o end else if #found > 0 then io.stderr:write("[quiz] a bullet list mixes " .. #found .. " task item(s) with " .. plain .. " plain one(s), so none of it" .. " became options -- write every option as `- [x]` or `- [ ]`\n") end statement:insert(b) -- an ordinary bullet list belongs to the statement end else statement:insert(b) end end local a = div.attributes or {} return { statement = statement, options = options, why = qwhy, points = tonumber(a.points) or dflt.points, penalty = tonumber(a.penalty) or dflt.penalty, } end local function parse_quiz(el) local intro, questions = pandoc.Blocks({}), {} local a = el.attributes or {} local dflt = { points = tonumber(a.points) or opts.points, penalty = tonumber(a.penalty) or opts.penalty, } for _, b in ipairs(el.content) do if is_question(b) then questions[#questions + 1] = parse_question(b, dflt) else intro:insert(b) end end -- a quiz written without ::: {.question} is one question if #questions == 0 then local single = parse_question(el, dflt) 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", '
') }) -- The head is emitted even for a one-question quiz: it is where the score -- lands after Check, so it cannot be conditional on there being a number. out:insert(raw("html", '

' .. (total > 1 and ("" .. esc_html(labels.question .. " " .. i) .. "") or "") .. '

')) out:extend(q.statement) out:insert(raw("html", '")) out:insert(raw("html", '')) if #q.why > 0 then out:insert(raw("html", '")) end out:insert(raw("html", "
")) return out end local function html_quiz(num, title, intro, questions) local out = pandoc.Blocks({ raw("html", '
') }) out:insert(raw("html", '

' .. esc_html(labels.label .. " " .. num) .. "" .. (title and ("\u{2002}—\u{2002}" .. esc_html(title) .. "") or "") .. "

")) out:extend(intro) out:insert(raw("html", '

' .. esc_html(labels.hint) .. "

")) for i, q in ipairs(questions) do out:extend(html_question(q, i, #questions)) end out:insert(raw("html", '
' .. '" .. '" .. '' .. "
")) 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({}) -- The points a question is worth are printed in the statement, because a -- reader working on paper has no Check button to tell them afterwards. local avail = fill(labels.avail, 0, q.points) if total > 1 then out:insert(pandoc.Para({ pandoc.Strong({ pandoc.Str(labels.question .. " " .. i) }), enspace(), pandoc.RawInline("latex", "{\\small\\itshape (" .. esc_tex(avail) .. ")}"), })) else out:insert(pandoc.Para({ pandoc.RawInline("latex", "{\\small\\itshape (" .. esc_tex(avail) .. ")}"), })) 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*%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 -- Quarto numbers appendices 1, 2, ... like chapters, while the book shows -- them as A, B, ...: the files after the render list's "appendix" divider -- are appendices, and their quizzes are A.1, A.2, ... local function appendix_files(meta) local set, after = {}, false if meta.book == nil or meta.book.render == nil then return set end for _, item in ipairs(meta.book.render) do if str(item.type) == "appendix" then after = true elseif after and item.file ~= nil then set[basename(str(item.file))] = true end end return set end local function appendix_letter(n) local k = tonumber(n) if k == nil or k < 1 or k > 26 then return n end return string.char(64 + math.floor(k)) 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 if item.number == nil then return nil end local n = str(item.number) if appendix_files(meta)[basename(file)] then n = appendix_letter(n) end return n 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 appendices = appendix_files(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) if next_number ~= nil and appendices[basename(marker.bookItemFile)] then next_number = appendix_letter(next_number) end 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 }, }