@folijs/core 0.4.0 → 0.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (153) hide show
  1. package/CHANGELOG.md +49 -0
  2. package/dist/model/schema.d.ts +9 -1
  3. package/dist/model/schema.d.ts.map +1 -1
  4. package/dist/model/schema.js +13 -3
  5. package/dist/model/schema.js.map +1 -1
  6. package/dist/state/commands.d.ts +10 -1
  7. package/dist/state/commands.d.ts.map +1 -1
  8. package/dist/state/commands.js +125 -40
  9. package/dist/state/commands.js.map +1 -1
  10. package/dist/state/comments.d.ts.map +1 -1
  11. package/dist/state/comments.js +15 -6
  12. package/dist/state/comments.js.map +1 -1
  13. package/dist/state/controls.d.ts +128 -0
  14. package/dist/state/controls.d.ts.map +1 -0
  15. package/dist/state/controls.js +1459 -0
  16. package/dist/state/controls.js.map +1 -0
  17. package/dist/state/editor.d.ts +86 -1
  18. package/dist/state/editor.d.ts.map +1 -1
  19. package/dist/state/editor.js +169 -41
  20. package/dist/state/editor.js.map +1 -1
  21. package/dist/state/fields.d.ts +79 -0
  22. package/dist/state/fields.d.ts.map +1 -0
  23. package/dist/state/fields.js +398 -0
  24. package/dist/state/fields.js.map +1 -0
  25. package/dist/state/fieldupdate.d.ts +178 -0
  26. package/dist/state/fieldupdate.d.ts.map +1 -0
  27. package/dist/state/fieldupdate.js +1574 -0
  28. package/dist/state/fieldupdate.js.map +1 -0
  29. package/dist/state/find.d.ts +68 -0
  30. package/dist/state/find.d.ts.map +1 -0
  31. package/dist/state/find.js +397 -0
  32. package/dist/state/find.js.map +1 -0
  33. package/dist/state/history.d.ts +12 -1
  34. package/dist/state/history.d.ts.map +1 -1
  35. package/dist/state/history.js +43 -7
  36. package/dist/state/history.js.map +1 -1
  37. package/dist/state/index.d.ts +15 -5
  38. package/dist/state/index.d.ts.map +1 -1
  39. package/dist/state/index.js +13 -3
  40. package/dist/state/index.js.map +1 -1
  41. package/dist/state/links.d.ts.map +1 -1
  42. package/dist/state/links.js +30 -19
  43. package/dist/state/links.js.map +1 -1
  44. package/dist/state/mark.d.ts.map +1 -1
  45. package/dist/state/mark.js +8 -1
  46. package/dist/state/mark.js.map +1 -1
  47. package/dist/state/navigation.d.ts +70 -0
  48. package/dist/state/navigation.d.ts.map +1 -0
  49. package/dist/state/navigation.js +226 -0
  50. package/dist/state/navigation.js.map +1 -0
  51. package/dist/state/notes.d.ts +94 -0
  52. package/dist/state/notes.d.ts.map +1 -0
  53. package/dist/state/notes.js +444 -0
  54. package/dist/state/notes.js.map +1 -0
  55. package/dist/state/pictures.d.ts +51 -0
  56. package/dist/state/pictures.d.ts.map +1 -0
  57. package/dist/state/pictures.js +140 -0
  58. package/dist/state/pictures.js.map +1 -0
  59. package/dist/state/review.d.ts +13 -4
  60. package/dist/state/review.d.ts.map +1 -1
  61. package/dist/state/review.js +223 -29
  62. package/dist/state/review.js.map +1 -1
  63. package/dist/state/sections.d.ts +101 -0
  64. package/dist/state/sections.d.ts.map +1 -0
  65. package/dist/state/sections.js +472 -0
  66. package/dist/state/sections.js.map +1 -0
  67. package/dist/state/selection.d.ts +12 -1
  68. package/dist/state/selection.d.ts.map +1 -1
  69. package/dist/state/selection.js +12 -0
  70. package/dist/state/selection.js.map +1 -1
  71. package/dist/state/state.d.ts +2 -0
  72. package/dist/state/state.d.ts.map +1 -1
  73. package/dist/state/state.js +4 -0
  74. package/dist/state/state.js.map +1 -1
  75. package/dist/state/stories.d.ts +41 -0
  76. package/dist/state/stories.d.ts.map +1 -0
  77. package/dist/state/stories.js +243 -0
  78. package/dist/state/stories.js.map +1 -0
  79. package/dist/state/tablecommands.d.ts +77 -0
  80. package/dist/state/tablecommands.d.ts.map +1 -0
  81. package/dist/state/tablecommands.js +675 -0
  82. package/dist/state/tablecommands.js.map +1 -0
  83. package/dist/state/tables.d.ts +110 -0
  84. package/dist/state/tables.d.ts.map +1 -0
  85. package/dist/state/tables.js +730 -0
  86. package/dist/state/tables.js.map +1 -0
  87. package/dist/state/track.d.ts +23 -0
  88. package/dist/state/track.d.ts.map +1 -1
  89. package/dist/state/track.js +113 -15
  90. package/dist/state/track.js.map +1 -1
  91. package/dist/state/word.d.ts +78 -16
  92. package/dist/state/word.d.ts.map +1 -1
  93. package/dist/state/word.js +231 -11
  94. package/dist/state/word.js.map +1 -1
  95. package/dist/state/wordclip.d.ts +15 -6
  96. package/dist/state/wordclip.d.ts.map +1 -1
  97. package/dist/state/wordclip.js +213 -18
  98. package/dist/state/wordclip.js.map +1 -1
  99. package/dist/state/wordformat.d.ts +10 -2
  100. package/dist/state/wordformat.d.ts.map +1 -1
  101. package/dist/state/wordformat.js +98 -17
  102. package/dist/state/wordformat.js.map +1 -1
  103. package/dist/v3/document.d.ts +237 -7
  104. package/dist/v3/document.d.ts.map +1 -1
  105. package/dist/v3/document.js +314 -15
  106. package/dist/v3/document.js.map +1 -1
  107. package/dist/v3/index.d.ts +2 -2
  108. package/dist/v3/index.d.ts.map +1 -1
  109. package/dist/v3/index.js +2 -2
  110. package/dist/v3/index.js.map +1 -1
  111. package/dist/v3/migrate.d.ts +2 -2
  112. package/dist/v3/migrate.d.ts.map +1 -1
  113. package/dist/v3/resolve.d.ts +57 -5
  114. package/dist/v3/resolve.d.ts.map +1 -1
  115. package/dist/v3/resolve.js +224 -16
  116. package/dist/v3/resolve.js.map +1 -1
  117. package/dist/v3/schema.d.ts +6 -0
  118. package/dist/v3/schema.d.ts.map +1 -1
  119. package/dist/v3/schema.js +254 -8
  120. package/dist/v3/schema.js.map +1 -1
  121. package/package.json +1 -1
  122. package/src/model/schema.ts +18 -2
  123. package/src/state/commands.ts +121 -32
  124. package/src/state/comments.ts +14 -6
  125. package/src/state/controls.ts +1596 -0
  126. package/src/state/editor.ts +292 -46
  127. package/src/state/fields.ts +432 -0
  128. package/src/state/fieldupdate.ts +1770 -0
  129. package/src/state/find.ts +510 -0
  130. package/src/state/history.ts +51 -7
  131. package/src/state/index.ts +157 -0
  132. package/src/state/links.ts +27 -17
  133. package/src/state/mark.ts +8 -1
  134. package/src/state/navigation.ts +305 -0
  135. package/src/state/notes.ts +519 -0
  136. package/src/state/numeric-pictures.word.json +172 -0
  137. package/src/state/pictures.ts +168 -0
  138. package/src/state/review.ts +265 -31
  139. package/src/state/sections.ts +571 -0
  140. package/src/state/selection.ts +15 -1
  141. package/src/state/state.ts +5 -0
  142. package/src/state/stories.ts +285 -0
  143. package/src/state/tablecommands.ts +741 -0
  144. package/src/state/tables.ts +761 -0
  145. package/src/state/track.ts +128 -16
  146. package/src/state/word.ts +276 -13
  147. package/src/state/wordclip.ts +231 -32
  148. package/src/state/wordformat.ts +96 -14
  149. package/src/v3/document.ts +572 -16
  150. package/src/v3/index.ts +21 -0
  151. package/src/v3/migrate.ts +2 -2
  152. package/src/v3/resolve.ts +289 -21
  153. package/src/v3/schema.ts +278 -9
