Expand the common siunitx commands
\SI/\qty, \SIrange, \num and \si were unsupported, so numbers and units leaked as command text. A body pass now reads their braced arguments, normalizes the number (dropping thin spaces and grouping braces) and maps common unit macros to short symbols: metre/meter to m, second to s, kilogram to kg, per to /, squared and cubed to superscripts, and the kilo/milli/micro/nano/centi prefixes. A preview test renders "3.5 m", "2 km/s", "1000" and a bare "m" with no warnings.
This commit is contained in:
1 parent
e53ce3b601
commit
25c7659afe
4 files changed
+143
-6
No files matched your search
+137
@@ -6470,6 +6470,7 @@ fn geometry_and_body_with_images(
|
||||
body = expand_lipsum(&body);
|
||||
body = expand_par_breaks(&body);
|
||||
body = expand_counter_formats(&body, &geometry);
|
||||
body = expand_si_units(&body);
|
||||
// Class \maketitle definitions (arXiv, sn-jnl) issue \thispagestyle{empty}.
|
||||
if geometry.fancy_pagestyle && geometry.title.is_some() {
|
||||
geometry.suppress_first_page_header = true;
|
||||
@@ -6540,6 +6541,119 @@ fn unwrap_scaled_tables(source: &str) -> String {
|
||||
output
|
||||
}
|
||||
|
||||
/// Expand the common siunitx text commands: `\SI`/`\qty`, `\SIrange`,
|
||||
/// `\num` and `\si`. Unit macros are mapped to short symbols.
|
||||
fn expand_si_units(body: &str) -> String {
|
||||
let mut output = String::new();
|
||||
let mut rest = body;
|
||||
loop {
|
||||
let mut next: Option<(usize, &str)> = None;
|
||||
for command in ["\\SIrange", "\\SI", "\\qty", "\\num", "\\si"] {
|
||||
if let Some(index) = rest.find(command) {
|
||||
let better = next.is_none_or(|(known, _)| index < known);
|
||||
if better {
|
||||
next = Some((index, command));
|
||||
}
|
||||
}
|
||||
}
|
||||
let Some((index, command)) = next else {
|
||||
output.push_str(rest);
|
||||
break;
|
||||
};
|
||||
output.push_str(&rest[..index]);
|
||||
let after = rest[index + command.len()..].trim_start();
|
||||
let groups = if command == "\\SIrange" {
|
||||
3
|
||||
} else if command == "\\num" || command == "\\si" {
|
||||
1
|
||||
} else {
|
||||
2
|
||||
};
|
||||
let mut cursor = after;
|
||||
let mut values = Vec::new();
|
||||
let mut parsed = true;
|
||||
for _ in 0..groups {
|
||||
if let Some((value, used)) = braced_group(cursor) {
|
||||
values.push(value);
|
||||
cursor = cursor[used..].trim_start();
|
||||
} else {
|
||||
parsed = false;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if !parsed {
|
||||
output.push_str(command);
|
||||
rest = &rest[index + command.len()..];
|
||||
continue;
|
||||
}
|
||||
let text = match command {
|
||||
"\\num" => si_number(&values[0]),
|
||||
"\\si" => si_unit_text(&values[0]),
|
||||
"\\SIrange" => format!(
|
||||
"{}–{} {}",
|
||||
si_number(&values[0]),
|
||||
si_number(&values[1]),
|
||||
si_unit_text(&values[2])
|
||||
),
|
||||
_ => format!("{} {}", si_number(&values[0]), si_unit_text(&values[1])),
|
||||
};
|
||||
output.push_str(text.trim());
|
||||
rest = cursor;
|
||||
}
|
||||
output
|
||||
}
|
||||
|
||||
fn si_number(value: &str) -> String {
|
||||
value
|
||||
.replace("\\,", "")
|
||||
.replace('~', " ")
|
||||
.replace(['{', '}'], "")
|
||||
.trim()
|
||||
.to_string()
|
||||
}
|
||||
|
||||
fn si_unit_text(unit: &str) -> String {
|
||||
let mut output = String::new();
|
||||
let mut rest = unit;
|
||||
while let Some(character) = rest.chars().next() {
|
||||
if character == '\\' {
|
||||
let after = &rest[1..];
|
||||
let length = after
|
||||
.chars()
|
||||
.take_while(|character| character.is_ascii_alphabetic())
|
||||
.count();
|
||||
let command = &after[..length];
|
||||
output.push_str(match command {
|
||||
"metre" | "meter" => "m",
|
||||
"second" => "s",
|
||||
"kilogram" => "kg",
|
||||
"gram" => "g",
|
||||
"ampere" => "A",
|
||||
"kelvin" => "K",
|
||||
"mole" => "mol",
|
||||
"candela" => "cd",
|
||||
"per" => "/",
|
||||
"squared" => "²",
|
||||
"cubed" => "³",
|
||||
"cdot" => "·",
|
||||
"kilo" => "k",
|
||||
"milli" => "m",
|
||||
"micro" => "µ",
|
||||
"nano" => "n",
|
||||
"centi" => "c",
|
||||
other => other,
|
||||
});
|
||||
rest = &after[length..];
|
||||
} else {
|
||||
if character != '{' && character != '}' {
|
||||
output.push(character);
|
||||
}
|
||||
rest = &rest[character.len_utf8()..];
|
||||
}
|
||||
}
|
||||
output.trim().to_string()
|
||||
}
|
||||
|
||||
/// Expand `\arabic`/`\roman`/`\Roman`/`\alph`/`\Alph`/`\value` with a counter
|
||||
/// name into its current formatted value.
|
||||
fn expand_counter_formats(body: &str, geometry: &PageGeometry) -> String {
|
||||
@@ -17246,6 +17360,29 @@ A definition.
|
||||
assert!(text.contains("D"), "{text}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn siunitx_commands_expand() {
|
||||
let source = "\\documentclass{article}\n\\begin{document}\n\n\\SI{3.5}{m}, \\SI{2}{\\kilo\\metre\\per\\second}, \\num{1\\,000}, \\si{\\metre}.\n\n\\end{document}\n";
|
||||
let json = preview_json(source).expect("preview");
|
||||
let value: serde_json::Value = serde_json::from_str(&json).expect("JSON");
|
||||
assert_eq!(
|
||||
value["warnings"].as_array().map(Vec::len),
|
||||
Some(0),
|
||||
"{}",
|
||||
value["warnings"]
|
||||
);
|
||||
let svg = value["pages"][0]["svg"].as_str().expect("svg");
|
||||
let text: String = svg
|
||||
.split('>')
|
||||
.filter_map(|piece| piece.split('<').next())
|
||||
.collect::<String>()
|
||||
.split_whitespace()
|
||||
.collect();
|
||||
assert!(text.contains("3.5m"), "{text}");
|
||||
assert!(text.contains("2km/s"), "{text}");
|
||||
assert!(text.contains("1000"), "{text}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn appendices_environment_switches_numbering() {
|
||||
let source = "\\documentclass{article}\n\\begin{document}\n\n\\section{Main}\n\nBody.\n\n\\begin{appendices}\n\\section{Extra}\n\\end{appendices}\n\n\\end{document}\n";
|
||||
|
||||
Reference in new issue
Block a user