Execute newcommand macros from the preamble
This commit is contained in:
1 parent
e008741aa5
commit
a5da5c9521
4 files changed
+217
-4
No files matched your search
+213
@@ -166,6 +166,8 @@ struct PageGeometry {
|
||||
bibliography: Vec<(String, String)>,
|
||||
/// `\newtheorem` definitions from the preamble.
|
||||
theorem_definitions: Vec<TheoremDefinition>,
|
||||
/// `\newcommand` definitions from the preamble.
|
||||
macros: Vec<MacroDefinition>,
|
||||
}
|
||||
|
||||
/// A `\newtheorem` declaration: display name, shared counter and section scope.
|
||||
@@ -180,6 +182,155 @@ struct TheoremDefinition {
|
||||
|
||||
/// Parse `\newtheorem{env}[shared]{Display}`,
|
||||
/// `\newtheorem{env}{Display}[within]` and `\newtheorem*{env}{Display}`.
|
||||
/// A user macro captured from `\newcommand`.
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
struct MacroDefinition {
|
||||
name: String,
|
||||
args: u8,
|
||||
body: String,
|
||||
}
|
||||
|
||||
/// Consume a braced group; the returned count includes the closing brace.
|
||||
fn take_group_after_open(text: &str) -> Option<(String, usize)> {
|
||||
let mut depth = 0_i32;
|
||||
for (offset, character) in text.char_indices() {
|
||||
match character {
|
||||
'{' => depth += 1,
|
||||
'}' if depth == 0 => {
|
||||
return Some((text[..offset].to_string(), offset + 1));
|
||||
}
|
||||
'}' => depth -= 1,
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
/// Parse `\newcommand{\name}[n]{body}` (and renew/provide variants).
|
||||
fn macro_definition(line: &str) -> Option<MacroDefinition> {
|
||||
let rest = line
|
||||
.strip_prefix("\\newcommand")
|
||||
.or_else(|| line.strip_prefix("\\renewcommand"))
|
||||
.or_else(|| line.strip_prefix("\\providecommand"))?;
|
||||
let rest = rest.trim_start();
|
||||
let rest = rest.strip_prefix('*').unwrap_or(rest).trim_start();
|
||||
let (name, rest) = if let Some(after_open) = rest.strip_prefix('{') {
|
||||
let close = after_open.find('}')?;
|
||||
(
|
||||
after_open[..close].trim().to_string(),
|
||||
&after_open[close + 1..],
|
||||
)
|
||||
} else {
|
||||
let after_slash = rest.strip_prefix('\\')?;
|
||||
let length = after_slash
|
||||
.find(|character: char| !character.is_ascii_alphabetic())
|
||||
.unwrap_or(after_slash.len());
|
||||
(
|
||||
format!("\\{}", &after_slash[..length]),
|
||||
&after_slash[length..],
|
||||
)
|
||||
};
|
||||
if name.is_empty() {
|
||||
return None;
|
||||
}
|
||||
let mut rest = rest.trim_start();
|
||||
let mut args = 0_u8;
|
||||
if let Some(after_bracket) = rest.strip_prefix('[') {
|
||||
let close = after_bracket.find(']')?;
|
||||
args = after_bracket[..close].trim().parse().ok()?;
|
||||
rest = &after_bracket[close + 1..];
|
||||
}
|
||||
let rest = rest.trim_start();
|
||||
if rest.starts_with('[') {
|
||||
// Optional arguments are not supported yet.
|
||||
return None;
|
||||
}
|
||||
let body = rest.strip_prefix('{')?;
|
||||
let (body, _) = take_group_after_open(body)?;
|
||||
Some(MacroDefinition { name, args, body })
|
||||
}
|
||||
|
||||
/// Replace `#1`..`#9` in a macro body with its arguments.
|
||||
fn substitute_macro_args(body: &str, args: &[String]) -> String {
|
||||
let mut output = String::with_capacity(body.len());
|
||||
let mut characters = body.chars().peekable();
|
||||
while let Some(character) = characters.next() {
|
||||
if character == '#' {
|
||||
if let Some(next) = characters.peek().copied() {
|
||||
if let Some(index) = next.to_digit(10) {
|
||||
if index >= 1 && (index as usize) <= args.len() {
|
||||
output.push_str(&args[index as usize - 1]);
|
||||
characters.next();
|
||||
continue;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
output.push(character);
|
||||
}
|
||||
output
|
||||
}
|
||||
|
||||
/// Collect `count` braced arguments starting at `text`; the count is bytes
|
||||
/// consumed including leading whitespace and braces.
|
||||
fn macro_arguments(text: &str, count: u8) -> Option<(Vec<String>, usize)> {
|
||||
let mut args = Vec::new();
|
||||
let mut consumed = 0_usize;
|
||||
let mut cursor = text;
|
||||
for _ in 0..count {
|
||||
let trimmed = cursor.trim_start();
|
||||
consumed += cursor.len() - trimmed.len();
|
||||
cursor = trimmed;
|
||||
let after_open = cursor.strip_prefix('{')?;
|
||||
let (argument, used) = take_group_after_open(after_open)?;
|
||||
args.push(argument);
|
||||
consumed += 1 + used;
|
||||
cursor = &after_open[used..];
|
||||
}
|
||||
Some((args, consumed))
|
||||
}
|
||||
|
||||
/// Expand user macros in a single pass, repeating until nothing changes.
|
||||
fn expand_macros(source: &str, macros: &[MacroDefinition]) -> String {
|
||||
if macros.is_empty() {
|
||||
return source.to_string();
|
||||
}
|
||||
let mut text = source.to_string();
|
||||
for _ in 0..8 {
|
||||
let mut output = String::with_capacity(text.len());
|
||||
let mut index = 0;
|
||||
let mut changed = false;
|
||||
while index < text.len() {
|
||||
let rest = &text[index..];
|
||||
if let Some(after_slash) = rest.strip_prefix('\\') {
|
||||
let length = after_slash
|
||||
.find(|character: char| !character.is_ascii_alphabetic())
|
||||
.unwrap_or(after_slash.len());
|
||||
if length > 0 {
|
||||
let name = format!("\\{}", &after_slash[..length]);
|
||||
if let Some(definition) = macros.iter().find(|macro_| macro_.name == name)
|
||||
&& let Some((args, consumed)) =
|
||||
macro_arguments(&after_slash[length..], definition.args)
|
||||
{
|
||||
output.push_str(&substitute_macro_args(&definition.body, &args));
|
||||
index += 1 + length + consumed;
|
||||
changed = true;
|
||||
continue;
|
||||
}
|
||||
}
|
||||
}
|
||||
let character = rest.chars().next().expect("non-empty tail");
|
||||
output.push(character);
|
||||
index += character.len_utf8();
|
||||
}
|
||||
text = output;
|
||||
if !changed {
|
||||
break;
|
||||
}
|
||||
}
|
||||
text
|
||||
}
|
||||
|
||||
fn newtheorem_definition(line: &str) -> Option<TheoremDefinition> {
|
||||
let rest = line.strip_prefix("\\newtheorem")?;
|
||||
let (starred, rest) = match rest.strip_prefix('*') {
|
||||
@@ -349,6 +500,15 @@ fn strip_page_geometry(source: &str) -> (String, PageGeometry) {
|
||||
}
|
||||
continue;
|
||||
}
|
||||
if trimmed.starts_with("\\newcommand")
|
||||
|| trimmed.starts_with("\\renewcommand")
|
||||
|| trimmed.starts_with("\\providecommand")
|
||||
{
|
||||
if let Some(definition) = macro_definition(trimmed) {
|
||||
geometry.macros.push(definition);
|
||||
}
|
||||
continue;
|
||||
}
|
||||
if trimmed.starts_with("\\newtheorem") {
|
||||
if let Some(definition) = newtheorem_definition(trimmed) {
|
||||
geometry.theorem_definitions.push(definition);
|
||||
@@ -575,6 +735,7 @@ fn geometry_and_body(source: &str) -> (String, PageGeometry) {
|
||||
// paragraphs of their own.
|
||||
let mut body = latex_body(&stripped).trim_matches('\n').to_string();
|
||||
geometry.bibliography = extract_bibliography(&mut body);
|
||||
body = expand_macros(&body, &geometry.macros);
|
||||
(body, geometry)
|
||||
}
|
||||
|
||||
@@ -3982,6 +4143,58 @@ See \ref{fig:a} and \ref{tab:b}.";
|
||||
assert_eq!(blocks[0].left_skip, 12);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn newcommand_definitions_expand_in_the_body() {
|
||||
let source = "\\newcommand{\\R}{\\mathbb{R}}\n\\newcommand{\\pair}[2]{(#1,#2)}\n\n$\\R$ and $\\pair{x}{y}$";
|
||||
let (body, geometry) = geometry_and_body(source);
|
||||
assert_eq!(geometry.macros.len(), 2);
|
||||
assert!(!body.contains("\\newcommand"));
|
||||
assert!(body.contains("\\mathbb{R}"));
|
||||
assert!(body.contains("(x,y)"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn macro_arguments_substitute_in_order() {
|
||||
let definition =
|
||||
macro_definition("\\newcommand{\\vect}[2]{\\mathbf{#2}^{#1}}").expect("definition");
|
||||
assert_eq!(definition.args, 2);
|
||||
assert_eq!(
|
||||
expand_macros("\\vect{2}{x}", std::slice::from_ref(&definition)),
|
||||
"\\mathbf{x}^{2}"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn macros_expand_nested_and_stop_on_recursion() {
|
||||
let definitions = vec![
|
||||
MacroDefinition {
|
||||
name: "\\a".into(),
|
||||
args: 0,
|
||||
body: "\\b".into(),
|
||||
},
|
||||
MacroDefinition {
|
||||
name: "\\b".into(),
|
||||
args: 0,
|
||||
body: "B".into(),
|
||||
},
|
||||
];
|
||||
assert_eq!(expand_macros("\\a", &definitions), "B");
|
||||
let recursive = vec![MacroDefinition {
|
||||
name: "\\loop".into(),
|
||||
args: 0,
|
||||
body: "\\loop".into(),
|
||||
}];
|
||||
assert_eq!(expand_macros("\\loop", &recursive), "\\loop");
|
||||
assert_eq!(expand_macros("\\missing", &definitions), "\\missing");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn macros_expand_in_previews() {
|
||||
let json = preview_json("\\newcommand{\\name}{Ada}\n\nHello \\name.").expect("preview");
|
||||
assert!(json.contains(">A</text>"));
|
||||
assert!(json.contains(">d</text>"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn newtheorem_definitions_are_captured() {
|
||||
let source = "\\newtheorem{claim}[theorem]{Claim}\n\\newtheorem*{note}{Note}\n\\newtheorem{observation}{Observation}[section]\n\nBody.";
|
||||
|
||||
Reference in new issue
Block a user