mirror of
https://github.com/storytold/wordcraft.git
synced 2026-11-20 12:51:16 -06:00
References: a table of contents writes its page numbers as PAGEREF fields, as Word does (#5097)
A hyperlinked TOC wrote each entry's page number as plain text inside the link. Word writes it as a PAGEREF _Toc… \h field, so Update Field in Word moves the number with its heading; with plain text the numbers stay what they were when the file was saved. Entries that link to a bookmark now end with that field (result: the page number). Entries without a link and \n levels are unchanged. The DOCX span test looks for the TOC's own end, the last one, since PAGEREF fields now end inside it. Co-authored-by: dfgodvan <180286157+dfgodvan@users.noreply.github.com> Co-authored-by: Brandon Thomas <echelon@gmail.com>
This commit is contained in:
co-authored by
dfgodvan
Brandon Thomas
parent
8afe6bef6d
commit
401c6c0dc2
+3
-1
File diff suppressed because one or more lines are too long
@@ -508,9 +508,21 @@ fn regenerate_toc(s: &mut Session, leader: Option<TabLeader>, tabs: &[(String, V
|
||||
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 show_page = no_pages.is_none_or(|(a, b)| !(a..=b).contains(&(e.level + 1)));
|
||||
let text = if show_page { format!("{}{sep}{page}", e.text) } else { e.text.clone() };
|
||||
let props = CharProps { link: links.get(k).cloned().flatten(), ..Default::default() };
|
||||
let mut para = Paragraph::with_text(&text, props).styled(&format!("TOC{}", 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
|
||||
// it, so updating it in Word follows the heading to its new page.
|
||||
let pageref = link.as_deref().and_then(|l| l.strip_prefix('#')).filter(|_| show_page).map(|b| format!("PAGEREF {b} \\h"));
|
||||
let text = match (show_page, &pageref) {
|
||||
(true, None) => format!("{}{sep}{page}", e.text),
|
||||
(true, Some(_)) => format!("{}{sep}", e.text),
|
||||
(false, _) => e.text.clone(),
|
||||
};
|
||||
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() };
|
||||
para.insert_object(para.len(), field, &props)?;
|
||||
}
|
||||
para.mark = CharProps::default();
|
||||
if e.text.contains('\t') {
|
||||
para.props.tabs = tabs.iter().find(|(style, _)| Some(style) == para.props.style.as_ref()).map(|(_, tabs)| tabs.clone());
|
||||
|
||||
@@ -4113,7 +4113,8 @@ fn update_toc_clears_stale_field_result_for_docx_span() {
|
||||
s
|
||||
};
|
||||
let b = xml.find(r#"w:fldCharType="begin""#).expect("TOC begin marker present");
|
||||
let e = xml.find(r#"w:fldCharType="end""#).expect("TOC end marker present");
|
||||
// The TOC's end is the last one: the entries' page numbers are `PAGEREF` fields inside it.
|
||||
let e = xml.rfind(r#"w:fldCharType="end""#).expect("TOC end marker present");
|
||||
assert!(b < e, "begin marker precedes end marker");
|
||||
let inside_field = &xml[b..e];
|
||||
let after_field = &xml[e..];
|
||||
@@ -4298,6 +4299,50 @@ fn toc_page_numbers_follow_headings() {
|
||||
}
|
||||
}
|
||||
|
||||
/// A hyperlinked TOC's page numbers are `PAGEREF` fields to the headings' bookmarks, as Word
|
||||
/// writes them, so updating them in Word follows the headings; they survive a save and reopen.
|
||||
#[test]
|
||||
fn toc_page_numbers_are_pageref_fields() {
|
||||
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!({}));
|
||||
let fields: Vec<(String, String)> = s
|
||||
.doc
|
||||
.body
|
||||
.iter()
|
||||
.filter_map(|b| b.as_para())
|
||||
.filter(|p| p.props.style.as_deref() == Some("TOC1"))
|
||||
.flat_map(|p| p.objects.iter())
|
||||
.filter_map(|o| match o {
|
||||
wordcraft_doc::para::InlineObject::Field { instr, result, .. } => Some((instr.clone(), result.clone())),
|
||||
_ => None,
|
||||
})
|
||||
.collect();
|
||||
assert_eq!(fields.len(), 2, "{fields:?}");
|
||||
for ((instr, result), page) in fields.iter().zip(["2", "3"]) {
|
||||
let mark = instr.strip_prefix("PAGEREF ").and_then(|r| r.strip_suffix(" \\h")).unwrap_or_else(|| panic!("{instr}"));
|
||||
assert!(mark.starts_with("_Toc") && s.doc.bookmarks().iter().any(|(n, _)| n == mark), "{instr}");
|
||||
assert_eq!(result, page);
|
||||
}
|
||||
let expected = text(&s);
|
||||
assert!(expected.contains("Alpha\t2") && expected.contains("Bravo\t3"), "{expected}");
|
||||
let bytes = crate::io::save_bytes("toc.docx", &s.doc).unwrap();
|
||||
let mut z = zip::ZipArchive::new(std::io::Cursor::new(&bytes)).unwrap();
|
||||
let mut xml = String::new();
|
||||
std::io::Read::read_to_string(&mut z.by_name("word/document.xml").unwrap(), &mut xml).unwrap();
|
||||
assert_eq!(xml.matches("PAGEREF _Toc").count(), 2, "{xml}");
|
||||
let mut s = Session::new(crate::io::open_bytes("toc.docx", &bytes).unwrap());
|
||||
run(&mut s, "references.updateFields", json!({}));
|
||||
assert_eq!(text(&s), expected);
|
||||
}
|
||||
|
||||
/// Headings numbered through a list carry their numbers, and the level's separator, into the
|
||||
/// TOC entries.
|
||||
#[test]
|
||||
|
||||
File diff suppressed because one or more lines are too long
Reference in New Issue
Block a user