docxkeun 0.1.3 → 0.3.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 (199) hide show
  1. package/CHANGELOG.md +74 -0
  2. package/README.md +166 -16
  3. package/dist/api/editor.d.ts +231 -7
  4. package/dist/api/editor.js +1125 -26
  5. package/dist/api/headers.d.ts +51 -0
  6. package/dist/api/headers.js +133 -0
  7. package/dist/api/index.d.ts +6 -1
  8. package/dist/api/index.js +4 -1
  9. package/dist/api/lists.d.ts +37 -0
  10. package/dist/api/lists.js +132 -0
  11. package/dist/api/parts.js +1 -0
  12. package/dist/api/positions.js +1 -0
  13. package/dist/api/revisions.d.ts +61 -0
  14. package/dist/api/revisions.js +401 -0
  15. package/dist/api/selection.d.ts +57 -0
  16. package/dist/api/selection.js +91 -0
  17. package/dist/api/tables.d.ts +60 -0
  18. package/dist/api/tables.js +138 -0
  19. package/dist/charts/color.d.ts +45 -0
  20. package/dist/charts/color.js +322 -0
  21. package/dist/charts/format.d.ts +12 -0
  22. package/dist/charts/format.js +459 -0
  23. package/dist/charts/index.d.ts +11 -0
  24. package/dist/charts/index.js +8 -0
  25. package/dist/charts/model.d.ts +225 -0
  26. package/dist/charts/model.js +758 -0
  27. package/dist/charts/outline.d.ts +17 -0
  28. package/dist/charts/outline.js +214 -0
  29. package/dist/charts/render.d.ts +20 -0
  30. package/dist/charts/render.js +1772 -0
  31. package/dist/drawing/arrows.d.ts +37 -0
  32. package/dist/drawing/arrows.js +99 -0
  33. package/dist/drawing/formula.d.ts +40 -0
  34. package/dist/drawing/formula.js +159 -0
  35. package/dist/drawing/geometry.d.ts +61 -0
  36. package/dist/drawing/geometry.js +286 -0
  37. package/dist/drawing/index.d.ts +12 -0
  38. package/dist/drawing/index.js +8 -0
  39. package/dist/drawing/presets.d.ts +72 -0
  40. package/dist/drawing/presets.js +2874 -0
  41. package/dist/fonts/shaping/apply.d.ts +94 -0
  42. package/dist/fonts/shaping/apply.js +349 -0
  43. package/dist/fonts/shaping/arabic.d.ts +28 -0
  44. package/dist/fonts/shaping/arabic.js +235 -0
  45. package/dist/fonts/shaping/buffer.d.ts +53 -0
  46. package/dist/fonts/shaping/buffer.js +95 -0
  47. package/dist/fonts/shaping/gdef.d.ts +30 -0
  48. package/dist/fonts/shaping/gdef.js +66 -0
  49. package/dist/fonts/shaping/gpos.d.ts +86 -0
  50. package/dist/fonts/shaping/gpos.js +428 -0
  51. package/dist/fonts/shaping/gsub.d.ts +65 -0
  52. package/dist/fonts/shaping/gsub.js +313 -0
  53. package/dist/fonts/shaping/index.d.ts +32 -0
  54. package/dist/fonts/shaping/index.js +402 -0
  55. package/dist/fonts/shaping/indic.d.ts +6 -0
  56. package/dist/fonts/shaping/indic.js +805 -0
  57. package/dist/fonts/shaping/layout-common.d.ts +124 -0
  58. package/dist/fonts/shaping/layout-common.js +349 -0
  59. package/dist/fonts/shaping/plan.d.ts +87 -0
  60. package/dist/fonts/shaping/plan.js +152 -0
  61. package/dist/fonts/shaping/scripts.d.ts +26 -0
  62. package/dist/fonts/shaping/scripts.js +160 -0
  63. package/dist/fonts/shaping/shaper.d.ts +23 -0
  64. package/dist/fonts/shaping/shaper.js +5 -0
  65. package/dist/fonts/shaping/unicode.d.ts +34 -0
  66. package/dist/fonts/shaping/unicode.js +138 -0
  67. package/dist/images/bmp.d.ts +9 -0
  68. package/dist/images/bmp.js +234 -0
  69. package/dist/images/gif.d.ts +9 -0
  70. package/dist/images/gif.js +215 -0
  71. package/dist/images/index.d.ts +18 -0
  72. package/dist/images/index.js +63 -0
  73. package/dist/images/png-encode.d.ts +4 -0
  74. package/dist/images/png-encode.js +73 -0
  75. package/dist/images/size.d.ts +10 -0
  76. package/dist/images/size.js +83 -0
  77. package/dist/images/tiff.d.ts +14 -0
  78. package/dist/images/tiff.js +407 -0
  79. package/dist/index.d.ts +7 -2
  80. package/dist/index.js +5 -0
  81. package/dist/layout/bidi.d.ts +18 -0
  82. package/dist/layout/bidi.js +71 -0
  83. package/dist/layout/blocks.d.ts +20 -3
  84. package/dist/layout/blocks.js +88 -58
  85. package/dist/layout/cache.d.ts +31 -0
  86. package/dist/layout/cache.js +38 -0
  87. package/dist/layout/drawing.d.ts +30 -0
  88. package/dist/layout/drawing.js +120 -0
  89. package/dist/layout/engine.d.ts +3 -0
  90. package/dist/layout/engine.js +218 -11
  91. package/dist/layout/index.d.ts +1 -0
  92. package/dist/layout/index.js +1 -0
  93. package/dist/layout/lines.d.ts +63 -5
  94. package/dist/layout/lines.js +245 -20
  95. package/dist/layout/paint.d.ts +25 -3
  96. package/dist/layout/paint.js +26 -10
  97. package/dist/layout/shapes.d.ts +7 -0
  98. package/dist/layout/shapes.js +338 -0
  99. package/dist/layout/style.d.ts +4 -0
  100. package/dist/layout/style.js +2 -0
  101. package/dist/layout/types.d.ts +89 -2
  102. package/dist/math/boxes.d.ts +88 -0
  103. package/dist/math/boxes.js +166 -0
  104. package/dist/math/index.d.ts +29 -0
  105. package/dist/math/index.js +44 -0
  106. package/dist/math/layout.d.ts +13 -0
  107. package/dist/math/layout.js +771 -0
  108. package/dist/math/linear.d.ts +3 -0
  109. package/dist/math/linear.js +152 -0
  110. package/dist/math/omml.d.ts +15 -0
  111. package/dist/math/omml.js +57 -0
  112. package/dist/math/paths.d.ts +61 -0
  113. package/dist/math/paths.js +450 -0
  114. package/dist/math/symbols.d.ts +49 -0
  115. package/dist/math/symbols.js +269 -0
  116. package/dist/math/text.d.ts +53 -0
  117. package/dist/math/text.js +316 -0
  118. package/dist/metafile/canvas.d.ts +80 -0
  119. package/dist/metafile/canvas.js +515 -0
  120. package/dist/metafile/dib.d.ts +27 -0
  121. package/dist/metafile/dib.js +300 -0
  122. package/dist/metafile/emf.d.ts +31 -0
  123. package/dist/metafile/emf.js +591 -0
  124. package/dist/metafile/geometry.d.ts +49 -0
  125. package/dist/metafile/geometry.js +85 -0
  126. package/dist/metafile/index.d.ts +27 -0
  127. package/dist/metafile/index.js +34 -0
  128. package/dist/metafile/reader.d.ts +28 -0
  129. package/dist/metafile/reader.js +59 -0
  130. package/dist/metafile/state.d.ts +118 -0
  131. package/dist/metafile/state.js +172 -0
  132. package/dist/metafile/text.d.ts +17 -0
  133. package/dist/metafile/text.js +130 -0
  134. package/dist/metafile/wmf.d.ts +33 -0
  135. package/dist/metafile/wmf.js +395 -0
  136. package/dist/model/content.d.ts +92 -7
  137. package/dist/model/content.js +251 -17
  138. package/dist/model/document.d.ts +34 -1
  139. package/dist/model/document.js +80 -1
  140. package/dist/model/fields.d.ts +4 -0
  141. package/dist/model/fields.js +10 -0
  142. package/dist/model/numbering.d.ts +2 -0
  143. package/dist/model/numbering.js +22 -0
  144. package/dist/model/props.d.ts +2 -0
  145. package/dist/model/props.js +3 -0
  146. package/dist/opc/index.d.ts +1 -1
  147. package/dist/opc/package.d.ts +34 -0
  148. package/dist/opc/package.js +58 -4
  149. package/dist/pdf/export.js +97 -6
  150. package/dist/pdf/images.d.ts +7 -0
  151. package/dist/pdf/images.js +39 -2
  152. package/dist/render/activity.d.ts +179 -0
  153. package/dist/render/activity.js +1003 -0
  154. package/dist/render/clipboard.d.ts +29 -0
  155. package/dist/render/clipboard.js +401 -0
  156. package/dist/render/comments.d.ts +166 -0
  157. package/dist/render/comments.js +779 -0
  158. package/dist/render/context-menu.d.ts +124 -0
  159. package/dist/render/context-menu.js +525 -0
  160. package/dist/render/editing.d.ts +146 -5
  161. package/dist/render/editing.js +678 -53
  162. package/dist/render/index.d.ts +12 -0
  163. package/dist/render/index.js +11 -0
  164. package/dist/render/navigation-panel.d.ts +76 -0
  165. package/dist/render/navigation-panel.js +431 -0
  166. package/dist/render/selection.js +5 -0
  167. package/dist/render/svg.d.ts +4 -6
  168. package/dist/render/svg.js +69 -7
  169. package/dist/render/toolbar.d.ts +83 -0
  170. package/dist/render/toolbar.js +505 -0
  171. package/dist/render/ui/comment-layout.d.ts +39 -0
  172. package/dist/render/ui/comment-layout.js +79 -0
  173. package/dist/render/ui/icons.d.ts +6 -0
  174. package/dist/render/ui/icons.js +38 -0
  175. package/dist/render/ui/menu.d.ts +38 -0
  176. package/dist/render/ui/menu.js +274 -0
  177. package/dist/render/ui/nav-model.d.ts +11 -0
  178. package/dist/render/ui/nav-model.js +34 -0
  179. package/dist/render/ui/overflow.d.ts +5 -0
  180. package/dist/render/ui/overflow.js +18 -0
  181. package/dist/render/ui/popover.d.ts +18 -0
  182. package/dist/render/ui/popover.js +109 -0
  183. package/dist/render/ui/theme.d.ts +2 -0
  184. package/dist/render/ui/theme.js +29 -0
  185. package/dist/render/undo.d.ts +76 -0
  186. package/dist/render/undo.js +144 -0
  187. package/dist/render/viewer.d.ts +100 -7
  188. package/dist/render/viewer.js +304 -92
  189. package/dist/security/policy.d.ts +3 -0
  190. package/dist/security/policy.js +6 -2
  191. package/dist/security/protection.d.ts +1 -0
  192. package/dist/security/protection.js +1 -1
  193. package/dist/text/bidi-data.d.ts +53 -0
  194. package/dist/text/bidi-data.js +318 -0
  195. package/dist/text/bidi.d.ts +37 -0
  196. package/dist/text/bidi.js +508 -0
  197. package/dist/xml/ns.d.ts +5 -0
  198. package/dist/xml/ns.js +7 -0
  199. package/package.json +9 -2
