docxkeun-mcp 0.1.0 → 0.2.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/README.md +8 -3
- package/dist/markup.d.ts +40 -0
- package/dist/markup.js +202 -0
- package/dist/operations.d.ts +6 -1
- package/dist/operations.js +217 -11
- package/dist/outline.js +10 -1
- package/dist/preview-page.js +33 -1
- package/dist/server.js +38 -6
- package/package.json +2 -2
package/README.md
CHANGED
|
@@ -68,7 +68,7 @@ Ask Claude for the preview link (the `get_preview_link` tool), or open `http://1
|
|
|
68
68
|
|
|
69
69
|
To watch a folder without an AI client, run `npx docxkeun-mcp --preview-only ~/Documents/contracts`; it redraws documents whenever they are saved.
|
|
70
70
|
|
|
71
|
-
The "AI effects" menu in the header picks how the AI's work shows: animated, still (highlights without motion) or off
|
|
71
|
+
The "AI effects" menu in the header picks how the AI's work shows: animated, still (highlights without motion) or off. **Style** picks the effect (highlight band, word shimmer, underline wave, edge glow, spotlight, quiet or sparkles), and **Marks** whether a mark stays on what the AI changed. The browser remembers all three.
|
|
72
72
|
|
|
73
73
|
While a tool runs, the preview shows where the AI is working: a shimmer over the paragraphs and its own caret ("Claude is editing…"), or a scan line while it reads. When the change lands, new text inks in, removed paragraphs float away, and change bars with a ✦ (hover: what the text was) stay in the margin until the next change.
|
|
74
74
|
|
|
@@ -95,10 +95,13 @@ Each role gets only the tools it may use.
|
|
|
95
95
|
| `get_preview_link` | A link to the live preview of a document (only with `--preview`) | viewer |
|
|
96
96
|
| `get_selection` | What the user selected (or clicked) in the live preview: paragraph numbers, page and text. Also the resource `docxkeun://selection` (only with `--preview`) | viewer |
|
|
97
97
|
| `add_comment`, `reply_to_comment`, `resolve_comment`, `delete_comment` | Comments (a commenter may delete only its own) | commenter |
|
|
98
|
-
| `create_document` | A new document from paragraphs | editor |
|
|
98
|
+
| `create_document` | A new, blank document from paragraphs | editor |
|
|
99
|
+
| `copy_document` | An exact copy of a document in a new file (formatting, tables, lists, pictures, headers, footers, comments), for example to translate the copy | editor |
|
|
99
100
|
| `replace_text` | Find and replace, keeping formatting; regex with `$1` | editor |
|
|
100
101
|
| `fill_template` | `{{placeholder}}` fields and content controls | editor |
|
|
101
102
|
| `edit_paragraph`, `insert_paragraphs`, `delete_paragraphs` | Paragraph text and styles | editor |
|
|
103
|
+
| `copy_paragraphs` | Copy paragraphs and tables with their formatting and lists, optionally onto a new page (for example to translate a document); lists in the copy start again | editor |
|
|
104
|
+
| `insert_table`, `edit_table` | Make a table (header row, column widths, borders, alignment); add or delete rows, or delete a table. Cells are paragraphs, so the text tools edit them | editor |
|
|
102
105
|
| `format_text` | Bold, italic, underline, colour, highlight, size, font | editor |
|
|
103
106
|
| `format_paragraph` | Alignment, right-to-left direction, indents, spacing, line spacing, keep and page-break rules | editor |
|
|
104
107
|
| `replace_story_text` | Edit text in a header, footer, footnote, endnote or text box | editor |
|
|
@@ -107,12 +110,14 @@ Each role gets only the tools it may use.
|
|
|
107
110
|
| `add_footnote` | A footnote at a place in a paragraph | editor |
|
|
108
111
|
| `set_track_changes` | Turn Word's Track Changes on or off; while on, every edit is a tracked change signed with `--author` | editor |
|
|
109
112
|
| `accept_revisions`, `reject_revisions` | Review tracked changes by id, by author, or all | editor |
|
|
110
|
-
| `set_list` | Bullets, numbers (1. 1)), letters (a. A.) or roman numerals; restart numbering, change level, join or leave a list | editor |
|
|
113
|
+
| `set_list` | Bullets, numbers (1. 1)), letters (a. A.) or roman numerals; restart numbering, change level, join paragraphs that are not next to each other into one list, or leave a list | editor |
|
|
111
114
|
| `add_hyperlink`, `add_bookmark` | Links to web addresses or bookmarks | editor |
|
|
112
115
|
| `lock_region`, `unlock_region` | Lock text or paragraphs against editing (Word content controls) | owner |
|
|
113
116
|
| `protect_document` | Word's editing restrictions: read-only, comments only, tracked changes only, forms only | owner |
|
|
114
117
|
| `set_open_password` | Encrypt with a password to open (AES-256), or remove it | owner |
|
|
115
118
|
|
|
119
|
+
`read_document` shows text formatting as tags: text formatted differently from the rest of its paragraph is wrapped in `<b>`, `<i>`, `<u>`, `<s>`, `<sup>` or `<sub>`, and a paragraph's alignment and whole-paragraph formatting are in its description (`[1] (centered; bold, underlined) AGREEMENT`). `edit_paragraph`, `insert_paragraphs`, `create_document` and `replace_text` take the same tags, so an AI that rewrites or translates a paragraph keeps its bold, underlined and other formatted words; each tagged part copies the font, size and colour of the matching phrase. Searches ignore the tags.
|
|
120
|
+
|
|
116
121
|
Editing tools save to the file straight away; every one of them takes `output` to write a copy instead. Encrypted documents take `password`, and stay encrypted when they are changed.
|
|
117
122
|
|
|
118
123
|
## Safety
|
package/dist/markup.d.ts
ADDED
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Character formatting as light tags, so an AI can see it and keep it: read_document shows <b>, <i>,
|
|
3
|
+
* <u>, <s>, <sup> and <sub> around text formatted that way, and the writing tools take the same tags.
|
|
4
|
+
* Formatting the whole paragraph has (a bold title) is named once in the paragraph's description
|
|
5
|
+
* instead of tagging all its text.
|
|
6
|
+
*/
|
|
7
|
+
import type { DocParagraph, TextInline } from 'docxkeun';
|
|
8
|
+
import type { TextFormat, TextPiece } from 'docxkeun/editor';
|
|
9
|
+
export declare const TAGS: readonly ['b', 'i', 'u', 's', 'sup', 'sub'];
|
|
10
|
+
export type Tag = (typeof TAGS)[number];
|
|
11
|
+
type Tags = ReadonlySet<Tag>;
|
|
12
|
+
export declare function tagsOf(props: TextInline['props']): Set<Tag>;
|
|
13
|
+
/** What formatting the paragraph's text has as a whole, in words ("bold, underlined"). */
|
|
14
|
+
export declare function wholeFormatting(para: DocParagraph): string[];
|
|
15
|
+
/** The paragraph's text with tags around what only part of it is formatted with. */
|
|
16
|
+
export declare function markupOf(para: DocParagraph): string;
|
|
17
|
+
export interface Segment {
|
|
18
|
+
text: string;
|
|
19
|
+
tags: Set<Tag>;
|
|
20
|
+
}
|
|
21
|
+
/** Whether text has any formatting tags (or the escapes < > &). */
|
|
22
|
+
export declare function hasMarkup(text: string): boolean;
|
|
23
|
+
/**
|
|
24
|
+
* Split tagged text into pieces with their formatting. Lenient: a closing tag that was never opened
|
|
25
|
+
* is ignored, a tag left open runs to the end, and any other "<" or "&" is ordinary text.
|
|
26
|
+
*/
|
|
27
|
+
export declare function parseMarkup(text: string): Segment[];
|
|
28
|
+
/** The text without its tags. */
|
|
29
|
+
export declare function plainText(text: string): string;
|
|
30
|
+
/** Direct formatting that turns text formatted `have` into `want`. */
|
|
31
|
+
export declare function formatFor(want: Tags, have: Tags): TextFormat | undefined;
|
|
32
|
+
/**
|
|
33
|
+
* New text for a paragraph as pieces for DocxEditor.replaceRange. The paragraph's text is read as
|
|
34
|
+
* stretches of one formatting each; the new text's parts copy them in order, so the second bold part
|
|
35
|
+
* of a translation copies the second bold phrase of the original (with its own font, size and colour).
|
|
36
|
+
* A part whose formatting the paragraph never had copies its ordinary text and sets the difference.
|
|
37
|
+
* Formatting the whole paragraph had needs no tags.
|
|
38
|
+
*/
|
|
39
|
+
export declare function piecesFor(para: DocParagraph, segments: Segment[]): TextPiece[];
|
|
40
|
+
export {};
|
package/dist/markup.js
ADDED
|
@@ -0,0 +1,202 @@
|
|
|
1
|
+
export const TAGS = ['b', 'i', 'u', 's', 'sup', 'sub'];
|
|
2
|
+
const WORDS = { b: 'bold', i: 'italic', u: 'underlined', s: 'struck through', sup: 'superscript', sub: 'subscript' };
|
|
3
|
+
/** Formatting that shows on spaces and tabs too (a signature line is often underlined blanks). */
|
|
4
|
+
const SHOWS_ON_SPACE = new Set(['u', 's']);
|
|
5
|
+
const TAG_OR_ENTITY = /<(\/?)(sup|sub|b|i|u|s)>|&(lt|gt|amp);/g;
|
|
6
|
+
export function tagsOf(props) {
|
|
7
|
+
const t = new Set();
|
|
8
|
+
if (props.bold)
|
|
9
|
+
t.add('b');
|
|
10
|
+
if (props.italic)
|
|
11
|
+
t.add('i');
|
|
12
|
+
if (props.underline && props.underline !== 'none')
|
|
13
|
+
t.add('u');
|
|
14
|
+
if (props.strike || props.dstrike)
|
|
15
|
+
t.add('s');
|
|
16
|
+
if (props.vertAlign === 'superscript')
|
|
17
|
+
t.add('sup');
|
|
18
|
+
else if (props.vertAlign === 'subscript')
|
|
19
|
+
t.add('sub');
|
|
20
|
+
return t;
|
|
21
|
+
}
|
|
22
|
+
const same = (a, b) => a.size === b.size && [...a].every((t) => b.has(t));
|
|
23
|
+
const without = (a, b) => new Set([...a].filter((t) => !b.has(t)));
|
|
24
|
+
const visible = (text) => /\S/.test(text);
|
|
25
|
+
/** The paragraph's text (text runs, tabs and line breaks, as read_document shows it) in formatted pieces. */
|
|
26
|
+
function piecesOf(para) {
|
|
27
|
+
const out = [];
|
|
28
|
+
let links = 0;
|
|
29
|
+
for (const inline of para.inlines) {
|
|
30
|
+
if (inline.kind === 'linkStart')
|
|
31
|
+
links++;
|
|
32
|
+
else if (inline.kind === 'linkEnd')
|
|
33
|
+
links = Math.max(0, links - 1);
|
|
34
|
+
else if (inline.kind === 'text' || inline.kind === 'tab' || (inline.kind === 'break' && inline.type === 'line')) {
|
|
35
|
+
const text = inline.kind === 'text' ? inline.text : inline.kind === 'tab' ? '\t' : '\n';
|
|
36
|
+
out.push({ text, tags: tagsOf(inline.props), run: inline.run, inLink: links > 0 });
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
return out;
|
|
40
|
+
}
|
|
41
|
+
/** Formatting every visible character of the paragraph has. */
|
|
42
|
+
function wholeOf(pieces) {
|
|
43
|
+
const shown = pieces.filter((p) => visible(p.text));
|
|
44
|
+
if (!shown.length)
|
|
45
|
+
return new Set();
|
|
46
|
+
return new Set(TAGS.filter((t) => shown.every((p) => p.tags.has(t))));
|
|
47
|
+
}
|
|
48
|
+
/** What formatting the paragraph's text has as a whole, in words ("bold, underlined"). */
|
|
49
|
+
export function wholeFormatting(para) {
|
|
50
|
+
return [...wholeOf(piecesOf(para))].map((t) => WORDS[t]);
|
|
51
|
+
}
|
|
52
|
+
function escape(text) {
|
|
53
|
+
return text.replace(/&(?=(?:lt|gt|amp);)/g, '&').replace(/<(?=\/?(?:sup|sub|b|i|u|s)>)/g, '<');
|
|
54
|
+
}
|
|
55
|
+
/** The paragraph's text with tags around what only part of it is formatted with. */
|
|
56
|
+
export function markupOf(para) {
|
|
57
|
+
const pieces = piecesOf(para);
|
|
58
|
+
const whole = wholeOf(pieces);
|
|
59
|
+
const shown = pieces.map((p) => ({ text: p.text, tags: without(p.tags, whole) }));
|
|
60
|
+
// Bold or italic spaces look like any other spaces: they follow the text around them, so a bold
|
|
61
|
+
// phrase reads <b>PT Swadaya Usaha Persada</b> however Word split it into runs.
|
|
62
|
+
shown.forEach((p, i) => {
|
|
63
|
+
if (visible(p.text))
|
|
64
|
+
return;
|
|
65
|
+
const near = [shown[i - 1], shown[i + 1]].filter((n) => !!n && visible(n.text));
|
|
66
|
+
const around = near.length === 2 && !same(near[0].tags, near[1].tags) ? new Set([...near[0].tags].filter((t) => near[1].tags.has(t))) : (near[0]?.tags ?? new Set());
|
|
67
|
+
p.tags = new Set([...[...p.tags].filter((t) => SHOWS_ON_SPACE.has(t)), ...[...around].filter((t) => !SHOWS_ON_SPACE.has(t))]);
|
|
68
|
+
});
|
|
69
|
+
let out = '';
|
|
70
|
+
const merged = [];
|
|
71
|
+
for (const p of shown) {
|
|
72
|
+
const last = merged[merged.length - 1];
|
|
73
|
+
if (last && same(last.tags, p.tags))
|
|
74
|
+
last.text += p.text;
|
|
75
|
+
else
|
|
76
|
+
merged.push({ ...p });
|
|
77
|
+
}
|
|
78
|
+
// Tags stay open across pieces that keep them: <b>6.337 M<sup>2</sup> (enam ribu…)</b>.
|
|
79
|
+
const open = [];
|
|
80
|
+
for (const p of merged) {
|
|
81
|
+
let keep = 0;
|
|
82
|
+
while (keep < open.length && p.tags.has(open[keep]))
|
|
83
|
+
keep++;
|
|
84
|
+
while (open.length > keep)
|
|
85
|
+
out += `</${open.pop()}>`;
|
|
86
|
+
for (const t of TAGS) {
|
|
87
|
+
if (p.tags.has(t) && !open.includes(t)) {
|
|
88
|
+
open.push(t);
|
|
89
|
+
out += `<${t}>`;
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
out += escape(p.text);
|
|
93
|
+
}
|
|
94
|
+
while (open.length)
|
|
95
|
+
out += `</${open.pop()}>`;
|
|
96
|
+
return out;
|
|
97
|
+
}
|
|
98
|
+
/** Whether text has any formatting tags (or the escapes < > &). */
|
|
99
|
+
export function hasMarkup(text) {
|
|
100
|
+
return new RegExp(TAG_OR_ENTITY.source).test(text);
|
|
101
|
+
}
|
|
102
|
+
/**
|
|
103
|
+
* Split tagged text into pieces with their formatting. Lenient: a closing tag that was never opened
|
|
104
|
+
* is ignored, a tag left open runs to the end, and any other "<" or "&" is ordinary text.
|
|
105
|
+
*/
|
|
106
|
+
export function parseMarkup(text) {
|
|
107
|
+
const out = [];
|
|
108
|
+
const depth = new Map();
|
|
109
|
+
let last = 0;
|
|
110
|
+
const push = (s) => {
|
|
111
|
+
if (!s)
|
|
112
|
+
return;
|
|
113
|
+
const tags = new Set(TAGS.filter((t) => (depth.get(t) ?? 0) > 0));
|
|
114
|
+
const prev = out[out.length - 1];
|
|
115
|
+
if (prev && same(prev.tags, tags))
|
|
116
|
+
prev.text += s;
|
|
117
|
+
else
|
|
118
|
+
out.push({ text: s, tags });
|
|
119
|
+
};
|
|
120
|
+
for (const m of text.matchAll(TAG_OR_ENTITY)) {
|
|
121
|
+
push(text.slice(last, m.index));
|
|
122
|
+
last = m.index + m[0].length;
|
|
123
|
+
if (m[3]) {
|
|
124
|
+
push(m[3] === 'lt' ? '<' : m[3] === 'gt' ? '>' : '&');
|
|
125
|
+
continue;
|
|
126
|
+
}
|
|
127
|
+
const tag = m[2];
|
|
128
|
+
const n = depth.get(tag) ?? 0;
|
|
129
|
+
depth.set(tag, m[1] ? Math.max(0, n - 1) : n + 1);
|
|
130
|
+
}
|
|
131
|
+
push(text.slice(last));
|
|
132
|
+
return out;
|
|
133
|
+
}
|
|
134
|
+
/** The text without its tags. */
|
|
135
|
+
export function plainText(text) {
|
|
136
|
+
return parseMarkup(text)
|
|
137
|
+
.map((s) => s.text)
|
|
138
|
+
.join('');
|
|
139
|
+
}
|
|
140
|
+
/** Direct formatting that turns text formatted `have` into `want`. */
|
|
141
|
+
export function formatFor(want, have) {
|
|
142
|
+
const f = {};
|
|
143
|
+
if (want.has('b') !== have.has('b'))
|
|
144
|
+
f.bold = want.has('b');
|
|
145
|
+
if (want.has('i') !== have.has('i'))
|
|
146
|
+
f.italic = want.has('i');
|
|
147
|
+
if (want.has('u') !== have.has('u'))
|
|
148
|
+
f.underline = want.has('u');
|
|
149
|
+
if (want.has('s') !== have.has('s'))
|
|
150
|
+
f.strike = want.has('s');
|
|
151
|
+
const va = (t) => (t.has('sup') ? 'superscript' : t.has('sub') ? 'subscript' : 'baseline');
|
|
152
|
+
if (va(want) !== va(have))
|
|
153
|
+
f.vertAlign = va(want);
|
|
154
|
+
return Object.keys(f).length ? f : undefined;
|
|
155
|
+
}
|
|
156
|
+
/**
|
|
157
|
+
* New text for a paragraph as pieces for DocxEditor.replaceRange. The paragraph's text is read as
|
|
158
|
+
* stretches of one formatting each; the new text's parts copy them in order, so the second bold part
|
|
159
|
+
* of a translation copies the second bold phrase of the original (with its own font, size and colour).
|
|
160
|
+
* A part whose formatting the paragraph never had copies its ordinary text and sets the difference.
|
|
161
|
+
* Formatting the whole paragraph had needs no tags.
|
|
162
|
+
*/
|
|
163
|
+
export function piecesFor(para, segments) {
|
|
164
|
+
const pieces = piecesOf(para);
|
|
165
|
+
const whole = wholeOf(pieces);
|
|
166
|
+
// Within a stretch, copy an ordinary run rather than a hyperlink's (its colour comes from the link), then the longest.
|
|
167
|
+
const better = (a, b) => (a.inLink !== b.inLink ? !a.inLink : a.text.length > b.text.length);
|
|
168
|
+
const spans = [];
|
|
169
|
+
for (const p of pieces) {
|
|
170
|
+
if (!visible(p.text) || !p.run)
|
|
171
|
+
continue;
|
|
172
|
+
const last = spans[spans.length - 1];
|
|
173
|
+
if (last && same(last.tags, p.tags)) {
|
|
174
|
+
if (better(p, last.model))
|
|
175
|
+
last.model = p;
|
|
176
|
+
}
|
|
177
|
+
else
|
|
178
|
+
spans.push({ tags: p.tags, model: p });
|
|
179
|
+
}
|
|
180
|
+
const plain = (spans.find((s) => same(s.tags, whole)) ?? spans[0])?.model;
|
|
181
|
+
const used = new Map();
|
|
182
|
+
let previous;
|
|
183
|
+
return segments.map((seg) => {
|
|
184
|
+
const want = new Set([...seg.tags, ...whole]);
|
|
185
|
+
const key = TAGS.filter((t) => want.has(t)).join(',');
|
|
186
|
+
const matching = spans.filter((s) => same(s.tags, want));
|
|
187
|
+
if (matching.length) {
|
|
188
|
+
// Spaces between two parts of one phrase ("<b>A</b> <b>B</b>") do not start the next one.
|
|
189
|
+
const advance = visible(seg.text) && key !== previous;
|
|
190
|
+
if (advance)
|
|
191
|
+
used.set(key, (used.get(key) ?? 0) + 1);
|
|
192
|
+
if (visible(seg.text))
|
|
193
|
+
previous = key;
|
|
194
|
+
const n = Math.max(1, used.get(key) ?? 0);
|
|
195
|
+
return { text: seg.text, like: matching[Math.min(n, matching.length) - 1].model.run };
|
|
196
|
+
}
|
|
197
|
+
if (visible(seg.text))
|
|
198
|
+
previous = key;
|
|
199
|
+
const format = formatFor(want, plain?.tags ?? new Set());
|
|
200
|
+
return { text: seg.text, ...(plain?.run ? { like: plain.run } : {}), ...(format ? { format } : {}) };
|
|
201
|
+
});
|
|
202
|
+
}
|
package/dist/operations.d.ts
CHANGED
|
@@ -5,10 +5,11 @@
|
|
|
5
5
|
* the minimum role that may use it, and whether it reads, adds or changes.
|
|
6
6
|
*/
|
|
7
7
|
import { z } from 'zod';
|
|
8
|
-
import { type DocxDocument } from 'docxkeun';
|
|
8
|
+
import { type DocParagraph, type DocxDocument } from 'docxkeun';
|
|
9
9
|
import { type DocxEditor } from 'docxkeun/editor';
|
|
10
10
|
import { type Role } from 'docxkeun/security';
|
|
11
11
|
import { type ParagraphEntry } from './outline.js';
|
|
12
|
+
import { type Segment } from './markup.js';
|
|
12
13
|
/** One open document and who is acting on it. */
|
|
13
14
|
export interface DocContext {
|
|
14
15
|
doc: DocxDocument;
|
|
@@ -57,6 +58,10 @@ export declare const newParagraph: z.ZodObject<{
|
|
|
57
58
|
text: z.ZodString;
|
|
58
59
|
style: z.ZodOptional<z.ZodString>;
|
|
59
60
|
}, z.core.$strip>;
|
|
61
|
+
/** Write tagged text into an empty paragraph. */
|
|
62
|
+
export declare function writeTagged(editor: DocxEditor, paragraph: DocParagraph['el'], segments: Segment[]): void;
|
|
63
|
+
/** Format the parts of a paragraph's new text that `segments` tag (its text is their text, in order). */
|
|
64
|
+
export declare function tagParagraph(editor: DocxEditor, paragraph: DocParagraph['el'], segments: Segment[]): void;
|
|
60
65
|
/**
|
|
61
66
|
* The paragraphs (numbers from 1) a call will read or change, from its arguments: `paragraph`,
|
|
62
67
|
* `from`/`to`, `after`/`before`, or the paragraphs holding `text`, `find`, `query` or a template
|
package/dist/operations.js
CHANGED
|
@@ -9,6 +9,7 @@ import { blocksToText, describeChart, readChart } from 'docxkeun';
|
|
|
9
9
|
import { DocxEditor as Editor, paragraphText, paragraphsOf } from 'docxkeun/editor';
|
|
10
10
|
import { readProtection } from 'docxkeun/security';
|
|
11
11
|
import { commentAnchors, commentsByParagraph, commentThreads, describeParagraph, listParagraphs, locksByParagraph, quote, resolveStyle, tableCount, wordCount, } from './outline.js';
|
|
12
|
+
import { formatFor, hasMarkup, parseMarkup, piecesFor, plainText } from './markup.js';
|
|
12
13
|
function define(op) {
|
|
13
14
|
return op;
|
|
14
15
|
}
|
|
@@ -32,6 +33,9 @@ export function escapeRegExp(s) {
|
|
|
32
33
|
}
|
|
33
34
|
export function searchPattern(query, options) {
|
|
34
35
|
const matchCase = options.matchCase ?? true;
|
|
36
|
+
// read_document's formatting tags are not part of the text.
|
|
37
|
+
if (!options.regex && hasMarkup(query))
|
|
38
|
+
query = plainText(query);
|
|
35
39
|
if (!options.regex)
|
|
36
40
|
return matchCase ? query : new RegExp(escapeRegExp(query), 'gi');
|
|
37
41
|
try {
|
|
@@ -99,7 +103,7 @@ const target = {
|
|
|
99
103
|
occurrence: z.number().int().min(1).optional().describe('Which match of `text` to use, counting from 1 (default 1)'),
|
|
100
104
|
};
|
|
101
105
|
export const newParagraph = z.object({
|
|
102
|
-
text: z.string().describe('Paragraph text; "\\n" makes a line break and "\\t" a tab'),
|
|
106
|
+
text: z.string().describe('Paragraph text; "\\n" makes a line break and "\\t" a tab. <b>, <i>, <u>, <s>, <sup> and <sub> tags format parts of it'),
|
|
103
107
|
style: z.string().optional().describe('Paragraph style name or id, e.g. "Heading 1" (default: the normal style)'),
|
|
104
108
|
});
|
|
105
109
|
const textFormat = z
|
|
@@ -124,8 +128,10 @@ const textFormat = z
|
|
|
124
128
|
const readDocument = define({
|
|
125
129
|
name: 'read_document',
|
|
126
130
|
title: 'Read a document',
|
|
127
|
-
description: 'Read a Word document as numbered paragraphs. Each line is "[number] (style; list label; table position; locks; comments) text", ' +
|
|
128
|
-
'e.g. "[
|
|
131
|
+
description: 'Read a Word document as numbered paragraphs. Each line is "[number] (style; list label; table position; alignment; formatting of the whole paragraph; locks; comments) text", ' +
|
|
132
|
+
'e.g. "[1] (centered; bold, underlined) AGREEMENT" or "[4] (list item a.; justified) …". ' +
|
|
133
|
+
'Text formatted differently from the rest of its paragraph is tagged: <b>bold</b>, <i>italic</i>, <u>underlined</u>, <s>struck through</s>, <sup>superscript</sup>, <sub>subscript</sub>. ' +
|
|
134
|
+
'The tags are not part of the text (find_text and replace_text ignore them); edit_paragraph and insert_paragraphs take them, so keep them when you rewrite or translate text. ' +
|
|
129
135
|
'Long documents come in pages of paragraphs: pass `from` to continue.',
|
|
130
136
|
role: 'viewer',
|
|
131
137
|
kind: 'read',
|
|
@@ -333,7 +339,7 @@ const replaceText = define({
|
|
|
333
339
|
kind: 'change',
|
|
334
340
|
schema: z.object({
|
|
335
341
|
find: z.string().min(1).describe('Text to replace'),
|
|
336
|
-
replace: z.string().describe('Replacement text (empty deletes the matches)'),
|
|
342
|
+
replace: z.string().describe('Replacement text (empty deletes the matches); <b>, <i>, <u>… tags add formatting to parts of it'),
|
|
337
343
|
regex: z.boolean().optional().describe('Treat find as a JavaScript regular expression'),
|
|
338
344
|
matchCase: z.boolean().optional().describe('Match upper/lower case exactly (default true)'),
|
|
339
345
|
paragraph: paragraphNumber.optional().describe('Only replace in this paragraph'),
|
|
@@ -356,7 +362,9 @@ const replaceText = define({
|
|
|
356
362
|
skipped++;
|
|
357
363
|
continue;
|
|
358
364
|
}
|
|
359
|
-
|
|
365
|
+
const replacement = args.regex ? expandReplacement(args.replace, m) : args.replace;
|
|
366
|
+
// Untagged text keeps the formatting of what it replaces; tags add to it.
|
|
367
|
+
ctx.editor.replaceRange(m, hasMarkup(replacement) ? parseMarkup(replacement).map((x) => ({ text: x.text, ...(x.tags.size ? { format: formatFor(x.tags, new Set()) } : {}) })) : replacement);
|
|
360
368
|
}
|
|
361
369
|
const done = chosen.length - skipped;
|
|
362
370
|
if (done === 0)
|
|
@@ -394,12 +402,14 @@ const fillTemplate = define({
|
|
|
394
402
|
const editParagraph = define({
|
|
395
403
|
name: 'edit_paragraph',
|
|
396
404
|
title: 'Edit a paragraph',
|
|
397
|
-
description: "Replace a paragraph's text
|
|
405
|
+
description: "Replace a paragraph's text and/or change its style. The paragraph keeps its own formatting (alignment, indents, list, whole-paragraph bold and so on). " +
|
|
406
|
+
'Use the tags read_document shows (<b>, <i>, <u>, <s>, <sup>, <sub>) for text formatted differently from the rest: each tagged part takes the formatting ' +
|
|
407
|
+
'(font, size and colour too) of the text that had the same tags. Keep the tags when rewriting or translating, or that formatting is lost.',
|
|
398
408
|
role: 'editor',
|
|
399
409
|
kind: 'change',
|
|
400
410
|
schema: z.object({
|
|
401
411
|
paragraph: paragraphNumber.describe('Paragraph number from read_document'),
|
|
402
|
-
text: z.string().optional().describe('New text for the whole paragraph'),
|
|
412
|
+
text: z.string().optional().describe('New text for the whole paragraph, with formatting tags as read_document shows them'),
|
|
403
413
|
style: z.string().optional().describe('New paragraph style name or id, e.g. "Heading 2"'),
|
|
404
414
|
}),
|
|
405
415
|
run(ctx, args) {
|
|
@@ -413,11 +423,12 @@ const editParagraph = define({
|
|
|
413
423
|
done.push(`style set to ${args.style}`);
|
|
414
424
|
}
|
|
415
425
|
if (args.text !== undefined) {
|
|
426
|
+
const segments = parseMarkup(args.text);
|
|
416
427
|
const range = ctx.editor.paragraphRange(e.para);
|
|
417
428
|
if (range)
|
|
418
|
-
ctx.editor.replaceRange(range,
|
|
429
|
+
ctx.editor.replaceRange(range, piecesFor(e.para, segments));
|
|
419
430
|
else if (args.text)
|
|
420
|
-
ctx.editor
|
|
431
|
+
writeTagged(ctx.editor, e.para.el, segments);
|
|
421
432
|
done.push('text replaced');
|
|
422
433
|
}
|
|
423
434
|
return `Paragraph ${args.paragraph}: ${done.join(', ')}.`;
|
|
@@ -450,7 +461,10 @@ const insertParagraphs = define({
|
|
|
450
461
|
: args.before !== undefined
|
|
451
462
|
? { before: entry(ctx, args.before).para.el }
|
|
452
463
|
: 'end';
|
|
453
|
-
|
|
464
|
+
const segments = parseMarkup(p.text);
|
|
465
|
+
const el = ctx.editor.insertParagraph(where, segments.map((x) => x.text).join(''), opts);
|
|
466
|
+
tagParagraph(ctx.editor, el, segments);
|
|
467
|
+
els.push(el);
|
|
454
468
|
});
|
|
455
469
|
return `Inserted ${plural(els.length, 'paragraph')} (now ${newNumbers(ctx, els)}).`;
|
|
456
470
|
},
|
|
@@ -481,12 +495,167 @@ const deleteParagraphs = define({
|
|
|
481
495
|
return `Deleted ${to === args.from ? `paragraph ${args.from}` : `paragraphs ${args.from}–${to}`}.`;
|
|
482
496
|
},
|
|
483
497
|
});
|
|
498
|
+
/** Where new content goes: after or before a paragraph (its table, if it is in one), or at the end. */
|
|
499
|
+
function placeOf(ctx, args) {
|
|
500
|
+
if (args.after !== undefined && args.before !== undefined)
|
|
501
|
+
throw new Error('Pass after or before, not both.');
|
|
502
|
+
if (args.after !== undefined) {
|
|
503
|
+
const e = entry(ctx, args.after);
|
|
504
|
+
return { where: { after: e.para.el }, said: e.cell ? `after table ${e.cell.table}` : `after paragraph ${args.after}` };
|
|
505
|
+
}
|
|
506
|
+
if (args.before !== undefined) {
|
|
507
|
+
const e = entry(ctx, args.before);
|
|
508
|
+
return { where: { before: e.para.el }, said: e.cell ? `before table ${e.cell.table}` : `before paragraph ${args.before}` };
|
|
509
|
+
}
|
|
510
|
+
return { where: 'end', said: 'at the end' };
|
|
511
|
+
}
|
|
512
|
+
/** The descendants of an element with a name (document order). */
|
|
513
|
+
function findAll(node, name) {
|
|
514
|
+
const out = [];
|
|
515
|
+
for (const c of node.children) {
|
|
516
|
+
if (c.type !== 'element')
|
|
517
|
+
continue;
|
|
518
|
+
if (c.name === name)
|
|
519
|
+
out.push(c);
|
|
520
|
+
out.push(...findAll(c, name));
|
|
521
|
+
}
|
|
522
|
+
return out;
|
|
523
|
+
}
|
|
524
|
+
/** Table `n` (1-based), counted as read_document counts them. */
|
|
525
|
+
function tableAt(ctx, n) {
|
|
526
|
+
const tables = [];
|
|
527
|
+
const walk = (blocks) => {
|
|
528
|
+
for (const b of blocks) {
|
|
529
|
+
if (b.kind !== 'table')
|
|
530
|
+
continue;
|
|
531
|
+
tables.push(b.el);
|
|
532
|
+
for (const row of b.rows)
|
|
533
|
+
for (const c of row.cells)
|
|
534
|
+
walk(c.blocks);
|
|
535
|
+
}
|
|
536
|
+
};
|
|
537
|
+
walk(ctx.doc.body().blocks);
|
|
538
|
+
const t = tables[n - 1];
|
|
539
|
+
if (!t)
|
|
540
|
+
throw new Error(`There is no table ${n}; the document has ${plural(tables.length, 'table')}.`);
|
|
541
|
+
return t;
|
|
542
|
+
}
|
|
543
|
+
const copyParagraphs = define({
|
|
544
|
+
name: 'copy_paragraphs',
|
|
545
|
+
title: 'Copy paragraphs',
|
|
546
|
+
description: 'Copy paragraphs, with their formatting, lists, tables and pictures, to another place (default: the end of the document). ' +
|
|
547
|
+
'A table the range starts or ends in is copied whole. Use it to duplicate content, for example to translate a document on a new page: ' +
|
|
548
|
+
'copy everything with pageBreak, then change the copies’ text with edit_paragraph or replace_text (table cells are paragraphs too). ' +
|
|
549
|
+
'Lists in the copy number from 1 again unless restartLists is false. Comments, bookmarks and footnote references are not copied. Paragraph numbers after the copy shift.',
|
|
550
|
+
role: 'editor',
|
|
551
|
+
kind: 'add',
|
|
552
|
+
schema: z.object({
|
|
553
|
+
from: paragraphNumber.describe('First paragraph to copy'),
|
|
554
|
+
to: paragraphNumber.optional().describe('Last paragraph to copy (default: same as from)'),
|
|
555
|
+
after: paragraphNumber.optional().describe('Put the copy after this paragraph (after its table, if it is in one). Default: at the end'),
|
|
556
|
+
before: paragraphNumber.optional().describe('Put the copy before this paragraph (before its table, if it is in one)'),
|
|
557
|
+
pageBreak: z.boolean().optional().describe('Start the copy on a new page'),
|
|
558
|
+
restartLists: z.boolean().optional().describe('Number lists in the copy from 1 again (default true); false continues the original lists'),
|
|
559
|
+
}),
|
|
560
|
+
async run(ctx, args) {
|
|
561
|
+
const to = args.to ?? args.from;
|
|
562
|
+
if (to < args.from)
|
|
563
|
+
throw new Error('`to` must not be before `from`.');
|
|
564
|
+
const { where, said } = placeOf(ctx, args);
|
|
565
|
+
const { blocks, dropped } = await ctx.editor.copyBlocks(entry(ctx, args.from).para.el, entry(ctx, to).para.el, where, {
|
|
566
|
+
...(args.pageBreak !== undefined ? { pageBreak: args.pageBreak } : {}),
|
|
567
|
+
...(args.restartLists !== undefined ? { restartLists: args.restartLists } : {}),
|
|
568
|
+
});
|
|
569
|
+
const paragraphs = blocks.flatMap((b) => (b.name === 'w:p' ? [b] : findAll(b, 'w:p')));
|
|
570
|
+
const tables = blocks.filter((b) => b.name === 'w:tbl').length;
|
|
571
|
+
const left = [
|
|
572
|
+
dropped.comments ? plural(dropped.comments, 'comment anchor') : '',
|
|
573
|
+
dropped.bookmarks ? plural(dropped.bookmarks, 'bookmark') : '',
|
|
574
|
+
dropped.notes ? plural(dropped.notes, 'footnote reference') : '',
|
|
575
|
+
].filter(Boolean);
|
|
576
|
+
return (`Copied ${to === args.from ? `paragraph ${args.from}` : `paragraphs ${args.from}–${to}`}${tables ? ` (with ${plural(tables, 'table')})` : ''} ${said}` +
|
|
577
|
+
`${args.pageBreak ? ', starting on a new page' : ''}: the copy is ${newNumbers(ctx, paragraphs)}.` +
|
|
578
|
+
(args.restartLists === false ? '' : ' Lists in the copy start again at 1.') +
|
|
579
|
+
(left.length ? ` Not copied: ${left.join(', ')}.` : ''));
|
|
580
|
+
},
|
|
581
|
+
});
|
|
582
|
+
const insertTableOp = define({
|
|
583
|
+
name: 'insert_table',
|
|
584
|
+
title: 'Insert a table',
|
|
585
|
+
description: 'Insert a table of text before or after a paragraph (default: at the end of the document). It spans the text width, with grid lines unless borders is false. ' +
|
|
586
|
+
'Its cells become paragraphs in read_document (“table N, row R, cell C”), so their text can be changed and formatted like any paragraph. Paragraph numbers after it shift.',
|
|
587
|
+
role: 'editor',
|
|
588
|
+
kind: 'add',
|
|
589
|
+
schema: z.object({
|
|
590
|
+
rows: z.array(z.array(z.string()).min(1)).min(1).max(500).describe('The rows, each a list of cell texts; "\\n" in a cell starts a new line. Short rows get empty cells'),
|
|
591
|
+
header: z.boolean().optional().describe('The first row is a header: bold, and repeated at the top of each page the table runs onto'),
|
|
592
|
+
widths: z.array(z.number().positive()).optional().describe('Relative column widths, one per column (e.g. [1, 4, 2]); default: equal'),
|
|
593
|
+
borders: z.boolean().optional().describe('Grid lines (default true)'),
|
|
594
|
+
align: z.enum(['left', 'center', 'right']).optional().describe('Position between the margins (default left)'),
|
|
595
|
+
after: paragraphNumber.optional().describe('Insert after this paragraph (after its table, if it is in one). Default: at the end'),
|
|
596
|
+
before: paragraphNumber.optional().describe('Insert before this paragraph (before its table, if it is in one)'),
|
|
597
|
+
}),
|
|
598
|
+
run(ctx, args) {
|
|
599
|
+
const { where, said } = placeOf(ctx, args);
|
|
600
|
+
const table = ctx.editor.insertTable(where, args.rows, {
|
|
601
|
+
...(args.header !== undefined ? { header: args.header } : {}),
|
|
602
|
+
...(args.widths ? { widths: args.widths } : {}),
|
|
603
|
+
...(args.borders !== undefined ? { borders: args.borders } : {}),
|
|
604
|
+
...(args.align ? { align: args.align } : {}),
|
|
605
|
+
});
|
|
606
|
+
const columns = Math.max(...args.rows.map((r) => r.length));
|
|
607
|
+
const first = listParagraphs(ctx.doc).find((e) => e.para.el === findAll(table, 'w:p')[0]);
|
|
608
|
+
return `Inserted a ${args.rows.length}×${columns} table ${said}${first?.cell ? ` (table ${first.cell.table})` : ''}: its cells are ${newNumbers(ctx, findAll(table, 'w:p'))}.`;
|
|
609
|
+
},
|
|
610
|
+
});
|
|
611
|
+
const editTable = define({
|
|
612
|
+
name: 'edit_table',
|
|
613
|
+
title: 'Add or delete table rows',
|
|
614
|
+
description: 'Change a table’s rows: add rows (they copy the formatting of the row next to them), delete rows, or delete the whole table. ' +
|
|
615
|
+
'Tables are numbered as read_document shows them (“table 2, row 1, cell 1”); to change a cell’s text, edit its paragraph. Paragraph numbers after the table shift.',
|
|
616
|
+
role: 'editor',
|
|
617
|
+
kind: 'change',
|
|
618
|
+
schema: z.object({
|
|
619
|
+
table: z.number().int().min(1).describe('Table number from read_document'),
|
|
620
|
+
action: z.enum(['add_rows', 'delete_rows', 'delete_table']),
|
|
621
|
+
rows: z.array(z.array(z.string())).min(1).optional().describe('add_rows: the new rows, each a list of cell texts'),
|
|
622
|
+
beforeRow: z.number().int().min(1).optional().describe('add_rows: put the new rows before this row (default: after the last row)'),
|
|
623
|
+
fromRow: z.number().int().min(1).optional().describe('delete_rows: first row to delete'),
|
|
624
|
+
toRow: z.number().int().min(1).optional().describe('delete_rows: last row to delete (default: same as fromRow)'),
|
|
625
|
+
}),
|
|
626
|
+
run(ctx, args) {
|
|
627
|
+
const table = tableAt(ctx, args.table);
|
|
628
|
+
const rowsOf = () => table.children.filter((c) => c.type === 'element' && c.name === 'w:tr').length;
|
|
629
|
+
if (args.action === 'delete_table') {
|
|
630
|
+
ctx.editor.deleteTable(table);
|
|
631
|
+
return `Deleted table ${args.table}.`;
|
|
632
|
+
}
|
|
633
|
+
if (args.action === 'add_rows') {
|
|
634
|
+
if (!args.rows)
|
|
635
|
+
throw new Error('Pass rows: the new rows’ cell texts.');
|
|
636
|
+
const at = args.beforeRow === undefined ? rowsOf() : args.beforeRow - 1;
|
|
637
|
+
const made = ctx.editor.insertTableRows(table, at, args.rows);
|
|
638
|
+
return `Added ${plural(made.length, 'row')} to table ${args.table} (now ${plural(rowsOf(), 'row')}): the new cells are ${newNumbers(ctx, made.flatMap((r) => findAll(r, 'w:p')))}.`;
|
|
639
|
+
}
|
|
640
|
+
if (args.fromRow === undefined)
|
|
641
|
+
throw new Error('Pass fromRow: the first row to delete.');
|
|
642
|
+
const toRow = args.toRow ?? args.fromRow;
|
|
643
|
+
if (toRow < args.fromRow)
|
|
644
|
+
throw new Error('`toRow` must not be before `fromRow`.');
|
|
645
|
+
ctx.editor.deleteTableRows(table, args.fromRow - 1, toRow - 1);
|
|
646
|
+
const which = toRow === args.fromRow ? `row ${args.fromRow}` : `rows ${args.fromRow}–${toRow}`;
|
|
647
|
+
const left = table.children.some((c) => c.type === 'element' && c.name === 'w:tr') && listParagraphs(ctx.doc).some((e) => findAll(table, 'w:p').includes(e.para.el));
|
|
648
|
+
return left ? `Deleted ${which} of table ${args.table} (${plural(rowsOf(), 'row')} left).` : `Deleted ${which}, the whole table ${args.table}.`;
|
|
649
|
+
},
|
|
650
|
+
});
|
|
484
651
|
const setList = define({
|
|
485
652
|
name: 'set_list',
|
|
486
653
|
title: 'Change list formatting',
|
|
487
654
|
description: 'Make paragraphs a bulleted or numbered list, or switch a list between bullets, numbers (1. or 1)), letters (a. A.) and roman numerals (i. I.). ' +
|
|
488
655
|
'Also restarts numbering, changes the list level (indent), adds paragraphs to an existing list, or takes them out of a list. ' +
|
|
489
|
-
'Every paragraph from `from` to `to` is affected. A changed list keeps its indentation. read_document shows the labels.'
|
|
656
|
+
'Every paragraph from `from` to `to` is affected. A changed list keeps its indentation. read_document shows the labels. ' +
|
|
657
|
+
'To make one list of paragraphs that are not next to each other (other paragraphs between them), give the first a format, then add each of the others with sameListAs pointing at the first. ' +
|
|
658
|
+
'(To copy a list as it is, copy_paragraphs keeps lists, formatting and tables.)',
|
|
490
659
|
role: 'editor',
|
|
491
660
|
kind: 'change',
|
|
492
661
|
schema: z.object({
|
|
@@ -507,6 +676,9 @@ const setList = define({
|
|
|
507
676
|
const targets = [];
|
|
508
677
|
for (let n = args.from; n <= to; n++)
|
|
509
678
|
targets.push(entry(ctx, n).para.el);
|
|
679
|
+
if (args.sameListAs !== undefined && !entry(ctx, args.sameListAs).para.numbering) {
|
|
680
|
+
throw new Error(`Paragraph ${args.sameListAs} is not in a list yet. Make it one first (set_list from ${args.sameListAs} with a format), then add the others with sameListAs: ${args.sameListAs}.`);
|
|
681
|
+
}
|
|
510
682
|
await ctx.editor.setList(targets, {
|
|
511
683
|
format: args.format,
|
|
512
684
|
start: args.start,
|
|
@@ -912,6 +1084,35 @@ const replaceStoryText = define({
|
|
|
912
1084
|
return `Replaced ${plural(count, 'match', 'matches')} of ${quote(args.find)} in ${story.label}.`;
|
|
913
1085
|
},
|
|
914
1086
|
});
|
|
1087
|
+
/** Write tagged text into an empty paragraph. */
|
|
1088
|
+
export function writeTagged(editor, paragraph, segments) {
|
|
1089
|
+
const text = segments.map((x) => x.text).join('');
|
|
1090
|
+
if (!text)
|
|
1091
|
+
return;
|
|
1092
|
+
editor.appendText(paragraph, text);
|
|
1093
|
+
tagParagraph(editor, paragraph, segments);
|
|
1094
|
+
}
|
|
1095
|
+
/** Format the parts of a paragraph's new text that `segments` tag (its text is their text, in order). */
|
|
1096
|
+
export function tagParagraph(editor, paragraph, segments) {
|
|
1097
|
+
if (!segments.some((x) => x.tags.size))
|
|
1098
|
+
return;
|
|
1099
|
+
const para = editor.paragraphs().find((p) => p.el === paragraph);
|
|
1100
|
+
if (!para)
|
|
1101
|
+
return;
|
|
1102
|
+
const pt = paragraphText(para);
|
|
1103
|
+
const parts = [];
|
|
1104
|
+
let at = 0;
|
|
1105
|
+
for (const seg of segments) {
|
|
1106
|
+
const format = seg.tags.size ? formatFor(seg.tags, new Set()) : undefined;
|
|
1107
|
+
const range = format ? rangeIn(pt, at, at + seg.text.length) : undefined;
|
|
1108
|
+
at += seg.text.length;
|
|
1109
|
+
if (range && format)
|
|
1110
|
+
parts.push({ range, format });
|
|
1111
|
+
}
|
|
1112
|
+
// Later parts first, so earlier positions stay valid as runs are split.
|
|
1113
|
+
for (const { range, format } of parts.reverse())
|
|
1114
|
+
editor.formatRange(range, format);
|
|
1115
|
+
}
|
|
915
1116
|
/** A range for characters [a, b) of a paragraph's text. */
|
|
916
1117
|
function rangeIn(pt, a, b) {
|
|
917
1118
|
const at = (k, side) => {
|
|
@@ -1150,6 +1351,8 @@ export function activityLabel(name) {
|
|
|
1150
1351
|
return 'reading';
|
|
1151
1352
|
if (/^format_|set_list/.test(name))
|
|
1152
1353
|
return 'formatting';
|
|
1354
|
+
if (/^copy_/.test(name))
|
|
1355
|
+
return 'copying';
|
|
1153
1356
|
if (/^delete_|reject_/.test(name))
|
|
1154
1357
|
return 'deleting';
|
|
1155
1358
|
if (/^(insert|add|create)_/.test(name))
|
|
@@ -1176,6 +1379,9 @@ export const OPERATIONS = [
|
|
|
1176
1379
|
editParagraph,
|
|
1177
1380
|
insertParagraphs,
|
|
1178
1381
|
deleteParagraphs,
|
|
1382
|
+
copyParagraphs,
|
|
1383
|
+
insertTableOp,
|
|
1384
|
+
editTable,
|
|
1179
1385
|
setList,
|
|
1180
1386
|
formatText,
|
|
1181
1387
|
addHyperlink,
|
package/dist/outline.js
CHANGED
|
@@ -3,6 +3,7 @@
|
|
|
3
3
|
* from 1, with their style, table position, locks and comments.
|
|
4
4
|
*/
|
|
5
5
|
import { readComments } from 'docxkeun';
|
|
6
|
+
import { markupOf, wholeFormatting } from './markup.js';
|
|
6
7
|
export function paragraphTextOf(para) {
|
|
7
8
|
let text = '';
|
|
8
9
|
for (const inline of para.inlines) {
|
|
@@ -183,6 +184,7 @@ export function quote(text, max = 80) {
|
|
|
183
184
|
const flat = text.replace(/\s+/g, ' ').trim();
|
|
184
185
|
return `"${flat.length > max ? flat.slice(0, max - 1) + '…' : flat}"`;
|
|
185
186
|
}
|
|
187
|
+
const ALIGNMENT = { center: 'centered', right: 'right-aligned', both: 'justified', distribute: 'justified' };
|
|
186
188
|
export function describeParagraph(doc, e, extras = {}) {
|
|
187
189
|
const tags = [];
|
|
188
190
|
const style = e.para.styleId && e.para.styleId !== doc.styles.defaults.paragraph ? styleName(doc, e.para.styleId) : undefined;
|
|
@@ -195,6 +197,12 @@ export function describeParagraph(doc, e, extras = {}) {
|
|
|
195
197
|
tags.push(`list level ${e.para.numbering.ilvl + 1}`);
|
|
196
198
|
if (e.cell)
|
|
197
199
|
tags.push(`table ${e.cell.table}, row ${e.cell.row}, cell ${e.cell.cell}`);
|
|
200
|
+
const align = ALIGNMENT[e.para.props.jc ?? ''];
|
|
201
|
+
if (align)
|
|
202
|
+
tags.push(align);
|
|
203
|
+
const whole = e.text.trim() ? wholeFormatting(e.para) : [];
|
|
204
|
+
if (whole.length)
|
|
205
|
+
tags.push(whole.join(', '));
|
|
198
206
|
for (const { region, whole } of extras.locks ?? []) {
|
|
199
207
|
const name = region.title ? ` "${region.title}"` : '';
|
|
200
208
|
tags.push(`${whole ? 'locked' : 'partly locked'}${name}, lock ${region.id}`);
|
|
@@ -206,7 +214,8 @@ export function describeParagraph(doc, e, extras = {}) {
|
|
|
206
214
|
if (extras.revisions)
|
|
207
215
|
tags.push(`${extras.revisions} tracked change${extras.revisions > 1 ? 's' : ''}`);
|
|
208
216
|
const objects = extras.objects?.length ? ` ${extras.objects.map((o) => `{${o}}`).join(' ')}` : '';
|
|
209
|
-
|
|
217
|
+
const text = e.text ? markupOf(e.para) : '';
|
|
218
|
+
return `[${e.n}]${tags.length ? ` (${tags.join('; ')})` : ''}${text ? ' ' + text : ''}${objects}`;
|
|
210
219
|
}
|
|
211
220
|
export function wordCount(entries) {
|
|
212
221
|
let n = 0;
|
package/dist/preview-page.js
CHANGED
|
@@ -45,6 +45,8 @@ export const PREVIEW_HTML = `<!doctype html>
|
|
|
45
45
|
<span id="status">Connecting…</span>
|
|
46
46
|
<label><input type="checkbox" id="follow" checked> Follow changes</label>
|
|
47
47
|
<label title="How the AI's work shows: shimmer, caret and change marks">AI effects <select id="effects"><option value="animated">Animated</option><option value="still">Still</option><option value="off">Off</option></select></label>
|
|
48
|
+
<label title="How the paragraph the AI is changing looks">Style <select id="aiStyle"></select></label>
|
|
49
|
+
<label title="Keep a mark on what the AI changed until its next change"><input type="checkbox" id="aiMarks" checked> Marks</label>
|
|
48
50
|
<span class="zoom"><button id="zoomOut" aria-label="Zoom out">−</button><span id="zoom">100%</span><button id="zoomIn" aria-label="Zoom in">+</button><button id="fit" aria-pressed="true">Fit width</button></span>
|
|
49
51
|
<span id="sel" hidden title="The AI can read this selection with get_selection"><span></span></span>
|
|
50
52
|
<span id="pages"></span>
|
|
@@ -58,7 +60,7 @@ export const PREVIEW_HTML = `<!doctype html>
|
|
|
58
60
|
</html>
|
|
59
61
|
`;
|
|
60
62
|
export const PREVIEW_SCRIPT = `import { FontRegistry, loadBundledFonts } from './lib/index.js';
|
|
61
|
-
import { DocxViewer } from './lib/render/index.js';
|
|
63
|
+
import { ACTIVITY_STYLES, DocxViewer } from './lib/render/index.js';
|
|
62
64
|
|
|
63
65
|
const $ = (id) => document.getElementById(id);
|
|
64
66
|
const picker = $('doc');
|
|
@@ -105,6 +107,34 @@ effects.addEventListener('change', () => {
|
|
|
105
107
|
} catch {}
|
|
106
108
|
});
|
|
107
109
|
|
|
110
|
+
// The style of the AI's work and whether its marks stay; remembered in this browser.
|
|
111
|
+
const aiStyle = $('aiStyle');
|
|
112
|
+
const aiMarks = $('aiMarks');
|
|
113
|
+
for (const s of ACTIVITY_STYLES) {
|
|
114
|
+
const option = new Option(s.label, s.style);
|
|
115
|
+
option.title = s.description;
|
|
116
|
+
aiStyle.add(option);
|
|
117
|
+
}
|
|
118
|
+
try {
|
|
119
|
+
const saved = localStorage.getItem('docxkeun-ai-style');
|
|
120
|
+
if (saved && ACTIVITY_STYLES.some((s) => s.style === saved)) aiStyle.value = saved;
|
|
121
|
+
aiMarks.checked = localStorage.getItem('docxkeun-ai-marks') !== 'off';
|
|
122
|
+
} catch {}
|
|
123
|
+
viewer.activity.style = aiStyle.value;
|
|
124
|
+
viewer.activity.marksShown = aiMarks.checked;
|
|
125
|
+
aiStyle.addEventListener('change', () => {
|
|
126
|
+
viewer.activity.style = aiStyle.value;
|
|
127
|
+
try {
|
|
128
|
+
localStorage.setItem('docxkeun-ai-style', aiStyle.value);
|
|
129
|
+
} catch {}
|
|
130
|
+
});
|
|
131
|
+
aiMarks.addEventListener('change', () => {
|
|
132
|
+
viewer.activity.marksShown = aiMarks.checked;
|
|
133
|
+
try {
|
|
134
|
+
localStorage.setItem('docxkeun-ai-marks', aiMarks.checked ? 'on' : 'off');
|
|
135
|
+
} catch {}
|
|
136
|
+
});
|
|
137
|
+
|
|
108
138
|
// The AI's name and colours on the pages, from the server's --author and --ai-color.
|
|
109
139
|
try {
|
|
110
140
|
const ai = JSON.parse(document.querySelector('meta[name="docxkeun-ai"]').content || '{}');
|
|
@@ -203,6 +233,8 @@ async function load(path, focus) {
|
|
|
203
233
|
const bytes = new Uint8Array(await res.arrayBuffer());
|
|
204
234
|
// Let the "working" shimmer show for a moment before the result appears.
|
|
205
235
|
if (before) await sleep(Math.max(0, workingSince + 700 - Date.now()));
|
|
236
|
+
// The AI's marks build up while it works on a document; another document starts clean.
|
|
237
|
+
if (loaded !== path) viewer.activity.clearMarks();
|
|
206
238
|
await viewer.load(bytes);
|
|
207
239
|
loaded = path;
|
|
208
240
|
document.title = path + ' · docxkeun live preview';
|
package/dist/server.js
CHANGED
|
@@ -11,7 +11,8 @@ import { describeSelection, DocxEditor, LockedRegionError, paragraphsOf, selecti
|
|
|
11
11
|
import { exportPdf } from 'docxkeun/pdf';
|
|
12
12
|
import { AccessPolicy, PasswordRequiredError, PermissionError, WrongPasswordError, pdfSecurity, readProtection, removeProtection, setProtection, } from 'docxkeun/security';
|
|
13
13
|
import { fontsFor } from './fonts.js';
|
|
14
|
-
import { activityLabel, describeOperation, newParagraph, operationsFor, plural, targetParagraphs } from './operations.js';
|
|
14
|
+
import { activityLabel, describeOperation, newParagraph, operationsFor, plural, tagParagraph, targetParagraphs, writeTagged } from './operations.js';
|
|
15
|
+
import { parseMarkup } from './markup.js';
|
|
15
16
|
import { commentThreads, listParagraphs, locksByParagraph, paragraphStyles, quote, resolveStyle, tableCount, wordCount } from './outline.js';
|
|
16
17
|
import { Queue, Workspace, WorkspaceError } from './workspace.js';
|
|
17
18
|
/** This package's version, read from its package.json (one level above src/ and dist/). */
|
|
@@ -55,7 +56,11 @@ export async function createServer(options) {
|
|
|
55
56
|
instructions: [
|
|
56
57
|
`This server reads and changes Word documents (.docx) in: ${ws.roots.join(', ')}.`,
|
|
57
58
|
'Start with read_document. It numbers paragraphs from 1, including paragraphs in table cells; tools that take `paragraph` use those numbers.',
|
|
58
|
-
'Numbers shift after insert_paragraphs
|
|
59
|
+
'Numbers shift after insert_paragraphs, delete_paragraphs, copy_paragraphs and table changes, so read the document again before reusing numbers from earlier.',
|
|
60
|
+
...(role === 'editor' || role === 'owner'
|
|
61
|
+
? ['Tables: insert_table makes one and edit_table adds or deletes rows; cells are paragraphs, so edit their text like any paragraph. To duplicate content with its formatting, lists and tables (for example to translate a document onto a new page), use copy_paragraphs and then change the copies\u2019 text, rather than retyping it with insert_paragraphs. For a copy or new version of a whole document in another file (for example a translation), use copy_document and then change the copy; create_document makes a blank document without the original\u2019s formatting.',
|
|
62
|
+
'read_document shows text formatted differently from the rest of its paragraph with <b>, <i>, <u>, <s>, <sup> and <sub> tags, and formatting of the whole paragraph in its description. Keep those tags when you rewrite or translate a paragraph with edit_paragraph, so the bold, underlined and other text stays where it was; the paragraph\u2019s own formatting stays by itself.']
|
|
63
|
+
: []),
|
|
59
64
|
'Changes are saved to the file straight away; pass `output` to write a copy instead.',
|
|
60
65
|
`Your role is ${role}: you may ${ROLE_SUMMARY[role]}. Comments you add are signed "${author}".`,
|
|
61
66
|
"Locked regions and the document's own protection are enforced. If an edit is refused, tell the user rather than working around it.",
|
|
@@ -310,7 +315,7 @@ export async function createServer(options) {
|
|
|
310
315
|
if (allows('editor')) {
|
|
311
316
|
tool('create_document', {
|
|
312
317
|
title: 'Create a document',
|
|
313
|
-
description: 'Create a new Word document from paragraphs. The new document has the styles Normal, Heading 1 and Heading 2.',
|
|
318
|
+
description: 'Create a new, blank Word document from paragraphs of plain text. The new document has the styles Normal, Heading 1 and Heading 2 and none of any other document\'s formatting. To copy a document, use copy_document (an exact copy), never retype it here.',
|
|
314
319
|
inputSchema: z.object({
|
|
315
320
|
path,
|
|
316
321
|
paragraphs: z.array(newParagraph).describe('The paragraphs, in order'),
|
|
@@ -328,14 +333,15 @@ export async function createServer(options) {
|
|
|
328
333
|
let prev = first;
|
|
329
334
|
args.paragraphs.forEach((p, i) => {
|
|
330
335
|
const style = styles[i];
|
|
336
|
+
const segments = parseMarkup(p.text);
|
|
331
337
|
if (i === 0) {
|
|
332
338
|
if (style)
|
|
333
339
|
editor.setParagraphStyle(first, style);
|
|
334
|
-
|
|
335
|
-
editor.appendText(first, p.text);
|
|
340
|
+
writeTagged(editor, first, segments);
|
|
336
341
|
}
|
|
337
342
|
else {
|
|
338
|
-
prev = editor.insertParagraph({ after: prev },
|
|
343
|
+
prev = editor.insertParagraph({ after: prev }, segments.map((x) => x.text).join(''), style ? { style } : {});
|
|
344
|
+
tagParagraph(editor, prev, segments);
|
|
339
345
|
}
|
|
340
346
|
});
|
|
341
347
|
await ws.write(dest, await doc.save({ modified: new Date() }));
|
|
@@ -343,6 +349,32 @@ export async function createServer(options) {
|
|
|
343
349
|
preview?.notify({ path: dest, message });
|
|
344
350
|
return message;
|
|
345
351
|
}));
|
|
352
|
+
tool('copy_document', {
|
|
353
|
+
title: 'Copy a document',
|
|
354
|
+
description: 'Copy a document to a new file, exactly as it is: formatting, styles, tables, lists, pictures, headers, footers, comments and page setup. Use it whenever the user wants a copy or a new version of a document (for example a translation in a new file), then change the copy with the other tools.',
|
|
355
|
+
inputSchema: z.object({
|
|
356
|
+
path,
|
|
357
|
+
to: z.string().describe('The new file, a .docx inside the allowed folders'),
|
|
358
|
+
overwrite: z.boolean().optional().describe('Allow `to` to replace an existing file (default false)'),
|
|
359
|
+
}),
|
|
360
|
+
annotations: ADD,
|
|
361
|
+
}, async (args) => queue.run(async () => {
|
|
362
|
+
const source = await ws.resolve(args.path, 'document', true);
|
|
363
|
+
const dest = await ws.resolve(args.to, 'document', false);
|
|
364
|
+
if (dest === source)
|
|
365
|
+
throw new Error(`${ws.display(dest)} is the same file as the original; give the copy another name`);
|
|
366
|
+
if (!args.overwrite && (await ws.exists(dest)))
|
|
367
|
+
throw new Error(`${ws.display(dest)} already exists; pass overwrite: true to replace it`);
|
|
368
|
+
// The bytes as they are: nothing is re-saved, so nothing can be lost.
|
|
369
|
+
const bytes = await ws.read(source);
|
|
370
|
+
await ws.write(dest, bytes);
|
|
371
|
+
const encrypted = bytes[0] === 0xd0 && bytes[1] === 0xcf && bytes[2] === 0x11 && bytes[3] === 0xe0;
|
|
372
|
+
const shown = ws.display(dest);
|
|
373
|
+
const message = `Copied ${ws.display(source)} to ${shown}: an exact copy with all its formatting, tables, lists, pictures, headers, footers and comments. ` +
|
|
374
|
+
`Change the copy with path "${shown}".${encrypted ? ' It opens with the same password.' : ''}`;
|
|
375
|
+
preview?.notify({ path: dest, message: `Copied from ${ws.display(source)}.` });
|
|
376
|
+
return message;
|
|
377
|
+
}));
|
|
346
378
|
}
|
|
347
379
|
// ==== protection (owner) ============================================================================
|
|
348
380
|
if (allows('owner')) {
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "docxkeun-mcp",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.2.0",
|
|
4
4
|
"description": "MCP server for Word .docx files: lets Claude and other AI assistants read, edit, comment on, track changes in, protect and convert .docx files to PDF, with a live preview that shows the AI at work. Built on docxkeun.",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"author": "Kevin Jeremia (https://github.com/kevinkjs)",
|
|
@@ -53,7 +53,7 @@
|
|
|
53
53
|
},
|
|
54
54
|
"dependencies": {
|
|
55
55
|
"@modelcontextprotocol/server": "^2.4.0",
|
|
56
|
-
"docxkeun": "^0.
|
|
56
|
+
"docxkeun": "^0.3.0",
|
|
57
57
|
"docxkeun-fonts": "^0.1.1",
|
|
58
58
|
"zod": "^4.2.0"
|
|
59
59
|
},
|