diff --git a/crates/engine/src/cmd/citations.rs b/crates/engine/src/cmd/citations.rs index ccdc826e3d..f8496128a1 100644 --- a/crates/engine/src/cmd/citations.rs +++ b/crates/engine/src/cmd/citations.rs @@ -25,6 +25,7 @@ pub use cross_refs::{caption_labels, ref_targets}; use generated::ENTRY_STYLE; pub(crate) use generated::generated_list; use generated::table_of_figures; +pub(super) use generated::wrapped_list; pub use generated::{figures_instr, update_generated}; pub use render::{cite, entry}; pub use sources::update_citations; diff --git a/crates/engine/src/cmd/citations/generated.rs b/crates/engine/src/cmd/citations/generated.rs index b234948c68..ef8ad6e4b8 100644 --- a/crates/engine/src/cmd/citations/generated.rs +++ b/crates/engine/src/cmd/citations/generated.rs @@ -74,7 +74,7 @@ const MAX_WRAPPED: usize = 10_000; /// A generated list (index, bibliography, table of figures or authorities) held as a complex /// field that starts at body block `i` and runs over its entries: its field code and the block /// it ends in. `None` for anything else (a TOC has its own update). -fn wrapped_list(s: &Session, i: usize) -> Option<(String, usize, usize, usize)> { +pub(in crate::cmd) fn wrapped_list(s: &Session, i: usize) -> Option<(String, usize, usize, usize)> { let p = s.doc.body.get(i)?.as_para()?; let (k, off, instr) = p.objects_with_offsets().enumerate().find_map(|(k, (off, o))| match o { InlineObject::FieldStart { instr, .. } => { diff --git a/crates/engine/src/cmd/index.rs b/crates/engine/src/cmd/index.rs index 9864fab8ba..41c1bcf653 100644 --- a/crates/engine/src/cmd/index.rs +++ b/crates/engine/src/cmd/index.rs @@ -136,6 +136,44 @@ fn index_field(s: &Session) -> Option<(usize, String)> { }) } +fn entry_leader(p: &Paragraph) -> Option { + p.props.tabs.as_ref()?.last().map(|tab| tab.leader) +} + +/// The index Insert Index will update and the leader its current result shows. +pub fn index_settings(s: &Session) -> Option<(FieldCode, Option)> { + if let Some((i, instr)) = index_field(s) { + let leader = s + .doc + .body + .iter() + .skip(i + 1) + .map_while(|b| b.as_para().filter(|p| p.props.style.as_deref() == Some(ENTRY_STYLE))) + .find_map(entry_leader); + return Some((FieldCode::parse(&instr), leader)); + } + + (0..s.doc.body.len()).find_map(|i| { + let (instr, start, last, end) = super::citations::wrapped_list(s, i)?; + let field = FieldCode::parse(&instr); + if field.name != "INDEX" { + return None; + } + // Conversion removes the wrapped entries. Read their page-number stop before they go, + // including a style's stop, without taking tabs outside the field result. + let leader = (i..=last).find_map(|j| { + let p = s.doc.body.get(j)?.as_para()?; + let from = if j == i { start } else { 0 }; + let to = if j == last { end } else { p.len() }; + if !p.text.get(from..to)?.contains('\t') { + return None; + } + s.doc.styles.resolve_para(&p.props).tabs.iter().rfind(|tab| tab.align == TabAlign::Right).map(|tab| tab.leader) + }); + Some((field, leader)) + }) +} + /// Whether an INDEX field (a plain one or a range field, as Word files hold it) sits in the main /// text's own paragraphs (`main`), or anywhere else a reader sees: a table cell, a text box, a /// header or a footer in use. Stored headers and footers no page shows (a first-page header @@ -342,7 +380,7 @@ pub fn rebuild_from(s: &mut Session, i: usize, leader: Option, instr: let mut old_leader = None; let mut old_sect = None; while let Some(p) = s.doc.body.get(i + 1).and_then(|b| b.as_para()).filter(|p| p.props.style.as_deref() == Some(ENTRY_STYLE)) { - old_leader = old_leader.or_else(|| p.props.tabs.as_ref().and_then(|t| t.last()).map(|t| t.leader)); + old_leader = old_leader.or_else(|| entry_leader(p)); if p.section.is_some() { old_sect = p.section.clone(); } diff --git a/crates/ui-egui/src/dialogs/dialogs_refs/index.rs b/crates/ui-egui/src/dialogs/dialogs_refs/index.rs index 27c4462ef1..26dfc02733 100644 --- a/crates/ui-egui/src/dialogs/dialogs_refs/index.rs +++ b/crates/ui-egui/src/dialogs/dialogs_refs/index.rs @@ -16,9 +16,10 @@ use craft::ui::text::{NumberField, TextField}; use egui::Ui; use serde::{Deserialize, Serialize}; use serde_json::{Value, json}; +use wordcraft_doc::props::TabLeader; use wordcraft_engine::cmd::references::FieldCode; -use super::sample::{LEADERS, leader_char, sample_card}; +use super::sample::{LEADERS, sample_card}; use crate::WordApp; use crate::dialogs::host::{Asks, Filed, WordForm, captioned, labelled, open_form}; @@ -55,21 +56,19 @@ pub(super) fn body_field(app: &WordApp, name: &str) -> Option { impl IndexForm { /// The index in the document, or Word's defaults for a new one (two columns). pub fn read(app: &WordApp) -> IndexForm { - // Insert Index updates an inline index first. Otherwise it rebuilds the range field - // before writing the settings, so the dialog needs to read those switches too. - let index = body_field(app, "INDEX").or_else(|| { - app.session.doc.body.iter().filter_map(|b| b.as_para()).flat_map(|p| p.objects.iter()).find_map(|o| { - let wordcraft_doc::InlineObject::FieldStart { instr, .. } = o else { return None }; - let field = FieldCode::parse(instr); - (field.name == "INDEX").then_some(field) - }) - }); - match index { - Some(f) => IndexForm { + match wordcraft_engine::cmd::index::index_settings(&app.session) { + Some((f, leader)) => IndexForm { kind: if f.has('r') { "runIn" } else { "indented" }.into(), columns: f.arg('c').and_then(|c| c.trim().parse().ok()).unwrap_or(1).clamp(1, 4), right_align: f.arg('e').is_some_and(|e| e.contains('\t')), - leader: "dot".into(), + leader: match leader.unwrap_or(TabLeader::Dot) { + TabLeader::None => "none", + TabLeader::Dot => "dot", + TabLeader::Hyphen => "hyphen", + TabLeader::Underscore => "underscore", + TabLeader::MiddleDot => "middleDot", + } + .into(), headings: f.has('h'), }, None => IndexForm { kind: "indented".into(), columns: 2, right_align: false, leader: "dot".into(), headings: true }, @@ -112,7 +111,8 @@ impl WordForm for IndexForm { } fn body(&mut self, ui: &mut Ui, _cx: &mut FormCx<'_, '_>, asks: &mut Vec) -> bool { - sample_card(tl!("Preview"), self.sample_lines(), self.right_align, leader_char(&self.leader)).show(ui); + let leader = wordcraft_engine::cmd::references::leader(&self.leader).char(); + sample_card(tl!("Preview"), self.sample_lines(), self.right_align, leader).show(ui); let kind = captioned(ui, Label::from(tl!("Type:").to_string()), |name, ui| { RadioGroup::new(name, Bind::given(self.kind.clone())).show(ui, |ui, _| { Row::new().show(ui, |ui, _| { @@ -132,7 +132,10 @@ impl WordForm for IndexForm { } Checkbox::new(Bind::bound(&mut self.right_align)).label(Label::from(tl!("Page numbers at the right margin").to_string())).show(ui); let title = Label::from(tl!("Tab leader:").to_string()); - let entries = leaders(); + let mut entries = leaders(); + if self.leader == "middleDot" { + entries.push(Entry::new("middleDot".to_string(), Label::from("········"))); + } let leader = Field::new(title.clone()) .show(ui, |ui, _| { Select::new(title.clone(), Bind::given(Mixed::Same(self.leader.clone())), &entries) diff --git a/crates/ui-egui/src/dialogs/dialogs_refs/tests.rs b/crates/ui-egui/src/dialogs/dialogs_refs/tests.rs index 202900da06..10e8c0b14e 100644 --- a/crates/ui-egui/src/dialogs/dialogs_refs/tests.rs +++ b/crates/ui-egui/src/dialogs/dialogs_refs/tests.rs @@ -242,21 +242,36 @@ fn index_and_mark_entry_dialogs_write_switches() { fn index_dialog_keeps_range_field_settings_when_confirmed_without_edits() { use egui::accesskit::{Role, Toggled}; use egui_kittest::kittest::{NodeT, Queryable}; - use wordcraft_doc::{Block, Paragraph, Path}; + use wordcraft_doc::Path; + use wordcraft_doc::props::{TabAlign, TabLeader}; let mut a = app("Kilns are hot."); a.run("select.text", json!({"text": "Kilns"})).unwrap(); a.session.run("references.markEntry", &json!({})).unwrap(); - // Original synthetic range field with non-default type, columns, alignment and headings. + // Wrap a generated entry so the imported field has a real result with a non-dot leader. + a.session.run("caret.docEnd", &json!({})).unwrap(); + a.session + .run("references.index", &json!({"type": "runIn", "columns": 3, "rightAlign": true, "headings": false, "tabLeader": "hyphen"})) + .unwrap(); let instr = "INDEX \\c \"3\" \\e \"\t\" \\r"; - let mut para = Paragraph::new(); - para.insert_object(0, InlineObject::FieldEnd, &Default::default()).unwrap(); - para.insert_object(0, InlineObject::FieldStart { instr: instr.into(), locked: false, dirty: false }, &Default::default()).unwrap(); - let last = a.session.doc.body.len(); - a.session.doc.insert_block(StoryRef::Body, &Path::top(last), Block::Para(para)).unwrap(); + let is_index = |o: &InlineObject| matches!(o, InlineObject::Field { instr: code, .. } if code == instr); + let header = a.session.doc.body.iter().position(|b| b.as_para().is_some_and(|p| p.objects.iter().any(is_index))).unwrap(); + let p = a.session.doc.para_mut(StoryRef::Body, &Path::top(header)).unwrap(); + let field_offset = p.objects_with_offsets().find(|(_, o)| is_index(o)).unwrap().0; + p.delete(0, field_offset).unwrap(); + *p.objects.iter_mut().find(|o| is_index(o)).unwrap() = InlineObject::FieldStart { instr: instr.into(), locked: false, dirty: false }; + let entry = a.session.doc.para_mut(StoryRef::Body, &Path::top(header + 1)).unwrap(); + entry.insert_object(entry.len(), InlineObject::FieldEnd, &Default::default()).unwrap(); a.session.touch(); + let entry_tab = |a: &WordApp| { + let p = a.session.doc.body.get(header + 1).and_then(|b| b.as_para()).expect("the generated entry"); + assert!(p.plain_text().contains("Kilns\t")); + *p.props.tabs.as_ref().unwrap().last().unwrap() + }; + let expected_tab = entry_tab(&a); + assert_eq!((expected_tab.align, expected_tab.leader), (TabAlign::Right, TabLeader::Hyphen)); assert_eq!(a.run("references.index", json!({})).unwrap(), json!({"pending": "index"})); let mut h = crate::test_harness::builder().with_size(vec2(1440.0, 900.0)).build_ui_state( |ui, app: &mut WordApp| { @@ -270,6 +285,7 @@ fn index_dialog_keeps_range_field_settings_when_confirmed_without_edits() { h.get_by_role_and_label(Role::Dialog, "Index"); let opened = form::(h.state()); assert_eq!((opened.kind.as_str(), opened.columns, opened.right_align, opened.headings), ("runIn", 3, true, false)); + assert_eq!(opened.leader, "hyphen"); assert_eq!(h.state().session.doc.field_ranges(StoryRef::Body)[0].instr, instr, "opening leaves the range field intact"); let right_aligned = h.get_by_role_and_label(Role::CheckBox, "Page numbers at the right margin").accesskit_node().toggled(); assert_eq!(right_aligned, Some(Toggled::True)); @@ -280,6 +296,27 @@ fn index_dialog_keeps_range_field_settings_when_confirmed_without_edits() { let indexes: Vec<_> = instrs(h.state()).into_iter().filter(|i| i.starts_with("INDEX")).collect(); assert_eq!(indexes, [instr.to_string()], "the rebuilt index keeps the same switches"); assert!(h.state().session.doc.field_ranges(StoryRef::Body).is_empty(), "the range was replaced in place"); + assert_eq!(entry_tab(h.state()), expected_tab, "OK preserves the leader, alignment and stop"); + + // The converted inline index keeps the leader on a second unedited confirmation. + h.state_mut().run("references.index", json!({})).unwrap(); + h.run_steps(3); + assert_eq!(form::(h.state()).leader, "hyphen"); + h.get_by_role_and_label(Role::Button, "OK").click(); + h.run_steps(3); + assert_eq!(entry_tab(h.state()), expected_tab); + + h.state_mut().run("references.index", json!({})).unwrap(); + h.run_steps(3); + let ctx = h.ctx.clone(); + let id = craft::ui::dialog::dialog_id("index"); + h.state_mut().dialog_host.set_json_field(&ctx, id, "leader", json!("underscore")).unwrap(); + h.get_by_role_and_label(Role::Button, "OK").click(); + h.run_steps(3); + let changed_tab = entry_tab(h.state()); + assert_eq!(changed_tab.leader, TabLeader::Underscore); + assert_eq!((changed_tab.align, changed_tab.pos), (expected_tab.align, expected_tab.pos)); + assert_eq!(instrs(h.state()).into_iter().filter(|i| i.starts_with("INDEX")).collect::>(), [instr.to_string()]); } /// #402: Custom Table of Contents and its Options make the TOC switches, and the dialog