docrev 0.9.18 → 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 (134) hide show
  1. package/.gitattributes +1 -1
  2. package/CHANGELOG.md +173 -149
  3. package/PLAN-tables-and-postprocess.md +850 -850
  4. package/README.md +431 -406
  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/build.d.ts +8 -0
  11. package/dist/lib/build.d.ts.map +1 -1
  12. package/dist/lib/build.js +62 -6
  13. package/dist/lib/build.js.map +1 -1
  14. package/dist/lib/commands/context.d.ts +1 -1
  15. package/dist/lib/commands/context.d.ts.map +1 -1
  16. package/dist/lib/commands/context.js +1 -1
  17. package/dist/lib/commands/context.js.map +1 -1
  18. package/dist/lib/commands/sections.js +7 -7
  19. package/dist/lib/commands/sections.js.map +1 -1
  20. package/dist/lib/commands/sync.d.ts.map +1 -1
  21. package/dist/lib/commands/sync.js +15 -14
  22. package/dist/lib/commands/sync.js.map +1 -1
  23. package/dist/lib/commands/utilities.js +164 -164
  24. package/dist/lib/commands/verify-anchors.js +6 -6
  25. package/dist/lib/commands/verify-anchors.js.map +1 -1
  26. package/dist/lib/commands/word-tools.js +8 -8
  27. package/dist/lib/grammar.js +3 -3
  28. package/dist/lib/macro-filter.lua +201 -0
  29. package/dist/lib/macros.d.ts +102 -0
  30. package/dist/lib/macros.d.ts.map +1 -0
  31. package/dist/lib/macros.js +218 -0
  32. package/dist/lib/macros.js.map +1 -0
  33. package/dist/lib/pdf-comments.js +44 -44
  34. package/dist/lib/plugins.js +57 -57
  35. package/dist/lib/pptx-color-filter.lua +37 -0
  36. package/dist/lib/pptx-themes.js +115 -115
  37. package/dist/lib/schema.d.ts.map +1 -1
  38. package/dist/lib/schema.js +34 -0
  39. package/dist/lib/schema.js.map +1 -1
  40. package/dist/lib/sections.d.ts +35 -0
  41. package/dist/lib/sections.d.ts.map +1 -1
  42. package/dist/lib/sections.js +81 -0
  43. package/dist/lib/sections.js.map +1 -1
  44. package/dist/lib/spelling.js +2 -2
  45. package/dist/lib/templates.js +387 -387
  46. package/dist/lib/themes.js +51 -51
  47. package/eslint.config.js +27 -27
  48. package/lib/anchor-match.ts +276 -276
  49. package/lib/annotations.ts +644 -644
  50. package/lib/build.ts +1766 -1694
  51. package/lib/citations.ts +160 -160
  52. package/lib/commands/build.ts +855 -855
  53. package/lib/commands/citations.ts +515 -515
  54. package/lib/commands/comments.ts +1050 -1050
  55. package/lib/commands/context.ts +176 -174
  56. package/lib/commands/core.ts +309 -309
  57. package/lib/commands/doi.ts +435 -435
  58. package/lib/commands/file-ops.ts +372 -372
  59. package/lib/commands/history.ts +320 -320
  60. package/lib/commands/index.ts +87 -87
  61. package/lib/commands/init.ts +259 -259
  62. package/lib/commands/merge-resolve.ts +378 -378
  63. package/lib/commands/preview.ts +178 -178
  64. package/lib/commands/project-info.ts +244 -244
  65. package/lib/commands/quality.ts +517 -517
  66. package/lib/commands/response.ts +454 -454
  67. package/lib/commands/section-boundaries.ts +82 -82
  68. package/lib/commands/sections.ts +451 -451
  69. package/lib/commands/sync.ts +709 -706
  70. package/lib/commands/text-ops.ts +449 -449
  71. package/lib/commands/utilities.ts +448 -448
  72. package/lib/commands/verify-anchors.ts +272 -272
  73. package/lib/commands/word-tools.ts +340 -340
  74. package/lib/comment-realign.ts +517 -517
  75. package/lib/config.ts +84 -84
  76. package/lib/crossref.ts +781 -781
  77. package/lib/csl.ts +191 -191
  78. package/lib/dependencies.ts +98 -98
  79. package/lib/diff-engine.ts +465 -465
  80. package/lib/doi-cache.ts +115 -115
  81. package/lib/doi.ts +897 -897
  82. package/lib/equations.ts +506 -506
  83. package/lib/errors.ts +346 -346
  84. package/lib/format.ts +541 -541
  85. package/lib/git.ts +326 -326
  86. package/lib/grammar.ts +303 -303
  87. package/lib/image-registry.ts +180 -180
  88. package/lib/import.ts +911 -911
  89. package/lib/journals.ts +543 -543
  90. package/lib/macro-filter.lua +201 -0
  91. package/lib/macros.ts +273 -0
  92. package/lib/merge.ts +633 -633
  93. package/lib/orcid.ts +144 -144
  94. package/lib/pdf-comments.ts +263 -263
  95. package/lib/pdf-import.ts +524 -524
  96. package/lib/plugins.ts +362 -362
  97. package/lib/postprocess.ts +188 -188
  98. package/lib/pptx-color-filter.lua +37 -37
  99. package/lib/pptx-template.ts +469 -469
  100. package/lib/pptx-themes.ts +483 -483
  101. package/lib/protect-restore.ts +520 -520
  102. package/lib/rate-limiter.ts +94 -94
  103. package/lib/response.ts +197 -197
  104. package/lib/restore-references.ts +240 -240
  105. package/lib/review.ts +327 -327
  106. package/lib/schema.ts +488 -454
  107. package/lib/scientific-words.ts +73 -73
  108. package/lib/sections.ts +425 -335
  109. package/lib/slides.ts +756 -756
  110. package/lib/spelling.ts +334 -334
  111. package/lib/templates.ts +526 -526
  112. package/lib/themes.ts +742 -742
  113. package/lib/trackchanges.ts +247 -247
  114. package/lib/tui.ts +450 -450
  115. package/lib/types.ts +550 -550
  116. package/lib/undo.ts +250 -250
  117. package/lib/utils.ts +69 -69
  118. package/lib/variables.ts +179 -179
  119. package/lib/word-extraction.ts +806 -806
  120. package/lib/word.ts +643 -643
  121. package/lib/wordcomments.ts +840 -840
  122. package/package.json +137 -137
  123. package/scripts/postbuild.js +47 -28
  124. package/skill/REFERENCE.md +539 -539
  125. package/skill/SKILL.md +295 -295
  126. package/tsconfig.json +26 -26
  127. package/types/index.d.ts +525 -525
  128. package/issues.md +0 -180
  129. package/site/assets/extra.css +0 -208
  130. package/site/commands.html +0 -926
  131. package/site/configuration.html +0 -469
  132. package/site/index.html +0 -288
  133. package/site/troubleshooting.html +0 -461
  134. package/site/workflow.html +0 -518
