-- 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("&", "&"):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 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", '
' .. esc_html(labels.question .. " " .. i) .. "
")) end out:extend(q.statement) 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", '