fix: rendering in typst
This commit is contained in:
8 files changed
+414
-81
No files matched your search
@@ -110,7 +110,7 @@ fn is_tiered(course: &CourseFile, lecture: &str) -> bool {
|
||||
/// # Returns
|
||||
///
|
||||
/// Registry ids in printed order.
|
||||
fn numbered_targets(course: &CourseFile, lecture: &str) -> Vec<String> {
|
||||
pub fn numbered_targets(course: &CourseFile, lecture: &str) -> Vec<String> {
|
||||
if !is_tiered(course, lecture) {
|
||||
// Untiered page: level groups, in the order they print, which is the
|
||||
// numbering this page has always had.
|
||||
|
||||
+11
-7
@@ -259,11 +259,10 @@ pub fn render(catalog: &Catalog, record: &AssessmentFile, opts: &Options) -> Res
|
||||
|
||||
/// The Quarto YAML front matter.
|
||||
fn front_matter(course: &CourseFile, record: &AssessmentFile, variant: Variant) -> String {
|
||||
let title = if matches!(variant, Variant::Solutions) {
|
||||
format!("{}: {}", record.assessment.title, variant.title_word())
|
||||
} else {
|
||||
record.assessment.title.clone()
|
||||
};
|
||||
// Both documents name themselves. Two PDFs called "Homework 1" are
|
||||
// indistinguishable in a downloads folder, which is how a solutions copy
|
||||
// gets posted in place of the worksheet.
|
||||
let title = format!("{}: {}", record.assessment.title, variant.title_word());
|
||||
let subtitle = format!("{} · {}", course.course.code, course.course.title);
|
||||
let mut out = String::from("---\n");
|
||||
out.push_str(&format!("title: \"{}\"\n", yaml_quote(&title)));
|
||||
@@ -663,13 +662,18 @@ items:
|
||||
&Options::default().form,
|
||||
)
|
||||
.expect("renders");
|
||||
assert!(ws.contains("title: \"Homework 1: Questions\""));
|
||||
assert!(ws.contains("title: \"Homework 1: Questions\""), "{ws}");
|
||||
let sol = solutions(
|
||||
&catalog("front-matter-sol"),
|
||||
&record(),
|
||||
&Options::default().form,
|
||||
)
|
||||
.expect("renders");
|
||||
assert!(sol.contains("title: \"Homework 1: Solutions\""));
|
||||
assert!(sol.contains("title: \"Homework 1: Solutions\""), "{sol}");
|
||||
// Neither document may title itself with the bare assessment name: two
|
||||
// PDFs called "Homework 1" are indistinguishable once downloaded, and
|
||||
// the pair that gets confused is the one with the answers in it.
|
||||
assert!(!ws.contains("title: \"Homework 1\""), "{ws}");
|
||||
assert!(!sol.contains("title: \"Homework 1\""), "{sol}");
|
||||
}
|
||||
}
|
||||
+21
-1
@@ -1172,7 +1172,11 @@ mod tests {
|
||||
assert!(m.contains("<allowed_attempts>-1</allowed_attempts>"));
|
||||
assert!(m.contains("<quiz_type>assignment</quiz_type>"));
|
||||
assert!(m.contains("<show_correct_answers>true</show_correct_answers>"));
|
||||
assert!(m.contains("<shuffle_answers>false</shuffle_answers>"));
|
||||
// Canvas does the shuffling. The form fixes an option order for the
|
||||
// printed paper, but an online quiz has no printed order to preserve and
|
||||
// `data::canvas` matches responses back by answer text rather than by
|
||||
// letter, so a per-student shuffle costs the analysis nothing.
|
||||
assert!(m.contains("<shuffle_answers>true</shuffle_answers>"));
|
||||
// Default is unpublished, so an import never goes live unreviewed.
|
||||
assert!(m.contains("<available>false</available>"));
|
||||
assert!(m.contains("<workflow_state>unpublished</workflow_state>"));
|
||||
@@ -1180,6 +1184,22 @@ mod tests {
|
||||
assert!(m.contains(CANVAS_NS));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn shuffling_can_be_turned_off_per_assessment() {
|
||||
// A record with `shuffle: false` is the case where the printed order has
|
||||
// to be preserved online too, such as an item whose options are a
|
||||
// sequence ("first ... then ...") that reads wrong in any other order.
|
||||
let opts = QtiOptions {
|
||||
shuffle_in_canvas: false,
|
||||
..QtiOptions::default()
|
||||
};
|
||||
let m = build_assessment_meta("gq", "ga", "T", 1.0, &opts).render(0);
|
||||
assert!(
|
||||
m.contains("<shuffle_answers>false</shuffle_answers>"),
|
||||
"{m}"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hide_results_tracks_letting_students_see_responses() {
|
||||
// Default (on): hide_results is empty, so students may review and the
|
||||
|
||||
@@ -69,6 +69,7 @@ use crate::Layout;
|
||||
use crate::assessment::{AssessmentFile, Form};
|
||||
use crate::catalog::Catalog;
|
||||
use crate::error::{Error, Result};
|
||||
use crate::markup;
|
||||
|
||||
/// What to render.
|
||||
#[derive(Debug, Clone)]
|
||||
@@ -195,6 +196,17 @@ pub fn render(catalog: &Catalog, record: &AssessmentFile, opts: &Options) -> Res
|
||||
}
|
||||
|
||||
let mut warnings = payload::check(&payload, &opts.config);
|
||||
for (slot, body) in &bodies {
|
||||
if markup::needs_chem_import(&template.source, body) {
|
||||
warnings.push(format!(
|
||||
"the `{}` slot carries a chemical formula, but the template {} does not import \
|
||||
whalogen, so Typst will stop at `unknown variable: ce`; add `{}`",
|
||||
slot.as_str(),
|
||||
template.origin,
|
||||
markup::CHEM_IMPORT
|
||||
));
|
||||
}
|
||||
}
|
||||
if template.is_inert() {
|
||||
warnings.push(format!(
|
||||
"the template {} declares no coursebank markers, so no questions were injected; add \
|
||||
|
||||
@@ -1031,6 +1031,17 @@ fn render(
|
||||
}
|
||||
|
||||
let mut warnings = Vec::new();
|
||||
for (slot, body) in &bodies {
|
||||
if crate::markup::needs_chem_import(&template.source, body) {
|
||||
warnings.push(format!(
|
||||
"the `{}` slot carries a chemical formula, but the template {} does not import \
|
||||
whalogen, so Typst will stop at `unknown variable: ce`; add `{}`",
|
||||
slot.as_str(),
|
||||
template.origin,
|
||||
crate::markup::CHEM_IMPORT
|
||||
));
|
||||
}
|
||||
}
|
||||
if template.is_inert() {
|
||||
warnings.push(format!(
|
||||
"the template {} declares no coursebank markers, so the report is empty; add `// \
|
||||
@@ -1213,6 +1224,42 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn report_markup_takes_the_same_path_as_a_paper() {
|
||||
for source in [
|
||||
"$\\ce{H2O <=> H+ + OH-}$",
|
||||
"the backbone $\\ce{-C=O}$ group",
|
||||
"$K_w = [\\text{H}^+][\\text{OH}^-]$",
|
||||
"see @fig:x where x < y",
|
||||
"costs \\$5, and just $5",
|
||||
] {
|
||||
let expected = crate::markup::to_typst(source);
|
||||
assert_eq!(
|
||||
markup_value(source, true).to_typst(0),
|
||||
format!("[{expected}]"),
|
||||
"content mode diverged on {source:?}"
|
||||
);
|
||||
assert_eq!(
|
||||
markup_value(source, false).to_typst(0),
|
||||
Value::str(expected).to_typst(0),
|
||||
"string mode diverged on {source:?}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_report_carrying_chemistry_names_a_template_missing_the_import() {
|
||||
let body = "#let cb-data = (stem: [#ce(\"H2O\")])";
|
||||
assert!(crate::markup::needs_chem_import(
|
||||
"#import \"@preview/mitex:0.2.7\": mi\n// coursebank:data\n",
|
||||
body
|
||||
));
|
||||
assert!(!crate::markup::needs_chem_import(
|
||||
crate::markup::CHEM_IMPORT,
|
||||
body
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_headline_leads_with_the_distribution() {
|
||||
let lines = headline(&empty_cohort());
|
||||
|
||||
+20
-68
@@ -1066,61 +1066,27 @@ fn numeric_map(map: &BTreeMap<String, f64>) -> Value {
|
||||
)
|
||||
}
|
||||
|
||||
/// Rewrites inline LaTeX math (`$...$`) into a call to mitex's `mi`, so Typst's
|
||||
/// own math grammar never has to parse it. Typst's `\times`, `\Delta`, `\ln` and
|
||||
/// friends are not valid Typst math — a bare backslash escapes the next
|
||||
/// character instead of naming a symbol — which is why equations compile but
|
||||
/// print wrong instead of failing outright. `\$` is left alone, matching LaTeX's
|
||||
/// own convention for a literal dollar sign, and a `$` with no matching close is
|
||||
/// left alone too, rather than swallowing the rest of the field.
|
||||
fn rewrite_latex_math(source: &str) -> String {
|
||||
let chars: Vec<(usize, char)> = source.char_indices().collect();
|
||||
let mut out = String::with_capacity(source.len());
|
||||
let mut i = 0;
|
||||
while i < chars.len() {
|
||||
let (_, c) = chars[i];
|
||||
if c == '\\' && i + 1 < chars.len() {
|
||||
out.push('\\');
|
||||
out.push(chars[i + 1].1);
|
||||
i += 2;
|
||||
continue;
|
||||
}
|
||||
if c != '$' {
|
||||
out.push(c);
|
||||
i += 1;
|
||||
continue;
|
||||
}
|
||||
let mut j = i + 1;
|
||||
let close = loop {
|
||||
if j >= chars.len() {
|
||||
break None;
|
||||
}
|
||||
match chars[j].1 {
|
||||
'\\' => j += 2,
|
||||
'$' => break Some(j),
|
||||
_ => j += 1,
|
||||
}
|
||||
};
|
||||
match close {
|
||||
Some(close_idx) => {
|
||||
let start = chars[i + 1].0;
|
||||
let end = chars[close_idx].0;
|
||||
out.push_str("#mi(");
|
||||
out.push_str(&Value::str(&source[start..end]).to_typst(0));
|
||||
out.push(')');
|
||||
i = close_idx + 1;
|
||||
}
|
||||
None => {
|
||||
out.push('$');
|
||||
i += 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// Emits one markup-bearing field for a diagnostic report.
|
||||
///
|
||||
/// The conversion itself lives in [`markup::to_typst`], which is the single
|
||||
/// entry point for turning authoring markup into Typst: it rewrites inline
|
||||
/// LaTeX math, routes mhchem through whalogen, and escapes the characters Typst
|
||||
/// treats specially in content mode. This path used to carry its own copy of
|
||||
/// the math rewriting, which drifted — the reports escaped nothing outside math
|
||||
/// and silently disagreed with the exam papers about an unmatched `$`.
|
||||
///
|
||||
/// # Arguments
|
||||
///
|
||||
/// * `source` - the authoring source.
|
||||
/// * `content` - whether to emit a content block rather than a quoted string.
|
||||
/// A string is evaluated by the template with `eval(.., mode: "markup")`, so
|
||||
/// both modes need the same escaping.
|
||||
///
|
||||
/// # Returns
|
||||
///
|
||||
/// The value to place in the payload.
|
||||
pub(crate) fn markup_value(source: &str, content: bool) -> Value {
|
||||
let source = rewrite_latex_math(source);
|
||||
let source = markup::to_typst(source);
|
||||
if content {
|
||||
Value::content(source)
|
||||
} else {
|
||||
@@ -1270,17 +1236,3 @@ mod tests {
|
||||
assert!(!balanced("closing ] first"));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn latex_math_becomes_a_mitex_call() {
|
||||
assert_eq!(
|
||||
rewrite_latex_math("angle $\\phi$ (phi)"),
|
||||
"angle #mi(\"\\\\phi\") (phi)"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn escaped_and_unmatched_dollar_signs_are_left_alone() {
|
||||
assert_eq!(rewrite_latex_math("costs \\$5 total"), "costs \\$5 total");
|
||||
assert_eq!(rewrite_latex_math("just $5"), "just $5");
|
||||
}
|
||||
@@ -33,6 +33,7 @@
|
||||
// it. If you change one thing here, keep that.
|
||||
|
||||
#import "@preview/mitex:0.2.7": mi
|
||||
#import "@preview/whalogen:0.3.0": ce
|
||||
|
||||
// ─────────────────────────────────────────────────────────────────────────────
|
||||
// Data
|
||||
|
||||
Reference in new issue
Block a user