diff --git a/ROADMAP.md b/ROADMAP.md index e8281f3767..00a89f0299 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -258,6 +258,7 @@ Ranked, to beta (detail and remaining milestones in [docs/roadmap.md](docs/roadm - 2026-10-31: ODT: headers and footers are saved (they were dropped on every save), each page's header sits where LibreOffice puts it on open, and page numbers, page counts, dates and other text fields open as fields that update and are saved as ODF fields (gap 19). Readiness unchanged. - 2026-10-31: ODT: paragraph spacing, indents and line spacing are read and written, and an ODT's own default spacing (none, single lines) replaces Word's 8 pt after and 1.15 lines, so LibreOffice documents keep their vertical rhythm on open and save (gap 19). Readiness unchanged. - 2026-11-01: PDF export, printing and page images show the body's SEQ, STYLEREF and REF fields with their current results, as Word fills them in when it prints or exports even with Update fields before printing off: a caption numbered 7 when it is the first shows 1 on paper, and a REF to a bookmark the document lacks prints Word's "Error! Reference source not found.". NUMWORDS, FILENAME, the document properties, formulas and locked fields keep their stored results there, as in Word; the editor and the saved document keep every stored result. +- 2026-10-31: PDFs, prints and page images show each `PAGEREF` in the body with the page its bookmark is on, as Word fills them in when it prints or exports, so a table of contents saved with stale page numbers prints the pages its headings are on; on screen they keep their stored result until fields are updated, as in Word, and a locked one keeps it everywhere. A reference to a bookmark the document lacks prints Word's "Error! Bookmark not defined." Readiness unchanged. - 2026-10-28: Print Markup HTML, Markdown and text copies discover comment anchors in one paragraph walk, so unrelated bookmark markers no longer cause repeated prefix scans (#3614). Existing quotes, replies, order and export limits are unchanged; original synthetic semantic and scaling regressions cover the traversal. - 2026-11-04: Table Sort refuses malformed and nonexistent explicit columns before reordering rows (#5531). Omitted column 0, valid columns, header/order/language behavior and Undo/Redo are retained. Original Linux CLI/MCP controls and repeated native/DOCX reopens cover the command; native Word and desktop comparison remain untested. Readiness estimates unchanged. - 2026-10-30: Layout resource caps (#3867, #4385) and linear-time passes (#3866, #4392): repeated table-header rows are capped by item counts, a clipped group counting every nested member, the wrap cache by decoded pixels and the widths a linked text box chain lays out by their lines and items; PDF export, hit testing, tracked-change and clipped-table costs, and long endnote selections no longer grow quadratically. Synthetic regression tests only; no new Word comparison. @@ -996,6 +997,7 @@ MATH glyphs that reference the same construction now share its immutable variant | 2026-11-07 | trivial | Progress log: `.doc` brace and bracket shapes unfilled by default (#5943) | | 2026-11-04 | trivial | PR #4609: relative REF keeps context already displayed by the own or a needed ancestor label; six synthetic legal-template cases and separate-list context follow the Word for Windows measurements reported by @pakiat in PR discussion. Existing unknown-switch/cache boundaries and readiness estimates unchanged; no new native Word run. | | 2026-11-01 | trivial | Progress log: SEQ, STYLEREF and REF fields show fresh results in output | +| 2026-10-31 | trivial | Progress log: PDFs and prints show a table of contents' current page numbers | | 2026-10-29 | trivial | Progress log: Print Markup balloon anchors use one object walk per paragraph (#3614); readiness estimates unchanged | | 2026-10-28 | trivial | Print Markup text-copy comment discovery walks paragraph objects once (#3614); quotes, order, limits and readiness estimates unchanged | | 2026-11-03 | trivial | Progress log: Language pack languages in every language list (CP4.3) | diff --git a/crates/engine/src/cmd/references.rs b/crates/engine/src/cmd/references.rs index 9e5c5fead5..b360375119 100644 --- a/crates/engine/src/cmd/references.rs +++ b/crates/engine/src/cmd/references.rs @@ -17,6 +17,8 @@ mod properties; mod toc; use fields::caption; +#[cfg(test)] +use fields::output_fields_with; pub use fields::{ CHAPTER_SEPARATORS, REFERENCE_NOT_FOUND, output_fields, refresh_date_fields, seq_format, update_fields, update_fields_in, update_seq, }; diff --git a/crates/engine/src/cmd/references/fields.rs b/crates/engine/src/cmd/references/fields.rs index eab9e21ed1..eedd16fee3 100644 --- a/crates/engine/src/cmd/references/fields.rs +++ b/crates/engine/src/cmd/references/fields.rs @@ -198,8 +198,9 @@ pub const REFERENCE_NOT_FOUND: &str = "Error! Reference source not found."; /// comment or text box is found too, and a REF to it shows that text as `stored` holds it, its /// own fields not yet refreshed, as Word's output does (measured in Word for Windows). The /// document's bookmarks are looked up once, and each bookmark's text read once, however many -/// fields refer to it. -fn ref_results(doc: &wordcraft_doc::Document, stored: &wordcraft_doc::Document) -> Vec { +/// fields refer to it. `error` is what a REF to a missing bookmark shows ([`REFERENCE_NOT_FOUND`] +/// in English). +fn ref_results(doc: &wordcraft_doc::Document, stored: &wordcraft_doc::Document, error: &str) -> Vec { let mut out = Vec::new(); let mut starts: std::collections::HashMap = std::collections::HashMap::new(); for (name, start) in doc.bookmarks().into_iter().chain(part_bookmarks(doc)) { @@ -220,7 +221,7 @@ fn ref_results(doc: &wordcraft_doc::Document, stored: &wordcraft_doc::Document) let f = FieldCode::parse(instr); let target = f.args.first().map(|s| s.split('\\').next().unwrap_or("").trim_matches('"')).unwrap_or(""); let Some(start) = starts.get(target) else { - out.push((StoryRef::Body, path.clone(), k, REFERENCE_NOT_FOUND.to_string())); + out.push((StoryRef::Body, path.clone(), k, error.to_string())); continue; }; let text = texts.entry(target.to_string()).or_insert_with(|| { @@ -281,7 +282,15 @@ fn changed(doc: &wordcraft_doc::Document, mut results: Vec) -> Vec< /// formulas keep their stored results (measured with Word for Windows, printing and exporting /// fields whose stored results were wrong). The document itself keeps its stored results. /// `None` when every such field already shows its fresh result, so nothing is copied then. +/// A `REF` to a missing bookmark shows Word's error in the interface language +/// ([`crate::set_reference_error`]). pub fn output_fields(doc: &wordcraft_doc::Document) -> Option { + let error = crate::locale::reference_error(); + output_fields_with(doc, error.as_deref().unwrap_or(REFERENCE_NOT_FOUND)) +} + +/// [`output_fields`], with `ref_error` for a `REF` to a missing bookmark. +pub(crate) fn output_fields_with(doc: &wordcraft_doc::Document, ref_error: &str) -> Option { // Numbers first, then the fields that read them: a STYLEREF to a heading holding a SEQ field, // and a REF to a bookmarked caption, show the new number. let seq = changed(doc, seq_results(doc)); @@ -293,7 +302,7 @@ pub fn output_fields(doc: &wordcraft_doc::Document) -> Option>(), ["stale", "stale"], "the document keeps it"); } +/// Word prints a REF's missing-bookmark error in its interface language: output takes the text +/// the shell sets ([`crate::set_reference_error`]), and a REF to a bookmark the document has +/// still shows the bookmark's text. +#[test] +fn a_missing_references_error_is_in_the_interface_language() { + let mut s = Session::new(wordcraft_doc::Document::from_text("Target")); + s.run("select.text", &json!({"text": "Target"})).unwrap(); + s.run("insert.bookmark", &json!({"name": "Here"})).unwrap(); + s.run("caret.docEnd", &json!({})).unwrap(); + for instr in ["REF NoSuchMark \\h", "REF Here \\h"] { + s.run("text.insert", &json!({"text": " "})).unwrap(); + s.run("insert.field", &json!({"instr": instr, "result": "stale"})).unwrap(); + } + let french = "Erreur ! Source du renvoi introuvable."; + let out = output_fields_with(&s.doc, french).expect("both results change"); + let shown: Vec = out + .para(StoryRef::Body, &wordcraft_doc::Path::top(0)) + .unwrap() + .objects + .iter() + .filter_map(|o| match o { + InlineObject::Field { result, .. } => Some(result.clone()), + _ => None, + }) + .collect(); + assert_eq!(shown, [french, "Target"]); +} + /// A REF showing the bookmarked paragraph's number (`\r`, `\n`, `\w`), which output doesn't /// compute, keeps its stored number when printed or exported rather than show the paragraph's /// text; a plain REF to the same bookmark is filled in. diff --git a/crates/engine/src/io_ext.rs b/crates/engine/src/io_ext.rs index f46d2f50ff..ed6c9466d6 100644 --- a/crates/engine/src/io_ext.rs +++ b/crates/engine/src/io_ext.rs @@ -103,7 +103,13 @@ pub fn save(ext: &str, doc: &Document, opts: &crate::io::ExportOptions) -> Optio pub fn render_png(doc: &Document, page: usize, scale: f32, opts: &crate::io::ExportOptions) -> Result, String> { let out = crate::cmd::references::output_fields(doc); let doc = out.as_ref().unwrap_or(doc); - let lo = wordcraft_layout::LayoutOptions { comment_balloons: opts.markup && opts.comments, numeral: opts.numeral, ..Default::default() }; + let lo = wordcraft_layout::LayoutOptions { + comment_balloons: opts.markup && opts.comments, + numeral: opts.numeral, + output_page_refs: true, + bookmark_error: crate::locale::bookmark_error(), + ..Default::default() + }; let l = wordcraft_layout::layout(doc, &mut wordcraft_layout::LayoutCache::new(), &lo); let p = l.pages.get(page).ok_or_else(|| format!("no page {}", page + 1))?; if opts.strict { diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index e5795e534e..88358e7df4 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -34,6 +34,7 @@ use serde_json::Value; pub use io::Password; pub use keymap::KeyMap; +pub use locale::{set_bookmark_error, set_reference_error}; pub use ribbon::RibbonLayout; pub use session::{ CellRange, ColumnBlock, DocInfo, DocState, EditSnapshot, FindState, MathEdit, Prefs, Selection, Session, StylesPaneDock, UNDO_LIST_MAX, diff --git a/crates/engine/src/locale.rs b/crates/engine/src/locale.rs index 5d76e2eb87..9f35a49904 100644 --- a/crates/engine/src/locale.rs +++ b/crates/engine/src/locale.rs @@ -1,4 +1,4 @@ -use std::sync::OnceLock; +use std::sync::{Arc, OnceLock, RwLock}; /// The system locale (BCP 47 tag) the shell found at startup, for Numeral › System. pub(super) static SYSTEM_LOCALE: OnceLock = OnceLock::new(); @@ -13,3 +13,41 @@ pub fn set_system_locale(tag: &str) { pub(crate) fn system_locale() -> Option<&'static str> { SYSTEM_LOCALE.get().map(String::as_str) } + +/// What output prints for a page reference to a missing bookmark, in the interface language +/// ([`set_bookmark_error`]); `None` until the shell sets it (English). +static BOOKMARK_ERROR: RwLock>> = RwLock::new(None); + +/// Tell the engine what PDFs, prints and page images show for a page reference to a bookmark the +/// document doesn't have, in the interface language: Word prints "Error! Bookmark not defined." +/// in its own. The shell calls this when its language is set; headless sessions print English. +pub fn set_bookmark_error(text: &str) { + let mut slot = BOOKMARK_ERROR.write().unwrap_or_else(std::sync::PoisonError::into_inner); + if slot.as_deref() != Some(text) { + *slot = Some(Arc::from(text)); + } +} + +/// The text [`set_bookmark_error`] recorded, for output's layout options. +pub(crate) fn bookmark_error() -> Option> { + BOOKMARK_ERROR.read().unwrap_or_else(std::sync::PoisonError::into_inner).clone() +} + +/// What output prints for a `REF` to a missing bookmark, in the interface language +/// ([`set_reference_error`]); `None` until the shell sets it (English). +static REFERENCE_ERROR: RwLock>> = RwLock::new(None); + +/// Tell the engine what PDFs, prints and page images show for a `REF` to a bookmark the document +/// doesn't have, in the interface language: Word prints "Error! Reference source not found." in +/// its own. The shell calls this when its language is set; headless sessions print English. +pub fn set_reference_error(text: &str) { + let mut slot = REFERENCE_ERROR.write().unwrap_or_else(std::sync::PoisonError::into_inner); + if slot.as_deref() != Some(text) { + *slot = Some(Arc::from(text)); + } +} + +/// The text [`set_reference_error`] recorded, for output's `REF` results. +pub(crate) fn reference_error() -> Option> { + REFERENCE_ERROR.read().unwrap_or_else(std::sync::PoisonError::into_inner).clone() +} diff --git a/crates/engine/src/session/layout.rs b/crates/engine/src/session/layout.rs index 2f773e308f..21c26f7099 100644 --- a/crates/engine/src/session/layout.rs +++ b/crates/engine/src/session/layout.rs @@ -74,6 +74,9 @@ impl Session { typing_word: typing, filename: filename.clone(), filepath: filepath.clone(), + // The editor shows a body page reference as stored until fields are updated. + output_page_refs: false, + bookmark_error: None, }; let l = Arc::new(wordcraft_layout::layout(&self.doc, &mut self.cache, &opts)); let [newest, _] = std::mem::take(&mut self.layout); @@ -155,7 +158,8 @@ impl Session { layout.map(|l| (copy.doc, copy.sel, l)) } - /// A layout for output (PDF, images, print): no proofing marks, print view. + /// A layout for output (PDF, images, print): no proofing marks, print view, and page + /// references in the body showing their bookmarks' pages, as Word prints them. pub fn export_layout(&self) -> Arc { self.export_layout_with(false) } @@ -177,6 +181,8 @@ impl Session { numeral: self.view.numeral.resolve(SYSTEM_LOCALE.get().map(String::as_str)), filename: Some(Arc::from(fn_name.as_str())), filepath: Some(Arc::from(fn_path.as_str())), + output_page_refs: true, + bookmark_error: crate::locale::bookmark_error(), ..Default::default() }; Arc::new(wordcraft_layout::layout(doc, &mut LayoutCache::new(), &opts)) diff --git a/crates/engine/src/strict.rs b/crates/engine/src/strict.rs index 223366b81e..45f08d14c0 100644 --- a/crates/engine/src/strict.rs +++ b/crates/engine/src/strict.rs @@ -193,7 +193,13 @@ pub fn strict_report( /// The PDF export's options for `opts`: the one place they are built, shared by the export and /// its strict check. pub(crate) fn pdf_options(opts: &ExportOptions) -> wordcraft_pdf::PdfOptions { - wordcraft_pdf::PdfOptions { include_markup: opts.markup, comments: opts.markup && opts.comments, numeral: opts.numeral, ..Default::default() } + wordcraft_pdf::PdfOptions { + include_markup: opts.markup, + comments: opts.markup && opts.comments, + numeral: opts.numeral, + bookmark_error: crate::locale::bookmark_error(), + ..Default::default() + } } /// What a page image shows: the display options `file.exportPng` renders with. diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index 1181f55c09..bad50faa30 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -4929,6 +4929,50 @@ fn toc_page_numbers_are_pageref_fields() { assert_eq!(text(&s), expected); } +/// Output (PDF, print) shows a table of contents' page numbers where the headings now are, as +/// Word fills its `PAGEREF`s in when it prints or exports; the editor shows them as stored until +/// the table is updated, and the document keeps them. +#[test] +fn output_shows_toc_page_numbers_where_the_headings_are() { + let mut s = s(); + run(&mut s, "references.toc", json!({})); + run(&mut s, "caret.docEnd", json!({})); + for name in ["Alpha", "Bravo"] { + run(&mut s, "text.pageBreak", json!({})); + run(&mut s, "text.insert", json!({"text": name})); + run(&mut s, "para.heading1", json!({})); + run(&mut s, "text.newParagraph", json!({})); + } + run(&mut s, "references.updateToc", json!({})); + // Another page before Alpha moves the headings to pages 3 and 4. + let alpha = s + .doc + .body + .iter() + .position(|b| b.as_para().is_some_and(|p| p.props.style.as_deref() == Some("Heading1") && p.text.contains("Alpha"))) + .unwrap(); + s.sel = crate::Selection::caret(Pos::body(alpha, 0)); + run(&mut s, "text.pageBreak", json!({})); + let toc_numbers = |l: &wordcraft_layout::DocLayout| -> Vec { + l.pages[0] + .items + .iter() + .flat_map(|it| match it { + wordcraft_layout::Placed::Lines { para, .. } => para.shown.iter().map(|s| s.1.clone()).collect(), + _ => vec![], + }) + .collect() + }; + assert_eq!(s.export_layout().pages.len(), 4); + assert_eq!(toc_numbers(&s.layout()), ["2", "3"]); + assert_eq!(toc_numbers(&s.export_layout()), ["3", "4"]); + assert!(text(&s).contains("Alpha\t2"), "the document keeps the stored numbers"); + // A page image is laid out as the print job is: it shows the same numbers. + let png = crate::io_ext::render_png(&s.doc, 0, 1.0, &Default::default()).unwrap(); + let printed = wordcraft_render::render_page(&s.doc, &s.export_layout().pages[0], 1.0, &Default::default()).to_png(); + assert!(png == printed, "the page image and the printed page differ"); +} + /// Headings numbered through a list carry their numbers, and the level's separator, into the /// TOC entries. #[test] diff --git a/crates/layout/src/cache.rs b/crates/layout/src/cache.rs index 25234f1f1a..d0fb9cd5a5 100644 --- a/crates/layout/src/cache.rs +++ b/crates/layout/src/cache.rs @@ -107,6 +107,9 @@ pub(crate) fn env_hash(doc: &Document, opts: &LayoutOptions) -> u64 { outline.hash(&mut h); opts.filename.hash(&mut h); opts.filepath.hash(&mut h); + // Output shows page references the editor leaves stored (a missing bookmark's error too). + opts.output_page_refs.hash(&mut h); + opts.bookmark_error.hash(&mut h); h.finish() } @@ -187,3 +190,7 @@ impl Totals { /// The most extra layout passes for page totals in the body: a total that changes the page /// count (its digits pushing text to another page) is tried again, this many times at most. pub(crate) const MAX_TOTAL_PASSES: usize = 3; + +/// The most extra layout passes for output's body `PAGEREF`s: a page number whose digits move a +/// bookmark to another page is tried again, this many times at most. +pub(crate) const MAX_PAGE_REF_PASSES: usize = 3; diff --git a/crates/layout/src/fields.rs b/crates/layout/src/fields.rs index 1719518bd0..b98b69a065 100644 --- a/crates/layout/src/fields.rs +++ b/crates/layout/src/fields.rs @@ -1,6 +1,6 @@ //! Field results computed at layout time (page numbers) and note numbering. -use std::collections::HashMap; +use std::collections::{HashMap, HashSet}; use std::sync::Arc; use wordcraft_doc::section::NumFormat; @@ -31,6 +31,17 @@ pub struct FieldCtx { pub bookmark_pages: Arc, /// A key for caches standing for `bookmark_pages` (0 when it's empty). pub bookmarks_key: u64, + /// Output ([`crate::LayoutOptions::output_page_refs`]) with `bookmark_pages` found for the + /// whole document: a `PAGEREF` to a bookmark that is neither there nor in `bookmarks` shows + /// `bookmark_error` instead of its result. Off while the pages aren't known yet (the first + /// pass shows the stored results, the closest guess). + pub output: bool, + /// The names of all the document's bookmarks, for output (see `output`): one in a story that + /// `bookmark_pages` doesn't place (a header, a comment) keeps the field's result. + pub bookmarks: Arc>, + /// What output shows for a `PAGEREF` to a missing bookmark ([`BOOKMARK_NOT_DEFINED`] when + /// empty). + pub bookmark_error: Arc, /// Where a paragraph runs onto later pages: from text offset `.0` on, its fields are on page /// `.1` (ascending offsets). Empty except during the layout of a body paragraph split across /// pages, for its later pages (#1352); nothing else laid out meanwhile sees it. @@ -295,6 +306,15 @@ pub fn field_text_on(instr: &str, result: &str, ctx: &FieldCtx, page: u32) -> (S "SECTION" => (field_number(instr, fmt.unwrap_or(NumFormat::Decimal), ctx.section), true), "PAGEREF" => match pageref_page(instr, ctx) { Some((n, page_format)) => (field_number(instr, fmt.unwrap_or(page_format), n), true), + // Printed or exported, a reference to a bookmark the document lacks shows Word's + // error (measured in Word for Windows). + None if ctx.output + && !has_switch(instr, 'p') + && pageref_target(instr).is_some_and(|t| !ctx.bookmark_pages.contains_key(t) && !ctx.bookmarks.contains(t)) => + { + let text = if ctx.bookmark_error.is_empty() { BOOKMARK_NOT_DEFINED } else { &ctx.bookmark_error }; + (text.to_string(), true) + } None => (result.to_string(), false), }, "TITLE" if result.is_empty() => (apply_case_switch(instr, ctx.title.to_string()), false), @@ -319,6 +339,10 @@ pub fn field_text_on(instr: &str, result: &str, ctx: &FieldCtx, page: u32) -> (S } } +/// What Word prints for a `PAGEREF` to a bookmark the document doesn't have, in English (Word +/// prints it in its interface language: see [`crate::LayoutOptions::bookmark_error`]). +pub const BOOKMARK_NOT_DEFINED: &str = "Error! Bookmark not defined."; + /// Extract the bookmark target from a `PAGEREF` instruction. fn pageref_target(instr: &str) -> Option<&str> { let mut parts = instr.split_whitespace(); diff --git a/crates/layout/src/headers.rs b/crates/layout/src/headers.rs index bf7bce7a83..0793cc1c5b 100644 --- a/crates/layout/src/headers.rs +++ b/crates/layout/src/headers.rs @@ -236,23 +236,83 @@ pub(crate) fn headers_footers_refer_to_pages(doc: &Document) -> bool { }) } -/// Where each bookmark in the body starts: the number and number format of the page it is placed -/// on (with two of the same name, the first in the document). +/// Whether a story laid out with the body (the body itself, text boxes, footnotes and endnotes) +/// shows an unlocked `PAGEREF` field, which output resolves from the paginated document +/// ([`crate::LayoutOptions::output_page_refs`]); a locked one keeps its result, so it needs no +/// extra pass. Headers and footers are filled in after pagination and need none either. +pub(crate) fn flow_refers_to_pages(doc: &Document) -> bool { + use wordcraft_doc::PartKind; + let refers = |story: StoryRef| { + doc.para_paths(story).iter().filter_map(|path| doc.para(story, path)).any(|p| { + p.objects.iter().any(|o| matches!(o, InlineObject::Field { instr, locked, .. } if !*locked && fields::field_name(instr) == "PAGEREF")) + }) + }; + refers(StoryRef::Body) + || doc + .parts + .iter() + .filter(|(_, part)| matches!(part.kind, PartKind::TextBox | PartKind::Footnote | PartKind::Endnote)) + .any(|(id, _)| refers(StoryRef::Part(*id))) +} + +/// The names of all the document's bookmarks, in any story: a `PAGEREF` to one of them that +/// [`bookmark_pages`] can't place keeps its result rather than showing Word's error. +pub(crate) fn bookmark_names(doc: &Document) -> HashSet { + let mut names = HashSet::new(); + let stories = std::iter::once(StoryRef::Body).chain(doc.parts.keys().map(|id| StoryRef::Part(*id))); + for story in stories { + for path in doc.para_paths(story) { + let Some(p) = doc.para(story, &path) else { continue }; + for o in &p.objects { + if let InlineObject::BookmarkStart { name } = o { + names.insert(name.clone()); + } + } + } + } + names +} + +/// Where each bookmark in the body, a footnote or an endnote, or in a text box anchored in one of +/// them, starts: the number and number format of the page it is placed on (with two of the same +/// name, the first found). A bookmark in a text box is on the page of the box's anchor (measured +/// in Word for Windows); one in a note, on the page that shows that part of the note. pub(crate) fn bookmark_pages(doc: &Document, pages: &[Page], sections: &[(usize, &SectionProps)]) -> fields::BookmarkPages { + use wordcraft_doc::PartKind; // Each paragraph's bookmarks: name, offset, and its line in the paragraph layout last looked // up (the pieces of a paragraph usually share one). - let mut wanted: HashMap)>> = HashMap::new(); + let mut wanted: Wanted = HashMap::new(); let mut seen = HashSet::new(); - for path in doc.para_paths(StoryRef::Body) { - let Some(p) = doc.para(StoryRef::Body, &path) else { continue }; - if !p.objects.iter().any(|o| matches!(o, InlineObject::BookmarkStart { .. })) { - continue; + let mut stories = vec![StoryRef::Body]; + let mut notes: Vec = + doc.parts.iter().filter(|(_, part)| matches!(part.kind, PartKind::Footnote | PartKind::Endnote)).map(|(id, _)| *id).collect(); + notes.sort_unstable(); + stories.extend(notes.into_iter().map(StoryRef::Part)); + for &story in &stories { + for path in doc.para_paths(story) { + let Some(p) = doc.para(story, &path) else { continue }; + if !p.objects.iter().any(|o| matches!(o, InlineObject::BookmarkStart { .. })) { + continue; + } + for (off, o) in p.object_offsets().into_iter().zip(&p.objects) { + if let InlineObject::BookmarkStart { name } = o + && seen.insert(name.as_str()) + { + wanted.entry(story).or_default().entry(path.clone()).or_default().push((name.clone(), off, None)); + } + } } - for (off, o) in p.object_offsets().into_iter().zip(&p.objects) { - if let InlineObject::BookmarkStart { name } = o - && seen.insert(name.as_str()) - { - wanted.entry(path.clone()).or_default().push((name.clone(), off, None)); + } + if doc.parts.values().any(|part| part.kind == PartKind::TextBox) { + let mut boxes = HashSet::new(); + for &story in &stories { + for path in doc.para_paths(story) { + let Some(p) = doc.para(story, &path) else { continue }; + for (off, o) in p.object_offsets().into_iter().zip(&p.objects) { + for id in o.text_boxes() { + box_bookmarks(doc, id, (story, &path, off), &mut boxes, &mut wordcraft_doc::BoxBudget::default(), &mut seen, &mut wanted); + } + } } } } @@ -263,8 +323,9 @@ pub(crate) fn bookmark_pages(doc: &Document, pages: &[Page], sections: &[(usize, } let format = sections.get(page.section).map(|(_, s)| s.page_num_format).unwrap_or_default(); for it in &page.items { - let Placed::Lines { story: StoryRef::Body, path, para, l0, l1, .. } = it else { continue }; - let Some(marks) = wanted.get_mut(path) else { continue }; + let Placed::Lines { story, path, para, l0, l1, .. } = it else { continue }; + let Some(paras) = wanted.get_mut(story) else { continue }; + let Some(marks) = paras.get_mut(path) else { continue }; let layout = Arc::as_ptr(para) as usize; marks.retain_mut(|(name, off, line)| { let li = match *line { @@ -282,21 +343,61 @@ pub(crate) fn bookmark_pages(doc: &Document, pages: &[Page], sections: &[(usize, false }); if marks.is_empty() { - wanted.remove(path); + paras.remove(path); + if paras.is_empty() { + wanted.remove(story); + } } } } out } -/// A key for caches standing for `marks` (0 for none). -pub(crate) fn marks_key(marks: &fields::BookmarkPages) -> u64 { - if marks.is_empty() { - return 0; +/// The bookmarks [`bookmark_pages`] looks for, by story and paragraph: name, offset, and the line +/// in the paragraph layout last looked up. +type Wanted = HashMap)>>>; + +/// Add the bookmarks of text box `id`, and of the boxes inside it, to `wanted` at `anchor` (the +/// story, paragraph and offset of the outermost box). A box shown twice, or inside itself, counts +/// once, and the boxes inside one go as deep as layout shows them ([`wordcraft_doc::BoxBudget`]): a +/// bookmark in a box nested deeper has no page. +fn box_bookmarks<'d>( + doc: &'d Document, + id: u32, + anchor: (StoryRef, &Path, usize), + boxes: &mut HashSet, + budget: &mut wordcraft_doc::BoxBudget, + seen: &mut HashSet<&'d str>, + wanted: &mut Wanted, +) { + if boxes.contains(&id) || !budget.enter(id) { + return; } + boxes.insert(id); + let story = StoryRef::Part(id); + for path in doc.para_paths(story) { + let Some(p) = doc.para(story, &path) else { continue }; + for o in &p.objects { + if let InlineObject::BookmarkStart { name } = o + && seen.insert(name.as_str()) + { + wanted.entry(anchor.0).or_default().entry(anchor.1.clone()).or_default().push((name.clone(), anchor.2, None)); + } + for inner in o.text_boxes() { + box_bookmarks(doc, inner, anchor, boxes, budget, seen, wanted); + } + } + } + budget.leave(); +} + +/// A key for caches standing for `marks`: 0 while the pages aren't known (`None`), something else +/// once they are, even with no bookmarks (output then shows missing ones as errors). +pub(crate) fn marks_key(marks: Option<&fields::BookmarkPages>) -> u64 { + let Some(marks) = marks else { return 0 }; let mut v: Vec<_> = marks.iter().collect(); v.sort_by(|a, b| a.0.cmp(b.0)); - hash_of(&v) + hash_of(&v).max(1) } pub(crate) fn headers_footers(ctx: &mut Ctx, pages: &mut [Page], sections: &[(usize, &SectionProps)], totals: &Totals) { diff --git a/crates/layout/src/lib.rs b/crates/layout/src/lib.rs index 40151d6363..6178d9ceeb 100644 --- a/crates/layout/src/lib.rs +++ b/crates/layout/src/lib.rs @@ -73,7 +73,7 @@ mod table_flow; use boxes::{BOX_INSET_X, BOX_INSET_Y}; use boxes::{BoxInput, BoxLayout, Edges, fit_box, layout_box, push_para}; pub use cache::LayoutCache; -use cache::{MAX_TOTAL_PASSES, Totals}; +use cache::{MAX_PAGE_REF_PASSES, MAX_TOTAL_PASSES, Totals}; #[cfg(test)] use ctx::picture_outline; use ctx::{Ctx, Pass}; @@ -234,6 +234,14 @@ pub struct LayoutOptions { pub filename: Option>, /// Document full path for FILENAME \p fields ([`FieldCtx::filepath`]). pub filepath: Option>, + /// Output (PDF, print, page images): `PAGEREF` fields in the body show the page their + /// bookmark is on, as Word fills them in when it prints or exports. The editor leaves this + /// off: there a body `PAGEREF` keeps its result until fields are updated, as in Word. + pub output_page_refs: bool, + /// What output shows for a `PAGEREF` to a bookmark the document doesn't have: Word prints + /// "Error! Bookmark not defined." in its interface language. `None` is the English text, + /// [`fields::BOOKMARK_NOT_DEFINED`]. + pub bookmark_error: Option>, } /// The word being typed ([`LayoutOptions::typing_word`]): the paragraph by its revision @@ -344,8 +352,15 @@ pub fn layout(doc: &Document, cache: &mut LayoutCache, opts: &LayoutOptions) -> let mut totals = Totals::first_guess(doc.sections().len()); let mut passes = 0; let (mut early, mut rewraps) = (EarlyFloats::new(), 0); + // Output's `PAGEREF`s in the body, text boxes and notes ([`LayoutOptions::output_page_refs`]) + // show the pages the pass before found for their bookmarks, until those hold (bounded, like + // the totals). The first pass, with no pages found yet, shows their stored results. + let page_refs = opts.output_page_refs && headers::flow_refers_to_pages(doc); + let mut marks: Option> = None; + let mut mark_passes = 0; let mut l = loop { - match layout_pass(doc, cache, opts, ¬e_pages, &totals, passes < MAX_TOTAL_PASSES, (&early, rewraps < MAX_REWRAP_PASSES)) { + match layout_pass(doc, cache, opts, (¬e_pages, marks.as_ref()), &totals, passes < MAX_TOTAL_PASSES, (&early, rewraps < MAX_REWRAP_PASSES)) + { Pass::Again(t) => { totals = t; passes += 1; @@ -364,6 +379,18 @@ pub fn layout(doc: &Document, cache: &mut LayoutCache, opts: &LayoutOptions) -> continue; } } + if page_refs && mark_passes < MAX_PAGE_REF_PASSES { + let found = headers::bookmark_pages(doc, &l.pages, &doc.sections()); + if marks.as_deref() != Some(&found) { + marks = Some(Arc::new(found)); + mark_passes += 1; + // The page numbers shown can move text to other pages: the page totals and + // footnotes numbered per page get their passes to settle again. + passes = 0; + note_passes = 1; + continue; + } + } break l; } } diff --git a/crates/layout/src/para/paragraph.rs b/crates/layout/src/para/paragraph.rs index b6da050323..8186468b43 100644 --- a/crates/layout/src/para/paragraph.rs +++ b/crates/layout/src/para/paragraph.rs @@ -411,7 +411,7 @@ impl<'a> Shaped<'a> { /// A field: a legacy form field, its code in braces, or its result. fn field(&mut self, cx: &Cx, (k, o): (usize, &InlineObject), slot: Slot, rc: &Arc) { - let InlineObject::Field { instr, result, code, .. } = o else { return }; + let InlineObject::Field { instr, result, code, locked, .. } = o else { return }; let env = cx.env; let form = if env.field_codes != *code { None } else { o.legacy_form() }; if let Some(wordcraft_doc::legacy_form::LegacyForm::CheckBox { size, .. }) = form { @@ -426,6 +426,9 @@ impl<'a> Shaped<'a> { shaded.shading = Some(FIELD_SHADING); } self.b.shape_atomic(&field_code_text(instr), slot.start, slot.end, &Arc::new(shaded)); + } else if *locked && crate::fields::field_name(instr) == "PAGEREF" { + // A locked page reference keeps its result, as Word prints and exports it. + self.b.shape_atomic(result, slot.start, slot.end, &linked(rc, instr)); } else { self.field_result(cx, (instr, result), slot, rc); } diff --git a/crates/layout/src/pass.rs b/crates/layout/src/pass.rs index a29b2a700c..af5bc8a8e0 100644 --- a/crates/layout/src/pass.rs +++ b/crates/layout/src/pass.rs @@ -2,9 +2,12 @@ use std::collections::VecDeque; use super::cache::{LayoutCache, Totals, env_hash, hash_of}; use super::ctx::{Ctx, Pass, with_pct_base}; +use super::fields::{BOOKMARK_NOT_DEFINED, BookmarkPages}; use super::floats::{EarlyFloats, WrapArea, early_covered, left_out_objects}; use super::flow::{OutlinePass, place_outline_para, place_para}; -use super::headers::{HfLinks, bookmark_pages, headers_footers, headers_footers_refer_to_pages, marks_key, mirror_even_pages, section_side}; +use super::headers::{ + HfLinks, bookmark_names, bookmark_pages, headers_footers, headers_footers_refer_to_pages, marks_key, mirror_even_pages, section_side, +}; use super::notes::{MAX_NOTE_PAGES, NoteSeps, note_info, place_endnotes}; use super::page::{PageBuilder, body_top_for, foot_top_for, item_bottom}; use super::placed::Placed; @@ -60,12 +63,13 @@ fn reset_cache(doc: &Document, cache: &mut LayoutCache, opts: &LayoutOptions) { cache.used.clear(); } -/// The walk state at the start of a pass, with the note references the body shows. +/// The walk state at the start of a pass, with the note references the body shows and the pages +/// of the bookmarks its `PAGEREF`s show (`None` until output has found them). fn new_ctx<'a>( doc: &'a Document, cache: &'a mut LayoutCache, opts: &'a LayoutOptions, - (note_pages, totals): (&HashMap, &Totals), + (note_pages, marks, totals): (&HashMap, Option<&Arc>, &Totals), ) -> Ctx<'a> { let notes = note_info(doc, opts.hides_deleted(StoryRef::Body), note_pages); let notes_hash = hash_of(&{ @@ -89,6 +93,11 @@ fn new_ctx<'a>( author: doc.core.creator.as_str().into(), filename: opts.filename.clone().unwrap_or_else(|| "".into()), filepath: opts.filepath.clone().unwrap_or_else(|| "".into()), + bookmark_pages: marks.cloned().unwrap_or_default(), + bookmarks_key: marks_key(marks.map(|m| &**m)), + output: opts.output_page_refs && marks.is_some(), + bookmarks: if opts.output_page_refs { Arc::new(bookmark_names(doc)) } else { Arc::default() }, + bookmark_error: opts.bookmark_error.clone().unwrap_or_else(|| BOOKMARK_NOT_DEFINED.into()), ..Default::default() }, notes_hash, @@ -482,8 +491,10 @@ fn fill_headers_footers( ctx.track_totals = false; if headers_footers_refer_to_pages(ctx.doc) { let marks = bookmark_pages(ctx.doc, pages, sections); - ctx.fields.bookmarks_key = marks_key(&marks); + ctx.fields.bookmarks_key = marks_key(Some(&marks)); ctx.fields.bookmark_pages = Arc::new(marks); + // The pages are known now: output shows a reference to a missing bookmark as Word does. + ctx.fields.output = ctx.opts.output_page_refs; } headers_footers(ctx, pages, sections, &found); if ctx.doc.settings.mirror_margins { @@ -515,20 +526,21 @@ fn index_lines(pages: &[Page]) -> HashMap<(StoryRef, Path), Vec<(usize, usize)>> } /// One layout pass, numbering footnotes restarted on each page by `note_pages` ([`note_info`]), -/// with `totals` assumed for the page totals in the body. With `may_repeat`, a pass whose body -/// shows totals that turn out different asks to be done again. Pages start with the wrap areas -/// of the `early` floats; with `may_rewrap`, a pass that finds others asks to be done again. +/// with `totals` assumed for the page totals in the body and `marks` for the pages its `PAGEREF`s +/// show. With `may_repeat`, a pass whose body shows totals that turn out different asks to be +/// done again. Pages start with the wrap areas of the `early` floats; with `may_rewrap`, a pass +/// that finds others asks to be done again. pub(crate) fn layout_pass( doc: &Document, cache: &mut LayoutCache, opts: &LayoutOptions, - note_pages: &HashMap, + (note_pages, marks): (&HashMap, Option<&Arc>), totals: &Totals, may_repeat: bool, (early, may_rewrap): (&EarlyFloats, bool), ) -> Pass { reset_cache(doc, cache, opts); - let mut ctx = new_ctx(doc, cache, opts, (note_pages, totals)); + let mut ctx = new_ctx(doc, cache, opts, (note_pages, marks, totals)); let hf = Arc::clone(&ctx.hf); let sections = &hf.sections; let mode = Mode::of(opts.view); diff --git a/crates/layout/src/tests.rs b/crates/layout/src/tests.rs index 6f6b28bd55..845f25db9f 100644 --- a/crates/layout/src/tests.rs +++ b/crates/layout/src/tests.rs @@ -10784,7 +10784,7 @@ fn footer_page_total_needs_one_body_pass() { d.last_section.footers.default = Some(id); let first = |d: &Document| { let totals = Totals::first_guess(d.sections().len()); - layout_pass(d, &mut LayoutCache::new(), &LayoutOptions::default(), &HashMap::new(), &totals, true, (&EarlyFloats::new(), true)) + layout_pass(d, &mut LayoutCache::new(), &LayoutOptions::default(), (&HashMap::new(), None), &totals, true, (&EarlyFloats::new(), true)) }; assert!(matches!(first(&d), Pass::Done(l) if l.pages.len() == 3), "the footer's total asked for another pass"); // The same field in the body is only known once every page is laid out. @@ -14798,7 +14798,15 @@ fn last_rewrap_pass_keeps_early_floats_clear_of_text() { let one_page = picture_above_anchor(&"Earlier text flows beside the picture placed above its anchor. ".repeat(3), 4, 72.0); for d in [one_page, early_float_across_pages()] { let totals = Totals::first_guess(d.sections().len()); - let pass = layout_pass(&d, &mut LayoutCache::new(), &LayoutOptions::default(), &HashMap::new(), &totals, false, (&EarlyFloats::new(), false)); + let pass = layout_pass( + &d, + &mut LayoutCache::new(), + &LayoutOptions::default(), + (&HashMap::new(), None), + &totals, + false, + (&EarlyFloats::new(), false), + ); let Pass::Done(l) = pass else { panic!("a last pass is done") }; let (under, n) = text_under_shapes(&l); assert_eq!(under, None); diff --git a/crates/layout/src/tests/pages.rs b/crates/layout/src/tests/pages.rs index 46252bac6e..476ff1ed96 100644 --- a/crates/layout/src/tests/pages.rs +++ b/crates/layout/src/tests/pages.rs @@ -345,6 +345,296 @@ fn page_references_in_footers_show_their_bookmarks_page() { assert_eq!(texts, ["9"]); } +/// Output (PDF, print, page images) shows each body `PAGEREF` its bookmark's page, counted from +/// the section's restart, as Word fills them in when it prints or exports; the editor keeps the +/// stored result until fields are updated, and a locked reference keeps it in output too. +/// Measured in Word for Microsoft 365: references stored as "9" to a heading on the third page +/// print and export as 3, or 2 when the second page starts a section numbered from 1; a locked +/// one stays 9, in the body and in a footer. +#[test] +fn page_references_in_the_body_show_their_bookmarks_page_in_output() { + let field = |instr: &str, locked: bool| InlineObject::Field { + instr: instr.into(), + result: "9".into(), + locked, + dirty: false, + code: false, + form: String::new(), + }; + let mut d = Document::from_text("See page \nLocked \nBlank\nHeading"); + for (i, instr, locked) in [(0, "PAGEREF _Toc1 \\h", false), (1, "PAGEREF _Toc1", true)] { + let p = d.para_mut(StoryRef::Body, &Path::top(i)).unwrap(); + let n = p.len(); + p.insert_object(n, field(instr, locked), &Default::default()).unwrap(); + } + for i in [2, 3] { + d.para_mut(StoryRef::Body, &Path::top(i)).unwrap().props.page_break_before = Some(true); + } + let heading = d.para_mut(StoryRef::Body, &Path::top(3)).unwrap(); + heading.insert_object(0, InlineObject::BookmarkStart { name: "_Toc1".into() }, &Default::default()).unwrap(); + let refs = |l: &DocLayout| -> Vec { + l.pages[0] + .items + .iter() + .flat_map(|it| if let Placed::Lines { para, .. } = it { para.shown.iter().map(|s| s.1.clone()).collect() } else { vec![] }) + .collect() + }; + let output = LayoutOptions { output_page_refs: true, ..Default::default() }; + // Only an unlocked reference calls for the extra pass: a locked one keeps its result. + assert!(crate::headers::flow_refers_to_pages(&d)); + let mut all_locked = d.clone(); + if let Some(InlineObject::Field { locked, .. }) = all_locked.para_mut(StoryRef::Body, &Path::top(0)).unwrap().objects.last_mut() { + *locked = true; + } + assert!(!crate::headers::flow_refers_to_pages(&all_locked)); + let l = lay(&d); + assert_eq!(l.pages.len(), 3); + assert_eq!(refs(&l), ["9", "9"]); + assert_eq!(refs(&layout(&d, &mut LayoutCache::new(), &output)), ["3", "9"]); + // The second page starts a section that numbers its pages from 1. + let first = d.last_section.clone(); + d.para_mut(StoryRef::Body, &Path::top(1)).unwrap().section = Some(Box::new(first)); + d.last_section.page_num_start = Some(1); + let l = layout(&d, &mut LayoutCache::new(), &output); + assert_eq!(l.pages.iter().map(|p| p.number).collect::>(), [1, 1, 2]); + assert_eq!(refs(&l), ["2", "9"]); + assert_eq!(refs(&lay(&d)), ["9", "9"]); + // A footer's references: the unlocked one shows the page, the locked one keeps its result. + let mut fp = Paragraph::new(); + fp.insert_object(0, field("PAGEREF _Toc1", false), &Default::default()).unwrap(); + fp.insert_object(fp.len(), field("PAGEREF _Toc1", true), &Default::default()).unwrap(); + d.last_section.footers.default = Some(d.add_part(PartKind::Footer, vec![para_block(fp)])); + assert_eq!(footer_shown(&lay(&d)).last().map(String::as_str), Some("2/9")); +} + +/// Printed or exported, a reference to a bookmark the document doesn't have shows Word's error, +/// whether or not the document has other bookmarks (measured in Word for Windows: "Error! +/// Bookmark not defined."); the editor keeps the stored result, and so does a reference that +/// shows "above" or "below" (`\p`). +#[test] +fn a_page_reference_to_a_missing_bookmark_shows_words_error_in_output() { + let field = + |instr: &str| InlineObject::Field { instr: instr.into(), result: "9".into(), locked: false, dirty: false, code: false, form: String::new() }; + let output = LayoutOptions { output_page_refs: true, ..Default::default() }; + for other_mark in [false, true] { + let mut d = Document::from_text("See \nAbove \nTarget"); + for (i, instr) in [(0, "PAGEREF NoSuchMark \\h"), (1, "PAGEREF NoSuchMark \\p")] { + let p = d.para_mut(StoryRef::Body, &Path::top(i)).unwrap(); + let n = p.len(); + p.insert_object(n, field(instr), &Default::default()).unwrap(); + } + if other_mark { + let p = d.para_mut(StoryRef::Body, &Path::top(2)).unwrap(); + p.insert_object(0, InlineObject::BookmarkStart { name: "Elsewhere".into() }, &Default::default()).unwrap(); + } + let shown = |l: &DocLayout| -> Vec { + l.pages[0] + .items + .iter() + .flat_map(|it| if let Placed::Lines { para, .. } = it { para.shown.iter().map(|s| s.1.clone()).collect() } else { vec![] }) + .collect() + }; + assert_eq!(shown(&layout(&d, &mut LayoutCache::new(), &output)), [crate::fields::BOOKMARK_NOT_DEFINED, "9"], "other bookmark: {other_mark}"); + assert_eq!(shown(&lay(&d)), ["9", "9"], "the editor, other bookmark: {other_mark}"); + // One cache for the editor's layout and then output's: output doesn't reuse the + // editor's paragraphs, and the editor doesn't reuse output's after it. + let mut cache = LayoutCache::new(); + let editor = LayoutOptions::default(); + assert_eq!(shown(&layout(&d, &mut cache, &editor)), ["9", "9"]); + assert_eq!( + shown(&layout(&d, &mut cache, &output)), + [crate::fields::BOOKMARK_NOT_DEFINED, "9"], + "a shared cache, other bookmark: {other_mark}" + ); + assert_eq!(shown(&layout(&d, &mut cache, &editor)), ["9", "9"], "the editor after output, other bookmark: {other_mark}"); + } +} + +/// Printed or exported, a reference to a bookmark in a text box shows the page of the box's +/// anchor (measured in Word for Windows), not "Error! Bookmark not defined.". +#[test] +fn a_page_reference_to_a_bookmark_in_a_text_box_shows_its_anchors_page_in_output() { + use wordcraft_doc::para::{Float, ShapeKind, Wrap}; + let mut d = Document::from_text("See \nSecond"); + d.para_mut(StoryRef::Body, &Path::top(1)).unwrap().props.page_break_before = Some(true); + let mut inner = Paragraph::with_text("Caption", Default::default()); + inner.insert_object(0, InlineObject::BookmarkStart { name: "Boxed".into() }, &Default::default()).unwrap(); + let story = d.add_part(PartKind::TextBox, vec![para_block(inner)]); + let shape = InlineObject::Shape { + kind: ShapeKind::TextBox, + w: 100.0, + h: 40.0, + fill: None, + stroke: None, + stroke_width: 0.0, + float: Float { wrap: Wrap::Inline, ..Default::default() }, + story: Some(story), + freeform: None, + effects: Default::default(), + extra: Default::default(), + }; + d.para_mut(StoryRef::Body, &Path::top(1)).unwrap().insert_object(0, shape, &Default::default()).unwrap(); + let field = + InlineObject::Field { instr: "PAGEREF Boxed \\h".into(), result: "9".into(), locked: false, dirty: false, code: false, form: String::new() }; + let p = d.para_mut(StoryRef::Body, &Path::top(0)).unwrap(); + let n = p.len(); + p.insert_object(n, field, &Default::default()).unwrap(); + let output = layout(&d, &mut LayoutCache::new(), &LayoutOptions { output_page_refs: true, ..Default::default() }); + let shown: Vec = output.pages[0] + .items + .iter() + .flat_map(|it| match it { + Placed::Lines { story: StoryRef::Body, para, .. } => para.shown.iter().map(|s| s.1.clone()).collect(), + _ => vec![], + }) + .collect(); + assert_eq!(shown, ["2"]); +} + +/// The field results shown on page `page` by the lines of `story`. +fn shown_in(l: &DocLayout, page: usize, story: StoryRef) -> Vec { + l.pages[page] + .items + .iter() + .flat_map(|it| match it { + Placed::Lines { story: s, para, .. } if *s == story => para.shown.iter().map(|s| s.1.clone()).collect(), + _ => vec![], + }) + .collect() +} + +/// A page reference field showing `result` until it is updated. +fn pageref(instr: &str, result: &str) -> InlineObject { + InlineObject::Field { instr: instr.into(), result: result.into(), locked: false, dirty: false, code: false, form: String::new() } +} + +/// Three pages, a bookmark "Body" on the third; a text box on the first page and a footnote on +/// the second refer to it, the footnote also to a bookmark that doesn't exist, and holds the +/// bookmark "InNote"; the header holds the bookmark "InHeader". With `body_refs` the first +/// paragraph refers to "InNote" and "InHeader" too. Returns the document and the box's and the +/// note's stories. +fn refs_outside_the_body(body_refs: bool) -> (Document, StoryRef, StoryRef) { + use wordcraft_doc::para::{Float, ShapeKind, Wrap}; + let mut d = Document::from_text("Intro \nSecond\nTarget"); + for i in [1, 2] { + d.para_mut(StoryRef::Body, &Path::top(i)).unwrap().props.page_break_before = Some(true); + } + d.para_mut(StoryRef::Body, &Path::top(2)) + .unwrap() + .insert_object(0, InlineObject::BookmarkStart { name: "Body".into() }, &Default::default()) + .unwrap(); + let mut boxed = Paragraph::with_text("Box ", Default::default()); + boxed.insert_object(boxed.len(), pageref("PAGEREF Body \\h", "9"), &Default::default()).unwrap(); + let box_story = d.add_part(PartKind::TextBox, vec![para_block(boxed)]); + let shape = InlineObject::Shape { + kind: ShapeKind::TextBox, + w: 100.0, + h: 40.0, + fill: None, + stroke: None, + stroke_width: 0.0, + float: Float { wrap: Wrap::Inline, ..Default::default() }, + story: Some(box_story), + freeform: None, + effects: Default::default(), + extra: Default::default(), + }; + d.para_mut(StoryRef::Body, &Path::top(0)).unwrap().insert_object(0, shape, &Default::default()).unwrap(); + let mut note = Paragraph::with_text("Note ", Default::default()); + note.insert_object(0, InlineObject::BookmarkStart { name: "InNote".into() }, &Default::default()).unwrap(); + for f in [pageref("PAGEREF Body \\h", "9"), pageref("PAGEREF Gone \\h", "9")] { + note.insert_object(note.len(), f, &Default::default()).unwrap(); + } + let note_id = d.add_part(PartKind::Footnote, vec![para_block(note)]); + d.insert_object(&Pos::body(1, 6), InlineObject::NoteRef { kind: NoteKind::Footnote, id: note_id, custom: String::new() }, &Default::default()) + .unwrap(); + let mut hp = Paragraph::with_text("Header", Default::default()); + hp.insert_object(0, InlineObject::BookmarkStart { name: "InHeader".into() }, &Default::default()).unwrap(); + d.last_section.headers.default = Some(d.add_part(PartKind::Header, vec![para_block(hp)])); + if body_refs { + let p = d.para_mut(StoryRef::Body, &Path::top(0)).unwrap(); + for f in [pageref("PAGEREF InNote \\h", "9"), pageref("PAGEREF InHeader \\h", "9")] { + p.insert_object(p.len(), f, &Default::default()).unwrap(); + } + } + (d, StoryRef::Part(box_story), StoryRef::Part(note_id)) +} + +/// Printed or exported, page references in text boxes and notes show their bookmarks' pages too, +/// also when the body has none (the extra pass is for them as well); a bookmark in a note is on +/// the page that shows the note; a reference to a bookmark that exists where pages aren't found +/// (a header) keeps its result, and only one to a bookmark nowhere in the document shows Word's +/// error. The editor keeps every stored result. +#[test] +fn page_references_outside_the_body_show_pages_in_output() { + let output = LayoutOptions { output_page_refs: true, ..Default::default() }; + for body_refs in [false, true] { + let (d, boxed, note) = refs_outside_the_body(body_refs); + assert!(crate::headers::flow_refers_to_pages(&d)); + let l = layout(&d, &mut LayoutCache::new(), &output); + assert_eq!(l.pages.len(), 3); + assert_eq!(shown_in(&l, 0, boxed), ["3"], "the text box, body refs: {body_refs}"); + assert_eq!(shown_in(&l, 1, note), ["3", crate::fields::BOOKMARK_NOT_DEFINED], "the footnote, body refs: {body_refs}"); + let body: Vec = if body_refs { vec!["2".into(), "9".into()] } else { vec![] }; + assert_eq!(shown_in(&l, 0, StoryRef::Body), body, "body refs: {body_refs}"); + let editor = lay(&d); + assert_eq!(shown_in(&editor, 0, boxed), ["9"]); + assert_eq!(shown_in(&editor, 1, note), ["9", "9"]); + } +} + +/// Output shows a reference to a missing bookmark in the text it is given for the interface +/// language (Word prints its error in its own), English without one. +#[test] +fn a_missing_bookmarks_error_is_in_the_interface_language() { + let (d, _, note) = refs_outside_the_body(false); + let french: Arc = "Erreur ! Signet non défini.".into(); + let l = + layout(&d, &mut LayoutCache::new(), &LayoutOptions { output_page_refs: true, bookmark_error: Some(french.clone()), ..Default::default() }); + assert_eq!(shown_in(&l, 1, note), ["3", &*french]); +} + +/// The first pass of output, before any bookmark's page is known, shows the stored results (the +/// closest guess: a table of contents isn't stretched by errors), not Word's error. +#[test] +fn outputs_first_pass_shows_stored_page_references() { + let mut d = Document::from_text("See "); + let p = d.para_mut(StoryRef::Body, &Path::top(0)).unwrap(); + p.insert_object(p.len(), pageref("PAGEREF Gone \\h", "9"), &Default::default()).unwrap(); + let output = LayoutOptions { output_page_refs: true, ..Default::default() }; + let totals = crate::cache::Totals::first_guess(d.sections().len()); + let first = crate::pass::layout_pass( + &d, + &mut LayoutCache::new(), + &output, + (&std::collections::HashMap::new(), None), + &totals, + true, + (&crate::floats::EarlyFloats::new(), true), + ); + let crate::ctx::Pass::Done(l) = first else { panic!("one page needs no other pass") }; + assert_eq!(shown_in(&l, 0, StoryRef::Body), ["9"]); + assert_eq!(shown_in(&layout(&d, &mut LayoutCache::new(), &output), 0, StoryRef::Body), [crate::fields::BOOKMARK_NOT_DEFINED]); +} + +/// Output's page references can change the page count after the totals settled (here many +/// references to a missing bookmark grow from their stored "9" to Word's error, adding pages): +/// the body's `NUMPAGES` still shows the pages the document ends with. +#[test] +fn output_page_references_that_change_the_page_count_leave_totals_right() { + const REFS: usize = 300; + let mut d = Document::from_text(&" ".repeat(REFS)); + let p = d.para_mut(StoryRef::Body, &Path::top(0)).unwrap(); + for off in (1..=REFS).rev() { + p.insert_object(off, pageref("PAGEREF Gone \\h", "9"), &Default::default()).unwrap(); + } + p.insert_object(0, pageref("NUMPAGES", "9"), &Default::default()).unwrap(); + let stored = lay(&d).pages.len(); + let l = layout(&d, &mut LayoutCache::new(), &LayoutOptions { output_page_refs: true, ..Default::default() }); + assert!(l.pages.len() > stored, "{} pages, {stored} with the stored results", l.pages.len()); + assert_eq!(shown_in(&l, 0, StoryRef::Body).first(), Some(&l.pages.len().to_string())); +} + /// The fields' text in each page's footer, joined with "/". fn footer_shown(l: &DocLayout) -> Vec { l.pages @@ -771,3 +1061,45 @@ fn table_cell_page_field_uses_the_section_number_format() { .collect(); assert_eq!(shown, "one"); } + +/// Printed or exported, a reference to a bookmark in a text box nested in text boxes shows the +/// outermost box's anchor page as deep as layout shows the boxes ([`wordcraft_doc::MAX_TEXT_BOX_DEPTH`] +/// levels); one nested deeper, which layout doesn't show, keeps its stored result. +#[test] +fn a_page_reference_into_nested_text_boxes_stops_where_layout_does() { + use wordcraft_doc::para::{Float, ShapeKind, Wrap}; + let shape = |story: u32| InlineObject::Shape { + kind: ShapeKind::TextBox, + w: 100.0, + h: 40.0, + fill: None, + stroke: None, + stroke_width: 0.0, + float: Float { wrap: Wrap::Inline, ..Default::default() }, + story: Some(story), + freeform: None, + effects: Default::default(), + extra: Default::default(), + }; + let deepest = wordcraft_doc::MAX_TEXT_BOX_DEPTH + 1; + let mut d = Document::from_text("See \nSecond"); + d.para_mut(StoryRef::Body, &Path::top(1)).unwrap().props.page_break_before = Some(true); + // From the deepest box out: box `level` holds bookmark "Level{level}" and the box inside it. + let mut inner: Option = None; + for level in (1..=deepest).rev() { + let mut p = Paragraph::with_text("Box", Default::default()); + p.insert_object(0, InlineObject::BookmarkStart { name: format!("Level{level}") }, &Default::default()).unwrap(); + if let Some(id) = inner { + p.insert_object(p.len(), shape(id), &Default::default()).unwrap(); + } + inner = Some(d.add_part(PartKind::TextBox, vec![para_block(p)])); + } + d.para_mut(StoryRef::Body, &Path::top(1)).unwrap().insert_object(0, shape(inner.unwrap()), &Default::default()).unwrap(); + let p = d.para_mut(StoryRef::Body, &Path::top(0)).unwrap(); + for level in [1, wordcraft_doc::MAX_TEXT_BOX_DEPTH, deepest] { + let n = p.len(); + p.insert_object(n, pageref(&format!("PAGEREF Level{level} \\h"), "9"), &Default::default()).unwrap(); + } + let output = layout(&d, &mut LayoutCache::new(), &LayoutOptions { output_page_refs: true, ..Default::default() }); + assert_eq!(shown_in(&output, 0, StoryRef::Body), ["2", "2", "9"]); +} diff --git a/crates/pdf/src/export.rs b/crates/pdf/src/export.rs index 81b7b94d20..759b3c7ab5 100644 --- a/crates/pdf/src/export.rs +++ b/crates/pdf/src/export.rs @@ -9,7 +9,8 @@ use super::{ /// Lay out `doc` and write it as PDF. Without markup the layout is the final text: tracked /// deletions are left out, as in Word's "No Markup" view. With `comments` each page carries the -/// markup area with the comment balloons. +/// markup area with the comment balloons. Page references in the body show their bookmarks' +/// pages, as Word's export fills them in. pub fn export(doc: &Document, opts: &PdfOptions) -> Result, PdfError> { write::guard(|| { let lay = layout(doc, &mut LayoutCache::new(), &opts.layout_options()); diff --git a/crates/pdf/src/options.rs b/crates/pdf/src/options.rs index 7a0f57d8da..5f7baa803c 100644 --- a/crates/pdf/src/options.rs +++ b/crates/pdf/src/options.rs @@ -50,6 +50,10 @@ pub struct PdfOptions { /// How [`export`] shows digits (the Numeral setting; callers resolve `System`, see /// [`NumeralMode::resolve`]). [`export_layout`] keeps the layout it is given. pub numeral: NumeralMode, + /// What [`export`] shows for a page reference to a bookmark the document doesn't have, in the + /// interface language (`None`: Word's English "Error! Bookmark not defined."). [`export_layout`] + /// keeps the layout it is given. + pub bookmark_error: Option>, } /// How many characters of the watermark text the PDF draws. @@ -70,12 +74,15 @@ impl PdfOptions { } } - /// How [`crate::export`] lays a document out for these options. + /// How [`crate::export`] lays a document out for these options. Page references in the body + /// show their bookmarks' pages, as Word's export fills them in. pub fn layout_options(&self) -> wordcraft_layout::LayoutOptions { wordcraft_layout::LayoutOptions { hide_deleted: !self.include_markup, comment_balloons: self.comments, numeral: self.numeral, + output_page_refs: true, + bookmark_error: self.bookmark_error.clone(), ..Default::default() } } @@ -98,6 +105,7 @@ impl Default for PdfOptions { links: true, paper: None, numeral: NumeralMode::Arabic, + bookmark_error: None, } } } diff --git a/crates/pdf/src/tests.rs b/crates/pdf/src/tests.rs index aab3988cc5..efa7681478 100644 --- a/crates/pdf/src/tests.rs +++ b/crates/pdf/src/tests.rs @@ -3156,6 +3156,27 @@ fn baseline_is_the_most_shared_y() { assert_eq!(baseline(&[(1, 0.0, -0.0), (2, 3.0, 0.0)]), Some(0.0)); } +/// The exported PDF shows a body page reference's page and Word's error for a missing bookmark, +/// as Word's export does, where the document stores "9" for both. +#[test] +fn exported_page_references_show_the_page_or_words_error() { + let field = + |instr: &str| InlineObject::Field { instr: instr.into(), result: "9".into(), locked: false, dirty: false, code: false, form: String::new() }; + let mut d = Document::from_text("See \nMissing \nTarget"); + for (i, instr) in [(0, "PAGEREF Target"), (1, "PAGEREF NoSuchMark")] { + let p = d.para_mut(wordcraft_doc::StoryRef::Body, &wordcraft_doc::Path::top(i)).unwrap(); + let n = p.len(); + p.insert_object(n, field(instr), &CharProps::default()).unwrap(); + } + let target = d.para_mut(wordcraft_doc::StoryRef::Body, &wordcraft_doc::Path::top(2)).unwrap(); + target.props.page_break_before = Some(true); + target.insert_object(0, InlineObject::BookmarkStart { name: "Target".into() }, &CharProps::default()).unwrap(); + let text = extract_text(&export(&d, &PdfOptions::default()).unwrap()); + let first = squash(&text[0]); + assert!(first.contains("See 2"), "{first}"); + assert!(first.contains("Missing Error! Bookmark not defined."), "{first}"); +} + #[test] fn the_author_is_left_out_when_personal_information_is_removed() { let mut d = Document::from_text("Private"); diff --git a/crates/ui-egui/src/app.rs b/crates/ui-egui/src/app.rs index ddfa5f97b1..96dba9b114 100644 --- a/crates/ui-egui/src/app.rs +++ b/crates/ui-egui/src/app.rs @@ -251,6 +251,10 @@ impl WordApp { crate::language_packs::tick(self); let lang = i18n::Lang::from_pref(&self.ui.language); i18n::set_current(lang); + // PDFs and prints show a page reference or a REF to a missing bookmark in the + // interface's language, as Word prints them in its own. + wordcraft_engine::set_bookmark_error(i18n::tr(lang, "Error! Bookmark not defined.")); + wordcraft_engine::set_reference_error(i18n::tr(lang, "Error! Reference source not found.")); crate::rtl::sync(ctx); // New documents are written in the interface's language when WordCraft can proof it // (a Polish interface: Polish spelling, grammar and hyphenation from the first word). diff --git a/docs/gaps.md b/docs/gaps.md index 1a22b57ddf..a3d2a9ec6a 100644 --- a/docs/gaps.md +++ b/docs/gaps.md @@ -240,6 +240,7 @@ Page Setup's margin, paper-size and document-grid number boxes scroll long text | 2026-11-04 | trivial | PR #4609: relative REF keeps context already displayed by the own or a needed ancestor label; six synthetic legal-template cases and separate-list context follow the Word for Windows measurements reported by @pakiat in PR discussion. Existing unknown-switch/cache boundaries and readiness estimates unchanged; no new native Word run. | | 2026-11-01 | trivial | #19 narrowed: ODT read and written nearly whole on this branch (styles, tables, notes, comments, tracked changes including formatting, fields, indexes and marks, drawings, charts, embedded objects, forms, ruby, password protection, flat ODT), checked against LibreOffice; what's left listed; estimate 18–27 h → 10–16 h | | 2026-11-01 | trivial | #10 narrowed: text in a turned text box is drawn turned with it on screen and in PNG and PDF (upside down when flipped across, never mirrored); editing it still goes by its upright text; estimate unchanged | +| 2026-10-31 | trivial | PDFs, prints and page images show body PAGEREF fields' pages, so a table of contents prints its headings' pages, as Word does; not a ranked gap; readiness estimates unchanged | | 2026-10-29 | trivial | Print Markup balloon anchor discovery no longer repeats paragraph-prefix scans (#3614); readiness estimates unchanged | | 2026-10-28 | trivial | Print Markup text-copy comment discovery walks paragraph objects once (#3614); quotes, order, limits and readiness estimates unchanged | | 2026-11-04 | trivial | Table Sort rejects malformed or nonexistent explicit columns before mutation; valid columns, the omitted-column default and history are retained (#5531). Readiness estimates unchanged. | diff --git a/docs/layout-parity.md b/docs/layout-parity.md index 957164306b..55c2b611b0 100644 --- a/docs/layout-parity.md +++ b/docs/layout-parity.md @@ -101,8 +101,8 @@ Exact line spacing keeps the run font baseline around tall equations; automatic | Fields: PAGE, NUMPAGES, SECTIONPAGES, TOC page numbers | ✅ | #52; totals in the body need a second pass once the page count is known (#451); SECTIONPAGES includes shared continuous-section start pages | — | | Compatibility modes (Word 2003/2007/2010 layout for old files: `w:compat` options) | 🟡 | `allowSpaceOfSameStyleInTable` supported in modes 11/12/14; mode 15 retains contextual suppression. `doNotExpandShiftReturn` keeps justified lines that end in a manual line break short (#3924). `doNotSuppressIndentation` (Word 2003's indent rules; a `.doc`'s `Copts.fWW11IndentRules`): below mode 15 an unnumbered paragraph's line starts right after a floating object that ends before its indent, never in the margin, and not beside a drop cap (#5939); the numbered-paragraph half of the rule is not implemented, and files set it only once craft-libs reads it. Most other legacy compat options remain ignored | 10–20 | | Fields: STYLEREF in headers and footers (running chapter titles) | ✅ | Evaluated per page at layout time: the page's first (or with `\l` last) paragraph of the style, else the nearest before it; style name, id or heading level (a level finds the style named `heading N` whatever its id, so localized documents match, #1286); character styles; `\n \r \w \s \t \p` (`\r` treated as `\w`); body STYLEREF updated with the other fields (#775). Field results with right-to-left text (a Hebrew heading, "פרק א") are laid out with bidi reordering like ordinary text: the result is an isolate taking its first strong letter's direction (else the text's around the field), and each level run is shaped and mirrored in its own direction, so `{ PAGE }` in field-code view and `(Chapter 1)` keep their brackets in right-to-left paragraphs; this covers every field and note mark shown as text (#1670). Header paragraphs are cached on their per-page results, so typing in body text no STYLEREF shows doesn't lay the headers out again (#1286) | — | -| Fields filled in for output: SEQ, STYLEREF, REF in the body | ✅ | PDF export, print jobs and page images lay out a copy whose unlocked SEQ, STYLEREF and REF fields show their current results, as Word does when printing or exporting with Update fields before printing off (measured in Word for Windows with stale stored results); a locked SEQ keeps its result but still counts, its `\r` too, and a SEQ in a tracked deletion keeps its result and doesn't count, with markup shown or hidden (measured in Word for Windows); NUMWORDS, FILENAME, the document properties and formulas keep their stored results, as in Word; REF fields with `\p`, `\r`, `\n` or `\w` (above or below, and paragraph numbers) keep theirs until those are computed, and so does a REF to a bookmark that ends in a later paragraph (Word shows its paragraphs as paragraphs of the result); SEQ numbers are filled in before the STYLEREF and REF fields that read them, so a STYLEREF to a heading holding a SEQ field shows its new number (after F9 too); SEQ fields in text boxes are numbered where their boxes are anchored, after F9 too, and a REF to a bookmark in a text box, header, footer, footnote, endnote or comment shows that text as stored, as in Word; a REF to a bookmark the document lacks prints "Error! Reference source not found."; the document is unchanged (`cmd::references::tests::output_shows_fresh_seq_styleref_and_ref_results`, `cmd::references::tests::output_numbers_text_box_captions_where_their_boxes_are_anchored`, `cmd::references::tests::output_shows_references_to_bookmarks_outside_the_body`, `cmd::references::tests::output_shows_words_error_for_a_reference_to_a_missing_bookmark`, `cmd::references::tests::output_counts_locked_seq_fields_and_not_deleted_ones`) | — | -| Fields: PAGE, NUMPAGES, SECTIONPAGES, TOC page numbers, PAGEREF in headers and footers | ✅ | #52; totals in the body need a second pass once the page count is known (#451); SECTIONPAGES includes shared continuous-section start pages; a PAGE field in a paragraph that runs onto a later page (a page break inside it, or a natural split) shows that page's number, the rest of the paragraph broken again for the wider result (#1352); PAGEREF in headers and footers shows its bookmark's page, filled in after pagination like their totals (#1477); in the body it keeps its result until fields are updated | — | +| Fields filled in for output: SEQ, STYLEREF, REF in the body | ✅ | PDF export, print jobs and page images lay out a copy whose unlocked SEQ, STYLEREF and REF fields show their current results, as Word does when printing or exporting with Update fields before printing off (measured in Word for Windows with stale stored results); a locked SEQ keeps its result but still counts, its `\r` too, and a SEQ in a tracked deletion keeps its result and doesn't count, with markup shown or hidden (measured in Word for Windows); NUMWORDS, FILENAME, the document properties and formulas keep their stored results, as in Word; REF fields with `\p`, `\r`, `\n` or `\w` (above or below, and paragraph numbers) keep theirs until those are computed, and so does a REF to a bookmark that ends in a later paragraph (Word shows its paragraphs as paragraphs of the result); SEQ numbers are filled in before the STYLEREF and REF fields that read them, so a STYLEREF to a heading holding a SEQ field shows its new number (after F9 too); SEQ fields in text boxes are numbered where their boxes are anchored, after F9 too, and a REF to a bookmark in a text box, header, footer, footnote, endnote or comment shows that text as stored, as in Word; a REF to a bookmark the document lacks prints "Error! Reference source not found.", which the shell can give in the interface language as Word prints it in its own (English in every language until craft-i18n has the text); the document is unchanged (`cmd::references::tests::output_shows_fresh_seq_styleref_and_ref_results`, `cmd::references::tests::output_numbers_text_box_captions_where_their_boxes_are_anchored`, `cmd::references::tests::output_shows_references_to_bookmarks_outside_the_body`, `cmd::references::tests::output_shows_words_error_for_a_reference_to_a_missing_bookmark`, `cmd::references::tests::output_counts_locked_seq_fields_and_not_deleted_ones`, `cmd::references::tests::a_missing_references_error_is_in_the_interface_language`) | — | +| Fields: PAGE, NUMPAGES, SECTIONPAGES, TOC page numbers, PAGEREF in headers and footers | ✅ | #52; totals in the body need a second pass once the page count is known (#451); SECTIONPAGES includes shared continuous-section start pages; a PAGE field in a paragraph that runs onto a later page (a page break inside it, or a natural split) shows that page's number, the rest of the paragraph broken again for the wider result (#1352); PAGEREF in headers and footers shows its bookmark's page, filled in after pagination like their totals (#1477); in the body it keeps its result until fields are updated on screen, and shows its bookmark's page (from the section's restart) in PDFs, prints and page images, as Word fills it in when it prints or exports, so a table of contents prints the pages its headings are on; so do references in text boxes, footnotes and endnotes, and a bookmark in a note is on the page that shows it; a reference to a bookmark the document doesn't have prints Word's "Error! Bookmark not defined." in the interface language, while one to a bookmark in a header or comment keeps its result; a locked PAGEREF keeps its result everywhere | — | | Fields: `\* DollarText`, `\* Hex` and `\* ArabicDash` | 🟡 | `\* DollarText` writes lowercase cardinal text, "and", and the first two decimals over 100 (`{ = 9.20 + 5.35 \* DollarText }` shows "fourteen and 55/100"), `\* Hex` uppercase hexadecimal digits (458 shows "1CA"), and `\* ArabicDash` the number between hyphens (`{ PAGE \* ArabicDash }` shows "- 31 -"), in table formulas and in the page-number, SEQ, PAGEREF, NUMWORDS, NUMCHARS and REVNUM fields; a capitalization switch applies after them (#4226). A result past 999,999 in cardinal or ordinal text, or past 999,999.99 in dollar text, keeps its digits, and so does a negative result or a fractional Hex or ArabicDash result. `layout::fields::tests::dollar_text_hex_and_arabic_dash_switches`, `engine::cmd::table_formula::tests::dollar_text_and_hex_switches_write_the_result`, `engine::tests::table_formula_results_take_dollar_text_and_hex`; not compared with Word | — | | Page-by-page comparison harness against Word | ❌ | Run Word locally on our own synthetic documents, export PDF, compare line breaks; Word output stays under `plan/` (never committed) | 8–12 | @@ -311,6 +311,7 @@ The front-of-text opt-out is retained from the earlier implementation; this patc | 2026-10-29 | trivial | A list item deleted whole under Track Changes shows its number in the deletion's colour and with its mark (struck through by default) with markup, and not at all without (#4828) | | 2026-11-04 | trivial | Headers, footers and note separators of the second and later sections are measured with their own section's document grid and SECTION/SECTIONPAGES values, not the previous section's; a regression from the #4501 refactor (#4683). `layout::tests::pages::a_sections_header_is_measured_without_the_previous_sections_grid` | | 2026-11-08 | trivial | Turned inline pictures with no recorded effect extent keep their line to the frame (exchanged near a quarter turn in Word 2013+ layout) and overhang it, cut at the line's top and bottom, as in Word | +| 2026-11-04 | trivial | PAGEREF in text boxes and notes shows pages in output; PAGEREF's and REF's missing-bookmark errors in the interface language; readiness estimates unchanged | | 2026-11-08 | trivial | Contextual spacing drops the space after a table cell's last paragraph in the Normal style, the end-of-cell mark counting as a Normal paragraph; another style keeps it, and a middle or bottom cell of a split row lines up without the dropped space (#5450) (`layout::tests::contextual_spacing_drops_the_space_after_a_cells_last_normal_paragraph`, `a_bottom_cell_of_a_split_row_ignores_a_dropped_space_after_beside_it`). | | 2026-11-04 | trivial | Header table measurements and fitted text-box heights use the page section’s PAGE format; cache reuse follows the field context | | 2026-11-03 | trivial | Body PAGE fields in tables use the active section number format; reflow views measure headers and footers with it before body placement | @@ -331,6 +332,7 @@ The front-of-text opt-out is retained from the earlier implementation; this patc | 2026-11-04 | trivial | Output counts a locked SEQ and not one in a tracked deletion, as Word does; readiness estimates unchanged | | 2026-11-01 | trivial | SEQ fields in text boxes are numbered where their boxes are anchored, in output and after F9, and a REF finds a bookmark in a text box | | 2026-11-01 | trivial | SEQ, STYLEREF and REF fields show fresh results in output; readiness estimates unchanged | +| 2026-10-31 | trivial | Body PAGEREF fields show their bookmarks' pages in PDFs, prints and page images, as Word fills them in when it prints or exports (measured in Word for Microsoft 365: references stored as 9 print and export as 3, or 2 after a section numbered from 1); a locked PAGEREF keeps its result, in the body and in headers and footers; one to a bookmark in a text box shows the page of the box's anchor; one to a bookmark the document lacks prints "Error! Bookmark not defined.", as in Word. `layout::tests::pages::page_references_in_the_body_show_their_bookmarks_page_in_output`, `layout::tests::pages::a_page_reference_to_a_missing_bookmark_shows_words_error_in_output`, `layout::tests::pages::a_page_reference_to_a_bookmark_in_a_text_box_shows_its_anchors_page_in_output`, `pdf::tests::exported_page_references_show_the_page_or_words_error`, `engine::tests::output_shows_toc_page_numbers_where_the_headings_are` | | 2026-10-29 | trivial | Print Markup balloon anchor discovery walks paragraph objects once (#3614); readiness estimates unchanged | | 2026-11-03 | trivial | A decimal tab scans the text after it once, not once per cluster. Separate from the #3412 word-measurement fix | | 2026-10-30 | trivial | Layout work bounds for hostile documents (#3867): header-row repeats budgeted per layout and counting canvas members; picture-outline decode budget charged for cached outlines too, so cold and warm layouts wrap alike; linked-box chains keep exact widths up to a work cap, not 16 widths; `gridAfter` bounded |