Honour definecolor models in text colors

This commit is contained in:
gloamxun committed 2026-10-26 02:28:05 +08:00
1 parent a888421f0e
commit 4cb456743a
4 files changed
+161 -32

No files matched your search

+157 -28
View File
@@ -185,6 +185,8 @@ struct PageGeometry {
counters: Vec<(String, u32)>,
/// Named lengths declared with `\newlength` and their current values.
lengths: Vec<(String, i64)>,
/// Colors declared with `\definecolor` and their RGB values.
colors: Vec<(String, [u8; 3])>,
/// Integer registers declared with `\newcount` and their current values.
count_registers: Vec<(String, i64)>,
/// Dimension registers declared with `\newdimen`, in scaled points.
@@ -1782,10 +1784,17 @@ fn strip_page_geometry(source: &str) -> (String, PageGeometry) {
}
}
}
if trimmed.starts_with("\\newcommand")
|| trimmed.starts_with("\\renewcommand")
|| trimmed.starts_with("\\providecommand")
|| trimmed.starts_with("\\def")
let is_macro_command = |command: &str| {
trimmed.strip_prefix(command).is_some_and(|rest| {
rest.starts_with('{')
|| rest.starts_with('\\')
|| rest.chars().next().is_some_and(char::is_whitespace)
})
};
if is_macro_command("\\newcommand")
|| is_macro_command("\\renewcommand")
|| is_macro_command("\\providecommand")
|| is_macro_command("\\def")
{
if let Some(definition) = macro_definition(trimmed) {
geometry.macros.push(definition);
@@ -1846,6 +1855,11 @@ fn strip_page_geometry(source: &str) -> (String, PageGeometry) {
.extend(graphics_path_groups(trimmed));
continue;
}
if let Some((name, rgb)) = define_color(trimmed) {
geometry.colors.retain(|(known, _)| known != &name);
geometry.colors.push((name, rgb));
continue;
}
if trimmed.starts_with("\\hypersetup") {
for (key, value) in hypersetup_values(trimmed) {
match key.as_str() {
@@ -5440,7 +5454,92 @@ fn strip_hrefs(text: &str) -> String {
output
}
fn named_color(name: &str) -> Option<[u8; 3]> {
fn color_byte(value: f64) -> u8 {
(value.clamp(0.0, 1.0) * 255.0).round() as u8
}
fn color_int(value: &str) -> Option<u8> {
let parsed = value.trim().parse::<i64>().ok()?;
Some(parsed.clamp(0, 255) as u8)
}
fn hex_pair(text: &str) -> Option<u8> {
u8::from_str_radix(text, 16).ok()
}
fn define_color(line: &str) -> Option<(String, [u8; 3])> {
let rest = line.trim_start().strip_prefix("\\definecolor")?;
let rest = rest.trim_start();
let (name, used) = braced_group(rest)?;
let rest = rest[used..].trim_start();
let (model, used) = braced_group(rest)?;
let rest = rest[used..].trim_start();
let (spec, _) = braced_group(rest)?;
let rgb = match model.trim() {
"rgb" => {
let parts: Vec<f64> = spec
.split(',')
.map(|part| part.trim().parse::<f64>().ok())
.collect::<Option<Vec<_>>>()?;
if parts.len() != 3 {
return None;
}
[
color_byte(parts[0]),
color_byte(parts[1]),
color_byte(parts[2]),
]
}
"RGB" => {
let parts: Vec<&str> = spec.split(',').collect();
if parts.len() != 3 {
return None;
}
[
color_int(parts[0])?,
color_int(parts[1])?,
color_int(parts[2])?,
]
}
"gray" => {
let level = color_byte(spec.trim().parse::<f64>().ok()?);
[level, level, level]
}
"HTML" => {
let digits = spec.trim();
if digits.len() != 6 {
return None;
}
[
hex_pair(&digits[0..2])?,
hex_pair(&digits[2..4])?,
hex_pair(&digits[4..6])?,
]
}
"cmyk" => {
let parts: Vec<f64> = spec
.split(',')
.map(|part| part.trim().parse::<f64>().ok())
.collect::<Option<Vec<_>>>()?;
if parts.len() != 4 {
return None;
}
let k = parts[3].clamp(0.0, 1.0);
[
color_byte((1.0 - parts[0].clamp(0.0, 1.0)) * (1.0 - k)),
color_byte((1.0 - parts[1].clamp(0.0, 1.0)) * (1.0 - k)),
color_byte((1.0 - parts[2].clamp(0.0, 1.0)) * (1.0 - k)),
]
}
_ => return None,
};
Some((name.trim().to_string(), rgb))
}
fn named_color(name: &str, custom: &[(String, [u8; 3])]) -> Option<[u8; 3]> {
if let Some((_, rgb)) = custom.iter().rev().find(|(known, _)| known == name) {
return Some(*rgb);
}
match name.trim().to_ascii_lowercase().as_str() {
"black" => Some([0, 0, 0]),
"white" => Some([255, 255, 255]),
@@ -5466,7 +5565,7 @@ fn named_color(name: &str) -> Option<[u8; 3]> {
}
/// Splits `\textcolor{name}{text}` runs out of a paragraph piece.
fn split_textcolor(text: &str) -> Vec<(Option<[u8; 3]>, String)> {
fn split_textcolor(text: &str, custom: &[(String, [u8; 3])]) -> Vec<(Option<[u8; 3]>, String)> {
let mut out = Vec::new();
let mut rest = text;
let mut plain = String::new();
@@ -5510,7 +5609,7 @@ fn split_textcolor(text: &str) -> Vec<(Option<[u8; 3]>, String)> {
rest = "";
break;
};
match named_color(name) {
match named_color(name, custom) {
Some(color) => {
if !plain.is_empty() {
out.push((None, std::mem::take(&mut plain)));
@@ -5535,6 +5634,7 @@ fn inline_math_segments(
text: &str,
base: ParagraphFont,
style: &ParagraphStyle,
custom: &[(String, [u8; 3])],
) -> Option<Vec<texrra_tex_core::paragraph::InlineSegment>> {
if style.font_size != 655_360 {
return None;
@@ -5547,7 +5647,7 @@ fn inline_math_segments(
for part in split_hrefs(text) {
match part {
HrefPart::Plain(piece) => {
for (color, chunk) in split_textcolor(&piece) {
for (color, chunk) in split_textcolor(&piece, custom) {
let runs = inline_styled_runs(&chunk, base)
.unwrap_or_else(|| vec![(base, style.font_size, 0, chunk.clone())]);
for (font, size, raise, run_text) in runs {
@@ -7612,28 +7712,29 @@ fn build_document_with_labels(
xspace_skip: geometry.xspace_skip,
};
let plain = strip_hrefs(&text);
let mut unit = match inline_math_segments(&text, paragraph.font, &style) {
Some(segments) => Unit::paragraph_with_style_and_segments(
index as u64,
text.clone(),
style.clone(),
segments,
),
None => match inline_runs(&plain, paragraph.font) {
Some(runs) => Unit::paragraph_with_style_and_runs(
let mut unit =
match inline_math_segments(&text, paragraph.font, &style, &geometry.colors) {
Some(segments) => Unit::paragraph_with_style_and_segments(
index as u64,
plain.clone(),
style,
runs,
text.clone(),
style.clone(),
segments,
),
None => Unit::paragraph_with_style_and_face(
index as u64,
plain,
style,
paragraph.font,
),
},
};
None => match inline_runs(&plain, paragraph.font) {
Some(runs) => Unit::paragraph_with_style_and_runs(
index as u64,
plain.clone(),
style,
runs,
),
None => Unit::paragraph_with_style_and_face(
index as u64,
plain,
style,
paragraph.font,
),
},
};
unit.space_before = paragraph.space_before;
unit.space_stretch = paragraph.space_stretch;
unit.space_shrink = paragraph.space_shrink;
@@ -9100,6 +9201,34 @@ a & b
assert_eq!(body.trim(), "Gap 4.5pt.");
}
#[test]
fn definecolor_models_produce_rgb_values() {
assert_eq!(
define_color("\\definecolor{red}{rgb}{1,0,0}"),
Some(("red".to_string(), [255, 0, 0]))
);
assert_eq!(
define_color("\\definecolor{accent}{HTML}{336699}"),
Some(("accent".to_string(), [0x33, 0x66, 0x99]))
);
assert_eq!(
define_color("\\definecolor{grey}{gray}{0.5}"),
Some(("grey".to_string(), [128, 128, 128]))
);
assert_eq!(
define_color("\\definecolor{ink}{cmyk}{0,0,0,1}"),
Some(("ink".to_string(), [0, 0, 0]))
);
}
#[test]
fn definecolor_colors_are_used_by_textcolor() {
let json = preview_json("\\definecolor{accent}{HTML}{336699}\n\n\\textcolor{accent}{Deep}")
.expect("preview");
assert!(json.contains(r##"fill=\"#336699\""##), "{json}");
assert!(!json.contains("definecolor"), "{json}");
}
#[test]
fn color_switch_paints_the_rest_of_the_paragraph() {
let json = preview_json("\\color{blue} Blue text.").expect("preview");