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