@@ -3,9 +3,16 @@
3
3
  * everything docxkeun does not understand is preserved), passes through the access guard, and
4
4
  * notifies listeners such as the viewer.
5
5
  */
6
- import { REL } from '../opc/index.js';
7
- import { attr, el, elements, ensureChild, findAll, firstChild, insertOrdered, removeChildren, textContent } from '../xml/index.js';
8
- import { ensureNamespaces, ensurePart, randomHexId } from './parts.js';
6
+ import { CONTENT_TYPE, IMAGE_CONTENT_TYPES, REL } from '../opc/index.js';
7
+ import { imageInfo } from '../images/size.js';
8
+ import { hasEvenPages, hasFirstPage, headerParagraphs, headerText, referencesOf, sectionProperties, SECTPR_ORDER, textWidth } from './headers.js';
9
+ import { attr, el, elements, ensureChild, findAll, firstChild, insertOrdered, NS, removeChildren, textContent } from '../xml/index.js';
10
+ import { createList, listItems } from './lists.js';
11
+ import { buildTable, cleanCopy, columnWidths, markInserted, markRow } from './tables.js';
12
+ import { cloneElement } from '../xml/index.js';
13
+ import { acceptRevisions, cleanRunProps, deleteRun, insertedRuns, listRevisions, markParagraph, nextRevisionId, paragraphMarkRevision, recordParagraphFormat, recordRunFormat, rejectRevisions, revisionStamp, runRevision, } from './revisions.js';
14
+ import { SETTINGS_ORDER } from '../security/protection.js';
15
+ import { ensureNamespaces, ensurePart, randomHexId, ROOT_NAMESPACES } from './parts.js';
9
16
  import { between, EditError, indexOfChild, isolate, PPR_ORDER, replaceMark, RPR_ORDER, textNode, TreeIndex, } from './positions.js';
10
17
  const LOCK_VALUES = { content: 'contentLocked', contentAndControl: 'sdtContentLocked', control: 'sdtLocked' };
11
18
  const LOCK_MODES = { contentLocked: 'content', sdtContentLocked: 'contentAndControl', sdtLocked: 'control' };
