docxkeun 0.2.0 → 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.
package/CHANGELOG.md CHANGED
@@ -2,6 +2,32 @@
2
2
 
3
3
  All notable changes to docxkeun and docxkeun-fonts. Versions follow [semantic versioning](https://semver.org); while the version is 0.x, minor versions may contain breaking changes.
4
4
 
5
+ ## 0.3.0 (2026-11-23)
6
+
7
+ ### docxkeun
8
+
9
+ - **AI effect styles:** `aiActivity: { style }` and `viewer.activity.style` pick how the paragraph the AI is changing looks: `highlight` (the band, as before), `words` (the letters themselves shimmer), `underline`, `edge`, `spotlight`, `quiet` or `sparkles`. `ACTIVITY_STYLES` lists them with labels for a picker. The mark that stays after a change follows the style: a soft tint on the paragraph (`highlight`), glowing changed words (`words`), underlined changed words (`underline`), or the ✦ margin bar (the others); `marks: false` / `viewer.activity.marksShown` turn the marks off. Every style has a still form for `animate: false` and `prefers-reduced-motion`.
10
+ - The AI's marks now build up over a run of changes instead of showing only the latest one: each follows its paragraph as others are added or removed, a paragraph changed twice is marked against its text before the first change, and `clearMarks()` starts over. `ParagraphChange.from` gives a changed paragraph's index in the old text.
11
+ - The AI's marks and effects now follow zoom changes and the comment column's width (they kept their old positions before), and the change map's ticks show the text from before.
12
+ - **Tables:** `DocxEditor.insertTable()` adds a table that spans the text width, with an optional bold header row that repeats on each page, relative column widths and alignment. It uses Word's "Table Grid" style when the document has it, or plain borders. `insertTableRows()` adds rows formatted like the row they copy, `deleteTableRows()` and `deleteTable()` remove them, and `tableOf()` finds the table a cell paragraph is in. All of them record tracked changes when Track Changes is on, and rejecting an inserted table removes it whole.
13
+ - **Copying content:** `DocxEditor.copyBlocks()` copies paragraphs and tables with their formatting, lists and pictures, optionally starting on a new page. Lists in the copy start again at 1 (or continue with `restartLists: false`). Bookmarks, comment anchors and note references are left out and counted, and ids that must be unique are renewed.
14
+ - `DocxEditor.replaceRange()` also takes pieces of text, each formatted like a run you point to (`{ text, like, format }`), so rewritten text can keep which words were bold, underlined or coloured.
15
+ - `setList` with `sameListAs` now accepts the joined list's own `format`, and its errors say what to do instead: join a paragraph that is not in a list yet by making it one first; use `start` without `sameListAs` to number from a given value.
16
+
17
+ ### docxkeun chat
18
+
19
+ - "Appearance" also picks the effect style and whether marks stay after each change, with a live sample. A reply's marks cover all its changes; opening a document or undoing a reply clears them.
20
+ - Claude now sees which words are bold, italic, underlined, struck through, superscript or subscript, and keeps them when it rewrites or translates text (it used to flatten a rewritten paragraph to one formatting).
21
+ - Claude can now copy content with its formatting and make and change tables, so "translate this document onto a new page" keeps the tables and lists instead of retyping them as plain text.
22
+
23
+ ### docxkeun-mcp 0.2.0
24
+
25
+ - The live preview's header has a **Style** list and a **Marks** switch next to "AI effects", remembered in the browser. Marks build up while the AI works on a document and start over when you open another one.
26
+ - New tools: `copy_paragraphs` copies paragraphs and tables with their formatting and lists (for example onto a new page, to translate a document), `insert_table` makes a table, and `edit_table` adds or deletes rows or deletes a table.
27
+ - `set_list` explains how to join paragraphs that are not next to each other into one list, and accepts the list's own format with `sameListAs`.
28
+ - **Text formatting is visible and kept.** `read_document` tags text formatted differently from the rest of its paragraph (`<b>`, `<i>`, `<u>`, `<s>`, `<sup>`, `<sub>`) and names a paragraph's alignment and whole-paragraph formatting in its description, e.g. `[1] (centered; bold, underlined) AGREEMENT`. `edit_paragraph`, `insert_paragraphs`, `create_document` and `replace_text` take the same tags. When `edit_paragraph` rewrites a paragraph, each tagged part copies the formatting (font, size and colour too) of the matching phrase in the original, in order. Before, rewriting a paragraph gave all of it the first run's formatting, so bold names and amounts were lost in translations and small edits alike.
29
+ - New tool `copy_document` copies a document to a new file exactly as it is (an encrypted one stays encrypted), so "make a copy" or "translate it into a new file" keeps every bit of formatting. Before, the AI could only retype the text into `create_document`, which made a blank document and lost the text and paragraph formatting, lists and tables. `create_document`'s description now sends copies to `copy_document`.
30
+
5
31
  ## 0.2.0 (2026-11-22)
6
32
 
7
33
  ### docxkeun
package/README.md CHANGED
@@ -125,6 +125,20 @@ The effects are optional: `new DocxViewer(el, { aiActivity: false })` turns them
125
125
 
126
126
  Name and colours: `aiActivity: { name: 'Aria', color: ['#0b57d0', '#1e8e3e'] }` puts "Aria is editing…" on the caret and draws the caret, shimmer, glow and change marks from blue to green; one colour (`color: '#0b57d0'`) is used for both ends. Change them at run time with `viewer.activity.name` and `viewer.activity.color` (`undefined` goes back to the default purple to orange), or from CSS with `--docxkeun-ai-color-1` and `--docxkeun-ai-color-2` (any CSS colour). The caret's label turns dark when white text would be hard to read on the colours you pick.
127
127
 
128
+ Effect styles: `aiActivity: { style: 'words' }` (or `viewer.activity.style = 'words'` at run time) picks how the paragraph being changed looks, and so which mark stays after the change. `ACTIVITY_STYLES` lists them with a label and a line for a picker:
129
+
130
+ | Style | While the AI works | After the change |
131
+ |---|---|---|
132
+ | `highlight` (default) | a tinted band sweeps over the lines | the paragraph keeps a soft tint |
133
+ | `words` | the letters themselves shimmer | the changed words glow |
134
+ | `underline` | a streak runs under each line | the changed words stay underlined |
135
+ | `edge` | a soft glow breathes around the paragraph | the ✦ bar in the margin |
136
+ | `spotlight` | the rest of the page dims | the ✦ bar in the margin |
137
+ | `quiet` | only the caret and a pulsing margin bar | the ✦ bar in the margin |
138
+ | `sparkles` | small ✦ drift over the paragraph | the ✦ bar in the margin |
139
+
140
+ Marks build up over a run of changes, each following its paragraph as others are added or removed (a paragraph changed twice is marked against its text before the first change), until `viewer.activity.clearMarks()`: the chat app clears them when you send a new message, the live preview when you open another document. `marks: false` (or `viewer.activity.marksShown = false`) leaves nothing behind. The change map on the right edge jumps to each change, and its ticks show the text from before.
141
+
128
142
  ### Viewer UI
129
143
 
130
144
  Four optional parts share one look and one frame: a toolbar, a navigation panel, a comment column and a right-click menu. With none enabled the viewer's DOM is unchanged.
@@ -181,7 +195,7 @@ await editor.resolveComment(id);
181
195
  const bytes = await viewer.document!.save();
182
196
  ```
183
197
 
184
- Also available: `insertText`, `appendText`, `replaceRange`, `replaceAll`, `deleteRange` (across paragraphs), `insertParagraph`, `deleteParagraph`, `setParagraphStyle`, `formatParagraph` (alignment, right-to-left, indents, spacing, keep rules), `insertImage`, `addFootnote`, `setHeader` / `setFooter` / `removeHeader` / `removeFooter` / `headersAndFooters()`, `await removeHyperlink` (async since it also drops the link's relationship when unused), `setHyperlinkTarget`, `setImageAlt`, `clearFormatting`, `hyperlinks()`, `bookmarks()`, `removeBookmark`, `editComment`, `deleteComment`, `addEditableRange`, `removeEditableRange`.
198
+ Also available: `insertText`, `appendText`, `replaceRange` (text, or pieces each formatted like a given run: `[{ text, like: boldRun }, { text, like: plainRun }]`), `replaceAll`, `deleteRange` (across paragraphs), `insertParagraph`, `deleteParagraph`, `setParagraphStyle`, `formatParagraph` (alignment, right-to-left, indents, spacing, keep rules), `insertImage`, `addFootnote`, `setHeader` / `setFooter` / `removeHeader` / `removeFooter` / `headersAndFooters()`, `await removeHyperlink` (async since it also drops the link's relationship when unused), `setHyperlinkTarget`, `setImageAlt`, `clearFormatting`, `hyperlinks()`, `bookmarks()`, `removeBookmark`, `editComment`, `deleteComment`, `addEditableRange`, `removeEditableRange`.
185
199
 
186
200
  ```ts
187
201
  // Tracked changes: record edits as Word revisions, then review them.
@@ -220,6 +234,21 @@ await editor.setList([extra], { sameListAs: items[1]! }); // continue an ex
220
234
  await editor.setList(items, { format: 'none' }); // no longer a list
221
235
  ```
222
236
 
237
+ Tables and copies: `insertTable` builds a table that spans the text width (Word's "Table Grid" style when the document has it, otherwise plain borders), `insertTableRows` / `deleteTableRows` / `deleteTable` change one, and `tableOf(paragraph)` finds the table a cell paragraph is in. `copyBlocks` copies paragraphs and tables with their formatting, lists and pictures, for example to translate a document onto a new page. With Track Changes on, all of these are recorded as revisions.
238
+
239
+ ```ts
240
+ const [first, last] = [editor.paragraphs()[0]!.el, editor.paragraphs().at(-1)!.el];
241
+ const { blocks, dropped } = await editor.copyBlocks(first, last, 'end', { pageBreak: true }); // lists in the copy start again at 1
242
+ // dropped: { comments, notes, bookmarks } left out of the copy, since they can exist only once
243
+
244
+ const table = editor.insertTable({ after: blocks.at(-1)! }, [
245
+ ['No', 'Description', 'Total'],
246
+ ['1', 'Land benefit value', 'Rp 201.801.600'],
247
+ ], { header: true, widths: [1, 4, 2] }); // bold header row, repeated on each page
248
+ editor.insertTableRows(table, 2, [['2', 'Admin fee', 'Rp 500.000']]); // copies the formatting of the row above
249
+ editor.deleteTableRows(table, 2); // 0-based; deleting every row deletes the table
250
+ ```
251
+
223
252
  ### PDF
224
253
 
225
254
  ```ts
@@ -360,7 +389,7 @@ Known limits:
360
389
  - **Pictures:** only the first frame of a GIF and the first page of a TIFF; JPEG-compressed and CMYK TIFFs are not decoded. EMF+-only pictures (some Office 2007+ charts pasted as pictures) and clipping inside metafiles are not supported.
361
390
  - **Equations:** no line breaks inside an equation and no equation numbers. Math symbols missing from your fonts fall back to other fonts (the bundled fonts have no math font such as Cambria Math).
362
391
  - **Right-to-left and complex scripts:** the bundled fonts have no Arabic or Indic letters; register a font that has them (for example Arial, Times New Roman or Noto) for PDF export. The viewer leaves shaping these scripts to the browser.
363
- - **Editing:** creating or changing shapes, charts and equations, moving or resizing pictures, and editing table structure (rows, columns, merging) are not supported. A keystroke still paginates the whole document, re-using the measured lines of unchanged paragraphs.
392
+ - **Editing:** creating or changing shapes, charts and equations, moving or resizing pictures, and changing a table's columns or merged cells are not supported. Rows can be added and deleted from code, not yet on the page. A keystroke still paginates the whole document, re-using the measured lines of unchanged paragraphs.
364
393
 
365
394
  ## Development
366
395
 
@@ -3,6 +3,7 @@ import type { DocParagraph, Block } from '../model/content.js';
3
3
  import type { DocxDocument } from '../model/document.js';
4
4
  import { type XmlElement } from '../xml/index.js';
5
5
  import { type ListFormat, type ListItem } from './lists.js';
6
+ import { type CopyDropped, type TableOptions } from './tables.js';
6
7
  import { type Revision, type RevisionFilter } from './revisions.js';
7
8
  import { EditError, type DocPosition, type DocRange } from './positions.js';
8
9
  export type EditAction = 'edit' | 'format' | 'comment' | 'reply' | 'resolveComment' | 'editComment' | 'deleteComment' | 'link' | 'bookmark' | 'fillForm' | 'protect' | 'review';
@@ -70,6 +71,13 @@ export interface TextFormat {
70
71
  smallCaps?: boolean;
71
72
  hidden?: boolean;
72
73
  }
74
+ /** A piece of new text for `replaceRange`: formatted like the run `like` (default: the range's first run), then `format`. */
75
+ export interface TextPiece {
76
+ text: string;
77
+ /** A w:r element whose formatting the piece copies. */
78
+ like?: XmlElement;
79
+ format?: TextFormat;
80
+ }
73
81
  /** Paragraph formatting for `formatParagraph` (lengths in points; undefined leaves a property alone). */
74
82
  export interface ParagraphFormat {
75
83
  align?: 'left' | 'center' | 'right' | 'justify';
@@ -280,8 +288,12 @@ export declare class DocxEditor {
280
288
  appendText(paragraph: XmlElement, text: string, format?: TextFormat): XmlElement;
281
289
  /** Delete a range (it may span paragraphs, but not table cells). */
282
290
  deleteRange(range: DocRange): void;
283
- /** Replace a range with text formatted like the range's first run. */
284
- replaceRange(range: DocRange, text: string, format?: TextFormat): void;
291
+ /**
292
+ * Replace a range with text formatted like the range's first run, or with pieces of text that are
293
+ * each formatted like their own `like` run (for example to rewrite a sentence and keep which words
294
+ * were bold). `format` is applied on top.
295
+ */
296
+ replaceRange(range: DocRange, text: string | TextPiece[], format?: TextFormat): void;
285
297
  /** Replace every match; returns how many were replaced. */
286
298
  replaceAll(query: string | RegExp, replacement: string | ((m: Match) => string)): number;
287
299
  /**
@@ -312,6 +324,51 @@ export declare class DocxEditor {
312
324
  format?: TextFormat;
313
325
  }): XmlElement;
314
326
  deleteParagraph(paragraph: XmlElement): void;
327
+ /** The block (paragraph, table or content control) of the body that holds `node`. */
328
+ private topBlock;
329
+ /** Put new blocks into the body before/after the block holding `ref`, or at the start or end. */
330
+ private placeBlocks;
331
+ /** Permission to add content next to `where`. */
332
+ private checkPlace;
333
+ /**
334
+ * Copy the body's blocks from the one holding `from` to the one holding `to` (a table is copied
335
+ * whole) and put the copies at `where`, with their formatting, lists, tables and pictures. Lists
336
+ * in the copy number from the start again unless `restartLists` is false, and `pageBreak` starts
337
+ * the copy on a new page. What may exist only once (bookmarks, comment anchors, note references)
338
+ * is left out of the copy and counted in `dropped`.
339
+ */
340
+ copyBlocks(from: XmlElement, to: XmlElement, where: {
341
+ before?: XmlElement;
342
+ after?: XmlElement;
343
+ } | 'start' | 'end', options?: {
344
+ pageBreak?: boolean;
345
+ restartLists?: boolean;
346
+ }): Promise<{
347
+ blocks: XmlElement[];
348
+ dropped: CopyDropped;
349
+ }>;
350
+ /**
351
+ * Insert a table of text (`rows` of cell texts; "\n" in a cell starts a new paragraph) before or
352
+ * after the block holding a paragraph, or at the start or end. It spans the text width.
353
+ */
354
+ insertTable(where: {
355
+ before?: XmlElement;
356
+ after?: XmlElement;
357
+ } | 'start' | 'end', rows: string[][], options?: TableOptions): XmlElement;
358
+ /** The table holding a paragraph (the innermost one). */
359
+ tableOf(paragraph: XmlElement): XmlElement;
360
+ /** Permission to change a table: its whole text. */
361
+ private checkTable;
362
+ /**
363
+ * Insert rows into a table before row `at` (0-based; the row count appends). Each new row copies
364
+ * the formatting of the row next to it and gets the texts of one entry of `rows`.
365
+ */
366
+ insertTableRows(table: XmlElement, at: number, rows: string[][]): XmlElement[];
367
+ /** Delete rows `from` to `to` (0-based, inclusive) of a table; deleting them all deletes the table. */
368
+ deleteTableRows(table: XmlElement, from: number, to?: number): void;
369
+ /** Delete a whole table. */
370
+ deleteTable(table: XmlElement): void;
371
+ private markRowDeleted;
315
372
  setParagraphStyle(paragraph: XmlElement, styleId: string): void;
316
373
  /** Change paragraph formatting: alignment, direction, indents, spacing and keep rules. */
317
374
  formatParagraph(paragraph: XmlElement, format: ParagraphFormat): void;
@@ -8,6 +8,8 @@ import { imageInfo } from '../images/size.js';
8
8
  import { hasEvenPages, hasFirstPage, headerParagraphs, headerText, referencesOf, sectionProperties, SECTPR_ORDER, textWidth } from './headers.js';
9
9
  import { attr, el, elements, ensureChild, findAll, firstChild, insertOrdered, NS, removeChildren, textContent } from '../xml/index.js';
10
10
  import { createList, listItems } from './lists.js';
11
+ import { buildTable, cleanCopy, columnWidths, markInserted, markRow } from './tables.js';
12
+ import { cloneElement } from '../xml/index.js';
11
13
  import { acceptRevisions, cleanRunProps, deleteRun, insertedRuns, listRevisions, markParagraph, nextRevisionId, paragraphMarkRevision, recordParagraphFormat, recordRunFormat, rejectRevisions, revisionStamp, runRevision, } from './revisions.js';
12
14
  import { SETTINGS_ORDER } from '../security/protection.js';
13
15
  import { ensureNamespaces, ensurePart, randomHexId, ROOT_NAMESPACES } from './parts.js';
@@ -173,6 +175,21 @@ function endOfRun(run, fallback) {
173
175
  return { node: fallback, offset: 0 };
174
176
  return last.name === 'w:t' ? { node: last, offset: textContent(last).length } : { node: last, offset: 1 };
175
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
+ }
176
193
  function newRun(text, template, format) {
177
194
  const rPr = template ? firstChild(template, 'w:rPr') : undefined;
178
195
  const run = el('w:r', {}, [...(rPr ? [structuredClone(rPr)] : []), ...runContent(text)]);
@@ -969,23 +986,33 @@ export class DocxEditor {
969
986
  this.removeRange(range);
970
987
  this.changed();
971
988
  }
972
- /** 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
+ */
973
994
  replaceRange(range, text, format) {
974
995
  this.check('edit', range);
975
996
  const index = this.index();
976
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));
977
1004
  const track = this.tracking();
978
1005
  if (track) {
979
1006
  // The old text stays as a deletion; the new text follows it as an insertion.
980
1007
  const { startMark, endMark } = this.trackedCut(range, track);
981
1008
  replaceMark(this.index(), startMark, []);
982
1009
  this.liftOutOfInsertion(endMark, this.index());
983
- replaceMark(this.index(), endMark, text || format ? [this.placed(newRun(text, template, format), track)] : []);
1010
+ replaceMark(this.index(), endMark, runs.length ? [insertedRuns(runs, track.nextId(), track.who)] : []);
984
1011
  this.changed();
985
1012
  return;
986
1013
  }
987
1014
  const { startMark, endMark, idx } = this.cut(range);
988
- replaceMark(idx, startMark, text || format ? [newRun(text, template, format)] : []);
1015
+ replaceMark(idx, startMark, runs);
989
1016
  replaceMark(idx, endMark, []);
990
1017
  this.changed();
991
1018
  }
@@ -1203,6 +1230,280 @@ export class DocxEditor {
1203
1230
  parent.children.splice(indexOfChild(parent, paragraph), 1);
1204
1231
  this.changed();
1205
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
+ }
1206
1507
  setParagraphStyle(paragraph, styleId) {
1207
1508
  this.check('format', this.paragraphRange(paragraph));
1208
1509
  const track = this.tracking();
@@ -1328,11 +1629,19 @@ export class DocxEditor {
1328
1629
  return undefined;
1329
1630
  }
1330
1631
  if (sameListAs) {
1331
- if (format !== undefined || start !== undefined)
1332
- throw new EditError('sameListAs cannot be combined with format or start');
1333
1632
  const target = all.get(sameListAs)?.numbering;
1334
1633
  if (!target)
1335
- throw new EditError('The paragraph to join is not in a list');
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
+ }
1336
1645
  for (const p of paras)
1337
1646
  this.writeNumPr(p, { numId: target.numId, ilvl: level ?? (p.numbering ? p.numbering.ilvl : target.ilvl) });
1338
1647
  this.changed();
@@ -1,7 +1,8 @@
1
- export { DocxEditor, OBJECT_CHAR, paragraphText, paragraphsOf, applyFormat, runContent, lockModeOf, LockedRegionError, LOCK_TAG, type EditAction, type EditGuard, type TextFormat, type CommentInput, type Match, type LockMode, type LockedRegion, type SetListOptions, type EditorOptions, type ParagraphFormat, documentTracksChanges } from './editor.js';
1
+ export { DocxEditor, OBJECT_CHAR, paragraphText, paragraphsOf, applyFormat, runContent, lockModeOf, LockedRegionError, LOCK_TAG, type EditAction, type EditGuard, type TextFormat, type TextPiece, type CommentInput, type Match, type LockMode, type LockedRegion, type SetListOptions, type EditorOptions, type ParagraphFormat, documentTracksChanges } from './editor.js';
2
2
  export { listRevisions, acceptRevisions, rejectRevisions, type Revision, type RevisionKind, type RevisionFilter } from './revisions.js';
3
3
  export { LIST_FORMATS, type ListFormat, type ListItem } from './lists.js';
4
4
  export { EditError, TreeIndex, type DocPosition, type DocRange } from './positions.js';
5
5
  export { ensurePart, randomHexId } from './parts.js';
6
6
  export { selectionInfoFor, describeSelection, type SelectionInfo, type SelectedParagraph, type TextSpot } from './selection.js';
7
7
  export type { HeaderFooterInfo, HeaderFooterKind, HeaderFooterOptions, HeaderFooterType } from './headers.js';
8
+ export type { TableOptions, CopyDropped } from './tables.js';
@@ -310,6 +310,17 @@ function joinWithNext(p, para) {
310
310
  p.parent.set(c, next);
311
311
  parent.children.splice(i, 1);
312
312
  }
313
+ /** Remove a table row; a table left without rows goes too (a cell that held it keeps a paragraph). */
314
+ function removeRow(p, row) {
315
+ const table = p.parent.get(row);
316
+ remove(p, row);
317
+ if (!table || elements(table, 'w:tr').length)
318
+ return;
319
+ const holder = p.parent.get(table);
320
+ remove(p, table);
321
+ if (holder?.name === 'w:tc' && !elements(holder, 'w:p').length)
322
+ holder.children.push(el('w:p'));
323
+ }
313
324
  function restoreProperties(p, change) {
314
325
  const owner = p.parent.get(change);
315
326
  if (!owner)
@@ -362,14 +373,14 @@ function apply(root, filter, accept) {
362
373
  const row = p.parent.get(p.parent.get(node));
363
374
  remove(p, node);
364
375
  if (!accept && row)
365
- remove(p, row);
376
+ removeRow(p, row);
366
377
  break;
367
378
  }
368
379
  case 'row-delete': {
369
380
  const row = p.parent.get(p.parent.get(node));
370
381
  remove(p, node);
371
382
  if (accept && row)
372
- remove(p, row);
383
+ removeRow(p, row);
373
384
  break;
374
385
  }
375
386
  }