docrev 0.10.0 → 0.10.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (126) hide show
  1. package/.gitattributes +1 -1
  2. package/CHANGELOG.md +173 -164
  3. package/PLAN-tables-and-postprocess.md +850 -850
  4. package/README.md +431 -431
  5. package/bin/rev.js +11 -11
  6. package/bin/rev.ts +145 -145
  7. package/completions/rev.bash +127 -127
  8. package/completions/rev.ps1 +210 -210
  9. package/completions/rev.zsh +207 -207
  10. package/dist/lib/anchor-match.d.ts +1 -1
  11. package/dist/lib/anchor-match.d.ts.map +1 -1
  12. package/dist/lib/anchor-match.js +17 -47
  13. package/dist/lib/anchor-match.js.map +1 -1
  14. package/dist/lib/build.js +4 -4
  15. package/dist/lib/commands/context.d.ts +1 -1
  16. package/dist/lib/commands/context.d.ts.map +1 -1
  17. package/dist/lib/commands/context.js +1 -1
  18. package/dist/lib/commands/context.js.map +1 -1
  19. package/dist/lib/commands/sections.js +7 -7
  20. package/dist/lib/commands/sections.js.map +1 -1
  21. package/dist/lib/commands/sync.d.ts.map +1 -1
  22. package/dist/lib/commands/sync.js +15 -14
  23. package/dist/lib/commands/sync.js.map +1 -1
  24. package/dist/lib/commands/utilities.js +164 -164
  25. package/dist/lib/commands/verify-anchors.js +6 -6
  26. package/dist/lib/commands/verify-anchors.js.map +1 -1
  27. package/dist/lib/commands/word-tools.js +8 -8
  28. package/dist/lib/grammar.js +3 -3
  29. package/dist/lib/macro-filter.lua +201 -201
  30. package/dist/lib/pdf-comments.js +44 -44
  31. package/dist/lib/plugins.js +57 -57
  32. package/dist/lib/pptx-color-filter.lua +37 -37
  33. package/dist/lib/pptx-themes.js +115 -115
  34. package/dist/lib/sections.d.ts +35 -0
  35. package/dist/lib/sections.d.ts.map +1 -1
  36. package/dist/lib/sections.js +81 -0
  37. package/dist/lib/sections.js.map +1 -1
  38. package/dist/lib/spelling.js +2 -2
  39. package/dist/lib/templates.js +387 -387
  40. package/dist/lib/themes.js +51 -51
  41. package/docs-src/build.py +113 -113
  42. package/docs-src/extra.css +208 -208
  43. package/docs-src/md-to-html.lua +6 -6
  44. package/docs-src/template.html +116 -116
  45. package/eslint.config.js +27 -27
  46. package/lib/anchor-match.ts +276 -308
  47. package/lib/annotations.ts +644 -644
  48. package/lib/build.ts +1766 -1766
  49. package/lib/citations.ts +160 -160
  50. package/lib/commands/build.ts +855 -855
  51. package/lib/commands/citations.ts +515 -515
  52. package/lib/commands/comments.ts +1050 -1050
  53. package/lib/commands/context.ts +176 -174
  54. package/lib/commands/core.ts +309 -309
  55. package/lib/commands/doi.ts +435 -435
  56. package/lib/commands/file-ops.ts +372 -372
  57. package/lib/commands/history.ts +320 -320
  58. package/lib/commands/index.ts +87 -87
  59. package/lib/commands/init.ts +259 -259
  60. package/lib/commands/merge-resolve.ts +378 -378
  61. package/lib/commands/preview.ts +178 -178
  62. package/lib/commands/project-info.ts +244 -244
  63. package/lib/commands/quality.ts +517 -517
  64. package/lib/commands/response.ts +454 -454
  65. package/lib/commands/section-boundaries.ts +82 -82
  66. package/lib/commands/sections.ts +451 -451
  67. package/lib/commands/sync.ts +709 -706
  68. package/lib/commands/text-ops.ts +449 -449
  69. package/lib/commands/utilities.ts +448 -448
  70. package/lib/commands/verify-anchors.ts +272 -272
  71. package/lib/commands/word-tools.ts +340 -340
  72. package/lib/comment-realign.ts +517 -517
  73. package/lib/config.ts +84 -84
  74. package/lib/crossref.ts +781 -781
  75. package/lib/csl.ts +191 -191
  76. package/lib/dependencies.ts +98 -98
  77. package/lib/diff-engine.ts +465 -465
  78. package/lib/doi-cache.ts +115 -115
  79. package/lib/doi.ts +897 -897
  80. package/lib/equations.ts +506 -506
  81. package/lib/errors.ts +346 -346
  82. package/lib/format.ts +541 -541
  83. package/lib/git.ts +326 -326
  84. package/lib/grammar.ts +303 -303
  85. package/lib/image-registry.ts +180 -180
  86. package/lib/import.ts +911 -911
  87. package/lib/journals.ts +543 -543
  88. package/lib/macro-filter.lua +201 -201
  89. package/lib/macros.ts +273 -273
  90. package/lib/merge.ts +633 -633
  91. package/lib/orcid.ts +144 -144
  92. package/lib/pdf-comments.ts +263 -263
  93. package/lib/pdf-import.ts +524 -524
  94. package/lib/plugins.ts +362 -362
  95. package/lib/postprocess.ts +188 -188
  96. package/lib/pptx-color-filter.lua +37 -37
  97. package/lib/pptx-template.ts +469 -469
  98. package/lib/pptx-themes.ts +483 -483
  99. package/lib/protect-restore.ts +520 -520
  100. package/lib/rate-limiter.ts +94 -94
  101. package/lib/response.ts +197 -197
  102. package/lib/restore-references.ts +240 -240
  103. package/lib/review.ts +327 -327
  104. package/lib/schema.ts +488 -488
  105. package/lib/scientific-words.ts +73 -73
  106. package/lib/sections.ts +425 -335
  107. package/lib/slides.ts +756 -756
  108. package/lib/spelling.ts +334 -334
  109. package/lib/templates.ts +526 -526
  110. package/lib/themes.ts +742 -742
  111. package/lib/trackchanges.ts +247 -247
  112. package/lib/tui.ts +450 -450
  113. package/lib/types.ts +550 -550
  114. package/lib/undo.ts +250 -250
  115. package/lib/utils.ts +69 -69
  116. package/lib/variables.ts +179 -179
  117. package/lib/word-extraction.ts +806 -806
  118. package/lib/word.ts +643 -643
  119. package/lib/wordcomments.ts +840 -840
  120. package/mkdocs.yml +64 -64
  121. package/package.json +137 -137
  122. package/scripts/postbuild.js +47 -47
  123. package/skill/REFERENCE.md +539 -539
  124. package/skill/SKILL.md +295 -295
  125. package/tsconfig.json +26 -26
  126. package/types/index.d.ts +525 -525
