Merge pull request #1754 from alehel/port/odt-list-item-paragraphs

craft-odf, -flow, -html, -markdown: a list item's further paragraphs stay paragraphs
This commit is contained in:
FredApps authored and GitHub committed 2026-11-26 10:53:01 +01:00
commit 64f56ab28b
17 files changed
+850 -64

No files matched your search

Generated
+2
View File
@@ -3467,6 +3467,8 @@ dependencies = [
"base64 0.23.1",
"chrono",
"craft-flow",
"craft-html",
"craft-markdown",
"craft-math",
"craft-metafile",
"craft-wordmodel",
+2
View File
@@ -229,6 +229,8 @@ fn every_para_prop_round_trips() {
fmt_change: None,
snap_to_grid: Some(false),
text_alignment: Some(TextAlignment::Top),
// A list item's further paragraph: WordprocessingML has no such paragraph.
list_item: None,
};
let variants = [
ParaProps { line_spacing: Some(LineSpacing::AtLeast(14.0)), indent_first: Some(24.0), align: Some(Align::Center), ..Default::default() },
+48 -2
View File
@@ -529,6 +529,7 @@ fn flow_paras_in(doc: &Document, p: &Paragraph, opts: FlowOpts) -> Vec<Para> {
wrap: None,
index: None,
group: None,
item: p.props.list_item.filter(|_| list.is_none()).map(|l| l.min(8)),
};
if opts.paras {
out.extra = para_extra(doc, &p.props);
@@ -579,6 +580,8 @@ fn flow_paras_in(doc: &Document, p: &Paragraph, opts: FlowOpts) -> Vec<Para> {
wrap: None,
index: None,
group: None,
// A list item's further paragraph, each piece of it.
item: out.item,
};
let prev = std::mem::replace(&mut out, next);
if prev.inlines.is_empty() {
@@ -952,9 +955,50 @@ fn kept_index(doc: &Document, bl: &Blocks, i: usize) -> Option<(usize, std::sync
(paras.len() == *n && craft_wordmodel::kept::run_fingerprint(paras.into_iter()) == *run).then(|| (*n, xml.clone()))
}
/// Where the text of each level's last numbered paragraph starts, points.
type ItemText = [Option<f32>; 9];
/// The flow paragraphs of `p`, a list item's further paragraph only while it still sits at its
/// item's text: one moved out of it (Enter, then Decrease Indent to the margin, the ruler, the
/// Paragraph dialog…) is body text after the list. Asked of the paragraph itself, so whichever
/// command moved it, the paragraph is where it shows.
fn flow_paras_at(doc: &Document, p: &Paragraph, opts: FlowOpts, at: &mut ItemText) -> Vec<Para> {
let rp = doc.styles.resolve_para(&p.props);
// (Its own indent, or its style's.)
let left = rp.indent_left;
let mut paras = flow_paras_in(doc, p, opts);
if let Some(n) = rp.numbering.filter(|n| n.num != 0) {
// The paragraph's own indent, else its level's, else its style's (as Word places it).
let level = doc.numbering.level(n.num, n.level).map(|l| l.indent);
// Nonzero character indents override point indents, including an explicit zero.
let text = if rp.indent_chars[0] != 0.0 { left } else { p.props.indent_left.or(level).unwrap_or(left) };
if let Some(t) = at.get_mut(usize::from(n.level)) {
*t = Some(text);
}
} else if let Some(l) = p.props.list_item {
// Before any numbered paragraph, an explicit header has no prior baseline to outdent from.
let kept = match at.get(usize::from(l)).copied().flatten() {
Some(text) => left >= text - 0.5,
None => true,
};
if !kept {
for q in &mut paras {
q.item = None;
}
// Moved out of its item, it is body text: the lists before it have ended.
*at = [None; 9];
}
} else {
// Body text: the lists before it have ended, and where their items' text was with them.
*at = [None; 9];
}
paras
}
fn flow_blocks(doc: &Document, bl: &Blocks, depth: usize, tracked: FlowOpts) -> Vec<FBlock> {
let mut out = Vec::new();
let mut skip = 0usize;
let mut at: ItemText = [None; 9];
for (i, b) in bl.iter().enumerate() {
if skip > 0 {
skip -= 1;
@@ -969,7 +1013,7 @@ fn flow_blocks(doc: &Document, bl: &Blocks, depth: usize, tracked: FlowOpts) ->
let from = out.len();
for b in bl.get(i..i + ix.0).unwrap_or(&[]) {
if let Block::Para(p) = &**b {
out.extend(flow_paras_in(doc, p, tracked).into_iter().map(FBlock::Para));
out.extend(flow_paras_at(doc, p, tracked, &mut at).into_iter().map(FBlock::Para));
}
}
let n = out.len() - from;
@@ -980,7 +1024,7 @@ fn flow_blocks(doc: &Document, bl: &Blocks, depth: usize, tracked: FlowOpts) ->
continue;
}
match &**b {
Block::Para(p) => out.extend(flow_paras_in(doc, p, tracked).into_iter().map(FBlock::Para)),
Block::Para(p) => out.extend(flow_paras_at(doc, p, tracked, &mut at).into_iter().map(FBlock::Para)),
Block::Table(t) if depth < MAX_DEPTH => out.push(FBlock::Table(flow_table(doc, t, depth, tracked))),
Block::Table(t) => {
for r in &t.rows {
@@ -1105,6 +1149,8 @@ fn with_cell_text(doc: &Document, blocks: &Blocks, chr: &CharProps, align: Optio
if !table.is_empty() {
let mut props = doc.styles.table_para_patch(&p.props, &table);
props.overlay(&p.props);
// Direct only, so no overlay carries it: a list item's further paragraph stays one.
props.list_item = p.props.list_item;
p.props = props;
}
Arc::new(Block::Para(p))
+146
View File
@@ -26,6 +26,7 @@ mod media;
pub mod odf_object;
mod to_doc;
mod types;
pub use types::continues_list;
pub use color::parse_color;
pub use from_doc::{
@@ -210,4 +211,149 @@ mod tests {
p.trim();
assert_eq!(p.inlines, vec![Inline::Text("a ".into(), i), Inline::Text("b".into(), b)]);
}
/// Paragraphs of `text` in order, each with its props set by `set`.
fn doc_of(paras: &[(&str, &dyn Fn(&mut craft_wordmodel::ParaProps))]) -> craft_wordmodel::Document {
let mut doc = craft_wordmodel::Document::new();
doc.body = paras
.iter()
.map(|(t, set)| {
let mut p = craft_wordmodel::Paragraph::with_text(t, Default::default());
set(&mut p.props);
std::sync::Arc::new(craft_wordmodel::Block::Para(p))
})
.collect();
doc
}
/// The text and `item` of each flow paragraph, a table cell's included.
fn items(blocks: &[FBlock]) -> Vec<(String, Option<u8>)> {
let mut out = Vec::new();
for b in blocks {
match b {
FBlock::Para(p) => out.push((p.text(), p.item)),
FBlock::Table(t) => {
for c in t.rows.iter().flatten() {
out.extend(items(&c.blocks));
}
}
}
}
out
}
#[test]
fn character_indents_set_the_list_continuation_baseline() {
let mut doc = craft_wordmodel::Document::new();
let num = std::sync::Arc::make_mut(&mut doc.numbering).add_list(craft_wordmodel::ListKind::Numbered);
let numbered = move |p: &mut craft_wordmodel::ParaProps| {
p.numbering = Some(NumRef { num, level: 0 });
p.indent_left = Some(0.0);
p.indent_left_chars = Some(6.0);
};
let outdented = |p: &mut craft_wordmodel::ParaProps| {
p.list_item = Some(0);
p.indent_left = Some(0.0);
};
doc.body = doc_of(&[("One", &numbered), ("Out", &outdented)]).body;
let got = items(&from_doc(&doc).blocks);
assert_eq!(got.iter().find(|r| r.0 == "Out").map(|r| r.1), Some(None));
}
#[test]
fn a_zero_indent_header_keeps_its_explicit_list_membership() {
let header = |p: &mut craft_wordmodel::ParaProps| {
p.list_item = Some(0);
p.indent_left = Some(0.0);
};
let doc = doc_of(&[("Header", &header)]);
assert_eq!(items(&from_doc(&doc).blocks), [("Header".into(), Some(0))]);
}
/// A list item's further paragraph cut by a page break is that paragraph on both pages: the
/// text after the break stays in the item too.
#[test]
fn a_further_paragraph_stays_in_its_item_past_a_page_break() {
let cont = |p: &mut craft_wordmodel::ParaProps| {
p.list_item = Some(0);
p.indent_left = Some(36.0);
};
let doc = doc_of(&[("Before\u{c}After", &cont)]);
let got = items(&from_doc(&doc).blocks);
assert_eq!(got, [("Before".to_string(), Some(0)), ("After".to_string(), Some(0))], "{got:?}");
}
/// Body text ends the lists before it: a list starting with a header (no number) at its text
/// is a list's paragraph however far an earlier list's text was indented.
#[test]
fn a_list_header_after_body_text_is_in_its_list() {
let mut doc = craft_wordmodel::Document::new();
let num = std::sync::Arc::make_mut(&mut doc.numbering).add_list(craft_wordmodel::ListKind::Numbered);
let numbered = move |p: &mut craft_wordmodel::ParaProps| {
p.numbering = Some(NumRef { num, level: 0 });
p.indent_left = Some(72.0);
};
let header = |p: &mut craft_wordmodel::ParaProps| {
p.list_item = Some(0);
p.indent_left = Some(36.0);
};
let numbered_36 = move |p: &mut craft_wordmodel::ParaProps| {
p.numbering = Some(NumRef { num, level: 0 });
p.indent_left = Some(36.0);
};
let body = doc_of(&[("One", &numbered), ("Body", &|_| {}), ("Header", &header), ("Two", &numbered_36)]).body;
doc.body = body;
let got = items(&from_doc(&doc).blocks);
assert_eq!(got.iter().find(|r| r.0 == "Header").map(|r| r.1), Some(Some(0)), "{got:?}");
}
/// A further paragraph moved out of its item (to the margin) is body text: a list starting with
/// a header after it, less indented than the list before, keeps the header in its list.
#[test]
fn a_list_header_after_an_outdented_further_paragraph_is_in_its_list() {
let mut doc = craft_wordmodel::Document::new();
let num = std::sync::Arc::make_mut(&mut doc.numbering).add_list(craft_wordmodel::ListKind::Numbered);
let numbered = move |p: &mut craft_wordmodel::ParaProps| {
p.numbering = Some(NumRef { num, level: 0 });
p.indent_left = Some(72.0);
};
let outdented = |p: &mut craft_wordmodel::ParaProps| {
p.list_item = Some(0);
p.indent_left = Some(0.0);
};
let header = |p: &mut craft_wordmodel::ParaProps| {
p.list_item = Some(0);
p.indent_left = Some(36.0);
};
let numbered_36 = move |p: &mut craft_wordmodel::ParaProps| {
p.numbering = Some(NumRef { num, level: 0 });
p.indent_left = Some(36.0);
};
let body = doc_of(&[("One", &numbered), ("Out", &outdented), ("Header", &header), ("Two", &numbered_36)]).body;
doc.body = body;
let got = items(&from_doc(&doc).blocks);
assert_eq!(got.iter().find(|r| r.0 == "Out").map(|r| r.1), Some(None), "{got:?}");
assert_eq!(got.iter().find(|r| r.0 == "Header").map(|r| r.1), Some(Some(0)), "{got:?}");
}
/// A list item's further paragraph in a table cell a table style formats stays one.
#[test]
fn a_further_paragraph_in_a_styled_cell_stays_in_its_item() {
let cont = |p: &mut craft_wordmodel::ParaProps| {
p.list_item = Some(0);
p.indent_left = Some(36.0);
};
let mut doc = craft_wordmodel::Document::new();
// Table Grid: paragraph formatting of its own (no space after, single spacing).
let mut t = craft_wordmodel::table::Table::new(1, 1, 200.0);
if let Some(c) = t.rows.first_mut().and_then(|r| r.cells.first_mut()) {
c.blocks = doc_of(&[("Cont", &cont)]).body;
}
doc.body = vec![
std::sync::Arc::new(craft_wordmodel::Block::Table(t)),
std::sync::Arc::new(craft_wordmodel::Block::Para(craft_wordmodel::Paragraph::new())),
];
let got = items(&from_doc_with(&doc, FlowOpts { paras: true, ..Default::default() }).blocks);
assert_eq!(got.iter().find(|r| r.0 == "Cont").map(|r| r.1), Some(Some(0)), "{got:?}");
}
}
+20 -2
View File
@@ -158,6 +158,9 @@ fn para_props(p: &Para, list_num: Option<u32>) -> ParaProps {
}
out.numbering = Some(NumRef { num, level: li.level.min(8) });
}
if p.list.is_none() {
out.list_item = p.item.map(|l| l.min(8));
}
out.align = p.align;
if p.rtl {
out.bidi = Some(true);
@@ -766,6 +769,12 @@ impl<'a> Builder<'a> {
fn blocks(&mut self, blocks: &[FBlock], depth: usize) -> Blocks {
let mut out = Blocks::new();
// Each list the source numbers, all of it in these blocks: a run of it after a paragraph
// it doesn't number may be the first to use a level.
let mut of_list: std::collections::HashMap<u32, Vec<ListInfo>> = std::collections::HashMap::new();
for li in blocks.iter().filter_map(|b| if let FBlock::Para(p) = b { p.list } else { None }).filter(|li| li.list != 0) {
of_list.entry(li.list).or_default().push(li);
}
let mut i = 0;
while let Some(b) = blocks.get(i) {
match b {
@@ -779,7 +788,14 @@ impl<'a> Builder<'a> {
let mut top: Option<bool> = None;
let id = p.list.map_or(0, |l| l.list);
while let Some(FBlock::Para(q)) = blocks.get(j) {
let Some(li) = q.list else { break };
let Some(li) = q.list else {
// An item's further paragraph is in the list: it goes on after it.
if super::continues_list(blocks, j).is_some() {
j += 1;
continue;
}
break;
};
if li.list != id {
break;
}
@@ -795,7 +811,9 @@ impl<'a> Builder<'a> {
let num = match self.lists.get(&id) {
Some(num) if id != 0 => *num,
_ => {
let num = self.new_list(&group);
// First met here, so this is the only time it's asked for.
let all = if id == 0 { group } else { of_list.remove(&id).unwrap_or(group) };
let num = self.new_list(&all);
if id != 0 {
self.lists.insert(id, num);
}
+14
View File
@@ -716,6 +716,9 @@ pub struct Para {
pub index: Option<Box<(std::sync::Arc<str>, usize)>>,
/// The group of paragraphs its markup kept as read belongs to (see [`Group`]).
pub group: Option<Box<Group>>,
/// A list item's further paragraph, with no number of its own (`list` is `None`): the level
/// of the item it belongs to.
pub item: Option<u8>,
}
/// Paragraphs whose markup kept as read ties them together (a comment from one to another, a
@@ -1107,3 +1110,14 @@ pub fn ruby_as_text(inlines: &[Inline]) -> std::borrow::Cow<'_, [Inline]> {
pub fn clean_text(s: &str) -> String {
s.chars().filter(|c| *c != OBJ && (!c.is_control() || matches!(c, '\t' | '\n' | '\u{000C}' | '\u{000E}'))).collect()
}
/// Whether the paragraph at `i` in `blocks` is a list item's further paragraph, and the level of
/// its item: HTML and Markdown keep it in its item, so the list doesn't start again after it.
/// A plain paragraph or a heading (ODF's `text:h` may sit in a list item); the writers have no
/// way to put the other kinds in an item.
pub fn continues_list(blocks: &[FBlock], i: usize) -> Option<u8> {
match blocks.get(i) {
Some(FBlock::Para(p)) if p.list.is_none() && matches!(p.kind, Kind::Normal | Kind::Heading(_)) => p.item.map(|l| l.min(8)),
_ => None,
}
}
+13 -1
View File
@@ -433,7 +433,19 @@ fn blocks_html(blocks: &[FBlock], out: &mut String, depth: usize, spaced: bool)
// Nested lists from consecutive list paragraphs.
let mut stack: Vec<(bool, bool)> = Vec::new(); // (ordered, li open)
while let Some(FBlock::Para(q)) = blocks.get(i) {
let Some(li) = q.list else { break };
let Some(li) = q.list else {
// A list item's further paragraph, in its item (its sublists end first).
let Some(lv) = model::continues_list(blocks, i).map(usize::from) else { break };
while stack.len() > lv + 1 {
close_list(&mut stack, out);
}
if stack.len() != lv + 1 || !stack.last().is_some_and(|s| s.1) {
break;
}
out.push_str(&para_html(q, false));
i += 1;
continue;
};
let lv = li.level.min(8) as usize;
while stack.len() > lv + 1 {
close_list(&mut stack, out);
+34
View File
@@ -985,6 +985,18 @@ fn hostile_style_sheets_never_panic() {
}
}
/// A list item's further paragraph keeps its alignment (and page break) in its item.
#[test]
fn an_items_further_paragraph_keeps_its_alignment() {
let mut one = Para { list: Some(model::ListInfo { ordered: true, ..Default::default() }), ..Default::default() };
one.push_text("One", &Fmt::default());
let mut cont = Para { item: Some(0), align: Some(Align::Center), ..Default::default() };
cont.spacing.left = Some(36.0);
cont.push_text("Cont", &Fmt::default());
let html = export(&model::to_doc(&Flow { blocks: vec![FBlock::Para(one), FBlock::Para(cont)], meta: Meta::default() }));
assert!(html.contains("<li>One<p style=\"text-align:center\">Cont</p></li>"), "{html}");
}
#[test]
fn conflicting_mso_vmerge_declarations_last_wins() {
let html_restart_wins = "<table><tr><td style='mso-yfti-vmerge: continue; mso-yfti-vmerge: restart'>A</td></tr></table>";
@@ -2153,6 +2165,28 @@ fn the_fragment_spaces_only_top_level_paragraphs_and_headings() {
assert!(fragment.contains("<ul><li>Item</li></ul>"), "{fragment}");
}
/// A list item's further paragraph keeps its alignment and page break in the fragment, without
/// spacing or indents, as the item itself.
#[test]
fn the_fragment_leaves_a_list_items_further_paragraph_unspaced() {
let chr = craft_wordmodel::CharProps::default();
let mut d = Document::new();
let num = std::sync::Arc::make_mut(&mut d.numbering).add_list(craft_wordmodel::ListKind::Bullet);
let mut item = craft_wordmodel::Paragraph::with_text("Item", chr.clone()).styled("ListParagraph");
item.props.numbering = Some(craft_wordmodel::props::NumRef { num, level: 0 });
let mut more = craft_wordmodel::Paragraph::with_text("More", chr);
more.props.list_item = Some(0);
more.props.align = Some(craft_wordmodel::Align::Center);
more.props.page_break_before = Some(true);
more.props.indent_left = Some(72.0);
more.props.space_after = Some(6.0);
d.body = vec![craft_wordmodel::para_block(item), craft_wordmodel::para_block(more)];
let fragment = export_fragment(&d);
let more = fragment.split("<li>Item").nth(1).and_then(|s| s.split("</li>").next()).unwrap();
assert!(more.contains("More") && more.contains("text-align:center") && more.contains("break-before:page"), "{fragment}");
assert!(!fragment.contains("margin-"), "{fragment}");
}
/// Code blocks and the paragraphs of a table cell keep the fragment's plain markup, whatever their
/// spacing.
#[test]
+4
View File
@@ -14,3 +14,7 @@ workspace = true
craft-flow = { workspace = true }
craft-html = { workspace = true }
craft-wordmodel = { workspace = true }
[dev-dependencies]
# A test writes imported Markdown to HTML, to check a list stays one there.
craft-html = { workspace = true, features = ["flow"] }
+29 -6
View File
@@ -593,6 +593,19 @@ fn parse_quote(lines: &[String], i: &mut usize, depth: usize, level: u8, refs: &
&& p.kind == Kind::Normal
{
p.kind = Kind::Quote;
// A quoted list item's further paragraph: the writers keep only plain paragraphs in
// an item, so it joins the item's last paragraph with a line break, as a block in an
// item does, and the list goes on after it.
if p.item.is_some() {
p.item = None;
if let Some(FBlock::Para(prev)) = out.last_mut()
&& prev.list.is_some()
{
prev.push_text("\n", &Fmt::default());
prev.inlines.append(&mut p.inlines);
continue;
}
}
}
out.push(block);
}
@@ -682,21 +695,31 @@ fn parse_list(lines: &[String], mut i: usize, depth: usize, level: u8, out: &mut
}
for b in inner {
match b {
FBlock::Para(mut p) if p.list.is_none() => {
FBlock::Para(mut p) if p.list.is_none() && p.item.is_none() => {
if !placed {
p.list = Some(li);
placed = true;
out.push(FBlock::Para(p));
} else if p.kind == Kind::Normal {
// The item's further paragraph: one with no number, at the item's text.
p.item = Some(li.level);
p.spacing.left = Some((f32::from(li.level) + 1.0) * 36.0);
p.spacing.first = Some(0.0);
} else if let Some(FBlock::Para(prev)) = out.last_mut()
&& prev.list.is_some_and(|x| x.level == li.level)
&& (prev.list.is_some_and(|x| x.level >= li.level) || prev.item.is_some_and(|l| l >= li.level))
{
// A continuation paragraph joins the item with a line break.
// A code block, quote or heading in the item joins the item's last
// paragraph, a sublist's included, with a line break: it is no item of
// its own, and only a plain paragraph is read as a further one.
prev.push_text("\n", &Fmt::default());
prev.inlines.extend(p.inlines);
continue;
} else {
p.list = Some(li);
out.push(FBlock::Para(p));
// One after a table: no number either, at the item's text.
p.item = Some(li.level);
p.spacing.left = Some((f32::from(li.level) + 1.0) * 36.0);
p.spacing.first = Some(0.0);
}
out.push(FBlock::Para(p));
}
FBlock::Para(p) => {
if !placed {
+26
View File
@@ -335,6 +335,10 @@ pub(super) fn write_blocks(blocks: &[FBlock], out: &mut Vec<String>) {
let mut i = 0;
let mut counters = [0u32; 9];
let mut prev_list = false;
// How far each level's last item's text is indented (where its further paragraphs go), and
// the level of the last item.
let mut conts = [0usize; 9];
let mut prev_level = 0usize;
let mut prev_top_ordered = false;
while let Some(b) = blocks.get(i) {
match b {
@@ -365,6 +369,8 @@ pub(super) fn write_blocks(blocks: &[FBlock], out: &mut Vec<String>) {
}
FBlock::Para(p) => {
let body = inlines_md(&p.inlines);
// A further paragraph of an item still open: its level.
let in_item = model::continues_list(blocks, i).map(usize::from).filter(|lv| prev_list && *lv <= prev_level);
match p.list {
Some(li) => {
let lv = li.level.min(8) as usize;
@@ -387,6 +393,10 @@ pub(super) fn write_blocks(blocks: &[FBlock], out: &mut Vec<String>) {
let marker = if li.ordered { format!("{}.", n.unwrap_or(1)) } else { "-".to_string() };
let pad = " ".repeat(4 * lv);
let cont = " ".repeat(4 * lv + marker.len() + 1);
if let Some(c) = conts.get_mut(lv) {
*c = cont.len();
}
prev_level = lv;
let body = if p.kind == Kind::Code {
code_span(&p.text())
} else {
@@ -408,6 +418,22 @@ pub(super) fn write_blocks(blocks: &[FBlock], out: &mut Vec<String>) {
out.push(String::new());
}
}
// A list item's further paragraph: in its item, and the list goes on after it.
None if in_item.is_some() => {
let lv = in_item.unwrap_or_default();
prev_level = lv;
// A sublist after it is a new one.
for d in counters.iter_mut().skip(lv + 1) {
*d = 0;
}
let pad = " ".repeat(conts.get(lv).copied().unwrap_or(0));
let text = match p.kind {
Kind::Heading(n) => format!("{} {}", "#".repeat(n.clamp(1, 6) as usize), heading_text(&body)),
_ => escape_lines(body).replace("\\\n", &format!("\\\n{pad}")),
};
out.push(format!("{pad}{text}").trim_end().to_string());
out.push(String::new());
}
None => {
prev_list = false;
let line = match p.kind {
+87
View File
@@ -793,3 +793,90 @@ fn heading_trailing_hash_survives_round_trip() {
assert_eq!(export(&import(&md)), want, "second export of {src:?}");
}
}
/// A list item's further paragraph is read as a paragraph of its own in the item, with no number:
/// written and read again, it stays one, and the list goes on after it.
#[test]
fn an_items_further_paragraph_round_trips() {
let src = "1. One\n\n Cont\n\n2. Two\n - Sub\n\n More\n";
let shape = |d: &Document| {
d.body.iter().filter_map(|b| b.as_para()).map(|p| (p.text.clone(), p.props.numbering.map(|n| n.num), p.props.indent_left)).collect::<Vec<_>>()
};
let d = import(src);
let rows = shape(&d);
assert_eq!(rows.iter().map(|r| r.0.as_str()).collect::<Vec<_>>(), ["One", "Cont", "Two", "Sub", "More"], "{rows:?}");
for (t, at) in [("Cont", 36.0), ("More", 36.0)] {
let r = rows.iter().find(|r| r.0 == t).unwrap();
assert_eq!((r.1, r.2), (None, Some(at)), "{t}: no number, at the item's text: {rows:?}");
}
assert_eq!(rows[0].1, rows[2].1, "one list: {rows:?}");
let md = export(&d);
assert!(md.starts_with("1. One\n\n Cont\n\n2. Two\n"), "{md}");
assert!(md.contains("\n\n More"), "{md}");
assert_eq!(shape(&import(&md)), rows, "{md}");
// A numbered sublist after an item's further paragraph starts again.
let md = export(&import("1. One\n 1. a\n 2. b\n\n More\n\n 1. c\n"));
assert!(md.contains("\n 1. c"), "{md}");
}
/// A code block, quote or heading inside a list item is no item of its own: it gets no number,
/// and the list's next item keeps its number (#5723 review).
#[test]
fn a_block_inside_an_item_gets_no_number() {
let numbered =
|d: &Document| d.body.iter().filter_map(|b| b.as_para()).filter(|p| p.props.numbering.is_some()).map(|p| p.text.clone()).collect::<Vec<_>>();
for (src, last) in [
("1. Install:\n\n ```\n cargo build\n cargo test\n ```\n\n2. Run\n", "2. Run"),
("1. Install:\n\n > quoted\n\n2. Run\n", "2. Run"),
("1. Install:\n\n # Heading\n\n2. Run\n", "2. Run"),
("1. Install:\n\n Cont\n\n ```\n cargo build\n ```\n\n2. Run\n", "2. Run"),
] {
let d = import(src);
let rows = numbered(&d);
assert_eq!(rows.len(), 2, "{src:?}: two numbered items: {rows:?}");
assert!(rows[0].starts_with("Install:"), "{src:?}: {rows:?}");
assert_eq!(rows[1], "Run", "{src:?}: {rows:?}");
let md = export(&d);
assert!(md.contains(&format!("\n{last}")), "{src:?}: {md}");
assert!(!md.contains("3."), "{src:?}: {md}");
}
let d = import("1. Install:\n\n ```\n cargo build\n cargo test\n ```\n\n2. Run\n");
assert!(numbered(&d)[0].contains("cargo build") && numbered(&d)[0].contains("cargo test"), "the code stays in its item: {:?}", numbered(&d));
}
/// A code block, quote or heading after a sublist in an item stays in the list: the list's next
/// item keeps its number in Markdown and HTML (#5723 review).
#[test]
fn a_block_after_a_sublist_keeps_the_next_items_number() {
for src in
["1. a\n - sub\n\n ```\n code\n ```\n2. b\n", "1. a\n - sub\n\n > quoted\n\n2. b\n", "1. a\n - sub\n\n # Heading\n\n2. b\n"]
{
let d = import(src);
let text: String = d.body.iter().filter_map(|b| b.as_para()).map(|p| p.text.clone()).collect::<Vec<_>>().join("|");
for w in ["code", "quoted", "Heading"] {
if src.contains(w) {
assert!(text.contains(w), "{src:?}: the block's text stays: {text}");
}
}
let md = export(&d);
assert!(md.contains("\n2. b"), "{src:?}: {md}");
let html = craft_html::doc::export(&d);
assert_eq!(html.matches("<ol").count(), 1, "{src:?}: one list: {html}");
}
}
/// A quoted list item's further paragraph stays in its item: the list goes on after it, in the
/// quote, and keeps its numbers.
#[test]
fn a_quoted_items_further_paragraph_keeps_the_list() {
let d = import("> 1. One\n>\n> Cont\n>\n> 2. Two\n");
let nums: Vec<u32> = d.body.iter().filter_map(|b| b.as_para()).filter_map(|p| p.props.numbering.map(|n| n.num)).collect();
assert_eq!(nums.len(), 2, "{nums:?}");
assert_eq!(nums[0], nums[1], "one list: {nums:?}");
let text: String = d.body.iter().filter_map(|b| b.as_para()).map(|p| p.text.clone()).collect::<Vec<_>>().join("|");
assert!(text.contains("Cont"), "{text}");
let md = export(&d);
assert!(md.contains("> 2. Two") && !md.contains("> 1. Two"), "{md}");
let html = craft_html::doc::export(&d);
assert_eq!(html.matches("<ol").count(), 1, "one list: {html}");
}
+3
View File
@@ -63,6 +63,9 @@ optional = true
[dev-dependencies]
# The tests build archives, hostile ones included, by hand.
zip = { version = "9", default-features = false, features = ["deflate-flate2"] }
# The `text` tests export ODT input to HTML and Markdown, to check list items stay whole there.
craft-html = { workspace = true, features = ["flow"] }
craft-markdown = { workspace = true }
[target.'cfg(all(target_arch = "wasm32", target_os = "unknown"))'.dependencies]
# The browser clock for tracked-change dates (`text` feature; `SystemTime::now()` panics there).
+29 -15
View File
@@ -219,6 +219,16 @@ pub(super) struct Body<'a> {
next_comment: u32,
}
/// `p`, read as a list's paragraph, as one the list doesn't number (a list item's second paragraph,
/// a list header's): a paragraph of its own at the level's text indent.
fn unnumbered(p: &mut Para) {
let Some(li) = p.list.take() else { return };
let indent = li.label.and_then(|l| l.indent).map_or((f32::from(li.level) + 1.0) * 36.0, |i| f32::from(i) / 20.0);
p.spacing.left = p.spacing.left.or(Some(indent));
p.spacing.first = p.spacing.first.or(Some(0.0));
p.item = Some(li.level.min(8));
}
impl<'a> Body<'a> {
pub(super) fn new(styles: &'a Styles, pages: &'a Pages, zip: &'a mut dyn FnMut(&str) -> Option<Vec<u8>>) -> Self {
let page = pages.first.clone().unwrap_or_default();
@@ -417,6 +427,14 @@ impl<'a> Body<'a> {
{
p.index = Some(Box::new((std::sync::Arc::from(xml), n)));
}
// The list kept whole or not, an unnumbered paragraph's markup is only for it.
for b in blocks.iter_mut().skip(k.done) {
if let FBlock::Para(p) = b
&& p.list.is_none()
{
p.kept = None;
}
}
}
None
}
@@ -1057,21 +1075,15 @@ impl Body<'_> {
}
}
self.paras_done += 1;
let cont = std::mem::take(&mut self.para_cont);
let level = p.list.map(|l| l.level);
let c = self.container();
if cont
&& let Some(FBlock::Para(prev)) = c.last_mut()
&& prev.list.is_some()
&& prev.list.map(|l| l.level) == level
{
prev.push_text("\n", &Fmt::default());
prev.inlines.extend(p.inlines);
// Two elements made one paragraph: neither's markup is it.
prev.kept = None;
return;
if std::mem::take(&mut self.para_cont) {
unnumbered(&mut p);
// Its markup means nothing outside its list: only a list kept whole may keep it, and
// that is seen when the list ends.
if self.kept_list.is_none() {
p.kept = None;
}
}
c.push(FBlock::Para(p));
self.container().push(FBlock::Para(p));
}
fn push_text(&mut self, t: &str) {
@@ -1752,6 +1764,7 @@ impl Body<'_> {
}
}
"list-item" | "list-header" => {
let header = local(q) == "list-header";
// An item restarting the numbering begins a list of its own from there.
if let Some(v) = get(a, "text:start-value").and_then(|v| v.trim().parse::<u32>().ok()) {
self.list_id = self.new_list_id();
@@ -1761,8 +1774,9 @@ impl Body<'_> {
if let Some(l) = self.lists.last_mut() {
l.1 = true;
}
// A list header's paragraphs have no number (§5.3.3), as an item's after its first.
if let Some(u) = self.item_used.last_mut() {
*u = false;
*u = header;
}
}
_ => return false,
+313
View File
@@ -166,3 +166,316 @@ fn list_level_positions_are_read_and_written() {
assert_eq!((c.indent, c.hanging, c.align), (a.indent, a.hanging, a.align));
assert!((e.indent - b.indent).abs() < 0.01 && (e.hanging - b.hanging).abs() < 0.01);
}
#[test]
fn a_list_items_further_paragraphs_are_paragraphs_with_no_number() {
// LibreOffice writes an unnumbered entry as an item's second paragraph. It was joined to the
// first by a line break, losing its paragraph, and so the first's markup too.
let styles = format!(
r#"<office:document-styles {NS_T}><office:styles><text:list-style style:name="L"><text:list-level-style-number text:level="1" style:num-format="1"><style:list-level-properties text:list-level-position-and-space-mode="label-alignment"><style:list-level-label-alignment fo:margin-left="1in" fo:text-indent="-0.25in"/></style:list-level-properties></text:list-level-style-number></text:list-style></office:styles></office:document-styles>"#
);
let body = r#"<text:list text:style-name="L"><text:list-header><text:p>Header</text:p></text:list-header><text:list-item><text:p>One</text:p><text:p>Still one</text:p><text:p>And again</text:p></text:list-item><text:list-item><text:p>Two</text:p></text:list-item></text:list><text:p>After</text:p>"#;
let content = format!("<office:document-content {NS_T}><office:body><office:text>{body}</office:text></office:body></office:document-content>");
let shape = |d: &craft_wordmodel::Document| {
d.body.iter().filter_map(|b| b.as_para()).map(|p| (p.text.clone(), p.props.numbering.is_some(), p.props.indent_left)).collect::<Vec<_>>()
};
let d = import(&package(&content, Some(&styles))).unwrap();
let want = |a: &[(String, bool, Option<f32>)]| {
let row = |t: &str| a.iter().find(|r| r.0 == t).unwrap_or_else(|| panic!("{t} in {a:?}"));
assert_eq!(a.len(), 6, "each its own paragraph: {a:?}");
for t in ["Header", "Still one", "And again"] {
assert!(!row(t).1, "{t} has no number: {a:?}");
assert_eq!(row(t).2, Some(72.0), "{t} at the item's text: {a:?}");
}
for t in ["One", "Two"] {
assert!(row(t).1, "{t} is numbered: {a:?}");
}
assert!(!row("After").1);
};
want(&shape(&d));
// The numbers go on past the unnumbered paragraph: one list.
let nums: Vec<u32> = d.body.iter().filter_map(|b| b.as_para()).filter_map(|p| p.props.numbering.map(|n| n.num)).collect();
assert_eq!(nums.len(), 2);
assert_eq!(nums[0], nums[1], "{nums:?}");
// And so do they written from the model, and written as read.
for saved in [crate::text::tests::export_model(&d).unwrap(), export(&d).unwrap()] {
let back = import(&saved).unwrap();
want(&shape(&back));
assert_eq!(back.body.iter().filter_map(|b| b.as_para()).find(|p| p.text == "Header").unwrap().props.list_item, Some(0));
let nums: Vec<u32> = back.body.iter().filter_map(|b| b.as_para()).filter_map(|p| p.props.numbering.map(|n| n.num)).collect();
assert_eq!(nums[0], nums[1], "{nums:?}");
}
// Edited, an unnumbered paragraph is saved as edited, not as the list's kept markup said, and
// the list around it stays one.
for t in ["Header", "Still one"] {
let mut d = import(&package(&content, Some(&styles))).unwrap();
let i = d.body.iter().position(|b| b.as_para().is_some_and(|p| p.text == t)).unwrap();
d.insert_text(&craft_wordmodel::Pos::body(i, 0), "Edited ", &Default::default()).unwrap();
let back = import(&export(&d).unwrap()).unwrap();
let rows = shape(&back);
assert_eq!(rows.len(), 6, "each its own paragraph: {rows:?}");
assert!(!rows.iter().any(|r| r.0 == t), "{t} was edited: {rows:?}");
let row = rows.iter().find(|r| r.0 == format!("Edited {t}")).unwrap_or_else(|| panic!("the edit: {rows:?}"));
assert_eq!((row.1, row.2), (false, Some(72.0)), "{t}: no number, at the item's text: {rows:?}");
let nums: Vec<u32> = back.body.iter().filter_map(|b| b.as_para()).filter_map(|p| p.props.numbering.map(|n| n.num)).collect();
assert_eq!(nums.len(), 2, "{rows:?}");
assert_eq!(nums[0], nums[1], "{nums:?}");
}
}
/// A level first used after an unnumbered paragraph is still the file's: a bulleted sublist stays
/// bulleted, a numbered one under bullets stays numbered, read and written from the model.
#[test]
fn a_sublist_after_an_unnumbered_paragraph_keeps_its_levels() {
let open = |first: &str, second: &str| {
let styles = format!(
r#"<office:document-styles {NS_T}><office:styles><text:list-style style:name="L">{first}{second}</text:list-style></office:styles></office:document-styles>"#
);
let content = format!(
r#"<office:document-content {NS_T}><office:body><office:text><text:list text:style-name="L"><text:list-item><text:p>One</text:p><text:p>More</text:p><text:list><text:list-item><text:p>Sub</text:p></text:list-item></text:list></text:list-item></text:list></office:text></office:body></office:document-content>"#
);
import(&package(&content, Some(&styles))).unwrap()
};
let sub = |d: &Document| {
let p = d.body.iter().filter_map(|b| b.as_para()).find(|p| p.text == "Sub").unwrap();
let n = p.props.numbering.unwrap();
d.numbering.level(n.num, n.level).map(|l| (n.level, l.format, l.text.clone(), l.start)).unwrap()
};
let number = |level: u8, format: &str, start: u8| {
format!(r#"<text:list-level-style-number text:level="{level}" style:num-format="{format}" style:num-suffix="." text:start-value="{start}"/>"#)
};
let bullet = |level: u8| format!(r#"<text:list-level-style-bullet text:level="{level}" text:bullet-char="–"/>"#);
let d = open(&number(1, "1", 1), &bullet(2));
assert_eq!(sub(&d), (1, NumFormat::Bullet, "–".to_string(), 1));
assert_eq!(sub(&import(&crate::text::tests::export_model(&d).unwrap()).unwrap()), sub(&d), "written from the model");
let d = open(&bullet(1), &number(2, "i", 3));
let (level, format, _, start) = sub(&d);
assert_eq!((level, format, start), (1, NumFormat::LowerRoman, 3));
assert_eq!(sub(&import(&crate::text::tests::export_model(&d).unwrap()).unwrap()), sub(&d), "written from the model");
}
/// A list item's further paragraph stays in its item in HTML and Markdown: the list goes on after it.
#[test]
fn a_list_items_further_paragraph_stays_in_it_in_html_and_markdown() {
let styles = format!(
r#"<office:document-styles {NS_T}><office:styles><text:list-style style:name="L"><text:list-level-style-number text:level="1" style:num-format="1" style:num-suffix="."/></text:list-style></office:styles></office:document-styles>"#
);
let content = format!(
r#"<office:document-content {NS_T}><office:body><office:text><text:list text:style-name="L"><text:list-item><text:p>One</text:p><text:p>Cont</text:p></text:list-item><text:list-item><text:p>Two</text:p></text:list-item></text:list></office:text></office:body></office:document-content>"#
);
let d = import(&package(&content, Some(&styles))).unwrap();
let html = craft_html::doc::export(&d);
assert_eq!(html.matches("<ol").count(), 1, "{html}");
assert!(html.contains("<p>Cont</p>"), "{html}");
let md = craft_markdown::export(&d);
assert!(md.contains("1. One\n\n Cont\n\n2. Two"), "{md}");
}
/// Only a list item's own further paragraph stays in it: an indented paragraph between two lists
/// joined by `text:continue-list` ends the list, and a last item's further paragraph (a one-item
/// list's too) stays in it.
#[test]
fn only_an_items_own_further_paragraph_stays_in_it() {
let styles = format!(
r#"<office:document-styles {NS_T}><office:styles><text:list-style style:name="L"><text:list-level-style-number text:level="1" style:num-format="1" style:num-suffix="."/></text:list-style></office:styles></office:document-styles>"#
);
let open = |body: &str| {
// (An indent of its own: LibreOffice writes one as an automatic style.)
let auto = r#"<office:automatic-styles><style:style style:name="Ind" style:family="paragraph"><style:paragraph-properties fo:margin-left="0.5in" fo:text-indent="0in"/></style:style></office:automatic-styles>"#;
let content =
format!("<office:document-content {NS_T}>{auto}<office:body><office:text>{body}</office:text></office:body></office:document-content>");
import(&package(&content, Some(&styles))).unwrap()
};
// A paragraph of its own between two parts of one list.
let d = open(
r#"<text:list xml:id="a" text:style-name="L"><text:list-item><text:p>One</text:p></text:list-item></text:list><text:p text:style-name="Ind">Between</text:p><text:list text:continue-list="a" text:style-name="L"><text:list-item><text:p>Two</text:p></text:list-item></text:list>"#,
);
let between = d.body.iter().filter_map(|b| b.as_para()).find(|p| p.text == "Between").unwrap();
assert_eq!(between.props.indent_left, Some(36.0));
let html = craft_html::doc::export(&d);
assert_eq!(html.matches("<ol").count(), 2, "{html}");
assert!(!html.contains("<p>Between</p></li>") && !html.contains("<li>One<p>"), "{html}");
let md = craft_markdown::export(&d);
assert!(md.contains("\n\nBetween\n\n") && !md.contains(" Between"), "{md}");
// A last item's further paragraph, and a one-item list's.
for body in [
r#"<text:list text:style-name="L"><text:list-item><text:p>One</text:p></text:list-item><text:list-item><text:p>Two</text:p><text:p>Cont</text:p></text:list-item></text:list><text:p>After</text:p>"#,
r#"<text:list text:style-name="L"><text:list-item><text:p>Two</text:p><text:p>Cont</text:p></text:list-item></text:list><text:p>After</text:p>"#,
] {
let d = open(body);
let html = craft_html::doc::export(&d);
assert!(html.contains("<li>Two<p>Cont</p></li>"), "{html}");
let md = craft_markdown::export(&d);
assert!(md.contains("1. Two\n\n Cont\n\nAfter") || md.contains("2. Two\n\n Cont\n\nAfter"), "{md}");
}
}
/// Written from the model, a list item's further paragraph is in its `text:list-item`, after the
/// item's sublist, and the list stays one (#5723 review).
#[test]
fn a_further_paragraph_written_from_the_model_stays_in_its_item() {
let d = craft_markdown::import("1. One\n\n Cont\n - Sub\n\n More\n\n2. Two\n");
let xml = crate::text::tests::content_of(&crate::text::tests::export_model(&d).unwrap());
let one = xml.find(">One<").unwrap();
let body = xml.get(one..).unwrap();
assert!(body.contains("Cont</text:p><text:list>"), "{xml}");
assert!(body.contains("Sub</text:p></text:list-item></text:list><text:p"), "{xml}");
assert!(body.contains("More</text:p></text:list-item><text:list-item><text:p"), "{xml}");
assert_eq!(xml.matches("<text:list xml:id").count(), 1, "one list: {xml}");
let back = import(&crate::text::tests::export_model(&d).unwrap()).unwrap();
let rows: Vec<_> =
back.body.iter().filter_map(|b| b.as_para()).map(|p| (p.text.clone(), p.props.numbering.is_some(), p.props.list_item)).collect();
assert_eq!(
rows,
[
("One".to_string(), true, None),
("Cont".to_string(), false, Some(0)),
("Sub".to_string(), true, None),
("More".to_string(), false, Some(0)),
("Two".to_string(), true, None)
],
"{xml}"
);
}
/// A list item's further paragraph opening or closing a section kept as read ends the list there,
/// as an item doing so does: the section opens before it, or closes after it, not somewhere past.
#[test]
fn a_further_paragraph_opening_or_closing_a_section_ends_the_list_there() {
let styles = format!(
r#"<office:document-styles {NS_T}><office:styles><text:list-style style:name="L"><text:list-level-style-number text:level="1" style:num-format="1" style:num-suffix="."/></text:list-style></office:styles></office:document-styles>"#
);
let content = format!(
r#"<office:document-content {NS_T} {NS_X}><office:body><office:text><text:section text:name="S"><text:list xml:id="l1" text:style-name="L"><text:list-item><text:p>Zero</text:p></text:list-item><text:list-item><text:p>One</text:p><text:p>Cont</text:p></text:list-item></text:list></text:section><text:list text:style-name="L" text:continue-list="l1"><text:list-item><text:p>Two</text:p></text:list-item></text:list></office:text></office:body></office:document-content>"#
);
let mut d = import(&package(&content, Some(&styles))).unwrap();
// Edited, so the list is written from the model; the section's paragraphs are as read.
let i = d.body.iter().position(|b| b.as_para().is_some_and(|p| p.text == "One")).unwrap();
d.insert_text(&craft_wordmodel::Pos::body(i, 0), "Edited ", &Default::default()).unwrap();
let c = crate::text::tests::content_of(&export(&d).unwrap());
let (close, two) = (c.find("</text:section>"), c.find(">Two<"));
assert!(close.is_some() && two.is_some() && close < two, "the section closes before Two: {c}");
assert!(c.find(">Cont<") < close, "{c}");
// And one opening a section starts after the list: the section opens before it.
let content = format!(
r#"<office:document-content {NS_T} {NS_X}><office:body><office:text><text:list xml:id="l1" text:style-name="L"><text:list-item><text:p>One</text:p></text:list-item></text:list><text:section text:name="S"><text:list text:style-name="L" text:continue-list="l1"><text:list-header><text:p>Header</text:p></text:list-header><text:list-item><text:p>Two</text:p></text:list-item></text:list></text:section></office:text></office:body></office:document-content>"#
);
let mut d = import(&package(&content, Some(&styles))).unwrap();
let i = d.body.iter().position(|b| b.as_para().is_some_and(|p| p.text == "One")).unwrap();
d.insert_text(&craft_wordmodel::Pos::body(i, 0), "Edited ", &Default::default()).unwrap();
let c = crate::text::tests::content_of(&export(&d).unwrap());
let (open, header) = (c.find("<text:section"), c.find(">Header<"));
assert!(open.is_some() && header.is_some() && open < header, "the section opens before Header: {c}");
}
/// A heading (`text:h`) in a list item is one of its further paragraphs: it stays in its item in
/// HTML, Markdown and ODT written from the model, and the list numbers on after it.
#[test]
fn a_heading_in_a_list_item_stays_in_it() {
let styles = format!(
r#"<office:document-styles {NS_T}><office:styles><text:list-style style:name="L"><text:list-level-style-number text:level="1" style:num-format="1" style:num-suffix="."/></text:list-style></office:styles></office:document-styles>"#
);
let content = format!(
r#"<office:document-content {NS_T} {NS_X}><office:body><office:text><text:list text:style-name="L"><text:list-item><text:p>One</text:p><text:h text:outline-level="2">Head</text:h><text:p>After</text:p></text:list-item><text:list-item><text:p>Two</text:p></text:list-item></text:list></office:text></office:body></office:document-content>"#
);
let mut d = import(&package(&content, Some(&styles))).unwrap();
let html = craft_html::doc::export(&d);
assert_eq!(html.matches("<ol").count(), 1, "{html}");
assert!(html.contains("<li>One<h2>Head</h2><p>After</p></li>"), "{html}");
let md = craft_markdown::export(&d);
assert!(md.contains("1. One\n\n ## Head\n\n After\n\n2. Two"), "{md}");
// Edited, so the list is written from the model.
let i = d.body.iter().position(|b| b.as_para().is_some_and(|p| p.text == "One")).unwrap();
d.insert_text(&craft_wordmodel::Pos::body(i, 0), "Edited ", &Default::default()).unwrap();
let out = export(&d).unwrap();
let c = crate::text::tests::content_of(&out);
assert!(c.contains("Edited One</text:p><text:h"), "{c}");
assert!(c.contains(">Head</text:h>"), "{c}");
assert!(c.contains("After</text:p></text:list-item><text:list-item>"), "{c}");
let back = import(&out).unwrap();
let rows: Vec<_> =
back.body.iter().filter_map(|b| b.as_para()).map(|p| (p.text.clone(), p.props.numbering.is_some(), p.props.list_item)).collect();
assert_eq!(
rows,
[
("Edited One".to_string(), true, None),
("Head".to_string(), false, Some(0)),
("After".to_string(), false, Some(0)),
("Two".to_string(), true, None)
],
"{c}"
);
let head = back.body.iter().filter_map(|b| b.as_para()).find(|p| p.text == "Head").unwrap();
assert_eq!(head.props.style.as_deref(), Some("Heading2"), "{c}");
}
#[test]
fn zero_indent_multi_paragraph_header_survives_model_export() {
let styles = format!(
r#"<office:document-styles {NS_T}><office:styles><text:list-style style:name="L"><text:list-level-style-number text:level="1" style:num-format="1"><style:list-level-properties text:list-level-position-and-space-mode="label-alignment"><style:list-level-label-alignment fo:margin-left="0in" fo:text-indent="0in"/></style:list-level-properties></text:list-level-style-number></text:list-style></office:styles></office:document-styles>"#
);
let content = format!(
r#"<office:document-content {NS_T}><office:body><office:text><text:list text:style-name="L"><text:list-header><text:p>Header</text:p><text:p>More header</text:p></text:list-header><text:list-item><text:p>One</text:p></text:list-item></text:list></office:text></office:body></office:document-content>"#
);
let doc = import(&package(&content, Some(&styles))).unwrap();
let bytes = crate::text::tests::export_model(&doc).unwrap();
let xml = crate::text::tests::entry(&bytes, "content.xml");
assert_eq!(xml.matches("<text:list-header>").count(), 1);
let back = import(&bytes).unwrap();
for text in ["Header", "More header"] {
let p = back.body.iter().filter_map(|b| b.as_para()).find(|p| p.text == text).unwrap();
assert_eq!(p.props.list_item, Some(0));
assert!(p.props.numbering.is_none());
}
}
/// A sublist's header, written from the model, stays with the sublist's items in the item the
/// sublist is in: alone or of several paragraphs, below another header, and before the item goes
/// on after the sublist.
#[test]
fn a_sublists_header_written_from_the_model_stays_in_its_parent_item() {
let styles = format!(
r#"<office:document-styles {NS_T}><office:styles><text:list-style style:name="L"><text:list-level-style-number text:level="1" style:num-format="1"/><text:list-level-style-number text:level="2" style:num-format="a"/><text:list-level-style-number text:level="3" style:num-format="i"/></text:list-style></office:styles></office:document-styles>"#
);
// The lists of `xml`, without attributes.
let lists = |xml: &str| -> String {
let (from, to) = (xml.find("<text:list ").unwrap(), xml.rfind("</text:list>").unwrap());
let mut out = String::new();
for part in xml.get(from..to).unwrap().split('<').skip(1) {
let (tag, text) = part.split_once('>').unwrap();
out.push_str(&format!("<{}>{text}", tag.split(' ').next().unwrap()));
}
out + "</text:list>"
};
let head = "<text:list-header><text:p>Sub header</text:p></text:list-header>";
let sub = "<text:list-item><text:p>Sub</text:p></text:list-item>";
for inner in [
format!("<text:list>{head}{sub}<text:list-item><text:p>Sub two</text:p></text:list-item></text:list>"),
format!(
"<text:p>More</text:p><text:list><text:list-header><text:p>Sub header</text:p><text:p>Second line</text:p></text:list-header>{sub}</text:list>"
),
format!("<text:list>{head}</text:list><text:p>Parent again</text:p>"),
"<text:list><text:list-header><text:p>Sub header</text:p><text:list><text:list-header><text:p>Deeper</text:p></text:list-header><text:list-item><text:p>Deepest</text:p></text:list-item></text:list></text:list-header></text:list>".to_string(),
] {
let list = |parent: &str, attrs: &str| {
format!(
"<text:list{attrs}><text:list-item><text:p>{parent}</text:p>{inner}</text:list-item><text:list-item><text:p>Next</text:p></text:list-item></text:list>"
)
};
let content = format!(
"<office:document-content {NS_T}><office:body><office:text>{}</office:text></office:body></office:document-content>",
list("Parent", r#" text:style-name="L""#)
);
let mut d = import(&package(&content, Some(&styles))).unwrap();
// Edited, so the list is written from the model.
let i = d.body.iter().position(|b| b.as_para().is_some_and(|p| p.text == "Parent")).unwrap();
d.insert_text(&craft_wordmodel::Pos::body(i, 0), "Edited ", &Default::default()).unwrap();
let out = export(&d).unwrap();
assert_eq!(lists(&crate::text::tests::content_of(&out)), list("Edited Parent", ""));
let rows = |d: &Document| {
let paras = d.body.iter().filter_map(|b| b.as_para());
paras.map(|p| (p.text.clone(), p.props.numbering.map(|n| n.level), p.props.list_item)).collect::<Vec<_>>()
};
assert_eq!(rows(&import(&out).unwrap()), rows(&d));
}
}
+75 -38
View File
@@ -97,20 +97,35 @@ pub(super) const GRAPHICS_PARENT: &str = "\u{0}graphics";
/// level's kind as its first item there says. An item of another list, or (lists not told apart)
/// a top-level item of the other kind, starts a new list; with section wrappers (`wraps`), so
/// does an item opening a section, and one closing a section ends it.
fn list_run(blocks: &[FBlock], start: usize, wraps: bool) -> (usize, [ListOut; 9]) {
fn list_run(blocks: &[FBlock], start: usize, wraps: bool) -> (usize, [ListOut; 9], u32) {
let p = match blocks.get(start) {
Some(FBlock::Para(p)) => p,
_ => return (start.saturating_add(1), [ListOut { ordered: false, label: None, start: 1 }; 9]),
_ => return (start.saturating_add(1), [ListOut { ordered: false, label: None, start: 1 }; 9], 0),
};
let id = p.list.map_or(0, |l| l.list);
let mut id = p.list.map(|l| l.list);
let first = ListOut { ordered: p.list.is_some_and(|l| l.ordered), label: None, start: 1 };
let mut kinds = [first; 9];
let mut seen = [false; 9];
let mut i = start;
while let Some(FBlock::Para(q)) = blocks.get(i) {
let Some(li) = q.list else { break };
let Some(li) = q.list else {
// A section it opens or closes ends the run, as an item's does.
let wrap = q.wrap.as_deref().filter(|_| wraps);
match model::continues_list(blocks, i) {
// (One below the last item is the header of a sublist in it.)
Some(_) if i == start || !wrap.is_some_and(|w| !w.0.is_empty()) => {
i += 1;
if wrap.is_some_and(|w| w.1 > 0) {
break;
}
continue;
}
_ => break,
}
};
let l = li.level.min(8) as usize;
if li.list != id || (id == 0 && l == 0 && seen[0] && kinds[0].ordered != li.ordered) {
let list_id = *id.get_or_insert(li.list);
if li.list != list_id || (list_id == 0 && l == 0 && seen[0] && kinds[0].ordered != li.ordered) {
break;
}
let wrap = q.wrap.as_deref().filter(|_| wraps);
@@ -128,7 +143,40 @@ fn list_run(blocks: &[FBlock], start: usize, wraps: bool) -> (usize, [ListOut; 9
break;
}
}
(i.max(start + 1), kinds)
(i.max(start + 1), kinds, id.unwrap_or(0))
}
/// What is open in a list being written.
#[derive(Clone, Copy, PartialEq)]
enum ListPart {
None,
Item,
Header,
}
/// Close the open part of the innermost list, then open `part`.
fn list_part(out: &mut String, stack: &mut [ListPart], part: ListPart) {
let Some(top) = stack.last_mut() else { return };
out.push_str(match top {
ListPart::None => "",
ListPart::Item => "</text:list-item>",
ListPart::Header => "</text:list-header>",
});
out.push_str(match part {
ListPart::None => "",
ListPart::Item => "<text:list-item>",
ListPart::Header => "<text:list-header>",
});
*top = part;
}
/// Close nested items and lists down to the requested open depth.
fn close_lists(out: &mut String, stack: &mut Vec<ListPart>, depth: usize) {
while stack.len() > depth {
list_part(out, stack, ListPart::None);
stack.pop();
out.push_str("</text:list>");
}
}
/// The `xml:id` of the list markup `xml` (kept as read) begins with, if it does.
@@ -799,7 +847,9 @@ impl Writer {
}
// A list without its own `xml:id` (older files' lists) is given one, for a list going on
// with it to name.
if p.list.is_some()
// (Its first numbered paragraph's: a list header has no number.)
let list = run.iter().find_map(|b| if let FBlock::Para(q) = b { q.list } else { None });
if list.is_some()
&& list_xml_id(&ix.0).is_none()
&& let Some(at) = markup.find("<text:list").map(|i| i + "<text:list".len())
{
@@ -815,7 +865,7 @@ impl Writer {
self.close_wrap(last.as_ref(), 0, out);
self.master = None;
// A list kept so: a list continuing it, written from the model, names it.
if let Some(l) = p.list
if let Some(l) = list
&& let Some(id) = markup.find("<text:list").and_then(|i| markup.get(i..)).and_then(list_xml_id)
{
if l.list != 0 {
@@ -923,10 +973,9 @@ impl Writer {
}
i += 1;
}
FBlock::Para(p) if p.list.is_some() => {
FBlock::Para(p) if p.list.is_some() || model::continues_list(blocks, i).is_some() => {
let start = i;
let id = p.list.map_or(0, |l| l.list);
let (end, kinds) = list_run(blocks, start, self.wraps_at(depth));
let (end, kinds, id) = list_run(blocks, start, self.wraps_at(depth));
i = end;
// The sections kept as read its first item opens and its last closes, around it.
let wrap_of = |k: usize| match blocks.get(k) {
@@ -938,23 +987,15 @@ impl Writer {
self.list_styles.push(kinds);
let lname = format!("{}L{}", self.prefix, self.list_styles.len());
let id_of_list = id;
// Open lists: per level, whether a list-item is open.
let mut stack: Vec<bool> = Vec::new();
// Open lists: per level, what is open in it.
let mut stack: Vec<ListPart> = Vec::new();
for (qi, q) in blocks.get(start..i).unwrap_or(&[]).iter().enumerate() {
let FBlock::Para(q) = q else { continue };
let lv = q.list.map(|l| l.level.min(8) as usize).unwrap_or(0);
while stack.len() > lv + 1 {
if stack.pop() == Some(true) {
out.push_str("</text:list-item>");
}
out.push_str("</text:list>");
}
let lv = usize::from(q.list.map(|l| l.level).or(q.item).unwrap_or(0).min(8));
close_lists(out, &mut stack, lv + 1);
while stack.len() < lv + 1 {
if let Some(top) = stack.last_mut()
&& !*top
{
out.push_str("<text:list-item>");
*top = true;
if stack.last() == Some(&ListPart::None) {
list_part(out, &mut stack, ListPart::Item);
}
if stack.is_empty() {
let id = format!("{}lst{}", self.prefix, self.list_styles.len());
@@ -981,23 +1022,19 @@ impl Writer {
} else {
out.push_str("<text:list>");
}
stack.push(false);
stack.push(ListPart::None);
}
if let Some(top) = stack.last_mut() {
if *top {
out.push_str("</text:list-item>");
}
*top = true;
// An unnumbered paragraph goes in the item or header open at its level (its
// sublists ended first); a list's leading ones are its header's. Keep that
// membership when original markup is gone.
if q.list.is_some() {
list_part(out, &mut stack, ListPart::Item);
} else if stack.last() == Some(&ListPart::None) {
list_part(out, &mut stack, ListPart::Header);
}
out.push_str("<text:list-item>");
self.para_in(q, chain(start + qi), out);
}
while let Some(open) = stack.pop() {
if open {
out.push_str("</text:list-item>");
}
out.push_str("</text:list>");
}
close_lists(out, &mut stack, 0);
self.close_wrap(closes.as_ref(), 0, out);
out.push('\n');
}
+5
View File
@@ -580,6 +580,11 @@ pub struct ParaProps {
/// file (not laid out yet); Word sizes a line by it, so dropping it changes Word's pages.
#[serde(skip_serializing_if = "Option::is_none")]
pub text_alignment: Option<TextAlignment>,
/// A list item's paragraph after its first (or a list header's), with no number of its own,
/// at this list level (0..=8): formats with list items (ODT, HTML, Markdown) keep it in the
/// item. Set only directly, never by a style.
#[serde(skip_serializing_if = "Option::is_none")]
pub list_item: Option<u8>,
}
impl ParaProps {