@@ -1,855 +1,855 @@
1
- /**
2
- * Build commands: build, install, doctor, refs, migrate
3
- *
4
- * Commands for building documents and managing dependencies.
5
- */
6
-
7
- import {
8
- chalk,
9
- fs,
10
- path,
11
- fmt,
12
- findFiles,
13
- stripAnnotations,
14
- buildRegistry,
15
- detectHardcodedRefs,
16
- convertHardcodedRefs,
17
- getRefStatus,
18
- formatRegistry,
19
- build,
20
- loadBuildConfig,
21
- hasPandoc,
22
- hasPandocCrossref,
23
- formatBuildResults,
24
- getUserName,
25
- } from './context.js';
26
- import type { Command } from 'commander';
27
- import * as readline from 'readline';
28
-
29
- interface RefsOptions {
30
- dir: string;
31
- }
32
-
33
- interface MigrateOptions {
34
- dir: string;
35
- auto?: boolean;
36
- dryRun?: boolean;
37
- }
38
-
39
- interface InstallOptions {
40
- check?: boolean;
41
- }
42
-
43
- interface BuildOptions {
44
- dir: string;
45
- journal?: string;
46
- crossref?: boolean;
47
- toc?: boolean;
48
- showChanges?: boolean;
49
- dual?: boolean;
50
- reference?: string;
51
- theme?: string;
52
- colortheme?: string;
53
- aspectratio?: string;
54
- verbose?: boolean;
55
- pandocArg?: string[];
56
- output?: string;
57
- }
58
-
59
- /**
60
- * Register build commands with the program
61
- */
62
- export function register(program: Command, pkg?: { version?: string }): void {
63
- // ==========================================================================
64
- // REFS command - Show figure/table reference status
65
- // ==========================================================================
66
-
67
- program
68
- .command('refs')
69
- .description('Show figure/table reference registry and status')
70
- .argument('[file]', 'Optional file to analyze for references')
71
- .option('-d, --dir <directory>', 'Directory to scan for anchors', '.')
72
- .action((file: string | undefined, options: RefsOptions) => {
73
- const dir = path.resolve(options.dir);
74
-
75
- if (!fs.existsSync(dir)) {
76
- console.error(chalk.red(`Directory not found: ${dir}`));
77
- process.exit(1);
78
- }
79
-
80
- console.log(chalk.cyan('Building figure/table registry...\n'));
81
-
82
- const registry = buildRegistry(dir);
83
-
84
- console.log(chalk.bold('Registry:'));
85
- console.log(formatRegistry(registry));
86
-
87
- if (file) {
88
- if (!fs.existsSync(file)) {
89
- console.error(chalk.red(`\nFile not found: ${file}`));
90
- process.exit(1);
91
- }
92
-
93
- const text = fs.readFileSync(file, 'utf-8');
94
- const status = getRefStatus(text, registry);
95
-
96
- console.log(chalk.cyan(`\nReferences in ${path.basename(file)}:\n`));
97
-
98
- if (status.dynamic.length > 0) {
99
- console.log(chalk.green(` Dynamic (@fig:, @tbl:): ${status.dynamic.length}`));
100
- for (const ref of status.dynamic.slice(0, 5)) {
101
- console.log(chalk.dim(` ${ref.match}`));
102
- }
103
- if (status.dynamic.length > 5) {
104
- console.log(chalk.dim(` ... and ${status.dynamic.length - 5} more`));
105
- }
106
- }
107
-
108
- if (status.hardcoded.length > 0) {
109
- console.log(chalk.yellow(`\n Hardcoded (Figure 1, Table 2): ${status.hardcoded.length}`));
110
- for (const ref of status.hardcoded.slice(0, 5)) {
111
- console.log(chalk.dim(` "${ref.match}"`));
112
- }
113
- if (status.hardcoded.length > 5) {
114
- console.log(chalk.dim(` ... and ${status.hardcoded.length - 5} more`));
115
- }
116
- console.log(chalk.cyan(`\n Run ${chalk.bold(`rev migrate ${file}`)} to convert to dynamic refs`));
117
- }
118
-
119
- if (status.dynamic.length === 0 && status.hardcoded.length === 0) {
120
- console.log(chalk.dim(' No figure/table references found.'));
121
- }
122
- }
123
- });
124
-
125
- // ==========================================================================
126
- // MIGRATE command - Convert hardcoded refs to dynamic
127
- // ==========================================================================
128
-
129
- program
130
- .command('migrate')
131
- .description('Convert hardcoded figure/table refs to dynamic @-syntax')
132
- .argument('<file>', 'Markdown file to migrate')
133
- .option('-d, --dir <directory>', 'Directory for registry', '.')
134
- .option('--auto', 'Auto-convert without prompting')
135
- .option('--dry-run', 'Preview without saving')
136
- .action(async (file: string, options: MigrateOptions) => {
137
- if (!fs.existsSync(file)) {
138
- console.error(chalk.red(`File not found: ${file}`));
139
- process.exit(1);
140
- }
141
-
142
- const dir = path.resolve(options.dir);
143
- console.log(chalk.cyan('Building figure/table registry...\n'));
144
-
145
- const registry = buildRegistry(dir);
146
- const text = fs.readFileSync(file, 'utf-8');
147
- const refs = detectHardcodedRefs(text);
148
-
149
- if (refs.length === 0) {
150
- console.log(chalk.green('No hardcoded references found.'));
151
- return;
152
- }
153
-
154
- console.log(chalk.yellow(`Found ${refs.length} hardcoded reference(s):\n`));
155
-
156
- if (options.auto) {
157
- const { converted, conversions, warnings } = convertHardcodedRefs(text, registry);
158
-
159
- for (const w of warnings) {
160
- console.log(chalk.yellow(` Warning: ${w}`));
161
- }
162
-
163
- for (const c of conversions) {
164
- console.log(chalk.green(` "${c.from}" → ${c.to}`));
165
- }
166
-
167
- if (options.dryRun) {
168
- console.log(chalk.yellow('\n(Dry run - no changes saved)'));
169
- } else if (conversions.length > 0) {
170
- fs.writeFileSync(file, converted, 'utf-8');
171
- console.log(chalk.green(`\nConverted ${conversions.length} reference(s) in ${file}`));
172
- }
173
- } else {
174
- const rl = readline.createInterface({
175
- input: process.stdin,
176
- output: process.stdout,
177
- });
178
-
179
- let result = text;
180
- let converted = 0;
181
- let skipped = 0;
182
-
183
- const askQuestion = (prompt: string): Promise<string> =>
184
- new Promise((resolve) => rl.question(prompt, resolve));
185
-
186
- const sortedRefs = [...refs].sort((a, b) => b.position - a.position);
187
-
188
- for (const ref of sortedRefs) {
189
- const num = ref.numbers[0];
190
- const { numberToLabel } = await import('../crossref.js');
191
- const label = numberToLabel(ref.type, num.num, num.isSupp, registry);
192
-
193
- if (!label) {
194
- console.log(chalk.yellow(` "${ref.match}" - no matching anchor found, skipping`));
195
- skipped++;
196
- continue;
197
- }
198
-
199
- const replacement = `@${ref.type}:${label}`;
200
- console.log(`\n ${chalk.yellow(`"${ref.match}"`)} → ${chalk.green(replacement)}`);
201
-
202
- const answer = await askQuestion(chalk.cyan(' Convert? [y/n/a/q] '));
203
-
204
- if (answer.toLowerCase() === 'q') {
205
- console.log(chalk.dim(' Quitting...'));
206
- break;
207
- } else if (answer.toLowerCase() === 'a') {
208
- result = result.slice(0, ref.position) + replacement + result.slice(ref.position + ref.match.length);
209
- converted++;
210
-
211
- for (const remaining of sortedRefs.slice(sortedRefs.indexOf(ref) + 1)) {
212
- const rNum = remaining.numbers[0];
213
- const rLabel = numberToLabel(remaining.type, rNum.num, rNum.isSupp, registry);
214
- if (rLabel) {
215
- const rReplacement = `@${remaining.type}:${rLabel}`;
216
- result = result.slice(0, remaining.position) + rReplacement + result.slice(remaining.position + remaining.match.length);
217
- converted++;
218
- console.log(chalk.green(` "${remaining.match}" → ${rReplacement}`));
219
- }
220
- }
221
- break;
222
- } else if (answer.toLowerCase() === 'y') {
223
- result = result.slice(0, ref.position) + replacement + result.slice(ref.position + ref.match.length);
224
- converted++;
225
- } else {
226
- skipped++;
227
- }
228
- }
229
-
230
- rl.close();
231
-
232
- console.log(chalk.cyan(`\nConverted: ${converted}, Skipped: ${skipped}`));
233
-
234
- if (converted > 0 && !options.dryRun) {
235
- fs.writeFileSync(file, result, 'utf-8');
236
- console.log(chalk.green(`Saved ${file}`));
237
- } else if (options.dryRun) {
238
- console.log(chalk.yellow('(Dry run - no changes saved)'));
239
- }
240
- }
241
- });
242
-
243
- // ==========================================================================
244
- // INSTALL command - Install dependencies
245
- // ==========================================================================
246
-
247
- program
248
- .command('install')
249
- .description('Check and install dependencies (pandoc-crossref)')
250
- .option('--check', 'Only check, don\'t install')
251
- .action(async (options: InstallOptions) => {
252
- const os = await import('os');
253
- const { execSync } = await import('child_process');
254
- const platform = os.platform();
255
-
256
- console.log(chalk.cyan('Checking dependencies...\n'));
257
-
258
- let hasPandocInstalled = false;
259
- try {
260
- const version = execSync('pandoc --version', { encoding: 'utf-8' }).split('\n')[0];
261
- console.log(chalk.green(` ✓ ${version}`));
262
- hasPandocInstalled = true;
263
- } catch {
264
- console.log(chalk.red(' ✗ pandoc not found'));
265
- }
266
-
267
- let hasCrossref = false;
268
- try {
269
- const version = execSync('pandoc-crossref --version', { encoding: 'utf-8' }).split('\n')[0];
270
- console.log(chalk.green(` ✓ pandoc-crossref ${version}`));
271
- hasCrossref = true;
272
- } catch {
273
- console.log(chalk.yellow(' ✗ pandoc-crossref not found'));
274
- }
275
-
276
- console.log('');
277
-
278
- if (hasPandocInstalled && hasCrossref) {
279
- console.log(chalk.green('All dependencies installed!'));
280
- return;
281
- }
282
-
283
- if (options.check) {
284
- if (!hasCrossref) {
285
- console.log(chalk.yellow('pandoc-crossref is optional but recommended for @fig: references.'));
286
- }
287
- return;
288
- }
289
-
290
- if (!hasPandocInstalled || !hasCrossref) {
291
- console.log(chalk.cyan('Installation options:\n'));
292
-
293
- if (platform === 'darwin') {
294
- console.log(chalk.bold('macOS (Homebrew):'));
295
- if (!hasPandocInstalled) console.log(chalk.dim(' brew install pandoc'));
296
- if (!hasCrossref) console.log(chalk.dim(' brew install pandoc-crossref'));
297
- console.log('');
298
- } else if (platform === 'win32') {
299
- console.log(chalk.bold('Windows (Chocolatey):'));
300
- if (!hasPandocInstalled) console.log(chalk.dim(' choco install pandoc'));
301
- if (!hasCrossref) console.log(chalk.dim(' choco install pandoc-crossref'));
302
- console.log('');
303
- console.log(chalk.bold('Windows (Scoop):'));
304
- if (!hasPandocInstalled) console.log(chalk.dim(' scoop install pandoc'));
305
- if (!hasCrossref) console.log(chalk.dim(' scoop install pandoc-crossref'));
306
- console.log('');
307
- } else {
308
- console.log(chalk.bold('Linux (apt):'));
309
- if (!hasPandocInstalled) console.log(chalk.dim(' sudo apt install pandoc'));
310
- console.log('');
311
- }
312
-
313
- console.log(chalk.bold('Cross-platform (conda):'));
314
- if (!hasPandocInstalled) console.log(chalk.dim(' conda install -c conda-forge pandoc'));
315
- if (!hasCrossref) console.log(chalk.dim(' conda install -c conda-forge pandoc-crossref'));
316
- console.log('');
317
-
318
- if (!hasCrossref) {
319
- console.log(chalk.bold('Manual download:'));
320
- console.log(chalk.dim(' https://github.com/lierdakil/pandoc-crossref/releases'));
321
- console.log('');
322
- }
323
-
324
- try {
325
- execSync('conda --version', { encoding: 'utf-8', stdio: 'pipe' });
326
- console.log(chalk.cyan('Conda detected. Install missing dependencies? [y/N] '));
327
-
328
- const rl = readline.createInterface({
329
- input: process.stdin,
330
- output: process.stdout,
331
- });
332
-
333
- rl.question('', (answer) => {
334
- rl.close();
335
- if (answer.toLowerCase() === 'y') {
336
- console.log(chalk.cyan('\nInstalling via conda...'));
337
- try {
338
- if (!hasPandocInstalled) {
339
- console.log(chalk.dim(' Installing pandoc...'));
340
- execSync('conda install -y -c conda-forge pandoc', { stdio: 'inherit' });
341
- }
342
- if (!hasCrossref) {
343
- console.log(chalk.dim(' Installing pandoc-crossref...'));
344
- execSync('conda install -y -c conda-forge pandoc-crossref', { stdio: 'inherit' });
345
- }
346
- console.log(chalk.green('\nDone! Run "rev install --check" to verify.'));
347
- } catch (err) {
348
- const error = err as Error;
349
- console.log(chalk.red(`\nInstallation failed: ${error.message}`));
350
- console.log(chalk.dim('Try installing manually with the commands above.'));
351
- }
352
- }
353
- });
354
- } catch {
355
- // Conda not available
356
- }
357
- }
358
- });
359
-
360
- // ==========================================================================
361
- // DOCTOR command - Diagnose setup and configuration issues
362
- // ==========================================================================
363
-
364
- program
365
- .command('doctor')
366
- .description('Diagnose setup and configuration issues')
367
- .action(async () => {
368
- const os = await import('os');
369
- const { execSync } = await import('child_process');
370
-
371
- const version = pkg?.version || 'unknown';
372
- console.log(chalk.bold.cyan(`\n rev doctor`) + chalk.dim(` v${version}\n`));
373
- console.log(chalk.dim(` ${os.platform()} ${os.release()} | Node ${process.version}\n`));
374
-
375
- let issues = 0;
376
- let warnings = 0;
377
-
378
- console.log(chalk.bold(' Environment'));
379
- console.log(chalk.dim(' ─────────────────────────────────'));
380
-
381
- const nodeVer = parseInt(process.version.slice(1).split('.')[0], 10);
382
- if (nodeVer >= 18) {
383
- console.log(chalk.green(' ✓') + ` Node.js ${process.version}`);
384
- } else {
385
- console.log(chalk.red(' ✗') + ` Node.js ${process.version} (requires >=18)`);
386
- issues++;
387
- }
388
-
389
- try {
390
- const pandocVer = execSync('pandoc --version', { encoding: 'utf-8' }).split('\n')[0];
391
- console.log(chalk.green(' ✓') + ` ${pandocVer}`);
392
- } catch {
393
- console.log(chalk.red(' ✗') + ' pandoc not found');
394
- issues++;
395
- }
396
-
397
- try {
398
- const crossrefVer = execSync('pandoc-crossref --version', { encoding: 'utf-8' }).split('\n')[0];
399
- console.log(chalk.green(' ✓') + ` pandoc-crossref ${crossrefVer}`);
400
- } catch {
401
- console.log(chalk.yellow(' !') + ' pandoc-crossref not found (optional)');
402
- warnings++;
403
- }
404
-
405
- console.log();
406
- console.log(chalk.bold(' Project'));
407
- console.log(chalk.dim(' ─────────────────────────────────'));
408
-
409
- const configPath = path.join(process.cwd(), 'rev.yaml');
410
- if (fs.existsSync(configPath)) {
411
- console.log(chalk.green(' ✓') + ' rev.yaml found');
412
-
413
- try {
414
- const { default: YAML } = await import('yaml');
415
- const config = YAML.parse(fs.readFileSync(configPath, 'utf-8'));
416
-
417
- if (config.title) {
418
- console.log(chalk.green(' ✓') + ` Title: ${config.title}`);
419
- } else {
420
- console.log(chalk.yellow(' !') + ' No title in rev.yaml');
421
- warnings++;
422
- }
423
-
424
- if (config.sections && config.sections.length > 0) {
425
- console.log(chalk.green(' ✓') + ` Sections: ${config.sections.length} defined`);
426
-
427
- let missing = 0;
428
- for (const sec of config.sections) {
429
- const secFile = typeof sec === 'string' ? sec : sec.file;
430
- if (!fs.existsSync(secFile)) missing++;
431
- }
432
- if (missing > 0) {
433
- console.log(chalk.yellow(' !') + ` ${missing} section file(s) missing`);
434
- warnings++;
435
- }
436
- }
437
-
438
- if (config.bibliography) {
439
- if (fs.existsSync(config.bibliography)) {
440
- console.log(chalk.green(' ✓') + ` Bibliography: ${config.bibliography}`);
441
- } else {
442
- console.log(chalk.yellow(' !') + ` Bibliography file not found: ${config.bibliography}`);
443
- warnings++;
444
- }
445
- }
446
- } catch (e) {
447
- const error = e as Error;
448
- console.log(chalk.red(' ✗') + ` rev.yaml parse error: ${error.message}`);
449
- issues++;
450
- }
451
- } else {
452
- console.log(chalk.dim(' ·') + ' No rev.yaml (not a rev project)');
453
- }
454
-
455
- const mdFiles = findFiles('.md');
456
- if (mdFiles.length > 0) {
457
- console.log(chalk.green(' ✓') + ` Markdown files: ${mdFiles.length}`);
458
- } else {
459
- console.log(chalk.dim(' ·') + ' No markdown files');
460
- }
461
-
462
- console.log();
463
- if (issues === 0 && warnings === 0) {
464
- console.log(chalk.green.bold(' All checks passed! ✓\n'));
465
- } else if (issues === 0) {
466
- console.log(chalk.yellow(` ${warnings} warning(s), no critical issues\n`));
467
- } else {
468
- console.log(chalk.red(` ${issues} issue(s), ${warnings} warning(s)\n`));
469
- console.log(chalk.dim(' Run "rev install" to fix missing dependencies.\n'));
470
- }
471
- });
472
-
473
- // ==========================================================================
474
- // BUILD command - Combine sections and run pandoc
475
- // ==========================================================================
476
-
477
- program
478
- .command('build')
479
- .alias('b')
480
- .description('Build PDF/DOCX/TEX/PPTX/Beamer from sections')
481
- .argument('[formats...]', 'Output formats: pdf, docx, tex, beamer, pptx, all', ['pdf', 'docx'])
482
- .option('-d, --dir <directory>', 'Project directory', '.')
483
- .option('-j, --journal <name>', 'Use journal profile for build formatting defaults')
484
- .option('--no-crossref', 'Skip pandoc-crossref filter')
485
- .option('--toc', 'Include table of contents')
486
- .option('--show-changes', 'Export DOCX with visible track changes (audit mode)')
487
- .option('--dual', 'Output both clean version and annotated version (with comments)')
488
- .option('--reference <docx>', 'Reference DOCX for comment position alignment (use with --dual)')
489
- .option('--theme <name>', 'Beamer theme (default, metropolis, etc.)')
490
- .option('--colortheme <name>', 'Beamer color theme')
491
- .option('--aspectratio <ratio>', 'Beamer aspect ratio (169, 43)')
492
- .option(
493
- '--pandoc-arg <arg>',
494
- 'Extra arg to pass to pandoc (repeatable). Applied to every format being built; appended after rev.yaml pandoc-args so CLI wins.',
495
- (val: string, prev: string[] = []) => [...prev, val],
496
- []
497
- )
498
- .option('-o, --output <path>', 'Output filename or path. Relative paths resolve under outputDir; absolute paths bypass it. Extension auto-added if missing. Applied to every format being built; overrides rev.yaml output.<format>.')
499
- .option('--verbose', 'Show detailed output including postprocess scripts and the pandoc invocation')
500
- .action(async (formats: string[], options: BuildOptions) => {
501
- const dir = path.resolve(options.dir);
502
-
503
- if (!fs.existsSync(dir)) {
504
- console.error(chalk.red(`Directory not found: ${dir}`));
505
- process.exit(1);
506
- }
507
-
508
- if (!hasPandoc()) {
509
- console.error(chalk.red('pandoc not found.'));
510
- console.error(chalk.dim('Run "rev install" to install dependencies.'));
511
- process.exit(1);
512
- }
513
-
514
- const config = loadBuildConfig(dir);
515
-
516
- if (!config._configPath) {
517
- console.error(chalk.yellow('No rev.yaml found.'));
518
- console.error(chalk.dim('Run "rev new" to create a project, or "rev init" for existing files.'));
519
- process.exit(1);
520
- }
521
-
522
- // Apply journal formatting from CLI flag (overrides rev.yaml journal field)
523
- let journalName: string | undefined;
524
- if (options.journal) {
525
- const { getJournalProfile } = await import('../journals.js');
526
- const { mergeJournalFormatting } = await import('../build.js');
527
- const profile = getJournalProfile(options.journal);
528
- if (!profile) {
529
- console.error(fmt.status('error', `Unknown journal: ${options.journal}`));
530
- console.error(chalk.dim('Use "rev validate --list" to see available profiles'));
531
- process.exit(1);
532
- }
533
- journalName = profile.name;
534
- if (profile.formatting) {
535
- Object.assign(config, mergeJournalFormatting(config, profile.formatting, dir));
536
- }
537
- } else if ((config as unknown as { journal?: string }).journal) {
538
- // Journal set in rev.yaml — already applied by loadConfig, just get name for display
539
- const { getJournalProfile } = await import('../journals.js');
540
- const profile = getJournalProfile((config as unknown as { journal?: string }).journal!);
541
- if (profile) journalName = profile.name;
542
- }
543
-
544
- console.log(fmt.header(`Building ${config.title || 'document'}`));
545
- console.log();
546
-
547
- const targetFormats = formats.length > 0 ? formats : ['pdf', 'docx'];
548
- const tocEnabled = options.toc || config.pdf?.toc || config.docx?.toc;
549
- if (journalName) console.log(chalk.dim(` Journal: ${journalName}`));
550
- console.log(chalk.dim(` Formats: ${targetFormats.join(', ')}`));
551
- console.log(chalk.dim(` Crossref: ${hasPandocCrossref() && options.crossref !== false ? 'enabled' : 'disabled'}`));
552
- if (tocEnabled) console.log(chalk.dim(` TOC: enabled`));
553
- if (options.showChanges) console.log(chalk.dim(` Track changes: visible`));
554
- if (options.dual) console.log(chalk.dim(` Dual output: clean + with comments`));
555
- console.log('');
556
-
557
- if (options.toc) {
558
- config.pdf = config.pdf || {};
559
- config.pdf.toc = true;
560
- config.docx = config.docx || {};
561
- config.docx.toc = true;
562
- }
563
-
564
- if (options.dual) {
565
- config.docx = config.docx || {};
566
- config.docx.keepComments = false;
567
- }
568
-
569
- // Apply beamer CLI options
570
- if (options.theme) {
571
- config.beamer = config.beamer || {};
572
- config.beamer.theme = options.theme;
573
- }
574
- if (options.colortheme) {
575
- config.beamer = config.beamer || {};
576
- config.beamer.colortheme = options.colortheme;
577
- }
578
- if (options.aspectratio) {
579
- config.beamer = config.beamer || {};
580
- config.beamer.aspectratio = options.aspectratio;
581
- }
582
-
583
- if (options.showChanges) {
584
- if (!targetFormats.includes('docx') && !targetFormats.includes('all')) {
585
- console.error(fmt.status('error', '--show-changes only applies to DOCX output'));
586
- process.exit(1);
587
- }
588
-
589
- const { combineSections, resolveOutputPath } = await import('../build.js');
590
- const { buildWithTrackChanges } = await import('../trackchanges.js');
591
-
592
- const spin = fmt.spinner('Building with track changes...').start();
593
-
594
- try {
595
- const paperPath = combineSections(dir, config);
596
- spin.stop();
597
- console.log(chalk.cyan('Combined sections → paper.md'));
598
- console.log(chalk.dim(` ${paperPath}\n`));
599
-
600
- const outputPath = resolveOutputPath(dir, config, 'docx', {
601
- cliOverride: options.output,
602
- suffix: '-changes',
603
- });
604
- const outDir = path.dirname(outputPath);
605
- if (!fs.existsSync(outDir)) fs.mkdirSync(outDir, { recursive: true });
606
-
607
- const spinTc = fmt.spinner('Applying track changes...').start();
608
- const result = await buildWithTrackChanges(paperPath, outputPath, {
609
- author: getUserName() || 'Author',
610
- });
611
- spinTc.stop();
612
-
613
- if (result.success) {
614
- console.log(chalk.cyan('Output (with track changes):'));
615
- console.log(` DOCX: ${path.basename(outputPath)}`);
616
- if (result.stats) {
617
- console.log(chalk.dim(` ${result.stats.insertions} insertions, ${result.stats.deletions} deletions, ${result.stats.substitutions} substitutions`));
618
- }
619
- console.log(chalk.green('\nBuild complete!'));
620
- } else {
621
- console.error(fmt.status('error', result.message));
622
- process.exit(1);
623
- }
624
- } catch (err) {
625
- spin.stop();
626
- const error = err as Error;
627
- console.error(fmt.status('error', error.message));
628
- if (process.env.DEBUG) console.error(error.stack);
629
- process.exit(1);
630
- }
631
- return;
632
- }
633
-
634
- const spin = fmt.spinner('Building...').start();
635
-
636
- try {
637
- const { results, paperPath, forwardRefsResolved, refsAutoInjected, warnings } = await build(dir, targetFormats, {
638
- crossref: options.crossref,
639
- config,
640
- verbose: options.verbose,
641
- pandocArgs: options.pandocArg,
642
- output: options.output,
643
- });
644
-
645
- spin.stop();
646
-
647
- console.log(chalk.cyan('Combined sections → paper.md'));
648
- console.log(chalk.dim(` ${paperPath}`));
649
- if (forwardRefsResolved > 0) {
650
- console.log(chalk.dim(` ${forwardRefsResolved} forward reference(s) pre-resolved`));
651
- }
652
- if (refsAutoInjected) {
653
- console.log(chalk.dim(` References section auto-injected before supplementary`));
654
- }
655
- console.log('');
656
-
657
- if (warnings && warnings.length > 0) {
658
- for (const w of warnings) {
659
- // Each warning may span multiple lines — colour the first line as
660
- // a warning header and pass through the rest unchanged.
661
- const [head, ...rest] = w.split('\n');
662
- console.log(chalk.yellow(`Warning: ${head}`));
663
- for (const line of rest) console.log(chalk.yellow(line));
664
- }
665
- console.log('');
666
- }
667
-
668
- console.log(chalk.cyan('Output:'));
669
- console.log(formatBuildResults(results));
670
-
671
- const failed = results.filter((r) => !r.success);
672
- if (failed.length > 0) {
673
- console.log('');
674
- for (const f of failed) {
675
- console.error(chalk.red(`\n${f.format} error:\n${f.error}`));
676
- }
677
- process.exit(1);
678
- }
679
-
680
- // Handle --dual mode
681
- if (options.dual) {
682
- const docxResult = results.find(r => r.format === 'docx' && r.success);
683
- if (docxResult) {
684
- const { prepareMarkdownWithMarkers, injectCommentsAtMarkers } = await import('../wordcomments.js');
685
- const { runPandoc, applyFormatTransforms } = await import('../build.js');
686
-
687
- let markdown = fs.readFileSync(paperPath, 'utf-8');
688
-
689
- if (options.reference) {
690
- const refPath = path.resolve(dir, options.reference);
691
- if (fs.existsSync(refPath)) {
692
- const spinRealign = fmt.spinner('Realigning comments from reference...').start();
693
- const { realignMarkdown } = await import('../comment-realign.js');
694
- const realigned = await realignMarkdown(refPath, markdown);
695
- if (realigned.success) {
696
- markdown = realigned.markdown;
697
- spinRealign.stop();
698
- console.log(chalk.dim(` Realigned ${realigned.insertions} comments from reference`));
699
- } else {
700
- spinRealign.stop();
701
- console.log(chalk.yellow(` Warning: Could not realign comments: ${realigned.error}`));
702
- }
703
- } else {
704
- console.log(chalk.yellow(` Warning: Reference not found: ${options.reference}`));
705
- }
706
- }
707
-
708
- markdown = stripAnnotations(markdown, { keepComments: true });
709
-
710
- // Apply DOCX transforms (author affiliations, @fig: → "Figure 1")
711
- // before injecting markers, so the comments DOCX matches the clean
712
- // DOCX in everything but the comments themselves.
713
- const registry = buildRegistry(dir, config.sections);
714
- markdown = applyFormatTransforms(markdown, 'docx', config, registry);
715
-
716
- const spinMarkers = fmt.spinner('Preparing markers...').start();
717
- const { markedMarkdown, comments } = prepareMarkdownWithMarkers(markdown);
718
- spinMarkers.stop();
719
-
720
- if (comments.length === 0) {
721
- console.log(chalk.yellow('\nNo comments found - skipping comments DOCX'));
722
- } else {
723
- const markedPath = path.join(dir, '.paper-marked.md');
724
- fs.writeFileSync(markedPath, markedMarkdown, 'utf-8');
725
-
726
- const spinBuild = fmt.spinner('Building marked DOCX...').start();
727
- const markedDocxPath = path.join(dir, '.paper-marked.docx');
728
- const pandocResult = await runPandoc(markedPath, 'docx', config, { ...options, outputPath: markedDocxPath, pandocArgs: options.pandocArg });
729
- spinBuild.stop();
730
-
731
- if (!pandocResult.success) {
732
- console.error(chalk.yellow(`\nWarning: Could not build marked DOCX: ${pandocResult.error}`));
733
- } else {
734
- const commentsDocxPath = docxResult.outputPath!.replace(/\.docx$/, '_comments.docx');
735
- const spinInject = fmt.spinner('Injecting comments at markers...').start();
736
- const commentResult = await injectCommentsAtMarkers(markedDocxPath, comments, commentsDocxPath);
737
- spinInject.stop();
738
-
739
- if (!process.env.DEBUG) {
740
- try {
741
- fs.unlinkSync(markedPath);
742
- fs.unlinkSync(markedDocxPath);
743
- } catch { /* ignore */ }
744
- }
745
-
746
- if (commentResult.success) {
747
- console.log(chalk.cyan('\nDual output:'));
748
- console.log(` Clean: ${path.basename(docxResult.outputPath!)}`);
749
- console.log(` Comments: ${path.basename(commentsDocxPath)} (${commentResult.commentCount} comments)`);
750
- if (commentResult.skippedComments > 0) {
751
- console.log(chalk.yellow(` Warning: ${commentResult.skippedComments} comments could not be anchored (markers not found)`));
752
- }
753
- } else {
754
- console.error(chalk.yellow(`\nWarning: Could not create comments DOCX: ${commentResult.error}`));
755
- }
756
- }
757
- }
758
- }
759
-
760
- const pdfResult = results.find(r => r.format === 'pdf' && r.success);
761
- if (pdfResult) {
762
- const { prepareMarkdownForAnnotatedPdf } = await import('../pdf-comments.js');
763
- const { runPandoc, applyFormatTransforms } = await import('../build.js');
764
-
765
- let markdown = fs.readFileSync(paperPath, 'utf-8');
766
- markdown = stripAnnotations(markdown, { keepComments: true });
767
-
768
- // Apply PDF transforms (table normalization, authblk header
769
- // injection) before todonotes preamble work, so the comments PDF
770
- // matches the clean PDF in everything but the margin notes.
771
- const registry = buildRegistry(dir, config.sections);
772
- markdown = applyFormatTransforms(markdown, 'pdf', config, registry);
773
-
774
- const spinPdf = fmt.spinner('Preparing annotated PDF...').start();
775
- const { markdown: annotatedMd, preamble, commentCount } = prepareMarkdownForAnnotatedPdf(markdown, {
776
- useTodonotes: true,
777
- stripResolved: true,
778
- });
779
-
780
- if (commentCount === 0) {
781
- spinPdf.stop();
782
- console.log(chalk.yellow('\nNo comments found - skipping annotated PDF'));
783
- } else {
784
- const annotatedPath = path.join(dir, '.paper-annotated.md');
785
- fs.writeFileSync(annotatedPath, annotatedMd, 'utf-8');
786
-
787
- const annotatedConfig = JSON.parse(JSON.stringify(config));
788
- annotatedConfig.pdf = annotatedConfig.pdf || {};
789
-
790
- // Pandoc consumes header-includes via -H <file>. Write preamble
791
- // (plus any existing user header file) to a temp .tex and point
792
- // headerIncludes at it.
793
- const preambleParts: string[] = [];
794
- const existingHeader = annotatedConfig.pdf.headerIncludes;
795
- if (existingHeader) {
796
- const existingPath = path.isAbsolute(existingHeader)
797
- ? existingHeader
798
- : path.join(dir, existingHeader);
799
- if (fs.existsSync(existingPath)) {
800
- preambleParts.push(fs.readFileSync(existingPath, 'utf-8'));
801
- }
802
- }
803
- preambleParts.push(preamble);
804
- const preamblePath = path.join(dir, '.paper-annotated.preamble.tex');
805
- fs.writeFileSync(preamblePath, preambleParts.join('\n'), 'utf-8');
806
- annotatedConfig.pdf.headerIncludes = preamblePath;
807
- annotatedConfig.pdf.geometry = 'left=2.5cm,right=4.5cm,top=2.5cm,bottom=2.5cm,marginparwidth=3.5cm';
808
-
809
- const annotatedPdfPath = pdfResult.outputPath!.replace(/\.pdf$/, '_comments.pdf');
810
- spinPdf.text = 'Building annotated PDF...';
811
- const pandocResult = await runPandoc(annotatedPath, 'pdf', annotatedConfig, { ...options, outputPath: annotatedPdfPath, pandocArgs: options.pandocArg });
812
- spinPdf.stop();
813
-
814
- if (!process.env.DEBUG) {
815
- try { fs.unlinkSync(annotatedPath); } catch { /* ignore */ }
816
- try { fs.unlinkSync(preamblePath); } catch { /* ignore */ }
817
- }
818
-
819
- if (pandocResult.success) {
820
- console.log(chalk.cyan('\nPDF dual output:'));
821
- console.log(` Clean: ${path.basename(pdfResult.outputPath!)}`);
822
- console.log(` Comments: ${path.basename(annotatedPdfPath)} (${commentCount} margin notes)`);
823
- } else {
824
- console.error(chalk.yellow(`\nWarning: Could not create annotated PDF: ${pandocResult.error}`));
825
- }
826
- }
827
- }
828
- }
829
-
830
- // Store base document for three-way merge (only for DOCX, not dual)
831
- const docxResult = results.find(r => r.format === 'docx' && r.success);
832
- if (docxResult && !options.dual) {
833
- try {
834
- const { storeBaseDocument } = await import('../merge.js');
835
- storeBaseDocument(dir, docxResult.outputPath!);
836
- console.log(chalk.dim(`\n Saved as .rev/base.docx for merge`));
837
- } catch (err) {
838
- // Non-fatal - just log if DEBUG
839
- if (process.env.DEBUG) {
840
- const error = err as Error;
841
- console.log(chalk.dim(`\n Could not store base document: ${error.message}`));
842
- }
843
- }
844
- }
845
-
846
- console.log(chalk.green('\nBuild complete!'));
847
- } catch (err) {
848
- spin.stop();
849
- const error = err as Error;
850
- console.error(fmt.status('error', error.message));
851
- if (process.env.DEBUG) console.error(error.stack);
852
- process.exit(1);
853
- }
854
- });
855
- }
1
+ /**
2
+ * Build commands: build, install, doctor, refs, migrate
3
+ *
4
+ * Commands for building documents and managing dependencies.
5
+ */
6
+
7
+ import {
8
+ chalk,
9
+ fs,
10
+ path,
11
+ fmt,
12
+ findFiles,
13
+ stripAnnotations,
14
+ buildRegistry,
15
+ detectHardcodedRefs,
16
+ convertHardcodedRefs,
17
+ getRefStatus,
18
+ formatRegistry,
19
+ build,
20
+ loadBuildConfig,
21
+ hasPandoc,
22
+ hasPandocCrossref,
23
+ formatBuildResults,
24
+ getUserName,
25
+ } from './context.js';
26
+ import type { Command } from 'commander';
27
+ import * as readline from 'readline';
28
+
29
+ interface RefsOptions {
30
+ dir: string;
31
+ }
32
+
33
+ interface MigrateOptions {
34
+ dir: string;
35
+ auto?: boolean;
36
+ dryRun?: boolean;
37
+ }
38
+
39
+ interface InstallOptions {
40
+ check?: boolean;
41
+ }
42
+
43
+ interface BuildOptions {
44
+ dir: string;
45
+ journal?: string;
46
+ crossref?: boolean;
47
+ toc?: boolean;
48
+ showChanges?: boolean;
49
+ dual?: boolean;
50
+ reference?: string;
51
+ theme?: string;
52
+ colortheme?: string;
53
+ aspectratio?: string;
54
+ verbose?: boolean;
55
+ pandocArg?: string[];
56
+ output?: string;
57
+ }
58
+
59
+ /**
60
+ * Register build commands with the program
61
+ */
62
+ export function register(program: Command, pkg?: { version?: string }): void {
63
+ // ==========================================================================
64
+ // REFS command - Show figure/table reference status
65
+ // ==========================================================================
66
+
67
+ program
68
+ .command('refs')
69
+ .description('Show figure/table reference registry and status')
70
+ .argument('[file]', 'Optional file to analyze for references')
71
+ .option('-d, --dir <directory>', 'Directory to scan for anchors', '.')
72
+ .action((file: string | undefined, options: RefsOptions) => {
73
+ const dir = path.resolve(options.dir);
74
+
75
+ if (!fs.existsSync(dir)) {
76
+ console.error(chalk.red(`Directory not found: ${dir}`));
77
+ process.exit(1);
78
+ }
79
+
80
+ console.log(chalk.cyan('Building figure/table registry...\n'));
81
+
82
+ const registry = buildRegistry(dir);
83
+
84
+ console.log(chalk.bold('Registry:'));
85
+ console.log(formatRegistry(registry));
86
+
87
+ if (file) {
88
+ if (!fs.existsSync(file)) {
89
+ console.error(chalk.red(`\nFile not found: ${file}`));
90
+ process.exit(1);
91
+ }
92
+
93
+ const text = fs.readFileSync(file, 'utf-8');
94
+ const status = getRefStatus(text, registry);
95
+
96
+ console.log(chalk.cyan(`\nReferences in ${path.basename(file)}:\n`));
97
+
98
+ if (status.dynamic.length > 0) {
99
+ console.log(chalk.green(` Dynamic (@fig:, @tbl:): ${status.dynamic.length}`));
100
+ for (const ref of status.dynamic.slice(0, 5)) {
101
+ console.log(chalk.dim(` ${ref.match}`));
102
+ }
103
+ if (status.dynamic.length > 5) {
104
+ console.log(chalk.dim(` ... and ${status.dynamic.length - 5} more`));
105
+ }
106
+ }
107
+
108
+ if (status.hardcoded.length > 0) {
109
+ console.log(chalk.yellow(`\n Hardcoded (Figure 1, Table 2): ${status.hardcoded.length}`));
110
+ for (const ref of status.hardcoded.slice(0, 5)) {
111
+ console.log(chalk.dim(` "${ref.match}"`));
112
+ }
113
+ if (status.hardcoded.length > 5) {
114
+ console.log(chalk.dim(` ... and ${status.hardcoded.length - 5} more`));
115
+ }
116
+ console.log(chalk.cyan(`\n Run ${chalk.bold(`rev migrate ${file}`)} to convert to dynamic refs`));
117
+ }
118
+
119
+ if (status.dynamic.length === 0 && status.hardcoded.length === 0) {
120
+ console.log(chalk.dim(' No figure/table references found.'));
121
+ }
122
+ }
123
+ });
124
+
125
+ // ==========================================================================
126
+ // MIGRATE command - Convert hardcoded refs to dynamic
127
+ // ==========================================================================
128
+
129
+ program
130
+ .command('migrate')
131
+ .description('Convert hardcoded figure/table refs to dynamic @-syntax')
132
+ .argument('<file>', 'Markdown file to migrate')
133
+ .option('-d, --dir <directory>', 'Directory for registry', '.')
134
+ .option('--auto', 'Auto-convert without prompting')
135
+ .option('--dry-run', 'Preview without saving')
136
+ .action(async (file: string, options: MigrateOptions) => {
137
+ if (!fs.existsSync(file)) {
138
+ console.error(chalk.red(`File not found: ${file}`));
139
+ process.exit(1);
140
+ }
141
+
142
+ const dir = path.resolve(options.dir);
143
+ console.log(chalk.cyan('Building figure/table registry...\n'));
144
+
145
+ const registry = buildRegistry(dir);
146
+ const text = fs.readFileSync(file, 'utf-8');
147
+ const refs = detectHardcodedRefs(text);
148
+
149
+ if (refs.length === 0) {
150
+ console.log(chalk.green('No hardcoded references found.'));
151
+ return;
152
+ }
153
+
154
+ console.log(chalk.yellow(`Found ${refs.length} hardcoded reference(s):\n`));
155
+
156
+ if (options.auto) {
157
+ const { converted, conversions, warnings } = convertHardcodedRefs(text, registry);
158
+
159
+ for (const w of warnings) {
160
+ console.log(chalk.yellow(` Warning: ${w}`));
161
+ }
162
+
163
+ for (const c of conversions) {
164
+ console.log(chalk.green(` "${c.from}" → ${c.to}`));
165
+ }
166
+
167
+ if (options.dryRun) {
168
+ console.log(chalk.yellow('\n(Dry run - no changes saved)'));
169
+ } else if (conversions.length > 0) {
170
+ fs.writeFileSync(file, converted, 'utf-8');
171
+ console.log(chalk.green(`\nConverted ${conversions.length} reference(s) in ${file}`));
172
+ }
173
+ } else {
174
+ const rl = readline.createInterface({
175
+ input: process.stdin,
176
+ output: process.stdout,
177
+ });
178
+
179
+ let result = text;
180
+ let converted = 0;
181
+ let skipped = 0;
182
+
183
+ const askQuestion = (prompt: string): Promise<string> =>
184
+ new Promise((resolve) => rl.question(prompt, resolve));
185
+
186
+ const sortedRefs = [...refs].sort((a, b) => b.position - a.position);
187
+
188
+ for (const ref of sortedRefs) {
189
+ const num = ref.numbers[0];
190
+ const { numberToLabel } = await import('../crossref.js');
191
+ const label = numberToLabel(ref.type, num.num, num.isSupp, registry);
192
+
193
+ if (!label) {
194
+ console.log(chalk.yellow(` "${ref.match}" - no matching anchor found, skipping`));
195
+ skipped++;
196
+ continue;
197
+ }
198
+
199
+ const replacement = `@${ref.type}:${label}`;
200
+ console.log(`\n ${chalk.yellow(`"${ref.match}"`)} → ${chalk.green(replacement)}`);
201
+
202
+ const answer = await askQuestion(chalk.cyan(' Convert? [y/n/a/q] '));
203
+
204
+ if (answer.toLowerCase() === 'q') {
205
+ console.log(chalk.dim(' Quitting...'));
206
+ break;
207
+ } else if (answer.toLowerCase() === 'a') {
208
+ result = result.slice(0, ref.position) + replacement + result.slice(ref.position + ref.match.length);
209
+ converted++;
210
+
211
+ for (const remaining of sortedRefs.slice(sortedRefs.indexOf(ref) + 1)) {
212
+ const rNum = remaining.numbers[0];
213
+ const rLabel = numberToLabel(remaining.type, rNum.num, rNum.isSupp, registry);
214
+ if (rLabel) {
215
+ const rReplacement = `@${remaining.type}:${rLabel}`;
216
+ result = result.slice(0, remaining.position) + rReplacement + result.slice(remaining.position + remaining.match.length);
217
+ converted++;
218
+ console.log(chalk.green(` "${remaining.match}" → ${rReplacement}`));
219
+ }
220
+ }
221
+ break;
222
+ } else if (answer.toLowerCase() === 'y') {
223
+ result = result.slice(0, ref.position) + replacement + result.slice(ref.position + ref.match.length);
224
+ converted++;
225
+ } else {
226
+ skipped++;
227
+ }
228
+ }
229
+
230
+ rl.close();
231
+
232
+ console.log(chalk.cyan(`\nConverted: ${converted}, Skipped: ${skipped}`));
233
+
234
+ if (converted > 0 && !options.dryRun) {
235
+ fs.writeFileSync(file, result, 'utf-8');
236
+ console.log(chalk.green(`Saved ${file}`));
237
+ } else if (options.dryRun) {
238
+ console.log(chalk.yellow('(Dry run - no changes saved)'));
239
+ }
240
+ }
241
+ });
242
+
243
+ // ==========================================================================
244
+ // INSTALL command - Install dependencies
245
+ // ==========================================================================
246
+
247
+ program
248
+ .command('install')
249
+ .description('Check and install dependencies (pandoc-crossref)')
250
+ .option('--check', 'Only check, don\'t install')
251
+ .action(async (options: InstallOptions) => {
252
+ const os = await import('os');
253
+ const { execSync } = await import('child_process');
254
+ const platform = os.platform();
255
+
256
+ console.log(chalk.cyan('Checking dependencies...\n'));
257
+
258
+ let hasPandocInstalled = false;
259
+ try {
260
+ const version = execSync('pandoc --version', { encoding: 'utf-8' }).split('\n')[0];
261
+ console.log(chalk.green(` ✓ ${version}`));
262
+ hasPandocInstalled = true;
263
+ } catch {
264
+ console.log(chalk.red(' ✗ pandoc not found'));
265
+ }
266
+
267
+ let hasCrossref = false;
268
+ try {
269
+ const version = execSync('pandoc-crossref --version', { encoding: 'utf-8' }).split('\n')[0];
270
+ console.log(chalk.green(` ✓ pandoc-crossref ${version}`));
271
+ hasCrossref = true;
272
+ } catch {
273
+ console.log(chalk.yellow(' ✗ pandoc-crossref not found'));
274
+ }
275
+
276
+ console.log('');
277
+
278
+ if (hasPandocInstalled && hasCrossref) {
279
+ console.log(chalk.green('All dependencies installed!'));
280
+ return;
281
+ }
282
+
283
+ if (options.check) {
284
+ if (!hasCrossref) {
285
+ console.log(chalk.yellow('pandoc-crossref is optional but recommended for @fig: references.'));
286
+ }
287
+ return;
288
+ }
289
+
290
+ if (!hasPandocInstalled || !hasCrossref) {
291
+ console.log(chalk.cyan('Installation options:\n'));
292
+
293
+ if (platform === 'darwin') {
294
+ console.log(chalk.bold('macOS (Homebrew):'));
295
+ if (!hasPandocInstalled) console.log(chalk.dim(' brew install pandoc'));
296
+ if (!hasCrossref) console.log(chalk.dim(' brew install pandoc-crossref'));
297
+ console.log('');
298
+ } else if (platform === 'win32') {
299
+ console.log(chalk.bold('Windows (Chocolatey):'));
300
+ if (!hasPandocInstalled) console.log(chalk.dim(' choco install pandoc'));
301
+ if (!hasCrossref) console.log(chalk.dim(' choco install pandoc-crossref'));
302
+ console.log('');
303
+ console.log(chalk.bold('Windows (Scoop):'));
304
+ if (!hasPandocInstalled) console.log(chalk.dim(' scoop install pandoc'));
305
+ if (!hasCrossref) console.log(chalk.dim(' scoop install pandoc-crossref'));
306
+ console.log('');
307
+ } else {
308
+ console.log(chalk.bold('Linux (apt):'));
309
+ if (!hasPandocInstalled) console.log(chalk.dim(' sudo apt install pandoc'));
310
+ console.log('');
311
+ }
312
+
313
+ console.log(chalk.bold('Cross-platform (conda):'));
314
+ if (!hasPandocInstalled) console.log(chalk.dim(' conda install -c conda-forge pandoc'));
315
+ if (!hasCrossref) console.log(chalk.dim(' conda install -c conda-forge pandoc-crossref'));
316
+ console.log('');
317
+
318
+ if (!hasCrossref) {
319
+ console.log(chalk.bold('Manual download:'));
320
+ console.log(chalk.dim(' https://github.com/lierdakil/pandoc-crossref/releases'));
321
+ console.log('');
322
+ }
323
+
324
+ try {
325
+ execSync('conda --version', { encoding: 'utf-8', stdio: 'pipe' });
326
+ console.log(chalk.cyan('Conda detected. Install missing dependencies? [y/N] '));
327
+
328
+ const rl = readline.createInterface({
329
+ input: process.stdin,
330
+ output: process.stdout,
331
+ });
332
+
333
+ rl.question('', (answer) => {
334
+ rl.close();
335
+ if (answer.toLowerCase() === 'y') {
336
+ console.log(chalk.cyan('\nInstalling via conda...'));
337
+ try {
338
+ if (!hasPandocInstalled) {
339
+ console.log(chalk.dim(' Installing pandoc...'));
340
+ execSync('conda install -y -c conda-forge pandoc', { stdio: 'inherit' });
341
+ }
342
+ if (!hasCrossref) {
343
+ console.log(chalk.dim(' Installing pandoc-crossref...'));
344
+ execSync('conda install -y -c conda-forge pandoc-crossref', { stdio: 'inherit' });
345
+ }
346
+ console.log(chalk.green('\nDone! Run "rev install --check" to verify.'));
347
+ } catch (err) {
348
+ const error = err as Error;
349
+ console.log(chalk.red(`\nInstallation failed: ${error.message}`));
350
+ console.log(chalk.dim('Try installing manually with the commands above.'));
351
+ }
352
+ }
353
+ });
354
+ } catch {
355
+ // Conda not available
356
+ }
357
+ }
358
+ });
359
+
360
+ // ==========================================================================
361
+ // DOCTOR command - Diagnose setup and configuration issues
362
+ // ==========================================================================
363
+
364
+ program
365
+ .command('doctor')
366
+ .description('Diagnose setup and configuration issues')
367
+ .action(async () => {
368
+ const os = await import('os');
369
+ const { execSync } = await import('child_process');
370
+
371
+ const version = pkg?.version || 'unknown';
372
+ console.log(chalk.bold.cyan(`\n rev doctor`) + chalk.dim(` v${version}\n`));
373
+ console.log(chalk.dim(` ${os.platform()} ${os.release()} | Node ${process.version}\n`));
374
+
375
+ let issues = 0;
376
+ let warnings = 0;
377
+
378
+ console.log(chalk.bold(' Environment'));
379
+ console.log(chalk.dim(' ─────────────────────────────────'));
380
+
381
+ const nodeVer = parseInt(process.version.slice(1).split('.')[0], 10);
382
+ if (nodeVer >= 18) {
383
+ console.log(chalk.green(' ✓') + ` Node.js ${process.version}`);
384
+ } else {
385
+ console.log(chalk.red(' ✗') + ` Node.js ${process.version} (requires >=18)`);
386
+ issues++;
387
+ }
388
+
389
+ try {
390
+ const pandocVer = execSync('pandoc --version', { encoding: 'utf-8' }).split('\n')[0];
391
+ console.log(chalk.green(' ✓') + ` ${pandocVer}`);
392
+ } catch {
393
+ console.log(chalk.red(' ✗') + ' pandoc not found');
394
+ issues++;
395
+ }
396
+
397
+ try {
398
+ const crossrefVer = execSync('pandoc-crossref --version', { encoding: 'utf-8' }).split('\n')[0];
399
+ console.log(chalk.green(' ✓') + ` pandoc-crossref ${crossrefVer}`);
400
+ } catch {
401
+ console.log(chalk.yellow(' !') + ' pandoc-crossref not found (optional)');
402
+ warnings++;
403
+ }
404
+
405
+ console.log();
406
+ console.log(chalk.bold(' Project'));
407
+ console.log(chalk.dim(' ─────────────────────────────────'));
408
+
409
+ const configPath = path.join(process.cwd(), 'rev.yaml');
410
+ if (fs.existsSync(configPath)) {
411
+ console.log(chalk.green(' ✓') + ' rev.yaml found');
412
+
413
+ try {
414
+ const { default: YAML } = await import('yaml');
415
+ const config = YAML.parse(fs.readFileSync(configPath, 'utf-8'));
416
+
417
+ if (config.title) {
418
+ console.log(chalk.green(' ✓') + ` Title: ${config.title}`);
419
+ } else {
420
+ console.log(chalk.yellow(' !') + ' No title in rev.yaml');
421
+ warnings++;
422
+ }
423
+
424
+ if (config.sections && config.sections.length > 0) {
425
+ console.log(chalk.green(' ✓') + ` Sections: ${config.sections.length} defined`);
426
+
427
+ let missing = 0;
428
+ for (const sec of config.sections) {
429
+ const secFile = typeof sec === 'string' ? sec : sec.file;
430
+ if (!fs.existsSync(secFile)) missing++;
431
+ }
432
+ if (missing > 0) {
433
+ console.log(chalk.yellow(' !') + ` ${missing} section file(s) missing`);
434
+ warnings++;
435
+ }
436
+ }
437
+
438
+ if (config.bibliography) {
439
+ if (fs.existsSync(config.bibliography)) {
440
+ console.log(chalk.green(' ✓') + ` Bibliography: ${config.bibliography}`);
441
+ } else {
442
+ console.log(chalk.yellow(' !') + ` Bibliography file not found: ${config.bibliography}`);
443
+ warnings++;
444
+ }
445
+ }
446
+ } catch (e) {
447
+ const error = e as Error;
448
+ console.log(chalk.red(' ✗') + ` rev.yaml parse error: ${error.message}`);
449
+ issues++;
450
+ }
451
+ } else {
452
+ console.log(chalk.dim(' ·') + ' No rev.yaml (not a rev project)');
453
+ }
454
+
455
+ const mdFiles = findFiles('.md');
456
+ if (mdFiles.length > 0) {
457
+ console.log(chalk.green(' ✓') + ` Markdown files: ${mdFiles.length}`);
458
+ } else {
459
+ console.log(chalk.dim(' ·') + ' No markdown files');
460
+ }
461
+
462
+ console.log();
463
+ if (issues === 0 && warnings === 0) {
464
+ console.log(chalk.green.bold(' All checks passed! ✓\n'));
465
+ } else if (issues === 0) {
466
+ console.log(chalk.yellow(` ${warnings} warning(s), no critical issues\n`));
467
+ } else {
468
+ console.log(chalk.red(` ${issues} issue(s), ${warnings} warning(s)\n`));
469
+ console.log(chalk.dim(' Run "rev install" to fix missing dependencies.\n'));
470
+ }
471
+ });
472
+
473
+ // ==========================================================================
474
+ // BUILD command - Combine sections and run pandoc
475
+ // ==========================================================================
476
+
477
+ program
478
+ .command('build')
479
+ .alias('b')
480
+ .description('Build PDF/DOCX/TEX/PPTX/Beamer from sections')
481
+ .argument('[formats...]', 'Output formats: pdf, docx, tex, beamer, pptx, all', ['pdf', 'docx'])
482
+ .option('-d, --dir <directory>', 'Project directory', '.')
483
+ .option('-j, --journal <name>', 'Use journal profile for build formatting defaults')
484
+ .option('--no-crossref', 'Skip pandoc-crossref filter')
485
+ .option('--toc', 'Include table of contents')
486
+ .option('--show-changes', 'Export DOCX with visible track changes (audit mode)')
487
+ .option('--dual', 'Output both clean version and annotated version (with comments)')
488
+ .option('--reference <docx>', 'Reference DOCX for comment position alignment (use with --dual)')
489
+ .option('--theme <name>', 'Beamer theme (default, metropolis, etc.)')
490
+ .option('--colortheme <name>', 'Beamer color theme')
491
+ .option('--aspectratio <ratio>', 'Beamer aspect ratio (169, 43)')
492
+ .option(
493
+ '--pandoc-arg <arg>',
494
+ 'Extra arg to pass to pandoc (repeatable). Applied to every format being built; appended after rev.yaml pandoc-args so CLI wins.',
495
+ (val: string, prev: string[] = []) => [...prev, val],
496
+ []
497
+ )
498
+ .option('-o, --output <path>', 'Output filename or path. Relative paths resolve under outputDir; absolute paths bypass it. Extension auto-added if missing. Applied to every format being built; overrides rev.yaml output.<format>.')
499
+ .option('--verbose', 'Show detailed output including postprocess scripts and the pandoc invocation')
500
+ .action(async (formats: string[], options: BuildOptions) => {
501
+ const dir = path.resolve(options.dir);
502
+
503
+ if (!fs.existsSync(dir)) {
504
+ console.error(chalk.red(`Directory not found: ${dir}`));
505
+ process.exit(1);
506
+ }
507
+
508
+ if (!hasPandoc()) {
509
+ console.error(chalk.red('pandoc not found.'));
510
+ console.error(chalk.dim('Run "rev install" to install dependencies.'));
511
+ process.exit(1);
512
+ }
513
+
514
+ const config = loadBuildConfig(dir);
515
+
516
+ if (!config._configPath) {
517
+ console.error(chalk.yellow('No rev.yaml found.'));
518
+ console.error(chalk.dim('Run "rev new" to create a project, or "rev init" for existing files.'));
519
+ process.exit(1);
520
+ }
521
+
522
+ // Apply journal formatting from CLI flag (overrides rev.yaml journal field)
523
+ let journalName: string | undefined;
524
+ if (options.journal) {
525
+ const { getJournalProfile } = await import('../journals.js');
526
+ const { mergeJournalFormatting } = await import('../build.js');
527
+ const profile = getJournalProfile(options.journal);
528
+ if (!profile) {
529
+ console.error(fmt.status('error', `Unknown journal: ${options.journal}`));
530
+ console.error(chalk.dim('Use "rev validate --list" to see available profiles'));
531
+ process.exit(1);
532
+ }
533
+ journalName = profile.name;
534
+ if (profile.formatting) {
535
+ Object.assign(config, mergeJournalFormatting(config, profile.formatting, dir));
536
+ }
537
+ } else if ((config as unknown as { journal?: string }).journal) {
538
+ // Journal set in rev.yaml — already applied by loadConfig, just get name for display
539
+ const { getJournalProfile } = await import('../journals.js');
540
+ const profile = getJournalProfile((config as unknown as { journal?: string }).journal!);
541
+ if (profile) journalName = profile.name;
542
+ }
543
+
544
+ console.log(fmt.header(`Building ${config.title || 'document'}`));
545
+ console.log();
546
+
547
+ const targetFormats = formats.length > 0 ? formats : ['pdf', 'docx'];
548
+ const tocEnabled = options.toc || config.pdf?.toc || config.docx?.toc;
549
+ if (journalName) console.log(chalk.dim(` Journal: ${journalName}`));
550
+ console.log(chalk.dim(` Formats: ${targetFormats.join(', ')}`));
551
+ console.log(chalk.dim(` Crossref: ${hasPandocCrossref() && options.crossref !== false ? 'enabled' : 'disabled'}`));
552
+ if (tocEnabled) console.log(chalk.dim(` TOC: enabled`));
553
+ if (options.showChanges) console.log(chalk.dim(` Track changes: visible`));
554
+ if (options.dual) console.log(chalk.dim(` Dual output: clean + with comments`));
555
+ console.log('');
556
+
557
+ if (options.toc) {
558
+ config.pdf = config.pdf || {};
559
+ config.pdf.toc = true;
560
+ config.docx = config.docx || {};
561
+ config.docx.toc = true;
562
+ }
563
+
564
+ if (options.dual) {
565
+ config.docx = config.docx || {};
566
+ config.docx.keepComments = false;
567
+ }
568
+
569
+ // Apply beamer CLI options
570
+ if (options.theme) {
571
+ config.beamer = config.beamer || {};
572
+ config.beamer.theme = options.theme;
573
+ }
574
+ if (options.colortheme) {
575
+ config.beamer = config.beamer || {};
576
+ config.beamer.colortheme = options.colortheme;
577
+ }
578
+ if (options.aspectratio) {
579
+ config.beamer = config.beamer || {};
580
+ config.beamer.aspectratio = options.aspectratio;
581
+ }
582
+
583
+ if (options.showChanges) {
584
+ if (!targetFormats.includes('docx') && !targetFormats.includes('all')) {
585
+ console.error(fmt.status('error', '--show-changes only applies to DOCX output'));
586
+ process.exit(1);
587
+ }
588
+
589
+ const { combineSections, resolveOutputPath } = await import('../build.js');
590
+ const { buildWithTrackChanges } = await import('../trackchanges.js');
591
+
592
+ const spin = fmt.spinner('Building with track changes...').start();
593
+
594
+ try {
595
+ const paperPath = combineSections(dir, config);
596
+ spin.stop();
597
+ console.log(chalk.cyan('Combined sections → paper.md'));
598
+ console.log(chalk.dim(` ${paperPath}\n`));
599
+
600
+ const outputPath = resolveOutputPath(dir, config, 'docx', {
601
+ cliOverride: options.output,
602
+ suffix: '-changes',
603
+ });
604
+ const outDir = path.dirname(outputPath);
605
+ if (!fs.existsSync(outDir)) fs.mkdirSync(outDir, { recursive: true });
606
+
607
+ const spinTc = fmt.spinner('Applying track changes...').start();
608
+ const result = await buildWithTrackChanges(paperPath, outputPath, {
609
+ author: getUserName() || 'Author',
610
+ });
611
+ spinTc.stop();
612
+
613
+ if (result.success) {
614
+ console.log(chalk.cyan('Output (with track changes):'));
615
+ console.log(` DOCX: ${path.basename(outputPath)}`);
616
+ if (result.stats) {
617
+ console.log(chalk.dim(` ${result.stats.insertions} insertions, ${result.stats.deletions} deletions, ${result.stats.substitutions} substitutions`));
618
+ }
619
+ console.log(chalk.green('\nBuild complete!'));
620
+ } else {
621
+ console.error(fmt.status('error', result.message));
622
+ process.exit(1);
623
+ }
624
+ } catch (err) {
625
+ spin.stop();
626
+ const error = err as Error;
627
+ console.error(fmt.status('error', error.message));
628
+ if (process.env.DEBUG) console.error(error.stack);
629
+ process.exit(1);
630
+ }
631
+ return;
632
+ }
633
+
634
+ const spin = fmt.spinner('Building...').start();
635
+
636
+ try {
637
+ const { results, paperPath, forwardRefsResolved, refsAutoInjected, warnings } = await build(dir, targetFormats, {
638
+ crossref: options.crossref,
639
+ config,
640
+ verbose: options.verbose,
641
+ pandocArgs: options.pandocArg,
642
+ output: options.output,
643
+ });
644
+
645
+ spin.stop();
646
+
647
+ console.log(chalk.cyan('Combined sections → paper.md'));
648
+ console.log(chalk.dim(` ${paperPath}`));
649
+ if (forwardRefsResolved > 0) {
650
+ console.log(chalk.dim(` ${forwardRefsResolved} forward reference(s) pre-resolved`));
651
+ }
652
+ if (refsAutoInjected) {
653
+ console.log(chalk.dim(` References section auto-injected before supplementary`));
654
+ }
655
+ console.log('');
656
+
657
+ if (warnings && warnings.length > 0) {
658
+ for (const w of warnings) {
659
+ // Each warning may span multiple lines — colour the first line as
660
+ // a warning header and pass through the rest unchanged.
661
+ const [head, ...rest] = w.split('\n');
662
+ console.log(chalk.yellow(`Warning: ${head}`));
663
+ for (const line of rest) console.log(chalk.yellow(line));
664
+ }
665
+ console.log('');
666
+ }
667
+
668
+ console.log(chalk.cyan('Output:'));
669
+ console.log(formatBuildResults(results));
670
+
671
+ const failed = results.filter((r) => !r.success);
672
+ if (failed.length > 0) {
673
+ console.log('');
674
+ for (const f of failed) {
675
+ console.error(chalk.red(`\n${f.format} error:\n${f.error}`));
676
+ }
677
+ process.exit(1);
678
+ }
679
+
680
+ // Handle --dual mode
681
+ if (options.dual) {
682
+ const docxResult = results.find(r => r.format === 'docx' && r.success);
683
+ if (docxResult) {
684
+ const { prepareMarkdownWithMarkers, injectCommentsAtMarkers } = await import('../wordcomments.js');
685
+ const { runPandoc, applyFormatTransforms } = await import('../build.js');
686
+
687
+ let markdown = fs.readFileSync(paperPath, 'utf-8');
688
+
689
+ if (options.reference) {
690
+ const refPath = path.resolve(dir, options.reference);
691
+ if (fs.existsSync(refPath)) {
692
+ const spinRealign = fmt.spinner('Realigning comments from reference...').start();
693
+ const { realignMarkdown } = await import('../comment-realign.js');
694
+ const realigned = await realignMarkdown(refPath, markdown);
695
+ if (realigned.success) {
696
+ markdown = realigned.markdown;
697
+ spinRealign.stop();
698
+ console.log(chalk.dim(` Realigned ${realigned.insertions} comments from reference`));
699
+ } else {
700
+ spinRealign.stop();
701
+ console.log(chalk.yellow(` Warning: Could not realign comments: ${realigned.error}`));
702
+ }
703
+ } else {
704
+ console.log(chalk.yellow(` Warning: Reference not found: ${options.reference}`));
705
+ }
706
+ }
707
+
708
+ markdown = stripAnnotations(markdown, { keepComments: true });
709
+
710
+ // Apply DOCX transforms (author affiliations, @fig: → "Figure 1")
711
+ // before injecting markers, so the comments DOCX matches the clean
712
+ // DOCX in everything but the comments themselves.
713
+ const registry = buildRegistry(dir, config.sections);
714
+ markdown = applyFormatTransforms(markdown, 'docx', config, registry);
715
+
716
+ const spinMarkers = fmt.spinner('Preparing markers...').start();
717
+ const { markedMarkdown, comments } = prepareMarkdownWithMarkers(markdown);
718
+ spinMarkers.stop();
719
+
720
+ if (comments.length === 0) {
721
+ console.log(chalk.yellow('\nNo comments found - skipping comments DOCX'));
722
+ } else {
723
+ const markedPath = path.join(dir, '.paper-marked.md');
724
+ fs.writeFileSync(markedPath, markedMarkdown, 'utf-8');
725
+
726
+ const spinBuild = fmt.spinner('Building marked DOCX...').start();
727
+ const markedDocxPath = path.join(dir, '.paper-marked.docx');
728
+ const pandocResult = await runPandoc(markedPath, 'docx', config, { ...options, outputPath: markedDocxPath, pandocArgs: options.pandocArg });
729
+ spinBuild.stop();
730
+
731
+ if (!pandocResult.success) {
732
+ console.error(chalk.yellow(`\nWarning: Could not build marked DOCX: ${pandocResult.error}`));
733
+ } else {
734
+ const commentsDocxPath = docxResult.outputPath!.replace(/\.docx$/, '_comments.docx');
735
+ const spinInject = fmt.spinner('Injecting comments at markers...').start();
736
+ const commentResult = await injectCommentsAtMarkers(markedDocxPath, comments, commentsDocxPath);
737
+ spinInject.stop();
738
+
739
+ if (!process.env.DEBUG) {
740
+ try {
741
+ fs.unlinkSync(markedPath);
742
+ fs.unlinkSync(markedDocxPath);
743
+ } catch { /* ignore */ }
744
+ }
745
+
746
+ if (commentResult.success) {
747
+ console.log(chalk.cyan('\nDual output:'));
748
+ console.log(` Clean: ${path.basename(docxResult.outputPath!)}`);
749
+ console.log(` Comments: ${path.basename(commentsDocxPath)} (${commentResult.commentCount} comments)`);
750
+ if (commentResult.skippedComments > 0) {
751
+ console.log(chalk.yellow(` Warning: ${commentResult.skippedComments} comments could not be anchored (markers not found)`));
752
+ }
753
+ } else {
754
+ console.error(chalk.yellow(`\nWarning: Could not create comments DOCX: ${commentResult.error}`));
755
+ }
756
+ }
757
+ }
758
+ }
759
+
760
+ const pdfResult = results.find(r => r.format === 'pdf' && r.success);
761
+ if (pdfResult) {
762
+ const { prepareMarkdownForAnnotatedPdf } = await import('../pdf-comments.js');
763
+ const { runPandoc, applyFormatTransforms } = await import('../build.js');
764
+
765
+ let markdown = fs.readFileSync(paperPath, 'utf-8');
766
+ markdown = stripAnnotations(markdown, { keepComments: true });
767
+
768
+ // Apply PDF transforms (table normalization, authblk header
769
+ // injection) before todonotes preamble work, so the comments PDF
770
+ // matches the clean PDF in everything but the margin notes.
771
+ const registry = buildRegistry(dir, config.sections);
772
+ markdown = applyFormatTransforms(markdown, 'pdf', config, registry);
773
+
774
+ const spinPdf = fmt.spinner('Preparing annotated PDF...').start();
775
+ const { markdown: annotatedMd, preamble, commentCount } = prepareMarkdownForAnnotatedPdf(markdown, {
776
+ useTodonotes: true,
777
+ stripResolved: true,
778
+ });
779
+
780
+ if (commentCount === 0) {
781
+ spinPdf.stop();
782
+ console.log(chalk.yellow('\nNo comments found - skipping annotated PDF'));
783
+ } else {
784
+ const annotatedPath = path.join(dir, '.paper-annotated.md');
785
+ fs.writeFileSync(annotatedPath, annotatedMd, 'utf-8');
786
+
787
+ const annotatedConfig = JSON.parse(JSON.stringify(config));
788
+ annotatedConfig.pdf = annotatedConfig.pdf || {};
789
+
790
+ // Pandoc consumes header-includes via -H <file>. Write preamble
791
+ // (plus any existing user header file) to a temp .tex and point
792
+ // headerIncludes at it.
793
+ const preambleParts: string[] = [];
794
+ const existingHeader = annotatedConfig.pdf.headerIncludes;
795
+ if (existingHeader) {
796
+ const existingPath = path.isAbsolute(existingHeader)
797
+ ? existingHeader
798
+ : path.join(dir, existingHeader);
799
+ if (fs.existsSync(existingPath)) {
800
+ preambleParts.push(fs.readFileSync(existingPath, 'utf-8'));
801
+ }
802
+ }
803
+ preambleParts.push(preamble);
804
+ const preamblePath = path.join(dir, '.paper-annotated.preamble.tex');
805
+ fs.writeFileSync(preamblePath, preambleParts.join('\n'), 'utf-8');
806
+ annotatedConfig.pdf.headerIncludes = preamblePath;
807
+ annotatedConfig.pdf.geometry = 'left=2.5cm,right=4.5cm,top=2.5cm,bottom=2.5cm,marginparwidth=3.5cm';
808
+
809
+ const annotatedPdfPath = pdfResult.outputPath!.replace(/\.pdf$/, '_comments.pdf');
810
+ spinPdf.text = 'Building annotated PDF...';
811
+ const pandocResult = await runPandoc(annotatedPath, 'pdf', annotatedConfig, { ...options, outputPath: annotatedPdfPath, pandocArgs: options.pandocArg });
812
+ spinPdf.stop();
813
+
814
+ if (!process.env.DEBUG) {
815
+ try { fs.unlinkSync(annotatedPath); } catch { /* ignore */ }
816
+ try { fs.unlinkSync(preamblePath); } catch { /* ignore */ }
817
+ }
818
+
819
+ if (pandocResult.success) {
820
+ console.log(chalk.cyan('\nPDF dual output:'));
821
+ console.log(` Clean: ${path.basename(pdfResult.outputPath!)}`);
822
+ console.log(` Comments: ${path.basename(annotatedPdfPath)} (${commentCount} margin notes)`);
823
+ } else {
824
+ console.error(chalk.yellow(`\nWarning: Could not create annotated PDF: ${pandocResult.error}`));
825
+ }
826
+ }
827
+ }
828
+ }
829
+
830
+ // Store base document for three-way merge (only for DOCX, not dual)
831
+ const docxResult = results.find(r => r.format === 'docx' && r.success);
832
+ if (docxResult && !options.dual) {
833
+ try {
834
+ const { storeBaseDocument } = await import('../merge.js');
835
+ storeBaseDocument(dir, docxResult.outputPath!);
836
+ console.log(chalk.dim(`\n Saved as .rev/base.docx for merge`));
837
+ } catch (err) {
838
+ // Non-fatal - just log if DEBUG
839
+ if (process.env.DEBUG) {
840
+ const error = err as Error;
841
+ console.log(chalk.dim(`\n Could not store base document: ${error.message}`));
842
+ }
843
+ }
844
+ }
845
+
846
+ console.log(chalk.green('\nBuild complete!'));
847
+ } catch (err) {
848
+ spin.stop();
849
+ const error = err as Error;
850
+ console.error(fmt.status('error', error.message));
851
+ if (process.env.DEBUG) console.error(error.stack);
852
+ process.exit(1);
853
+ }
854
+ });
855
+ }