docrev 0.10.1 → 0.11.0

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