@@ -31,6 +38,18 @@ function sdtTitle(sdt) {
31
38
  function locksContent(mode) {
32
39
  return mode === 'content' || mode === 'contentAndControl';
33
40
  }
41
+ /** Whether Word would record changes in this document: Track Changes on, or protected for tracked changes. */
42
+ export function documentTracksChanges(doc) {
43
+ const settings = doc.parts.settings ? doc.xmlSync(doc.parts.settings)?.root : undefined;
44
+ if (!settings)
45
+ return false;
46
+ const track = firstChild(settings, 'w:trackRevisions');
47
+ if (track && attr(track, 'w:val') !== 'false' && attr(track, 'w:val') !== '0')
48
+ return true;
49
+ const protection = firstChild(settings, 'w:documentProtection');
50
+ const enforced = attr(protection, 'w:enforcement');
51
+ return attr(protection, 'w:edit') === 'trackedChanges' && (enforced === '1' || enforced === 'true' || enforced === 'on');
52
+ }
34
53
  /** Every paragraph of a block list (including table cells), in document order. */
35
54
  export function paragraphsOf(blocks, out = []) {
36
55
  for (const b of blocks) {
@@ -43,7 +62,7 @@ export function paragraphsOf(blocks, out = []) {
43
62
  }
44
63
  return out;
45
64
  }
46
- export function paragraphText(para) {
65
+ export function paragraphText(para, options = {}) {
47
66
  let text = '';
48
67
  const segments = [];
49
68
  const add = (value, node) => {
@@ -57,9 +76,21 @@ export function paragraphText(para) {
57
76
  add('\t', inline.node);
58
77
  else if (inline.kind === 'break' && inline.type === 'line')
59
78
  add('\n', inline.node);
79
+ else if (options.objects && inline.kind === 'image' && !inline.float) {
80
+ // An inline picture or shape is one character (U+FFFC) the caret can step over and delete.
81
+ const node = objectNode(inline);
82
+ if (node)
83
+ add(OBJECT_CHAR, node);
84
+ }
60
85
  }
61
86
  return { paragraph: para.el, text, segments };
62
87
  }
88
+ /** Stands for an inline picture, shape or chart in `paragraphText(p, { objects: true })`. */
89
+ export const OBJECT_CHAR = '\ufffc';
90
+ /** The run child (w:drawing, w:pict, mc:AlternateContent) holding an inline object. */
91
+ export function objectNode(inline) {
92
+ return elements(inline.run).find((c) => c === inline.drawing || findAll(c, inline.drawing.name).includes(inline.drawing));
93
+ }
63
94
  /**
64
95
  * XML position of character offset `k` in a paragraph. With side 'start' the position is at the
65
96
  * start of the segment holding character k; with 'end' it is at the end of the segment holding
@@ -144,9 +175,26 @@ function endOfRun(run, fallback) {
144
175
  return { node: fallback, offset: 0 };
145
176
  return last.name === 'w:t' ? { node: last, offset: textContent(last).length } : { node: last, offset: 1 };
146
177
  }
178
+ /** Whether a list level is in a set_list format (decimal "1." and decimalParen "1)" differ by their text). */
179
+ function levelMatches(level, format) {
180
+ if (format === 'decimal')
181
+ return level.format === 'decimal' && !/\)\s*$/.test(level.text);
182
+ if (format === 'decimalParen')
183
+ return level.format === 'decimal' && /\)\s*$/.test(level.text);
184
+ return level.format === format;
185
+ }
186
+ function describeLevel(level) {
187
+ if (level.format === 'bullet')
188
+ return 'bulleted';
189
+ if (level.format === 'decimal')
190
+ return /\)\s*$/.test(level.text) ? 'numbered 1)' : 'numbered 1.';
191
+ return `numbered with ${level.format}`;
192
+ }
147
193
  function newRun(text, template, format) {
148
194
  const rPr = template ? firstChild(template, 'w:rPr') : undefined;
149
195
  const run = el('w:r', {}, [...(rPr ? [structuredClone(rPr)] : []), ...runContent(text)]);
196
+ // A new run starts with no revision history of its own.
197
+ cleanRunProps(run);
150
198
  if (format)
151
199
  applyFormat(run, format);
152
200
  return run;
@@ -155,14 +203,129 @@ const BOOKMARK_NAME = /^[\p{L}_][\p{L}\p{N}_]{0,39}$/u;
155
203
  export class DocxEditor {
156
204
  doc;
157
205
  guard;
158
- constructor(doc, guard) {
206
+ trackOverride;
207
+ authorName;
208
+ /** The part being edited. */
209
+ part;
210
+ constructor(doc, guard, options = {}) {
159
211
  this.doc = doc;
160
212
  this.guard = guard;
213
+ this.trackOverride = options.trackChanges;
214
+ this.authorName = options.author;
215
+ this.part = options.part ?? doc.mainPart;
216
+ if (this.part !== doc.mainPart && !doc.xmlSync(this.part))
217
+ throw new EditError(`No part "${this.part}" to edit`);
218
+ }
219
+ /** Whether this editor works on a header, footer or notes part rather than the main document. */
220
+ get isStory() {
221
+ return this.part !== this.doc.mainPart;
222
+ }
223
+ // ---- tracked changes ----------------------------------------------------------------------
224
+ /** Whether edits are recorded as tracked changes (default: the document's Track Changes setting). */
225
+ get trackChanges() {
226
+ return this.trackOverride ?? documentTracksChanges(this.doc);
227
+ }
228
+ set trackChanges(on) {
229
+ this.trackOverride = on;
230
+ }
231
+ /** The author tracked changes are recorded under. */
232
+ get author() {
233
+ const user = this.guard?.user;
234
+ return this.authorName ?? user?.name ?? user?.id ?? 'docxkeun';
235
+ }
236
+ /** Revision stamp and id source for one edit, or undefined when not tracking. */
237
+ tracking() {
238
+ if (!this.trackChanges)
239
+ return undefined;
240
+ return { who: revisionStamp(this.author), nextId: nextRevisionId(this.root) };
241
+ }
242
+ /** Turn Word's own Track Changes setting (settings.xml w:trackRevisions) on or off. */
243
+ async setTrackChangesSetting(on) {
244
+ this.guard?.assert('edit');
245
+ const { name, xml } = await ensurePart(this.doc, 'settings');
246
+ removeChildren(xml.root, 'w:trackRevisions');
247
+ if (on)
248
+ insertOrdered(xml.root, el('w:trackRevisions'), SETTINGS_ORDER);
249
+ this.trackOverride = undefined;
250
+ this.doc.touch(name);
251
+ }
252
+ /** Tracked changes in the main document, in document order. */
253
+ revisions() {
254
+ return listRevisions(this.root);
255
+ }
256
+ /** Accept tracked changes (all, or those matching ids / author). Returns how many. */
257
+ acceptRevisions(filter) {
258
+ this.guard?.assert('review');
259
+ const n = acceptRevisions(this.root, filter);
260
+ if (n)
261
+ this.changed();
262
+ return n;
263
+ }
264
+ /** Reject tracked changes (all, or those matching ids / author). Returns how many. */
265
+ rejectRevisions(filter) {
266
+ this.guard?.assert('review');
267
+ const n = rejectRevisions(this.root, filter);
268
+ if (n)
269
+ this.changed();
270
+ return n;
271
+ }
272
+ /** The new run as it goes into the document: wrapped in a w:ins when tracking. */
273
+ placed(run, track) {
274
+ return track ? insertedRuns([run], track.nextId(), track.who) : run;
275
+ }
276
+ /** Whether a run sits in an insertion by the current author (edits to it need no new revision). */
277
+ inOwnInsertion(run, idx) {
278
+ const rev = runRevision(run, (n) => idx.parent.get(n));
279
+ return !!rev && (rev.name === 'w:ins' || rev.name === 'w:moveTo') && attr(rev, 'w:author') === this.author;
280
+ }
281
+ /**
282
+ * A sentinel inside someone else's w:ins cannot take a nested w:ins: split that insertion at the
283
+ * sentinel so the new one goes between its two halves.
284
+ */
285
+ liftOutOfInsertion(mark, idx) {
286
+ const container = idx.parent.get(mark);
287
+ if (!container || (container.name !== 'w:ins' && container.name !== 'w:moveTo'))
288
+ return;
289
+ const outer = idx.parentOf(container);
290
+ const at = container.children.indexOf(mark);
291
+ const tail = container.children.splice(at);
292
+ tail.shift();
293
+ const pos = outer.children.indexOf(container);
294
+ const pieces = [mark];
295
+ if (tail.some((n) => n.type === 'element'))
296
+ pieces.push(el(container.name, { ...container.attrs }, tail));
297
+ outer.children.splice(pos + 1, 0, ...pieces);
298
+ if (!container.children.some((n) => n.type === 'element'))
299
+ outer.children.splice(outer.children.indexOf(container), 1);
300
+ }
301
+ /** Mark the runs of a range as deleted (and the paragraph marks inside it), keeping the text. */
302
+ trackedCut(range, track) {
303
+ const index = this.index();
304
+ const { startMark, endMark } = isolate(index, range);
305
+ let idx = this.index();
306
+ const startCell = idx.ancestor(startMark, 'w:tc');
307
+ const endCell = idx.ancestor(endMark, 'w:tc');
308
+ if (startCell !== endCell) {
309
+ replaceMark(idx, startMark, []);
310
+ replaceMark(idx, endMark, []);
311
+ throw new EditError('The range crosses table cells');
312
+ }
313
+ const startPara = idx.ancestor(startMark, 'w:p');
314
+ const endPara = idx.ancestor(endMark, 'w:p');
315
+ const paragraphs = startPara === endPara ? [] : [startPara, ...between(idx, startMark, endMark, 'w:p').filter((p) => p !== endPara)];
316
+ for (const run of between(idx, startMark, endMark, 'w:r'))
317
+ deleteRun(run, (n) => idx.parent.get(n), track.nextId, track.who);
318
+ for (const p of paragraphs)
319
+ markParagraph(p, 'del', track.nextId(), track.who);
320
+ idx = this.index();
321
+ return { startMark, endMark, idx };
161
322
  }
162
323
  get root() {
163
- return this.doc.documentXml.root;
324
+ return this.isStory ? this.doc.xmlSync(this.part).root : this.doc.documentXml.root;
164
325
  }
165
326
  get body() {
327
+ if (this.isStory)
328
+ return this.root;
166
329
  const body = firstChild(this.root, 'w:body');
167
330
  if (!body)
168
331
  throw new EditError('document has no body');
@@ -171,11 +334,12 @@ export class DocxEditor {
171
334
  index() {
172
335
  return new TreeIndex(this.root);
173
336
  }
174
- changed(part = this.doc.mainPart) {
337
+ changed(part = this.part) {
175
338
  this.doc.touch(part);
176
339
  }
177
340
  check(action, range, detail) {
178
- this.guard?.assert(action, range, detail);
341
+ const tracked = this.trackChanges && (action === 'edit' || action === 'format' || action === 'fillForm');
342
+ this.guard?.assert(action, range, tracked ? { ...detail, tracked: true } : detail);
179
343
  if (range && (action === 'edit' || action === 'format' || action === 'link'))
180
344
  this.assertUnlocked(range);
181
345
  }
@@ -229,9 +393,18 @@ export class DocxEditor {
229
393
  rangeFromSelection(sel) {
230
394
  return { start: { node: sel.start.inline.node, offset: sel.start.offset }, end: { node: sel.end.inline.node, offset: sel.end.offset } };
231
395
  }
232
- /** Every paragraph of the body, including those in tables, in document order. */
396
+ /** Every paragraph of the story (the body by default), including those in tables, in document order. */
233
397
  paragraphs() {
234
- return paragraphsOf(this.doc.body().blocks);
398
+ if (!this.isStory)
399
+ return paragraphsOf(this.doc.body().blocks);
400
+ const root = this.root;
401
+ if (root.name === 'w:footnotes' || root.name === 'w:endnotes') {
402
+ // Separator notes (w:type) are not content.
403
+ return elements(root)
404
+ .filter((n) => !attr(n, 'w:type') || attr(n, 'w:type') === 'normal')
405
+ .flatMap((n) => paragraphsOf(this.doc.readBlocks(this.part, n)));
406
+ }
407
+ return paragraphsOf(this.doc.headerFooter(this.part).blocks);
235
408
  }
236
409
  /** Range covering a paragraph's text (undefined for paragraphs without text). */
237
410
  paragraphRange(paragraph) {
@@ -287,20 +460,22 @@ export class DocxEditor {
287
460
  */
288
461
  insertText(at, text, format) {
289
462
  const edge = this.bypassLocks ? undefined : this.lockEdge(at);
463
+ const track = this.tracking();
290
464
  if (edge) {
291
465
  // Typing at the very edge of a locked region goes just outside it, as in Word.
292
- this.guard?.assert('edit', { start: at, end: at });
466
+ this.guard?.assert('edit', { start: at, end: at }, track ? { tracked: true } : undefined);
293
467
  const idx = this.index();
294
468
  const run = newRun(text, idx.parentOf(at.node), format);
295
469
  const parent = idx.parentOf(edge.sdt);
296
- parent.children.splice(indexOfChild(parent, edge.sdt) + (edge.after ? 1 : 0), 0, run);
470
+ parent.children.splice(indexOfChild(parent, edge.sdt) + (edge.after ? 1 : 0), 0, this.placed(run, track));
297
471
  this.changed();
298
472
  return endOfRun(run, run);
299
473
  }
300
474
  this.check('edit', { start: at, end: at });
301
475
  const plain = !format && !/[\t\r\n]/.test(text);
302
- // Typing into existing text: change the text node itself instead of adding a run per keystroke.
303
- if (plain && at.node.name === 'w:t') {
476
+ // Typing into existing text: change the text node itself instead of adding a run per keystroke
477
+ // (when tracking, only inside the author's own insertion).
478
+ if (plain && at.node.name === 'w:t' && (!track || this.inOwnInsertion(this.index().parentOf(at.node), this.index()))) {
304
479
  const current = textContent(at.node);
305
480
  const offset = Math.max(0, Math.min(at.offset, current.length));
306
481
  const value = current.slice(0, offset) + text + current.slice(offset);
@@ -314,28 +489,366 @@ export class DocxEditor {
314
489
  // An empty paragraph: the new run takes the paragraph mark's formatting.
315
490
  const markRPr = firstChild(firstChild(at.node, 'w:pPr'), 'w:rPr');
316
491
  const run = el('w:r', {}, [...(markRPr ? [structuredClone(markRPr)] : []), ...runContent(text)]);
492
+ // The paragraph mark's own revision markers do not belong on a text run.
493
+ const runPr = firstChild(run, 'w:rPr');
494
+ if (runPr)
495
+ for (const n of ['w:ins', 'w:del', 'w:moveFrom', 'w:moveTo', 'w:rPrChange'])
496
+ removeChildren(runPr, n);
317
497
  if (format)
318
498
  applyFormat(run, format);
319
499
  const pPr = firstChild(at.node, 'w:pPr');
320
- at.node.children.splice(pPr ? at.node.children.indexOf(pPr) + 1 : 0, 0, run);
500
+ at.node.children.splice(pPr ? at.node.children.indexOf(pPr) + 1 : 0, 0, this.placed(run, track));
321
501
  this.changed();
322
502
  return endOfRun(run, at.node);
323
503
  }
324
504
  const index = this.index();
325
505
  const template = index.parentOf(at.node);
326
506
  const { startMark, endMark } = isolate(index, { start: at, end: at });
327
- const idx = this.index();
507
+ let idx = this.index();
328
508
  const run = newRun(text, template, format);
329
- replaceMark(idx, startMark, [run]);
330
509
  replaceMark(idx, endMark, []);
510
+ idx = this.index();
511
+ if (track && !this.inOwnInsertion(template, index))
512
+ this.liftOutOfInsertion(startMark, idx);
513
+ idx = this.index();
514
+ replaceMark(idx, startMark, [track && !this.inOwnInsertion(template, index) ? this.placed(run, track) : run]);
331
515
  this.changed();
332
516
  return endOfRun(run, run);
333
517
  }
518
+ /** Insert a run holding `content` (a drawing, a note reference) at a position; returns the run. */
519
+ insertRunContent(at, content, rPr) {
520
+ // Insert a placeholder character in a run of its own (a format forces a new run), then swap in the content.
521
+ const end = this.insertText(at, '\u2063', {});
522
+ const t = end.node;
523
+ const run = this.index().parentOf(t);
524
+ run.children.splice(run.children.indexOf(t), 1, ...content);
525
+ if (rPr) {
526
+ removeChildren(run, 'w:rPr');
527
+ run.children.unshift(rPr);
528
+ }
529
+ this.changed();
530
+ return run;
531
+ }
532
+ /**
533
+ * Insert a picture (PNG, JPEG, GIF, BMP, TIFF, EMF or WMF) inline at a position. Without a size it
534
+ * gets its natural size, shrunk to `maxWidth` (default 468pt, a Letter page's text width).
535
+ */
536
+ async insertImage(at, bytes, options = {}) {
537
+ this.check('edit', { start: at, end: at });
538
+ const info = imageInfo(bytes);
539
+ if (!info)
540
+ throw new EditError('Unsupported image: use PNG, JPEG, GIF, BMP, TIFF, EMF or WMF');
541
+ let { width, height } = options;
542
+ if (width === undefined && height === undefined) {
543
+ width = info.width;
544
+ height = info.height;
545
+ const max = options.maxWidth ?? 468;
546
+ if (width > max) {
547
+ height = (height * max) / width;
548
+ width = max;
549
+ }
550
+ }
551
+ else if (width === undefined)
552
+ width = (info.width * height) / info.height;
553
+ else if (height === undefined)
554
+ height = (info.height * width) / info.width;
555
+ const ext = info.kind === 'jpeg' ? 'jpeg' : info.kind;
556
+ let n = 1;
557
+ while (this.doc.pkg.has(`word/media/image${n}.${ext}`))
558
+ n++;
559
+ const part = `word/media/image${n}.${ext}`;
560
+ this.doc.pkg.setBytes(part, bytes, IMAGE_CONTENT_TYPES[ext]);
561
+ const rId = await this.doc.pkg.addRelationship(this.part, REL.image, part);
562
+ await this.doc.refreshRels(this.part);
563
+ // Drawing ids must be unique in the document.
564
+ let id = 0;
565
+ for (const root of [this.doc.documentXml.root, this.root])
566
+ for (const d of findAll(root, 'wp:docPr'))
567
+ id = Math.max(id, Number(attr(d, 'id') ?? 0));
568
+ id++;
569
+ const name = options.name ?? `Picture ${id}`;
570
+ const cx = String(Math.round(width * 12700));
571
+ const cy = String(Math.round(height * 12700));
572
+ if (this.root.attrs['xmlns:wp'] === undefined)
573
+ this.root.attrs['xmlns:wp'] = NS.wp;
574
+ if (this.root.attrs['xmlns:r'] === undefined)
575
+ this.root.attrs['xmlns:r'] = NS.r;
576
+ const docPr = { id: String(id), name };
577
+ if (options.alt)
578
+ docPr.descr = options.alt;
579
+ const drawing = el('w:drawing', {}, [
580
+ el('wp:inline', { distT: '0', distB: '0', distL: '0', distR: '0' }, [
581
+ el('wp:extent', { cx, cy }),
582
+ el('wp:effectExtent', { l: '0', t: '0', r: '0', b: '0' }),
583
+ el('wp:docPr', docPr),
584
+ el('wp:cNvGraphicFramePr', {}, [el('a:graphicFrameLocks', { 'xmlns:a': NS.a, noChangeAspect: '1' })]),
585
+ el('a:graphic', { 'xmlns:a': NS.a }, [
586
+ el('a:graphicData', { uri: 'http://schemas.openxmlformats.org/drawingml/2006/picture' }, [
587
+ el('pic:pic', { 'xmlns:pic': NS.pic }, [
588
+ el('pic:nvPicPr', {}, [el('pic:cNvPr', { id: '0', name }), el('pic:cNvPicPr')]),
589
+ el('pic:blipFill', {}, [el('a:blip', { 'r:embed': rId }), el('a:stretch', {}, [el('a:fillRect')])]),
590
+ el('pic:spPr', {}, [el('a:xfrm', {}, [el('a:off', { x: '0', y: '0' }), el('a:ext', { cx, cy })]), el('a:prstGeom', { prst: 'rect' }, [el('a:avLst')])]),
591
+ ]),
592
+ ]),
593
+ ]),
594
+ ]),
595
+ ]);
596
+ this.insertRunContent(at, [drawing]);
597
+ return drawing;
598
+ }
599
+ /** Add a footnote whose reference mark goes at a position. Returns the note's id. */
600
+ async addFootnote(at, text) {
601
+ this.check('edit', { start: at, end: at });
602
+ if (this.isStory)
603
+ throw new EditError('Footnotes can only be added to the main document');
604
+ let part = this.doc.parts.footnotes;
605
+ if (!part || !this.doc.xmlSync(part)) {
606
+ part = 'word/footnotes.xml';
607
+ for (let n = 2; this.doc.pkg.has(part); n++)
608
+ part = `word/footnotes${n}.xml`;
609
+ const separator = (type, id, mark) => el('w:footnote', { 'w:type': type, 'w:id': id }, [el('w:p', {}, [el('w:pPr', {}, [el('w:spacing', { 'w:after': '0', 'w:line': '240', 'w:lineRule': 'auto' })]), el('w:r', {}, [el(mark)])])]);
610
+ const xml = { declaration: null, prolog: [], epilog: [], root: el('w:footnotes', { ...ROOT_NAMESPACES }, [separator('separator', '-1', 'w:separator'), separator('continuationSeparator', '0', 'w:continuationSeparator')]) };
611
+ this.doc.pkg.setXml(part, xml, CONTENT_TYPE.footnotes);
612
+ await this.doc.pkg.addRelationship(this.doc.mainPart, REL.footnotes, part);
613
+ await this.doc.refreshRels(this.doc.mainPart);
614
+ this.doc.parts.footnotes = part;
615
+ }
616
+ const notes = this.doc.xmlSync(part).root;
617
+ const id = String(Math.max(0, ...elements(notes, 'w:footnote').map((n) => Number(attr(n, 'w:id') ?? 0))) + 1);
618
+ const styled = (styleId, fallback) => (this.doc.styles.get(styleId) ? [el('w:rStyle', { 'w:val': styleId })] : fallback);
619
+ const refPr = () => el('w:rPr', {}, styled('FootnoteReference', [el('w:vertAlign', { 'w:val': 'superscript' })]));
620
+ const pPr = this.doc.styles.get('FootnoteText') ? [el('w:pPr', {}, [el('w:pStyle', { 'w:val': 'FootnoteText' })])] : [el('w:pPr', {}, [el('w:spacing', { 'w:after': '0' })])];
621
+ const textPr = this.doc.styles.get('FootnoteText') ? [] : [el('w:rPr', {}, [el('w:sz', { 'w:val': '20' })])];
622
+ notes.children.push(el('w:footnote', { 'w:id': id }, [
623
+ el('w:p', {}, [...pPr, el('w:r', {}, [refPr(), el('w:footnoteRef')]), el('w:r', {}, [...textPr, ...runContent(` ${text}`)])]),
624
+ ]));
625
+ this.doc.touch(part);
626
+ this.insertRunContent(at, [el('w:footnoteReference', { 'w:id': id })], refPr());
627
+ return id;
628
+ }
629
+ // ---- headers and footers -----------------------------------------------------------------
630
+ /** Headers and footers by section and page type, with their text ({PAGE} for page fields). */
631
+ headersAndFooters() {
632
+ const sections = sectionProperties(this.mainBody());
633
+ const out = [];
634
+ sections.forEach((sp, i) => {
635
+ for (const kind of ['header', 'footer']) {
636
+ for (const ref of referencesOf(sp, kind)) {
637
+ const part = this.doc.headerFooterPart(attr(ref, 'r:id') ?? '');
638
+ if (!part)
639
+ continue;
640
+ const type = (attr(ref, 'w:type') ?? 'default');
641
+ const known = out.find((h) => h.part === part && h.type === type && h.kind === kind);
642
+ if (known)
643
+ known.sections.push(i + 1);
644
+ else
645
+ out.push({ kind, type, sections: [i + 1], part, text: headerText(this.doc.xmlSync(part)?.root ?? el('w:hdr')) });
646
+ }
647
+ }
648
+ });
649
+ return out;
650
+ }
651
+ /** Give the document's sections a header (see `setHeaderFooter`). Returns the part name. */
652
+ setHeader(text, options = {}) {
653
+ return this.setHeaderFooter('header', text, options);
654
+ }
655
+ /** Give the document's sections a footer (see `setHeaderFooter`). Returns the part name. */
656
+ setFooter(text, options = {}) {
657
+ return this.setHeaderFooter('footer', text, options);
658
+ }
659
+ /**
660
+ * Create or replace a header or footer. `text`: lines become paragraphs, tabs split it into
661
+ * left / centre / right parts, and {PAGE}, {NUMPAGES}, {SECTIONPAGES} become page number fields
662
+ * ("Page {PAGE} of {NUMPAGES}"). Every section by default, or one (`section`, from 1); all pages,
663
+ * the first page or even pages (`type`). A part used only by these sections is rewritten in place,
664
+ * otherwise a new part is made, so other sections keep theirs. With Track Changes on, the text
665
+ * changes are recorded.
666
+ */
667
+ async setHeaderFooter(kind, text, options = {}) {
668
+ if (this.isStory)
669
+ throw new EditError('Headers and footers are set from an editor of the main document');
670
+ this.check('edit');
671
+ const type = options.type ?? 'default';
672
+ const body = this.mainBody();
673
+ let sections = sectionProperties(body);
674
+ if (!sections.length) {
675
+ body.children.push(el('w:sectPr', {}, [el('w:pgSz', { 'w:w': '12240', 'w:h': '15840' }), el('w:pgMar', { 'w:top': '1440', 'w:right': '1440', 'w:bottom': '1440', 'w:left': '1440', 'w:header': '720', 'w:footer': '720', 'w:gutter': '0' })]));
676
+ sections = sectionProperties(body);
677
+ }
678
+ const targets = this.sectionTargets(sections, options.section);
679
+ const refOf = (sp) => referencesOf(sp, kind).find((r) => (attr(r, 'w:type') ?? 'default') === type);
680
+ const partOf = (r) => (r ? this.doc.headerFooterPart(attr(r, 'r:id') ?? '') : undefined);
681
+ // Rewrite in place only when the targets share one part that nothing else uses.
682
+ const current = targets.map((sp) => partOf(refOf(sp)));
683
+ const shared = current[0] && current.every((p) => p === current[0]) ? current[0] : undefined;
684
+ const usedElsewhere = shared &&
685
+ sections.some((sp) => {
686
+ const refs = [...referencesOf(sp, 'header'), ...referencesOf(sp, 'footer')];
687
+ return refs.some((r) => partOf(r) === shared && (!targets.includes(sp) || r.name !== (kind === 'header' ? 'w:headerReference' : 'w:footerReference') || (attr(r, 'w:type') ?? 'default') !== type));
688
+ });
689
+ const paragraphs = headerParagraphs(this.doc, kind, text, options.align, textWidth(targets[0]));
690
+ const track = this.tracking();
691
+ if (track) {
692
+ for (const p of paragraphs) {
693
+ const pPr = firstChild(p, 'w:pPr');
694
+ const content = p.children.filter((c) => c.type === 'element' && c !== pPr);
695
+ p.children = [...(pPr ? [pPr] : []), ...(content.length ? [el('w:ins', insertedRuns([], track.nextId(), track.who).attrs, content)] : [])];
696
+ markParagraph(p, 'ins', track.nextId(), track.who);
697
+ }
698
+ }
699
+ let part;
700
+ if (shared && !usedElsewhere && this.doc.xmlSync(shared)) {
701
+ part = shared;
702
+ const root = this.doc.xmlSync(part).root;
703
+ if (track) {
704
+ // The old text stays, marked deleted.
705
+ const idx = new TreeIndex(root);
706
+ for (const run of findAll(root, 'w:r'))
707
+ deleteRun(run, (n) => idx.parent.get(n), track.nextId, track.who);
708
+ for (const p of findAll(root, 'w:p'))
709
+ markParagraph(p, 'del', track.nextId(), track.who);
710
+ root.children.push(...paragraphs);
711
+ }
712
+ else
713
+ root.children = paragraphs;
714
+ }
715
+ else {
716
+ let n = 1;
717
+ while (this.doc.pkg.has(`word/${kind}${n}.xml`))
718
+ n++;
719
+ part = `word/${kind}${n}.xml`;
720
+ const root = el(kind === 'header' ? 'w:hdr' : 'w:ftr', { ...ROOT_NAMESPACES }, paragraphs);
721
+ this.doc.pkg.setXml(part, { declaration: null, prolog: [], root, epilog: [] }, CONTENT_TYPE[kind]);
722
+ const rId = await this.doc.pkg.addRelationship(this.doc.mainPart, REL[kind], part);
723
+ await this.doc.refreshRels(this.doc.mainPart);
724
+ await this.doc.refreshRels(part);
725
+ for (const sp of targets) {
726
+ const ref = refOf(sp);
727
+ if (ref)
728
+ ref.attrs['r:id'] = rId;
729
+ else
730
+ insertOrdered(sp, el(kind === 'header' ? 'w:headerReference' : 'w:footerReference', { 'w:type': type, 'r:id': rId }), SECTPR_ORDER);
731
+ }
732
+ if (!this.root.attrs['xmlns:r'])
733
+ this.root.attrs['xmlns:r'] = NS.r;
734
+ await this.dropUnusedParts(current.filter((p) => !!p));
735
+ }
736
+ if (type === 'first')
737
+ for (const sp of targets)
738
+ if (!firstChild(sp, 'w:titlePg'))
739
+ insertOrdered(sp, el('w:titlePg'), SECTPR_ORDER);
740
+ if (type === 'even')
741
+ await this.setEvenAndOdd(true);
742
+ this.doc.touch(part);
743
+ this.changed();
744
+ return part;
745
+ }
746
+ /** Remove headers (see `removeHeaderFooter`). Returns how many references were removed. */
747
+ removeHeader(options = {}) {
748
+ return this.removeHeaderFooter('header', options);
749
+ }
750
+ /** Remove footers (see `removeHeaderFooter`). Returns how many references were removed. */
751
+ removeFooter(options = {}) {
752
+ return this.removeHeaderFooter('footer', options);
753
+ }
754
+ /**
755
+ * Remove headers or footers: of every type unless `type` says which, from every section unless
756
+ * `section` says which (a later section without its own then shows the previous section's). Parts
757
+ * nothing uses any more are deleted. Not recorded as a tracked change.
758
+ */
759
+ async removeHeaderFooter(kind, options = {}) {
760
+ if (this.isStory)
761
+ throw new EditError('Headers and footers are removed from an editor of the main document');
762
+ this.guard?.assert('edit');
763
+ const type = options.type ?? 'all';
764
+ const sections = sectionProperties(this.mainBody());
765
+ const targets = this.sectionTargets(sections, options.section);
766
+ const removed = [];
767
+ let count = 0;
768
+ let firstGone = false;
769
+ let evenGone = false;
770
+ for (const sp of targets) {
771
+ for (const ref of referencesOf(sp, kind)) {
772
+ const t = attr(ref, 'w:type') ?? 'default';
773
+ if (type !== 'all' && t !== type)
774
+ continue;
775
+ sp.children.splice(sp.children.indexOf(ref), 1);
776
+ const part = this.doc.headerFooterPart(attr(ref, 'r:id') ?? '');
777
+ if (part)
778
+ removed.push(part);
779
+ if (t === 'first')
780
+ firstGone = true;
781
+ if (t === 'even')
782
+ evenGone = true;
783
+ count++;
784
+ }
785
+ if (firstGone && !hasFirstPage(sp))
786
+ removeChildren(sp, 'w:titlePg');
787
+ }
788
+ if (!count)
789
+ return 0;
790
+ if (evenGone && !hasEvenPages(sections))
791
+ await this.setEvenAndOdd(false);
792
+ await this.dropUnusedParts(removed);
793
+ this.changed();
794
+ return count;
795
+ }
796
+ mainBody() {
797
+ const body = firstChild(this.doc.documentXml.root, 'w:body');
798
+ if (!body)
799
+ throw new EditError('document has no body');
800
+ return body;
801
+ }
802
+ sectionTargets(sections, section) {
803
+ if (section === undefined)
804
+ return sections;
805
+ const sp = sections[section - 1];
806
+ if (!sp)
807
+ throw new EditError(`There is no section ${section}; the document has ${sections.length}`);
808
+ return [sp];
809
+ }
810
+ /** Delete header/footer parts (and their relationships) that no section refers to any more. */
811
+ async dropUnusedParts(parts) {
812
+ const sections = sectionProperties(this.mainBody());
813
+ const inUse = new Set();
814
+ for (const sp of sections)
815
+ for (const r of [...referencesOf(sp, 'header'), ...referencesOf(sp, 'footer')])
816
+ inUse.add(attr(r, 'r:id') ?? '');
817
+ for (const part of new Set(parts)) {
818
+ const rels = [...this.doc.rels(this.doc.mainPart)].filter(([, rel]) => rel.target === part);
819
+ if (rels.some(([id]) => inUse.has(id)))
820
+ continue;
821
+ for (const [id] of rels)
822
+ await this.doc.pkg.removeRelationship(this.doc.mainPart, id);
823
+ if (this.doc.pkg.has(part))
824
+ this.doc.pkg.removePart(part);
825
+ }
826
+ await this.doc.refreshRels(this.doc.mainPart);
827
+ }
828
+ async setEvenAndOdd(on) {
829
+ const { name, xml } = await ensurePart(this.doc, 'settings');
830
+ const has = !!firstChild(xml.root, 'w:evenAndOddHeaders');
831
+ if (on === has)
832
+ return;
833
+ if (on)
834
+ insertOrdered(xml.root, el('w:evenAndOddHeaders'), SETTINGS_ORDER);
835
+ else
836
+ removeChildren(xml.root, 'w:evenAndOddHeaders');
837
+ this.doc.touch(name);
838
+ }
334
839
  /** Join a paragraph with the one right after it (Backspace at the start of the second). */
335
840
  mergeParagraphs(first, second) {
336
841
  const firstRange = this.paragraphRange(first);
337
842
  const secondRange = this.paragraphRange(second);
338
843
  this.check('edit', { start: firstRange?.end ?? { node: first, offset: 0 }, end: secondRange?.start ?? { node: second, offset: 0 } });
844
+ const track = this.tracking();
845
+ const mark = paragraphMarkRevision(first);
846
+ if (track && !(mark?.kind === 'ins' && attr(mark.el, 'w:author') === this.author)) {
847
+ // Deleting a paragraph mark is recorded; the paragraphs join when the change is accepted.
848
+ markParagraph(first, 'del', track.nextId(), track.who);
849
+ this.changed();
850
+ return;
851
+ }
339
852
  const idx = this.index();
340
853
  const parent = idx.parentOf(first);
341
854
  if (idx.parentOf(second) !== parent)
@@ -427,6 +940,16 @@ export class DocxEditor {
427
940
  const newPara = el('w:p', {}, [...(newPPr ? [newPPr] : []), ...tail]);
428
941
  const parent = idx.parentOf(para);
429
942
  parent.children.splice(indexOfChild(parent, para) + 1, 0, newPara);
943
+ const track = this.tracking();
944
+ // Enter inserts a paragraph mark: the first half's mark is the new one.
945
+ if (track) {
946
+ const newPr = firstChild(newPara, 'w:pPr');
947
+ const newMark = firstChild(newPr, 'w:rPr');
948
+ if (newMark)
949
+ for (const n of ['w:ins', 'w:del'])
950
+ removeChildren(newMark, n);
951
+ markParagraph(para, 'ins', track.nextId(), track.who);
952
+ }
430
953
  this.changed();
431
954
  return newPara;
432
955
  }
@@ -436,13 +959,21 @@ export class DocxEditor {
436
959
  this.check('edit', range);
437
960
  const runs = elements(paragraph, 'w:r');
438
961
  const run = newRun(text, runs[runs.length - 1], format);
439
- paragraph.children.push(run);
962
+ paragraph.children.push(this.placed(run, this.tracking()));
440
963
  this.changed();
441
964
  return run;
442
965
  }
443
966
  /** Delete a range (it may span paragraphs, but not table cells). */
444
967
  deleteRange(range) {
445
968
  this.check('edit', range);
969
+ const track = this.tracking();
970
+ if (track) {
971
+ const { startMark, endMark, idx } = this.trackedCut(range, track);
972
+ replaceMark(idx, startMark, []);
973
+ replaceMark(this.index(), endMark, []);
974
+ this.changed();
975
+ return;
976
+ }
446
977
  // Deleting inside one text node (backspace): edit it in place.
447
978
  if (range.start.node === range.end.node && range.start.node.name === 'w:t') {
448
979
  const current = textContent(range.start.node);
@@ -455,13 +986,33 @@ export class DocxEditor {
455
986
  this.removeRange(range);
456
987
  this.changed();
457
988
  }
458
- /** Replace a range with text formatted like the range's first run. */
989
+ /**
990
+ * Replace a range with text formatted like the range's first run, or with pieces of text that are
991
+ * each formatted like their own `like` run (for example to rewrite a sentence and keep which words
992
+ * were bold). `format` is applied on top.
993
+ */
459
994
  replaceRange(range, text, format) {
460
995
  this.check('edit', range);
461
996
  const index = this.index();
462
997
  const template = index.parentOf(range.start.node);
998
+ // Built before the cut, from the runs as they are now.
999
+ const runs = typeof text === 'string'
1000
+ ? text || format
1001
+ ? [newRun(text, template, format)]
1002
+ : []
1003
+ : text.filter((p) => p.text).map((p) => newRun(p.text, p.like ?? template, format || p.format ? { ...format, ...p.format } : undefined));
1004
+ const track = this.tracking();
1005
+ if (track) {
1006
+ // The old text stays as a deletion; the new text follows it as an insertion.
1007
+ const { startMark, endMark } = this.trackedCut(range, track);
1008
+ replaceMark(this.index(), startMark, []);
1009
+ this.liftOutOfInsertion(endMark, this.index());
1010
+ replaceMark(this.index(), endMark, runs.length ? [insertedRuns(runs, track.nextId(), track.who)] : []);
1011
+ this.changed();
1012
+ return;
1013
+ }
463
1014
  const { startMark, endMark, idx } = this.cut(range);
464
- replaceMark(idx, startMark, text || format ? [newRun(text, template, format)] : []);
1015
+ replaceMark(idx, startMark, runs);
465
1016
  replaceMark(idx, endMark, []);
466
1017
  this.changed();
467
1018
  }
@@ -550,8 +1101,34 @@ export class DocxEditor {
550
1101
  const index = this.index();
551
1102
  const { startMark, endMark } = isolate(index, range);
552
1103
  const idx = this.index();
553
- for (const run of between(idx, startMark, endMark, 'w:r'))
1104
+ const track = this.tracking();
1105
+ for (const run of between(idx, startMark, endMark, 'w:r')) {
1106
+ if (track && !this.inOwnInsertion(run, idx))
1107
+ recordRunFormat(run, track.nextId(), track.who);
554
1108
  applyFormat(run, format);
1109
+ }
1110
+ replaceMark(idx, startMark, []);
1111
+ replaceMark(idx, endMark, []);
1112
+ this.changed();
1113
+ }
1114
+ /** Remove direct character formatting (and character styles, except Hyperlink) from a range. */
1115
+ clearFormatting(range) {
1116
+ this.check('format', range);
1117
+ const index = this.index();
1118
+ const { startMark, endMark } = isolate(index, range);
1119
+ const idx = this.index();
1120
+ const track = this.tracking();
1121
+ for (const run of between(idx, startMark, endMark, 'w:r')) {
1122
+ if (track && !this.inOwnInsertion(run, idx))
1123
+ recordRunFormat(run, track.nextId(), track.who);
1124
+ const rPr = firstChild(run, 'w:rPr');
1125
+ if (!rPr)
1126
+ continue;
1127
+ const keep = rPr.children.filter((c) => c.type === 'element' && ((c.name === 'w:rStyle' && attr(c, 'w:val') === 'Hyperlink') || c.name === 'w:rPrChange'));
1128
+ rPr.children = keep;
1129
+ if (!keep.length)
1130
+ run.children.splice(run.children.indexOf(rPr), 1);
1131
+ }
555
1132
  replaceMark(idx, startMark, []);
556
1133
  replaceMark(idx, endMark, []);
557
1134
  this.changed();
@@ -607,7 +1184,10 @@ export class DocxEditor {
607
1184
  const ref = typeof where === 'object' ? (where.before ?? where.after) : undefined;
608
1185
  this.check('edit', ref ? { start: { node: ref, offset: 0 }, end: { node: ref, offset: 0 } } : undefined);
609
1186
  const pPr = options.style ? [el('w:pPr', {}, [el('w:pStyle', { 'w:val': options.style })])] : [];
610
- const para = el('w:p', {}, [...pPr, ...(text ? [newRun(text, undefined, options.format)] : [])]);
1187
+ const track = this.tracking();
1188
+ const para = el('w:p', {}, [...pPr, ...(text ? [this.placed(newRun(text, undefined, options.format), track)] : [])]);
1189
+ if (track)
1190
+ markParagraph(para, 'ins', track.nextId(), track.who);
611
1191
  const body = this.body;
612
1192
  if (where === 'start')
613
1193
  body.children.unshift(para);
@@ -628,6 +1208,18 @@ export class DocxEditor {
628
1208
  }
629
1209
  deleteParagraph(paragraph) {
630
1210
  this.check('edit', this.paragraphRange(paragraph) ?? { start: { node: paragraph, offset: 0 }, end: { node: paragraph, offset: 0 } });
1211
+ const track = this.tracking();
1212
+ const mark = paragraphMarkRevision(paragraph);
1213
+ const ownNew = mark?.kind === 'ins' && attr(mark.el, 'w:author') === this.author;
1214
+ if (track && !ownNew) {
1215
+ // The text is marked deleted and so is the paragraph mark; Word joins them away on accept.
1216
+ const tidx = this.index();
1217
+ for (const run of findAll(paragraph, 'w:r'))
1218
+ deleteRun(run, (n) => tidx.parent.get(n), track.nextId, track.who);
1219
+ markParagraph(paragraph, 'del', track.nextId(), track.who);
1220
+ this.changed();
1221
+ return;
1222
+ }
631
1223
  const idx = this.index();
632
1224
  const parent = idx.parentOf(paragraph);
633
1225
  // A table cell must keep at least one paragraph.
@@ -638,8 +1230,285 @@ export class DocxEditor {
638
1230
  parent.children.splice(indexOfChild(parent, paragraph), 1);
639
1231
  this.changed();
640
1232
  }
1233
+ // ---- copies and tables -----------------------------------------------------------------------
1234
+ /** The block (paragraph, table or content control) of the body that holds `node`. */
1235
+ topBlock(node, idx = this.index()) {
1236
+ let n = node;
1237
+ for (let p = idx.parent.get(n); p && p !== this.body; p = idx.parent.get(p))
1238
+ n = p;
1239
+ if (idx.parent.get(n) !== this.body)
1240
+ throw new EditError('That paragraph is not in the body of the document');
1241
+ return n;
1242
+ }
1243
+ /** Put new blocks into the body before/after the block holding `ref`, or at the start or end. */
1244
+ placeBlocks(blocks, where) {
1245
+ const body = this.body;
1246
+ const sect = firstChild(body, 'w:sectPr');
1247
+ let at;
1248
+ if (where === 'start')
1249
+ at = 0;
1250
+ else if (where === 'end')
1251
+ at = sect ? body.children.indexOf(sect) : body.children.length;
1252
+ else {
1253
+ const ref = where.before ?? where.after;
1254
+ if (!ref)
1255
+ throw new EditError('Pass the paragraph to place it before or after');
1256
+ const top = this.topBlock(ref);
1257
+ at = body.children.indexOf(top) + (where.after ? 1 : 0);
1258
+ }
1259
+ body.children.splice(at, 0, ...blocks);
1260
+ // Word wants a paragraph after a table that ends the document.
1261
+ const last = blocks[blocks.length - 1];
1262
+ const next = body.children[at + blocks.length];
1263
+ if (last?.name === 'w:tbl' && (!next || (next.type === 'element' && next.name === 'w:sectPr')))
1264
+ body.children.splice(at + blocks.length, 0, el('w:p'));
1265
+ }
1266
+ /** Permission to add content next to `where`. */
1267
+ checkPlace(where) {
1268
+ const ref = typeof where === 'object' ? (where.before ?? where.after) : undefined;
1269
+ this.check('edit', ref ? { start: { node: ref, offset: 0 }, end: { node: ref, offset: 0 } } : undefined);
1270
+ }
1271
+ /**
1272
+ * Copy the body's blocks from the one holding `from` to the one holding `to` (a table is copied
1273
+ * whole) and put the copies at `where`, with their formatting, lists, tables and pictures. Lists
1274
+ * in the copy number from the start again unless `restartLists` is false, and `pageBreak` starts
1275
+ * the copy on a new page. What may exist only once (bookmarks, comment anchors, note references)
1276
+ * is left out of the copy and counted in `dropped`.
1277
+ */
1278
+ async copyBlocks(from, to, where, options = {}) {
1279
+ this.checkPlace(where);
1280
+ const idx = this.index();
1281
+ const kids = this.body.children;
1282
+ const first = kids.indexOf(this.topBlock(from, idx));
1283
+ const last = kids.indexOf(this.topBlock(to, idx));
1284
+ if (last < first)
1285
+ throw new EditError('The last paragraph to copy comes before the first');
1286
+ const originals = kids.slice(first, last + 1).filter((c) => c.type === 'element' && c.name !== 'w:sectPr');
1287
+ const copies = originals.map(cloneElement);
1288
+ // Ids that must stay unique in the document.
1289
+ const revision = nextRevisionId(this.root);
1290
+ let drawing = 0;
1291
+ for (const d of findAll(this.root, 'wp:docPr'))
1292
+ drawing = Math.max(drawing, Number(attr(d, 'id')) || 0);
1293
+ const sdtIds = new Set(findAll(this.root, 'w:sdtPr').map((s) => attr(firstChild(s, 'w:id'), 'w:val')));
1294
+ const sdt = () => {
1295
+ let id;
1296
+ do
1297
+ id = String(1 + Math.floor(Math.random() * 2147483646));
1298
+ while (sdtIds.has(id));
1299
+ sdtIds.add(id);
1300
+ return id;
1301
+ };
1302
+ const dropped = { comments: 0, notes: 0, bookmarks: 0 };
1303
+ for (const c of copies)
1304
+ cleanCopy(c, { revision, drawing: () => String(++drawing), sdt }, dropped);
1305
+ // Lists in the copy: a new list of the same look for each list copied, so numbering restarts.
1306
+ if (options.restartLists ?? true) {
1307
+ const styleNumId = (s) => this.doc.styles.get(s)?.pPr.numId;
1308
+ const renumbered = new Map();
1309
+ for (const p of copies.flatMap((c) => (c.name === 'w:p' ? [c] : findAll(c, 'w:p')))) {
1310
+ const pPr = firstChild(p, 'w:pPr');
1311
+ const numPr = firstChild(pPr, 'w:numPr');
1312
+ const styleId = attr(firstChild(pPr, 'w:pStyle'), 'w:val');
1313
+ const numId = numPr ? attr(firstChild(numPr, 'w:numId'), 'w:val') : styleId ? this.doc.styles.get(styleId)?.pPr.numId : undefined;
1314
+ if (!numId || numId === '0')
1315
+ continue;
1316
+ let fresh = renumbered.get(numId);
1317
+ if (!fresh) {
1318
+ const abstractId = this.doc.numbering.abstractFor(numId, styleNumId)?.id;
1319
+ fresh = await createList(this.doc, { format: 'keep', levels: new Set(), base: { numId, abstractId } });
1320
+ renumbered.set(numId, fresh);
1321
+ }
1322
+ const ilvl = numPr ? attr(firstChild(numPr, 'w:ilvl'), 'w:val') ?? '0' : String(styleId ? (this.doc.styles.get(styleId)?.pPr.ilvl ?? 0) : 0);
1323
+ const target = ensureChild(p, 'w:pPr');
1324
+ if (p.children[0] !== target) {
1325
+ p.children.splice(p.children.indexOf(target), 1);
1326
+ p.children.unshift(target);
1327
+ }
1328
+ removeChildren(target, 'w:numPr');
1329
+ insertOrdered(target, el('w:numPr', {}, [el('w:ilvl', { 'w:val': ilvl }), el('w:numId', { 'w:val': fresh })]), PPR_ORDER);
1330
+ }
1331
+ }
1332
+ const blocks = [...copies];
1333
+ if (options.pageBreak) {
1334
+ const head = blocks[0];
1335
+ if (head?.name === 'w:p') {
1336
+ const pPr = ensureChild(head, 'w:pPr');
1337
+ if (head.children[0] !== pPr) {
1338
+ head.children.splice(head.children.indexOf(pPr), 1);
1339
+ head.children.unshift(pPr);
1340
+ }
1341
+ removeChildren(pPr, 'w:pageBreakBefore');
1342
+ insertOrdered(pPr, el('w:pageBreakBefore'), PPR_ORDER);
1343
+ }
1344
+ else
1345
+ blocks.unshift(el('w:p', {}, [el('w:pPr', {}, [el('w:pageBreakBefore')])]));
1346
+ }
1347
+ const track = this.tracking();
1348
+ if (track)
1349
+ for (const b of blocks)
1350
+ markInserted(b, track.nextId, track.who, (p) => markParagraph(p, 'ins', track.nextId(), track.who));
1351
+ this.placeBlocks(blocks, where);
1352
+ this.changed();
1353
+ return { blocks, dropped };
1354
+ }
1355
+ /**
1356
+ * Insert a table of text (`rows` of cell texts; "\n" in a cell starts a new paragraph) before or
1357
+ * after the block holding a paragraph, or at the start or end. It spans the text width.
1358
+ */
1359
+ insertTable(where, rows, options = {}) {
1360
+ this.checkPlace(where);
1361
+ const columns = Math.max(0, ...rows.map((r) => r.length));
1362
+ if (!rows.length || !columns)
1363
+ throw new EditError('A table needs at least one row and one column');
1364
+ if (rows.length > 500 || columns > 63)
1365
+ throw new EditError('A table can have at most 500 rows and 63 columns');
1366
+ if (options.widths && (options.widths.length !== columns || options.widths.some((w) => !(w > 0)))) {
1367
+ throw new EditError(`widths needs ${columns} positive numbers, one per column`);
1368
+ }
1369
+ const sections = sectionProperties(this.body);
1370
+ const total = textWidth(sections[sections.length - 1]);
1371
+ const grid = this.doc.styles.get('TableGrid') ? 'TableGrid' : undefined;
1372
+ const style = options.style ?? (options.borders === false ? undefined : grid);
1373
+ if (options.style && !this.doc.styles.get(options.style))
1374
+ throw new EditError(`There is no table style "${options.style}"`);
1375
+ const track = this.tracking();
1376
+ const table = buildTable(rows, columnWidths(columns, total, options.widths), {
1377
+ header: !!options.header,
1378
+ style,
1379
+ borders: options.borders !== false,
1380
+ align: options.align,
1381
+ paragraph: (text, header) => el('w:p', {}, [
1382
+ // Without a table style, cells get Table Grid's tight spacing.
1383
+ ...(style ? [] : [el('w:pPr', {}, [el('w:spacing', { 'w:before': '0', 'w:after': '0' })])]),
1384
+ ...(text ? [newRun(text, undefined, header ? { bold: true } : undefined)] : []),
1385
+ ]),
1386
+ });
1387
+ if (track)
1388
+ markInserted(table, track.nextId, track.who, (p) => markParagraph(p, 'ins', track.nextId(), track.who));
1389
+ this.placeBlocks([table], where);
1390
+ this.changed();
1391
+ return table;
1392
+ }
1393
+ /** The table holding a paragraph (the innermost one). */
1394
+ tableOf(paragraph) {
1395
+ const idx = this.index();
1396
+ const table = idx.ancestor(paragraph, 'w:tbl');
1397
+ if (!table)
1398
+ throw new EditError('That paragraph is not in a table');
1399
+ return table;
1400
+ }
1401
+ /** Permission to change a table: its whole text. */
1402
+ checkTable(table) {
1403
+ const paras = findAll(table, 'w:p');
1404
+ const a = this.paragraphRange(paras[0]);
1405
+ const b = this.paragraphRange(paras[paras.length - 1]);
1406
+ this.check('edit', a && b ? { start: a.start, end: b.end } : { start: { node: table, offset: 0 }, end: { node: table, offset: 0 } });
1407
+ }
1408
+ /**
1409
+ * Insert rows into a table before row `at` (0-based; the row count appends). Each new row copies
1410
+ * the formatting of the row next to it and gets the texts of one entry of `rows`.
1411
+ */
1412
+ insertTableRows(table, at, rows) {
1413
+ this.checkTable(table);
1414
+ const existing = elements(table, 'w:tr');
1415
+ if (!Number.isInteger(at) || at < 0 || at > existing.length)
1416
+ throw new EditError(`Rows go from 0 to ${existing.length}`);
1417
+ if (!rows.length)
1418
+ throw new EditError('Pass at least one row');
1419
+ const template = existing[at - 1] ?? existing[at];
1420
+ if (!template)
1421
+ throw new EditError('The table has no rows to copy the formatting of');
1422
+ const cells = elements(template, 'w:tc');
1423
+ const widest = Math.max(...rows.map((r) => r.length));
1424
+ if (widest > cells.length)
1425
+ throw new EditError(`That row has ${cells.length} cells, so a new row can have at most ${cells.length} texts`);
1426
+ const track = this.tracking();
1427
+ const made = rows.map((texts) => {
1428
+ const row = cloneElement(template);
1429
+ delete row.attrs['w14:paraId'];
1430
+ delete row.attrs['w14:textId'];
1431
+ // Only the first rows of a table repeat as a header.
1432
+ const trPr = firstChild(row, 'w:trPr');
1433
+ if (trPr && at > 0) {
1434
+ removeChildren(trPr, 'w:tblHeader');
1435
+ removeChildren(trPr, 'w:ins');
1436
+ removeChildren(trPr, 'w:del');
1437
+ }
1438
+ elements(row, 'w:tc').forEach((tc, i) => {
1439
+ const tcPr = firstChild(tc, 'w:tcPr');
1440
+ if (tcPr)
1441
+ removeChildren(tcPr, 'w:vMerge');
1442
+ const p = firstChild(tc, 'w:p') ?? el('w:p');
1443
+ const pPr = firstChild(p, 'w:pPr');
1444
+ const runTemplate = findAll(p, 'w:r')[0];
1445
+ const text = texts[i] ?? '';
1446
+ const lines = text.split('\n');
1447
+ const paragraphs = lines.map((line) => el('w:p', {}, [...(pPr ? [cloneElement(pPr)] : []), ...(line ? [newRun(line, runTemplate)] : [])]));
1448
+ tc.children = [...(tcPr ? [tcPr] : []), ...paragraphs];
1449
+ });
1450
+ if (track)
1451
+ markInserted(row, track.nextId, track.who, (p) => markParagraph(p, 'ins', track.nextId(), track.who));
1452
+ return row;
1453
+ });
1454
+ const anchor = existing[at];
1455
+ table.children.splice(anchor ? table.children.indexOf(anchor) : table.children.length, 0, ...made);
1456
+ this.changed();
1457
+ return made;
1458
+ }
1459
+ /** Delete rows `from` to `to` (0-based, inclusive) of a table; deleting them all deletes the table. */
1460
+ deleteTableRows(table, from, to = from) {
1461
+ this.checkTable(table);
1462
+ const rows = elements(table, 'w:tr');
1463
+ if (!Number.isInteger(from) || !Number.isInteger(to) || from < 0 || to >= rows.length || to < from)
1464
+ throw new EditError(`Rows go from 0 to ${rows.length - 1}`);
1465
+ if (from === 0 && to === rows.length - 1) {
1466
+ this.deleteTable(table);
1467
+ return;
1468
+ }
1469
+ const doomed = rows.slice(from, to + 1);
1470
+ const track = this.tracking();
1471
+ if (track)
1472
+ for (const row of doomed)
1473
+ this.markRowDeleted(row, track);
1474
+ else
1475
+ table.children = table.children.filter((c) => !(c.type === 'element' && doomed.includes(c)));
1476
+ this.changed();
1477
+ }
1478
+ /** Delete a whole table. */
1479
+ deleteTable(table) {
1480
+ this.checkTable(table);
1481
+ const track = this.tracking();
1482
+ if (track)
1483
+ for (const row of elements(table, 'w:tr'))
1484
+ this.markRowDeleted(row, track);
1485
+ else {
1486
+ const idx = this.index();
1487
+ const parent = idx.parentOf(table);
1488
+ parent.children.splice(indexOfChild(parent, table), 1);
1489
+ // A table cell, and the body, must keep a paragraph.
1490
+ if (parent.name === 'w:tc' && !elements(parent, 'w:p').length)
1491
+ parent.children.push(el('w:p'));
1492
+ if (parent === this.body && !elements(parent).some((c) => c.name === 'w:p' || c.name === 'w:tbl' || c.name === 'w:sdt')) {
1493
+ const sect = firstChild(parent, 'w:sectPr');
1494
+ parent.children.splice(sect ? parent.children.indexOf(sect) : parent.children.length, 0, el('w:p'));
1495
+ }
1496
+ }
1497
+ this.changed();
1498
+ }
1499
+ markRowDeleted(row, track) {
1500
+ const idx = this.index();
1501
+ for (const run of findAll(row, 'w:r'))
1502
+ deleteRun(run, (n) => idx.parent.get(n), track.nextId, track.who);
1503
+ for (const p of findAll(row, 'w:p'))
1504
+ markParagraph(p, 'del', track.nextId(), track.who);
1505
+ markRow(row, 'del', track.nextId(), track.who);
1506
+ }
641
1507
  setParagraphStyle(paragraph, styleId) {
642
1508
  this.check('format', this.paragraphRange(paragraph));
1509
+ const track = this.tracking();
1510
+ if (track)
1511
+ recordParagraphFormat(paragraph, track.nextId(), track.who, PPR_ORDER);
643
1512
  const pPr = ensureChild(paragraph, 'w:pPr');
644
1513
  if (paragraph.children[0] !== pPr) {
645
1514
  paragraph.children.splice(paragraph.children.indexOf(pPr), 1);
@@ -649,6 +1518,185 @@ export class DocxEditor {
649
1518
  insertOrdered(pPr, el('w:pStyle', { 'w:val': styleId }), PPR_ORDER);
650
1519
  this.changed();
651
1520
  }
1521
+ /** Change paragraph formatting: alignment, direction, indents, spacing and keep rules. */
1522
+ formatParagraph(paragraph, format) {
1523
+ this.check('format', this.paragraphRange(paragraph));
1524
+ const track = this.tracking();
1525
+ if (track)
1526
+ recordParagraphFormat(paragraph, track.nextId(), track.who, PPR_ORDER);
1527
+ const pPr = ensureChild(paragraph, 'w:pPr');
1528
+ if (paragraph.children[0] !== pPr) {
1529
+ paragraph.children.splice(paragraph.children.indexOf(pPr), 1);
1530
+ paragraph.children.unshift(pPr);
1531
+ }
1532
+ const twips = (pt) => String(Math.round(pt * 20));
1533
+ const onOff = (name, on) => {
1534
+ if (on === undefined)
1535
+ return;
1536
+ removeChildren(pPr, name);
1537
+ insertOrdered(pPr, on ? el(name) : el(name, { 'w:val': '0' }), PPR_ORDER);
1538
+ };
1539
+ onOff('w:keepNext', format.keepWithNext);
1540
+ onOff('w:keepLines', format.keepLinesTogether);
1541
+ onOff('w:pageBreakBefore', format.pageBreakBefore);
1542
+ if (format.direction)
1543
+ onOff('w:bidi', format.direction === 'rtl');
1544
+ if (format.align) {
1545
+ removeChildren(pPr, 'w:jc');
1546
+ // In a right-to-left paragraph Word reads left and right as start and end, so a visually
1547
+ // right-aligned RTL paragraph is stored as "left".
1548
+ const bidi = firstChild(pPr, 'w:bidi');
1549
+ const rtl = !!bidi && attr(bidi, 'w:val') !== '0' && attr(bidi, 'w:val') !== 'false';
1550
+ const visual = format.align === 'justify' ? 'both' : format.align;
1551
+ const jc = rtl && visual === 'left' ? 'right' : rtl && visual === 'right' ? 'left' : visual;
1552
+ insertOrdered(pPr, el('w:jc', { 'w:val': jc }), PPR_ORDER);
1553
+ }
1554
+ if (format.indentLeft !== undefined || format.indentRight !== undefined || format.indentFirstLine !== undefined) {
1555
+ const ind = ensureOrdered(pPr, 'w:ind', PPR_ORDER);
1556
+ if (format.indentLeft !== undefined) {
1557
+ delete ind.attrs['w:start'];
1558
+ ind.attrs['w:left'] = twips(format.indentLeft);
1559
+ }
1560
+ if (format.indentRight !== undefined) {
1561
+ delete ind.attrs['w:end'];
1562
+ ind.attrs['w:right'] = twips(format.indentRight);
1563
+ }
1564
+ if (format.indentFirstLine !== undefined) {
1565
+ delete ind.attrs['w:firstLine'];
1566
+ delete ind.attrs['w:hanging'];
1567
+ if (format.indentFirstLine >= 0)
1568
+ ind.attrs['w:firstLine'] = twips(format.indentFirstLine);
1569
+ else
1570
+ ind.attrs['w:hanging'] = twips(-format.indentFirstLine);
1571
+ }
1572
+ }
1573
+ if (format.spaceBefore !== undefined || format.spaceAfter !== undefined || format.lineSpacing !== undefined) {
1574
+ const sp = ensureOrdered(pPr, 'w:spacing', PPR_ORDER);
1575
+ if (format.spaceBefore !== undefined) {
1576
+ delete sp.attrs['w:beforeAutospacing'];
1577
+ sp.attrs['w:before'] = twips(format.spaceBefore);
1578
+ }
1579
+ if (format.spaceAfter !== undefined) {
1580
+ delete sp.attrs['w:afterAutospacing'];
1581
+ sp.attrs['w:after'] = twips(format.spaceAfter);
1582
+ }
1583
+ if (format.lineSpacing !== undefined) {
1584
+ sp.attrs['w:line'] = String(Math.round(format.lineSpacing * 240));
1585
+ sp.attrs['w:lineRule'] = 'auto';
1586
+ }
1587
+ }
1588
+ this.changed();
1589
+ }
1590
+ // ---- lists --------------------------------------------------------------------------------
1591
+ /** The list paragraphs of the body with their labels ("1.", "a)", "•"), keyed by w:p. */
1592
+ listItems() {
1593
+ return listItems(this.doc, this.paragraphs());
1594
+ }
1595
+ /**
1596
+ * Change list formatting of paragraphs:
1597
+ * - `format`: make them one list in that format ('bullet', 'decimal' 1., 'decimalParen' 1),
1598
+ * 'lowerLetter' a., 'upperLetter' A., 'lowerRoman' i., 'upperRoman' I.), numbered from `start`
1599
+ * (default 1). Paragraphs already in a list keep its indentation and their level. 'none' takes
1600
+ * them out of their list.
1601
+ * - `start` alone: restart the numbering, keeping the format.
1602
+ * - `level` (0–8): the list level (indent); alone, only the level changes.
1603
+ * - `sameListAs`: join the list of that paragraph, continuing its numbering.
1604
+ * Returns the numId the paragraphs now use (undefined after 'none').
1605
+ */
1606
+ async setList(paragraphs, options) {
1607
+ const { format, level, start, sameListAs } = options;
1608
+ if (paragraphs.length === 0)
1609
+ throw new EditError('setList needs at least one paragraph');
1610
+ if (level !== undefined && (!Number.isInteger(level) || level < 0 || level > 8))
1611
+ throw new EditError('List levels go from 0 to 8');
1612
+ if (start !== undefined && (!Number.isInteger(start) || start < 0 || start > 32767))
1613
+ throw new EditError('start must be a whole number from 0 to 32767');
1614
+ const all = new Map(this.paragraphs().map((p) => [p.el, p]));
1615
+ const paras = paragraphs.map((el) => {
1616
+ const p = all.get(el);
1617
+ if (!p)
1618
+ throw new EditError('setList only works on paragraphs of the document body');
1619
+ return p;
1620
+ });
1621
+ for (const p of paras)
1622
+ this.check('format', this.paragraphRange(p) ?? { start: { node: p.el, offset: 0 }, end: { node: p.el, offset: 0 } });
1623
+ if (format === 'none') {
1624
+ if (sameListAs || start !== undefined || level !== undefined)
1625
+ throw new EditError("format 'none' cannot be combined with other list options");
1626
+ for (const p of paras)
1627
+ this.writeNumPr(p, undefined);
1628
+ this.changed();
1629
+ return undefined;
1630
+ }
1631
+ if (sameListAs) {
1632
+ const target = all.get(sameListAs)?.numbering;
1633
+ if (!target)
1634
+ throw new EditError('The paragraph to join is not in a list yet: make it one first (with a format), then join the others to it');
1635
+ if (start !== undefined)
1636
+ throw new EditError("sameListAs continues that list's numbering; to number from a given value, use start without sameListAs");
1637
+ if (format !== undefined) {
1638
+ // Naming the list's own format is harmless; another format would start a different list.
1639
+ const styleNumId = (s) => this.doc.styles.get(s)?.pPr.numId;
1640
+ const lvl = this.doc.numbering.level(target.numId, level ?? target.ilvl, styleNumId);
1641
+ if (!lvl || !levelMatches(lvl, format)) {
1642
+ throw new EditError(`That list is ${lvl ? describeLevel(lvl) : 'in another format'}; to continue it leave out format, or to start a new list use format without sameListAs`);
1643
+ }
1644
+ }
1645
+ for (const p of paras)
1646
+ this.writeNumPr(p, { numId: target.numId, ilvl: level ?? (p.numbering ? p.numbering.ilvl : target.ilvl) });
1647
+ this.changed();
1648
+ return target.numId;
1649
+ }
1650
+ const first = paras.find((p) => p.numbering)?.numbering;
1651
+ if (format === undefined) {
1652
+ if (!first)
1653
+ throw new EditError('These paragraphs are not in a list; pass a format to make them one');
1654
+ if (start === undefined) {
1655
+ if (level === undefined)
1656
+ throw new EditError('Nothing to change: pass format, level, start or sameListAs');
1657
+ for (const p of paras) {
1658
+ if (!p.numbering)
1659
+ throw new EditError('Some of these paragraphs are not in a list; pass a format to make them one');
1660
+ this.writeNumPr(p, { numId: p.numbering.numId, ilvl: level });
1661
+ }
1662
+ this.changed();
1663
+ return first.numId;
1664
+ }
1665
+ }
1666
+ const ilvlOf = (p) => level ?? p.numbering?.ilvl ?? 0;
1667
+ const styleNumId = (s) => this.doc.styles.get(s)?.pPr.numId;
1668
+ const base = first ? { numId: first.numId, abstractId: this.doc.numbering.abstractFor(first.numId, styleNumId)?.id } : undefined;
1669
+ const numId = await createList(this.doc, {
1670
+ format: format ?? 'keep',
1671
+ levels: new Set(paras.map(ilvlOf)),
1672
+ ...(start !== undefined ? { start } : {}),
1673
+ ...(base ? { base } : {}),
1674
+ });
1675
+ for (const p of paras)
1676
+ this.writeNumPr(p, { numId, ilvl: ilvlOf(p) });
1677
+ this.changed();
1678
+ return numId;
1679
+ }
1680
+ /** Set or clear a paragraph's w:numPr (clearing style-given numbering with numId 0). */
1681
+ writeNumPr(para, num) {
1682
+ const p = para.el;
1683
+ const track = this.tracking();
1684
+ if (track)
1685
+ recordParagraphFormat(p, track.nextId(), track.who, PPR_ORDER);
1686
+ const pPr = ensureChild(p, 'w:pPr');
1687
+ if (p.children[0] !== pPr) {
1688
+ p.children.splice(p.children.indexOf(pPr), 1);
1689
+ p.children.unshift(pPr);
1690
+ }
1691
+ removeChildren(pPr, 'w:numPr');
1692
+ if (num) {
1693
+ insertOrdered(pPr, el('w:numPr', {}, [el('w:ilvl', { 'w:val': String(num.ilvl) }), el('w:numId', { 'w:val': num.numId })]), PPR_ORDER);
1694
+ return;
1695
+ }
1696
+ const styleNum = para.styleId ? this.doc.styles.get(para.styleId)?.pPr.numId : undefined;
1697
+ if (styleNum && styleNum !== '0')
1698
+ insertOrdered(pPr, el('w:numPr', {}, [el('w:numId', { 'w:val': '0' })]), PPR_ORDER);
1699
+ }
652
1700
  // ---- hyperlinks and bookmarks -------------------------------------------------------------
653
1701
  /** Turn a range (within one paragraph) into a hyperlink to a URL or a bookmark. */
654
1702
  async addHyperlink(range, target, tooltip) {
@@ -657,8 +1705,8 @@ export class DocxEditor {
657
1705
  throw new EditError(`Refusing link to "${target.url}": unsupported scheme`);
658
1706
  const attrs = {};
659
1707
  if ('url' in target) {
660
- attrs['r:id'] = await this.doc.pkg.addRelationship(this.doc.mainPart, REL.hyperlink, target.url, true);
661
- await this.doc.refreshRels(this.doc.mainPart);
1708
+ attrs['r:id'] = await this.doc.pkg.addRelationship(this.part, REL.hyperlink, target.url, true);
1709
+ await this.doc.refreshRels(this.part);
662
1710
  }
663
1711
  else
664
1712
  attrs['w:anchor'] = target.bookmark;
@@ -688,8 +1736,49 @@ export class DocxEditor {
688
1736
  this.changed();
689
1737
  return link;
690
1738
  }
1739
+ /** Point an existing w:hyperlink at another URL or a bookmark (same scheme rules as `addHyperlink`). */
1740
+ async setHyperlinkTarget(hyperlink, target) {
1741
+ this.check('link');
1742
+ if ('url' in target && !/^(https?|mailto|tel|ftp):/i.test(target.url))
1743
+ throw new EditError(`Refusing link to "${target.url}": unsupported scheme`);
1744
+ const old = hyperlink.attrs['r:id'];
1745
+ if ('url' in target) {
1746
+ hyperlink.attrs['r:id'] = await this.doc.pkg.addRelationship(this.part, REL.hyperlink, target.url, true);
1747
+ delete hyperlink.attrs['w:anchor'];
1748
+ if (!this.root.attrs['xmlns:r'])
1749
+ this.root.attrs['xmlns:r'] = NS.r;
1750
+ }
1751
+ else {
1752
+ hyperlink.attrs['w:anchor'] = target.bookmark;
1753
+ delete hyperlink.attrs['r:id'];
1754
+ }
1755
+ // The old tooltip described the old target.
1756
+ delete hyperlink.attrs['w:tooltip'];
1757
+ delete hyperlink.attrs['w:docLocation'];
1758
+ await this.dropHyperlinkRel(old);
1759
+ this.changed();
1760
+ }
1761
+ /** Remove a hyperlink relationship that nothing in this part refers to any more. */
1762
+ async dropHyperlinkRel(id) {
1763
+ if (id) {
1764
+ const used = findAll(this.root, 'w:hyperlink').some((h) => h.attrs['r:id'] === id);
1765
+ const rel = this.doc.rels(this.part).get(id);
1766
+ if (!used && rel && rel.external)
1767
+ await this.doc.pkg.removeRelationship(this.part, id);
1768
+ }
1769
+ await this.doc.refreshRels(this.part);
1770
+ }
1771
+ /** Set the alt text (wp:docPr/@descr) of a picture or drawing. */
1772
+ setImageAlt(drawing, text) {
1773
+ this.check('edit');
1774
+ const props = drawing.name === 'wp:docPr' ? drawing : findAll(drawing, 'wp:docPr')[0];
1775
+ if (!props)
1776
+ throw new EditError('This object has no description to edit');
1777
+ props.attrs['descr'] = text;
1778
+ this.changed();
1779
+ }
691
1780
  /** Unwrap a w:hyperlink, keeping its text. */
692
- removeHyperlink(link) {
1781
+ async removeHyperlink(link) {
693
1782
  this.check('link');
694
1783
  const idx = this.index();
695
1784
  const parent = idx.parentOf(link);
@@ -702,10 +1791,11 @@ export class DocxEditor {
702
1791
  }
703
1792
  parent.children.splice(indexOfChild(parent, link), 1, ...runs);
704
1793
  this.changed();
1794
+ await this.dropHyperlinkRel(attr(link, 'r:id'));
705
1795
  }
706
1796
  /** Every w:hyperlink in the body with its target. */
707
1797
  hyperlinks() {
708
- const rels = this.doc.rels(this.doc.mainPart);
1798
+ const rels = this.doc.rels(this.part);
709
1799
  return findAll(this.body, 'w:hyperlink').map((h) => {
710
1800
  const rId = attr(h, 'r:id');
711
1801
  return { el: h, url: rId ? rels.get(rId)?.target : undefined, anchor: attr(h, 'w:anchor'), tooltip: attr(h, 'w:tooltip'), text: textContent(h) };
@@ -1119,3 +2209,12 @@ function localDate(d) {
1119
2209
  return `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())}T${pad(d.getHours())}:${pad(d.getMinutes())}:${pad(d.getSeconds())}Z`;
1120
2210
  }
1121
2211
  export { EditError };
2212
+ /** The child `name` of `parent`, created in schema order when missing. */
2213
+ function ensureOrdered(parent, name, order) {
2214
+ const existing = firstChild(parent, name);
2215
+ if (existing)
2216
+ return existing;
2217
+ const node = el(name);
2218
+ insertOrdered(parent, node, order);
2219
+ return node;
2220
+ }