@@ -1,340 +1,340 @@
1
- /**
2
- * Word document tool commands: annotate, apply, comment
3
- *
4
- * Commands for working with Word documents directly (comments, track changes).
5
- */
6
-
7
- import type { Command } from 'commander';
8
- import {
9
- chalk,
10
- fs,
11
- path,
12
- fmt,
13
- getUserName,
14
- parseAnnotations,
15
- } from './context.js';
16
-
17
- // Options interfaces
18
- interface AnnotateOptions {
19
- message?: string;
20
- search?: string;
21
- author?: string;
22
- }
23
-
24
- interface ApplyOptions {
25
- author?: string;
26
- }
27
-
28
- interface CommentOptions {
29
- author?: string;
30
- }
31
-
32
- /**
33
- * Register word-tools commands with the program
34
- */
35
- export function register(program: Command): void {
36
- // ==========================================================================
37
- // ANNOTATE command - Add comments to Word document
38
- // ==========================================================================
39
-
40
- program
41
- .command('annotate')
42
- .description('Add comment to Word document')
43
- .argument('<docx>', 'Word document')
44
- .option('-m, --message <text>', 'Comment text')
45
- .option('-s, --search <text>', 'Text to attach comment to')
46
- .option('-a, --author <name>', 'Comment author')
47
- .action(async (docxPath: string, options: AnnotateOptions) => {
48
- if (!fs.existsSync(docxPath)) {
49
- console.error(chalk.red(`File not found: ${docxPath}`));
50
- process.exit(1);
51
- }
52
-
53
- if (!options.message) {
54
- console.error(chalk.red('Comment message required (-m)'));
55
- process.exit(1);
56
- }
57
-
58
- const { default: AdmZip } = await import('adm-zip');
59
- const zip = new AdmZip(docxPath);
60
-
61
- // Read document.xml
62
- const docEntry = zip.getEntry('word/document.xml');
63
- if (!docEntry) {
64
- console.error(chalk.red('Invalid Word document'));
65
- process.exit(1);
66
- }
67
-
68
- let docXml = zip.readAsText(docEntry);
69
-
70
- // Read or create comments.xml
71
- let commentsEntry = zip.getEntry('word/comments.xml');
72
- let commentsXml: string;
73
- let nextCommentId = 1;
74
-
75
- if (commentsEntry) {
76
- commentsXml = zip.readAsText(commentsEntry);
77
- const idMatches = commentsXml.match(/w:id="(\d+)"/g) || [];
78
- for (const m of idMatches) {
79
- const id = parseInt(m.match(/\d+/)![0]);
80
- if (id >= nextCommentId) nextCommentId = id + 1;
81
- }
82
- } else {
83
- commentsXml = `<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
84
- <w:comments xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main">
85
- </w:comments>`;
86
- }
87
-
88
- const author = options.author || getUserName() || 'Claude';
89
- const date = new Date().toISOString();
90
- const commentId = nextCommentId;
91
-
92
- // Add comment to comments.xml
93
- const newComment = `<w:comment w:id="${commentId}" w:author="${author}" w:date="${date}">
94
- <w:p><w:r><w:t>${options.message}</w:t></w:r></w:p>
95
- </w:comment>`;
96
-
97
- commentsXml = commentsXml.replace('</w:comments>', `${newComment}\n</w:comments>`);
98
-
99
- // Find text and add comment markers
100
- if (options.search) {
101
- const searchText = options.search;
102
- const textPattern = new RegExp(`(<w:t[^>]*>)([^<]*${searchText.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}[^<]*)(<\/w:t>)`, 'i');
103
-
104
- if (textPattern.test(docXml)) {
105
- docXml = docXml.replace(textPattern, (_match, start, text, end) => {
106
- return `<w:commentRangeStart w:id="${commentId}"/>${start}${text}${end}<w:commentRangeEnd w:id="${commentId}"/><w:r><w:commentReference w:id="${commentId}"/></w:r>`;
107
- });
108
- } else {
109
- console.log(chalk.yellow(`Text "${searchText}" not found in document. Comment added without anchor.`));
110
- }
111
- }
112
-
113
- // Update zip
114
- zip.updateFile('word/document.xml', Buffer.from(docXml));
115
-
116
- if (commentsEntry) {
117
- zip.updateFile('word/comments.xml', Buffer.from(commentsXml));
118
- } else {
119
- zip.addFile('word/comments.xml', Buffer.from(commentsXml));
120
-
121
- // Update [Content_Types].xml
122
- const ctEntry = zip.getEntry('[Content_Types].xml');
123
- if (ctEntry) {
124
- let ctXml = zip.readAsText(ctEntry);
125
- if (!ctXml.includes('comments.xml')) {
126
- ctXml = ctXml.replace('</Types>',
127
- '<Override PartName="/word/comments.xml" ContentType="application/vnd.openxmlformats-officedocument.wordprocessingml.comments+xml"/>\n</Types>');
128
- zip.updateFile('[Content_Types].xml', Buffer.from(ctXml));
129
- }
130
- }
131
-
132
- // Update document.xml.rels
133
- const relsEntry = zip.getEntry('word/_rels/document.xml.rels');
134
- if (relsEntry) {
135
- let relsXml = zip.readAsText(relsEntry);
136
- if (!relsXml.includes('comments.xml')) {
137
- const newRelId = `rId${Date.now()}`;
138
- relsXml = relsXml.replace('</Relationships>',
139
- `<Relationship Id="${newRelId}" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/comments" Target="comments.xml"/>\n</Relationships>`);
140
- zip.updateFile('word/_rels/document.xml.rels', Buffer.from(relsXml));
141
- }
142
- }
143
- }
144
-
145
- // Write back
146
- zip.writeZip(docxPath);
147
- console.log(fmt.status('success', `Added comment to ${docxPath}`));
148
- });
149
-
150
- // ==========================================================================
151
- // APPLY command - Apply MD annotations as Word track changes
152
- // ==========================================================================
153
-
154
- program
155
- .command('apply')
156
- .description('Apply markdown annotations to Word document as track changes')
157
- .argument('<md>', 'Markdown file with annotations')
158
- .argument('<docx>', 'Output Word document')
159
- .option('-a, --author <name>', 'Author name for track changes')
160
- .action(async (mdPath: string, docxPath: string, options: ApplyOptions) => {
161
- if (!fs.existsSync(mdPath)) {
162
- console.error(chalk.red(`File not found: ${mdPath}`));
163
- process.exit(1);
164
- }
165
-
166
- const mdContent = fs.readFileSync(mdPath, 'utf-8');
167
- const annotations = parseAnnotations(mdContent);
168
-
169
- if (annotations.length === 0) {
170
- console.log(chalk.yellow('No annotations found in markdown file'));
171
- }
172
-
173
- const author = options.author || getUserName() || 'Author';
174
-
175
- // Build document with track changes
176
- const { buildWithTrackChanges } = await import('../trackchanges.js');
177
-
178
- try {
179
- const result = await buildWithTrackChanges(mdPath, docxPath, { author });
180
-
181
- if (result.success) {
182
- console.log(fmt.status('success', result.message));
183
- console.log(chalk.dim(` ${annotations.length} annotations applied as track changes`));
184
- } else {
185
- console.error(chalk.red(result.message));
186
- process.exit(1);
187
- }
188
- } catch (err) {
189
- console.error(chalk.red(`Error: ${(err as Error).message}`));
190
- process.exit(1);
191
- }
192
- });
193
-
194
- // ==========================================================================
195
- // COMMENT command - Interactive comment addition to DOCX
196
- // ==========================================================================
197
-
198
- program
199
- .command('comment')
200
- .description('Add comments to Word document interactively')
201
- .argument('<docx>', 'Word document')
202
- .option('-a, --author <name>', 'Comment author')
203
- .action(async (docxPath: string, options: CommentOptions) => {
204
- if (!fs.existsSync(docxPath)) {
205
- console.error(chalk.red(`File not found: ${docxPath}`));
206
- process.exit(1);
207
- }
208
-
209
- const { default: AdmZip } = await import('adm-zip');
210
- const readline = await import('readline');
211
- const rl = readline.createInterface({
212
- input: process.stdin,
213
- output: process.stdout,
214
- });
215
-
216
- const ask = (prompt: string): Promise<string> => new Promise((resolve) => rl.question(prompt, resolve));
217
-
218
- const author = options.author || getUserName() || 'Reviewer';
219
-
220
- console.log(fmt.header('Interactive Comment Mode'));
221
- console.log(chalk.dim(` Document: ${docxPath}`));
222
- console.log(chalk.dim(` Author: ${author}`));
223
- console.log(chalk.dim(' Type your comment, then the text to attach it to.'));
224
- console.log(chalk.dim(' Enter empty comment to quit.\n'));
225
-
226
- let commentsAdded = 0;
227
-
228
- while (true) {
229
- const message = await ask(chalk.cyan('Comment: '));
230
-
231
- if (!message.trim()) {
232
- break;
233
- }
234
-
235
- const searchText = await ask(chalk.cyan('Attach to text: '));
236
-
237
- // Load document fresh each time
238
- const zip = new AdmZip(docxPath);
239
- const docEntry = zip.getEntry('word/document.xml');
240
-
241
- if (!docEntry) {
242
- console.error(chalk.red('Invalid Word document'));
243
- rl.close();
244
- process.exit(1);
245
- }
246
-
247
- let docXml = zip.readAsText(docEntry);
248
-
249
- // Read or create comments.xml
250
- let commentsEntry = zip.getEntry('word/comments.xml');
251
- let commentsXml: string;
252
- let nextCommentId = 1;
253
-
254
- if (commentsEntry) {
255
- commentsXml = zip.readAsText(commentsEntry);
256
- const idMatches = commentsXml.match(/w:id="(\d+)"/g) || [];
257
- for (const m of idMatches) {
258
- const id = parseInt(m.match(/\d+/)![0]);
259
- if (id >= nextCommentId) nextCommentId = id + 1;
260
- }
261
- } else {
262
- commentsXml = `<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
263
- <w:comments xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main">
264
- </w:comments>`;
265
- }
266
-
267
- const date = new Date().toISOString();
268
- const commentId = nextCommentId;
269
-
270
- // Add comment to comments.xml
271
- const newComment = `<w:comment w:id="${commentId}" w:author="${author}" w:date="${date}">
272
- <w:p><w:r><w:t>${message}</w:t></w:r></w:p>
273
- </w:comment>`;
274
-
275
- commentsXml = commentsXml.replace('</w:comments>', `${newComment}\n</w:comments>`);
276
-
277
- // Find text and add comment markers
278
- if (searchText.trim()) {
279
- const escapedSearch = searchText.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
280
- const textPattern = new RegExp(`(<w:t[^>]*>)([^<]*${escapedSearch}[^<]*)(<\/w:t>)`, 'i');
281
-
282
- if (textPattern.test(docXml)) {
283
- docXml = docXml.replace(textPattern, (_match, start, text, end) => {
284
- return `<w:commentRangeStart w:id="${commentId}"/>${start}${text}${end}<w:commentRangeEnd w:id="${commentId}"/><w:r><w:commentReference w:id="${commentId}"/></w:r>`;
285
- });
286
- console.log(chalk.green(` ✓ Comment added at "${searchText}"`));
287
- } else {
288
- console.log(chalk.yellow(` Text not found. Comment added without anchor.`));
289
- }
290
- } else {
291
- console.log(chalk.dim(` Comment added without anchor.`));
292
- }
293
-
294
- // Update zip
295
- zip.updateFile('word/document.xml', Buffer.from(docXml));
296
-
297
- if (commentsEntry) {
298
- zip.updateFile('word/comments.xml', Buffer.from(commentsXml));
299
- } else {
300
- zip.addFile('word/comments.xml', Buffer.from(commentsXml));
301
-
302
- // Update [Content_Types].xml
303
- const ctEntry = zip.getEntry('[Content_Types].xml');
304
- if (ctEntry) {
305
- let ctXml = zip.readAsText(ctEntry);
306
- if (!ctXml.includes('comments.xml')) {
307
- ctXml = ctXml.replace('</Types>',
308
- '<Override PartName="/word/comments.xml" ContentType="application/vnd.openxmlformats-officedocument.wordprocessingml.comments+xml"/>\n</Types>');
309
- zip.updateFile('[Content_Types].xml', Buffer.from(ctXml));
310
- }
311
- }
312
-
313
- // Update document.xml.rels
314
- const relsEntry = zip.getEntry('word/_rels/document.xml.rels');
315
- if (relsEntry) {
316
- let relsXml = zip.readAsText(relsEntry);
317
- if (!relsXml.includes('comments.xml')) {
318
- const newRelId = `rId${Date.now()}`;
319
- relsXml = relsXml.replace('</Relationships>',
320
- `<Relationship Id="${newRelId}" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/comments" Target="comments.xml"/>\n</Relationships>`);
321
- zip.updateFile('word/_rels/document.xml.rels', Buffer.from(relsXml));
322
- }
323
- }
324
- }
325
-
326
- zip.writeZip(docxPath);
327
- commentsAdded++;
328
- console.log();
329
- }
330
-
331
- rl.close();
332
- console.log();
333
-
334
- if (commentsAdded > 0) {
335
- console.log(fmt.status('success', `Added ${commentsAdded} comment(s) to ${docxPath}`));
336
- } else {
337
- console.log(chalk.dim('No comments added.'));
338
- }
339
- });
340
- }
1
+ /**
2
+ * Word document tool commands: annotate, apply, comment
3
+ *
4
+ * Commands for working with Word documents directly (comments, track changes).
5
+ */
6
+
7
+ import type { Command } from 'commander';
8
+ import {
9
+ chalk,
10
+ fs,
11
+ path,
12
+ fmt,
13
+ getUserName,
14
+ parseAnnotations,
15
+ } from './context.js';
16
+
17
+ // Options interfaces
18
+ interface AnnotateOptions {
19
+ message?: string;
20
+ search?: string;
21
+ author?: string;
22
+ }
23
+
24
+ interface ApplyOptions {
25
+ author?: string;
26
+ }
27
+
28
+ interface CommentOptions {
29
+ author?: string;
30
+ }
31
+
32
+ /**
33
+ * Register word-tools commands with the program
34
+ */
35
+ export function register(program: Command): void {
36
+ // ==========================================================================
37
+ // ANNOTATE command - Add comments to Word document
38
+ // ==========================================================================
39
+
40
+ program
41
+ .command('annotate')
42
+ .description('Add comment to Word document')
43
+ .argument('<docx>', 'Word document')
44
+ .option('-m, --message <text>', 'Comment text')
45
+ .option('-s, --search <text>', 'Text to attach comment to')
46
+ .option('-a, --author <name>', 'Comment author')
47
+ .action(async (docxPath: string, options: AnnotateOptions) => {
48
+ if (!fs.existsSync(docxPath)) {
49
+ console.error(chalk.red(`File not found: ${docxPath}`));
50
+ process.exit(1);
51
+ }
52
+
53
+ if (!options.message) {
54
+ console.error(chalk.red('Comment message required (-m)'));
55
+ process.exit(1);
56
+ }
57
+
58
+ const { default: AdmZip } = await import('adm-zip');
59
+ const zip = new AdmZip(docxPath);
60
+
61
+ // Read document.xml
62
+ const docEntry = zip.getEntry('word/document.xml');
63
+ if (!docEntry) {
64
+ console.error(chalk.red('Invalid Word document'));
65
+ process.exit(1);
66
+ }
67
+
68
+ let docXml = zip.readAsText(docEntry);
69
+
70
+ // Read or create comments.xml
71
+ let commentsEntry = zip.getEntry('word/comments.xml');
72
+ let commentsXml: string;
73
+ let nextCommentId = 1;
74
+
75
+ if (commentsEntry) {
76
+ commentsXml = zip.readAsText(commentsEntry);
77
+ const idMatches = commentsXml.match(/w:id="(\d+)"/g) || [];
78
+ for (const m of idMatches) {
79
+ const id = parseInt(m.match(/\d+/)![0]);
80
+ if (id >= nextCommentId) nextCommentId = id + 1;
81
+ }
82
+ } else {
83
+ commentsXml = `<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
84
+ <w:comments xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main">
85
+ </w:comments>`;
86
+ }
87
+
88
+ const author = options.author || getUserName() || 'Claude';
89
+ const date = new Date().toISOString();
90
+ const commentId = nextCommentId;
91
+
92
+ // Add comment to comments.xml
93
+ const newComment = `<w:comment w:id="${commentId}" w:author="${author}" w:date="${date}">
94
+ <w:p><w:r><w:t>${options.message}</w:t></w:r></w:p>
95
+ </w:comment>`;
96
+
97
+ commentsXml = commentsXml.replace('</w:comments>', `${newComment}\n</w:comments>`);
98
+
99
+ // Find text and add comment markers
100
+ if (options.search) {
101
+ const searchText = options.search;
102
+ const textPattern = new RegExp(`(<w:t[^>]*>)([^<]*${searchText.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}[^<]*)(<\/w:t>)`, 'i');
103
+
104
+ if (textPattern.test(docXml)) {
105
+ docXml = docXml.replace(textPattern, (_match, start, text, end) => {
106
+ return `<w:commentRangeStart w:id="${commentId}"/>${start}${text}${end}<w:commentRangeEnd w:id="${commentId}"/><w:r><w:commentReference w:id="${commentId}"/></w:r>`;
107
+ });
108
+ } else {
109
+ console.log(chalk.yellow(`Text "${searchText}" not found in document. Comment added without anchor.`));
110
+ }
111
+ }
112
+
113
+ // Update zip
114
+ zip.updateFile('word/document.xml', Buffer.from(docXml));
115
+
116
+ if (commentsEntry) {
117
+ zip.updateFile('word/comments.xml', Buffer.from(commentsXml));
118
+ } else {
119
+ zip.addFile('word/comments.xml', Buffer.from(commentsXml));
120
+
121
+ // Update [Content_Types].xml
122
+ const ctEntry = zip.getEntry('[Content_Types].xml');
123
+ if (ctEntry) {
124
+ let ctXml = zip.readAsText(ctEntry);
125
+ if (!ctXml.includes('comments.xml')) {
126
+ ctXml = ctXml.replace('</Types>',
127
+ '<Override PartName="/word/comments.xml" ContentType="application/vnd.openxmlformats-officedocument.wordprocessingml.comments+xml"/>\n</Types>');
128
+ zip.updateFile('[Content_Types].xml', Buffer.from(ctXml));
129
+ }
130
+ }
131
+
132
+ // Update document.xml.rels
133
+ const relsEntry = zip.getEntry('word/_rels/document.xml.rels');
134
+ if (relsEntry) {
135
+ let relsXml = zip.readAsText(relsEntry);
136
+ if (!relsXml.includes('comments.xml')) {
137
+ const newRelId = `rId${Date.now()}`;
138
+ relsXml = relsXml.replace('</Relationships>',
139
+ `<Relationship Id="${newRelId}" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/comments" Target="comments.xml"/>\n</Relationships>`);
140
+ zip.updateFile('word/_rels/document.xml.rels', Buffer.from(relsXml));
141
+ }
142
+ }
143
+ }
144
+
145
+ // Write back
146
+ zip.writeZip(docxPath);
147
+ console.log(fmt.status('success', `Added comment to ${docxPath}`));
148
+ });
149
+
150
+ // ==========================================================================
151
+ // APPLY command - Apply MD annotations as Word track changes
152
+ // ==========================================================================
153
+
154
+ program
155
+ .command('apply')
156
+ .description('Apply markdown annotations to Word document as track changes')
157
+ .argument('<md>', 'Markdown file with annotations')
158
+ .argument('<docx>', 'Output Word document')
159
+ .option('-a, --author <name>', 'Author name for track changes')
160
+ .action(async (mdPath: string, docxPath: string, options: ApplyOptions) => {
161
+ if (!fs.existsSync(mdPath)) {
162
+ console.error(chalk.red(`File not found: ${mdPath}`));
163
+ process.exit(1);
164
+ }
165
+
166
+ const mdContent = fs.readFileSync(mdPath, 'utf-8');
167
+ const annotations = parseAnnotations(mdContent);
168
+
169
+ if (annotations.length === 0) {
170
+ console.log(chalk.yellow('No annotations found in markdown file'));
171
+ }
172
+
173
+ const author = options.author || getUserName() || 'Author';
174
+
175
+ // Build document with track changes
176
+ const { buildWithTrackChanges } = await import('../trackchanges.js');
177
+
178
+ try {
179
+ const result = await buildWithTrackChanges(mdPath, docxPath, { author });
180
+
181
+ if (result.success) {
182
+ console.log(fmt.status('success', result.message));
183
+ console.log(chalk.dim(` ${annotations.length} annotations applied as track changes`));
184
+ } else {
185
+ console.error(chalk.red(result.message));
186
+ process.exit(1);
187
+ }
188
+ } catch (err) {
189
+ console.error(chalk.red(`Error: ${(err as Error).message}`));
190
+ process.exit(1);
191
+ }
192
+ });
193
+
194
+ // ==========================================================================
195
+ // COMMENT command - Interactive comment addition to DOCX
196
+ // ==========================================================================
197
+
198
+ program
199
+ .command('comment')
200
+ .description('Add comments to Word document interactively')
201
+ .argument('<docx>', 'Word document')
202
+ .option('-a, --author <name>', 'Comment author')
203
+ .action(async (docxPath: string, options: CommentOptions) => {
204
+ if (!fs.existsSync(docxPath)) {
205
+ console.error(chalk.red(`File not found: ${docxPath}`));
206
+ process.exit(1);
207
+ }
208
+
209
+ const { default: AdmZip } = await import('adm-zip');
210
+ const readline = await import('readline');
211
+ const rl = readline.createInterface({
212
+ input: process.stdin,
213
+ output: process.stdout,
214
+ });
215
+
216
+ const ask = (prompt: string): Promise<string> => new Promise((resolve) => rl.question(prompt, resolve));
217
+
218
+ const author = options.author || getUserName() || 'Reviewer';
219
+
220
+ console.log(fmt.header('Interactive Comment Mode'));
221
+ console.log(chalk.dim(` Document: ${docxPath}`));
222
+ console.log(chalk.dim(` Author: ${author}`));
223
+ console.log(chalk.dim(' Type your comment, then the text to attach it to.'));
224
+ console.log(chalk.dim(' Enter empty comment to quit.\n'));
225
+
226
+ let commentsAdded = 0;
227
+
228
+ while (true) {
229
+ const message = await ask(chalk.cyan('Comment: '));
230
+
231
+ if (!message.trim()) {
232
+ break;
233
+ }
234
+
235
+ const searchText = await ask(chalk.cyan('Attach to text: '));
236
+
237
+ // Load document fresh each time
238
+ const zip = new AdmZip(docxPath);
239
+ const docEntry = zip.getEntry('word/document.xml');
240
+
241
+ if (!docEntry) {
242
+ console.error(chalk.red('Invalid Word document'));
243
+ rl.close();
244
+ process.exit(1);
245
+ }
246
+
247
+ let docXml = zip.readAsText(docEntry);
248
+
249
+ // Read or create comments.xml
250
+ let commentsEntry = zip.getEntry('word/comments.xml');
251
+ let commentsXml: string;
252
+ let nextCommentId = 1;
253
+
254
+ if (commentsEntry) {
255
+ commentsXml = zip.readAsText(commentsEntry);
256
+ const idMatches = commentsXml.match(/w:id="(\d+)"/g) || [];
257
+ for (const m of idMatches) {
258
+ const id = parseInt(m.match(/\d+/)![0]);
259
+ if (id >= nextCommentId) nextCommentId = id + 1;
260
+ }
261
+ } else {
262
+ commentsXml = `<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
263
+ <w:comments xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main">
264
+ </w:comments>`;
265
+ }
266
+
267
+ const date = new Date().toISOString();
268
+ const commentId = nextCommentId;
269
+
270
+ // Add comment to comments.xml
271
+ const newComment = `<w:comment w:id="${commentId}" w:author="${author}" w:date="${date}">
272
+ <w:p><w:r><w:t>${message}</w:t></w:r></w:p>
273
+ </w:comment>`;
274
+
275
+ commentsXml = commentsXml.replace('</w:comments>', `${newComment}\n</w:comments>`);
276
+
277
+ // Find text and add comment markers
278
+ if (searchText.trim()) {
279
+ const escapedSearch = searchText.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
280
+ const textPattern = new RegExp(`(<w:t[^>]*>)([^<]*${escapedSearch}[^<]*)(<\/w:t>)`, 'i');
281
+
282
+ if (textPattern.test(docXml)) {
283
+ docXml = docXml.replace(textPattern, (_match, start, text, end) => {
284
+ return `<w:commentRangeStart w:id="${commentId}"/>${start}${text}${end}<w:commentRangeEnd w:id="${commentId}"/><w:r><w:commentReference w:id="${commentId}"/></w:r>`;
285
+ });
286
+ console.log(chalk.green(` ✓ Comment added at "${searchText}"`));
287
+ } else {
288
+ console.log(chalk.yellow(` Text not found. Comment added without anchor.`));
289
+ }
290
+ } else {
291
+ console.log(chalk.dim(` Comment added without anchor.`));
292
+ }
293
+
294
+ // Update zip
295
+ zip.updateFile('word/document.xml', Buffer.from(docXml));
296
+
297
+ if (commentsEntry) {
298
+ zip.updateFile('word/comments.xml', Buffer.from(commentsXml));
299
+ } else {
300
+ zip.addFile('word/comments.xml', Buffer.from(commentsXml));
301
+
302
+ // Update [Content_Types].xml
303
+ const ctEntry = zip.getEntry('[Content_Types].xml');
304
+ if (ctEntry) {
305
+ let ctXml = zip.readAsText(ctEntry);
306
+ if (!ctXml.includes('comments.xml')) {
307
+ ctXml = ctXml.replace('</Types>',
308
+ '<Override PartName="/word/comments.xml" ContentType="application/vnd.openxmlformats-officedocument.wordprocessingml.comments+xml"/>\n</Types>');
309
+ zip.updateFile('[Content_Types].xml', Buffer.from(ctXml));
310
+ }
311
+ }
312
+
313
+ // Update document.xml.rels
314
+ const relsEntry = zip.getEntry('word/_rels/document.xml.rels');
315
+ if (relsEntry) {
316
+ let relsXml = zip.readAsText(relsEntry);
317
+ if (!relsXml.includes('comments.xml')) {
318
+ const newRelId = `rId${Date.now()}`;
319
+ relsXml = relsXml.replace('</Relationships>',
320
+ `<Relationship Id="${newRelId}" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/comments" Target="comments.xml"/>\n</Relationships>`);
321
+ zip.updateFile('word/_rels/document.xml.rels', Buffer.from(relsXml));
322
+ }
323
+ }
324
+ }
325
+
326
+ zip.writeZip(docxPath);
327
+ commentsAdded++;
328
+ console.log();
329
+ }
330
+
331
+ rl.close();
332
+ console.log();
333
+
334
+ if (commentsAdded > 0) {
335
+ console.log(fmt.status('success', `Added ${commentsAdded} comment(s) to ${docxPath}`));
336
+ } else {
337
+ console.log(chalk.dim('No comments added.'));
338
+ }
339
+ });
340
+ }