mirror of
https://github.com/storytold/wordcraft.git
synced 2026-11-20 09:25:21 +00:00
References: TOC, index, table of figures and page cross-references use the section's page number format (#3856) (#5971)
This commit is contained in:
1 parent
53e05c2420
commit
c99dd5cc6e
10 files changed
+440
-42
No files matched your search
@@ -19,6 +19,7 @@ mod sources;
|
||||
mod styles;
|
||||
|
||||
use cross_refs::cross_ref;
|
||||
pub(crate) use cross_refs::leading_breaks;
|
||||
pub use cross_refs::{caption_labels, ref_targets};
|
||||
#[cfg(test)]
|
||||
use generated::ENTRY_STYLE;
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
use super::generated::page_of;
|
||||
use super::{CharProps, CmdError, CmdResult, Document, InlineObject, Paragraph, Pos, Selection, Session, StoryRef, Value, delete_selection, json, p};
|
||||
use crate::cmd::references::page_label;
|
||||
|
||||
pub(super) fn cross_ref(s: &mut Session, v: &Value) -> CmdResult {
|
||||
let to = p::str(v, "to").unwrap_or("heading");
|
||||
@@ -10,9 +10,10 @@ pub(super) fn cross_ref(s: &mut Session, v: &Value) -> CmdResult {
|
||||
let find = |ts: Vec<(String, Pos)>| ts.into_iter().find(|(t, _)| t == target || t.starts_with(target));
|
||||
let (text, pos) = find(targets).ok_or_else(|| CmdError::Params(format!("no {to} `{target}`")))?;
|
||||
let show = p::str(v, "show").unwrap_or("text");
|
||||
let page = page_of(s, &pos);
|
||||
let result = match show {
|
||||
"page" => page.to_string(),
|
||||
// The page the target's text starts on (after its leading page breaks), as its footer
|
||||
// shows it.
|
||||
"page" => page_label(s, &Pos { off: leading_breaks(&s.doc, &pos), ..pos.clone() }),
|
||||
"number" => text.split(':').next().unwrap_or(&text).trim().to_string(),
|
||||
"aboveBelow" => {
|
||||
if pos < s.sel.focus {
|
||||
@@ -152,6 +153,23 @@ pub fn ref_targets(s: &Session, to: &str) -> Vec<(String, Pos)> {
|
||||
targets
|
||||
}
|
||||
|
||||
/// The offset just past the page breaks at the start of the paragraph at `pos`, skipping bookmark
|
||||
/// marks among them (a `_Ref` bookmark may start before the breaks): its text starts there.
|
||||
pub(crate) fn leading_breaks(doc: &Document, pos: &Pos) -> usize {
|
||||
let Some(p) = doc.para(pos.story, &pos.path) else { return 0 };
|
||||
let mut after = 0;
|
||||
for (i, c) in p.text.char_indices() {
|
||||
if c == '\u{0C}' {
|
||||
after = i.saturating_add(c.len_utf8());
|
||||
} else if c != wordcraft_doc::para::OBJ
|
||||
|| !matches!(p.object_at(i), Some(InlineObject::BookmarkStart { .. } | InlineObject::BookmarkEnd { .. }))
|
||||
{
|
||||
break;
|
||||
}
|
||||
}
|
||||
after
|
||||
}
|
||||
|
||||
/// The hidden `_Ref` bookmark around the target paragraph at `pos` (its label and number only
|
||||
/// when `number_only`), reusing one already there. Returns its name and `at` moved past the
|
||||
/// bookmark marks inserted before it.
|
||||
@@ -159,16 +177,22 @@ fn ref_bookmark(s: &mut Session, pos: &Pos, number_only: bool, mut at: Pos) -> R
|
||||
const MARK: usize = wordcraft_doc::para::OBJ.len_utf8();
|
||||
let para = s.doc.para(pos.story, &pos.path).ok_or_else(|| CmdError::Params("cross-reference target is gone".into()))?;
|
||||
let end = if number_only { para.text.find(':').unwrap_or(para.len()) } else { para.len() };
|
||||
if let Some(InlineObject::BookmarkStart { name }) = para.object_at(0)
|
||||
&& name.starts_with("_Ref")
|
||||
{
|
||||
// Reuse it when it covers the same extent: up to the colon, or the whole paragraph.
|
||||
let same = para.object_offsets().into_iter().any(|o| {
|
||||
matches!(para.object_at(o), Some(InlineObject::BookmarkEnd { name: n }) if n == name)
|
||||
&& para.text.get(o.saturating_add(MARK)..).is_some_and(|rest| if number_only { rest.starts_with(':') } else { rest.is_empty() })
|
||||
});
|
||||
if same {
|
||||
return Ok((name.clone(), at));
|
||||
// The bookmark starts after the leading page breaks, so `PAGEREF` reads the page the text is on.
|
||||
let start = leading_breaks(&s.doc, pos).min(end);
|
||||
// Reuse one that starts there or at the paragraph's start (before the breaks): the field's
|
||||
// result still reads the page the text is on.
|
||||
for from in [start, 0] {
|
||||
if let Some(InlineObject::BookmarkStart { name }) = para.object_at(from)
|
||||
&& name.starts_with("_Ref")
|
||||
{
|
||||
// Reuse it when it covers the same extent: up to the colon, or the whole paragraph.
|
||||
let same = para.object_offsets().into_iter().any(|o| {
|
||||
matches!(para.object_at(o), Some(InlineObject::BookmarkEnd { name: n }) if n == name)
|
||||
&& para.text.get(o.saturating_add(MARK)..).is_some_and(|rest| if number_only { rest.starts_with(':') } else { rest.is_empty() })
|
||||
});
|
||||
if same {
|
||||
return Ok((name.clone(), at));
|
||||
}
|
||||
}
|
||||
}
|
||||
let next =
|
||||
@@ -176,11 +200,11 @@ fn ref_bookmark(s: &mut Session, pos: &Pos, number_only: bool, mut at: Pos) -> R
|
||||
let name = format!("_Ref{next:09}");
|
||||
let props = CharProps::default();
|
||||
s.doc.insert_object(&Pos { off: end, ..pos.clone() }, InlineObject::BookmarkEnd { name: name.clone() }, &props)?;
|
||||
s.doc.insert_object(&Pos { off: 0, ..pos.clone() }, InlineObject::BookmarkStart { name: name.clone() }, &props)?;
|
||||
s.doc.insert_object(&Pos { off: start, ..pos.clone() }, InlineObject::BookmarkStart { name: name.clone() }, &props)?;
|
||||
if at.story == pos.story && at.path == pos.path {
|
||||
if at.off >= end {
|
||||
at.off = at.off.saturating_add(2 * MARK);
|
||||
} else if at.off > 0 {
|
||||
} else if at.off > start {
|
||||
at.off = at.off.saturating_add(MARK);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -6,7 +6,9 @@ use super::{
|
||||
Block, CharProps, CmdError, CmdResult, Document, FieldCode, InlineObject, Paragraph, Path, Pos, Session, SortKey, StoryRef, TabAlign, TabLeader,
|
||||
TabStop, Value, delete_selection, heading_letter, p, sel_result, sort_key,
|
||||
};
|
||||
use crate::cmd::references::{page_at, page_formats, page_text};
|
||||
use std::sync::Arc;
|
||||
use wordcraft_doc::section::NumFormat;
|
||||
|
||||
/// The TOC field for `references.tableOfFigures` (ECMA-376 §17.16.5.68): `\c "<label>"` lists the
|
||||
/// captions that label's SEQ field numbers, `\a "<label>"` lists them without their label and
|
||||
@@ -331,9 +333,11 @@ fn add_entry_style(s: &mut Session) {
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn page_of(s: &mut Session, pos: &Pos) -> u32 {
|
||||
/// The page holding `pos`: its index in the layout (to order and deduplicate by) and its number
|
||||
/// in its section's format (`ii`), as the list writes it. Page "1" (index 0) when no page holds it.
|
||||
fn page_of(s: &mut Session, formats: &[NumFormat], pos: &Pos) -> (usize, String) {
|
||||
let l = s.layout();
|
||||
l.caret(pos).and_then(|c| l.pages.get(c.page)).map(|p| p.number).unwrap_or(1)
|
||||
page_at(&l, formats, pos).map_or_else(|| (0, "1".into()), |(i, n, fmt)| (i, page_text(n, fmt)))
|
||||
}
|
||||
|
||||
/// Entry lines (text, hanging indent) for a generated list.
|
||||
@@ -370,7 +374,7 @@ fn entries_for(s: &mut Session, kind: &str) -> Vec<(String, bool)> {
|
||||
}
|
||||
}
|
||||
}
|
||||
let mut with_pages: Vec<(String, u32)> = marks.into_iter().map(|(e, _)| (e, 0)).collect();
|
||||
let mut with_pages: Vec<(String, (usize, String))> = marks.into_iter().map(|(e, _)| (e, (0, String::new()))).collect();
|
||||
// Pages (layout once).
|
||||
let positions: Vec<Pos> = {
|
||||
let mut v = Vec::new();
|
||||
@@ -393,8 +397,9 @@ fn entries_for(s: &mut Session, kind: &str) -> Vec<(String, bool)> {
|
||||
}
|
||||
v
|
||||
};
|
||||
let formats = page_formats(s);
|
||||
for (i, pos) in positions.iter().enumerate() {
|
||||
let pg = page_of(s, pos);
|
||||
let pg = page_of(s, &formats, pos);
|
||||
if let Some(x) = with_pages.get_mut(i) {
|
||||
x.1 = pg;
|
||||
}
|
||||
@@ -403,14 +408,15 @@ fn entries_for(s: &mut Session, kind: &str) -> Vec<(String, bool)> {
|
||||
// `\n` without page numbers; `\p` the separator before them (a tab by default).
|
||||
let f = FieldCode::parse(kind);
|
||||
let sep = f.arg('p').unwrap_or("\t");
|
||||
return with_pages.into_iter().map(|(t, p)| (if f.has('n') { t } else { format!("{t}{sep}{p}") }, false)).collect();
|
||||
return with_pages.into_iter().map(|(t, p)| (if f.has('n') { t } else { format!("{t}{sep}{}", p.1) }, false)).collect();
|
||||
}
|
||||
// Index / TOA: group by entry, sort, list pages.
|
||||
let lang = crate::cmd::default_lang(s);
|
||||
let mut grouped: std::collections::BTreeMap<(SortKey, String), Vec<u32>> = Default::default();
|
||||
// Each page once, in page order (by its place in the layout, not its label: `ii` before `1`).
|
||||
let mut grouped: std::collections::BTreeMap<(SortKey, String), Vec<(usize, String)>> = Default::default();
|
||||
for (e, p) in with_pages {
|
||||
let pages = grouped.entry((sort_key(&e, lang.as_deref()), e)).or_default();
|
||||
if !pages.contains(&p) {
|
||||
if !pages.iter().any(|(i, _)| *i == p.0) {
|
||||
pages.push(p);
|
||||
}
|
||||
}
|
||||
@@ -424,7 +430,7 @@ fn entries_for(s: &mut Session, kind: &str) -> Vec<(String, bool)> {
|
||||
out.push((l, false));
|
||||
}
|
||||
}
|
||||
let list = pages.iter().map(ToString::to_string).collect::<Vec<_>>().join(", ");
|
||||
let list = pages.iter().map(|(_, label)| label.as_str()).collect::<Vec<_>>().join(", ");
|
||||
out.push(if kind.starts_with("INDEX") { (format!("{e}, {list}"), true) } else { (format!("{e}\t{list}"), false) });
|
||||
}
|
||||
out
|
||||
|
||||
@@ -488,6 +488,32 @@ fn table_of_authorities_updates() {
|
||||
assert!(after.matches("Doe v. Roe").count() > t.matches("Doe v. Roe").count(), "{after}");
|
||||
}
|
||||
|
||||
/// #3856: the table of figures and the table of authorities write each page as its footer shows
|
||||
/// it, in the section's number format; the authority cited on pages i and ii lists both.
|
||||
#[test]
|
||||
fn figures_and_authorities_follow_the_page_number_format() {
|
||||
let mut s = Session::new(wordcraft_doc::Document::from_text("Smith v. Jones held it.\nSmith v. Jones again."));
|
||||
s.run("select.text", &json!({"text": "Smith v. Jones again"})).unwrap();
|
||||
s.run("caret.home", &json!({})).unwrap();
|
||||
s.run("layout.break", &json!({"kind": "page"})).unwrap();
|
||||
s.run("references.caption", &json!({"label": "Figure", "text": "The court"})).unwrap();
|
||||
for occurrence in [1, 2] {
|
||||
s.run("select.text", &json!({"text": "Smith v. Jones", "occurrence": occurrence})).unwrap();
|
||||
s.run("references.markCitation", &json!({})).unwrap();
|
||||
}
|
||||
s.run("caret.docStart", &json!({})).unwrap();
|
||||
s.run("layout.pageNumberFormat", &json!({"format": "lowerRoman", "start": 1})).unwrap();
|
||||
s.run("caret.docEnd", &json!({})).unwrap();
|
||||
s.run("text.newParagraph", &json!({})).unwrap();
|
||||
s.run("references.tableOfFigures", &json!({})).unwrap();
|
||||
s.run("caret.docEnd", &json!({})).unwrap();
|
||||
s.run("text.newParagraph", &json!({})).unwrap();
|
||||
s.run("references.tableOfAuthorities", &json!({})).unwrap();
|
||||
let t = s.doc.plain_text(StoryRef::Body);
|
||||
assert!(t.contains("Figure 1: The court\tii"), "{t}");
|
||||
assert!(t.contains("Smith v. Jones\ti, ii"), "{t}");
|
||||
}
|
||||
|
||||
/// Field instructions and results in the body, in order.
|
||||
fn fields(s: &Session) -> Vec<(String, String)> {
|
||||
let mut out = Vec::new();
|
||||
@@ -900,3 +926,42 @@ fn citation_refresh_source_lookup_work_scales_with_document_size() {
|
||||
let p = big.doc.para(StoryRef::Body, &Path::top(0)).unwrap();
|
||||
assert!(p.objects.iter().enumerate().all(|(i, o)| matches!(o, InlineObject::Field { result, .. } if result == &format!("[{}]", i + 1))));
|
||||
}
|
||||
|
||||
/// A heading that starts with a page break and has a `_Ref` bookmark from before the break: the
|
||||
/// page cross-reference reuses it and reads the heading's page, and still does after Update Field.
|
||||
#[test]
|
||||
fn a_ref_bookmark_before_a_page_break_reads_the_heading_page() {
|
||||
let mut s = Session::new(wordcraft_doc::Document::from_text("Front\nPreface"));
|
||||
s.run("select.text", &json!({"text": "Preface"})).unwrap();
|
||||
s.run("styles.apply", &json!({"style": "Heading 1"})).unwrap();
|
||||
s.run("caret.home", &json!({})).unwrap();
|
||||
s.run("layout.break", &json!({"kind": "page"})).unwrap();
|
||||
let path =
|
||||
s.doc.para_paths(StoryRef::Body).into_iter().find(|p| s.doc.para(StoryRef::Body, p).is_some_and(|p| p.text.contains("Preface"))).unwrap();
|
||||
let len = s.doc.para(StoryRef::Body, &path).unwrap().len();
|
||||
let props = CharProps::default();
|
||||
s.doc
|
||||
.insert_object(
|
||||
&Pos { story: StoryRef::Body, path: path.clone(), off: len },
|
||||
InlineObject::BookmarkEnd { name: "_Ref000000003".into() },
|
||||
&props,
|
||||
)
|
||||
.unwrap();
|
||||
s.doc.insert_object(&Pos { story: StoryRef::Body, path, off: 0 }, InlineObject::BookmarkStart { name: "_Ref000000003".into() }, &props).unwrap();
|
||||
s.run("caret.docEnd", &json!({})).unwrap();
|
||||
s.run("insert.crossReference", &json!({"to": "heading", "target": "Preface", "show": "page"})).unwrap();
|
||||
let pageref = |s: &Session| {
|
||||
s.doc
|
||||
.para_paths(StoryRef::Body)
|
||||
.into_iter()
|
||||
.flat_map(|p| s.doc.para(StoryRef::Body, &p).map(|p| p.objects.clone()).unwrap_or_default())
|
||||
.find_map(|o| match o {
|
||||
InlineObject::Field { instr, result, .. } if instr.starts_with("PAGEREF") => Some((instr, result)),
|
||||
_ => None,
|
||||
})
|
||||
.unwrap()
|
||||
};
|
||||
assert_eq!(pageref(&s), ("PAGEREF _Ref000000003 \\h".to_string(), "2".to_string()));
|
||||
crate::cmd::references::update_fields_in(&mut s, true).unwrap();
|
||||
assert_eq!(pageref(&s).1, "2");
|
||||
}
|
||||
@@ -10,7 +10,7 @@ use wordcraft_doc::props::{CharProps, TabAlign, TabLeader, TabStop};
|
||||
use wordcraft_doc::section::SectionStart;
|
||||
use wordcraft_doc::{Block, Paragraph, Path, Pos, StoryRef};
|
||||
|
||||
use super::references::{FieldCode, field_arg, leader};
|
||||
use super::references::{FieldCode, field_arg, leader, page_at, page_formats, page_text};
|
||||
use super::sel_result;
|
||||
use crate::{CmdError, CmdResult, CommandSpec, Session, p};
|
||||
|
||||
@@ -162,6 +162,9 @@ fn insert_index(s: &mut Session, v: &Value) -> CmdResult {
|
||||
/// One page reference of an entry.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
struct PageRef {
|
||||
/// The page's index in the layout (the first page of a range): pages are told apart by it,
|
||||
/// not by their labels, which repeat across sections.
|
||||
at: usize,
|
||||
page: String,
|
||||
bold: bool,
|
||||
italic: bool,
|
||||
@@ -190,8 +193,10 @@ fn collect(s: &mut Session, lang: Option<&str>) -> BTreeMap<Vec<SortKey>, Node>
|
||||
}
|
||||
}
|
||||
}
|
||||
let formats = page_formats(s);
|
||||
let l = s.layout();
|
||||
let page = |pos: &Pos| l.caret(pos).and_then(|c| l.pages.get(c.page)).map(|p| p.number).unwrap_or(1);
|
||||
// A page's index in the layout and its number as its footer shows it (`ii`).
|
||||
let page = |pos: &Pos| page_at(&l, &formats, pos).map_or_else(|| (0, "1".to_string()), |(i, n, fmt)| (i, page_text(n, fmt)));
|
||||
let bookmark_end = |name: &str| {
|
||||
s.doc.para_paths(StoryRef::Body).into_iter().find_map(|path| {
|
||||
let p = s.doc.para(StoryRef::Body, &path)?;
|
||||
@@ -222,11 +227,12 @@ fn collect(s: &mut Session, lang: Option<&str>) -> BTreeMap<Vec<SortKey>, Node>
|
||||
}
|
||||
let range = f.arg('r').and_then(|bm| {
|
||||
let a = starts.iter().find(|(n, _)| n == bm).map(|(_, p)| page(p))?;
|
||||
let b = bookmark_end(bm).map(|p| page(&p)).unwrap_or(a);
|
||||
Some(if b > a { format!("{a}\u{2013}{b}") } else { a.to_string() })
|
||||
let b = bookmark_end(bm).map(|p| page(&p)).unwrap_or_else(|| a.clone());
|
||||
Some(if b.0 > a.0 { (a.0, format!("{}\u{2013}{}", a.1, b.1)) } else { a })
|
||||
});
|
||||
let r = PageRef { page: range.unwrap_or_else(|| page(&pos).to_string()), bold: f.has('b'), italic: f.has('i') };
|
||||
match node.pages.iter_mut().find(|x| x.page == r.page) {
|
||||
let (at, label) = range.unwrap_or_else(|| page(&pos));
|
||||
let r = PageRef { at, page: label, bold: f.has('b'), italic: f.has('i') };
|
||||
match node.pages.iter_mut().find(|x| x.at == r.at && x.page == r.page) {
|
||||
Some(x) => {
|
||||
x.bold |= r.bold;
|
||||
x.italic |= r.italic;
|
||||
|
||||
@@ -20,6 +20,7 @@ use fields::caption;
|
||||
pub use fields::{
|
||||
CHAPTER_SEPARATORS, REFERENCE_NOT_FOUND, output_fields, refresh_date_fields, seq_format, update_fields, update_fields_in, update_seq,
|
||||
};
|
||||
pub(crate) use fields::{page_at, page_formats, page_label, page_text};
|
||||
pub(super) use notes::note_options;
|
||||
use notes::{note, note_refs};
|
||||
pub use properties::{bookmark_text, date_picture};
|
||||
|
||||
@@ -317,6 +317,45 @@ pub fn update_fields(s: &mut Session) -> Result<(), CmdError> {
|
||||
update_fields_in(s, false)
|
||||
}
|
||||
|
||||
/// Each section's page number format (`w:pgNumType w:fmt`), by section index.
|
||||
pub(crate) fn page_formats(s: &Session) -> Vec<NumFormat> {
|
||||
s.doc.sections().into_iter().map(|(_, sec)| sec.page_num_format).collect()
|
||||
}
|
||||
|
||||
/// The page holding `pos` in `l`: its index in the layout, its number, and its section's page
|
||||
/// number format (`formats` from [`page_formats`]). `None` when no page holds it.
|
||||
pub(crate) fn page_at(l: &wordcraft_layout::DocLayout, formats: &[NumFormat], pos: &Pos) -> Option<(usize, u32, NumFormat)> {
|
||||
let c = l.caret(pos)?;
|
||||
let page = l.pages.get(c.page)?;
|
||||
Some((c.page, page.number, formats.get(page.section).copied().unwrap_or_default()))
|
||||
}
|
||||
|
||||
/// A page number as the page's footer shows it (`ii` in a lowerRoman section), as the `PAGE`
|
||||
/// and `PAGEREF` fields write it without a `\*` switch.
|
||||
pub(crate) fn page_text(number: u32, fmt: NumFormat) -> String {
|
||||
wordcraft_layout::fields::field_number("", fmt, number)
|
||||
}
|
||||
|
||||
/// The page number of the page holding `pos`, in its section's number format: what generated
|
||||
/// lists (TOC, index, tables of figures and authorities) and page cross-references write. Page
|
||||
/// "1" when no page holds it.
|
||||
pub(crate) fn page_label(s: &mut Session, pos: &Pos) -> String {
|
||||
let formats = page_formats(s);
|
||||
let l = s.layout();
|
||||
page_at(&l, &formats, pos).map_or_else(|| "1".into(), |(_, n, fmt)| page_text(n, fmt))
|
||||
}
|
||||
|
||||
/// Where `PAGEREF` reads bookmark `name` (starting at `pos`): a hidden `_Ref` bookmark from the
|
||||
/// start of a heading that starts with page breaks reads the page its text is on, as when its
|
||||
/// cross-reference was inserted.
|
||||
fn bookmark_page_pos(doc: &wordcraft_doc::Document, name: &str, pos: Pos) -> Pos {
|
||||
if pos.off == 0 && name.starts_with("_Ref") {
|
||||
let off = crate::cmd::citations::leading_breaks(doc, &pos);
|
||||
return Pos { off, ..pos };
|
||||
}
|
||||
pos
|
||||
}
|
||||
|
||||
/// [`update_fields`], or with `all` the whole document: the body (with SEQ, citations and TOC) and
|
||||
/// every part story, wherever the caret is (what printing needs).
|
||||
pub fn update_fields_in(s: &mut Session, all: bool) -> Result<(), CmdError> {
|
||||
@@ -326,18 +365,12 @@ pub fn update_fields_in(s: &mut Session, all: bool) -> Result<(), CmdError> {
|
||||
update_seq(s)?;
|
||||
}
|
||||
let mut pages: std::collections::HashMap<String, (u32, NumFormat)> = Default::default();
|
||||
let formats: Vec<NumFormat> = s.doc.sections().into_iter().map(|(_, sec)| sec.page_num_format).collect();
|
||||
let formats = page_formats(s);
|
||||
let marks = s.doc.bookmarks();
|
||||
for (name, pos) in marks {
|
||||
let pos = bookmark_page_pos(&s.doc, &name, pos);
|
||||
let l = s.layout();
|
||||
let page_info = l
|
||||
.caret(&pos)
|
||||
.and_then(|c| l.pages.get(c.page))
|
||||
.map(|p| {
|
||||
let format = formats.get(p.section).copied().unwrap_or_default();
|
||||
(p.number, format)
|
||||
})
|
||||
.unwrap_or((1, NumFormat::Decimal));
|
||||
let page_info = page_at(&l, &formats, &pos).map_or((1, NumFormat::Decimal), |(_, n, fmt)| (n, fmt));
|
||||
pages.entry(name).or_insert(page_info);
|
||||
}
|
||||
let stories: Vec<StoryRef> =
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
use super::{
|
||||
Block, CharProps, CmdError, CmdResult, Counters, FieldCode, InlineObject, LevelSuffix, NumFormat, OBJ, Paragraph, Path, Pos, Selection, Session,
|
||||
StoryRef, TabAlign, TabLeader, TabStop, Value, delete_selection, p, sel_result,
|
||||
StoryRef, TabAlign, TabLeader, TabStop, Value, delete_selection, p, page_at, page_formats, page_text, sel_result,
|
||||
};
|
||||
|
||||
/// A table-of-contents title is a heading, not document body: longer titles are rejected
|
||||
@@ -575,6 +575,7 @@ fn regenerate_toc(s: &mut Session, leader: Option<TabLeader>, tabs: &[(String, V
|
||||
};
|
||||
let no_pages = f.has('n').then(|| f.arg('n').and_then(level_range).unwrap_or((1, 9)));
|
||||
let sep = f.arg('p').map(str::to_string).unwrap_or_else(|| "\t".into());
|
||||
let formats = page_formats(s);
|
||||
for pass in 0..2 {
|
||||
// Pass 1 lays out with the entries in place, so headings below the TOC sit `entries.len()`
|
||||
// blocks further down and their pages account for the TOC's own length.
|
||||
@@ -594,8 +595,8 @@ fn regenerate_toc(s: &mut Session, leader: Option<TabLeader>, tabs: &[(String, V
|
||||
{
|
||||
*top = top.saturating_add(u32::try_from(shift).unwrap_or(u32::MAX));
|
||||
}
|
||||
let page =
|
||||
l.caret(&Pos { story: StoryRef::Body, path: target, off: e.lead }).and_then(|c| l.pages.get(c.page)).map(|pg| pg.number).unwrap_or(1);
|
||||
let page = page_at(&l, &formats, &Pos { story: StoryRef::Body, path: target, off: e.lead })
|
||||
.map_or_else(|| "1".into(), |(_, n, fmt)| page_text(n, fmt));
|
||||
let show_page = no_pages.is_none_or(|(a, b)| !(a..=b).contains(&(e.level + 1)));
|
||||
let link = links.get(k).cloned().flatten();
|
||||
// With a bookmark to point at, the page number is a `PAGEREF` field, as Word writes
|
||||
@@ -609,7 +610,7 @@ fn regenerate_toc(s: &mut Session, leader: Option<TabLeader>, tabs: &[(String, V
|
||||
let props = CharProps { link, ..Default::default() };
|
||||
let mut para = Paragraph::with_text(&text, props.clone()).styled(&format!("TOC{}", e.level + 1));
|
||||
if let Some(instr) = pageref {
|
||||
let field = InlineObject::Field { instr, result: page.to_string(), locked: false, dirty: false, code: false, form: String::new() };
|
||||
let field = InlineObject::Field { instr, result: page.clone(), locked: false, dirty: false, code: false, form: String::new() };
|
||||
para.insert_object(para.len(), field, &props)?;
|
||||
}
|
||||
para.mark = CharProps::default();
|
||||
|
||||
@@ -18,6 +18,7 @@ mod fit_one_page;
|
||||
mod font_sizes;
|
||||
mod fonts;
|
||||
mod ime_noop;
|
||||
mod page_number_formats_in_lists;
|
||||
mod para_tools;
|
||||
mod revision_checks;
|
||||
mod typing;
|
||||
|
||||
@@ -0,0 +1,260 @@
|
||||
//! Generated lists and page cross-references write a page as its footer shows it: in the number
|
||||
//! format of the page's section (`w:pgNumType w:fmt`), as Word does (#3856). The front matter is
|
||||
//! numbered i, ii; the body restarts at 1.
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use wordcraft_doc::StoryRef;
|
||||
use wordcraft_doc::para::InlineObject;
|
||||
|
||||
use crate::Session;
|
||||
|
||||
fn run(s: &mut Session, id: &str, v: Value) {
|
||||
s.run(id, &v).unwrap_or_else(|e| panic!("{id}: {e}"));
|
||||
}
|
||||
|
||||
/// Page i: "Front"; page ii: "Preface" (Heading 1); next-page section break; page 1: "Chapter one"
|
||||
/// (Heading 1). Section 1 lowerRoman from 1, section 2 decimal from 1.
|
||||
fn two_sections() -> Session {
|
||||
let mut s = Session::new(wordcraft_doc::Document::from_text("Front\nPreface\nChapter one"));
|
||||
for h in ["Preface", "Chapter one"] {
|
||||
run(&mut s, "select.text", json!({"text": h}));
|
||||
run(&mut s, "styles.apply", json!({"style": "Heading 1"}));
|
||||
}
|
||||
run(&mut s, "select.text", json!({"text": "Preface"}));
|
||||
run(&mut s, "caret.home", json!({}));
|
||||
run(&mut s, "layout.break", json!({"kind": "page"}));
|
||||
run(&mut s, "select.text", json!({"text": "Chapter one"}));
|
||||
run(&mut s, "caret.home", json!({}));
|
||||
run(&mut s, "layout.break", json!({"kind": "nextPage"}));
|
||||
run(&mut s, "select.text", json!({"text": "Chapter one"}));
|
||||
run(&mut s, "layout.pageNumberFormat", json!({"format": "decimal", "start": 1}));
|
||||
run(&mut s, "caret.docStart", json!({}));
|
||||
run(&mut s, "layout.pageNumberFormat", json!({"format": "lowerRoman", "start": 1}));
|
||||
s
|
||||
}
|
||||
|
||||
fn styled(s: &Session, prefix: &str) -> Vec<String> {
|
||||
s.doc
|
||||
.body
|
||||
.iter()
|
||||
.filter_map(|b| b.as_para())
|
||||
.filter(|p| p.props.style.as_deref().is_some_and(|st| st.starts_with(prefix) && st != "TOCHeading"))
|
||||
.map(|p| p.plain_text())
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn field_results(s: &Session, name: &str) -> Vec<String> {
|
||||
let mut out = Vec::new();
|
||||
for path in s.doc.para_paths(StoryRef::Body) {
|
||||
for o in &s.doc.para(StoryRef::Body, &path).unwrap().objects {
|
||||
if let InlineObject::Field { instr, result, .. } = o
|
||||
&& instr.trim_start().starts_with(name)
|
||||
{
|
||||
out.push(result.clone());
|
||||
}
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn toc_page_numbers_follow_the_section_format() {
|
||||
let mut s = two_sections();
|
||||
run(&mut s, "caret.docStart", json!({}));
|
||||
run(&mut s, "references.toc", json!({"levels": 1, "hyperlinks": false, "rightAlign": false}));
|
||||
assert_eq!(styled(&s, "TOC1"), ["Preface ii", "Chapter one 1"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn toc_pageref_results_follow_the_section_format() {
|
||||
let mut s = two_sections();
|
||||
run(&mut s, "caret.docStart", json!({}));
|
||||
run(&mut s, "references.toc", json!({"levels": 1, "hyperlinks": true, "rightAlign": false}));
|
||||
assert_eq!(field_results(&s, "PAGEREF"), ["ii", "1"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn toc_upper_roman_and_letters() {
|
||||
let mut s = two_sections();
|
||||
run(&mut s, "caret.docStart", json!({}));
|
||||
run(&mut s, "layout.pageNumberFormat", json!({"format": "upperRoman", "start": 4}));
|
||||
run(&mut s, "select.text", json!({"text": "Chapter one"}));
|
||||
run(&mut s, "layout.pageNumberFormat", json!({"format": "lowerLetter", "start": 3}));
|
||||
run(&mut s, "caret.docStart", json!({}));
|
||||
run(&mut s, "references.toc", json!({"levels": 1, "hyperlinks": false, "rightAlign": false}));
|
||||
// Preface is the section's 2nd page: 4 + 1 = 5 = V; Chapter one starts at 3 = c.
|
||||
assert_eq!(styled(&s, "TOC1"), ["Preface V", "Chapter one c"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn index_pages_follow_the_section_format() {
|
||||
let mut s = two_sections();
|
||||
run(&mut s, "select.text", json!({"text": "Preface"}));
|
||||
run(&mut s, "references.markEntry", json!({"entry": "Preface"}));
|
||||
run(&mut s, "select.text", json!({"text": "Chapter one"}));
|
||||
run(&mut s, "references.markEntry", json!({"entry": "Chapter"}));
|
||||
run(&mut s, "caret.docEnd", json!({}));
|
||||
run(&mut s, "references.index", json!({"columns": 1, "rightAlign": false}));
|
||||
let text = s.doc.plain_text(StoryRef::Body);
|
||||
// The index is the last thing in the document: its lines start with the entry.
|
||||
let entry = |name: &str| text.lines().rfind(|l| l.starts_with(name)).unwrap_or_default().to_string();
|
||||
let preface = entry("Preface");
|
||||
assert!(preface.ends_with("ii"), "index line {preface:?} in {text:?}");
|
||||
let chapter = entry("Chapter");
|
||||
assert!(chapter.ends_with('1') && chapter != "Chapter one", "index line {chapter:?} in {text:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn page_cross_reference_follows_the_section_format() {
|
||||
let mut s = two_sections();
|
||||
run(&mut s, "caret.docEnd", json!({}));
|
||||
// Before this change the field was inserted with "1", not even the decimal 2: find out which
|
||||
// page it reads, too.
|
||||
run(&mut s, "insert.crossReference", json!({"to": "heading", "target": "Preface", "show": "page"}));
|
||||
assert_eq!(field_results(&s, "PAGEREF"), ["ii"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn update_fields_still_agree() {
|
||||
// F9 already formats PAGEREF by the section; inserting must give the same as updating.
|
||||
let mut s = two_sections();
|
||||
run(&mut s, "caret.docStart", json!({}));
|
||||
run(&mut s, "references.toc", json!({"levels": 1, "hyperlinks": true, "rightAlign": false}));
|
||||
let inserted = field_results(&s, "PAGEREF");
|
||||
crate::cmd::references::update_fields_in(&mut s, true).unwrap();
|
||||
assert_eq!(field_results(&s, "PAGEREF"), inserted);
|
||||
}
|
||||
|
||||
// PR #5971 review: a decimal-only guard, `1, 1` across two sections, index page ranges and
|
||||
// `_Ref` bookmark reuse.
|
||||
|
||||
/// "Front" / page break / "Preface" (Heading 1) / page break / "Chapter one" (Heading 1), one
|
||||
/// decimal section: pages 1, 2, 3.
|
||||
fn decimal_only() -> Session {
|
||||
let mut s = Session::new(wordcraft_doc::Document::from_text("Front\nPreface\nChapter one"));
|
||||
for h in ["Preface", "Chapter one"] {
|
||||
run(&mut s, "select.text", json!({"text": h}));
|
||||
run(&mut s, "styles.apply", json!({"style": "Heading 1"}));
|
||||
run(&mut s, "caret.home", json!({}));
|
||||
run(&mut s, "layout.break", json!({"kind": "page"}));
|
||||
}
|
||||
s
|
||||
}
|
||||
|
||||
/// The last line of the body's text that starts with `name` (the index is at the end).
|
||||
fn index_line(s: &Session, name: &str) -> String {
|
||||
let text = s.doc.plain_text(StoryRef::Body);
|
||||
text.lines().rfind(|l| l.starts_with(name)).unwrap_or_default().to_string()
|
||||
}
|
||||
|
||||
/// The body paragraph whose text contains `text`, and the byte offset where `text` starts in it.
|
||||
fn find(s: &Session, text: &str) -> (wordcraft_doc::Path, usize) {
|
||||
s.doc
|
||||
.para_paths(StoryRef::Body)
|
||||
.into_iter()
|
||||
.find_map(|path| s.doc.para(StoryRef::Body, &path).and_then(|p| p.text.find(text)).map(|o| (path, o)))
|
||||
.unwrap_or_else(|| panic!("no paragraph with {text:?}"))
|
||||
}
|
||||
|
||||
fn add_mark(s: &mut Session, path: &wordcraft_doc::Path, off: usize, obj: InlineObject) {
|
||||
let at = wordcraft_doc::Pos { story: StoryRef::Body, path: path.clone(), off };
|
||||
s.doc.insert_object(&at, obj, &wordcraft_doc::CharProps::default()).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn decimal_only_documents_keep_plain_page_numbers() {
|
||||
let mut s = decimal_only();
|
||||
run(&mut s, "caret.docStart", json!({}));
|
||||
run(&mut s, "references.toc", json!({"levels": 1, "hyperlinks": false, "rightAlign": false}));
|
||||
assert_eq!(styled(&s, "TOC1"), ["Preface 2", "Chapter one 3"]);
|
||||
|
||||
let mut s = decimal_only();
|
||||
run(&mut s, "caret.docStart", json!({}));
|
||||
run(&mut s, "references.toc", json!({"levels": 1, "hyperlinks": true, "rightAlign": false}));
|
||||
assert_eq!(field_results(&s, "PAGEREF"), ["2", "3"]);
|
||||
|
||||
let mut s = decimal_only();
|
||||
run(&mut s, "caret.docEnd", json!({}));
|
||||
run(&mut s, "insert.crossReference", json!({"to": "heading", "target": "Preface", "show": "page"}));
|
||||
assert_eq!(field_results(&s, "PAGEREF"), ["2"]);
|
||||
|
||||
let mut s = decimal_only();
|
||||
run(&mut s, "select.text", json!({"text": "Preface"}));
|
||||
run(&mut s, "references.markEntry", json!({"entry": "Preface"}));
|
||||
run(&mut s, "select.text", json!({"text": "Chapter one"}));
|
||||
run(&mut s, "references.markEntry", json!({"entry": "Chapter"}));
|
||||
run(&mut s, "caret.docEnd", json!({}));
|
||||
run(&mut s, "references.index", json!({"columns": 1, "rightAlign": false}));
|
||||
let (preface, chapter) = (index_line(&s, "Preface"), index_line(&s, "Chapter"));
|
||||
assert!(preface.ends_with('2') && !preface.ends_with("12"), "{preface:?}");
|
||||
assert!(chapter.ends_with('3') && chapter != "Chapter one", "{chapter:?}");
|
||||
}
|
||||
|
||||
/// The same entry on page 1 of two sections lists both pages: the index merges pages by layout
|
||||
/// page, not by the number shown.
|
||||
#[test]
|
||||
fn the_same_label_on_two_pages_is_listed_twice() {
|
||||
let mut s = two_sections();
|
||||
run(&mut s, "caret.docStart", json!({}));
|
||||
run(&mut s, "layout.pageNumberFormat", json!({"format": "decimal", "start": 1}));
|
||||
for t in ["Front", "Chapter one"] {
|
||||
run(&mut s, "select.text", json!({"text": t}));
|
||||
run(&mut s, "references.markEntry", json!({"entry": "Topic"}));
|
||||
}
|
||||
run(&mut s, "caret.docEnd", json!({}));
|
||||
run(&mut s, "references.index", json!({"columns": 1, "rightAlign": false}));
|
||||
let line = index_line(&s, "Topic");
|
||||
assert!(line.ends_with("1, 1"), "{line:?}");
|
||||
}
|
||||
|
||||
/// An index entry for bookmark `Span` (`XE \r`), the bookmark from "Preface" (page ii) to `end`.
|
||||
fn range_entry(end: Option<(&str, bool)>) -> String {
|
||||
let mut s = two_sections();
|
||||
let (path, off) = find(&s, "Preface");
|
||||
// The end first, so the start's offset stays put when both are in one paragraph.
|
||||
if let Some((text, at_end_of_para)) = end {
|
||||
let (epath, eoff) = find(&s, text);
|
||||
let eoff = if at_end_of_para { s.doc.para(StoryRef::Body, &epath).unwrap().len() } else { eoff + text.len() };
|
||||
add_mark(&mut s, &epath, eoff, InlineObject::BookmarkEnd { name: "Span".into() });
|
||||
}
|
||||
add_mark(&mut s, &path, off, InlineObject::BookmarkStart { name: "Span".into() });
|
||||
run(&mut s, "select.text", json!({"text": "Front"}));
|
||||
run(&mut s, "references.markEntry", json!({"entry": "Span", "bookmark": "Span"}));
|
||||
run(&mut s, "caret.docEnd", json!({}));
|
||||
run(&mut s, "references.index", json!({"columns": 1, "rightAlign": false}));
|
||||
index_line(&s, "Span")
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_index_range_across_sections_uses_each_ends_format() {
|
||||
let line = range_entry(Some(("Chapter one", true)));
|
||||
assert!(line.ends_with("ii\u{2013}1"), "{line:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_index_range_on_one_page_is_one_page() {
|
||||
let line = range_entry(Some(("Preface", false)));
|
||||
assert!(line.ends_with("ii") && !line.contains('\u{2013}'), "{line:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_index_range_without_its_end_is_the_start_page() {
|
||||
let line = range_entry(None);
|
||||
assert!(line.ends_with("ii") && !line.contains('\u{2013}'), "{line:?}");
|
||||
}
|
||||
|
||||
/// A heading that starts with a page break and already has a `_Ref` bookmark around it from
|
||||
/// offset 0: a page cross-reference reuses it and reads the heading's page.
|
||||
#[test]
|
||||
fn a_ref_bookmark_before_the_page_break_is_reused() {
|
||||
let mut s = two_sections();
|
||||
let (path, _) = find(&s, "Preface");
|
||||
let len = s.doc.para(StoryRef::Body, &path).unwrap().len();
|
||||
add_mark(&mut s, &path, len, InlineObject::BookmarkEnd { name: "_Ref000000007".into() });
|
||||
add_mark(&mut s, &path, 0, InlineObject::BookmarkStart { name: "_Ref000000007".into() });
|
||||
run(&mut s, "caret.docEnd", json!({}));
|
||||
run(&mut s, "insert.crossReference", json!({"to": "heading", "target": "Preface", "show": "page"}));
|
||||
let refs: Vec<String> = s.doc.bookmarks().into_iter().map(|b| b.0).filter(|n| n.starts_with("_Ref")).collect();
|
||||
assert_eq!(refs, ["_Ref000000007"], "no second _Ref bookmark");
|
||||
assert_eq!(field_results(&s, "PAGEREF"), ["ii"]);
|
||||
}
|
||||
Reference in new issue
Block a user