Execute newif conditionals in the document body

This commit is contained in:
gloamxun committed 2026-10-24 22:21:47 +08:00
1 parent e99fab2086
commit 6c81a07766
4 files changed
+192 -4

No files matched your search

+188
View File
@@ -169,6 +169,8 @@ struct PageGeometry {
/// `\newcommand` definitions from the preamble.
macros: Vec<MacroDefinition>,
environments: Vec<EnvironmentDefinition>,
/// `\newif` boolean flags declared in the preamble.
conditionals: Vec<ConditionalDefinition>,
}
/// A `\newtheorem` declaration: display name, shared counter and section scope.
@@ -198,6 +200,13 @@ struct EnvironmentDefinition {
end: String,
}
/// A `\newif` boolean flag and its current value.
#[derive(Clone, Debug, PartialEq, Eq)]
struct ConditionalDefinition {
name: String,
value: bool,
}
/// 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;
@@ -642,6 +651,121 @@ fn braced_value(line: &str, command: &str) -> Option<String> {
Some(value.trim().to_string())
}
fn newif_definition(line: &str) -> Option<String> {
let rest = line.strip_prefix("\\newif")?.trim_start();
let (command, _) = control_sequence(rest)?;
let name = command.strip_prefix("\\if")?;
if name.is_empty() {
None
} else {
Some(name.to_string())
}
}
fn conditional_assignment(line: &str, flags: &[ConditionalDefinition]) -> Option<(String, bool)> {
let (command, _) = control_sequence(line)?;
let command = command.strip_prefix('\\')?;
let (name, value) = if let Some(name) = command.strip_suffix("true") {
(name, true)
} else {
(command.strip_suffix("false")?, false)
};
if flags.iter().any(|flag| flag.name == name) {
Some((name.to_string(), value))
} else {
None
}
}
fn conditional_at(
text: &str,
index: usize,
flags: &[ConditionalDefinition],
) -> Option<(bool, usize)> {
let (command, consumed) = control_sequence(text.get(index..)?)?;
let word = command.strip_prefix('\\')?;
if word == "iftrue" {
return Some((true, consumed));
}
if word == "iffalse" {
return Some((false, consumed));
}
let name = word.strip_prefix("if")?;
let flag = flags.iter().find(|flag| flag.name == name)?;
Some((flag.value, consumed))
}
fn conditional_end(text: &str, start: usize) -> Option<(Option<usize>, usize)> {
let mut index = start;
let mut depth = 0_usize;
let mut else_at = None;
while let Some(offset) = text[index..].find('\\') {
let position = index + offset;
let Some((command, consumed)) = control_sequence(&text[position..]) else {
index = position + 1;
continue;
};
let word = command.trim_start_matches('\\');
if word.starts_with("if") && word.len() > 2 {
depth += 1;
} else if word == "fi" {
if depth == 0 {
return Some((else_at, position));
}
depth -= 1;
} else if word == "else" && depth == 0 && else_at.is_none() {
else_at = Some(position);
}
index = position + consumed;
}
None
}
fn expand_conditionals(source: &str, flags: &[ConditionalDefinition]) -> String {
expand_conditionals_at(source, flags, 0)
}
fn expand_conditionals_at(source: &str, flags: &[ConditionalDefinition], depth: usize) -> String {
if depth > 8 {
return source.to_string();
}
let mut output = String::new();
let mut index = 0;
while let Some(offset) = source[index..].find('\\') {
let position = index + offset;
output.push_str(&source[index..position]);
if let Some((value, consumed)) = conditional_at(source, position, flags) {
let body_start = position + consumed;
if let Some((else_at, fi_at)) = conditional_end(source, body_start) {
let (chosen, after) = match else_at {
Some(else_at) => {
if value {
(&source[body_start..else_at], fi_at + 3)
} else {
(&source[else_at + 5..fi_at], fi_at + 3)
}
}
None => {
let chosen = if value {
&source[body_start..fi_at]
} else {
""
};
(chosen, fi_at + 3)
}
};
output.push_str(&expand_conditionals_at(chosen, flags, depth + 1));
index = after;
continue;
}
}
output.push_str(&source[position..position + 1]);
index = position + 1;
}
output.push_str(&source[index..]);
output
}
fn strip_page_geometry(source: &str) -> (String, PageGeometry) {
let mut geometry = PageGeometry::default();
let mut body = String::new();
@@ -676,6 +800,22 @@ fn strip_page_geometry(source: &str) -> (String, PageGeometry) {
}
continue;
}
if let Some(name) = newif_definition(trimmed) {
geometry
.conditionals
.push(ConditionalDefinition { name, value: false });
continue;
}
if let Some((name, value)) = conditional_assignment(trimmed, &geometry.conditionals) {
if let Some(flag) = geometry
.conditionals
.iter_mut()
.find(|flag| flag.name == name)
{
flag.value = value;
}
continue;
}
if trimmed.starts_with("\\newcommand")
|| trimmed.starts_with("\\renewcommand")
|| trimmed.starts_with("\\providecommand")
@@ -932,6 +1072,7 @@ fn geometry_and_body(source: &str) -> (String, PageGeometry) {
geometry.bibliography = extract_bibliography(&mut body);
body = expand_environments(&body, &geometry.environments);
body = expand_macros(&body, &geometry.macros);
body = expand_conditionals(&body, &geometry.conditionals);
(body, geometry)
}
@@ -4339,6 +4480,53 @@ See \ref{fig:a} and \ref{tab:b}.";
assert_eq!(blocks[0].left_skip, 12);
}
#[test]
fn newif_definitions_default_to_false() {
let source = "\\newif\\ifdraft\n\\ifdraft Draft\\else Final\\fi";
let (body, geometry) = geometry_and_body(source);
assert_eq!(geometry.conditionals.len(), 1);
assert_eq!(geometry.conditionals[0].name, "draft");
assert!(!geometry.conditionals[0].value);
assert_eq!(body.trim(), "Final");
}
#[test]
fn conditional_assignments_select_the_true_branch() {
let source = "\\newif\\ifdraft\n\\drafttrue\n\n\\ifdraft Draft\\else Final\\fi";
let (body, _) = geometry_and_body(source);
assert_eq!(body.trim(), "Draft");
}
#[test]
fn nested_conditionals_pick_the_inner_branch() {
let source =
"\\newif\\ifdraft\n\\drafttrue\n\n\\ifdraft A\\ifdraft B\\else C\\fi\\else D\\fi";
let (body, _) = geometry_and_body(source);
assert_eq!(body.trim(), "A B");
}
#[test]
fn unknown_conditionals_stay_literal() {
let source = "\\ifxyz A\\fi";
let (body, geometry) = geometry_and_body(source);
assert!(geometry.conditionals.is_empty());
assert_eq!(body.trim(), "\\ifxyz A\\fi");
}
#[test]
fn macros_can_introduce_conditionals() {
let source = "\\newif\\ifdraft\n\\drafttrue\n\\newcommand{\\pick}{\\ifdraft D\\else F\\fi}\n\n\\pick";
let (body, _) = geometry_and_body(source);
assert_eq!(body.trim(), "D");
}
#[test]
fn iftrue_and_iffalse_select_without_declarations() {
let source = "\\iftrue Yes\\else No\\fi and\\iffalse A\\else B\\fi";
let (body, _) = geometry_and_body(source);
assert_eq!(body.trim(), "Yes and B");
}
#[test]
fn newenvironment_wraps_its_body() {
let source = "\\newenvironment{note}{\\textbf{Note: }}{}\n\n\\begin{note}body\\end{note}.";