docxkeun-mcp 0.0.0-stage → 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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Kevin Jeremia
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,149 @@
1
- # Temporary Holding Version
1
+ # docxkeun-mcp
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ An [MCP](https://modelcontextprotocol.io) server for Word documents. It lets Claude (Claude Code, Claude Desktop) and other MCP clients read, edit, comment on, protect and convert `.docx` files to PDF.
4
+
5
+ It is built on [docxkeun](https://github.com/kevinkjs/docxkeun), so it needs no Word, no LibreOffice and no cloud service: the documents are opened, changed and converted on your machine. It only touches files in the folders you give it, and the AI's role (viewer, commenter, editor or owner) is enforced along with the document's own protection and locked regions.
6
+
7
+ ## Set up
8
+
9
+ Node.js 20.12 or newer is needed.
10
+
11
+ **Claude Code**
12
+
13
+ ```bash
14
+ claude mcp add docxkeun -- npx -y docxkeun-mcp ~/Documents/contracts
15
+ ```
16
+
17
+ **Claude Desktop**: add this to `claude_desktop_config.json` (Settings → Developer → Edit Config), then restart Claude:
18
+
19
+ ```json
20
+ {
21
+ "mcpServers": {
22
+ "docxkeun": {
23
+ "command": "npx",
24
+ "args": ["-y", "docxkeun-mcp", "/Users/you/Documents/contracts"]
25
+ }
26
+ }
27
+ }
28
+ ```
29
+
30
+ Claude Desktop starts servers without your shell's `PATH`; if it cannot find `npx`, use its full path (`which npx`).
31
+
32
+ **Other clients**: any MCP client that starts stdio servers can run `npx -y docxkeun-mcp <folder>`.
33
+
34
+ Then ask things like:
35
+
36
+ - "Read contract.docx and comment on anything unusual in the payment terms."
37
+ - "Fill in offer-letter.docx for Dana Putri, start date 1 December, and save it as offer-dana.docx."
38
+ - "Replace ACME Ltd. with Contoso GmbH everywhere in the agreements folder."
39
+ - "Change the a., b. items in the transfer letter to 1., 2."
40
+ - "Lock the signature block, protect the document so others can only comment, and export a PDF."
41
+
42
+ ## Options
43
+
44
+ ```
45
+ docxkeun-mcp [options] [folder ...]
46
+ ```
47
+
48
+ | Option | Meaning |
49
+ |---|---|
50
+ | `folder ...` | The folders the server may read and write (default: the current folder). Subfolders are included. |
51
+ | `--role <role>` | What the AI may do: `viewer`, `commenter`, `editor` (default) or `owner`. |
52
+ | `--author <name>` | The name on comments the AI adds, and on its caret in the live preview (default "AI assistant"). |
53
+ | `--ai-color <color>` | The colour of the AI's caret, shimmer and change marks in the live preview: a CSS colour, or two separated by a comma for a gradient (`"#0b57d0"` or `"#0b57d0,#1e8e3e"`). |
54
+ | `--fonts <folder>` | Extra `.ttf`/`.otf` fonts for page counts and PDF export, e.g. Microsoft Office's fonts for exact Calibri layout. Repeatable. |
55
+ | `--preview` | Also run the [live preview](#live-preview) at `http://127.0.0.1:5230` (or the next free port). |
56
+ | `--preview-port <n>` | The first port to try for the preview. |
57
+ | `--preview-only` | Run only the live preview, without the MCP server, until you stop it: for watching a folder while you edit in Word. |
58
+
59
+ ## Live preview
60
+
61
+ With `--preview`, the server also shows your documents in a web page, drawn by docxkeun's own viewer: pages, comments and list labels. The page redraws a document whenever it changes, whether through a tool or in Word, and shows a note of what the AI did ("Added comment 3 on …"). New comments scroll into view. A rail on the left lists headings, bookmarks and links; comments show as cards beside the page (small bubbles in a narrow pane). Right-click offers Copy, Copy link address and Open link, and Shift+right-click gives the browser's menu.
62
+
63
+ ```bash
64
+ claude mcp add docxkeun -- npx -y docxkeun-mcp --preview ~/Documents/contracts
65
+ ```
66
+
67
+ Ask Claude for the preview link (the `get_preview_link` tool), or open `http://127.0.0.1:5230`. In the Claude desktop app, open it in the browser pane next to the chat. "Follow changes" switches to whichever document the AI is editing, and "Fit width" keeps the page and its comments inside a narrow pane.
68
+
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
+
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
+
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
+
75
+ **Selections.** Select text (or click in a paragraph) in the preview, and the AI can ask what you mean by "this" with `get_selection`: it answers with the document, paragraph numbers, page and the text in «», read from the file. In Claude Code you can also @-mention the `docxkeun://selection` resource. A chip in the preview's header shows what is shared.
76
+
77
+ The preview only listens on 127.0.0.1, only answers requests addressed to that host (so other websites cannot read it through DNS rebinding), serves only the Word documents in the allowed folders, and is read-only. Pages report their selection with a token only the preview's own page has, and only as positions: the text the AI sees always comes from the file. Encrypted documents are not shown, since the preview has no password for them. It stops when the MCP client closes the server.
78
+
79
+ ## Tools
80
+
81
+ Each role gets only the tools it may use.
82
+
83
+ | Tool | What it does | Role |
84
+ |---|---|---|
85
+ | `list_documents` | Word documents in the allowed folders | viewer |
86
+ | `read_document` | Numbered paragraphs with styles, list labels, tables, locks, comments, tracked changes, text direction, and the pictures, charts, shapes and equations in them | viewer |
87
+ | `get_document_info` | Properties, page count, protection, encryption, locked regions, styles | viewer |
88
+ | `find_text` | Matches (text or regex) with paragraph numbers and context | viewer |
89
+ | `list_comments` | Comment threads with anchors and replies | viewer |
90
+ | `list_links` | Hyperlinks and bookmarks | viewer |
91
+ | `list_objects` | Pictures, charts (with their data), SmartArt, shapes, text boxes and equations | viewer |
92
+ | `read_headers_footers` | Headers, footers, footnotes, endnotes and text boxes, with ids for editing | viewer |
93
+ | `list_revisions` | Tracked changes with ids, authors, dates and paragraphs | viewer |
94
+ | `export_pdf` | PDF with embedded fonts, links, outline and comments; optional password and permissions | viewer |
95
+ | `get_preview_link` | A link to the live preview of a document (only with `--preview`) | viewer |
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
+ | `add_comment`, `reply_to_comment`, `resolve_comment`, `delete_comment` | Comments (a commenter may delete only its own) | commenter |
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 |
100
+ | `replace_text` | Find and replace, keeping formatting; regex with `$1` | editor |
101
+ | `fill_template` | `{{placeholder}}` fields and content controls | editor |
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 |
105
+ | `format_text` | Bold, italic, underline, colour, highlight, size, font | editor |
106
+ | `format_paragraph` | Alignment, right-to-left direction, indents, spacing, line spacing, keep and page-break rules | editor |
107
+ | `replace_story_text` | Edit text in a header, footer, footnote, endnote or text box | editor |
108
+ | `set_header_footer`, `remove_header_footer` | Add, replace or remove headers and footers: page numbers (`{PAGE}` of `{NUMPAGES}`), left / centre / right parts, first-page and even-page versions, per section | editor |
109
+ | `insert_image` | A picture file (PNG, JPEG, GIF, BMP, TIFF, EMF, WMF) from the allowed folders | editor |
110
+ | `add_footnote` | A footnote at a place in a paragraph | editor |
111
+ | `set_track_changes` | Turn Word's Track Changes on or off; while on, every edit is a tracked change signed with `--author` | editor |
112
+ | `accept_revisions`, `reject_revisions` | Review tracked changes by id, by author, or all | 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 |
114
+ | `add_hyperlink`, `add_bookmark` | Links to web addresses or bookmarks | editor |
115
+ | `lock_region`, `unlock_region` | Lock text or paragraphs against editing (Word content controls) | owner |
116
+ | `protect_document` | Word's editing restrictions: read-only, comments only, tracked changes only, forms only | owner |
117
+ | `set_open_password` | Encrypt with a password to open (AES-256), or remove it | owner |
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
+
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.
122
+
123
+ ## Safety
124
+
125
+ - **Folders.** Paths outside the given folders are refused, including through symlinks and `..`. Only Word documents (`.docx`, `.docm`, `.dotx`, `.dotm`) and PDFs (for export) are read or written. The server refuses to run with the whole file system as its folder.
126
+ - **Roles and protection.** Every change goes through docxkeun's `AccessPolicy`. A commenter cannot change text; only an owner can lock regions, change protection or set passwords. A document's own protection (for example "comments only") applies to every role except owner, and locked regions apply to everyone.
127
+ - **Writes.** Files are written to a temporary file and renamed, so a failed write never leaves a half-written document. Keep backups or use version control for documents you let an AI edit, and close a document in Word before an AI edits it, since Word does not notice changes made to an open file.
128
+ - **Your data and the AI.** The server itself sends nothing over the network, but your MCP client passes tool results (document text, comments) to its AI model. Passwords you give the AI to open a document are part of that conversation.
129
+ - **Approval.** MCP clients such as Claude Code and Claude Desktop ask before running a tool unless you allow it; tools that change files are marked as such.
130
+
131
+ ## Limitations
132
+
133
+ The tools edit the body (including tables), headers, footers, footnotes, endnotes and text boxes, insert pictures and footnotes, and record and review tracked changes. A document protected for tracked changes can be edited (every edit is recorded) but not reviewed; only its owner can accept or reject changes after removing the protection. Shapes, charts, SmartArt and equations can be read but not created or changed, and pictures can be inserted but not moved or resized. Page counts and PDFs come from docxkeun's own layout and may differ slightly from Word's. See [docxkeun's limitations](https://github.com/kevinkjs/docxkeun#status-and-limitations).
134
+
135
+ ## Use from code
136
+
137
+ ```ts
138
+ import { createServer } from 'docxkeun-mcp';
139
+ import { StdioServerTransport } from '@modelcontextprotocol/server/stdio';
140
+
141
+ const server = await createServer({ folders: ['/srv/documents'], role: 'commenter', author: 'Review Bot' });
142
+ await server.connect(new StdioServerTransport());
143
+ ```
144
+
145
+ `createServer` returns an `McpServer` from the [MCP TypeScript SDK](https://github.com/modelcontextprotocol/typescript-sdk), so it works with any of its transports.
146
+
147
+ ## License
148
+
149
+ [MIT](LICENSE) © Kevin Jeremia
package/dist/cli.d.ts ADDED
@@ -0,0 +1,2 @@
1
+ #!/usr/bin/env node
2
+ export {};
package/dist/cli.js ADDED
@@ -0,0 +1,107 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * docxkeun-mcp: an MCP server (stdio) for Word documents.
4
+ *
5
+ * docxkeun-mcp [--role editor] [--author "AI assistant"] [--fonts DIR] [--preview] [FOLDER ...]
6
+ */
7
+ import { parseArgs } from 'node:util';
8
+ import { StdioServerTransport } from '@modelcontextprotocol/server/stdio';
9
+ import { parseColors, startPreview } from './preview.js';
10
+ import { createServer, ROLES, VERSION } from './server.js';
11
+ const HELP = `docxkeun-mcp ${VERSION}: an MCP server that lets AI assistants read, edit, comment on,
12
+ protect and export Word documents (.docx).
13
+
14
+ Usage: docxkeun-mcp [options] [folder ...]
15
+
16
+ The server only reads and writes files inside the given folders (default: the current folder).
17
+
18
+ Options:
19
+ --role <role> What the AI may do (default: editor)
20
+ viewer read and export PDFs
21
+ commenter viewer + add, reply to and resolve comments
22
+ editor commenter + change text, formatting, links and bookmarks
23
+ owner editor + locks, document protection and passwords
24
+ --author <name> Name on comments the AI adds and on its caret in the live preview
25
+ (default: "AI assistant")
26
+ --ai-color <color> Colour of the AI's caret and highlights in the live preview: a CSS colour,
27
+ or two separated by a comma for a gradient ("#0b57d0" or "#0b57d0,#34a853")
28
+ --fonts <folder> Extra .ttf/.otf fonts for page counts and PDF export (repeatable)
29
+ --preview Also serve a live preview at http://127.0.0.1:5230 (or the next free port)
30
+ that redraws documents whenever they change
31
+ --preview-port <n> First port to try for the preview (default 5230)
32
+ --preview-only Run only the live preview (no MCP server) until stopped,
33
+ e.g. to watch a folder while you edit in Word
34
+ -h, --help Show this help
35
+ -v, --version Show the version
36
+
37
+ Claude Code: claude mcp add docxkeun -- npx -y docxkeun-mcp ~/Documents
38
+ Claude Desktop: {"mcpServers": {"docxkeun": {"command": "npx", "args": ["-y", "docxkeun-mcp", "/Users/you/Documents"]}}}
39
+ `;
40
+ async function main() {
41
+ const { values, positionals } = parseArgs({
42
+ allowPositionals: true,
43
+ options: {
44
+ role: { type: 'string' },
45
+ author: { type: 'string' },
46
+ 'ai-color': { type: 'string' },
47
+ fonts: { type: 'string', multiple: true },
48
+ preview: { type: 'boolean' },
49
+ 'preview-port': { type: 'string' },
50
+ 'preview-only': { type: 'boolean' },
51
+ help: { type: 'boolean', short: 'h' },
52
+ version: { type: 'boolean', short: 'v' },
53
+ },
54
+ });
55
+ if (values.help) {
56
+ process.stdout.write(HELP);
57
+ return;
58
+ }
59
+ if (values.version) {
60
+ process.stdout.write(`${VERSION}\n`);
61
+ return;
62
+ }
63
+ const role = (values.role ?? 'editor');
64
+ if (!ROLES.includes(role))
65
+ throw new Error(`Unknown role "${values.role}" (use ${ROLES.join(', ')})`);
66
+ const folders = positionals.length ? positionals : [process.cwd()];
67
+ let previewPort;
68
+ if (values['preview-port'] !== undefined) {
69
+ previewPort = Number(values['preview-port']);
70
+ if (!Number.isInteger(previewPort) || previewPort < 0 || previewPort > 65535)
71
+ throw new Error(`Not a port: ${values['preview-port']}`);
72
+ }
73
+ const color = values['ai-color'] === undefined ? undefined : parseColors(values['ai-color']);
74
+ // The caret carries the same name as the AI's comments.
75
+ const previewOptions = {
76
+ ...(previewPort === undefined ? {} : { port: previewPort }),
77
+ ai: { name: values.author?.trim() || 'AI assistant', ...(color ? { color } : {}) },
78
+ };
79
+ if (values['preview-only']) {
80
+ const preview = await startPreview(folders, previewOptions);
81
+ process.stdout.write(`docxkeun live preview: ${preview.url}\n`);
82
+ const stop = () => void preview.close().finally(() => process.exit(0));
83
+ process.once('SIGINT', stop);
84
+ process.once('SIGTERM', stop);
85
+ return;
86
+ }
87
+ const preview = values.preview || previewPort !== undefined ? await startPreview(folders, previewOptions) : undefined;
88
+ const server = await createServer({
89
+ folders,
90
+ role,
91
+ ...(values.author ? { author: values.author } : {}),
92
+ ...(values.fonts ? { fontFolders: values.fonts } : {}),
93
+ ...(preview ? { preview } : {}),
94
+ });
95
+ await server.connect(new StdioServerTransport());
96
+ if (preview) {
97
+ // The web server would keep the process alive after the client goes away: stop with stdin.
98
+ const stop = () => void preview.close().finally(() => process.exit(0));
99
+ process.stdin.once('end', stop);
100
+ process.stdin.once('close', stop);
101
+ }
102
+ process.stderr.write(`docxkeun-mcp ${VERSION} running (role: ${role}; folders: ${folders.join(', ')}${preview ? `; preview: ${preview.url}` : ''})\n`);
103
+ }
104
+ main().catch((e) => {
105
+ process.stderr.write(`docxkeun-mcp: ${e instanceof Error ? e.message : String(e)}\n`);
106
+ process.exit(1);
107
+ });
@@ -0,0 +1,3 @@
1
+ import { FontRegistry, type DocxDocument } from 'docxkeun';
2
+ /** A font registry for one document. */
3
+ export declare function fontsFor(doc: DocxDocument, fontFolders?: string[]): Promise<FontRegistry>;
package/dist/fonts.js ADDED
@@ -0,0 +1,64 @@
1
+ /**
2
+ * Fonts for page layout and PDF export: the bundled open fonts (docxkeun-fonts), the document's own
3
+ * embedded fonts, and any font folders given on the command line (for example Microsoft Office's).
4
+ */
5
+ import { readdir, readFile } from 'node:fs/promises';
6
+ import { extname, join } from 'node:path';
7
+ import { Font, FontRegistry, loadBundledFonts, registerEmbeddedFonts } from 'docxkeun';
8
+ import { fontUrls } from 'docxkeun-fonts';
9
+ const bundled = new Map();
10
+ function bundledFile(file) {
11
+ let bytes = bundled.get(file);
12
+ if (!bytes) {
13
+ const url = fontUrls[file];
14
+ if (!url)
15
+ throw new Error(`docxkeun-fonts has no ${file}`);
16
+ bytes = readFile(url).then((b) => new Uint8Array(b));
17
+ bundled.set(file, bytes);
18
+ }
19
+ return bytes;
20
+ }
21
+ const extraFonts = new Map();
22
+ async function readFontFolders(folders) {
23
+ const out = [];
24
+ for (const folder of folders) {
25
+ let names;
26
+ try {
27
+ names = await readdir(folder);
28
+ }
29
+ catch {
30
+ process.stderr.write(`docxkeun-mcp: cannot read font folder ${folder}\n`);
31
+ continue;
32
+ }
33
+ for (const name of names.sort()) {
34
+ if (!['.ttf', '.otf'].includes(extname(name).toLowerCase()))
35
+ continue;
36
+ const file = join(folder, name);
37
+ try {
38
+ out.push(Font.parse(new Uint8Array(await readFile(file))));
39
+ }
40
+ catch {
41
+ // Fonts docxkeun cannot parse (e.g. font collections or some CFF-based .otf files) are skipped.
42
+ process.stderr.write(`docxkeun-mcp: skipped font ${file}\n`);
43
+ }
44
+ }
45
+ }
46
+ return out;
47
+ }
48
+ /** A font registry for one document. */
49
+ export async function fontsFor(doc, fontFolders = []) {
50
+ const registry = new FontRegistry();
51
+ await loadBundledFonts(registry, { load: bundledFile });
52
+ if (fontFolders.length) {
53
+ const key = fontFolders.join('\0');
54
+ let fonts = extraFonts.get(key);
55
+ if (!fonts) {
56
+ fonts = readFontFolders(fontFolders);
57
+ extraFonts.set(key, fonts);
58
+ }
59
+ for (const font of await fonts)
60
+ registry.addFont(font);
61
+ }
62
+ await registerEmbeddedFonts(doc, registry);
63
+ return registry;
64
+ }
@@ -0,0 +1,4 @@
1
+ export { createServer, ROLES, VERSION, type DocxMcpOptions } from './server.js';
2
+ export { Workspace, WorkspaceError, DOCUMENT_EXTENSIONS } from './workspace.js';
3
+ export { startPreview, type Preview, type PreviewEvent, type PreviewOptions } from './preview.js';
4
+ export { OPERATIONS, operationsFor, contextFor, describeOperation, type Operation, type OperationKind, type OperationEnv, type DocContext } from './operations.js';
package/dist/index.js ADDED
@@ -0,0 +1,4 @@
1
+ export { createServer, ROLES, VERSION } from './server.js';
2
+ export { Workspace, WorkspaceError, DOCUMENT_EXTENSIONS } from './workspace.js';
3
+ export { startPreview } from './preview.js';
4
+ export { OPERATIONS, operationsFor, contextFor, describeOperation } from './operations.js';
@@ -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 &lt; &gt; &amp;). */
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, '&amp;').replace(/<(?=\/?(?:sup|sub|b|i|u|s)>)/g, '&lt;');
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 &lt; &gt; &amp;). */
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
+ }