Nest list environments with depth-aware indentation

This commit is contained in:
gloamxun committed 2026-10-24 21:04:21 +08:00
1 parent 4ca3302367
commit ac1bf660af
4 files changed
+303 -103

No files matched your search

+299 -99
View File
@@ -1583,6 +1583,268 @@ fn theorem_block(raw: &str, definitions: &[TheoremDefinition]) -> Option<Vec<Sou
Some(vec![heading, statement])
}
/// Recognise a list environment chunk and return its kind and body.
fn list_environment(raw: &str) -> Option<(&'static str, &str)> {
for environment in ["itemize", "enumerate", "description"] {
let begin = format!("\\begin{{{environment}}}");
let end = format!("\\end{{{environment}}}");
if let Some(body) = raw
.trim()
.strip_prefix(&begin)
.and_then(|text| text.strip_suffix(&end))
{
return Some((environment, body));
}
}
None
}
/// Split a list body at top-level `\\item` commands, keeping nested lists
/// inside the item that contains them.
fn split_list_items(body: &str) -> Vec<&str> {
let bytes = body.as_bytes();
let mut items = Vec::new();
let mut start = None;
let mut environment_depth = 0_usize;
let mut brace_depth = 0_usize;
let mut index = 0;
while index < bytes.len() {
match bytes[index] {
b'{' => {
brace_depth += 1;
index += 1;
continue;
}
b'}' => {
brace_depth = brace_depth.saturating_sub(1);
index += 1;
continue;
}
b'\\' => {
let rest = &body[index..];
if rest.starts_with("\\begin{") {
environment_depth += 1;
index += "\\begin{".len();
continue;
}
if rest.starts_with("\\end{") {
environment_depth = environment_depth.saturating_sub(1);
index += "\\end{".len();
continue;
}
if environment_depth == 0 && brace_depth == 0 && rest.starts_with("\\item") {
let after = index + "\\item".len();
let boundary = rest["\\item".len()..]
.chars()
.next()
.is_none_or(|character| !character.is_ascii_alphabetic());
if boundary {
if let Some(previous) = start {
items.push(&body[previous..index]);
}
start = Some(after);
index = after;
continue;
}
}
}
_ => {}
}
index += 1;
}
if let Some(previous) = start {
items.push(&body[previous..]);
}
items
}
/// Split item text into the part before a nested list, the nested list itself
/// and the continuation after it.
fn split_nested_list(text: &str) -> (String, Option<String>, String) {
let candidates = [
"\\begin{itemize}",
"\\begin{enumerate}",
"\\begin{description}",
];
let Some((start, environment)) = candidates
.iter()
.filter_map(|begin| {
let environment = begin.trim_start_matches("\\begin{").trim_end_matches('}');
text.find(begin).map(|index| (index, environment))
})
.min_by_key(|(index, _)| *index)
else {
return (text.to_string(), None, String::new());
};
let begin = format!("\\begin{{{environment}}}");
let end = format!("\\end{{{environment}}}");
let after_begin = start + begin.len();
let mut depth = 1_usize;
let mut cursor = after_begin;
while depth > 0 {
let next_begin = text[cursor..].find(&begin).map(|offset| cursor + offset);
let next_end = text[cursor..].find(&end).map(|offset| cursor + offset);
match (next_begin, next_end) {
(Some(begin_index), Some(end_index)) if begin_index < end_index => {
depth += 1;
cursor = begin_index + begin.len();
}
(_, Some(end_index)) => {
depth -= 1;
cursor = end_index + end.len();
}
(_, None) => return (text.to_string(), None, String::new()),
}
}
(
text[..start].to_string(),
Some(text[start..cursor].to_string()),
text[cursor..].to_string(),
)
}
fn alphabetic_label(mut number: u32, upper: bool) -> String {
let mut label = String::new();
while number > 0 {
let digit = ((number - 1) % 26) as u8;
label.insert(0, (b'a' + digit) as char);
number = (number - 1) / 26;
}
if upper {
label.to_ascii_uppercase()
} else {
label
}
}
fn roman_label(number: u32) -> String {
const VALUES: [(u32, &str); 13] = [
(1000, "m"),
(900, "cm"),
(500, "d"),
(400, "cd"),
(100, "c"),
(90, "xc"),
(50, "l"),
(40, "xl"),
(10, "x"),
(9, "ix"),
(5, "v"),
(4, "iv"),
(1, "i"),
];
let mut value = number;
let mut label = String::new();
for (amount, glyph) in VALUES {
while value >= amount {
label.push_str(glyph);
value -= amount;
}
}
if label.is_empty() {
number.to_string()
} else {
label
}
}
fn enumerate_label(number: u32, depth: usize) -> String {
match depth % 4 {
1 => format!("({}) ", alphabetic_label(number, false)),
2 => format!("{}. ", roman_label(number)),
3 => format!("{}. ", alphabetic_label(number, true)),
_ => format!("{number}. "),
}
}
fn bullet_label(depth: usize) -> &'static str {
match depth % 3 {
1 => "– ",
2 => "* ",
_ => "• ",
}
}
fn list_paragraph(text: String, depth: usize) -> SourceParagraph {
SourceParagraph {
text,
font: ParagraphFont::Roman,
line_height: 12,
math: false,
left_skip: 12 * (depth as i64 + 1),
centered: false,
right_aligned: false,
space_before: 0,
space_stretch: 0,
space_shrink: 0,
page_break: false,
equation_number: None,
equation_tag: None,
equation_rows: Vec::new(),
align_centered: false,
heading_level: None,
heading_starred: false,
heading_number: None,
footnotes: Vec::new(),
theorem: None,
float: None,
font_size: None,
}
}
/// Lay out a list environment, recursing into lists nested in its items.
fn list_blocks(
raw: &str,
depth: usize,
_definitions: &[TheoremDefinition],
) -> Option<Vec<SourceParagraph>> {
let (environment, body) = list_environment(raw)?;
let mut blocks = Vec::new();
let mut number = 0_u32;
for item in split_list_items(body) {
let item = item.trim();
if item.is_empty() {
continue;
}
let (label, rest) = match environment {
"description" => {
let (term, rest) = item
.strip_prefix('[')
.and_then(|text| text.split_once(']'))
.map(|(term, rest)| (term.trim(), rest.trim()))
.unwrap_or(("", item));
if term.is_empty() {
(String::new(), rest)
} else {
(format!("{term} — "), rest)
}
}
"enumerate" => {
number += 1;
(enumerate_label(number, depth), item)
}
_ => (bullet_label(depth).to_string(), item),
};
let (before, nested, after) = split_nested_list(rest);
if !before.trim().is_empty() {
blocks.push(list_paragraph(format!("{label}{}", before.trim()), depth));
}
if let Some(nested) = nested {
if let Some(nested_blocks) = list_blocks(&nested, depth + 1, _definitions) {
blocks.extend(nested_blocks);
}
}
if !after.trim().is_empty() {
blocks.push(list_paragraph(after.trim().to_string(), depth));
}
}
if blocks.is_empty() {
None
} else {
Some(blocks)
}
}
fn parse_blocks_raw(raw: &str, definitions: &[TheoremDefinition]) -> Vec<SourceParagraph> {
if let Some(block) = float_block(raw) {
return vec![block];
@@ -1670,56 +1932,8 @@ fn parse_blocks_raw(raw: &str, definitions: &[TheoremDefinition]) -> Vec<SourceP
block.right_aligned = right_aligned;
return vec![block];
}
for (environment, numbered) in [("itemize", false), ("enumerate", true)] {
let begin = format!("\\begin{{{environment}}}");
let finish = format!("\\end{{{environment}}}");
let Some(body) = raw
.strip_prefix(&begin)
.and_then(|text| text.strip_suffix(&finish))
else {
continue;
};
let mut number = 0;
let items: Vec<SourceParagraph> = body
.split("\\item")
.map(str::trim)
.filter(|item| !item.is_empty())
.map(|item| {
number += 1;
let prefix = if numbered {
format!("{number}. ")
} else {
"• ".to_string()
};
SourceParagraph {
text: format!("{prefix}{item}"),
font: ParagraphFont::Roman,
line_height: 12,
math: false,
left_skip: 12,
centered: false,
right_aligned: false,
space_before: 0,
space_stretch: 0,
space_shrink: 0,
page_break: false,
equation_number: None,
equation_tag: None,
equation_rows: Vec::new(),
align_centered: false,
heading_level: None,
heading_starred: false,
heading_number: None,
footnotes: Vec::new(),
theorem: None,
float: None,
font_size: None,
}
})
.collect();
if !items.is_empty() {
return items;
}
if let Some(blocks) = list_blocks(raw, 0, definitions) {
return blocks;
}
if let Some(body) = raw
.strip_prefix("\\begin{quote}")
@@ -1753,55 +1967,6 @@ fn parse_blocks_raw(raw: &str, definitions: &[TheoremDefinition]) -> Vec<SourceP
}];
}
}
if let Some(body) = raw
.strip_prefix("\\begin{description}")
.and_then(|text| text.strip_suffix("\\end{description}"))
{
let items: Vec<SourceParagraph> = body
.split("\\item")
.map(str::trim)
.filter(|item| !item.is_empty())
.map(|item| {
let (term, rest) = item
.strip_prefix('[')
.and_then(|text| text.split_once(']'))
.map(|(term, rest)| (term.trim(), rest.trim()))
.unwrap_or(("", item));
let text = if term.is_empty() {
rest.to_string()
} else {
format!("{term} — {rest}")
};
SourceParagraph {
text,
font: ParagraphFont::Roman,
line_height: 12,
math: false,
left_skip: 12,
centered: false,
right_aligned: false,
space_before: 0,
space_stretch: 0,
space_shrink: 0,
page_break: false,
equation_number: None,
equation_tag: None,
equation_rows: Vec::new(),
align_centered: false,
heading_level: None,
heading_starred: false,
heading_number: None,
footnotes: Vec::new(),
theorem: None,
float: None,
font_size: None,
}
})
.collect();
if !items.is_empty() {
return items;
}
}
vec![parse_paragraph(raw)]
}
@@ -3586,6 +3751,41 @@ See \ref{fig:a} and \ref{tab:b}.";
assert_eq!(document.units[2].source, "See 1 and 1.");
}
#[test]
fn nested_itemize_indents_and_relabels() {
let source = "\\begin{itemize}\n\\item Outer\n\\begin{itemize}\n\\item Inner\n\\end{itemize}\n\\end{itemize}";
let blocks = paragraphs(source).unwrap();
assert_eq!(
blocks.len(),
2,
"{:?}",
blocks.iter().map(|b| &b.text).collect::<Vec<_>>()
);
assert_eq!(blocks[0].text, "• Outer");
assert_eq!(blocks[0].left_skip, 12);
assert_eq!(blocks[1].text, "– Inner");
assert_eq!(blocks[1].left_skip, 24);
}
#[test]
fn nested_enumerate_uses_letter_labels() {
let source = "\\begin{enumerate}\n\\item First\n\\begin{enumerate}\n\\item Alpha\n\\item Beta\n\\end{enumerate}\n\\item Second\n\\end{enumerate}";
let blocks = paragraphs(source).unwrap();
let texts: Vec<&str> = blocks.iter().map(|block| block.text.as_str()).collect();
assert_eq!(texts, ["1. First", "(a) Alpha", "(b) Beta", "2. Second"]);
let skips: Vec<i64> = blocks.iter().map(|block| block.left_skip).collect();
assert_eq!(skips, [12, 24, 24, 12]);
}
#[test]
fn description_items_keep_their_terms() {
let source = "\\begin{description}\n\\item[Term] Definition\n\\end{description}";
let blocks = paragraphs(source).unwrap();
assert_eq!(blocks.len(), 1);
assert_eq!(blocks[0].text, "Term — Definition");
assert_eq!(blocks[0].left_skip, 12);
}
#[test]
fn newtheorem_definitions_are_captured() {
let source = "\\newtheorem{claim}[theorem]{Claim}\n\\newtheorem*{note}{Note}\n\\newtheorem{observation}{Observation}[section]\n\nBody.";