Colour the rest of a paragraph after a color switch

This commit is contained in:
gloamxun committed 2026-10-26 02:21:13 +08:00
1 parent 0d8125f854
commit a888421f0e
4 files changed
+29 -4

No files matched your search

+25
View File
@@ -7248,6 +7248,21 @@ fn expand_float_lists(
}
}
/// Parse a leading `\color{name}` switch and return the name plus the rest.
fn color_switch(text: &str) -> Option<(String, String)> {
let trimmed = text.trim_start();
let rest = trimmed.strip_prefix("\\color")?;
let rest = rest.trim_start();
if rest.starts_with('{') {
let (name, used) = braced_group(rest)?;
let after = rest[used..]
.trim_start_matches([' ', '\t', '\n'])
.to_string();
return Some((name.trim().to_string(), after));
}
None
}
fn build_document(paragraphs: &[SourceParagraph], geometry: &PageGeometry) -> Document {
build_document_with_labels(paragraphs, geometry, &mut HashMap::new(), &mut Vec::new())
}
@@ -7512,6 +7527,9 @@ fn build_document_with_labels(
.trim_start()
.to_string();
}
if let Some((color, rest)) = color_switch(&text) {
text = format!("\\textcolor{{{color}}}{{{rest}}}");
}
let class_size = paragraph
.font_size
.or(geometry.base_font_size)
@@ -9082,6 +9100,13 @@ a & b
assert_eq!(body.trim(), "Gap 4.5pt.");
}
#[test]
fn color_switch_paints_the_rest_of_the_paragraph() {
let json = preview_json("\\color{blue} Blue text.").expect("preview");
assert!(json.contains(r##"fill=\"#0000ff\""##), "{json}");
assert!(!json.contains("color{"), "{json}");
}
#[test]
fn page_numbers_follow_the_page_counter() {
let offset = preview_json("\\setcounter{page}{5}\n\nAlpha\n\n\\newpage\n\nBeta")