Skip to content

DesignCraft: An open-source page and layout design editor written by scratch in pure Rust

M7: index — page references, Generate/Update Index, IDML topics

Brandon Thomasc2222959debf
diff --git a/ROADMAP.md b/ROADMAP.md
index 6938cb3f8..69d23684f 100644
--- a/ROADMAP.md
+++ b/ROADMAP.md
@@ -19,6 +19,7 @@ DesignCraft aims at full Adobe InDesign parity — and to be better: faster, ope
- Data Merge (CSV or JSON rows, `<<Field>>` placeholders), spell checking (public-domain Moby list + document dictionary, suggestions), Step and Repeat (count or grid), snippets, object styles, Numbering & Section Options.
- Footnotes: Type › Insert Footnote (caret moves into the note), Document Footnote Options (numbering style incl. symbols, start/restart per page/spread/section, prefix/suffix, reference position/character style, paragraph style, separator, spacing, first baseline, rule above); notes composed at the bottom of the referencing column with the body text making room; edited in place on the canvas; rendered, exported to PDF (real text) and IDML (InDesign's structure, verified opening in InDesign 2026) and imported from IDML; `footnote.*` commands.
- Cross-references and text anchors: Insert Cross-Reference (paragraph by style, or text anchor), 11 formats with InDesign's building blocks (full/partial paragraph, paragraph text/number, page number, anchor name, chapter, file name) plus user formats; resolved live at composition — never out of date, no Update step; unresolved destinations show `??`; PDF link annotations to the destination page; IDML export/import as InDesign cross-reference sources, hyperlinks, text destinations and formats (verified in InDesign 2026); `xref.*` / `anchor.*` commands.
+- Index: page references (topic from the selection or up to 4 levels, sort keys; current page, to end of story, next n paragraphs, suppressed, See / See also), Generate / Update Index (section headings, nested or run-in, page ranges merged, Index Title / Section Head / Level 1–4 styles); IDML export/import as InDesign topics, page references and topic cross-references (verified in InDesign 2026); `index.*` commands.
- Menus expose the engine's features (TOC, numbering & sections, text variables, hyperlinks, cross-references, footnotes, step and repeat, spelling, fitting/content, effects, Data Merge, Preflight, EPUB); any menu command with parameters gets a dialog generated from its parameter documentation.
- Table of contents (generate/update, dot leaders) and text variables (running headers, last page number, chapter number, file name, dates, custom) resolved per page.
- Soft effects: blurred drop shadow, inner shadow, outer glow, basic feather.
@@ -26,7 +27,7 @@ DesignCraft aims at full Adobe InDesign parity — and to be better: faster, ope
- MCP server (`designcraft-cli mcp [--connect PORT]`, docs/mcp.md): headless engine or the running app; commands, batch, document/story inspection, page renders as images, window screenshots, pointer/keyboard/dialog input.
- Web build (`apps/designcraft-web`, trunk): the same UI on WebGPU with a WebGL2 fallback; open/place via the browser file picker or drag-and-drop, save/export as downloads.
-**Next (in order):** index, footnotes in EPUB / span columns / split footnotes · table/cell styles, text rotation in cells · PDF/X-4 output intent, tagged PDF · Links panel + relink · UI for Data Merge/spelling/hyperlinks.
+**Next (in order):** books, footnotes in EPUB / span columns / split footnotes · table/cell styles, text rotation in cells · PDF/X-4 output intent, tagged PDF · Links panel + relink · UI for Data Merge/spelling/hyperlinks.
## Milestones
@@ -39,7 +40,7 @@ DesignCraft aims at full Adobe InDesign parity — and to be better: faster, ope
| M4 | Color & effects | started |
| M5 | Graphics & links | started |
| M6 | Files & export (native, IDML, PDF, PNG/JPEG) | in progress (IDML ✅, PDF export) |
-| M7 | Long documents (sections, TOC, index, footnotes, books) | in progress (sections, TOC, text variables/running heads, hyperlinks, bookmarks, footnotes, cross-references) |
+| M7 | Long documents (sections, TOC, index, footnotes, books) | in progress (sections, TOC, text variables/running heads, hyperlinks, bookmarks, footnotes, cross-references, index) |
| M8 | Tables | ✅ core (table/cell styles, rotation, diagonal lines pending) |
| M9 | Performance (MT composition, tiles) | in progress (glyph path cache, culling, parallel compose 6.7× faster, perf harness) |
| M10 | Find/Change, spelling, Preflight | in progress (Find/Change ✅, spelling ✅, Preflight) |
diff --git a/crates/compose/src/shape.rs b/crates/compose/src/shape.rs
index 6785f0fab..c4ad1e38c 100644
--- a/crates/compose/src/shape.rs
+++ b/crates/compose/src/shape.rs
@@ -226,6 +226,7 @@ fn shape_run(
| designcraft_doc::FOOTNOTE_REF
| designcraft_doc::XREF_MARK
| designcraft_doc::ANCHOR_MARK
+ | designcraft_doc::INDEX_MARK
) || designcraft_doc::vars::var_index(c).is_some();
if special {
flush(seg_start, i, &seg_face, out);
@@ -265,7 +266,12 @@ fn shape_run(
_ => {
// Zero-width control glyph carrying metrics (tabs get their width at line layout).
let mut g = control_glyph(&primary, p, auto_leading, style, i, c);
- if c == '\t' || c == story::RIGHT_INDENT_TAB || c == story::TABLE_ANCHOR || c == designcraft_doc::ANCHOR_MARK {
+ if c == '\t'
+ || c == story::RIGHT_INDENT_TAB
+ || c == story::TABLE_ANCHOR
+ || c == designcraft_doc::ANCHOR_MARK
+ || c == designcraft_doc::INDEX_MARK
+ {
g.adv = 0.0;
}
out.push(g);
diff --git a/crates/compose/src/vars.rs b/crates/compose/src/vars.rs
index e19170b17..945d8bd04 100644
--- a/crates/compose/src/vars.rs
+++ b/crates/compose/src/vars.rs
@@ -19,6 +19,17 @@ pub fn has_running(doc: &Document, st: &Story) -> bool {
st.text.chars().filter_map(var_index).any(|i| matches!(doc.text_variables.get(i).map(|v| &v.kind), Some(VarKind::RunningHeader { .. })))
}
+/// Absolute page showing story byte `pos` of a composed story.
+pub fn page_of(doc: &Document, cs: &ComposedStory, pos: usize) -> Option<usize> {
+ let (fi, ..) = crate::caret(cs, pos)?;
+ // Overset text has no page.
+ let ft = cs.frames.get(fi)?;
+ if pos > ft.range.end && cs.overset_at.is_some_and(|o| pos >= o) {
+ return None;
+ }
+ place(doc, cs, pos).map(|p| p.0)
+}
+
/// Per (style, is character style): page → (first text, last text) on that page.
#[derive(Debug, Default)]
pub struct RunningIndex {
diff --git a/crates/doc/src/build.rs b/crates/doc/src/build.rs
index 55097c974..38b53ed65 100644
--- a/crates/doc/src/build.rs
+++ b/crates/doc/src/build.rs
@@ -142,6 +142,7 @@ impl Document {
text_variables: crate::vars::defaults(),
footnote_options: Default::default(),
xref_formats: crate::xref::default_formats(),
+ index: None,
created: crate::vars::now(),
modified: 0,
next_id: 0,
diff --git a/crates/doc/src/edit.rs b/crates/doc/src/edit.rs
index 890fffef1..4b53c78aa 100644
--- a/crates/doc/src/edit.rs
+++ b/crates/doc/src/edit.rs
@@ -233,6 +233,7 @@ impl Document {
}
st.anchors.extend(other.anchors.iter().cloned());
st.xrefs.extend(other.xrefs.iter().cloned());
+ st.index_refs.extend(other.index_refs.iter().cloned());
st.rev += 1;
}
let at = st.frames.iter().position(|f| *f == from).map_or(st.frames.len(), |p| p + 1);
@@ -362,6 +363,7 @@ impl Document {
st.fix_notes();
st.anchors.clear();
st.xrefs.clear();
+ st.index_refs.clear();
st.fix_marks();
st.rev += 1;
Ok(())
diff --git a/crates/doc/src/index.rs b/crates/doc/src/index.rs
new file mode 100644
index 000000000..0c2e58f4d
--- /dev/null
+++ b/crates/doc/src/index.rs
@@ -0,0 +1,246 @@
+//! Index (Window › Type & Tables › Index): page references marked in stories and the generated
+//! index story.
+//!
+//! A page reference is a zero-width [`INDEX_MARK`] in a story; [`Story::index_refs`] holds one
+//! [`IndexRef`] per mark in text order (like footnotes and cross-references). Generating the
+//! index composes the document to find each mark's page and writes a story with "Index Title",
+//! "Index Section Head" and "Index Level n" paragraph styles.
+
+use std::collections::BTreeMap;
+
+use serde::{Deserialize, Serialize};
+
+use crate::ids::StoryId;
+
+/// A page reference (index marker).
+pub const INDEX_MARK: char = '\u{E00D}';
+
+/// The page range a reference covers.
+#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase", tag = "type", content = "value")]
+pub enum IndexRange {
+ #[default]
+ CurrentPage,
+ /// From the marker's page to the page where the story ends.
+ ToEndOfStory,
+ /// From the marker's page through the next `n` paragraphs.
+ NextParagraphs(u32),
+ /// The topic is listed without page numbers.
+ SuppressPageRange,
+ /// "See …" instead of page numbers.
+ See(String),
+ /// Page numbers followed by "See also …".
+ SeeAlso(String),
+}
+
+#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct IndexRef {
+ /// Topic levels, 1 to 4 (e.g. `["Typography", "kerning"]`).
+ pub topics: Vec<String>,
+ /// Sort keys per level (empty = the topic itself).
+ #[serde(default, skip_serializing_if = "Vec::is_empty")]
+ pub sort: Vec<String>,
+ #[serde(default)]
+ pub range: IndexRange,
+}
+
+/// Generate Index options (kept for regeneration).
+#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase", default)]
+pub struct IndexSpec {
+ pub story: StoryId,
+ pub title: String,
+ /// Include Index Section Headings (A, B, C…).
+ pub section_headings: bool,
+ /// Run-in: subtopics follow their topic in one paragraph (else nested paragraphs).
+ pub run_in: bool,
+ /// Entry separators.
+ pub following_topic: String,
+ pub between_pages: String,
+ pub page_range: String,
+ pub between_entries: String,
+ pub before_cross_ref: String,
+}
+
+impl Default for IndexSpec {
+ fn default() -> Self {
+ IndexSpec {
+ story: StoryId(0),
+ title: "Index".into(),
+ section_headings: true,
+ run_in: false,
+ following_topic: " ".into(),
+ between_pages: ", ".into(),
+ page_range: "\u{2013}".into(),
+ between_entries: "; ".into(),
+ before_cross_ref: ". ".into(),
+ }
+ }
+}
+
+/// One reference with its resolved page span (absolute pages; None for page-less references).
+#[derive(Clone, Debug, PartialEq)]
+pub struct Resolved {
+ pub r: IndexRef,
+ pub pages: Option<(usize, usize)>,
+}
+
+#[derive(Default, Debug)]
+struct Node {
+ name: String,
+ pages: Vec<(usize, usize)>,
+ see: Vec<String>,
+ see_also: Vec<String>,
+ children: BTreeMap<String, Node>,
+}
+
+fn sort_key(s: &str) -> String {
+ let k: String = s.trim().trim_start_matches(|c: char| !c.is_alphanumeric()).to_lowercase();
+ if k.is_empty() { s.to_lowercase() } else { k }
+}
+
+/// The index as paragraphs `(style, text)`; `page_name` formats an absolute page.
+pub fn build(spec: &IndexSpec, refs: &[Resolved], page_name: &dyn Fn(usize) -> String) -> Vec<(String, String)> {
+ let mut root: BTreeMap<String, Node> = BTreeMap::new();
+ for res in refs {
+ let topics: Vec<&String> = res.r.topics.iter().filter(|t| !t.trim().is_empty()).take(4).collect();
+ if topics.is_empty() {
+ continue;
+ }
+ let keys: Vec<(String, String)> = topics
+ .iter()
+ .enumerate()
+ .map(|(i, t)| (format!("{}\u{0}{}", sort_key(res.r.sort.get(i).filter(|s| !s.is_empty()).unwrap_or(t)), t.trim()), t.trim().to_string()))
+ .collect();
+ let n = descend(&mut root, &keys);
+ match &res.r.range {
+ IndexRange::See(t) => n.see.push(t.clone()),
+ IndexRange::SeeAlso(t) => {
+ n.see_also.push(t.clone());
+ if let Some(p) = res.pages {
+ n.pages.push(p);
+ }
+ }
+ IndexRange::SuppressPageRange => {}
+ _ => {
+ if let Some(p) = res.pages {
+ n.pages.push(p);
+ }
+ }
+ }
+ }
+ let mut out = Vec::new();
+ if !spec.title.is_empty() {
+ out.push(("Index Title".to_string(), spec.title.clone()));
+ }
+ let mut heading: Option<char> = None;
+ for (key, n) in &root {
+ if spec.section_headings {
+ let c = key.chars().next().map(|c| if c.is_alphabetic() { c.to_uppercase().next().unwrap_or(c) } else { '#' });
+ if c != heading {
+ heading = c;
+ if let Some(c) = c {
+ out.push(("Index Section Head".into(), if c == '#' { "Symbols".into() } else { c.to_string() }));
+ }
+ }
+ }
+ emit(spec, n, 1, page_name, &mut out);
+ }
+ out
+}
+
+/// The node for a topic path (created as needed).
+fn descend<'a>(level: &'a mut BTreeMap<String, Node>, keys: &[(String, String)]) -> &'a mut Node {
+ let (k, name) = &keys[0];
+ let n = level.entry(k.clone()).or_insert_with(|| Node { name: name.clone(), ..Default::default() });
+ if keys.len() == 1 { n } else { descend(&mut n.children, &keys[1..]) }
+}
+
+fn entry_text(spec: &IndexSpec, n: &Node, page_name: &dyn Fn(usize) -> String) -> String {
+ let mut pages = n.pages.clone();
+ pages.sort_unstable();
+ pages.dedup();
+ // Drop single pages already inside a range.
+ let ranges: Vec<(usize, usize)> = pages.iter().copied().filter(|&(a, b)| a != b).collect();
+ pages.retain(|&(a, b)| a != b || !ranges.iter().any(|&(x, y)| x <= a && a <= y));
+ let list: Vec<String> =
+ pages.iter().map(|&(a, b)| if a == b { page_name(a) } else { format!("{}{}{}", page_name(a), spec.page_range, page_name(b)) }).collect();
+ let mut t = n.name.clone();
+ if !list.is_empty() {
+ t.push_str(&spec.following_topic);
+ t.push_str(&list.join(&spec.between_pages));
+ }
+ if !n.see.is_empty() {
+ t.push_str(if list.is_empty() { &spec.following_topic } else { &spec.before_cross_ref });
+ t.push_str("See ");
+ t.push_str(&n.see.join(&spec.between_entries));
+ }
+ if !n.see_also.is_empty() {
+ t.push_str(&spec.before_cross_ref);
+ t.push_str("See also ");
+ t.push_str(&n.see_also.join(&spec.between_entries));
+ }
+ t
+}
+
+fn emit(spec: &IndexSpec, n: &Node, level: usize, page_name: &dyn Fn(usize) -> String, out: &mut Vec<(String, String)>) {
+ if spec.run_in && level == 1 {
+ let mut t = entry_text(spec, n, page_name);
+ let subs: Vec<String> = n.children.values().map(|c| entry_text(spec, c, page_name)).collect();
+ if !subs.is_empty() {
+ t.push_str(": ");
+ t.push_str(&subs.join(&spec.between_entries));
+ }
+ out.push(("Index Level 1".into(), t));
+ return;
+ }
+ out.push((format!("Index Level {level}"), entry_text(spec, n, page_name)));
+ for c in n.children.values() {
+ emit(spec, c, (level + 1).min(4), page_name, out);
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ fn r(topics: &[&str], range: IndexRange, pages: Option<(usize, usize)>) -> Resolved {
+ Resolved { r: IndexRef { topics: topics.iter().map(|s| s.to_string()).collect(), sort: vec![], range }, pages }
+ }
+
+ #[test]
+ fn builds_nested_index() {
+ let refs = vec![
+ r(&["Typography", "kerning"], IndexRange::CurrentPage, Some((4, 4))),
+ r(&["Typography"], IndexRange::ToEndOfStory, Some((1, 3))),
+ r(&["Typography"], IndexRange::CurrentPage, Some((2, 2))),
+ r(&["typography", "Leading"], IndexRange::CurrentPage, Some((6, 6))),
+ r(&["Baseline grid"], IndexRange::CurrentPage, Some((0, 0))),
+ r(&["Grid"], IndexRange::See("Baseline grid".into()), None),
+ r(&["Ampersand"], IndexRange::SeeAlso("Glyphs".into()), Some((9, 9))),
+ ];
+ let spec = IndexSpec::default();
+ let out = build(&spec, &refs, &|p| (p + 1).to_string());
+ let lines: Vec<String> = out.iter().map(|(s, t)| format!("{s}|{t}")).collect();
+ assert_eq!(
+ lines,
+ [
+ "Index Title|Index",
+ "Index Section Head|A",
+ "Index Level 1|Ampersand 10. See also Glyphs",
+ "Index Section Head|B",
+ "Index Level 1|Baseline grid 1",
+ "Index Section Head|G",
+ "Index Level 1|Grid See Baseline grid",
+ "Index Section Head|T",
+ "Index Level 1|Typography 2\u{2013}4",
+ "Index Level 2|kerning 5",
+ "Index Level 1|typography",
+ "Index Level 2|Leading 7",
+ ]
+ );
+ let run_in = build(&IndexSpec { run_in: true, section_headings: false, title: String::new(), ..spec }, &refs[..2], &|p| (p + 1).to_string());
+ assert_eq!(run_in, [("Index Level 1".to_string(), "Typography 2\u{2013}4: kerning 5".to_string())]);
+ }
+}
diff --git a/crates/doc/src/lib.rs b/crates/doc/src/lib.rs
index b91ac1901..f6a83a5ea 100644
--- a/crates/doc/src/lib.rs
+++ b/crates/doc/src/lib.rs
@@ -12,6 +12,7 @@ pub mod attrs;
pub mod build;
mod edit;
pub mod ids;
+pub mod index;
pub mod item;
pub mod notes;
pub mod page;
@@ -30,6 +31,7 @@ pub use designcraft_color as color;
pub use designcraft_geom as geom;
pub use edit::{ItemLoc, ItemPath, SpreadRef, item_hit as edit_hit};
pub use ids::*;
+pub use index::{INDEX_MARK, IndexRef};
pub use item::*;
pub use notes::{FOOTNOTE_REF, FOOTNOTE_TABLE, Footnote, FootnoteOptions};
pub use page::*;
@@ -257,6 +259,9 @@ pub struct Document {
/// Cross-reference formats (Type › Hyperlinks & Cross-References › Cross-Reference Formats).
#[serde(default = "xref::default_formats")]
pub xref_formats: Vec<XrefFormat>,
+ /// The generated index (kept for Update Index).
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub index: Option<index::IndexSpec>,
/// Creation / last save time (Unix seconds, UTC).
#[serde(default)]
pub created: i64,
diff --git a/crates/doc/src/story.rs b/crates/doc/src/story.rs
index ea40e5fdf..df2e57efd 100644
--- a/crates/doc/src/story.rs
+++ b/crates/doc/src/story.rs
@@ -104,6 +104,9 @@ pub struct Story {
/// Cross-references, one per [`crate::xref::XREF_MARK`] in text order.
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub xrefs: Vec<Arc<crate::xref::CrossRef>>,
+ /// Index page references, one per [`crate::index::INDEX_MARK`] in text order.
+ #[serde(default, skip_serializing_if = "Vec::is_empty")]
+ pub index_refs: Vec<Arc<crate::index::IndexRef>>,
}
impl Story {
@@ -119,6 +122,7 @@ impl Story {
notes: Vec::new(),
anchors: Vec::new(),
xrefs: Vec::new(),
+ index_refs: Vec::new(),
}
}
@@ -207,7 +211,7 @@ impl Story {
let k = self.notes_before(pos);
self.notes_inserted(k, refs);
}
- if text.contains([crate::xref::ANCHOR_MARK, crate::xref::XREF_MARK]) {
+ if text.contains([crate::xref::ANCHOR_MARK, crate::xref::XREF_MARK, crate::index::INDEX_MARK]) {
self.marks_inserted(pos, text);
}
// Paragraph formats: each new '\n' splits the current paragraph; the new paragraphs copy it.
diff --git a/crates/doc/src/xref.rs b/crates/doc/src/xref.rs
index b7a8b47a2..6e87dd399 100644
--- a/crates/doc/src/xref.rs
+++ b/crates/doc/src/xref.rs
@@ -201,11 +201,26 @@ impl Story {
self.xrefs.insert(k + i, Arc::new(CrossRef { target: 0, format: String::new() }));
}
}
+ let n = text.matches(crate::index::INDEX_MARK).count();
+ if n > 0 {
+ let k = self.marks_before(crate::index::INDEX_MARK, pos);
+ for i in 0..n {
+ self.index_refs.insert(k + i, Arc::new(crate::index::IndexRef::default()));
+ }
+ }
+ }
+
+ /// Insert an index page reference at `pos`.
+ pub fn insert_index_ref(&mut self, pos: usize, r: crate::index::IndexRef) {
+ let pos = crate::story::floor_char_boundary(&self.text, pos.min(self.len()));
+ self.insert(pos, &crate::index::INDEX_MARK.to_string());
+ let k = self.marks_before(crate::index::INDEX_MARK, pos);
+ self.index_refs[k] = Arc::new(r);
}
/// Keep anchor/xref lists in step with a deletion of `a..b` (before it happens).
pub(crate) fn marks_deleted(&mut self, a: usize, b: usize) {
- for mark in [ANCHOR_MARK, XREF_MARK] {
+ for mark in [ANCHOR_MARK, XREF_MARK, crate::index::INDEX_MARK] {
let n = self.text[a..b].matches(mark).count();
if n == 0 {
continue;
@@ -213,8 +228,10 @@ impl Story {
let k = self.marks_before(mark, a);
if mark == ANCHOR_MARK {
self.anchors.drain(k..(k + n).min(self.anchors.len()));
- } else {
+ } else if mark == XREF_MARK {
self.xrefs.drain(k..(k + n).min(self.xrefs.len()));
+ } else {
+ self.index_refs.drain(k..(k + n).min(self.index_refs.len()));
}
}
}
@@ -234,6 +251,11 @@ impl Story {
while self.xrefs.len() < n {
self.xrefs.push(Arc::new(CrossRef { target: 0, format: String::new() }));
}
+ let n = self.text.matches(crate::index::INDEX_MARK).count();
+ self.index_refs.truncate(n);
+ while self.index_refs.len() < n {
+ self.index_refs.push(Arc::new(crate::index::IndexRef::default()));
+ }
}
pub(crate) fn check_marks(&self) -> Result<(), String> {
@@ -241,6 +263,10 @@ impl Story {
if a != self.anchors.len() || x != self.xrefs.len() {
return Err(format!("story {}: {a} anchor / {x} xref marks for {} anchors / {} xrefs", self.id.0, self.anchors.len(), self.xrefs.len()));
}
+ let i = self.text.matches(crate::index::INDEX_MARK).count();
+ if i != self.index_refs.len() {
+ return Err(format!("story {}: {i} index marks for {} references", self.id.0, self.index_refs.len()));
+ }
Ok(())
}
}
diff --git a/crates/engine/src/cmd/index.rs b/crates/engine/src/cmd/index.rs
new file mode 100644
index 000000000..bb6f09917
--- /dev/null
+++ b/crates/engine/src/cmd/index.rs
@@ -0,0 +1,258 @@
+//! Index: page references (New Page Reference) and Generate Index.
+
+use designcraft_doc::index::{IndexRange, IndexRef, IndexSpec, Resolved};
+use designcraft_doc::{Document, INDEX_MARK, ParaAttrs, ParaFormat, ParagraphStyle, SpreadRef, StoryId, TextSel};
+use designcraft_geom::Rect;
+use serde_json::{Value, json};
+
+use super::{CommandSpec, bad, cmd, has_doc, str_param};
+use crate::{Result, Session};
+
+pub fn specs() -> Vec<CommandSpec> {
+ vec![
+ cmd!(
+ "index.addReference",
+ "New Page Reference…",
+ ["Layout", "Index"],
+ None,
+ "{topics?: [level 1..4] | topic?: \"Level 1 > Level 2\" (default: the selected text), sort?: [keys], range?: currentPage|toEndOfStory|suppressPageRange|nextParagraphs|see|seeAlso, paragraphs?: n, target?: topic for see/seeAlso} — a marker at the insertion point",
+ in_story_text,
+ add_reference
+ ),
+ cmd!(query "index.list", "Index Page References", [], None, "{} → [{story, pos, topics, range, page}]", has_doc, list),
+ cmd!(
+ "index.generate",
+ "Generate Index…",
+ ["Layout", "Index"],
+ None,
+ "{title?: \"Index\", sectionHeadings?: true, runIn?: false, page?: 1-based page for a new frame, rect?: [x0,y0,x1,y1]} — replaces the existing index → {story, entries}",
+ has_doc,
+ generate
+ ),
+ cmd!("index.update", "Update Index", ["Layout", "Index"], None, "{} — regenerate the existing index", has_index, |s, _| {
+ let spec = s.doc()?.doc.index.clone().ok_or_else(|| bad("index.update", "no index"))?;
+ fill_index(s, spec, None)
+ }),
+ ]
+}
+
+fn in_story_text(s: &Session) -> std::result::Result<(), String> {
+ super::has_text(s)?;
+ match s.active().and_then(|d| d.selection.text) {
+ Some(t) if t.cell.is_some() => Err("index markers go in story text".into()),
+ _ => Ok(()),
+ }
+}
+
+fn has_index(s: &Session) -> std::result::Result<(), String> {
+ match s.doc() {
+ Ok(st) if st.doc.index.as_ref().is_some_and(|t| st.doc.story(t.story).is_some()) => Ok(()),
+ _ => Err("the document has no index".into()),
+ }
+}
+
+fn add_reference(s: &mut Session, p: &Value) -> Result<Value> {
+ let st = s.doc()?;
+ let t = st.selection.text.ok_or_else(|| bad("index.addReference", "no insertion point"))?;
+ let selected = st.doc.story(t.story).map(|x| designcraft_doc::xref::clean(x.slice(t.range()))).unwrap_or_default();
+ let topics: Vec<String> = if let Some(a) = p.get("topics").and_then(Value::as_array) {
+ a.iter().filter_map(Value::as_str).map(str::to_string).collect()
+ } else if let Some(t) = str_param(p, "topic") {
+ t.split('>').map(|s| s.trim().to_string()).filter(|s| !s.is_empty()).collect()
+ } else if !selected.is_empty() {
+ vec![selected]
+ } else {
+ return Err(bad("index.addReference", "give `topic` or select the text to index"));
+ };
+ if topics.is_empty() || topics.len() > 4 {
+ return Err(bad("index.addReference", "1 to 4 topic levels"));
+ }
+ let target = || str_param(p, "target").unwrap_or("").to_string();
+ let range = match str_param(p, "range").unwrap_or("currentPage") {
+ "currentPage" => IndexRange::CurrentPage,
+ "toEndOfStory" => IndexRange::ToEndOfStory,
+ "suppressPageRange" => IndexRange::SuppressPageRange,
+ "nextParagraphs" => IndexRange::NextParagraphs(p.get("paragraphs").and_then(Value::as_u64).unwrap_or(1) as u32),
+ "see" => IndexRange::See(target()),
+ "seeAlso" => IndexRange::SeeAlso(target()),
+ r => return Err(bad("index.addReference", format!("unknown range `{r}`"))),
+ };
+ let sort: Vec<String> =
+ p.get("sort").and_then(Value::as_array).map(|a| a.iter().filter_map(Value::as_str).map(str::to_string).collect()).unwrap_or_default();
+ let r = IndexRef { topics, sort, range };
+ s.edit(|d, sel| {
+ let st = d.story_mut(t.story).ok_or(designcraft_doc::DocError::NoStory(t.story))?;
+ // InDesign puts the marker before the selected text.
+ let at = t.range().start.min(st.len());
+ st.insert_index_ref(at, r.clone());
+ let shift = INDEX_MARK.len_utf8();
+ sel.text = Some(TextSel { anchor: t.anchor + shift, focus: t.focus + shift, ..t });
+ Ok(json!({"pos": at}))
+ })
+}
+
+/// Every page reference with its page span.
+fn resolve(s: &Session, d: &Document, skip: Option<StoryId>) -> Vec<(StoryId, usize, Resolved)> {
+ let mut out = Vec::new();
+ for st in d.stories.values().filter(|st| !st.index_refs.is_empty() && Some(st.id) != skip) {
+ let cs = s.cache.get(d, st.id, None);
+ let page = |pos: usize| designcraft_compose::vars::page_of(d, &cs, pos);
+ for ((pos, _), r) in st.text.match_indices(INDEX_MARK).zip(&st.index_refs) {
+ let start = page(pos);
+ let end = match &r.range {
+ IndexRange::ToEndOfStory => page(st.len().saturating_sub(1)),
+ IndexRange::NextParagraphs(n) => {
+ let ranges = st.para_ranges();
+ let pi = (st.para_at(pos) + *n as usize).min(ranges.len() - 1);
+ page(ranges[pi].end.saturating_sub(1).max(ranges[pi].start))
+ }
+ _ => start,
+ };
+ let pages = match (start, end) {
+ (Some(a), Some(b)) => Some((a, b.max(a))),
+ (Some(a), None) => Some((a, a)),
+ _ => None,
+ };
+ out.push((st.id, pos, Resolved { r: (**r).clone(), pages }));
+ }
+ }
+ out
+}
+
+fn list(s: &mut Session, _: &Value) -> Result<Value> {
+ let d = s.doc()?.doc.clone();
+ let rs = resolve(s, &d, None);
+ Ok(Value::Array(
+ rs.into_iter()
+ .map(|(sid, pos, r)| json!({"story": sid.0, "pos": pos, "topics": r.r.topics, "range": r.r.range, "page": r.pages.map(|p| d.page_name(p.0))}))
+ .collect(),
+ ))
+}
+
+fn ensure_styles(d: &mut Document) {
+ let mut want = vec![
+ ("Index Title", ParaAttrs { space_after: Some(12.0), ..Default::default() }, Some(16.0)),
+ (
+ "Index Section Head",
+ ParaAttrs { space_before: Some(8.0), space_after: Some(2.0), keep_with_next: Some(2), ..Default::default() },
+ Some(11.0),
+ ),
+ ];
+ let levels = [("Index Level 1", 0.0), ("Index Level 2", 12.0), ("Index Level 3", 24.0), ("Index Level 4", 36.0)];
+ for (name, indent) in levels {
+ // Hanging indent so turnover lines stand out from subtopics.
+ want.push((name, ParaAttrs { left_indent: Some(indent + 12.0), first_line_indent: Some(-12.0), ..Default::default() }, None));
+ }
+ let missing: Vec<_> = want.into_iter().filter(|(n, ..)| d.styles.para(n).is_none()).collect();
+ if missing.is_empty() {
+ return;
+ }
+ let st = d.styles_mut();
+ for (name, para, size) in missing {
+ st.paragraph.push(ParagraphStyle {
+ name: name.into(),
+ based_on: Some(designcraft_doc::story::BASIC_PARAGRAPH.into()),
+ next_style: None,
+ para,
+ chars: designcraft_doc::CharAttrs { size, ..Default::default() },
+ shortcut: String::new(),
+ });
+ }
+}
+
+fn fill_index(s: &mut Session, spec: IndexSpec, new_frame: Option<(usize, Option<Rect>)>) -> Result<Value> {
+ let d0 = s.doc()?.doc.clone();
+ let existing = d0.index.as_ref().map(|i| i.story).filter(|sid| d0.story(*sid).is_some());
+ let refs = resolve(s, &d0, existing);
+ let resolved: Vec<Resolved> = refs.into_iter().map(|(_, _, r)| r).collect();
+ let paras = designcraft_doc::index::build(&spec, &resolved, &|p| d0.page_name(p));
+ s.edit(|d, sel| {
+ ensure_styles(d);
+ let story = match existing {
+ Some(sid) => sid,
+ None => {
+ let (page, rect) = new_frame.unwrap_or((0, None));
+ let (si, pi) = d.page_loc(page).ok_or_else(|| bad("index.generate", format!("no page {}", page + 1)))?;
+ let r: Rect = rect.unwrap_or_else(|| d.spreads[si].pages[pi].margin_rect());
+ let layer = d.default_layer();
+ let (fid, sid) = d.add_text_frame(SpreadRef::Doc(si), r, layer, "", ParaFormat::default())?;
+ *sel = designcraft_doc::Selection::items(vec![fid]);
+ sid
+ }
+ };
+ let text = paras.iter().map(|(_, t)| t.as_str()).collect::<Vec<_>>().join("\n");
+ let st = d.story_mut(story).ok_or(designcraft_doc::DocError::NoStory(story))?;
+ let len = st.len();
+ st.replace(0..len, &text);
+ for (pi, r) in st.para_ranges().into_iter().enumerate() {
+ if let Some((name, _)) = paras.get(pi) {
+ st.format_paras(r.start..r.start, |f| *f = ParaFormat { style: name.clone(), ..Default::default() });
+ }
+ }
+ d.index = Some(IndexSpec { story, ..spec.clone() });
+ Ok(json!({"story": story.0, "entries": paras.iter().filter(|(s, _)| s.starts_with("Index Level")).count()}))
+ })
+}
+
+fn generate(s: &mut Session, p: &Value) -> Result<Value> {
+ let mut spec = s.doc()?.doc.index.clone().unwrap_or_default();
+ if let Some(t) = str_param(p, "title") {
+ spec.title = t.into();
+ }
+ if let Some(b) = p.get("sectionHeadings").and_then(Value::as_bool) {
+ spec.section_headings = b;
+ }
+ if let Some(b) = p.get("runIn").and_then(Value::as_bool) {
+ spec.run_in = b;
+ }
+ let page = p.get("page").and_then(Value::as_u64).unwrap_or(1).max(1) as usize - 1;
+ fill_index(s, spec, Some((page, super::rect_param(p, "rect"))))
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn page_references_build_an_index() {
+ let mut s = Session::new();
+ s.execute("file.new", &json!({"pages": 3, "facingPages": false})).unwrap();
+ let mut sids = vec![];
+ for page in 0..3usize {
+ let sp = s.doc().unwrap().doc.page_loc(page).unwrap().0;
+ let text = ["Kerning adjusts pairs.", "Leading sets line spacing. Kerning again.", "Grids organise pages."][page];
+ let r = s.execute("frame.create", &json!({"spread": sp, "rect": [72, 72, 400, 300], "content": "text", "text": text})).unwrap();
+ sids.push(s.doc().unwrap().doc.item(designcraft_doc::ItemId(r["id"].as_u64().unwrap())).unwrap().text_frame().unwrap().story);
+ }
+ // Topic from the selected word, explicit nested topics, a See reference.
+ s.execute("text.select", &json!({"story": sids[0].0, "anchor": 0, "focus": 7})).unwrap();
+ s.execute("index.addReference", &json!({})).unwrap();
+ s.execute("text.select", &json!({"story": sids[1].0, "anchor": 0, "focus": 0})).unwrap();
+ s.execute("index.addReference", &json!({"topic": "Type > Leading"})).unwrap();
+ s.execute("text.select", &json!({"story": sids[1].0, "anchor": 30, "focus": 30})).unwrap();
+ s.execute("index.addReference", &json!({"topic": "Kerning"})).unwrap();
+ s.execute("text.select", &json!({"story": sids[2].0, "anchor": 0, "focus": 0})).unwrap();
+ s.execute("index.addReference", &json!({"topic": "Line spacing", "range": "see", "target": "Type: Leading"})).unwrap();
+ // The marker doesn't change the selection's text.
+ let st = s.doc().unwrap().doc.story(sids[0]).unwrap().clone();
+ let sel = s.doc().unwrap().selection.text.unwrap();
+ let _ = sel;
+ assert!(st.text.starts_with(INDEX_MARK));
+ let l = s.execute("index.list", &json!({})).unwrap();
+ assert_eq!(l.as_array().unwrap().len(), 4);
+ s.execute("layout.pages.insert", &json!({"count": 1})).unwrap();
+ let r = s.execute("index.generate", &json!({"page": 4})).unwrap();
+ let sid = StoryId(r["story"].as_u64().unwrap());
+ let text = s.doc().unwrap().doc.story(sid).unwrap().text.clone();
+ assert_eq!(text, "Index\nK\nKerning 1, 2\nL\nLine spacing See Type: Leading\nT\nType\nLeading 2");
+ assert_eq!(s.doc().unwrap().doc.story(sid).unwrap().paras[6].style, "Index Level 1");
+ assert_eq!(s.doc().unwrap().doc.story(sid).unwrap().paras[7].style, "Index Level 2");
+ // Deleting a marked word removes its reference; update regenerates in place.
+ s.execute("text.select", &json!({"story": sids[0].0, "anchor": 0, "focus": INDEX_MARK.len_utf8() + 7})).unwrap();
+ s.execute("text.delete", &json!({})).unwrap();
+ s.execute("index.update", &json!({})).unwrap();
+ let text = s.doc().unwrap().doc.story(sid).unwrap().text.clone();
+ assert!(text.contains("Kerning 2\n"), "{text}");
+ s.doc().unwrap().doc.check().unwrap();
+ }
+}
diff --git a/crates/engine/src/cmd/mod.rs b/crates/engine/src/cmd/mod.rs
index b9253453c..d11956522 100644
--- a/crates/engine/src/cmd/mod.rs
+++ b/crates/engine/src/cmd/mod.rs
@@ -5,6 +5,7 @@ mod edit;
mod export;
mod file;
mod find;
+mod index;
mod inspect;
mod interactive;
pub mod interchange;
@@ -126,6 +127,7 @@ pub fn command_specs() -> &'static [CommandSpec] {
v.extend(toc::specs());
v.extend(notes::specs());
v.extend(xref::specs());
+ v.extend(index::specs());
v.extend(spelling::specs());
v.extend(datamerge::specs());
v.extend(interactive::specs());
diff --git a/crates/idml/src/export.rs b/crates/idml/src/export.rs
index a707c2f00..c49859354 100644
--- a/crates/idml/src/export.rs
+++ b/crates/idml/src/export.rs
@@ -133,6 +133,9 @@ struct Ex<'a> {
threads: HashMap<u64, (Option<u64>, Option<u64>)>,
/// Cross-reference sources written so far: (Self, target anchor).
xref_sources: Vec<(String, u64)>,
+ /// Index topics (paths) and their See / See also cross-references.
+ index_topics: BTreeSet<Vec<String>>,
+ index_xrefs: Vec<(Vec<String>, &'static str, String)>,
}
impl<'a> Ex<'a> {
@@ -145,6 +148,8 @@ impl<'a> Ex<'a> {
fonts: BTreeMap::new(),
threads: HashMap::new(),
xref_sources: Vec::new(),
+ index_topics: BTreeSet::new(),
+ index_xrefs: Vec::new(),
};
ex.assign_swatch_ids();
for s in d.stories.values() {
@@ -352,6 +357,9 @@ impl<'a> Ex<'a> {
el = el.attr("Marker", &s.marker).attr("PageStart", uid(page.id.0)).attr("SectionPrefix", &s.prefix);
root.push(with_props(el, vec![p("PageNumberStyle", "enumeration", names::number_style_out(s.style))]));
}
+ if !self.index_topics.is_empty() || !self.index_xrefs.is_empty() {
+ root.push(self.index_el());
+ }
// Formats before the stories whose sources apply them.
for (i, f) in d.xref_formats.iter().enumerate() {
root.push(xref_format_el(i, f));
@@ -1263,6 +1271,41 @@ impl<'a> Ex<'a> {
el
}
+ /// `<Index>`: nested topics with their See / See also cross-references.
+ fn index_el(&mut self) -> El {
+ let mut topics = self.index_topics.clone();
+ for (_, _, target) in &self.index_xrefs {
+ topics.insert(vec![target.clone()]);
+ }
+ fn build(ex: &mut Ex, topics: &BTreeSet<Vec<String>>, prefix: &[String]) -> Vec<El> {
+ let mut out = Vec::new();
+ for t in topics.iter().filter(|t| t.len() == prefix.len() + 1 && t.starts_with(prefix)) {
+ let mut el = El::new("Topic").attr("Self", topic_self(t)).attr("SortOrder", "").attr("Name", t.last().map_or("", String::as_str));
+ for (from, kind, target) in ex.index_xrefs.clone() {
+ if from == *t {
+ el.push(
+ El::new("CrossReference")
+ .attr("Self", ex.fresh())
+ .attr("ReferencedTopic", topic_self(std::slice::from_ref(&target)))
+ .attr("CrossReferenceType", kind)
+ .attr("CustomTypeString", ""),
+ );
+ }
+ }
+ for c in build(ex, topics, t) {
+ el.push(c);
+ }
+ out.push(el);
+ }
+ out
+ }
+ let mut el = El::new("Index").attr("Self", "ix");
+ for t in build(self, &topics, &[]) {
+ el.push(t);
+ }
+ el
+ }
+
fn footnote_option_el(&self) -> El {
let o = &self.d.footnote_options;
let marker = if o.ref_char_style == st::NO_CHAR_STYLE {
@@ -1433,6 +1476,41 @@ impl<'a> Ex<'a> {
.attr("DestinationUniqueKey", a.id & 0xFFFF_FFFF),
));
}
+ } else if ch == designcraft_doc::INDEX_MARK {
+ flush_text(&mut cur, &mut pending);
+ flush_content(&mut pending, &mut out);
+ let k = s.text[..seg_start + ci].matches(designcraft_doc::INDEX_MARK).count();
+ if let Some(r) = s.index_refs.get(k).filter(|r| !r.topics.is_empty()) {
+ use designcraft_doc::index::IndexRange as R;
+ for n in 1..=r.topics.len() {
+ self.index_topics.insert(r.topics[..n].to_vec());
+ }
+ let (kind, limit) = match &r.range {
+ R::CurrentPage => (Some("CurrentPage"), None),
+ R::ToEndOfStory => (Some("ToEndOfStory"), None),
+ R::NextParagraphs(n) => (Some("ForNextNParagraphs"), Some(*n)),
+ R::SuppressPageRange => (Some("SuppressPageNumbers"), None),
+ R::See(t) => {
+ self.index_xrefs.push((r.topics.clone(), "See", t.clone()));
+ (None, None)
+ }
+ R::SeeAlso(t) => {
+ self.index_xrefs.push((r.topics.clone(), "SeeAlso", t.clone()));
+ (Some("CurrentPage"), None)
+ }
+ };
+ if let Some(kind) = kind {
+ let mut el = El::new("PageReference")
+ .attr("Self", self.fresh())
+ .attr("PageReferenceType", kind)
+ .attr("ReferencedTopic", topic_self(&r.topics))
+ .attr("Id", k + 1);
+ if let Some(n) = limit {
+ el.set("PageReferenceLimit", n);
+ }
+ out.push(Node::El(el));
+ }
+ }
} else if ch == designcraft_doc::XREF_MARK {
// A source wrapping its current text (InDesign regenerates it on update).
flush_text(&mut cur, &mut pending);
@@ -1851,3 +1929,12 @@ fn xref_format_el(i: usize, f: &designcraft_doc::XrefFormat) -> El {
}
el
}
+
+fn topic_self(path: &[String]) -> String {
+ let mut s = String::from("ix");
+ for n in path {
+ s.push_str("Topicn");
+ s.push_str(&escape_id(n));
+ }
+ s
+}
diff --git a/crates/idml/src/import.rs b/crates/idml/src/import.rs
index 5e5126e90..7fb7d32f0 100644
--- a/crates/idml/src/import.rs
+++ b/crates/idml/src/import.rs
@@ -123,6 +123,9 @@ struct Importer<'r> {
/// Cross-reference format Self → name.
xref_format_names: HashMap<String, String>,
xref_formats: Vec<designcraft_doc::XrefFormat>,
+ /// Index topic Self → topic path; topic See / See also cross-references.
+ index_topics: HashMap<String, Vec<String>>,
+ index_xrefs: Vec<designcraft_doc::IndexRef>,
}
fn lab_to_color(l: f32, a: f32, b: f32) -> Color {
@@ -193,6 +196,8 @@ impl<'r> Importer<'r> {
xref_srcs: HashMap::new(),
xref_format_names: HashMap::new(),
xref_formats: designcraft_doc::xref::default_formats(),
+ index_topics: HashMap::new(),
+ index_xrefs: Vec::new(),
}
}
@@ -279,6 +284,9 @@ impl<'r> Importer<'r> {
for e in top.iter().filter(|e| e.local() == "CrossReferenceFormat") {
self.xref_format(e);
}
+ if let Some(ix) = top.iter().find(|e| e.local() == "Index") {
+ self.index_topics_of(ix, &[]);
+ }
// Stories (ids first so frames can reference them).
for e in top.iter().filter(|e| e.local() == "Story") {
let id = StoryId(self.alloc());
@@ -288,6 +296,15 @@ impl<'r> Importer<'r> {
let story = self.story(id, e);
self.stories.insert(id, story);
}
+ // Topic cross-references (See / See also) become markers at the start of the first story
+ // with text.
+ if !self.index_xrefs.is_empty()
+ && let Some(st) = self.stories.values_mut().find(|s| !s.text.is_empty())
+ {
+ for r in std::mem::take(&mut self.index_xrefs).into_iter().rev() {
+ st.insert_index_ref(0, r);
+ }
+ }
// Cross-references point at their hyperlink's destination.
for h in top.iter().filter(|e| e.local() == "Hyperlink") {
let (Some(src), Some(dest)) = (h.get("Source"), h.prop("Destination")) else { continue };
@@ -677,6 +694,38 @@ impl<'r> Importer<'r> {
}
}
+ /// Index topics (recursively); at the root, their See / See also cross-references too.
+ fn index_topics_of(&mut self, e: &El, prefix: &[String]) {
+ for t in e.find_all("Topic") {
+ let mut path = prefix.to_vec();
+ path.push(t.get("Name").unwrap_or("").to_string());
+ if let Some(me) = t.get("Self") {
+ self.index_topics.insert(me.to_string(), path.clone());
+ }
+ self.index_topics_of(t, &path);
+ }
+ if !prefix.is_empty() {
+ return;
+ }
+ let mut stack = vec![(e, Vec::<String>::new())];
+ while let Some((el, path)) = stack.pop() {
+ for t in el.find_all("Topic") {
+ let mut p = path.clone();
+ p.push(t.get("Name").unwrap_or("").to_string());
+ for x in t.find_all("CrossReference") {
+ let target = x.get("ReferencedTopic").and_then(|r| self.index_topics.get(r)).map(|p| p.join(": ")).unwrap_or_default();
+ use designcraft_doc::index::IndexRange as R;
+ let range = match x.get("CrossReferenceType") {
+ Some("SeeAlso") | Some("SeeAlsoHerein") => R::SeeAlso(target),
+ _ => R::See(target),
+ };
+ self.index_xrefs.push(designcraft_doc::IndexRef { topics: p.clone(), sort: vec![], range });
+ }
+ stack.push((t, p));
+ }
+ }
+ }
+
/// `CrossReferenceFormat`: building blocks back to a format definition.
fn xref_format(&mut self, e: &El) {
let name = e.get("Name").unwrap_or("Format").to_string();
@@ -937,9 +986,10 @@ impl<'r> Importer<'r> {
notes: Vec::new(),
anchors: Vec::new(),
xrefs: Vec::new(),
+ index_refs: Vec::new(),
};
self.walk_story(e, &mut b, &ParaFormat::default(), &CharAttrs::default(), &CharFormat::default(), None);
- let StoryBuilder { text, mut paras, runs, last, tables: tbls, notes, anchors, xrefs, .. } = b;
+ let StoryBuilder { text, mut paras, runs, last, tables: tbls, notes, anchors, xrefs, index_refs, .. } = b;
let mut chars: Vec<CharRun> = runs.into_iter().filter(|r| r.len > 0).collect();
if chars.is_empty() {
chars.push(CharRun { len: 0, format: last });
@@ -964,7 +1014,19 @@ impl<'r> Importer<'r> {
let format = self.xref_format_names.get(&fmt).cloned().unwrap_or_else(|| "Full Paragraph & Page Number".into());
xref_list.push(Arc::new(designcraft_doc::CrossRef { target: 0, format }));
}
- let mut st = Story { id, text, paras, chars, frames: vec![], rev: 0, tables, notes, anchors: anchor_list, xrefs: xref_list };
+ let mut st = Story {
+ id,
+ text,
+ paras,
+ chars,
+ frames: vec![],
+ rev: 0,
+ tables,
+ notes,
+ anchors: anchor_list,
+ xrefs: xref_list,
+ index_refs: index_refs.into_iter().map(Arc::new).collect(),
+ };
st.fix_notes();
st.fix_marks();
// Drop anything inconsistent (e.g. a table sharing a paragraph with another).
@@ -1151,6 +1213,18 @@ impl<'r> Importer<'r> {
b.anchors.push((c.get("Self").unwrap_or("").to_string(), c.get("Name").unwrap_or("Anchor").to_string()));
b.push(&designcraft_doc::ANCHOR_MARK.to_string(), cf);
}
+ "PageReference" => {
+ use designcraft_doc::index::IndexRange as R;
+ let topics = c.get("ReferencedTopic").and_then(|r| self.index_topics.get(r)).cloned().unwrap_or_default();
+ let range = match c.get("PageReferenceType") {
+ Some("ToEndOfStory") | Some("ToEndOfDocument") | Some("ToEndOfSection") => R::ToEndOfStory,
+ Some("ForNextNParagraphs") => R::NextParagraphs(c.num("PageReferenceLimit").unwrap_or(1.0).max(1.0) as u32),
+ Some("SuppressPageNumbers") => R::SuppressPageRange,
+ _ => R::CurrentPage,
+ };
+ b.index_refs.push(designcraft_doc::IndexRef { topics, sort: vec![], range });
+ b.push(&designcraft_doc::INDEX_MARK.to_string(), cf);
+ }
"CrossReferenceSource" => {
// The generated text is regenerated from the format.
b.xrefs.push((c.get("Self").unwrap_or("").to_string(), c.get("AppliedFormat").unwrap_or("").to_string()));
@@ -1641,6 +1715,7 @@ impl<'r> Importer<'r> {
text_variables: designcraft_doc::vars::defaults(),
footnote_options: std::mem::take(&mut self.footnote_options),
xref_formats: std::mem::take(&mut self.xref_formats),
+ index: None,
created: designcraft_doc::vars::now(),
modified: 0,
next_id: self.next_id,
@@ -1673,6 +1748,7 @@ struct StoryBuilder {
notes: Vec<Story>,
/// Text destinations (Self, name) and cross-reference sources (Self, format Self) in order.
anchors: Vec<(String, String)>,
+ index_refs: Vec<designcraft_doc::IndexRef>,
xrefs: Vec<(String, String)>,
}
diff --git a/crates/idml/src/tests.rs b/crates/idml/src/tests.rs
index 633bf5ff7..22ffadc75 100644
--- a/crates/idml/src/tests.rs
+++ b/crates/idml/src/tests.rs
@@ -453,3 +453,40 @@ fn round_trips_cross_references() {
assert_eq!(mine.definition, d.xref_format("Mine").unwrap().definition);
assert_eq!(back.xref_formats.len(), d.xref_formats.len());
}
+
+#[test]
+fn round_trips_index_references() {
+ use designcraft_doc::index::IndexRange;
+ let mut d = Document::new(&NewDocument::default());
+ let lid = d.default_layer();
+ let (_, sid) = d
+ .add_text_frame(SpreadRef::Doc(0), Rect::new(40.0, 40.0, 400.0, 400.0), lid, "Kerning adjusts pairs.\nMore.", ParaFormat::default())
+ .unwrap();
+ {
+ let s = d.story_mut(sid).unwrap();
+ s.insert_index_ref(
+ 0,
+ designcraft_doc::IndexRef { topics: vec!["Type".into(), "Kerning".into()], sort: vec![], range: IndexRange::CurrentPage },
+ );
+ s.insert_index_ref(5, designcraft_doc::IndexRef { topics: vec!["Pairs".into()], sort: vec![], range: IndexRange::NextParagraphs(2) });
+ s.insert_index_ref(9, designcraft_doc::IndexRef { topics: vec!["Spacing".into()], sort: vec![], range: IndexRange::See("Type".into()) });
+ }
+ d.check().unwrap();
+ let back = import_idml(&export_idml(&d)).unwrap();
+ back.check().unwrap();
+ let s = back.stories.values().next().unwrap();
+ let mut got: Vec<(Vec<String>, IndexRange)> = s.index_refs.iter().map(|r| (r.topics.clone(), r.range.clone())).collect();
+ got.sort_by(|a, b| a.0.cmp(&b.0));
+ assert_eq!(
+ got,
+ [
+ (vec!["Pairs".to_string()], IndexRange::NextParagraphs(2)),
+ (vec!["Spacing".to_string()], IndexRange::See("Type".into())),
+ (vec!["Type".to_string(), "Kerning".to_string()], IndexRange::CurrentPage),
+ ]
+ );
+ // The text survives; page references keep their places (See references, which InDesign keeps
+ // on topics rather than in text, come back at the story start).
+ assert_eq!(s.text.replace(designcraft_doc::INDEX_MARK, ""), "Kerning adjusts pairs.\nMore.");
+ assert!(s.text.starts_with(&format!("{0}{0}Ke{0}rning", designcraft_doc::INDEX_MARK)), "{:?}", s.text);
+}
diff --git a/crates/ui-egui/src/menus.rs b/crates/ui-egui/src/menus.rs
index 650c9e0a5..8857764bd 100644
--- a/crates/ui-egui/src/menus.rs
+++ b/crates/ui-egui/src/menus.rs
@@ -138,6 +138,11 @@ pub const MENUS: &[(&str, &[&str])] = &[
"cmd:layout.section",
"cmd:toc.generate",
"cmd:toc.update",
+ ">Index",
+ "cmd:index.addReference",
+ "cmd:index.generate",
+ "cmd:index.update",
+ "<",
],
),
(