From 9c27cebc14850882cc825b4155c8845de6146384 Mon Sep 17 00:00:00 2001
From: alehel
Date: Sun, 15 Nov 2026 21:57:23 +0100
Subject: [PATCH 1/6] ODT: a list item's further paragraphs stay paragraphs
LibreOffice writes an unnumbered list entry as an item's second paragraph.
The ODT reader joined it to the first with a line break, so a save could
bring the file back with the wrong paragraphs, and a list header got a
number. Such paragraphs are now read as paragraphs of their own, with no
number, at the item's text indent, and marked with the new
`ParaProps::list_item` (the flow model's `Para::item`).
- HTML and Markdown export keep the paragraph in its item, so one numbered
list continues across it.
- Markdown `parse_list` joins a code block, quote or heading inside an item
back to the item (also after a sublist), so it gets no number.
- The writers keep a paragraph in its item only while it sits at the item's
text indent, so text outdented to the margin leaves the list.
- ODT written from the model puts a further paragraph inside its
`text:list-item`.
- A level first used after an unnumbered paragraph keeps the file's label.
Ported from storytold/wordcraft#5723 after the readers and writers moved here.
Co-Authored-By: Claude Opus 5.5
---
Cargo.lock | 2 +
crates/docx/tests/it/roundtrip.rs | 2 +
crates/flow/src/from_doc.rs | 42 +++++-
crates/flow/src/lib.rs | 1 +
crates/flow/src/to_doc.rs | 22 ++-
crates/flow/src/types.rs | 12 ++
crates/html/src/doc/export.rs | 14 +-
crates/markdown/Cargo.toml | 4 +
crates/markdown/src/blocks.rs | 22 ++-
crates/markdown/src/export.rs | 23 +++
crates/markdown/src/tests.rs | 71 ++++++++++
crates/odf/Cargo.toml | 3 +
crates/odf/src/text/body.rs | 44 ++++--
crates/odf/src/text/tests_more/lists.rs | 170 +++++++++++++++++++++++
crates/odf/src/text/writer.rs | 34 ++++-
crates/wordmodel/src/props/para_props.rs | 5 +
16 files changed, 442 insertions(+), 29 deletions(-)
diff --git a/Cargo.lock b/Cargo.lock
index b3325f7908..62c841a7ec 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -2183,6 +2183,8 @@ dependencies = [
"base64 0.23.1",
"chrono",
"craft-flow",
+ "craft-html",
+ "craft-markdown",
"craft-math",
"craft-metafile",
"craft-wordmodel",
diff --git a/crates/docx/tests/it/roundtrip.rs b/crates/docx/tests/it/roundtrip.rs
index 8f3bbdd0bd..66bda8bbeb 100644
--- a/crates/docx/tests/it/roundtrip.rs
+++ b/crates/docx/tests/it/roundtrip.rs
@@ -225,6 +225,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() },
diff --git a/crates/flow/src/from_doc.rs b/crates/flow/src/from_doc.rs
index 341ded449f..8bcf4f5527 100644
--- a/crates/flow/src/from_doc.rs
+++ b/crates/flow/src/from_doc.rs
@@ -508,6 +508,7 @@ fn flow_paras_in(doc: &Document, p: &Paragraph, opts: FlowOpts) -> Vec {
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);
@@ -551,11 +552,13 @@ fn flow_paras_in(doc: &Document, p: &Paragraph, opts: FlowOpts) -> Vec {
wrap: None,
index: None,
group: None,
+ item: None,
};
let prev = std::mem::replace(&mut out, next);
if prev.inlines.is_empty() {
out.page_break |= prev.page_break;
out.list = prev.list;
+ out.item = prev.item;
} else {
done.push(prev);
}
@@ -907,9 +910,44 @@ 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; 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 {
+ 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);
+ let text = 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 at its level (a list header), anywhere off the margin.
+ let kept = match at.get(usize::from(l)).copied().flatten() {
+ Some(text) => left >= text - 0.5,
+ None => left > 0.5,
+ };
+ if !kept {
+ for q in &mut paras {
+ q.item = None;
+ }
+ }
+ }
+ paras
+}
+
fn flow_blocks(doc: &Document, bl: &Blocks, depth: usize, tracked: FlowOpts) -> Vec {
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;
@@ -924,7 +962,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;
@@ -935,7 +973,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 {
diff --git a/crates/flow/src/lib.rs b/crates/flow/src/lib.rs
index 774b5ffd17..5bcb7a68c9 100644
--- a/crates/flow/src/lib.rs
+++ b/crates/flow/src/lib.rs
@@ -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::{
diff --git a/crates/flow/src/to_doc.rs b/crates/flow/src/to_doc.rs
index c10be85c27..f10bc405e8 100644
--- a/crates/flow/src/to_doc.rs
+++ b/crates/flow/src/to_doc.rs
@@ -158,6 +158,9 @@ fn para_props(p: &Para, list_num: Option) -> 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;
let sp = p.spacing;
out.space_before = sp.before;
@@ -756,6 +759,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> = 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 {
@@ -769,7 +778,14 @@ impl<'a> Builder<'a> {
let mut top: Option = 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;
}
@@ -785,7 +801,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);
}
diff --git a/crates/flow/src/types.rs b/crates/flow/src/types.rs
index e897778f9c..8503f18d4a 100644
--- a/crates/flow/src/types.rs
+++ b/crates/flow/src/types.rs
@@ -713,6 +713,9 @@ pub struct Para {
pub index: Option, usize)>>,
/// The group of paragraphs its markup kept as read belongs to (see [`Group`]).
pub group: Option>,
+ /// 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,
}
/// Paragraphs whose markup kept as read ties them together (a comment from one to another, a
@@ -1092,3 +1095,12 @@ 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.
+pub fn continues_list(blocks: &[FBlock], i: usize) -> Option {
+ match blocks.get(i) {
+ Some(FBlock::Para(p)) if p.list.is_none() && p.kind == Kind::Normal => p.item.map(|l| l.min(8)),
+ _ => None,
+ }
+}
diff --git a/crates/html/src/doc/export.rs b/crates/html/src/doc/export.rs
index 78f6d9ae83..c50fcec0ff 100644
--- a/crates/html/src/doc/export.rs
+++ b/crates/html/src/doc/export.rs
@@ -275,7 +275,19 @@ fn blocks_html(blocks: &[FBlock], out: &mut String, depth: usize) {
// 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(&format!("{}
", inlines_html(&q.inlines)));
+ i += 1;
+ continue;
+ };
let lv = li.level.min(8) as usize;
while stack.len() > lv + 1 {
close_list(&mut stack, out);
diff --git a/crates/markdown/Cargo.toml b/crates/markdown/Cargo.toml
index eac067b267..aeb3b7acc8 100644
--- a/crates/markdown/Cargo.toml
+++ b/crates/markdown/Cargo.toml
@@ -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"] }
diff --git a/crates/markdown/src/blocks.rs b/crates/markdown/src/blocks.rs
index 72a7aedfb4..919a80886d 100644
--- a/crates/markdown/src/blocks.rs
+++ b/crates/markdown/src/blocks.rs
@@ -682,21 +682,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 the writers keep only plain paragraphs in an item.
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 {
diff --git a/crates/markdown/src/export.rs b/crates/markdown/src/export.rs
index 82fd952e3f..e1bdde3b86 100644
--- a/crates/markdown/src/export.rs
+++ b/crates/markdown/src/export.rs
@@ -346,6 +346,10 @@ pub(super) fn write_blocks(blocks: &[FBlock], out: &mut Vec) {
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 {
@@ -376,6 +380,8 @@ pub(super) fn write_blocks(blocks: &[FBlock], out: &mut Vec) {
}
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;
@@ -398,6 +404,10 @@ pub(super) fn write_blocks(blocks: &[FBlock], out: &mut Vec) {
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 {
@@ -419,6 +429,19 @@ pub(super) fn write_blocks(blocks: &[FBlock], out: &mut Vec) {
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 = 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 {
diff --git a/crates/markdown/src/tests.rs b/crates/markdown/src/tests.rs
index 96ad1dc3aa..e59ae436af 100644
--- a/crates/markdown/src/tests.rs
+++ b/crates/markdown/src/tests.rs
@@ -793,3 +793,74 @@ 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::>()
+ };
+ let d = import(src);
+ let rows = shape(&d);
+ assert_eq!(rows.iter().map(|r| r.0.as_str()).collect::>(), ["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::>();
+ 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::>().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(" {
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>) -> Self {
let page = pages.first.clone().unwrap_or_default();
@@ -411,6 +421,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
}
@@ -1050,21 +1068,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) {
@@ -1721,6 +1733,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::().ok()) {
self.list_id = self.new_list_id();
@@ -1730,8 +1743,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,
diff --git a/crates/odf/src/text/tests_more/lists.rs b/crates/odf/src/text/tests_more/lists.rs
index 079413aa82..fb3d519720 100644
--- a/crates/odf/src/text/tests_more/lists.rs
+++ b/crates/odf/src/text/tests_more/lists.rs
@@ -166,3 +166,173 @@ 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#""#
+ );
+ let body = r#"HeaderOneStill oneAnd againTwoAfter"#;
+ let content = format!("{body}");
+ 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::>()
+ };
+ let d = import(&package(&content, Some(&styles))).unwrap();
+ let want = |a: &[(String, bool, Option)]| {
+ 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 = 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));
+ let nums: Vec = 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 = 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#"{first}{second}"#
+ );
+ let content = format!(
+ r#"OneMoreSub"#
+ );
+ 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#""#)
+ };
+ let bullet = |level: u8| format!(r#""#);
+ 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#""#
+ );
+ let content = format!(
+ r#"OneContTwo"#
+ );
+ let d = import(&package(&content, Some(&styles))).unwrap();
+ let html = craft_html::doc::export(&d);
+ assert_eq!(html.matches("Cont
"), "{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#""#
+ );
+ let open = |body: &str| {
+ // (An indent of its own: LibreOffice writes one as an automatic style.)
+ let auto = r#""#;
+ let content =
+ format!("{auto}{body}");
+ import(&package(&content, Some(&styles))).unwrap()
+ };
+ // A paragraph of its own between two parts of one list.
+ let d = open(
+ r#"OneBetweenTwo"#,
+ );
+ 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("Between") && !html.contains("- One
"), "{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#"OneTwoContAfter"#,
+ r#"TwoContAfter"#,
+ ] {
+ let d = open(body);
+ let html = craft_html::doc::export(&d);
+ assert!(html.contains("
- Two
Cont
"), "{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"), "{xml}");
+ assert!(body.contains("Sub =
+ 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}"
+ );
+}
diff --git a/crates/odf/src/text/writer.rs b/crates/odf/src/text/writer.rs
index 2ad475739c..88af69b94e 100644
--- a/crates/odf/src/text/writer.rs
+++ b/crates/odf/src/text/writer.rs
@@ -107,9 +107,22 @@ fn list_run(blocks: &[FBlock], start: usize, wraps: bool) -> (usize, [ListOut; 9
let mut kinds = [first; 9];
let mut seen = [false; 9];
let mut i = start;
+ // The level of the last item: an item's further paragraph goes in an item still open.
+ let mut last = 0usize;
while let Some(FBlock::Para(q)) = blocks.get(i) {
- let Some(li) = q.list else { break };
+ let Some(li) = q.list else {
+ match model::continues_list(blocks, i).map(usize::from) {
+ Some(lv) if i > start && lv <= last => {
+ // The items below it are closed.
+ last = lv;
+ i += 1;
+ continue;
+ }
+ _ => break,
+ }
+ };
let l = li.level.min(8) as usize;
+ last = l;
if li.list != id || (id == 0 && l == 0 && seen[0] && kinds[0].ordered != li.ordered) {
break;
}
@@ -797,7 +810,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(" = Vec::new();
for (qi, q) in blocks.get(start..i).unwrap_or(&[]).iter().enumerate() {
let FBlock::Para(q) = q else { continue };
+ if q.list.is_none() {
+ // An item's further paragraph (`list_run` took it only below an open
+ // item at its level): in that item, its sublists ended first.
+ let lv = q.item.map_or(0, |l| l.min(8) as usize);
+ while stack.len() > lv + 1 {
+ if stack.pop() == Some(true) {
+ out.push_str("");
+ }
+ out.push_str("");
+ }
+ self.para_in(q, chain(start + qi), out);
+ 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) {
diff --git a/crates/wordmodel/src/props/para_props.rs b/crates/wordmodel/src/props/para_props.rs
index a48540248e..619f13e917 100644
--- a/crates/wordmodel/src/props/para_props.rs
+++ b/crates/wordmodel/src/props/para_props.rs
@@ -506,6 +506,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,
+ /// 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,
}
impl ParaProps {
From 9b944481034b47247c6f170aaae6f8dc16a10afb Mon Sep 17 00:00:00 2001
From: alehel
Date: Mon, 16 Nov 2026 17:44:17 +0100
Subject: [PATCH 2/6] List item further paragraphs: fixes from review
- flow: each piece of a further paragraph split at a page break keeps its item.
- flow: body text resets the per-level item text positions, so a list starting with a
header after an earlier, further-indented list keeps the header in its list.
- flow: a further paragraph in a table-style-formatted cell keeps its list_item marker.
- html: a further paragraph is written through para_html, keeping alignment and page break.
- markdown: a quoted list item's further paragraph joins the item with a line break, so the
quoted list stays one list and keeps its numbers.
- odf: a further paragraph opening or closing a kept section ends the list run, as an item does.
Co-Authored-By: Claude Opus 5.5
---
crates/flow/src/from_doc.rs | 9 ++-
crates/flow/src/lib.rs | 88 +++++++++++++++++++++++++
crates/html/src/doc/export.rs | 2 +-
crates/html/src/doc/tests.rs | 12 ++++
crates/markdown/src/blocks.rs | 13 ++++
crates/markdown/src/tests.rs | 16 +++++
crates/odf/src/text/tests_more/lists.rs | 30 +++++++++
crates/odf/src/text/writer.rs | 7 +-
8 files changed, 173 insertions(+), 4 deletions(-)
diff --git a/crates/flow/src/from_doc.rs b/crates/flow/src/from_doc.rs
index 8bcf4f5527..dcebfeea68 100644
--- a/crates/flow/src/from_doc.rs
+++ b/crates/flow/src/from_doc.rs
@@ -552,13 +552,13 @@ fn flow_paras_in(doc: &Document, p: &Paragraph, opts: FlowOpts) -> Vec {
wrap: None,
index: None,
group: None,
- item: 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() {
out.page_break |= prev.page_break;
out.list = prev.list;
- out.item = prev.item;
} else {
done.push(prev);
}
@@ -940,6 +940,9 @@ fn flow_paras_at(doc: &Document, p: &Paragraph, opts: FlowOpts, at: &mut ItemTex
q.item = None;
}
}
+ } else {
+ // Body text: the lists before it have ended, and where their items' text was with them.
+ *at = [None; 9];
}
paras
}
@@ -1098,6 +1101,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))
diff --git a/crates/flow/src/lib.rs b/crates/flow/src/lib.rs
index 5bcb7a68c9..f1129acc79 100644
--- a/crates/flow/src/lib.rs
+++ b/crates/flow/src/lib.rs
@@ -185,4 +185,92 @@ 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)> {
+ 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
+ }
+
+ /// 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 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:?}");
+ }
}
diff --git a/crates/html/src/doc/export.rs b/crates/html/src/doc/export.rs
index c50fcec0ff..878313dfe6 100644
--- a/crates/html/src/doc/export.rs
+++ b/crates/html/src/doc/export.rs
@@ -284,7 +284,7 @@ fn blocks_html(blocks: &[FBlock], out: &mut String, depth: usize) {
if stack.len() != lv + 1 || !stack.last().is_some_and(|s| s.1) {
break;
}
- out.push_str(&format!("{}
", inlines_html(&q.inlines)));
+ out.push_str(¶_html(q));
i += 1;
continue;
};
diff --git a/crates/html/src/doc/tests.rs b/crates/html/src/doc/tests.rs
index 640ab07d02..673bb496e0 100644
--- a/crates/html/src/doc/tests.rs
+++ b/crates/html/src/doc/tests.rs
@@ -767,3 +767,15 @@ fn hostile_style_sheets_never_panic() {
let _ = parse_in(&format!("x
y | "), &|_| None, true);
}
}
+
+/// 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("- One
Cont
"), "{html}");
+}
diff --git a/crates/markdown/src/blocks.rs b/crates/markdown/src/blocks.rs
index 919a80886d..64e7eefc9e 100644
--- a/crates/markdown/src/blocks.rs
+++ b/crates/markdown/src/blocks.rs
@@ -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);
}
diff --git a/crates/markdown/src/tests.rs b/crates/markdown/src/tests.rs
index e59ae436af..309fda157f 100644
--- a/crates/markdown/src/tests.rs
+++ b/crates/markdown/src/tests.rs
@@ -864,3 +864,19 @@ fn a_block_after_a_sublist_keeps_the_next_items_number() {
assert_eq!(html.matches(" 1. One\n>\n> Cont\n>\n> 2. Two\n");
+ let nums: Vec = 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::>().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(""#
+ );
+ let content = format!(
+ r#"ZeroOneContTwo"#
+ );
+ 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(""), 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#"OneHeaderTwo"#
+ );
+ 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("Header<"));
+ assert!(open.is_some() && header.is_some() && open < header, "the section opens before Header: {c}");
+}
diff --git a/crates/odf/src/text/writer.rs b/crates/odf/src/text/writer.rs
index 88af69b94e..cefcf4009c 100644
--- a/crates/odf/src/text/writer.rs
+++ b/crates/odf/src/text/writer.rs
@@ -111,11 +111,16 @@ fn list_run(blocks: &[FBlock], start: usize, wraps: bool) -> (usize, [ListOut; 9
let mut last = 0usize;
while let Some(FBlock::Para(q)) = blocks.get(i) {
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).map(usize::from) {
- Some(lv) if i > start && lv <= last => {
+ Some(lv) if i > start && lv <= last && !wrap.is_some_and(|w| !w.0.is_empty()) => {
// The items below it are closed.
last = lv;
i += 1;
+ if wrap.is_some_and(|w| w.1 > 0) {
+ break;
+ }
continue;
}
_ => break,
From 2510523bf9ca7ec4dc1d95e7fd267afefde58671 Mon Sep 17 00:00:00 2001
From: alehel
Date: Mon, 16 Nov 2026 19:33:54 +0100
Subject: [PATCH 3/6] flow: a further paragraph moved out of its item ends the
lists before it
A list item's further paragraph moved to the margin is body text, but the
item text position of the list before it stayed, so a list starting with a
less indented header after it lost the header. It now clears them, as body
text does.
Co-Authored-By: Claude Opus 5.5
---
crates/flow/src/from_doc.rs | 2 ++
crates/flow/src/lib.rs | 29 +++++++++++++++++++++++++++++
2 files changed, 31 insertions(+)
diff --git a/crates/flow/src/from_doc.rs b/crates/flow/src/from_doc.rs
index dcebfeea68..90a12e769c 100644
--- a/crates/flow/src/from_doc.rs
+++ b/crates/flow/src/from_doc.rs
@@ -939,6 +939,8 @@ fn flow_paras_at(doc: &Document, p: &Paragraph, opts: FlowOpts, at: &mut ItemTex
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.
diff --git a/crates/flow/src/lib.rs b/crates/flow/src/lib.rs
index f1129acc79..2860613437 100644
--- a/crates/flow/src/lib.rs
+++ b/crates/flow/src/lib.rs
@@ -253,6 +253,35 @@ mod tests {
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() {
From e994f6ce33de01a5687f5f94e90ba5aec6582a52 Mon Sep 17 00:00:00 2001
From: alehel
Date: Mon, 16 Nov 2026 19:36:36 +0100
Subject: [PATCH 4/6] flow: a heading in a list item stays in its item
A text:h inside a text:list-item is read as one of the item's further
paragraphs, but continues_list accepted only plain paragraphs, so the
HTML, Markdown and ODT writers ended the list at the heading and the
numbering restarted after it.
continues_list now also accepts headings. HTML writes the heading tag
inside the li, ODT writes a text:h inside the text:list-item, and
Markdown writes the ATX heading indented under the item. Quotes, code
and other kinds still end the list, as the writers cannot put them in
an item.
Co-Authored-By: Claude Opus 5.5
---
crates/flow/src/types.rs | 4 ++-
crates/markdown/src/blocks.rs | 2 +-
crates/markdown/src/export.rs | 5 ++-
crates/odf/src/text/tests_more/lists.rs | 41 +++++++++++++++++++++++++
4 files changed, 49 insertions(+), 3 deletions(-)
diff --git a/crates/flow/src/types.rs b/crates/flow/src/types.rs
index 8503f18d4a..4cbf992f8a 100644
--- a/crates/flow/src/types.rs
+++ b/crates/flow/src/types.rs
@@ -1098,9 +1098,11 @@ pub fn clean_text(s: &str) -> String {
/// 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 {
match blocks.get(i) {
- Some(FBlock::Para(p)) if p.list.is_none() && p.kind == Kind::Normal => p.item.map(|l| l.min(8)),
+ Some(FBlock::Para(p)) if p.list.is_none() && matches!(p.kind, Kind::Normal | Kind::Heading(_)) => p.item.map(|l| l.min(8)),
_ => None,
}
}
diff --git a/crates/markdown/src/blocks.rs b/crates/markdown/src/blocks.rs
index 64e7eefc9e..9b4ade84ac 100644
--- a/crates/markdown/src/blocks.rs
+++ b/crates/markdown/src/blocks.rs
@@ -709,7 +709,7 @@ fn parse_list(lines: &[String], mut i: usize, depth: usize, level: u8, out: &mut
{
// 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 the writers keep only plain paragraphs in an item.
+ // 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;
diff --git a/crates/markdown/src/export.rs b/crates/markdown/src/export.rs
index e1bdde3b86..ffb4423fdc 100644
--- a/crates/markdown/src/export.rs
+++ b/crates/markdown/src/export.rs
@@ -438,7 +438,10 @@ pub(super) fn write_blocks(blocks: &[FBlock], out: &mut Vec) {
*d = 0;
}
let pad = " ".repeat(conts.get(lv).copied().unwrap_or(0));
- let text = escape_lines(body).replace("\\\n", &format!("\\\n{pad}"));
+ 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());
}
diff --git a/crates/odf/src/text/tests_more/lists.rs b/crates/odf/src/text/tests_more/lists.rs
index 1819b00c37..937fc05590 100644
--- a/crates/odf/src/text/tests_more/lists.rs
+++ b/crates/odf/src/text/tests_more/lists.rs
@@ -366,3 +366,44 @@ fn a_further_paragraph_opening_or_closing_a_section_ends_the_list_there() {
let (open, header) = (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#""#
+ );
+ let content = format!(
+ r#"OneHeadAfterTwo"#
+ );
+ let mut d = import(&package(&content, Some(&styles))).unwrap();
+ let html = craft_html::doc::export(&d);
+ assert_eq!(html.matches("OneHead
After
"), "{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
Head"), "{c}");
+ assert!(c.contains("After"), "{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}");
+}
From 4efe28f2abda1b3f514a7775dc12a9a0031f20b1 Mon Sep 17 00:00:00 2001
From: alehel
Date: Wed, 18 Nov 2026 22:25:40 +0100
Subject: [PATCH 5/6] Preserve list headers and resolved continuation indents
---
crates/flow/src/from_doc.rs | 7 ++-
crates/flow/src/lib.rs | 28 ++++++++++
crates/odf/src/text/tests_more/lists.rs | 21 +++++++
crates/odf/src/text/writer.rs | 73 +++++++++++++++----------
4 files changed, 97 insertions(+), 32 deletions(-)
diff --git a/crates/flow/src/from_doc.rs b/crates/flow/src/from_doc.rs
index 05c7f47ed5..3662a65b89 100644
--- a/crates/flow/src/from_doc.rs
+++ b/crates/flow/src/from_doc.rs
@@ -957,15 +957,16 @@ fn flow_paras_at(doc: &Document, p: &Paragraph, opts: FlowOpts, at: &mut ItemTex
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);
- let text = p.props.indent_left.or(level).unwrap_or(left);
+ // 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 at its level (a list header), anywhere off the margin.
+ // 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 => left > 0.5,
+ None => true,
};
if !kept {
for q in &mut paras {
diff --git a/crates/flow/src/lib.rs b/crates/flow/src/lib.rs
index a483e0c6c4..238a455fb8 100644
--- a/crates/flow/src/lib.rs
+++ b/crates/flow/src/lib.rs
@@ -242,6 +242,34 @@ mod tests {
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]
diff --git a/crates/odf/src/text/tests_more/lists.rs b/crates/odf/src/text/tests_more/lists.rs
index 937fc05590..b9bb69148f 100644
--- a/crates/odf/src/text/tests_more/lists.rs
+++ b/crates/odf/src/text/tests_more/lists.rs
@@ -201,6 +201,7 @@ fn a_list_items_further_paragraphs_are_paragraphs_with_no_number() {
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 = 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:?}");
}
@@ -407,3 +408,23 @@ fn a_heading_in_a_list_item_stays_in_it() {
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#""#
+ );
+ let content = format!(
+ r#"HeaderMore headerOne"#
+ );
+ 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("").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());
+ }
+}
diff --git a/crates/odf/src/text/writer.rs b/crates/odf/src/text/writer.rs
index f64c79feca..84d0374477 100644
--- a/crates/odf/src/text/writer.rs
+++ b/crates/odf/src/text/writer.rs
@@ -97,24 +97,24 @@ 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;
// The level of the last item: an item's further paragraph goes in an item still open.
- let mut last = 0usize;
+ let mut last = usize::from(p.item.unwrap_or(0).min(8));
while let Some(FBlock::Para(q)) = blocks.get(i) {
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).map(usize::from) {
- Some(lv) if i > start && lv <= last && !wrap.is_some_and(|w| !w.0.is_empty()) => {
+ Some(lv) if lv <= last && (i == start || !wrap.is_some_and(|w| !w.0.is_empty())) => {
// The items below it are closed.
last = lv;
i += 1;
@@ -128,7 +128,8 @@ fn list_run(blocks: &[FBlock], start: usize, wraps: bool) -> (usize, [ListOut; 9
};
let l = li.level.min(8) as usize;
last = l;
- 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);
@@ -146,7 +147,25 @@ 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))
+}
+
+/// Close nested items and lists down to the requested open depth.
+fn close_lists(out: &mut String, stack: &mut Vec, depth: usize) {
+ while stack.len() > depth {
+ if stack.pop() == Some(true) {
+ out.push_str("");
+ }
+ out.push_str("");
+ }
+}
+
+/// Open or close the single leading header without splitting its consecutive paragraphs.
+fn list_header(out: &mut String, is_open: &mut bool, open: bool) {
+ if *is_open != open {
+ out.push_str(if open { "" } else { "" });
+ *is_open = open;
+ }
}
/// The `xml:id` of the list markup `xml` (kept as read) begins with, if it does.
@@ -943,10 +962,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) {
@@ -960,28 +978,22 @@ impl Writer {
let id_of_list = id;
// Open lists: per level, whether a list-item is open.
let mut stack: Vec = Vec::new();
+ let mut header_open = false;
for (qi, q) in blocks.get(start..i).unwrap_or(&[]).iter().enumerate() {
let FBlock::Para(q) = q else { continue };
- if q.list.is_none() {
+ if q.list.is_none() && stack.get(usize::from(q.item.unwrap_or(0).min(8))).copied() == Some(true) {
// An item's further paragraph (`list_run` took it only below an open
// item at its level): in that item, its sublists ended first.
let lv = q.item.map_or(0, |l| l.min(8) as usize);
- while stack.len() > lv + 1 {
- if stack.pop() == Some(true) {
- out.push_str("");
- }
- out.push_str("");
- }
+ close_lists(out, &mut stack, lv + 1);
self.para_in(q, chain(start + qi), out);
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("");
- }
- out.push_str("");
+ if q.list.is_some() {
+ list_header(out, &mut header_open, false);
}
+ 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
@@ -1016,6 +1028,13 @@ impl Writer {
}
stack.push(false);
}
+ // Leading unnumbered paragraphs belong to one list header, not to
+ // the document body. Keep that membership when original markup is gone.
+ if q.list.is_none() {
+ list_header(out, &mut header_open, true);
+ self.para_in(q, chain(start + qi), out);
+ continue;
+ }
if let Some(top) = stack.last_mut() {
if *top {
out.push_str("");
@@ -1025,12 +1044,8 @@ impl Writer {
out.push_str("");
self.para_in(q, chain(start + qi), out);
}
- while let Some(open) = stack.pop() {
- if open {
- out.push_str("");
- }
- out.push_str("");
- }
+ list_header(out, &mut header_open, false);
+ close_lists(out, &mut stack, 0);
self.close_wrap(closes.as_ref(), 0, out);
out.push('\n');
}
From ec4247be6a96e736cafe7211a4f705910cfbc64b Mon Sep 17 00:00:00 2001
From: alehel
Date: Wed, 25 Nov 2026 01:54:25 +0100
Subject: [PATCH 6/6] fix(odf): a sublist's header written from the model stays
in its parent item
Co-Authored-By: Claude Opus 5.5
---
crates/odf/src/text/tests_more/lists.rs | 51 +++++++++++++
crates/odf/src/text/writer.rs | 97 +++++++++++--------------
2 files changed, 94 insertions(+), 54 deletions(-)
diff --git a/crates/odf/src/text/tests_more/lists.rs b/crates/odf/src/text/tests_more/lists.rs
index b9bb69148f..115914ea02 100644
--- a/crates/odf/src/text/tests_more/lists.rs
+++ b/crates/odf/src/text/tests_more/lists.rs
@@ -428,3 +428,54 @@ fn zero_indent_multi_paragraph_header_survives_model_export() {
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#""#
+ );
+ // The lists of `xml`, without attributes.
+ let lists = |xml: &str| -> String {
+ let (from, to) = (xml.find("").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 + ""
+ };
+ let head = "Sub header";
+ let sub = "Sub";
+ for inner in [
+ format!("{head}{sub}Sub two"),
+ format!(
+ "MoreSub headerSecond line{sub}"
+ ),
+ format!("{head}Parent again"),
+ "Sub headerDeeperDeepest".to_string(),
+ ] {
+ let list = |parent: &str, attrs: &str| {
+ format!(
+ "{parent}{inner}Next"
+ )
+ };
+ let content = format!(
+ "{}",
+ 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::>()
+ };
+ assert_eq!(rows(&import(&out).unwrap()), rows(&d));
+ }
+}
diff --git a/crates/odf/src/text/writer.rs b/crates/odf/src/text/writer.rs
index 84d0374477..bc268d786c 100644
--- a/crates/odf/src/text/writer.rs
+++ b/crates/odf/src/text/writer.rs
@@ -107,16 +107,13 @@ fn list_run(blocks: &[FBlock], start: usize, wraps: bool) -> (usize, [ListOut; 9
let mut kinds = [first; 9];
let mut seen = [false; 9];
let mut i = start;
- // The level of the last item: an item's further paragraph goes in an item still open.
- let mut last = usize::from(p.item.unwrap_or(0).min(8));
while let Some(FBlock::Para(q)) = blocks.get(i) {
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).map(usize::from) {
- Some(lv) if lv <= last && (i == start || !wrap.is_some_and(|w| !w.0.is_empty())) => {
- // The items below it are closed.
- last = lv;
+ 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;
@@ -127,7 +124,6 @@ fn list_run(blocks: &[FBlock], start: usize, wraps: bool) -> (usize, [ListOut; 9
}
};
let l = li.level.min(8) as usize;
- last = l;
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;
@@ -150,21 +146,36 @@ fn list_run(blocks: &[FBlock], start: usize, wraps: bool) -> (usize, [ListOut; 9
(i.max(start + 1), kinds, id.unwrap_or(0))
}
-/// Close nested items and lists down to the requested open depth.
-fn close_lists(out: &mut String, stack: &mut Vec, depth: usize) {
- while stack.len() > depth {
- if stack.pop() == Some(true) {
- out.push_str("");
- }
- out.push_str("");
- }
+/// What is open in a list being written.
+#[derive(Clone, Copy, PartialEq)]
+enum ListPart {
+ None,
+ Item,
+ Header,
}
-/// Open or close the single leading header without splitting its consecutive paragraphs.
-fn list_header(out: &mut String, is_open: &mut bool, open: bool) {
- if *is_open != open {
- out.push_str(if open { "" } else { "" });
- *is_open = open;
+/// 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 => "",
+ ListPart::Header => "",
+ });
+ out.push_str(match part {
+ ListPart::None => "",
+ ListPart::Item => "",
+ ListPart::Header => "",
+ });
+ *top = part;
+}
+
+/// Close nested items and lists down to the requested open depth.
+fn close_lists(out: &mut String, stack: &mut Vec, depth: usize) {
+ while stack.len() > depth {
+ list_part(out, stack, ListPart::None);
+ stack.pop();
+ out.push_str("");
}
}
@@ -976,30 +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 = Vec::new();
- let mut header_open = false;
+ // Open lists: per level, what is open in it.
+ let mut stack: Vec = Vec::new();
for (qi, q) in blocks.get(start..i).unwrap_or(&[]).iter().enumerate() {
let FBlock::Para(q) = q else { continue };
- if q.list.is_none() && stack.get(usize::from(q.item.unwrap_or(0).min(8))).copied() == Some(true) {
- // An item's further paragraph (`list_run` took it only below an open
- // item at its level): in that item, its sublists ended first.
- let lv = q.item.map_or(0, |l| l.min(8) as usize);
- close_lists(out, &mut stack, lv + 1);
- self.para_in(q, chain(start + qi), out);
- continue;
- }
- if q.list.is_some() {
- list_header(out, &mut header_open, false);
- }
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("");
- *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());
@@ -1026,25 +1022,18 @@ impl Writer {
} else {
out.push_str("");
}
- stack.push(false);
+ stack.push(ListPart::None);
}
- // Leading unnumbered paragraphs belong to one list header, not to
- // the document body. Keep that membership when original markup is gone.
- if q.list.is_none() {
- list_header(out, &mut header_open, true);
- self.para_in(q, chain(start + qi), out);
- continue;
+ // 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);
}
- if let Some(top) = stack.last_mut() {
- if *top {
- out.push_str("");
- }
- *top = true;
- }
- out.push_str("");
self.para_in(q, chain(start + qi), out);
}
- list_header(out, &mut header_open, false);
close_lists(out, &mut stack, 0);
self.close_wrap(closes.as_ref(), 0, out);
out.push('\n');