@@ -0,0 +1,1770 @@
1
+ /**
2
+ * Updating and inserting Word's fields (ADR-0007, 11.8). A field's result is worked out from its
3
+ * instruction, as Word's switches say, and put between its separator and end; a table of contents
4
+ * is rebuilt from the headings as Word builds it. Everything happens in one transaction, recorded
5
+ * as tracked changes when tracking is on; what cannot be worked out keeps its result and is
6
+ * reported. Page numbers come from `FieldLayout`, which only a view has.
7
+ */
8
+ import {
9
+ Fragment,
10
+ type Mark,
11
+ type Node,
12
+ type NodeType,
13
+ type Schema,
14
+ Slice,
15
+ } from "../model/index.js";
16
+ import { TransformError } from "../transform/transform.js";
17
+ import type { SectionJSON } from "../v3/document.js";
18
+ import { formatNumber, type ListMarker } from "../v3/resolve.js";
19
+ import { attempt } from "./attempt.js";
20
+ import { controlEdit } from "./controls.js";
21
+ import type { Editor } from "./editor.js";
22
+ import { type Field, fieldAround, fieldsIn } from "./fields.js";
23
+ import { closeHistory, joinHistory } from "./history.js";
24
+ import { marksAt, TextSelection } from "./selection.js";
25
+ import type { Command, EditorState, Transaction } from "./state.js";
26
+ import { trackState, trackTransaction, untracked } from "./track.js";
27
+ import {
28
+ otherTrees,
29
+ type Story,
30
+ StoryStep,
31
+ storyBody,
32
+ type WordContext,
33
+ type WordEnvelope,
34
+ withEnvelope,
35
+ wordContext,
36
+ } from "./word.js";
37
+ import { ensureStyle } from "./wordformat.js";
38
+
39
+ // ---------- instructions ----------
40
+
41
+ /** A field's instruction in parts. Switch keys: the letter in lower case, or `*`, `@`, `#`. */
42
+ export interface FieldInstruction {
43
+ name: string;
44
+ args: string[];
45
+ switches: Map<string, string[]>;
46
+ }
47
+
48
+ /** The switches of each field that take a value (`\*`, `\@` and `\#` always do). */
49
+ const WITH_VALUE: Record<string, string> = {
50
+ SEQ: "rs",
51
+ TOC: "abcdflnopst",
52
+ MERGEFIELD: "bf",
53
+ REF: "d",
54
+ };
55
+ const GENERAL = "*@#";
56
+
57
+ /** Word's quoting: `"…"`, with `\"` and `\\` inside; a switch is `\` and one character. */
58
+ function tokens(text: string): { value: string; quoted: boolean }[] {
59
+ const out: { value: string; quoted: boolean }[] = [];
60
+ let i = 0;
61
+ while (i < text.length) {
62
+ if (/\s/.test(text[i] as string)) i++;
63
+ else if (text[i] === '"') {
64
+ let value = "";
65
+ for (i++; i < text.length && text[i] !== '"'; i++) {
66
+ if (text[i] === "\\" && (text[i + 1] === '"' || text[i + 1] === "\\")) i++;
67
+ value += text[i];
68
+ }
69
+ i++;
70
+ out.push({ value, quoted: true });
71
+ } else {
72
+ const start = i;
73
+ while (i < text.length && !/[\s"]/.test(text[i] as string)) i++;
74
+ out.push({ value: text.slice(start, i), quoted: false });
75
+ }
76
+ }
77
+ return out;
78
+ }
79
+
80
+ export function parseFieldInstruction(text: string): FieldInstruction {
81
+ const parts = tokens(text);
82
+ const name = (parts[0]?.value ?? "").toUpperCase();
83
+ const takesValue = GENERAL + (WITH_VALUE[name] ?? "");
84
+ const args: string[] = [];
85
+ const switches = new Map<string, string[]>();
86
+ for (let i = 1; i < parts.length; i++) {
87
+ const { value, quoted } = parts[i] as { value: string; quoted: boolean };
88
+ if (quoted || !value.startsWith("\\") || value.length < 2) {
89
+ args.push(value);
90
+ continue;
91
+ }
92
+ const letter = (value[1] as string).toLowerCase();
93
+ let given = value.slice(2);
94
+ const next = parts[i + 1];
95
+ if (!given && takesValue.includes(letter) && next && (next.quoted || next.value[0] !== "\\")) {
96
+ given = next.value;
97
+ i++;
98
+ }
99
+ switches.set(letter, [...(switches.get(letter) ?? []), given]);
100
+ }
101
+ return { name, args, switches };
102
+ }
103
+
104
+ const MONTHS =
105
+ "January February March April May June July August September October November December".split(
106
+ " ",
107
+ );
108
+ const DAYS = "Sunday Monday Tuesday Wednesday Thursday Friday Saturday".split(" ");
109
+ const pad = (n: number, size = 2) => String(n).padStart(size, "0");
110
+
111
+ /**
112
+ * A date in a Word date picture (`\@`).
113
+ * shortcut: month and day names are English; take the field's language when a document needs it.
114
+ */
115
+ export function formatDatePicture(date: Date, picture: string): string {
116
+ const hours12 = date.getHours() % 12 || 12;
117
+ const parts: Record<string, string> = {
118
+ d: String(date.getDate()),
119
+ dd: pad(date.getDate()),
120
+ ddd: (DAYS[date.getDay()] as string).slice(0, 3),
121
+ dddd: DAYS[date.getDay()] as string,
122
+ M: String(date.getMonth() + 1),
123
+ MM: pad(date.getMonth() + 1),
124
+ MMM: (MONTHS[date.getMonth()] as string).slice(0, 3),
125
+ MMMM: MONTHS[date.getMonth()] as string,
126
+ yy: pad(date.getFullYear() % 100),
127
+ yyyy: String(date.getFullYear()),
128
+ h: String(hours12),
129
+ hh: pad(hours12),
130
+ H: String(date.getHours()),
131
+ HH: pad(date.getHours()),
132
+ m: String(date.getMinutes()),
133
+ mm: pad(date.getMinutes()),
134
+ s: String(date.getSeconds()),
135
+ ss: pad(date.getSeconds()),
136
+ };
137
+ const noon = date.getHours() < 12;
138
+ const pattern = /'([^']*)'|AM\/PM|am\/pm|A\/P|a\/p|d+|M+|y+|h+|H+|m+|s+/g;
139
+ return picture.replace(pattern, (match, quoted) => {
140
+ if (quoted !== undefined) return quoted as string;
141
+ if (match.includes("/")) return (noon ? match.split("/")[0] : match.split("/")[1]) as string;
142
+ return parts[match] ?? match;
143
+ });
144
+ }
145
+
146
+ /**
147
+ * A number in a Word numeric picture (`\#`), as Word 16 writes it: `0` a digit, `#` a digit or a
148
+ * space, `x` a digit, dropping those to its left (after the point: nothing when no digit is left),
149
+ * `,` groups thousands, `+` and `-` the sign where they stand, `'…'` and any other character as
150
+ * they are, `;` sections for negative numbers and zero. Null for what is not followed (a sequence
151
+ * number in backquotes, a second point, a comma in the decimals, a number too large to write out).
152
+ */
153
+ export function formatNumericPicture(value: number, picture: string): string | null {
154
+ const sections: string[] = [""];
155
+ let quoted = false;
156
+ for (const c of picture) {
157
+ if (c === "'") quoted = !quoted;
158
+ if (c === ";" && !quoted) sections.push("");
159
+ else sections[sections.length - 1] += c;
160
+ }
161
+ const negative = value < 0 && sections[1] !== undefined;
162
+ const zero = value === 0 && sections[2] !== undefined;
163
+ const chosen = (negative ? sections[1] : zero ? sections[2] : sections[0]) as string;
164
+ const out: string[] = [];
165
+ const whole: { at: number; slot: string }[] = [];
166
+ const decimals: { at: number; slot: string }[] = [];
167
+ const signs: { at: number; sign: string }[] = [];
168
+ let point = false;
169
+ let grouped = false;
170
+ quoted = false;
171
+ for (const c of chosen) {
172
+ if (c === "'") quoted = !quoted;
173
+ else if (quoted) out.push(c);
174
+ else if (c === "`") return null;
175
+ else if (c === "0" || c === "#" || c === "x") {
176
+ (point ? decimals : whole).push({ at: out.length, slot: c });
177
+ out.push("");
178
+ } else if (c === ".") {
179
+ if (point) return null;
180
+ point = true;
181
+ out.push(".");
182
+ } else if (c === ",") {
183
+ if (point) return null;
184
+ grouped = true;
185
+ } else if (c === "+" || c === "-") {
186
+ signs.push({ at: out.length, sign: c });
187
+ out.push("");
188
+ } else out.push(c);
189
+ }
190
+ const size = Math.abs(value);
191
+ if (!Number.isFinite(size) || size >= 1e21) return null;
192
+ // `toFixed` stops at 100 places; what a picture asks beyond them is zeros.
193
+ const [digits = "", written = ""] = size.toFixed(Math.min(decimals.length, 100)).split(".");
194
+ const fraction = written.padEnd(decimals.length, "0");
195
+ const integer = digits === "0" ? "" : digits;
196
+ const isZero = !integer && !/[1-9]/.test(fraction);
197
+ let d = integer.length - 1;
198
+ let place = 0;
199
+ const grouping = (text: string) =>
200
+ grouped && place > 0 && place % 3 === 0 && text !== " " ? `${text},` : text;
201
+ for (let i = whole.length - 1; i >= 0; i--, place++) {
202
+ const { at, slot } = whole[i] as { at: number; slot: string };
203
+ out[at] = grouping(d >= 0 ? (integer[d--] as string) : slot === "0" ? "0" : " ");
204
+ }
205
+ // Digits beyond the slots go before the first, unless that is an `x`, which drops them.
206
+ const first = whole[0];
207
+ // Digits an `x` dropped take the sign with them.
208
+ const cut = d >= 0 && first?.slot === "x";
209
+ if (first && first.slot !== "x")
210
+ for (; d >= 0; d--, place++) out[first.at] = grouping(integer[d] as string) + out[first.at];
211
+ decimals.forEach(({ at, slot }, i) => {
212
+ const rest = fraction.slice(i);
213
+ const digit = rest[0] as string;
214
+ if (slot === "0" || /[1-9]/.test(rest)) out[at] = digit;
215
+ // A zero shows its first decimal, whatever the slot.
216
+ else if (isZero && i === 0) out[at] = "0";
217
+ else out[at] = slot === "#" ? " " : "";
218
+ });
219
+ for (const { at, sign } of signs)
220
+ out[at] = isZero ? " " : value < 0 ? "-" : sign === "+" ? "+" : " ";
221
+ if (value < 0 && !negative && !isZero && !signs.length && !cut) {
222
+ const start = whole.find(({ slot }) => slot !== "x");
223
+ if (start) out[start.at] = `-${out[start.at]}`;
224
+ }
225
+ return out.join("");
226
+ }
227
+
228
+ const NUMBER_SWITCH: Record<string, string> = {
229
+ ROMAN: "upperRoman",
230
+ roman: "lowerRoman",
231
+ ALPHABETIC: "upperLetter",
232
+ alphabetic: "lowerLetter",
233
+ };
234
+ const NUMBER_SWITCH_ANY_CASE: Record<string, string> = {
235
+ arabic: "decimal",
236
+ arabicdash: "numberInDash",
237
+ ordinal: "ordinal",
238
+ };
239
+ const CASE_SWITCH: Record<string, (text: string) => string> = {
240
+ upper: (text) => text.toUpperCase(),
241
+ lower: (text) => text.toLowerCase(),
242
+ firstcap: (text) => text.charAt(0).toUpperCase() + text.slice(1),
243
+ caps: (text) => text.replace(/(^|\s)(\S)/g, (_, space, c: string) => space + c.toUpperCase()),
244
+ };
245
+ const KEEPS_FORMAT = new Set(["mergeformat", "charformat"]);
246
+
247
+ /** `value` as the `\#` and `\*` switches say; null when a `\*` is not one Foli knows. */
248
+ function formatted(
249
+ value: string | number,
250
+ instruction: FieldInstruction,
251
+ numberFormat?: string,
252
+ ): string | null {
253
+ const parsed = typeof value === "number" ? value : Number(value.trim().replace(/,/g, ""));
254
+ const number = String(value).trim() !== "" && Number.isFinite(parsed) ? parsed : null;
255
+ const picture = instruction.switches.get("#")?.[0];
256
+ let format = numberFormat;
257
+ let hex = false;
258
+ const cases: ((text: string) => string)[] = [];
259
+ for (const name of instruction.switches.get("*") ?? []) {
260
+ const lower = name.toLowerCase();
261
+ if (KEEPS_FORMAT.has(lower)) continue;
262
+ const asNumber = NUMBER_SWITCH[name] ?? NUMBER_SWITCH_ANY_CASE[lower];
263
+ if (asNumber) format = asNumber;
264
+ else if (lower === "hex") hex = true;
265
+ else if (CASE_SWITCH[lower]) cases.push(CASE_SWITCH[lower]);
266
+ else return null;
267
+ }
268
+ let text = String(value);
269
+ if (number !== null && picture !== undefined) {
270
+ const pictured = formatNumericPicture(number, picture);
271
+ if (pictured === null) return null;
272
+ text = pictured;
273
+ } else if (number !== null && hex) text = number.toString(16).toUpperCase();
274
+ else if (number !== null && (format || typeof value === "number"))
275
+ text = formatNumber(number, format);
276
+ for (const apply of cases) text = apply(text);
277
+ return text;
278
+ }
279
+
280
+ // ---------- what an update is given and gives back ----------
281
+
282
+ /** Where a body position is, from a view's pages. */
283
+ export interface FieldPage {
284
+ /** The displayed number (`w:pgNumType` restarts count). */
285
+ number: number;
286
+ /** How many pages its section has. */
287
+ sectionPages: number;
288
+ /** The section's number format (`upperRoman`…). */
289
+ format?: string | undefined;
290
+ }
291
+
292
+ export interface FieldLayout {
293
+ readonly pages: number;
294
+ pageAt(pos: number): FieldPage | null;
295
+ }
296
+
297
+ export interface UpdateFieldsOptions {
298
+ /** Pages: without it page fields keep their results and are reported. */
299
+ layout?: FieldLayout | null | undefined;
300
+ /** Values of `MERGEFIELD`s by name. Without it merge fields are left alone. */
301
+ data?: Readonly<Record<string, unknown>> | undefined;
302
+ /** What `DATE` and `TIME` show (default: now). */
303
+ now?: Date | undefined;
304
+ /**
305
+ * Which fields: those a range of this editor's tree touches (a caret: the field around it, a
306
+ * table of contents for a page number in it), or those a function picks. Default: every field
307
+ * of the body and of the stories.
308
+ */
309
+ only?: { from: number; to: number } | ((field: Field) => boolean) | undefined;
310
+ /** Joins the undo step before it: the second pass of one update. */
311
+ continues?: boolean | undefined;
312
+ }
313
+
314
+ export type FieldSkipReason =
315
+ | "locked"
316
+ | "unknown"
317
+ | "no-layout"
318
+ | "no-data"
319
+ | "missing-bookmark"
320
+ | "unsupported-switch"
321
+ | "self-reference"
322
+ | "failed"
323
+ | "untrackable";
324
+
325
+ /** A field left as it was, and why. */
326
+ export interface FieldSkip {
327
+ instruction: string;
328
+ /** The story it is in; null: the body. */
329
+ story: string | null;
330
+ reason: FieldSkipReason;
331
+ /** The bookmark, merge field or switch concerned. */
332
+ detail?: string;
333
+ }
334
+
335
+ export interface FieldsReport {
336
+ /** Fields whose result changed. */
337
+ updated: number;
338
+ /** Fields worked out to the result they had. */
339
+ unchanged: number;
340
+ /** Tables of contents built again. */
341
+ rebuilt: number;
342
+ skipped: FieldSkip[];
343
+ }
344
+
345
+ const emptyReport = (): FieldsReport => ({ updated: 0, unchanged: 0, rebuilt: 0, skipped: [] });
346
+
347
+ // ---------- helpers over a tree ----------
348
+
349
+ /** @internal */
350
+ export interface Bookmark {
351
+ name: string;
352
+ /** After its start marker, before its end marker. */
353
+ from: number;
354
+ to: number;
355
+ }
356
+
357
+ const knownBookmarks = new WeakMap<Node, Map<string, Bookmark>>();
358
+
359
+ /**
360
+ * @internal A tree's bookmarks by name in lower case: Word's names do not differ by case alone.
361
+ */
362
+ export function bookmarksIn(tree: Node): Map<string, Bookmark> {
363
+ const known = knownBookmarks.get(tree);
364
+ if (known) return known;
365
+ const starts = new Map<unknown, { name: string; from: number }>();
366
+ const out = new Map<string, Bookmark>();
367
+ tree.descendants((node, pos) => {
368
+ if (node.type.name === "bookmarkStart")
369
+ starts.set(node.attrs.id, { name: String(node.attrs.name), from: pos + 1 });
370
+ else if (node.type.name === "bookmarkEnd") {
371
+ const start = starts.get(node.attrs.id);
372
+ const key = start?.name.toLowerCase();
373
+ if (start && key !== undefined && !out.has(key)) out.set(key, { ...start, to: pos });
374
+ }
375
+ return !node.isInline;
376
+ });
377
+ knownBookmarks.set(tree, out);
378
+ return out;
379
+ }
380
+
381
+ const bookmarkNamed = (tree: Node, name: string) => bookmarksIn(tree).get(name.toLowerCase());
382
+
383
+ /** A bookmark name for a field's code, quoted when it needs to be. */
384
+ const quotedName = (name: string) =>
385
+ /[\s"\\]/.test(name) ? `"${name.replace(/["\\]/g, "\\$&")}"` : name;
386
+
387
+ /** Makes names `prefix` + a number that no bookmark of `tree` has. */
388
+ function bookmarkNames(tree: Node, prefix: string): () => string {
389
+ const taken = bookmarksIn(tree);
390
+ let serial = 200_000_000;
391
+ for (const { name } of taken.values()) {
392
+ const number = name.toLowerCase().startsWith(prefix.toLowerCase())
393
+ ? Number(name.slice(prefix.length))
394
+ : 0;
395
+ // One too large to count from is only a name to keep clear of.
396
+ if (Number.isSafeInteger(number + 1 + taken.size)) serial = Math.max(serial, number);
397
+ }
398
+ return () => {
399
+ let name: string;
400
+ do name = `${prefix}${++serial}`;
401
+ while (taken.has(name.toLowerCase()));
402
+ return name;
403
+ };
404
+ }
405
+
406
+ const knownCodes = new WeakMap<Node, [number, number][]>();
407
+
408
+ /** Whether `pos` is in a field's code range (what never shows as a result). */
409
+ function inFieldCode(tree: Node, pos: number): boolean {
410
+ let ranges = knownCodes.get(tree);
411
+ if (!ranges) {
412
+ ranges = [];
413
+ for (const { from, codeEnd } of fieldsIn(tree)) {
414
+ const last = ranges[ranges.length - 1];
415
+ if (last && from < last[1]) last[1] = Math.max(last[1], codeEnd);
416
+ else ranges.push([from, codeEnd]);
417
+ }
418
+ knownCodes.set(tree, ranges);
419
+ }
420
+ let low = 0;
421
+ let high = ranges.length;
422
+ while (low < high) {
423
+ const middle = (low + high) >> 1;
424
+ if ((ranges[middle] as [number, number])[1] <= pos) low = middle + 1;
425
+ else high = middle;
426
+ }
427
+ const found = ranges[low];
428
+ return !!found && found[0] <= pos;
429
+ }
430
+
431
+ interface ParagraphAt {
432
+ node: Node;
433
+ pos: number;
434
+ }
435
+
436
+ /** @internal */
437
+ export function paragraphsOf(tree: Node): ParagraphAt[] {
438
+ const out: ParagraphAt[] = [];
439
+ tree.descendants((node, pos) => {
440
+ if (node.type.name === "paragraph") out.push({ node, pos });
441
+ return !node.isTextblock;
442
+ });
443
+ return out;
444
+ }
445
+
446
+ const REVIEW = new Set(["insertion", "deletion", "formatChange"]);
447
+ /** @internal */
448
+ export const withoutReview = (marks: readonly Mark[]) =>
449
+ marks.filter((m) => !REVIEW.has(m.type.name));
450
+ const isGone = (node: Node) => node.marks.some((m) => m.type.name === "deletion");
451
+
452
+ /** @internal Text as inline nodes: tabs and line feeds become their nodes. */
453
+ export function inlineText(schema: Schema, text: string, marks: readonly Mark[]): Node[] {
454
+ const nodes = schema.nodes as Record<string, NodeType>;
455
+ const out: Node[] = [];
456
+ for (const part of text.split(/(\t|\r\n|\r|\n)/)) {
457
+ if (!part) continue;
458
+ if (part === "\t") out.push((nodes.tab as NodeType).create(null, null, marks));
459
+ else if (/^[\r\n]/.test(part))
460
+ out.push((nodes.hardBreak as NodeType).create(null, null, marks));
461
+ else out.push(schema.text(part, marks));
462
+ }
463
+ return out;
464
+ }
465
+
466
+ /** The marks a new result takes: the old result's with `\* MERGEFORMAT`, else its code's. */
467
+ function resultMarks(field: Field, instruction: FieldInstruction): readonly Mark[] {
468
+ const merge = (instruction.switches.get("*") ?? []).some(
469
+ (name) => name.toLowerCase() === "mergeformat",
470
+ );
471
+ return withoutReview((merge ? field.resultMarks : null) ?? field.codeMarks ?? []);
472
+ }
473
+
474
+ /**
475
+ * What a bookmark holds, as inline nodes. Field codes and markers stay behind.
476
+ * shortcut: a paragraph end inside the bookmark becomes a line break, where Word's result has the
477
+ * paragraph; make it a slice when a document needs it.
478
+ */
479
+ export function bookmarkContent(tree: Node, mark: Bookmark): Node[] {
480
+ const schema = tree.type.schema;
481
+ const out: Node[] = [];
482
+ const hardBreak = schema.nodes.hardBreak as NodeType;
483
+ let paragraph: Node | null = null;
484
+ tree.nodesBetween(mark.from, mark.to, (node, pos, parent) => {
485
+ if (!node.isInline) return true;
486
+ if (paragraph && parent !== paragraph) out.push(hardBreak.create());
487
+ paragraph = parent;
488
+ if (isGone(node) || inFieldCode(tree, pos)) return false;
489
+ if (node.isText) {
490
+ const from = Math.max(mark.from - pos, 0);
491
+ const to = Math.min(mark.to - pos, node.nodeSize);
492
+ if (to > from) out.push(node.cut(from, to).mark(withoutLinks(node.marks)));
493
+ } else if (["tab", "hardBreak", "picture"].includes(node.type.name))
494
+ out.push(node.mark(withoutLinks(node.marks)));
495
+ return false;
496
+ });
497
+ return out;
498
+ }
499
+ const withoutLinks = (marks: readonly Mark[]) =>
500
+ withoutReview(marks).filter((m) => m.type.name !== "link");
501
+
502
+ /** The list numbers of a tree's paragraphs, and how a paragraph's number reads in context. */
503
+ class ListNumbers {
504
+ private readonly paragraphs: ParagraphAt[];
505
+ private readonly markers: (ListMarker | null)[];
506
+ /** The numbered paragraphs of each list, in order. */
507
+ private readonly lists = new Map<number, number[]>();
508
+
509
+ constructor(tree: Node, word: WordContext) {
510
+ this.paragraphs = paragraphsOf(tree);
511
+ this.markers = word.resolver.markers(this.paragraphs.map((p) => p.node.attrs));
512
+ this.markers.forEach((marker, i) => {
513
+ if (!marker) return;
514
+ const list = this.lists.get(marker.instance);
515
+ if (list) list.push(i);
516
+ else this.lists.set(marker.instance, [i]);
517
+ });
518
+ }
519
+
520
+ /** The last paragraph of list `instance` at or before paragraph `index` (-1: none). */
521
+ private lastOfList(instance: number, index: number): number {
522
+ const list = this.lists.get(instance) ?? [];
523
+ let low = 0;
524
+ let high = list.length;
525
+ while (low < high) {
526
+ const middle = (low + high) >> 1;
527
+ if ((list[middle] as number) <= index) low = middle + 1;
528
+ else high = middle;
529
+ }
530
+ return list[low - 1] ?? -1;
531
+ }
532
+
533
+ private indexAt(pos: number): number {
534
+ let low = 0;
535
+ let high = this.paragraphs.length;
536
+ while (low < high) {
537
+ const middle = (low + high) >> 1;
538
+ if ((this.paragraphs[middle] as ParagraphAt).pos <= pos) low = middle + 1;
539
+ else high = middle;
540
+ }
541
+ const found = this.paragraphs[low - 1];
542
+ return found && pos <= found.pos + found.node.nodeSize ? low - 1 : -1;
543
+ }
544
+
545
+ marker(pos: number): ListMarker | null {
546
+ return this.markers[this.indexAt(pos)] ?? null;
547
+ }
548
+
549
+ /** The numbered paragraphs above it in its list, then itself: indexes, outermost first. */
550
+ private chain(index: number): number[] {
551
+ const out = [index];
552
+ let level = this.markers[index]?.level ?? 0;
553
+ const list = this.markers[index]?.abstract;
554
+ for (let i = index - 1; i >= 0 && level > 0; i--) {
555
+ const marker = this.markers[i];
556
+ if (marker?.abstract === list && marker && marker.level < level) {
557
+ out.unshift(i);
558
+ level = marker.level;
559
+ }
560
+ }
561
+ return out;
562
+ }
563
+
564
+ /**
565
+ * `\n`: alone; `\w`: in full; `\r`: what differs from where its list stands at `from`, the
566
+ * last paragraph of that list there, other lists between counting for nothing. `plain`
567
+ * (`\t`): without the words of the number's format. As Word writes them, only the last
568
+ * trailing period goes.
569
+ */
570
+ number(pos: number, mode: "n" | "w" | "r", from: number, plain: boolean): string {
571
+ const index = this.indexAt(pos);
572
+ const marker = this.markers[index];
573
+ if (!marker) return "0";
574
+ const shown = (i: number) => {
575
+ const at = this.markers[i] as ListMarker;
576
+ return plain ? at.plain : at.text;
577
+ };
578
+ let chain = mode === "n" ? [index] : this.chain(index);
579
+ if (mode === "r") {
580
+ const at = this.lastOfList(marker.instance, this.indexAt(from));
581
+ const here = at < 0 ? [] : this.chain(at);
582
+ let shared = 0;
583
+ while (shared < chain.length - 1 && chain[shared] === here[shared]) shared++;
584
+ chain = chain.slice(shared);
585
+ }
586
+ const parts: string[] = [];
587
+ for (const i of chain) {
588
+ const text = shown(i);
589
+ const previous = parts[parts.length - 1]?.replace(/\.+$/, "");
590
+ // "2.3" under "2." already holds it.
591
+ if (previous && text.startsWith(previous) && !/^\w/.test(text.slice(previous.length)))
592
+ parts[parts.length - 1] = text;
593
+ else parts.push(text);
594
+ }
595
+ return parts.join("").replace(/\.+$/, "");
596
+ }
597
+ }
598
+
599
+ // ---------- one tree ----------
600
+
601
+ interface Run {
602
+ /** The tree's state and its transaction. */
603
+ state: EditorState;
604
+ tr: Transaction;
605
+ word: WordContext;
606
+ story: string | null;
607
+ /** The body's transaction: bookmarks and pages are the body's. */
608
+ bodyTr: Transaction;
609
+ options: UpdateFieldsOptions;
610
+ report: FieldsReport;
611
+ /** The envelope as new styles leave it. */
612
+ envelope: WordEnvelope;
613
+ /** List numbers, per tree worked on. */
614
+ numbers: Map<Node, ListNumbers>;
615
+ /** Whether tables of contents are built (not when tracking cannot record that). */
616
+ contents: boolean;
617
+ /** Picks fields of this tree. */
618
+ picked(field: Field): boolean;
619
+ }
620
+
621
+ const PAGE_FIELDS = new Set(["PAGE", "NUMPAGES", "SECTIONPAGES"]);
622
+ const VALUE_FIELDS = new Set([...PAGE_FIELDS, "DATE", "TIME", "SEQ", "MERGEFIELD"]);
623
+ /** The switches Foli honours, per field (`\*`, `\#` and `\@` go through `formatted`). */
624
+ const KNOWN_SWITCHES: Record<string, string> = {
625
+ PAGE: "",
626
+ NUMPAGES: "",
627
+ SECTIONPAGES: "",
628
+ DATE: "",
629
+ TIME: "",
630
+ SEQ: "cnrsh",
631
+ MERGEFIELD: "bf",
632
+ REF: "hnrwpt",
633
+ PAGEREF: "hp",
634
+ TOC: "ohzutnbpwx",
635
+ };
636
+
637
+ /** A position of the tree's transaction, in the document the layout was made from. */
638
+ function originalPos(tr: Transaction, pos: number): number {
639
+ let out = pos;
640
+ for (let i = tr.mapping.maps.length - 1; i >= 0; i--)
641
+ out = (tr.mapping.maps[i] as (typeof tr.mapping.maps)[number]).invert().map(out, 1);
642
+ return out;
643
+ }
644
+
645
+ const skip = (run: Run, field: Field, reason: FieldSkipReason, detail?: string) => {
646
+ run.report.skipped.push({
647
+ instruction: field.instruction,
648
+ story: run.story,
649
+ reason,
650
+ ...(detail ? { detail } : {}),
651
+ });
652
+ };
653
+
654
+ /** The page of a body position as of the layout, or null (reported when there is no layout). */
655
+ function pageOf(run: Run, field: Field, bodyPos: number): FieldPage | null {
656
+ const { layout } = run.options;
657
+ if (!layout) {
658
+ skip(run, field, "no-layout");
659
+ return null;
660
+ }
661
+ const page = layout.pageAt(originalPos(run.bodyTr, bodyPos));
662
+ if (!page) skip(run, field, "no-layout");
663
+ return page;
664
+ }
665
+
666
+ function headingsOf(tree: Node, word: WordContext): { pos: number; level: number }[] {
667
+ return paragraphsOf(tree).flatMap(({ node, pos }) => {
668
+ const level = headingLevel(word, node);
669
+ return level === null ? [] : [{ pos, level }];
670
+ });
671
+ }
672
+
673
+ /** @internal A paragraph's level from its heading style's name. */
674
+ export function headingLevel(word: WordContext, paragraph: Node): number | null {
675
+ const id = word.resolver.paragraph(paragraph.attrs).paragraph.style;
676
+ const name = word.envelope.styles.find((s) => s.id === id)?.name ?? "";
677
+ const match = /^heading ([1-9])$/i.exec(name);
678
+ return match ? Number(match[1]) : null;
679
+ }
680
+
681
+ /** What each `SEQ` of `fields` counts to, in document order. */
682
+ function sequenceValues(run: Run, fields: readonly Field[]): Map<Field, number> {
683
+ const tree = run.tr.doc;
684
+ const values = new Map<Field, number>();
685
+ const counters = new Map<string, number>();
686
+ const seen = new Map<string, { pos: number; value: number }[]>();
687
+ const headings = headingsOf(tree, run.word);
688
+ for (const field of fields) {
689
+ if (field.name !== "SEQ" || field.deleted) continue;
690
+ const { args, switches } = parseFieldInstruction(field.instruction);
691
+ const id = (args[0] ?? "").toLowerCase();
692
+ const list = seen.get(id) ?? [];
693
+ seen.set(id, list);
694
+ let value = counters.get(id) ?? 0;
695
+ const resetLevel = Number(switches.get("s")?.[0]);
696
+ // A heading since this sequence's last number starts it again.
697
+ const last = list[list.length - 1]?.pos ?? 0;
698
+ if (
699
+ resetLevel &&
700
+ headings.some((h) => h.pos >= last && h.pos < field.from && h.level <= resetLevel)
701
+ )
702
+ value = 0;
703
+ const target = args[1] ? bookmarkNamed(tree, args[1]) : undefined;
704
+ // Of `\c`, `\n` and `\r`, the first written counts.
705
+ const action = [...switches.keys()].find((letter) => "cnr".includes(letter));
706
+ const restart = Number(switches.get("r")?.[0]);
707
+ if (target) value = [...list].reverse().find((s) => s.pos < target.from)?.value ?? 0;
708
+ else if (action === "r" && Number.isFinite(restart)) value = restart;
709
+ else if (action !== "c") value++;
710
+ if (!target) counters.set(id, value);
711
+ list.push({ pos: field.from, value });
712
+ values.set(field, value);
713
+ }
714
+ return values;
715
+ }
716
+
717
+ interface Worked {
718
+ text: string;
719
+ /** The result, when it is more than text in the field's own format. */
720
+ nodes?: Node[];
721
+ }
722
+
723
+ const dataValue = (data: Readonly<Record<string, unknown>>, name: string) => {
724
+ if (Object.hasOwn(data, name)) return { found: true, value: data[name] };
725
+ const lower = name.toLowerCase();
726
+ const key = Object.keys(data).find((k) => k.toLowerCase() === lower);
727
+ return key === undefined ? { found: false, value: undefined } : { found: true, value: data[key] };
728
+ };
729
+
730
+ /** Where the field is against `target`, as Word's `\p` says it. */
731
+ const direction = (field: Field, target: Bookmark) =>
732
+ field.from < target.from ? "below" : "above";
733
+
734
+ /** The bookmark `name`, in this tree or else in the body; `inBody` when it is the body's. */
735
+ function findBookmark(run: Run, name: string) {
736
+ const own = bookmarkNamed(run.tr.doc, name);
737
+ if (own) return { mark: own, tree: run.tr.doc, inBody: run.story === null };
738
+ const body = run.story === null ? undefined : bookmarkNamed(run.bodyTr.doc, name);
739
+ return body ? { mark: body, tree: run.bodyTr.doc, inBody: true } : null;
740
+ }
741
+
742
+ /** The bookmark a field shows the text of, if it is one that does. */
743
+ function textTarget(tree: Node, field: Field): Bookmark | undefined {
744
+ const { name, args, switches } = parseFieldInstruction(field.instruction);
745
+ if (VALUE_FIELDS.has(name) || name === "PAGEREF" || name === "TOC") return undefined;
746
+ if (switches.has("n") || switches.has("r") || switches.has("w") || switches.has("p"))
747
+ return undefined;
748
+ const target = name === "REF" ? args[0] : tokens(field.instruction)[0]?.value;
749
+ return target ? bookmarkNamed(tree, target) : undefined;
750
+ }
751
+
752
+ /** Whether what `mark` holds comes, through references, from `field` itself. */
753
+ function refersBack(tree: Node, field: Field, mark: Bookmark): boolean {
754
+ const fields = fieldsIn(tree);
755
+ const seen = new Set([mark]);
756
+ const waiting = [mark];
757
+ for (let at = waiting.pop(); at; at = waiting.pop()) {
758
+ if (at.from <= field.from && field.to <= at.to) return true;
759
+ let low = 0;
760
+ let high = fields.length;
761
+ while (low < high) {
762
+ const middle = (low + high) >> 1;
763
+ if ((fields[middle] as Field).from < at.from) low = middle + 1;
764
+ else high = middle;
765
+ }
766
+ for (let i = low; i < fields.length && (fields[i] as Field).from < at.to; i++) {
767
+ const next = textTarget(tree, fields[i] as Field);
768
+ if (next && !seen.has(next)) {
769
+ seen.add(next);
770
+ waiting.push(next);
771
+ }
772
+ }
773
+ }
774
+ return false;
775
+ }
776
+
777
+ /** What `field` should show; null when it keeps its result (the reason reported). */
778
+ function work(run: Run, field: Field, sequence: Map<Field, number>): Worked | null {
779
+ const instruction = parseFieldInstruction(field.instruction);
780
+ const { name, args, switches } = instruction;
781
+ // Any other word is a bookmark's name standing for `REF`, or a field Foli does not know.
782
+ const implicit = !VALUE_FIELDS.has(name) && name !== "REF" && name !== "PAGEREF";
783
+ const bookmark = implicit ? tokens(field.instruction)[0]?.value : args[0];
784
+ const found = !VALUE_FIELDS.has(name) && bookmark ? findBookmark(run, bookmark) : null;
785
+ if (implicit && !found) {
786
+ skip(run, field, "unknown");
787
+ return null;
788
+ }
789
+ const allowed = KNOWN_SWITCHES[implicit ? "REF" : name] ?? "";
790
+ for (const letter of switches.keys())
791
+ if (!GENERAL.includes(letter) && !allowed.includes(letter)) {
792
+ skip(run, field, "unsupported-switch", `\\${letter}`);
793
+ return null;
794
+ }
795
+ const done = (value: string | number, numberFormat?: string): Worked | null => {
796
+ const text = formatted(value, instruction, numberFormat);
797
+ if (text === null) skip(run, field, "unsupported-switch", "\\*");
798
+ return text === null ? null : { text };
799
+ };
800
+ const { layout } = run.options;
801
+ switch (name) {
802
+ case "PAGE":
803
+ case "SECTIONPAGES": {
804
+ const page = pageOf(run, field, field.from);
805
+ if (!page) return null;
806
+ return name === "PAGE" ? done(page.number, page.format) : done(page.sectionPages);
807
+ }
808
+ case "NUMPAGES":
809
+ if (!layout) skip(run, field, "no-layout");
810
+ return layout ? done(layout.pages) : null;
811
+ case "DATE":
812
+ case "TIME": {
813
+ const picture = switches.get("@")?.[0] ?? (name === "DATE" ? "M/d/yyyy" : "h:mm AM/PM");
814
+ return done(formatDatePicture(run.options.now ?? new Date(), picture));
815
+ }
816
+ case "SEQ": {
817
+ // Hidden, unless a format asks for it to show.
818
+ const shows = (switches.get("*") ?? []).some((s) => !KEEPS_FORMAT.has(s.toLowerCase()));
819
+ return switches.has("h") && !shows ? { text: "" } : done(sequence.get(field) ?? 0);
820
+ }
821
+ case "MERGEFIELD": {
822
+ const { data } = run.options;
823
+ if (!data) return null;
824
+ const key = args[0] ?? "";
825
+ const { found, value } = dataValue(data, key);
826
+ if (!found) {
827
+ skip(run, field, "no-data", key);
828
+ return null;
829
+ }
830
+ let shown: string | number =
831
+ value === null || value === undefined ? "" : (value as string | number);
832
+ const picture = switches.get("@")?.[0];
833
+ if (value instanceof Date)
834
+ shown = picture ? formatDatePicture(value, picture) : value.toISOString();
835
+ else if (picture && typeof value === "string" && !Number.isNaN(Date.parse(value)))
836
+ shown = formatDatePicture(new Date(value), picture);
837
+ const text = formatted(typeof shown === "number" ? shown : String(shown), instruction);
838
+ if (text === null) {
839
+ skip(run, field, "unsupported-switch", "\\*");
840
+ return null;
841
+ }
842
+ // Word's text before and after a value, only when there is one.
843
+ const before = switches.get("b")?.[0] ?? "";
844
+ const after = switches.get("f")?.[0] ?? "";
845
+ return { text: text ? `${before}${text}${after}` : "" };
846
+ }
847
+ default:
848
+ }
849
+ if (!found) {
850
+ skip(run, field, "missing-bookmark", bookmark);
851
+ return null;
852
+ }
853
+ const { mark, tree, inBody } = found;
854
+ const place = switches.has("p") && tree === run.tr.doc ? direction(field, mark) : null;
855
+ if (name === "PAGEREF") {
856
+ if (!inBody) {
857
+ skip(run, field, "no-layout", bookmark);
858
+ return null;
859
+ }
860
+ const page = pageOf(run, field, mark.from);
861
+ if (!page) return null;
862
+ const here =
863
+ place && run.story === null && layout
864
+ ? layout.pageAt(originalPos(run.bodyTr, field.from))
865
+ : null;
866
+ if (place && here?.number === page.number) return { text: place };
867
+ const number = done(page.number, page.format);
868
+ return number && switches.has("p") ? { text: `on page ${number.text}` } : number;
869
+ }
870
+ const mode = (["n", "r", "w"] as const).find((letter) => switches.has(letter));
871
+ if (mode) {
872
+ let numbers = run.numbers.get(tree);
873
+ if (!numbers) {
874
+ numbers = new ListNumbers(tree, run.word);
875
+ run.numbers.set(tree, numbers);
876
+ }
877
+ const text = numbers.number(mark.from, mode, field.from, switches.has("t"));
878
+ return done(place ? `${text} ${place}` : text);
879
+ }
880
+ if (place) return done(place);
881
+ // Word refuses it too ("not a valid bookmark self-reference"): it would grow at every update.
882
+ if (tree === run.tr.doc && refersBack(tree, field, mark)) {
883
+ skip(run, field, "self-reference", bookmark);
884
+ return null;
885
+ }
886
+ const nodes = bookmarkContent(tree, mark);
887
+ const text = nodes.map((n) => (n.isText ? n.text : n.type.name === "tab" ? "\t" : "\n")).join("");
888
+ const cased = done(text);
889
+ if (!cased) return null;
890
+ // The bookmark's own formatting, unless a switch gives the field's.
891
+ const own = !(switches.get("*") ?? []).some((s) => KEEPS_FORMAT.has(s.toLowerCase()));
892
+ return cased.text === text && own ? { text, nodes } : cased;
893
+ }
894
+
895
+ function putResult(run: Run, field: Field, nodes: readonly Node[]): void {
896
+ const { tr } = run;
897
+ if (field.separator !== null) {
898
+ tr.replace(field.resultFrom, field.resultTo, new Slice(Fragment.fromArray([...nodes]), 0, 0));
899
+ return;
900
+ }
901
+ const marks = resultMarks(field, parseFieldInstruction(field.instruction));
902
+ const separator = (tr.doc.type.schema.nodes.fieldSeparator as NodeType).create(null, null, marks);
903
+ tr.insert(field.to - 1, [separator, ...nodes]);
904
+ }
905
+
906
+ /**
907
+ * Puts many results into their paragraphs at once, the fields from the last to the first. Untracked,
908
+ * those of one paragraph go in as one step: a step per field costs the paragraph's length each.
909
+ */
910
+ function putResults(run: Run, jobs: readonly (readonly [Field, Node[]])[]): void {
911
+ const { tr } = run;
912
+ const descending = [...jobs].reverse();
913
+ if (jobs.length < 32 || trackState(run.state)?.on) {
914
+ for (const [field, nodes] of descending) putResult(run, field, nodes);
915
+ return;
916
+ }
917
+ const paragraphs = paragraphsOf(tr.doc);
918
+ const paragraphAt = (pos: number): ParagraphAt | undefined => {
919
+ let low = 0;
920
+ let high = paragraphs.length;
921
+ while (low < high) {
922
+ const middle = (low + high) >> 1;
923
+ if ((paragraphs[middle] as ParagraphAt).pos < pos) low = middle + 1;
924
+ else high = middle;
925
+ }
926
+ return paragraphs[low - 1];
927
+ };
928
+ let group: (readonly [Field, Node[]])[] = [];
929
+ let holder: ParagraphAt | undefined;
930
+ const flush = () => {
931
+ const owner = holder;
932
+ const [first] = group;
933
+ const last = group[group.length - 1];
934
+ if (owner && first && last) {
935
+ const ascending = [...group].reverse();
936
+ const from = (last[0] as Field).resultFrom;
937
+ const to = (first[0] as Field).resultTo;
938
+ const kids: { at: number; node: Node }[] = [];
939
+ owner.node.forEach((node, offset) => {
940
+ const at = owner.pos + 1 + offset;
941
+ if (at >= from && at < to) kids.push({ at, node });
942
+ });
943
+ const content: Node[] = [];
944
+ let i = 0;
945
+ for (const [field, nodes] of ascending) {
946
+ while (kids[i] && (kids[i] as { at: number }).at < field.resultFrom)
947
+ content.push((kids[i++] as { node: Node }).node);
948
+ content.push(...nodes);
949
+ while (kids[i] && (kids[i] as { at: number }).at < field.resultTo) i++;
950
+ }
951
+ tr.replace(from, to, new Slice(Fragment.fromArray(content), 0, 0));
952
+ }
953
+ group = [];
954
+ holder = undefined;
955
+ };
956
+ for (const job of descending) {
957
+ const [field, nodes] = job;
958
+ const paragraph = paragraphAt(field.from);
959
+ const inside =
960
+ field.separator !== null &&
961
+ !!paragraph &&
962
+ field.resultTo < paragraph.pos + paragraph.node.nodeSize;
963
+ if (!inside) {
964
+ flush();
965
+ putResult(run, field, nodes);
966
+ } else {
967
+ if (paragraph !== holder) flush();
968
+ holder = paragraph;
969
+ group.push(job);
970
+ }
971
+ }
972
+ flush();
973
+ }
974
+
975
+ const lockedAbove = new WeakMap<Field, boolean>();
976
+
977
+ /** Whether the field or one around it is locked (each field walked once). */
978
+ function lockedChain(field: Field): boolean {
979
+ const path: Field[] = [];
980
+ let locked = false;
981
+ for (let at: Field | null = field; at; at = at.parent) {
982
+ const known = lockedAbove.get(at);
983
+ if (known !== undefined) {
984
+ locked = known;
985
+ break;
986
+ }
987
+ path.push(at);
988
+ if (at.locked) {
989
+ locked = true;
990
+ break;
991
+ }
992
+ }
993
+ for (const at of path) lockedAbove.set(at, locked);
994
+ return locked;
995
+ }
996
+
997
+ /** The tables of contents of a tree, those inside another left to it. */
998
+ function contentsIn(tree: Node): Field[] {
999
+ return fieldsIn(tree).filter((field) => {
1000
+ if (field.name !== "TOC") return false;
1001
+ for (let at = field.parent; at; at = at.parent) if (at.name === "TOC") return false;
1002
+ return true;
1003
+ });
1004
+ }
1005
+
1006
+ /** Which stage takes a field: nested in a code first, then values, references, contents. */
1007
+ const stageOf = (field: Field) =>
1008
+ field.inCode ? 0 : VALUE_FIELDS.has(field.name) ? 1 : field.name === "TOC" ? 3 : 2;
1009
+
1010
+ /** Updates the fields of a tree in `run.tr`. */
1011
+ function updateTree(run: Run): void {
1012
+ const { tr, report, story } = run;
1013
+ const schema = tr.doc.type.schema;
1014
+ // Every field not updated is reported once, at the first stage that sees it.
1015
+ const reported = new Set<number>();
1016
+ const usable = (field: Field): boolean => {
1017
+ if (field.deleted || !run.picked(field)) return false;
1018
+ if (story !== null && PAGE_FIELDS.has(field.name)) return false;
1019
+ if (!lockedChain(field)) return true;
1020
+ const at = originalPos(tr, field.from);
1021
+ if (!reported.has(at)) skip(run, field, "locked");
1022
+ reported.add(at);
1023
+ return false;
1024
+ };
1025
+ for (const stage of [0, 1, 2]) {
1026
+ const fields = fieldsIn(tr.doc);
1027
+ if (!fields.length) return;
1028
+ const sequence = sequenceValues(run, fields);
1029
+ const jobs = new Map<Field, Node[]>();
1030
+ for (const field of fields) {
1031
+ if (stageOf(field) !== stage || !usable(field)) continue;
1032
+ // One field that cannot be worked out never stops the others, or a print.
1033
+ try {
1034
+ const worked = work(run, field, sequence);
1035
+ if (!worked) continue;
1036
+ if (worked.text === field.result) {
1037
+ report.unchanged++;
1038
+ continue;
1039
+ }
1040
+ const marks = resultMarks(field, parseFieldInstruction(field.instruction));
1041
+ jobs.set(field, worked.nodes ?? inlineText(schema, worked.text, marks));
1042
+ report.updated++;
1043
+ } catch (error) {
1044
+ skip(run, field, "failed", (error as Error).message);
1045
+ }
1046
+ }
1047
+ // A result replaced takes the fields inside it along.
1048
+ const covered = new Set<Field>();
1049
+ for (const field of fields)
1050
+ if (field.parent && (jobs.has(field.parent) || covered.has(field.parent))) covered.add(field);
1051
+ putResults(
1052
+ run,
1053
+ [...jobs].filter(([field]) => !covered.has(field)),
1054
+ );
1055
+ }
1056
+ if (story !== null) {
1057
+ for (const field of fieldsIn(tr.doc))
1058
+ if (field.name === "TOC" && usable(field)) skip(run, field, "unknown", "in a story");
1059
+ return;
1060
+ }
1061
+ const count = contentsIn(tr.doc).length;
1062
+ for (let i = 0; i < count; i++) {
1063
+ const field = contentsIn(tr.doc)[i];
1064
+ if (!field || !usable(field)) continue;
1065
+ if (!run.contents) {
1066
+ skip(run, field, "untrackable");
1067
+ continue;
1068
+ }
1069
+ try {
1070
+ rebuildContents(run, i);
1071
+ } catch (error) {
1072
+ skip(run, field, "failed", (error as Error).message);
1073
+ }
1074
+ }
1075
+ }
1076
+
1077
+ // ---------- tables of contents ----------
1078
+
1079
+ interface Entry {
1080
+ /** The stretch of its paragraph it comes from. */
1081
+ from: number;
1082
+ to: number;
1083
+ level: number;
1084
+ title: string;
1085
+ number: string;
1086
+ /** What follows the number: Word's tab, or a space. */
1087
+ numberGap: string;
1088
+ bookmark: string | null;
1089
+ }
1090
+
1091
+ const knownContents = new WeakMap<Node, Field[]>();
1092
+
1093
+ /** Every table of contents of a tree, those inside others too. */
1094
+ function everyContents(tree: Node): Field[] {
1095
+ let found = knownContents.get(tree);
1096
+ if (!found) {
1097
+ found = fieldsIn(tree).filter((f) => f.name === "TOC");
1098
+ knownContents.set(tree, found);
1099
+ }
1100
+ return found;
1101
+ }
1102
+
1103
+ /** A stretch of a paragraph that makes an entry. */
1104
+ interface EntryPart {
1105
+ title: string;
1106
+ from: number;
1107
+ to: number;
1108
+ bookmark: string | null;
1109
+ }
1110
+
1111
+ /**
1112
+ * What a paragraph gives entries from: its text without codes, deleted or hidden text, spaces
1113
+ * around it dropped and line breaks as spaces. A table of contents standing in it divides it: Word
1114
+ * lists what is before and after as entries of their own.
1115
+ */
1116
+ function entryParts(tree: Node, word: WordContext, { node, pos }: ParagraphAt): EntryPart[] {
1117
+ const { run } = word.resolver.paragraph(node.attrs);
1118
+ const contents = everyContents(tree);
1119
+ const parts: EntryPart[] = [];
1120
+ let part: EntryPart | null = null;
1121
+ node.forEach((child, offset) => {
1122
+ const at = pos + 1 + offset;
1123
+ if (contents.some((f) => at >= f.from && at < f.to)) {
1124
+ part = null;
1125
+ return;
1126
+ }
1127
+ if (!part) {
1128
+ part = { title: "", from: at, to: at, bookmark: null };
1129
+ parts.push(part);
1130
+ }
1131
+ part.to = at + child.nodeSize;
1132
+ if (child.type.name === "bookmarkStart" && TOC_BOOKMARK.test(String(child.attrs.name)))
1133
+ part.bookmark ??= String(child.attrs.name);
1134
+ if (isGone(child) || inFieldCode(tree, at)) return;
1135
+ if (
1136
+ word.resolver.run(
1137
+ run,
1138
+ child.marks.map((m) => m.toJSON()),
1139
+ ).hidden
1140
+ )
1141
+ return;
1142
+ if (child.isText) part.title += child.text;
1143
+ else if (child.type.name === "tab") part.title += "\t";
1144
+ else if (child.type.name === "hardBreak") part.title += " ";
1145
+ });
1146
+ return parts
1147
+ .map((found) => ({ ...found, title: found.title.trim() }))
1148
+ .filter((found) => found.title);
1149
+ }
1150
+
1151
+ /** A paragraph's text as a heading to refer to. */
1152
+ /** @internal A paragraph's text as its entry. */
1153
+ export const entryTitle = (tree: Node, word: WordContext, paragraph: ParagraphAt) =>
1154
+ entryParts(tree, word, paragraph)
1155
+ .map((part) => part.title)
1156
+ .join(" ");
1157
+
1158
+ const TOC_BOOKMARK = /^_Toc\d+$/;
1159
+
1160
+ /** The range of levels `\o` (or `\u`) asks for. */
1161
+ const levelRange = (value: string | undefined) => {
1162
+ const match = /(\d)\s*-\s*(\d)/.exec(value ?? "");
1163
+ return match ? [Number(match[1]), Number(match[2])] : [1, 9];
1164
+ };
1165
+
1166
+ /** The level a paragraph style gives: a heading's, or its outline level (inherited too). */
1167
+ function styleLevel(word: WordContext, id: string | null | undefined): number | null {
1168
+ const name = word.envelope.styles.find((s) => s.id === id)?.name ?? "";
1169
+ const heading = /^heading ([1-9])$/i.exec(name);
1170
+ if (heading) return Number(heading[1]);
1171
+ const outline = id ? word.resolver.paragraph({ style: id }).paragraph.outlineLevel : null;
1172
+ return outline !== null && outline < 9 ? outline + 1 : null;
1173
+ }
1174
+
1175
+ /** The headings a table of contents lists, as its switches say. */
1176
+ function contentsEntries(tree: Node, word: WordContext, { switches }: FieldInstruction): Entry[] {
1177
+ const hasSource = switches.has("o") || switches.has("u") || switches.has("t");
1178
+ const [low, high] = levelRange(switches.get("o")?.[0]) as [number, number];
1179
+ const custom = new Map<string, number>();
1180
+ const pairs = (switches.get("t")?.[0] ?? "").split(/[,;]/).map((s) => s.trim());
1181
+ for (let i = 0; i + 1 < pairs.length; i += 2)
1182
+ custom.set((pairs[i] as string).toLowerCase(), Number(pairs[i + 1]) || 1);
1183
+ const scope = switches.has("b") ? bookmarkNamed(tree, switches.get("b")?.[0] ?? "") : null;
1184
+ const paragraphs = paragraphsOf(tree);
1185
+ const markers = word.resolver.markers(paragraphs.map((p) => p.node.attrs));
1186
+ const inRange = (level: number) => level >= low && level <= high;
1187
+ const out: Entry[] = [];
1188
+ paragraphs.forEach((paragraph, i) => {
1189
+ const { node, pos } = paragraph;
1190
+ if (scope && (pos + node.nodeSize <= scope.from || pos >= scope.to)) return;
1191
+ const format = word.resolver.paragraph(node.attrs).paragraph;
1192
+ const style = word.envelope.styles.find((s) => s.id === format.style);
1193
+ let level: number | undefined = custom.get((style?.name ?? format.style ?? "").toLowerCase());
1194
+ // What Word lists: styles by their level, and with `\u` a paragraph's own outline level.
1195
+ if (level === undefined && (switches.has("o") || switches.has("u") || !hasSource)) {
1196
+ const own = styleLevel(word, format.style);
1197
+ if (own !== null && inRange(own)) level = own;
1198
+ }
1199
+ const outline = format.outlineLevel;
1200
+ if (level === undefined && switches.has("u") && outline !== null && outline < 9)
1201
+ if (inRange(outline + 1)) level = outline + 1;
1202
+ if (level === undefined) return;
1203
+ const marker = markers[i];
1204
+ for (const { title, from, to, bookmark } of entryParts(tree, word, paragraph))
1205
+ out.push({
1206
+ from,
1207
+ to,
1208
+ level,
1209
+ title,
1210
+ number: marker?.text ?? "",
1211
+ numberGap: marker?.suffix === "space" ? " " : marker?.suffix === "nothing" ? "" : "\t",
1212
+ bookmark,
1213
+ });
1214
+ });
1215
+ return out;
1216
+ }
1217
+
1218
+ /** The width of the text of the section `pos` is in, in twips. */
1219
+ function textWidth(tree: Node, word: WordContext, pos: number): number {
1220
+ let found: SectionJSON | undefined;
1221
+ tree.forEach((node, at) => {
1222
+ if (!found && at + node.nodeSize > pos && node.attrs.section)
1223
+ found = node.attrs.section as SectionJSON;
1224
+ });
1225
+ const { pageSize, margins } = found ?? word.envelope.section;
1226
+ return (
1227
+ (pageSize?.width ?? 12_240) -
1228
+ (margins?.left ?? 1440) -
1229
+ (margins?.right ?? 1440) -
1230
+ (margins?.gutter ?? 0)
1231
+ );
1232
+ }
1233
+
1234
+ /** Whether a paragraph has something of `field` a tracked change has not deleted. */
1235
+ function holdsResult(node: Node, pos: number, field: Field): boolean {
1236
+ let live = pos < field.from;
1237
+ node.forEach((child, offset) => {
1238
+ const at = pos + 1 + offset;
1239
+ if (at >= field.from && at < field.to && !isGone(child))
1240
+ live ||= !child.type.name.startsWith("field") || at === field.from;
1241
+ });
1242
+ return live;
1243
+ }
1244
+
1245
+ /** The styles of the paragraphs a result fills: not the one holding only the end. */
1246
+ function resultStyles(tree: Node, field: Field): (string | null)[] {
1247
+ const out: (string | null)[] = [];
1248
+ tree.nodesBetween(field.from, field.to, (node, pos) => {
1249
+ if (!node.isTextblock) return true;
1250
+ if (holdsResult(node, pos, field) && pos + 1 !== field.resultTo)
1251
+ out.push((node.attrs.style as string | null) ?? null);
1252
+ return false;
1253
+ });
1254
+ return out;
1255
+ }
1256
+
1257
+ const NO_ENTRIES = "No table of contents entries found.";
1258
+
1259
+ /** Makes the table of contents number `index` of the tree list what its headings say. */
1260
+ function rebuildContents(run: Run, index: number): void {
1261
+ const { tr, word, report } = run;
1262
+ const contentsField = () => contentsIn(tr.doc)[index] as Field;
1263
+ let field = contentsField();
1264
+ const instruction = parseFieldInstruction(field.instruction);
1265
+ const { switches } = instruction;
1266
+ for (const letter of switches.keys())
1267
+ if (!GENERAL.includes(letter) && !(KNOWN_SWITCHES.TOC as string).includes(letter)) {
1268
+ skip(run, field, "unsupported-switch", `\\${letter}`);
1269
+ return;
1270
+ }
1271
+ const schema = tr.doc.type.schema;
1272
+ const entries = contentsEntries(tr.doc, word, instruction);
1273
+ const separator = switches.get("p")?.[0] || "\t";
1274
+ const noPages = levelRange(switches.get("n")?.[0]);
1275
+ const pagesHidden = (level: number) =>
1276
+ switches.has("n") && level >= (noPages[0] as number) && level <= (noPages[1] as number);
1277
+ const { layout } = run.options;
1278
+ const pageText = (entry: Entry) => {
1279
+ if (pagesHidden(entry.level) || !layout) return "";
1280
+ const page = layout.pageAt(originalPos(tr, entry.from));
1281
+ return page ? formatNumber(page.number, page.format) : "";
1282
+ };
1283
+ const line = (entry: Entry, page: string) =>
1284
+ (entry.number ? entry.number + entry.numberGap : "") +
1285
+ entry.title +
1286
+ (pagesHidden(entry.level) ? "" : separator + page);
1287
+ const styles: string[] = [];
1288
+ const styleFor = (level: number): string => {
1289
+ const known = ensureStyle({ envelope: run.envelope }, `toc ${level}`);
1290
+ if (!known) throw new TransformError("No table of contents style");
1291
+ run.envelope = known.envelope;
1292
+ return known.id;
1293
+ };
1294
+ for (const entry of entries) styles.push(styleFor(entry.level));
1295
+ // The same lines in the same styles: the page numbers were updated as fields.
1296
+ const shown = (text: string) => (layout ? text : text.replace(/\t[^\t\r]*(?=\r|$)/g, "\t"));
1297
+ // After text in its paragraph the entries start on a paragraph of their own, as in Word.
1298
+ const startsParagraph = tr.doc.resolve(field.from).parentOffset === 0;
1299
+ const lead = startsParagraph ? "" : "\r";
1300
+ const wanted = lead + entries.map((entry) => line(entry, pageText(entry))).join("\r");
1301
+ const current = resultStyles(tr.doc, field).slice(startsParagraph ? 0 : 1);
1302
+ if (
1303
+ (entries.length ? shown(wanted) === shown(field.result) : field.result === NO_ENTRIES) &&
1304
+ (!entries.length || styles.every((id, i) => current[i] === id))
1305
+ ) {
1306
+ report.unchanged++;
1307
+ return;
1308
+ }
1309
+ report.updated++;
1310
+ report.rebuilt++;
1311
+ // Every heading gets its `_Toc` bookmark, Word's way.
1312
+ const nextName = bookmarkNames(tr.doc, "_Toc");
1313
+ let id = nextBookmarkId(run.state, tr);
1314
+ const start = schema.nodes.bookmarkStart as NodeType;
1315
+ const end = schema.nodes.bookmarkEnd as NodeType;
1316
+ const missing = entries.filter((entry) => !entry.bookmark);
1317
+ const ids = new Map(missing.map((entry) => [entry, id++]));
1318
+ for (const entry of missing) entry.bookmark = nextName();
1319
+ for (const entry of missing.reverse()) {
1320
+ const mark = ids.get(entry) as number;
1321
+ tr.insert(entry.to, end.create({ id: mark }));
1322
+ tr.insert(entry.from, start.create({ id: mark, name: entry.bookmark }));
1323
+ }
1324
+ field = contentsField();
1325
+ const hyperlinks = switches.has("h");
1326
+ const linkStyle = hyperlinks && ensureStyle({ envelope: run.envelope }, "Hyperlink", "character");
1327
+ if (linkStyle) run.envelope = linkStyle.envelope;
1328
+ const width = textWidth(tr.doc, word, field.from) - 10;
1329
+ const $start = tr.doc.resolve(field.from);
1330
+ const $end = tr.doc.resolve(field.resultTo);
1331
+ // Entries stand where the field did: in its content controls.
1332
+ const controls = $start.parent.attrs.controls ?? null;
1333
+ const node = (name: string, attrs?: Record<string, unknown> | null, marks?: readonly Mark[]) =>
1334
+ (schema.nodes[name] as NodeType).create(attrs ?? null, null, marks ?? []);
1335
+ const paragraphs = entries.map((entry, i) => {
1336
+ const link = hyperlinks ? [schema.mark("link", { anchor: entry.bookmark })] : [];
1337
+ const styled = linkStyle
1338
+ ? [...link, schema.mark("characterStyle", { id: linkStyle.id })]
1339
+ : link;
1340
+ const content: Node[] = [];
1341
+ if (entry.number) content.push(...inlineText(schema, entry.number + entry.numberGap, styled));
1342
+ content.push(...inlineText(schema, entry.title, styled));
1343
+ if (!pagesHidden(entry.level)) {
1344
+ content.push(...inlineText(schema, separator, link));
1345
+ content.push(
1346
+ node("fieldStart", null, link),
1347
+ node("fieldCode", { text: ` PAGEREF ${entry.bookmark} \\h ` }, link),
1348
+ node("fieldSeparator", null, link),
1349
+ ...inlineText(schema, pageText(entry), link),
1350
+ node("fieldEnd", null, link),
1351
+ );
1352
+ }
1353
+ // A style with tab stops of its own keeps them: Word then writes none on the paragraph.
1354
+ // shortcut: Word sets the number's tab from the number's width; here 440 twips a level.
1355
+ const own = run.envelope.styles.find((s) => s.id === styles[i])?.paragraph?.tabs ?? [];
1356
+ const tabs = [
1357
+ ...(entry.number && entry.numberGap === "\t" && !own.some((t) => t.kind !== "right")
1358
+ ? [{ position: 440 * entry.level, kind: "left" }]
1359
+ : []),
1360
+ ...(separator === "\t" && !own.some((t) => t.kind === "right")
1361
+ ? [{ position: width, kind: "right", leader: "dot" }]
1362
+ : []),
1363
+ ];
1364
+ return (schema.nodes.paragraph as NodeType).create(
1365
+ { style: styles[i], ...(tabs.length ? { tabs } : {}), ...(controls ? { controls } : {}) },
1366
+ content,
1367
+ );
1368
+ });
1369
+ if (!layout)
1370
+ report.skipped.push({ instruction: field.instruction, story: null, reason: "no-layout" });
1371
+ if (!paragraphs.length) {
1372
+ tr.replace(
1373
+ field.resultFrom,
1374
+ field.resultTo,
1375
+ new Slice(Fragment.from(schema.text(NO_ENTRIES)), 0, 0),
1376
+ );
1377
+ return;
1378
+ }
1379
+ // The end goes on in a paragraph of its own, with what follows it, as in Word.
1380
+ if (field.separator === null) {
1381
+ const marks = field.codeMarks ?? [];
1382
+ tr.insert(field.resultTo, node("fieldSeparator", null, withoutReview(marks)));
1383
+ field = contentsField();
1384
+ }
1385
+ /** The paragraphs entries go into, line for line: tracked, each keeps its place and change. */
1386
+ const linesBefore = (closing: number) => {
1387
+ const found: ParagraphAt[] = [];
1388
+ tr.doc.nodesBetween(field.from, field.resultTo, (block, pos) => {
1389
+ if (!block.isTextblock) return true;
1390
+ if (pos !== closing && (pos > $start.before() || startsParagraph))
1391
+ if (holdsResult(block, pos, field)) found.push({ node: block, pos });
1392
+ return false;
1393
+ });
1394
+ return found;
1395
+ };
1396
+ const $inline = tr.doc.resolve(field.resultTo);
1397
+ if ($inline.parentOffset) {
1398
+ // Its paragraph becomes the end's: emptied when no entry needs it (a split beside lines being
1399
+ // deleted cannot be tracked), else divided.
1400
+ const spare =
1401
+ $inline.before() !== $start.before() &&
1402
+ paragraphs.length <= linesBefore($inline.before()).length;
1403
+ if (spare) tr.delete($inline.start(), field.resultTo);
1404
+ else tr.split(field.resultTo);
1405
+ field = contentsField();
1406
+ }
1407
+ const $close = tr.doc.resolve(field.resultTo);
1408
+ const closing = $close.before();
1409
+ const closes = $close.parent;
1410
+ const lines = linesBefore(closing);
1411
+ // A section ending in what is replaced goes on ending after the last entry, not after the first.
1412
+ let section = closes.attrs.section ?? null;
1413
+ tr.doc.nodesBetween(field.from, field.resultTo, (block, pos) => {
1414
+ if (block.isTextblock && pos !== closing) section ??= block.attrs.section ?? null;
1415
+ return !block.isTextblock;
1416
+ });
1417
+ if (section !== (closes.attrs.section ?? null))
1418
+ tr.setNodeMarkup(closing, closes.type, { ...closes.attrs, section });
1419
+ if (paragraphs.length > lines.length) tr.insert(closing, paragraphs.slice(lines.length));
1420
+ for (let i = lines.length - 1; i >= 0; i--) {
1421
+ const { node: old, pos } = lines[i] as ParagraphAt;
1422
+ const entry = paragraphs[i];
1423
+ if (!entry) {
1424
+ tr.delete(pos, pos + old.nodeSize);
1425
+ continue;
1426
+ }
1427
+ const from = pos < field.from ? field.resultFrom : pos + 1;
1428
+ tr.replace(from, pos + 1 + old.content.size, new Slice(entry.content, 0, 0));
1429
+ const { revision, formatChange } = old.attrs;
1430
+ tr.setNodeMarkup(pos, old.type, { ...entry.attrs, revision, formatChange });
1431
+ }
1432
+ if (!startsParagraph) {
1433
+ // What the first paragraph held of the old result goes; the text before the field stays.
1434
+ const held = tr.doc.resolve(field.from);
1435
+ if (field.resultFrom < held.end()) tr.delete(field.resultFrom, held.end());
1436
+ if (held.parent.attrs.section)
1437
+ tr.setNodeMarkup(held.before(), held.parent.type, { ...held.parent.attrs, section: null });
1438
+ }
1439
+ }
1440
+
1441
+ /** @internal A bookmark id no tree of the document uses yet. */
1442
+ export function nextBookmarkId(state: EditorState, tr: Transaction): number {
1443
+ let max = -1;
1444
+ for (const tree of [tr.doc, ...otherTrees(state)])
1445
+ tree.descendants((node) => {
1446
+ if (node.type.name.startsWith("bookmark")) max = Math.max(max, node.attrs.id as number);
1447
+ return !node.isInline;
1448
+ });
1449
+ return max + 1;
1450
+ }
1451
+
1452
+ // ---------- updating ----------
1453
+
1454
+ /** The fields a range picks: a caret, the field around it (see `only`). */
1455
+ function fieldsInRange(tree: Node, from: number, to: number): Set<number> {
1456
+ const fields = fieldsIn(tree);
1457
+ if (from < to)
1458
+ return new Set(fields.filter((f) => f.from < to && f.to > from).map((f) => f.from));
1459
+ // A caret stays out of a result's edges: one beside a field is at that field.
1460
+ let field =
1461
+ fieldAround(tree, from) ?? fields.find((f) => f.to === from || f.from === from) ?? null;
1462
+ if (field?.parent?.name === "TOC") field = field.parent;
1463
+ return new Set(field ? [field.from] : []);
1464
+ }
1465
+
1466
+ function storyRun(editor: Editor, id: string, story: Story, body: Run, out: Transaction): void {
1467
+ const storyEditor = editor.story(id);
1468
+ if (!storyEditor || !fieldsIn(story.doc).length) return;
1469
+ const { state } = storyEditor;
1470
+ const tr = state.tr.setMeta(controlEdit, "fields");
1471
+ const { updated, unchanged } = body.report;
1472
+ updateTree({ ...body, state, tr, story: id, bodyTr: body.tr });
1473
+ if (!tr.docChanged) return;
1474
+ const tracked = trackTransaction(state, tr);
1475
+ if (!tracked) {
1476
+ // None of it happens: what the count said of this story is taken back.
1477
+ body.report.updated = updated;
1478
+ body.report.unchanged = unchanged;
1479
+ body.report.skipped.push({ instruction: "", story: id, reason: "untrackable" });
1480
+ return;
1481
+ }
1482
+ const next = state.applyTransaction(tracked).state;
1483
+ out.step(
1484
+ new StoryStep(
1485
+ id,
1486
+ story,
1487
+ { ...story, doc: next.doc },
1488
+ state.selection.toJSON(),
1489
+ next.selection.toJSON(),
1490
+ ),
1491
+ );
1492
+ }
1493
+
1494
+ /** @internal The id of the story whose tree `doc` is. */
1495
+ export function storyIdOf(body: EditorState, doc: Node): string {
1496
+ for (const [id, story] of wordContext(body)?.stories ?? []) if (story.doc === doc) return id;
1497
+ return "";
1498
+ }
1499
+
1500
+ /**
1501
+ * Updates fields: one transaction, one undo step, tracked when tracking is on. Locked fields stay;
1502
+ * what cannot be worked out keeps its result and is reported. Page fields in a story are drawn by
1503
+ * the view page by page and left alone.
1504
+ */
1505
+ export function updateFields(editor: Editor, options: UpdateFieldsOptions = {}): FieldsReport {
1506
+ const { state } = editor;
1507
+ const word = wordContext(state);
1508
+ if (!word) return emptyReport();
1509
+ const body = storyBody(state)?.state;
1510
+ const { only } = options;
1511
+ const picks =
1512
+ only && typeof only !== "function" ? fieldsInRange(state.doc, only.from, only.to) : null;
1513
+ const attempt = (contents: boolean) => {
1514
+ // Word updates fields in locked content and in lists.
1515
+ const tr = state.tr.setMeta(controlEdit, "fields");
1516
+ const run: Run = {
1517
+ state,
1518
+ tr,
1519
+ word,
1520
+ story: null,
1521
+ bodyTr: tr,
1522
+ options,
1523
+ report: emptyReport(),
1524
+ envelope: word.envelope,
1525
+ numbers: new Map(),
1526
+ contents,
1527
+ picked: (field) => {
1528
+ if (typeof only === "function") return only(field);
1529
+ if (!picks) return true;
1530
+ // What a table of contents holds goes with it.
1531
+ const holder = field.parent?.name === "TOC" ? field.parent : null;
1532
+ return [field, holder].some((f) => f && picks.has(originalPos(tr, f.from)));
1533
+ },
1534
+ };
1535
+ if (body) {
1536
+ run.story = storyIdOf(body, state.doc);
1537
+ run.bodyTr = body.tr;
1538
+ }
1539
+ updateTree(run);
1540
+ return { run, out: trackTransaction(state, tr) };
1541
+ };
1542
+ // What tracking cannot record stays out, and the other fields are still updated.
1543
+ let made = attempt(true);
1544
+ if (!made.out) made = attempt(false);
1545
+ const { run, out } = made;
1546
+ if (!out) {
1547
+ const report = emptyReport();
1548
+ report.skipped.push({ instruction: "", story: run.story, reason: "untrackable" });
1549
+ return report;
1550
+ }
1551
+ if (!body && !picks)
1552
+ for (const [id, story] of word.stories) storyRun(editor, id, story, run, out);
1553
+ if (out.docChanged) {
1554
+ if (run.envelope !== word.envelope) withEnvelope(out, run.envelope);
1555
+ out.setMeta(options.continues ? joinHistory : closeHistory, true);
1556
+ editor.dispatch(out.setMeta(untracked, true));
1557
+ }
1558
+ return run.report;
1559
+ }
1560
+
1561
+ // ---------- inserting ----------
1562
+
1563
+ export interface InsertFieldOptions {
1564
+ /** The result until it is updated, when it cannot be worked out here. */
1565
+ result?: string;
1566
+ layout?: FieldLayout | null | undefined;
1567
+ data?: UpdateFieldsOptions["data"];
1568
+ now?: Date | undefined;
1569
+ }
1570
+
1571
+ /** Whether a field can go at the selection. */
1572
+ const canInsert = (state: EditorState) =>
1573
+ wordContext(state) !== null && state.selection.$from.parent.inlineContent;
1574
+
1575
+ /** Puts a new field at `pos` of `tr`, its result worked out; returns where it ends. */
1576
+ function placeField(
1577
+ state: EditorState,
1578
+ tr: Transaction,
1579
+ pos: number,
1580
+ instruction: string,
1581
+ marks: readonly Mark[],
1582
+ options: InsertFieldOptions,
1583
+ ): number {
1584
+ const schema = tr.doc.type.schema;
1585
+ const make = (name: string, attrs?: Record<string, unknown>) =>
1586
+ (schema.nodes[name] as NodeType).create(attrs ?? null, null, marks);
1587
+ const initial = options.result ? inlineText(schema, options.result, marks) : [];
1588
+ const nodes = [
1589
+ make("fieldStart"),
1590
+ make("fieldCode", { text: ` ${instruction} ` }),
1591
+ make("fieldSeparator"),
1592
+ ...initial,
1593
+ make("fieldEnd"),
1594
+ ];
1595
+ tr.insert(pos, nodes);
1596
+ const size = nodes.reduce((sum, node) => sum + node.nodeSize, 0);
1597
+ const word = wordContext(state) as WordContext;
1598
+ const body = storyBody(state)?.state;
1599
+ const run: Run = {
1600
+ state,
1601
+ tr,
1602
+ word,
1603
+ story: body ? storyIdOf(body, state.doc) : null,
1604
+ bodyTr: body ? body.tr : tr,
1605
+ options,
1606
+ report: emptyReport(),
1607
+ envelope: word.envelope,
1608
+ numbers: new Map(),
1609
+ contents: true,
1610
+ picked: (field) => field.from === pos,
1611
+ };
1612
+ updateTree(run);
1613
+ if (run.envelope !== word.envelope) withEnvelope(tr, run.envelope);
1614
+ const placed = fieldsIn(tr.doc).find((f) => f.from === pos);
1615
+ return placed?.to ?? pos + size;
1616
+ }
1617
+
1618
+ /** Replaces the selection with a field; its result is worked out where that can be done here. */
1619
+ export function insertField(instruction: string, options: InsertFieldOptions = {}): Command {
1620
+ return (state, dispatch) => {
1621
+ if (!canInsert(state) || !instruction.trim()) return false;
1622
+ if (!dispatch) return true;
1623
+ return attempt(state, dispatch, (tr) => {
1624
+ const marks = withoutReview(state.storedMarks ?? marksAt(state.selection.$from));
1625
+ tr.deleteSelection();
1626
+ const end = placeField(state, tr, tr.selection.from, instruction.trim(), marks, options);
1627
+ tr.setSelection(TextSelection.create(tr.doc, end)).setMeta(closeHistory, true);
1628
+ });
1629
+ };
1630
+ }
1631
+
1632
+ /** A `PAGE` field at the selection. */
1633
+ export const insertPageNumber = (options: InsertFieldOptions = {}): Command =>
1634
+ insertField("PAGE", { result: "1", ...options });
1635
+
1636
+ /** A `DATE` field at the selection, in a Word date picture. */
1637
+ export const insertDate = (picture = "d MMMM yyyy", options: InsertFieldOptions = {}): Command =>
1638
+ insertField(`DATE \\@ "${picture.replace(/"/g, '\\"')}"`, options);
1639
+
1640
+ /** What can be cross-referenced: bookmarks (not Word's own, `_…`) and headings. */
1641
+ export interface CrossReferenceTargets {
1642
+ bookmarks: { name: string; text: string }[];
1643
+ headings: { pos: number; level: number; text: string; number: string }[];
1644
+ }
1645
+
1646
+ export function crossReferenceTargets(state: EditorState): CrossReferenceTargets {
1647
+ const word = wordContext(state);
1648
+ if (!word) return { bookmarks: [], headings: [] };
1649
+ const tree = storyBody(state)?.state.doc ?? state.doc;
1650
+ const bookmarks = [...bookmarksIn(tree).values()]
1651
+ .filter((mark) => !mark.name.startsWith("_"))
1652
+ .map((mark) => ({
1653
+ name: mark.name,
1654
+ text: bookmarkContent(tree, mark)
1655
+ .map((n) => n.text ?? " ")
1656
+ .join(""),
1657
+ }));
1658
+ const numbers = new ListNumbers(tree, word);
1659
+ const headings = headingsOf(tree, word).flatMap(({ pos, level }) => {
1660
+ const node = tree.nodeAt(pos) as Node;
1661
+ const text = entryTitle(tree, word, { node, pos });
1662
+ return text.trim() ? [{ pos, level, text, number: numbers.marker(pos + 1)?.text ?? "" }] : [];
1663
+ });
1664
+ return { bookmarks, headings };
1665
+ }
1666
+
1667
+ export interface CrossReference {
1668
+ /** A bookmark's name, or a heading's position (`crossReferenceTargets`). */
1669
+ to: string | number;
1670
+ /** What the field shows: the text, its page, or its paragraph's number. Default text. */
1671
+ show?: "text" | "page" | "number";
1672
+ /** Whether a click on it goes there (`\h`). Default true. */
1673
+ link?: boolean;
1674
+ layout?: FieldLayout | null | undefined;
1675
+ }
1676
+
1677
+ /** A `REF` or `PAGEREF` at the selection; a heading gets a `_Ref` bookmark, as Word gives it. */
1678
+ export function insertCrossReference(reference: CrossReference): Command {
1679
+ return (state, dispatch) => {
1680
+ const { to, show = "text", link = true, layout } = reference;
1681
+ // A heading is the body's: its bookmark cannot be added from a story's transaction.
1682
+ if (!canInsert(state) || (typeof to === "number" && storyBody(state))) return false;
1683
+ const heading = typeof to === "number" ? state.doc.nodeAt(to) : null;
1684
+ if (typeof to === "number" ? heading?.type.name !== "paragraph" : !findName(state, to))
1685
+ return false;
1686
+ if (!dispatch) return true;
1687
+ return attempt(state, dispatch, (tr) => {
1688
+ let name = typeof to === "string" ? to : null;
1689
+ if (typeof to === "number") {
1690
+ const node = heading as Node;
1691
+ node.forEach((child) => {
1692
+ // Not a `_Toc` one: Word makes those again with the table of contents.
1693
+ if (child.type.name === "bookmarkStart" && /^_Ref\d+$/.test(child.attrs.name as string))
1694
+ name ??= child.attrs.name as string;
1695
+ });
1696
+ if (!name) {
1697
+ name = bookmarkNames(tr.doc, "_Ref")();
1698
+ const id = nextBookmarkId(state, tr);
1699
+ const { bookmarkStart, bookmarkEnd } = tr.doc.type.schema.nodes as Record<
1700
+ string,
1701
+ NodeType
1702
+ >;
1703
+ tr.insert(to + 1 + node.content.size, (bookmarkEnd as NodeType).create({ id }));
1704
+ tr.insert(to + 1, (bookmarkStart as NodeType).create({ id, name }));
1705
+ }
1706
+ }
1707
+ const marks = withoutReview(state.storedMarks ?? marksAt(state.selection.$from));
1708
+ tr.deleteSelection();
1709
+ const code =
1710
+ (show === "page" ? "PAGEREF " : "REF ") +
1711
+ quotedName(name as string) +
1712
+ (show === "number" ? " \\r" : "") +
1713
+ (link ? " \\h" : "");
1714
+ const end = placeField(state, tr, tr.selection.from, code, marks, { layout });
1715
+ tr.setSelection(TextSelection.create(tr.doc, end)).setMeta(closeHistory, true);
1716
+ });
1717
+ };
1718
+ }
1719
+
1720
+ const findName = (state: EditorState, name: string) =>
1721
+ !!bookmarkNamed(storyBody(state)?.state.doc ?? state.doc, name);
1722
+
1723
+ export interface TableOfContentsOptions {
1724
+ /** The heading levels listed. Default 1 to 3. */
1725
+ from?: number;
1726
+ to?: number;
1727
+ /** Entries link to their headings (`\h`). Default true. */
1728
+ hyperlinks?: boolean;
1729
+ layout?: FieldLayout | null | undefined;
1730
+ }
1731
+
1732
+ /**
1733
+ * A table of contents at the selection, as Word's own (`TOC \o "1-3" \h \z \u`), in a paragraph of
1734
+ * its own, built from the headings. Not in a story: Word's headings are the body's.
1735
+ */
1736
+ export function insertTableOfContents(options: TableOfContentsOptions = {}): Command {
1737
+ return (state, dispatch) => {
1738
+ if (!canInsert(state) || storyBody(state)) return false;
1739
+ // A table of contents holds its entries, not another one.
1740
+ const { from: start, to: end } = state.selection;
1741
+ const inContents = fieldsIn(state.doc).some(
1742
+ (f) => f.name === "TOC" && f.from < end && start < f.to,
1743
+ );
1744
+ if (inContents) return false;
1745
+ if (!dispatch) return true;
1746
+ const { from = 1, to = 3, hyperlinks = true, layout } = options;
1747
+ return attempt(state, dispatch, (tr) => {
1748
+ tr.deleteSelection();
1749
+ const $pos = tr.selection.$from;
1750
+ const paragraph = tr.doc.type.schema.nodes.paragraph as NodeType;
1751
+ let at = $pos.pos;
1752
+ if ($pos.parent.content.size) {
1753
+ if ($pos.parentOffset === 0) {
1754
+ tr.insert($pos.before(), paragraph.create());
1755
+ at = $pos.before() + 1;
1756
+ } else if ($pos.parentOffset === $pos.parent.content.size) {
1757
+ tr.insert($pos.after(), paragraph.create());
1758
+ at = $pos.after() + 1;
1759
+ } else {
1760
+ tr.split($pos.pos);
1761
+ tr.insert($pos.pos + 1, paragraph.create());
1762
+ at = $pos.pos + 2;
1763
+ }
1764
+ }
1765
+ const code = `TOC \\o "${from}-${to}"${hyperlinks ? " \\h" : ""} \\z \\u`;
1766
+ const end = placeField(state, tr, at, code, [], { layout });
1767
+ tr.setSelection(TextSelection.create(tr.doc, end)).setMeta(closeHistory, true);
1768
+ });
1769
+ };
1770
+ }