Parse declaration groups in inline styled text

This commit is contained in:
gloamxun committed 2026-10-24 02:12:29 +08:00
1 parent 53fabe95db
commit 0e8999671b
3 files changed
+155 -58

No files matched your search

+152 -55
View File
@@ -1070,69 +1070,130 @@ fn nfss_font(raw: &str) -> Option<(ParagraphFont, String)> {
/// Split a paragraph containing inline style commands into styled runs.
///
/// Only whole-group commands are recognised (`\textbf{...}` and friends); the
/// braces are removed and their contents become a run in the requested face.
/// Handles `\textbf{...}`-style wrappers, declaration groups such as
/// `{\bfseries ...}` and arbitrary nesting of both, including braces inside a
/// group. Plain text inherits the surrounding face.
fn inline_runs(text: &str, base: ParagraphFont) -> Option<Vec<(ParagraphFont, String)>> {
const COMMANDS: [(&str, Option<ParagraphFont>); 11] = [
("\\textbf", Some(ParagraphFont::Bold)),
("\\emph", Some(ParagraphFont::Italic)),
("\\textit", Some(ParagraphFont::Italic)),
("\\textsl", Some(ParagraphFont::Italic)),
("\\texttt", Some(ParagraphFont::Mono)),
("\\textsf", Some(ParagraphFont::Sans)),
("\\textmd", None),
("\\textnormal", None),
("\\textup", None),
("\\textrm", None),
("\\textsc", None),
];
let mut runs: Vec<(ParagraphFont, String)> = Vec::new();
let mut plain = String::new();
let mut rest = text;
let mut runs = Vec::new();
let mut found = false;
loop {
let mut next: Option<(usize, usize, Option<ParagraphFont>)> = None;
for (command, font) in COMMANDS {
let Some(position) = rest.find(command) else {
continue;
};
let after = &rest[position + command.len()..];
if !after.starts_with('{') {
continue;
}
if next.is_none_or(|(best, _, _)| position < best) {
next = Some((position, command.len(), font));
}
}
let Some((position, length, font)) = next else {
break;
};
let body_start = position + length + 1;
let Some(offset) = rest[body_start..].find('}') else {
break;
};
let body_end = body_start + offset;
plain.push_str(&rest[..position]);
if !plain.is_empty() {
runs.push((base, std::mem::take(&mut plain)));
}
let body = &rest[body_start..body_end];
if !body.is_empty() {
runs.push((font.unwrap_or(base), body.to_string()));
}
rest = &rest[body_end + 1..];
found = true;
}
parse_runs(text, base, &mut runs, &mut found);
if !found {
return None;
}
plain.push_str(rest);
if !plain.is_empty() {
runs.push((base, plain));
}
Some(runs)
}
fn push_run(runs: &mut Vec<(ParagraphFont, String)>, font: ParagraphFont, text: &str) {
if text.is_empty() {
return;
}
if let Some((last_font, last_text)) = runs.last_mut()
&& *last_font == font
{
last_text.push_str(text);
return;
}
runs.push((font, text.to_string()));
}
/// Match a balanced `{...}` at the start of `rest`, returning its contents and
/// the number of bytes consumed (including both braces).
fn braced_group(rest: &str) -> Option<(&str, usize)> {
if !rest.starts_with('{') {
return None;
}
let mut depth = 0usize;
for (offset, character) in rest.char_indices() {
match character {
'{' => depth += 1,
'}' => {
depth -= 1;
if depth == 0 {
return Some((&rest[1..offset], offset + 1));
}
}
_ => {}
}
}
None
}
const INLINE_COMMANDS: [(&str, Option<ParagraphFont>); 11] = [
("\\textbf", Some(ParagraphFont::Bold)),
("\\emph", Some(ParagraphFont::Italic)),
("\\textit", Some(ParagraphFont::Italic)),
("\\textsl", Some(ParagraphFont::Italic)),
("\\texttt", Some(ParagraphFont::Mono)),
("\\textsf", Some(ParagraphFont::Sans)),
("\\textmd", None),
("\\textnormal", None),
("\\textup", None),
("\\textrm", None),
("\\textsc", None),
];
/// Match a styled wrapper command at the start of `rest`.
fn inline_wrapper(rest: &str) -> Option<(Option<ParagraphFont>, &str, usize)> {
for (command, font) in INLINE_COMMANDS {
let Some(after) = rest.strip_prefix(command) else {
continue;
};
if let Some((inner, length)) = braced_group(after) {
return Some((font, inner, command.len() + length));
}
}
None
}
fn parse_runs(
text: &str,
font: ParagraphFont,
runs: &mut Vec<(ParagraphFont, String)>,
found: &mut bool,
) {
let mut index = 0;
while index < text.len() {
let rest = &text[index..];
if let Some((inner, length)) = braced_group(rest) {
let (inner_font, inner_text) = match nfss_font(inner) {
Some((declared, body)) => (declared, body),
None => (font, inner.to_string()),
};
if nfss_font(inner).is_some() {
*found = true;
}
parse_runs(&inner_text, inner_font, runs, found);
index += length;
continue;
}
if let Some((wrapper_font, inner, length)) = inline_wrapper(rest) {
*found = true;
parse_runs(inner, wrapper_font.unwrap_or(font), runs, found);
index += length;
continue;
}
if rest.starts_with('\\') {
let step = rest
.char_indices()
.skip(1)
.find(|(_, character)| !character.is_ascii_alphabetic())
.map(|(offset, _)| offset.max(1))
.unwrap_or(rest.len());
push_run(runs, font, &rest[..step]);
index += step;
continue;
}
let step = rest
.char_indices()
.skip(1)
.find(|(_, character)| *character == '{' || *character == '\\')
.map(|(offset, _)| offset)
.unwrap_or(rest.len());
push_run(runs, font, &rest[..step]);
index += step;
}
}
fn parse_paragraph(raw: &str) -> SourceParagraph {
if let Some((font, body)) = nfss_font(raw) {
return SourceParagraph {
@@ -1954,6 +2015,42 @@ mod inline_tests {
}
#[test]
#[test]
fn declaration_groups_switch_the_face() {
let runs = inline_runs("{\\bfseries bold} normal", ParagraphFont::Roman).expect("runs");
assert_eq!(
runs,
vec![
(ParagraphFont::Bold, "bold".to_string()),
(ParagraphFont::Roman, " normal".to_string()),
]
);
}
#[test]
fn nested_groups_recurse() {
let runs = inline_runs(
"{\\bfseries bold \\textit{italic} bold} plain",
ParagraphFont::Roman,
)
.expect("runs");
assert_eq!(
runs,
vec![
(ParagraphFont::Bold, "bold ".to_string()),
(ParagraphFont::Italic, "italic".to_string()),
(ParagraphFont::Bold, " bold".to_string()),
(ParagraphFont::Roman, " plain".to_string()),
]
);
}
#[test]
fn wrapper_groups_keep_nested_braces() {
let runs = inline_runs("\\textbf{a {b} c}", ParagraphFont::Roman).expect("runs");
assert_eq!(runs, vec![(ParagraphFont::Bold, "a b c".to_string())]);
}
fn styled_runs_paint_with_their_face() {
let document = Document::new(
550 * 65_536,