Reserve hspace width in running text

This commit is contained in:
gloamxun committed 2026-10-26 04:28:03 +08:00
1 parent 090f389589
commit c290b6f38d
3 files changed
+74 -3

No files matched your search

+71
View File
@@ -6952,6 +6952,56 @@ fn expand_ensuremath_plain(text: &str) -> String {
out
}
fn expand_hspace_plain(text: &str) -> String {
let mut out = String::new();
let mut rest = text;
while let Some(index) = rest.find("\\hspace") {
out.push_str(&rest[..index]);
let after_command = &rest[index + "\\hspace".len()..];
let after_star = after_command
.trim_start()
.strip_prefix('*')
.unwrap_or(after_command);
let Some((body, used)) = braced_group(after_star.trim_start()) else {
out.push_str(&rest[index..]);
return out;
};
out.push_str("$\\hspace{");
out.push_str(body);
out.push_str("}$");
rest = &after_star.trim_start()[used..];
}
out.push_str(rest);
out
}
fn expand_hspace(text: &str) -> String {
let mut out = String::new();
let mut rest = text;
let mut math_mode = false;
while !rest.is_empty() {
if math_mode {
if let Some(position) = rest.find('$') {
out.push_str(&rest[..=position]);
rest = &rest[position + 1..];
math_mode = false;
} else {
out.push_str(rest);
break;
}
} else if let Some(position) = rest.find('$') {
out.push_str(&expand_hspace_plain(&rest[..position]));
out.push('$');
rest = &rest[position + 1..];
math_mode = true;
} else {
out.push_str(&expand_hspace_plain(rest));
break;
}
}
out
}
/// Expand `\\ensuremath{...}` outside math mode into an inline math run.
fn expand_ensuremath(text: &str) -> String {
let mut out = String::new();
@@ -9048,6 +9098,7 @@ fn build_document_with_labels(
text = strip_noop_commands(&text);
text = strip_box_commands(&text);
text = expand_ensuremath(&text);
text = expand_hspace(&text);
if let Some((color, rest)) = color_switch(&text) {
text = format!("\\textcolor{{{color}}}{{{rest}}}");
}
@@ -13112,6 +13163,26 @@ A definition.
assert_eq!(runs[0].3, "Boxed");
}
#[test]
fn hspace_keeps_its_math_width() {
let blocks = paragraphs("A \\hspace{2em} B").expect("paragraphs");
let document = build_document(&blocks, &PageGeometry::default());
let engine = Engine::layout(&document);
let mut positions = Vec::new();
for page in engine.pages() {
for item in page.display_list().items {
if let texrra_tex_core::render::DisplayItem::Text { text, x, .. } = item {
if text == "A" || text == "B" {
positions.push((text, x));
}
}
}
}
let a = positions.iter().find(|(text, _)| text == "A").expect("A").1;
let b = positions.iter().find(|(text, _)| text == "B").expect("B").1;
assert!(b - a > 1_200_000, "gap {}", b - a);
}
#[test]
fn more_text_symbols_expand() {
let preview = preview_json(