docrev 0.8.1 → 0.8.5

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 (306) hide show
  1. package/.claude/settings.local.json +9 -0
  2. package/PLAN-tables-and-postprocess.md +850 -0
  3. package/README.md +33 -0
  4. package/bin/rev.js +12 -131
  5. package/bin/rev.ts +145 -0
  6. package/dist/bin/rev.d.ts +9 -0
  7. package/dist/bin/rev.d.ts.map +1 -0
  8. package/dist/bin/rev.js +118 -0
  9. package/dist/bin/rev.js.map +1 -0
  10. package/dist/lib/annotations.d.ts +91 -0
  11. package/dist/lib/annotations.d.ts.map +1 -0
  12. package/dist/lib/annotations.js +554 -0
  13. package/dist/lib/annotations.js.map +1 -0
  14. package/dist/lib/build.d.ts +171 -0
  15. package/dist/lib/build.d.ts.map +1 -0
  16. package/dist/lib/build.js +755 -0
  17. package/dist/lib/build.js.map +1 -0
  18. package/dist/lib/citations.d.ts +34 -0
  19. package/dist/lib/citations.d.ts.map +1 -0
  20. package/dist/lib/citations.js +140 -0
  21. package/dist/lib/citations.js.map +1 -0
  22. package/dist/lib/commands/build.d.ts +13 -0
  23. package/dist/lib/commands/build.d.ts.map +1 -0
  24. package/dist/lib/commands/build.js +678 -0
  25. package/dist/lib/commands/build.js.map +1 -0
  26. package/dist/lib/commands/citations.d.ts +11 -0
  27. package/dist/lib/commands/citations.d.ts.map +1 -0
  28. package/dist/lib/commands/citations.js +428 -0
  29. package/dist/lib/commands/citations.js.map +1 -0
  30. package/dist/lib/commands/comments.d.ts +11 -0
  31. package/dist/lib/commands/comments.d.ts.map +1 -0
  32. package/dist/lib/commands/comments.js +883 -0
  33. package/dist/lib/commands/comments.js.map +1 -0
  34. package/dist/lib/commands/context.d.ts +35 -0
  35. package/dist/lib/commands/context.d.ts.map +1 -0
  36. package/dist/lib/commands/context.js +59 -0
  37. package/dist/lib/commands/context.js.map +1 -0
  38. package/dist/lib/commands/core.d.ts +11 -0
  39. package/dist/lib/commands/core.d.ts.map +1 -0
  40. package/dist/lib/commands/core.js +246 -0
  41. package/dist/lib/commands/core.js.map +1 -0
  42. package/dist/lib/commands/doi.d.ts +11 -0
  43. package/dist/lib/commands/doi.d.ts.map +1 -0
  44. package/dist/lib/commands/doi.js +373 -0
  45. package/dist/lib/commands/doi.js.map +1 -0
  46. package/dist/lib/commands/history.d.ts +11 -0
  47. package/dist/lib/commands/history.d.ts.map +1 -0
  48. package/dist/lib/commands/history.js +245 -0
  49. package/dist/lib/commands/history.js.map +1 -0
  50. package/dist/lib/commands/index.d.ts +28 -0
  51. package/dist/lib/commands/index.d.ts.map +1 -0
  52. package/dist/lib/commands/index.js +35 -0
  53. package/dist/lib/commands/index.js.map +1 -0
  54. package/dist/lib/commands/init.d.ts +11 -0
  55. package/dist/lib/commands/init.d.ts.map +1 -0
  56. package/dist/lib/commands/init.js +209 -0
  57. package/dist/lib/commands/init.js.map +1 -0
  58. package/dist/lib/commands/response.d.ts +11 -0
  59. package/dist/lib/commands/response.d.ts.map +1 -0
  60. package/dist/lib/commands/response.js +317 -0
  61. package/dist/lib/commands/response.js.map +1 -0
  62. package/dist/lib/commands/sections.d.ts +11 -0
  63. package/dist/lib/commands/sections.d.ts.map +1 -0
  64. package/dist/lib/commands/sections.js +1071 -0
  65. package/dist/lib/commands/sections.js.map +1 -0
  66. package/dist/lib/commands/utilities.d.ts +19 -0
  67. package/dist/lib/commands/utilities.d.ts.map +1 -0
  68. package/dist/lib/commands/utilities.js +2009 -0
  69. package/dist/lib/commands/utilities.js.map +1 -0
  70. package/dist/lib/comment-realign.d.ts +50 -0
  71. package/dist/lib/comment-realign.d.ts.map +1 -0
  72. package/dist/lib/comment-realign.js +372 -0
  73. package/dist/lib/comment-realign.js.map +1 -0
  74. package/dist/lib/config.d.ts +41 -0
  75. package/dist/lib/config.d.ts.map +1 -0
  76. package/dist/lib/config.js +76 -0
  77. package/dist/lib/config.js.map +1 -0
  78. package/dist/lib/crossref.d.ts +108 -0
  79. package/dist/lib/crossref.d.ts.map +1 -0
  80. package/dist/lib/crossref.js +597 -0
  81. package/dist/lib/crossref.js.map +1 -0
  82. package/dist/lib/dependencies.d.ts +30 -0
  83. package/dist/lib/dependencies.d.ts.map +1 -0
  84. package/dist/lib/dependencies.js +95 -0
  85. package/dist/lib/dependencies.js.map +1 -0
  86. package/dist/lib/doi-cache.d.ts +29 -0
  87. package/dist/lib/doi-cache.d.ts.map +1 -0
  88. package/dist/lib/doi-cache.js +104 -0
  89. package/dist/lib/doi-cache.js.map +1 -0
  90. package/dist/lib/doi.d.ts +65 -0
  91. package/dist/lib/doi.d.ts.map +1 -0
  92. package/dist/lib/doi.js +710 -0
  93. package/dist/lib/doi.js.map +1 -0
  94. package/dist/lib/equations.d.ts +61 -0
  95. package/dist/lib/equations.d.ts.map +1 -0
  96. package/dist/lib/equations.js +445 -0
  97. package/dist/lib/equations.js.map +1 -0
  98. package/dist/lib/errors.d.ts +60 -0
  99. package/dist/lib/errors.d.ts.map +1 -0
  100. package/dist/lib/errors.js +303 -0
  101. package/dist/lib/errors.js.map +1 -0
  102. package/dist/lib/format.d.ts +104 -0
  103. package/dist/lib/format.d.ts.map +1 -0
  104. package/dist/lib/format.js +416 -0
  105. package/dist/lib/format.js.map +1 -0
  106. package/dist/lib/git.d.ts +88 -0
  107. package/dist/lib/git.d.ts.map +1 -0
  108. package/dist/lib/git.js +304 -0
  109. package/dist/lib/git.js.map +1 -0
  110. package/dist/lib/grammar.d.ts +62 -0
  111. package/dist/lib/grammar.d.ts.map +1 -0
  112. package/dist/lib/grammar.js +244 -0
  113. package/dist/lib/grammar.js.map +1 -0
  114. package/dist/lib/image-registry.d.ts +68 -0
  115. package/dist/lib/image-registry.d.ts.map +1 -0
  116. package/dist/lib/image-registry.js +112 -0
  117. package/dist/lib/image-registry.js.map +1 -0
  118. package/dist/lib/import.d.ts +184 -0
  119. package/dist/lib/import.d.ts.map +1 -0
  120. package/dist/lib/import.js +1581 -0
  121. package/dist/lib/import.js.map +1 -0
  122. package/dist/lib/journals.d.ts +55 -0
  123. package/dist/lib/journals.d.ts.map +1 -0
  124. package/dist/lib/journals.js +417 -0
  125. package/dist/lib/journals.js.map +1 -0
  126. package/dist/lib/merge.d.ts +138 -0
  127. package/dist/lib/merge.d.ts.map +1 -0
  128. package/dist/lib/merge.js +603 -0
  129. package/dist/lib/merge.js.map +1 -0
  130. package/dist/lib/orcid.d.ts +36 -0
  131. package/dist/lib/orcid.d.ts.map +1 -0
  132. package/dist/lib/orcid.js +117 -0
  133. package/dist/lib/orcid.js.map +1 -0
  134. package/dist/lib/pdf-comments.d.ts +95 -0
  135. package/dist/lib/pdf-comments.d.ts.map +1 -0
  136. package/dist/lib/pdf-comments.js +192 -0
  137. package/dist/lib/pdf-comments.js.map +1 -0
  138. package/dist/lib/pdf-import.d.ts +118 -0
  139. package/dist/lib/pdf-import.d.ts.map +1 -0
  140. package/dist/lib/pdf-import.js +397 -0
  141. package/dist/lib/pdf-import.js.map +1 -0
  142. package/dist/lib/plugins.d.ts +76 -0
  143. package/dist/lib/plugins.d.ts.map +1 -0
  144. package/dist/lib/plugins.js +235 -0
  145. package/dist/lib/plugins.js.map +1 -0
  146. package/dist/lib/postprocess.d.ts +42 -0
  147. package/dist/lib/postprocess.d.ts.map +1 -0
  148. package/dist/lib/postprocess.js +138 -0
  149. package/dist/lib/postprocess.js.map +1 -0
  150. package/dist/lib/pptx-template.d.ts +59 -0
  151. package/dist/lib/pptx-template.d.ts.map +1 -0
  152. package/dist/lib/pptx-template.js +613 -0
  153. package/dist/lib/pptx-template.js.map +1 -0
  154. package/dist/lib/pptx-themes.d.ts +80 -0
  155. package/dist/lib/pptx-themes.d.ts.map +1 -0
  156. package/dist/lib/pptx-themes.js +818 -0
  157. package/dist/lib/pptx-themes.js.map +1 -0
  158. package/dist/lib/protect-restore.d.ts +137 -0
  159. package/dist/lib/protect-restore.d.ts.map +1 -0
  160. package/dist/lib/protect-restore.js +394 -0
  161. package/dist/lib/protect-restore.js.map +1 -0
  162. package/dist/lib/rate-limiter.d.ts +27 -0
  163. package/dist/lib/rate-limiter.d.ts.map +1 -0
  164. package/dist/lib/rate-limiter.js +79 -0
  165. package/dist/lib/rate-limiter.js.map +1 -0
  166. package/dist/lib/response.d.ts +41 -0
  167. package/dist/lib/response.d.ts.map +1 -0
  168. package/dist/lib/response.js +150 -0
  169. package/dist/lib/response.js.map +1 -0
  170. package/dist/lib/review.d.ts +35 -0
  171. package/dist/lib/review.d.ts.map +1 -0
  172. package/dist/lib/review.js +263 -0
  173. package/dist/lib/review.js.map +1 -0
  174. package/dist/lib/schema.d.ts +66 -0
  175. package/dist/lib/schema.d.ts.map +1 -0
  176. package/dist/lib/schema.js +339 -0
  177. package/dist/lib/schema.js.map +1 -0
  178. package/dist/lib/scientific-words.d.ts +6 -0
  179. package/dist/lib/scientific-words.d.ts.map +1 -0
  180. package/dist/lib/scientific-words.js +66 -0
  181. package/dist/lib/scientific-words.js.map +1 -0
  182. package/dist/lib/sections.d.ts +40 -0
  183. package/dist/lib/sections.d.ts.map +1 -0
  184. package/dist/lib/sections.js +288 -0
  185. package/dist/lib/sections.js.map +1 -0
  186. package/dist/lib/slides.d.ts +86 -0
  187. package/dist/lib/slides.d.ts.map +1 -0
  188. package/dist/lib/slides.js +676 -0
  189. package/dist/lib/slides.js.map +1 -0
  190. package/dist/lib/spelling.d.ts +76 -0
  191. package/dist/lib/spelling.d.ts.map +1 -0
  192. package/dist/lib/spelling.js +272 -0
  193. package/dist/lib/spelling.js.map +1 -0
  194. package/dist/lib/templates.d.ts +30 -0
  195. package/dist/lib/templates.d.ts.map +1 -0
  196. package/dist/lib/templates.js +504 -0
  197. package/dist/lib/templates.js.map +1 -0
  198. package/dist/lib/themes.d.ts +85 -0
  199. package/dist/lib/themes.d.ts.map +1 -0
  200. package/dist/lib/themes.js +652 -0
  201. package/dist/lib/themes.js.map +1 -0
  202. package/dist/lib/trackchanges.d.ts +51 -0
  203. package/dist/lib/trackchanges.d.ts.map +1 -0
  204. package/dist/lib/trackchanges.js +202 -0
  205. package/dist/lib/trackchanges.js.map +1 -0
  206. package/dist/lib/tui.d.ts +76 -0
  207. package/dist/lib/tui.d.ts.map +1 -0
  208. package/dist/lib/tui.js +377 -0
  209. package/dist/lib/tui.js.map +1 -0
  210. package/dist/lib/types.d.ts +447 -0
  211. package/dist/lib/types.d.ts.map +1 -0
  212. package/dist/lib/types.js +6 -0
  213. package/dist/lib/types.js.map +1 -0
  214. package/dist/lib/undo.d.ts +57 -0
  215. package/dist/lib/undo.d.ts.map +1 -0
  216. package/dist/lib/undo.js +185 -0
  217. package/dist/lib/undo.js.map +1 -0
  218. package/dist/lib/utils.d.ts +16 -0
  219. package/dist/lib/utils.d.ts.map +1 -0
  220. package/dist/lib/utils.js +40 -0
  221. package/dist/lib/utils.js.map +1 -0
  222. package/dist/lib/variables.d.ts +42 -0
  223. package/dist/lib/variables.d.ts.map +1 -0
  224. package/dist/lib/variables.js +141 -0
  225. package/dist/lib/variables.js.map +1 -0
  226. package/dist/lib/word.d.ts +80 -0
  227. package/dist/lib/word.d.ts.map +1 -0
  228. package/dist/lib/word.js +360 -0
  229. package/dist/lib/word.js.map +1 -0
  230. package/dist/lib/wordcomments.d.ts +51 -0
  231. package/dist/lib/wordcomments.d.ts.map +1 -0
  232. package/dist/lib/wordcomments.js +587 -0
  233. package/dist/lib/wordcomments.js.map +1 -0
  234. package/eslint.config.js +27 -0
  235. package/lib/annotations.ts +622 -0
  236. package/lib/apply-buildup-colors.py +88 -0
  237. package/lib/build.ts +1013 -0
  238. package/lib/{citations.js → citations.ts} +38 -27
  239. package/lib/commands/{build.js → build.ts} +80 -27
  240. package/lib/commands/{citations.js → citations.ts} +36 -18
  241. package/lib/commands/{comments.js → comments.ts} +187 -54
  242. package/lib/commands/{context.js → context.ts} +18 -8
  243. package/lib/commands/{core.js → core.ts} +34 -20
  244. package/lib/commands/{doi.js → doi.ts} +32 -16
  245. package/lib/commands/{history.js → history.ts} +25 -12
  246. package/lib/commands/{index.js → index.ts} +9 -5
  247. package/lib/commands/{init.js → init.ts} +20 -8
  248. package/lib/commands/{response.js → response.ts} +47 -20
  249. package/lib/commands/{sections.js → sections.ts} +273 -68
  250. package/lib/commands/{utilities.js → utilities.ts} +338 -158
  251. package/lib/{comment-realign.js → comment-realign.ts} +117 -45
  252. package/lib/config.ts +84 -0
  253. package/lib/{crossref.js → crossref.ts} +213 -138
  254. package/lib/dependencies.ts +106 -0
  255. package/lib/doi-cache.ts +115 -0
  256. package/lib/{doi.js → doi.ts} +115 -281
  257. package/lib/{equations.js → equations.ts} +60 -64
  258. package/lib/{errors.js → errors.ts} +56 -48
  259. package/lib/{format.js → format.ts} +137 -63
  260. package/lib/{git.js → git.ts} +66 -63
  261. package/lib/{grammar.js → grammar.ts} +45 -32
  262. package/lib/image-registry.ts +180 -0
  263. package/lib/import.ts +2060 -0
  264. package/lib/journals.ts +505 -0
  265. package/lib/{merge.js → merge.ts} +185 -135
  266. package/lib/{orcid.js → orcid.ts} +17 -22
  267. package/lib/{pdf-comments.js → pdf-comments.ts} +76 -18
  268. package/lib/{pdf-import.js → pdf-import.ts} +148 -70
  269. package/lib/{plugins.js → plugins.ts} +82 -39
  270. package/lib/postprocess.ts +188 -0
  271. package/lib/pptx-color-filter.lua +37 -0
  272. package/lib/pptx-template.ts +625 -0
  273. package/lib/pptx-themes/academic.pptx +0 -0
  274. package/lib/pptx-themes/corporate.pptx +0 -0
  275. package/lib/pptx-themes/dark.pptx +0 -0
  276. package/lib/pptx-themes/default.pptx +0 -0
  277. package/lib/pptx-themes/minimal.pptx +0 -0
  278. package/lib/pptx-themes/plant.pptx +0 -0
  279. package/lib/pptx-themes.ts +896 -0
  280. package/lib/protect-restore.ts +516 -0
  281. package/lib/rate-limiter.ts +94 -0
  282. package/lib/{response.js → response.ts} +36 -21
  283. package/lib/{review.js → review.ts} +53 -43
  284. package/lib/{schema.js → schema.ts} +70 -25
  285. package/lib/{sections.js → sections.ts} +71 -76
  286. package/lib/slides.ts +793 -0
  287. package/lib/{spelling.js → spelling.ts} +43 -59
  288. package/lib/{templates.js → templates.ts} +20 -17
  289. package/lib/themes.ts +742 -0
  290. package/lib/{trackchanges.js → trackchanges.ts} +52 -23
  291. package/lib/types.ts +509 -0
  292. package/lib/{undo.js → undo.ts} +75 -52
  293. package/lib/utils.ts +41 -0
  294. package/lib/{variables.js → variables.ts} +60 -54
  295. package/lib/word.ts +428 -0
  296. package/lib/{wordcomments.js → wordcomments.ts} +94 -40
  297. package/package.json +15 -5
  298. package/skill/REFERENCE.md +67 -0
  299. package/tsconfig.json +26 -0
  300. package/lib/annotations.js +0 -414
  301. package/lib/build.js +0 -639
  302. package/lib/config.js +0 -79
  303. package/lib/import.js +0 -1145
  304. package/lib/journals.js +0 -629
  305. package/lib/word.js +0 -225
  306. /package/lib/{scientific-words.js → scientific-words.ts} +0 -0
@@ -0,0 +1,2009 @@
1
+ /**
2
+ * Utility commands: help, completions, word-count, stats, search, backup, archive,
3
+ * export, preview, watch, lint, grammar, annotate, apply, comment, clean, check,
4
+ * open, spelling, upgrade, batch, install-cli-skill, uninstall-cli-skill
5
+ *
6
+ * Miscellaneous utility commands for project management.
7
+ */
8
+ import { chalk, fs, path, fmt, findFiles, loadBuildConfig, getComments, setCommentStatus, countAnnotations, stripAnnotations, parseAnnotations, getUserName, countWords, } from './context.js';
9
+ /**
10
+ * Register utility commands with the program
11
+ */
12
+ export function register(program, pkg) {
13
+ // ==========================================================================
14
+ // HELP command - Comprehensive help
15
+ // ==========================================================================
16
+ program
17
+ .command('help')
18
+ .description('Show detailed help and workflow guide')
19
+ .argument('[topic]', 'Help topic: workflow, syntax, commands')
20
+ .action((topic) => {
21
+ if (!topic || topic === 'all') {
22
+ showFullHelp(pkg);
23
+ }
24
+ else if (topic === 'workflow') {
25
+ showWorkflowHelp();
26
+ }
27
+ else if (topic === 'syntax') {
28
+ showSyntaxHelp();
29
+ }
30
+ else if (topic === 'commands') {
31
+ showCommandsHelp();
32
+ }
33
+ else {
34
+ console.log(chalk.yellow(`Unknown topic: ${topic}`));
35
+ console.log(chalk.dim('Available topics: workflow, syntax, commands'));
36
+ }
37
+ });
38
+ // ==========================================================================
39
+ // COMPLETIONS command - Shell completions
40
+ // ==========================================================================
41
+ program
42
+ .command('completions')
43
+ .description('Output shell completions')
44
+ .argument('<shell>', 'Shell type: bash, zsh, powershell')
45
+ .action((shell) => {
46
+ const completionsDir = path.join(import.meta.dirname, '..', '..', 'completions');
47
+ if (shell === 'bash') {
48
+ const bashFile = path.join(completionsDir, 'rev.bash');
49
+ if (fs.existsSync(bashFile)) {
50
+ console.log(fs.readFileSync(bashFile, 'utf-8'));
51
+ }
52
+ else {
53
+ console.error(chalk.red('Bash completions not found'));
54
+ process.exit(1);
55
+ }
56
+ }
57
+ else if (shell === 'zsh') {
58
+ const zshFile = path.join(completionsDir, 'rev.zsh');
59
+ if (fs.existsSync(zshFile)) {
60
+ console.log(fs.readFileSync(zshFile, 'utf-8'));
61
+ }
62
+ else {
63
+ console.error(chalk.red('Zsh completions not found'));
64
+ process.exit(1);
65
+ }
66
+ }
67
+ else if (shell === 'powershell' || shell === 'pwsh') {
68
+ const psFile = path.join(completionsDir, 'rev.ps1');
69
+ if (fs.existsSync(psFile)) {
70
+ console.log(fs.readFileSync(psFile, 'utf-8'));
71
+ }
72
+ else {
73
+ console.error(chalk.red('PowerShell completions not found'));
74
+ process.exit(1);
75
+ }
76
+ }
77
+ else {
78
+ console.error(chalk.red(`Unknown shell: ${shell}`));
79
+ console.log(chalk.dim('Supported shells: bash, zsh, powershell'));
80
+ process.exit(1);
81
+ }
82
+ });
83
+ // ==========================================================================
84
+ // WORD-COUNT command - Per-section word counts
85
+ // ==========================================================================
86
+ program
87
+ .command('word-count')
88
+ .alias('wc')
89
+ .description('Show word counts per section')
90
+ .option('-l, --limit <number>', 'Warn if total exceeds limit', parseInt)
91
+ .option('-j, --journal <name>', 'Use journal word limit')
92
+ .action(async (options) => {
93
+ let config = {};
94
+ try {
95
+ config = loadBuildConfig('.') || {};
96
+ }
97
+ catch {
98
+ // Not in a rev project, that's ok
99
+ }
100
+ const sections = config.sections || [];
101
+ if (sections.length === 0) {
102
+ // Try to find .md files
103
+ const mdFiles = fs.readdirSync('.').filter(f => f.endsWith('.md') && !['README.md', 'CLAUDE.md', 'paper.md'].includes(f));
104
+ if (mdFiles.length === 0) {
105
+ console.error(chalk.red('No section files found. Run from a rev project directory.'));
106
+ process.exit(1);
107
+ }
108
+ sections.push(...mdFiles);
109
+ }
110
+ let total = 0;
111
+ const rows = [];
112
+ for (const section of sections) {
113
+ if (!fs.existsSync(section))
114
+ continue;
115
+ const text = fs.readFileSync(section, 'utf-8');
116
+ const words = countWords(text);
117
+ total += words;
118
+ rows.push([section, words.toLocaleString()]);
119
+ }
120
+ rows.push(['', '']);
121
+ rows.push([chalk.bold('Total'), chalk.bold(total.toLocaleString())]);
122
+ console.log(fmt.header('Word Count'));
123
+ console.log(fmt.table(['Section', 'Words'], rows));
124
+ // Check limit
125
+ let limit = options.limit;
126
+ if (options.journal) {
127
+ const { getJournalProfile } = await import('../journals.js');
128
+ const profile = getJournalProfile(options.journal);
129
+ if (profile?.requirements?.wordLimit?.main) {
130
+ limit = profile.requirements.wordLimit.main;
131
+ console.log(chalk.dim(`\nUsing ${profile.name} word limit: ${limit.toLocaleString()}`));
132
+ }
133
+ }
134
+ if (limit && total > limit) {
135
+ console.log(chalk.red(`\n⚠ Over limit by ${(total - limit).toLocaleString()} words`));
136
+ }
137
+ else if (limit) {
138
+ console.log(chalk.green(`\n✓ Within limit (${(limit - total).toLocaleString()} words remaining)`));
139
+ }
140
+ });
141
+ // ==========================================================================
142
+ // STATS command - Project dashboard
143
+ // ==========================================================================
144
+ program
145
+ .command('stats')
146
+ .description('Show project statistics dashboard')
147
+ .action(async (_options) => {
148
+ let config = {};
149
+ try {
150
+ config = loadBuildConfig('.') || {};
151
+ }
152
+ catch {
153
+ // Not in a rev project, that's ok
154
+ }
155
+ let sections = config.sections || [];
156
+ if (sections.length === 0) {
157
+ sections = fs.readdirSync('.').filter(f => f.endsWith('.md') && !['README.md', 'CLAUDE.md', 'paper.md'].includes(f));
158
+ }
159
+ let totalWords = 0;
160
+ let totalFigures = 0;
161
+ let totalTables = 0;
162
+ let totalComments = 0;
163
+ let pendingComments = 0;
164
+ const citations = new Set();
165
+ for (const section of sections) {
166
+ if (!fs.existsSync(section))
167
+ continue;
168
+ const text = fs.readFileSync(section, 'utf-8');
169
+ totalWords += countWords(text);
170
+ totalFigures += (text.match(/!\[.*?\]\(.*?\)/g) || []).length;
171
+ totalTables += (text.match(/^\|[^|]+\|/gm) || []).length / 5; // Approximate
172
+ const comments = getComments(text);
173
+ totalComments += comments.length;
174
+ pendingComments += comments.filter(c => !c.resolved).length;
175
+ const cites = text.match(/@(\w+)(?![:\w])/g) || [];
176
+ cites.forEach(c => citations.add(c.slice(1)));
177
+ }
178
+ console.log(fmt.header('Project Statistics'));
179
+ console.log();
180
+ const stats = [
181
+ ['Sections', sections.length],
182
+ ['Words', totalWords.toLocaleString()],
183
+ ['Figures', Math.round(totalFigures)],
184
+ ['Tables', Math.round(totalTables)],
185
+ ['Citations', citations.size],
186
+ ['Comments', `${totalComments} (${pendingComments} pending)`],
187
+ ];
188
+ for (const [label, value] of stats) {
189
+ console.log(` ${chalk.dim(label.padEnd(12))} ${chalk.bold(value)}`);
190
+ }
191
+ // Bibliography stats
192
+ const bibPath = config.bibliography || 'references.bib';
193
+ if (fs.existsSync(bibPath)) {
194
+ const bibContent = fs.readFileSync(bibPath, 'utf-8');
195
+ const bibEntries = (bibContent.match(/@\w+\s*\{/g) || []).length;
196
+ console.log(` ${chalk.dim('Bib entries'.padEnd(12))} ${chalk.bold(bibEntries)}`);
197
+ }
198
+ console.log();
199
+ });
200
+ // ==========================================================================
201
+ // SEARCH command - Search across section files
202
+ // ==========================================================================
203
+ program
204
+ .command('search')
205
+ .description('Search across all section files')
206
+ .argument('<query>', 'Search query (supports regex)')
207
+ .option('-i, --ignore-case', 'Case-insensitive search')
208
+ .option('-c, --context <lines>', 'Show context lines', parseInt, 1)
209
+ .action((query, options) => {
210
+ let config = {};
211
+ try {
212
+ config = loadBuildConfig('.') || {};
213
+ }
214
+ catch {
215
+ // Not in a rev project, that's ok
216
+ }
217
+ let sections = config.sections || [];
218
+ if (sections.length === 0) {
219
+ sections = fs.readdirSync('.').filter(f => f.endsWith('.md') && !['README.md', 'CLAUDE.md'].includes(f));
220
+ }
221
+ const flags = options.ignoreCase ? 'gi' : 'g';
222
+ let pattern;
223
+ try {
224
+ pattern = new RegExp(query, flags);
225
+ }
226
+ catch {
227
+ pattern = new RegExp(query.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'), flags);
228
+ }
229
+ let totalMatches = 0;
230
+ for (const section of sections) {
231
+ if (!fs.existsSync(section))
232
+ continue;
233
+ const text = fs.readFileSync(section, 'utf-8');
234
+ const lines = text.split('\n');
235
+ const matches = [];
236
+ for (let i = 0; i < lines.length; i++) {
237
+ if (pattern.test(lines[i])) {
238
+ matches.push({ line: i + 1, text: lines[i] });
239
+ pattern.lastIndex = 0;
240
+ }
241
+ }
242
+ if (matches.length > 0) {
243
+ console.log(chalk.cyan.bold(`\n${section}`));
244
+ for (const match of matches) {
245
+ const highlighted = match.text.replace(pattern, (m) => chalk.yellow.bold(m));
246
+ console.log(` ${chalk.dim(match.line + ':')} ${highlighted}`);
247
+ }
248
+ totalMatches += matches.length;
249
+ }
250
+ }
251
+ if (totalMatches === 0) {
252
+ console.log(chalk.yellow(`No matches found for "${query}"`));
253
+ }
254
+ else {
255
+ console.log(chalk.dim(`\n${totalMatches} match${totalMatches === 1 ? '' : 'es'} found`));
256
+ }
257
+ });
258
+ // ==========================================================================
259
+ // BACKUP command - Timestamped project backup
260
+ // ==========================================================================
261
+ program
262
+ .command('backup')
263
+ .description('Create timestamped project backup')
264
+ .option('-n, --name <name>', 'Custom backup name')
265
+ .option('-o, --output <dir>', 'Output directory', '.')
266
+ .action(async (options) => {
267
+ const { default: AdmZip } = await import('adm-zip');
268
+ const zip = new AdmZip();
269
+ const date = new Date().toISOString().slice(0, 10);
270
+ const name = options.name || `backup-${date}`;
271
+ const outputPath = path.join(options.output || '.', `${name}.zip`);
272
+ // Files to exclude
273
+ const excludePatterns = [
274
+ 'node_modules', '.git', '.DS_Store', '*.zip',
275
+ 'paper.md' // Generated file
276
+ ];
277
+ const shouldInclude = (file) => {
278
+ for (const pattern of excludePatterns) {
279
+ if (file.includes(pattern.replace('*', '')))
280
+ return false;
281
+ }
282
+ return true;
283
+ };
284
+ const addDir = (dir, zipPath = '') => {
285
+ const entries = fs.readdirSync(dir, { withFileTypes: true });
286
+ for (const entry of entries) {
287
+ const fullPath = path.join(dir, entry.name);
288
+ const entryZipPath = path.join(zipPath, entry.name);
289
+ if (!shouldInclude(entry.name))
290
+ continue;
291
+ if (entry.isDirectory()) {
292
+ addDir(fullPath, entryZipPath);
293
+ }
294
+ else {
295
+ zip.addLocalFile(fullPath, zipPath || undefined);
296
+ }
297
+ }
298
+ };
299
+ // Add current directory
300
+ const entries = fs.readdirSync('.', { withFileTypes: true });
301
+ for (const entry of entries) {
302
+ if (!shouldInclude(entry.name))
303
+ continue;
304
+ if (entry.isDirectory()) {
305
+ addDir(entry.name, entry.name);
306
+ }
307
+ else if (entry.isFile()) {
308
+ zip.addLocalFile(entry.name);
309
+ }
310
+ }
311
+ zip.writeZip(outputPath);
312
+ console.log(fmt.status('success', `Backup created: ${outputPath}`));
313
+ });
314
+ // ==========================================================================
315
+ // ARCHIVE command - Archive reviewer docx files
316
+ // ==========================================================================
317
+ program
318
+ .command('archive')
319
+ .description('Move reviewer .docx files to archive folder')
320
+ .argument('[files...]', 'Specific files to archive (default: all .docx)')
321
+ .option('-d, --dir <folder>', 'Archive folder name', 'archive')
322
+ .option('--by <name>', 'Reviewer name (auto-detected if single commenter)')
323
+ .option('--no-rename', 'Keep original filenames')
324
+ .option('--dry-run', 'Preview without moving files')
325
+ .action(async (files, options) => {
326
+ const { extractWordComments } = await import('../import.js');
327
+ const { default: YAML } = await import('yaml');
328
+ // Find docx files to archive
329
+ let docxFiles = files && files.length > 0
330
+ ? files.filter(f => f.endsWith('.docx') && fs.existsSync(f))
331
+ : findFiles('.docx');
332
+ // Exclude our own build outputs
333
+ let projectSlug = null;
334
+ const configPath = path.join(process.cwd(), 'rev.yaml');
335
+ if (fs.existsSync(configPath)) {
336
+ try {
337
+ const config = YAML.parse(fs.readFileSync(configPath, 'utf-8'));
338
+ if (config.title) {
339
+ projectSlug = config.title
340
+ .toLowerCase()
341
+ .replace(/[^a-z0-9]+/g, '-')
342
+ .replace(/^-|-$/g, '')
343
+ .slice(0, 50);
344
+ }
345
+ }
346
+ catch (e) {
347
+ // Ignore config errors
348
+ }
349
+ }
350
+ // Filter out build outputs
351
+ if (projectSlug && (!files || files.length === 0)) {
352
+ const buildPatterns = [
353
+ `${projectSlug}.docx`,
354
+ `${projectSlug}_comments.docx`,
355
+ `${projectSlug}-changes.docx`,
356
+ 'paper.docx',
357
+ 'paper_comments.docx',
358
+ 'paper-changes.docx',
359
+ ];
360
+ const excluded = [];
361
+ docxFiles = docxFiles.filter(f => {
362
+ const base = path.basename(f).toLowerCase();
363
+ const isBuilt = buildPatterns.includes(base);
364
+ if (isBuilt)
365
+ excluded.push(f);
366
+ return !isBuilt;
367
+ });
368
+ if (excluded.length > 0) {
369
+ console.log(chalk.dim(` Skipping build outputs: ${excluded.join(', ')}`));
370
+ console.log();
371
+ }
372
+ }
373
+ if (docxFiles.length === 0) {
374
+ console.log(fmt.status('info', 'No .docx files to archive.'));
375
+ return;
376
+ }
377
+ const projectTitle = projectSlug;
378
+ // Create archive folder
379
+ const archiveDir = path.resolve(options.dir || 'archive');
380
+ if (!options.dryRun && !fs.existsSync(archiveDir)) {
381
+ fs.mkdirSync(archiveDir, { recursive: true });
382
+ }
383
+ console.log(fmt.header('Archive'));
384
+ console.log();
385
+ const moved = [];
386
+ for (const file of docxFiles) {
387
+ const stat = fs.statSync(file);
388
+ const mtime = stat.mtime;
389
+ const timestamp = mtime.toISOString().slice(0, 19).replace(/[-:]/g, '').replace('T', '_');
390
+ // Determine reviewer name
391
+ let reviewer = options.by || null;
392
+ if (!reviewer && options.rename !== false) {
393
+ try {
394
+ const comments = await extractWordComments(file);
395
+ const authors = [...new Set(comments.map(c => c.author).filter(a => a && a !== 'Unknown'))];
396
+ if (authors.length === 1) {
397
+ reviewer = authors[0].replace(/[^a-zA-Z0-9]/g, '-').replace(/^-|-$/g, '');
398
+ }
399
+ }
400
+ catch (e) {
401
+ // Ignore extraction errors
402
+ }
403
+ }
404
+ // Generate new name
405
+ let newName;
406
+ if (options.rename === false) {
407
+ newName = path.basename(file);
408
+ }
409
+ else {
410
+ const base = path.basename(file, '.docx');
411
+ if (/^\d{8}_\d{6}_/.test(base)) {
412
+ newName = path.basename(file);
413
+ }
414
+ else {
415
+ const namePart = projectTitle || base;
416
+ if (reviewer) {
417
+ newName = `${timestamp}_${reviewer}_${namePart}.docx`;
418
+ }
419
+ else {
420
+ newName = `${timestamp}_${namePart}.docx`;
421
+ }
422
+ }
423
+ }
424
+ const destPath = path.join(archiveDir, newName);
425
+ if (options.dryRun) {
426
+ console.log(` ${chalk.dim(file)} → ${chalk.cyan(path.join(options.dir || 'archive', newName))}`);
427
+ }
428
+ else {
429
+ // Handle name collision
430
+ let finalPath = destPath;
431
+ let counter = 1;
432
+ while (fs.existsSync(finalPath)) {
433
+ const ext = path.extname(newName);
434
+ const base = path.basename(newName, ext);
435
+ finalPath = path.join(archiveDir, `${base}_${counter}${ext}`);
436
+ counter++;
437
+ }
438
+ fs.renameSync(file, finalPath);
439
+ console.log(` ${chalk.dim(file)} → ${chalk.green(path.relative(process.cwd(), finalPath))}`);
440
+ }
441
+ moved.push(file);
442
+ }
443
+ console.log();
444
+ if (options.dryRun) {
445
+ console.log(fmt.status('info', `Would archive ${moved.length} file(s). Run without --dry-run to proceed.`));
446
+ }
447
+ else {
448
+ console.log(fmt.status('success', `Archived ${moved.length} file(s) to ${options.dir || 'archive'}/`));
449
+ }
450
+ });
451
+ // ==========================================================================
452
+ // EXPORT command - Export project as distributable zip
453
+ // ==========================================================================
454
+ program
455
+ .command('export')
456
+ .description('Export project as distributable zip')
457
+ .option('-o, --output <file>', 'Output filename')
458
+ .option('--include-output', 'Include built PDF/DOCX files')
459
+ .action(async (options) => {
460
+ const { default: AdmZip } = await import('adm-zip');
461
+ const { build } = await import('../build.js');
462
+ let config = {};
463
+ try {
464
+ config = loadBuildConfig('.') || {};
465
+ }
466
+ catch {
467
+ // Not in a rev project, that's ok
468
+ }
469
+ // Build first if including output
470
+ if (options.includeOutput) {
471
+ console.log(chalk.dim('Building documents...'));
472
+ await build('.', ['pdf', 'docx']);
473
+ }
474
+ const zip = new AdmZip();
475
+ const projectName = config.title?.replace(/[^a-zA-Z0-9]/g, '-').toLowerCase() || 'project';
476
+ const outputPath = options.output || `${projectName}-export.zip`;
477
+ const exclude = ['node_modules', '.git', '.DS_Store', '*.zip'];
478
+ const shouldInclude = (name) => {
479
+ if (!options.includeOutput && (name.endsWith('.pdf') || name.endsWith('.docx'))) {
480
+ return false;
481
+ }
482
+ for (const pattern of exclude) {
483
+ if (name === pattern || name.includes(pattern.replace('*', '')))
484
+ return false;
485
+ }
486
+ return true;
487
+ };
488
+ const addDir = (dir, zipPath = '') => {
489
+ const entries = fs.readdirSync(dir, { withFileTypes: true });
490
+ for (const entry of entries) {
491
+ const fullPath = path.join(dir, entry.name);
492
+ const entryZipPath = path.join(zipPath, entry.name);
493
+ if (!shouldInclude(entry.name))
494
+ continue;
495
+ if (entry.isDirectory()) {
496
+ addDir(fullPath, entryZipPath);
497
+ }
498
+ else {
499
+ zip.addLocalFile(fullPath, zipPath || undefined);
500
+ }
501
+ }
502
+ };
503
+ const entries = fs.readdirSync('.', { withFileTypes: true });
504
+ for (const entry of entries) {
505
+ if (!shouldInclude(entry.name))
506
+ continue;
507
+ if (entry.isDirectory()) {
508
+ addDir(entry.name, entry.name);
509
+ }
510
+ else if (entry.isFile()) {
511
+ zip.addLocalFile(entry.name);
512
+ }
513
+ }
514
+ zip.writeZip(outputPath);
515
+ console.log(fmt.status('success', `Exported: ${outputPath}`));
516
+ });
517
+ // ==========================================================================
518
+ // PREVIEW command - Build and open document
519
+ // ==========================================================================
520
+ program
521
+ .command('preview')
522
+ .description('Build and open document in default app')
523
+ .argument('[format]', 'Format to preview: pdf, docx', 'pdf')
524
+ .action(async (format, _options) => {
525
+ const { exec } = await import('child_process');
526
+ const { build } = await import('../build.js');
527
+ let config = {};
528
+ try {
529
+ config = loadBuildConfig('.') || {};
530
+ }
531
+ catch (err) {
532
+ console.error(chalk.red('Not in a rev project directory (no rev.yaml found)'));
533
+ process.exit(1);
534
+ }
535
+ console.log(chalk.dim(`Building ${format}...`));
536
+ const result = await build('.', [format]);
537
+ const buildResult = result.results.find(r => r.format === format);
538
+ if (!buildResult?.success) {
539
+ const errorMsg = buildResult?.error || 'Unknown error';
540
+ console.error(chalk.red(`Build failed: ${errorMsg}`));
541
+ process.exit(1);
542
+ }
543
+ const outputFile = buildResult.outputPath;
544
+ if (!outputFile || !fs.existsSync(outputFile)) {
545
+ console.error(chalk.red(`Output file not found: ${outputFile}`));
546
+ process.exit(1);
547
+ }
548
+ // Open with system default
549
+ const openCmd = process.platform === 'darwin' ? 'open' :
550
+ process.platform === 'win32' ? 'start' : 'xdg-open';
551
+ exec(`${openCmd} "${outputFile}"`, (err) => {
552
+ if (err) {
553
+ console.error(chalk.red(`Could not open file: ${err.message}`));
554
+ }
555
+ else {
556
+ console.log(fmt.status('success', `Opened ${outputFile}`));
557
+ }
558
+ });
559
+ });
560
+ // ==========================================================================
561
+ // WATCH command - Auto-rebuild on changes
562
+ // ==========================================================================
563
+ program
564
+ .command('watch')
565
+ .description('Watch files and auto-rebuild on changes')
566
+ .argument('[format]', 'Format to build: pdf, docx, all', 'pdf')
567
+ .option('--no-open', 'Do not open after first build')
568
+ .action(async (format, options) => {
569
+ const { exec } = await import('child_process');
570
+ const { build } = await import('../build.js');
571
+ let config = {};
572
+ try {
573
+ config = loadBuildConfig('.') || {};
574
+ }
575
+ catch (err) {
576
+ console.error(chalk.red('Not in a rev project directory (no rev.yaml found)'));
577
+ process.exit(1);
578
+ }
579
+ let sections = config.sections || [];
580
+ if (sections.length === 0) {
581
+ sections = fs.readdirSync('.').filter(f => f.endsWith('.md') && !['README.md', 'CLAUDE.md', 'paper.md'].includes(f));
582
+ }
583
+ const filesToWatch = [
584
+ ...sections,
585
+ 'rev.yaml',
586
+ config.bibliography || 'references.bib'
587
+ ].filter(f => fs.existsSync(f));
588
+ console.log(fmt.header('Watch Mode'));
589
+ console.log(chalk.dim(`Watching: ${filesToWatch.join(', ')}`));
590
+ console.log(chalk.dim('Press Ctrl+C to stop\n'));
591
+ let building = false;
592
+ let pendingBuild = false;
593
+ const doBuild = async () => {
594
+ if (building) {
595
+ pendingBuild = true;
596
+ return;
597
+ }
598
+ building = true;
599
+ console.log(chalk.dim(`\n[${new Date().toLocaleTimeString()}] Rebuilding...`));
600
+ try {
601
+ const formats = format === 'all' ? ['pdf', 'docx'] : [format];
602
+ const result = await build('.', formats);
603
+ for (const r of result.results) {
604
+ if (r.success) {
605
+ console.log(chalk.green(` ✓ ${r.format}: ${r.outputPath}`));
606
+ }
607
+ else {
608
+ console.log(chalk.red(` ✗ ${r.format}: ${r.error}`));
609
+ }
610
+ }
611
+ }
612
+ catch (err) {
613
+ console.error(chalk.red(` Build error: ${err.message}`));
614
+ }
615
+ building = false;
616
+ if (pendingBuild) {
617
+ pendingBuild = false;
618
+ doBuild();
619
+ }
620
+ };
621
+ // Initial build
622
+ await doBuild();
623
+ // Open after first build
624
+ if (options.open) {
625
+ const outputFile = format === 'docx' ?
626
+ (config.title?.replace(/[^a-zA-Z0-9]/g, '-').toLowerCase() || 'paper') + '.docx' :
627
+ (config.title?.replace(/[^a-zA-Z0-9]/g, '-').toLowerCase() || 'paper') + '.pdf';
628
+ if (fs.existsSync(outputFile)) {
629
+ const openCmd = process.platform === 'darwin' ? 'open' :
630
+ process.platform === 'win32' ? 'start' : 'xdg-open';
631
+ exec(`${openCmd} "${outputFile}"`);
632
+ }
633
+ }
634
+ // Watch files
635
+ for (const file of filesToWatch) {
636
+ fs.watch(file, { persistent: true }, (eventType) => {
637
+ if (eventType === 'change') {
638
+ doBuild();
639
+ }
640
+ });
641
+ }
642
+ });
643
+ // ==========================================================================
644
+ // LINT command - Check for common issues
645
+ // ==========================================================================
646
+ program
647
+ .command('lint')
648
+ .description('Check for common issues in the project')
649
+ .option('--fix', 'Auto-fix issues where possible')
650
+ .action(async (_options) => {
651
+ let config = {};
652
+ try {
653
+ config = loadBuildConfig('.') || {};
654
+ }
655
+ catch {
656
+ // Not in a rev project, that's ok
657
+ }
658
+ let sections = config.sections || [];
659
+ if (sections.length === 0) {
660
+ sections = fs.readdirSync('.').filter(f => f.endsWith('.md') && !['README.md', 'CLAUDE.md', 'paper.md'].includes(f));
661
+ }
662
+ const issues = [];
663
+ const warnings = [];
664
+ // Collect all content
665
+ let allText = '';
666
+ for (const section of sections) {
667
+ if (fs.existsSync(section)) {
668
+ allText += fs.readFileSync(section, 'utf-8') + '\n';
669
+ }
670
+ }
671
+ // Check 1: Broken cross-references
672
+ const figAnchors = new Set();
673
+ const tblAnchors = new Set();
674
+ const eqAnchors = new Set();
675
+ const anchorPattern = /\{#(fig|tbl|eq):([^}]+)\}/g;
676
+ let match;
677
+ while ((match = anchorPattern.exec(allText)) !== null) {
678
+ if (match[1] === 'fig')
679
+ figAnchors.add(match[2]);
680
+ else if (match[1] === 'tbl')
681
+ tblAnchors.add(match[2]);
682
+ else if (match[1] === 'eq')
683
+ eqAnchors.add(match[2]);
684
+ }
685
+ const refPattern = /@(fig|tbl|eq):([a-zA-Z0-9_-]+)/g;
686
+ while ((match = refPattern.exec(allText)) !== null) {
687
+ const type = match[1];
688
+ const label = match[2];
689
+ const anchors = type === 'fig' ? figAnchors : type === 'tbl' ? tblAnchors : eqAnchors;
690
+ if (!anchors.has(label)) {
691
+ issues.push({
692
+ type: 'error',
693
+ message: `Broken reference: @${type}:${label}`,
694
+ fix: null
695
+ });
696
+ }
697
+ }
698
+ // Check 2: Orphaned figures
699
+ for (const label of figAnchors) {
700
+ if (!allText.includes(`@fig:${label}`)) {
701
+ warnings.push({
702
+ type: 'warning',
703
+ message: `Unreferenced figure: {#fig:${label}}`,
704
+ });
705
+ }
706
+ }
707
+ // Check 3: Missing citations
708
+ const bibPath = config.bibliography || 'references.bib';
709
+ if (fs.existsSync(bibPath)) {
710
+ const bibContent = fs.readFileSync(bibPath, 'utf-8');
711
+ const bibKeys = new Set();
712
+ const bibPattern = /@\w+\s*\{\s*([^,]+)/g;
713
+ while ((match = bibPattern.exec(bibContent)) !== null) {
714
+ bibKeys.add(match[1].trim());
715
+ }
716
+ const citePattern = /@([a-zA-Z][a-zA-Z0-9_-]*)(?![:\w])/g;
717
+ while ((match = citePattern.exec(allText)) !== null) {
718
+ const key = match[1];
719
+ if (!bibKeys.has(key) && !['fig', 'tbl', 'eq'].includes(key)) {
720
+ issues.push({
721
+ type: 'error',
722
+ message: `Missing citation: @${key}`,
723
+ });
724
+ }
725
+ }
726
+ }
727
+ // Check 4: Unresolved comments
728
+ const comments = getComments(allText);
729
+ const pending = comments.filter(c => !c.resolved);
730
+ if (pending.length > 0) {
731
+ warnings.push({
732
+ type: 'warning',
733
+ message: `${pending.length} unresolved comment${pending.length === 1 ? '' : 's'}`,
734
+ });
735
+ }
736
+ // Check 5: Empty sections
737
+ for (const section of sections) {
738
+ if (fs.existsSync(section)) {
739
+ const content = fs.readFileSync(section, 'utf-8').trim();
740
+ if (content.length < 50) {
741
+ warnings.push({
742
+ type: 'warning',
743
+ message: `Section appears empty: ${section}`,
744
+ });
745
+ }
746
+ }
747
+ }
748
+ // Output results
749
+ console.log(fmt.header('Lint Results'));
750
+ console.log();
751
+ if (issues.length === 0 && warnings.length === 0) {
752
+ console.log(chalk.green('✓ No issues found'));
753
+ return;
754
+ }
755
+ for (const issue of issues) {
756
+ console.log(chalk.red(` ✗ ${issue.message}`));
757
+ }
758
+ for (const warning of warnings) {
759
+ console.log(chalk.yellow(` ⚠ ${warning.message}`));
760
+ }
761
+ console.log();
762
+ console.log(chalk.dim(`${issues.length} error${issues.length === 1 ? '' : 's'}, ${warnings.length} warning${warnings.length === 1 ? '' : 's'}`));
763
+ if (issues.length > 0) {
764
+ process.exit(1);
765
+ }
766
+ });
767
+ // ==========================================================================
768
+ // GRAMMAR command - Check grammar and style
769
+ // ==========================================================================
770
+ program
771
+ .command('grammar')
772
+ .description('Check grammar and style issues')
773
+ .argument('[files...]', 'Markdown files to check')
774
+ .option('--learn <word>', 'Add word to custom dictionary')
775
+ .option('--forget <word>', 'Remove word from custom dictionary')
776
+ .option('--list', 'List custom dictionary words')
777
+ .option('--rules', 'List available grammar rules')
778
+ .option('--no-scientific', 'Disable scientific writing rules')
779
+ .option('-s, --severity <level>', 'Minimum severity: error, warning, info', 'info')
780
+ .action(async (files, options) => {
781
+ const { checkGrammar, getGrammarSummary, loadDictionary, addToDictionary, removeFromDictionary, listRules, } = await import('../grammar.js');
782
+ // Handle dictionary management
783
+ if (options.learn) {
784
+ const added = addToDictionary(options.learn);
785
+ if (added) {
786
+ console.log(fmt.status('success', `Added "${options.learn}" to dictionary`));
787
+ }
788
+ else {
789
+ console.log(chalk.dim(`"${options.learn}" already in dictionary`));
790
+ }
791
+ return;
792
+ }
793
+ if (options.forget) {
794
+ const removed = removeFromDictionary(options.forget);
795
+ if (removed) {
796
+ console.log(fmt.status('success', `Removed "${options.forget}" from dictionary`));
797
+ }
798
+ else {
799
+ console.log(chalk.yellow(`"${options.forget}" not in dictionary`));
800
+ }
801
+ return;
802
+ }
803
+ if (options.list) {
804
+ const words = loadDictionary();
805
+ console.log(fmt.header('Custom Dictionary'));
806
+ console.log();
807
+ if (words.size === 0) {
808
+ console.log(chalk.dim(' No custom words defined'));
809
+ console.log(chalk.dim(' Use --learn <word> to add words'));
810
+ }
811
+ else {
812
+ const sorted = [...words].sort();
813
+ for (const word of sorted) {
814
+ console.log(` ${word}`);
815
+ }
816
+ console.log();
817
+ console.log(chalk.dim(`${words.size} word(s)`));
818
+ }
819
+ return;
820
+ }
821
+ if (options.rules) {
822
+ const rules = listRules(options.scientific);
823
+ console.log(fmt.header('Grammar Rules'));
824
+ console.log();
825
+ for (const rule of rules) {
826
+ const icon = rule.severity === 'error' ? chalk.red('●') :
827
+ rule.severity === 'warning' ? chalk.yellow('●') :
828
+ chalk.blue('●');
829
+ console.log(` ${icon} ${chalk.bold(rule.id)}`);
830
+ console.log(chalk.dim(` ${rule.message}`));
831
+ }
832
+ return;
833
+ }
834
+ // Get files to check
835
+ let mdFiles = files;
836
+ if (!mdFiles || mdFiles.length === 0) {
837
+ let config = {};
838
+ try {
839
+ config = loadBuildConfig('.') || {};
840
+ }
841
+ catch {
842
+ // Not in a rev project
843
+ }
844
+ mdFiles = config.sections || [];
845
+ if (mdFiles.length === 0) {
846
+ mdFiles = fs.readdirSync('.').filter(f => f.endsWith('.md') && !['README.md', 'CLAUDE.md', 'paper.md'].includes(f));
847
+ }
848
+ }
849
+ if (mdFiles.length === 0) {
850
+ console.error(chalk.red('No markdown files found'));
851
+ process.exit(1);
852
+ }
853
+ console.log(fmt.header('Grammar Check'));
854
+ console.log();
855
+ const severityLevels = { error: 3, warning: 2, info: 1 };
856
+ const minSeverity = severityLevels[options.severity || 'info'] || 1;
857
+ let allIssues = [];
858
+ for (const file of mdFiles) {
859
+ if (!fs.existsSync(file))
860
+ continue;
861
+ const text = fs.readFileSync(file, 'utf-8');
862
+ const issues = checkGrammar(text, { scientific: options.scientific });
863
+ // Filter by severity
864
+ const filtered = issues.filter((i) => severityLevels[i.severity] >= minSeverity);
865
+ if (filtered.length > 0) {
866
+ console.log(chalk.cyan.bold(file));
867
+ for (const issue of filtered) {
868
+ const icon = issue.severity === 'error' ? chalk.red('●') :
869
+ issue.severity === 'warning' ? chalk.yellow('●') :
870
+ chalk.blue('●');
871
+ console.log(` ${chalk.dim(`L${issue.line}:`)} ${icon} ${issue.message}`);
872
+ console.log(chalk.dim(` "${issue.match}" in: ${issue.context.slice(0, 60)}...`));
873
+ }
874
+ console.log();
875
+ allIssues.push(...filtered.map(i => ({ ...i, file })));
876
+ }
877
+ }
878
+ const summary = getGrammarSummary(allIssues);
879
+ if (summary.total === 0) {
880
+ console.log(chalk.green('✓ No issues found'));
881
+ }
882
+ else {
883
+ console.log(chalk.dim(`Found ${summary.total} issue(s): ${summary.errors} errors, ${summary.warnings} warnings, ${summary.info} info`));
884
+ console.log();
885
+ console.log(chalk.dim('Tip: Use --learn <word> to add words to dictionary'));
886
+ }
887
+ });
888
+ // ==========================================================================
889
+ // ANNOTATE command - Add comments to Word document
890
+ // ==========================================================================
891
+ program
892
+ .command('annotate')
893
+ .description('Add comment to Word document')
894
+ .argument('<docx>', 'Word document')
895
+ .option('-m, --message <text>', 'Comment text')
896
+ .option('-s, --search <text>', 'Text to attach comment to')
897
+ .option('-a, --author <name>', 'Comment author')
898
+ .action(async (docxPath, options) => {
899
+ if (!fs.existsSync(docxPath)) {
900
+ console.error(chalk.red(`File not found: ${docxPath}`));
901
+ process.exit(1);
902
+ }
903
+ if (!options.message) {
904
+ console.error(chalk.red('Comment message required (-m)'));
905
+ process.exit(1);
906
+ }
907
+ const { default: AdmZip } = await import('adm-zip');
908
+ const zip = new AdmZip(docxPath);
909
+ // Read document.xml
910
+ const docEntry = zip.getEntry('word/document.xml');
911
+ if (!docEntry) {
912
+ console.error(chalk.red('Invalid Word document'));
913
+ process.exit(1);
914
+ }
915
+ let docXml = zip.readAsText(docEntry);
916
+ // Read or create comments.xml
917
+ let commentsEntry = zip.getEntry('word/comments.xml');
918
+ let commentsXml;
919
+ let nextCommentId = 1;
920
+ if (commentsEntry) {
921
+ commentsXml = zip.readAsText(commentsEntry);
922
+ const idMatches = commentsXml.match(/w:id="(\d+)"/g) || [];
923
+ for (const m of idMatches) {
924
+ const id = parseInt(m.match(/\d+/)[0]);
925
+ if (id >= nextCommentId)
926
+ nextCommentId = id + 1;
927
+ }
928
+ }
929
+ else {
930
+ commentsXml = `<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
931
+ <w:comments xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main">
932
+ </w:comments>`;
933
+ }
934
+ const author = options.author || getUserName() || 'Claude';
935
+ const date = new Date().toISOString();
936
+ const commentId = nextCommentId;
937
+ // Add comment to comments.xml
938
+ const newComment = `<w:comment w:id="${commentId}" w:author="${author}" w:date="${date}">
939
+ <w:p><w:r><w:t>${options.message}</w:t></w:r></w:p>
940
+ </w:comment>`;
941
+ commentsXml = commentsXml.replace('</w:comments>', `${newComment}\n</w:comments>`);
942
+ // Find text and add comment markers
943
+ if (options.search) {
944
+ const searchText = options.search;
945
+ const textPattern = new RegExp(`(<w:t[^>]*>)([^<]*${searchText.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}[^<]*)(<\/w:t>)`, 'i');
946
+ if (textPattern.test(docXml)) {
947
+ docXml = docXml.replace(textPattern, (_match, start, text, end) => {
948
+ return `<w:commentRangeStart w:id="${commentId}"/>${start}${text}${end}<w:commentRangeEnd w:id="${commentId}"/><w:r><w:commentReference w:id="${commentId}"/></w:r>`;
949
+ });
950
+ }
951
+ else {
952
+ console.log(chalk.yellow(`Text "${searchText}" not found in document. Comment added without anchor.`));
953
+ }
954
+ }
955
+ // Update zip
956
+ zip.updateFile('word/document.xml', Buffer.from(docXml));
957
+ if (commentsEntry) {
958
+ zip.updateFile('word/comments.xml', Buffer.from(commentsXml));
959
+ }
960
+ else {
961
+ zip.addFile('word/comments.xml', Buffer.from(commentsXml));
962
+ // Update [Content_Types].xml
963
+ const ctEntry = zip.getEntry('[Content_Types].xml');
964
+ if (ctEntry) {
965
+ let ctXml = zip.readAsText(ctEntry);
966
+ if (!ctXml.includes('comments.xml')) {
967
+ ctXml = ctXml.replace('</Types>', '<Override PartName="/word/comments.xml" ContentType="application/vnd.openxmlformats-officedocument.wordprocessingml.comments+xml"/>\n</Types>');
968
+ zip.updateFile('[Content_Types].xml', Buffer.from(ctXml));
969
+ }
970
+ }
971
+ // Update document.xml.rels
972
+ const relsEntry = zip.getEntry('word/_rels/document.xml.rels');
973
+ if (relsEntry) {
974
+ let relsXml = zip.readAsText(relsEntry);
975
+ if (!relsXml.includes('comments.xml')) {
976
+ const newRelId = `rId${Date.now()}`;
977
+ relsXml = relsXml.replace('</Relationships>', `<Relationship Id="${newRelId}" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/comments" Target="comments.xml"/>\n</Relationships>`);
978
+ zip.updateFile('word/_rels/document.xml.rels', Buffer.from(relsXml));
979
+ }
980
+ }
981
+ }
982
+ // Write back
983
+ zip.writeZip(docxPath);
984
+ console.log(fmt.status('success', `Added comment to ${docxPath}`));
985
+ });
986
+ // ==========================================================================
987
+ // APPLY command - Apply MD annotations as Word track changes
988
+ // ==========================================================================
989
+ program
990
+ .command('apply')
991
+ .description('Apply markdown annotations to Word document as track changes')
992
+ .argument('<md>', 'Markdown file with annotations')
993
+ .argument('<docx>', 'Output Word document')
994
+ .option('-a, --author <name>', 'Author name for track changes')
995
+ .action(async (mdPath, docxPath, options) => {
996
+ if (!fs.existsSync(mdPath)) {
997
+ console.error(chalk.red(`File not found: ${mdPath}`));
998
+ process.exit(1);
999
+ }
1000
+ const mdContent = fs.readFileSync(mdPath, 'utf-8');
1001
+ const annotations = parseAnnotations(mdContent);
1002
+ if (annotations.length === 0) {
1003
+ console.log(chalk.yellow('No annotations found in markdown file'));
1004
+ }
1005
+ const author = options.author || getUserName() || 'Author';
1006
+ // Build document with track changes
1007
+ const { buildWithTrackChanges } = await import('../trackchanges.js');
1008
+ try {
1009
+ const result = await buildWithTrackChanges(mdPath, docxPath, { author });
1010
+ if (result.success) {
1011
+ console.log(fmt.status('success', result.message));
1012
+ console.log(chalk.dim(` ${annotations.length} annotations applied as track changes`));
1013
+ }
1014
+ else {
1015
+ console.error(chalk.red(result.message));
1016
+ process.exit(1);
1017
+ }
1018
+ }
1019
+ catch (err) {
1020
+ console.error(chalk.red(`Error: ${err.message}`));
1021
+ process.exit(1);
1022
+ }
1023
+ });
1024
+ // ==========================================================================
1025
+ // COMMENT command - Interactive comment addition to DOCX
1026
+ // ==========================================================================
1027
+ program
1028
+ .command('comment')
1029
+ .description('Add comments to Word document interactively')
1030
+ .argument('<docx>', 'Word document')
1031
+ .option('-a, --author <name>', 'Comment author')
1032
+ .action(async (docxPath, options) => {
1033
+ if (!fs.existsSync(docxPath)) {
1034
+ console.error(chalk.red(`File not found: ${docxPath}`));
1035
+ process.exit(1);
1036
+ }
1037
+ const { default: AdmZip } = await import('adm-zip');
1038
+ const readline = await import('readline');
1039
+ const rl = readline.createInterface({
1040
+ input: process.stdin,
1041
+ output: process.stdout,
1042
+ });
1043
+ const ask = (prompt) => new Promise((resolve) => rl.question(prompt, resolve));
1044
+ const author = options.author || getUserName() || 'Reviewer';
1045
+ console.log(fmt.header('Interactive Comment Mode'));
1046
+ console.log(chalk.dim(` Document: ${docxPath}`));
1047
+ console.log(chalk.dim(` Author: ${author}`));
1048
+ console.log(chalk.dim(' Type your comment, then the text to attach it to.'));
1049
+ console.log(chalk.dim(' Enter empty comment to quit.\n'));
1050
+ let commentsAdded = 0;
1051
+ while (true) {
1052
+ const message = await ask(chalk.cyan('Comment: '));
1053
+ if (!message.trim()) {
1054
+ break;
1055
+ }
1056
+ const searchText = await ask(chalk.cyan('Attach to text: '));
1057
+ // Load document fresh each time
1058
+ const zip = new AdmZip(docxPath);
1059
+ const docEntry = zip.getEntry('word/document.xml');
1060
+ if (!docEntry) {
1061
+ console.error(chalk.red('Invalid Word document'));
1062
+ rl.close();
1063
+ process.exit(1);
1064
+ }
1065
+ let docXml = zip.readAsText(docEntry);
1066
+ // Read or create comments.xml
1067
+ let commentsEntry = zip.getEntry('word/comments.xml');
1068
+ let commentsXml;
1069
+ let nextCommentId = 1;
1070
+ if (commentsEntry) {
1071
+ commentsXml = zip.readAsText(commentsEntry);
1072
+ const idMatches = commentsXml.match(/w:id="(\d+)"/g) || [];
1073
+ for (const m of idMatches) {
1074
+ const id = parseInt(m.match(/\d+/)[0]);
1075
+ if (id >= nextCommentId)
1076
+ nextCommentId = id + 1;
1077
+ }
1078
+ }
1079
+ else {
1080
+ commentsXml = `<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
1081
+ <w:comments xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main">
1082
+ </w:comments>`;
1083
+ }
1084
+ const date = new Date().toISOString();
1085
+ const commentId = nextCommentId;
1086
+ // Add comment to comments.xml
1087
+ const newComment = `<w:comment w:id="${commentId}" w:author="${author}" w:date="${date}">
1088
+ <w:p><w:r><w:t>${message}</w:t></w:r></w:p>
1089
+ </w:comment>`;
1090
+ commentsXml = commentsXml.replace('</w:comments>', `${newComment}\n</w:comments>`);
1091
+ // Find text and add comment markers
1092
+ if (searchText.trim()) {
1093
+ const escapedSearch = searchText.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
1094
+ const textPattern = new RegExp(`(<w:t[^>]*>)([^<]*${escapedSearch}[^<]*)(<\/w:t>)`, 'i');
1095
+ if (textPattern.test(docXml)) {
1096
+ docXml = docXml.replace(textPattern, (_match, start, text, end) => {
1097
+ return `<w:commentRangeStart w:id="${commentId}"/>${start}${text}${end}<w:commentRangeEnd w:id="${commentId}"/><w:r><w:commentReference w:id="${commentId}"/></w:r>`;
1098
+ });
1099
+ console.log(chalk.green(` ✓ Comment added at "${searchText}"`));
1100
+ }
1101
+ else {
1102
+ console.log(chalk.yellow(` Text not found. Comment added without anchor.`));
1103
+ }
1104
+ }
1105
+ else {
1106
+ console.log(chalk.dim(` Comment added without anchor.`));
1107
+ }
1108
+ // Update zip
1109
+ zip.updateFile('word/document.xml', Buffer.from(docXml));
1110
+ if (commentsEntry) {
1111
+ zip.updateFile('word/comments.xml', Buffer.from(commentsXml));
1112
+ }
1113
+ else {
1114
+ zip.addFile('word/comments.xml', Buffer.from(commentsXml));
1115
+ // Update [Content_Types].xml
1116
+ const ctEntry = zip.getEntry('[Content_Types].xml');
1117
+ if (ctEntry) {
1118
+ let ctXml = zip.readAsText(ctEntry);
1119
+ if (!ctXml.includes('comments.xml')) {
1120
+ ctXml = ctXml.replace('</Types>', '<Override PartName="/word/comments.xml" ContentType="application/vnd.openxmlformats-officedocument.wordprocessingml.comments+xml"/>\n</Types>');
1121
+ zip.updateFile('[Content_Types].xml', Buffer.from(ctXml));
1122
+ }
1123
+ }
1124
+ // Update document.xml.rels
1125
+ const relsEntry = zip.getEntry('word/_rels/document.xml.rels');
1126
+ if (relsEntry) {
1127
+ let relsXml = zip.readAsText(relsEntry);
1128
+ if (!relsXml.includes('comments.xml')) {
1129
+ const newRelId = `rId${Date.now()}`;
1130
+ relsXml = relsXml.replace('</Relationships>', `<Relationship Id="${newRelId}" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/comments" Target="comments.xml"/>\n</Relationships>`);
1131
+ zip.updateFile('word/_rels/document.xml.rels', Buffer.from(relsXml));
1132
+ }
1133
+ }
1134
+ }
1135
+ zip.writeZip(docxPath);
1136
+ commentsAdded++;
1137
+ console.log();
1138
+ }
1139
+ rl.close();
1140
+ console.log();
1141
+ if (commentsAdded > 0) {
1142
+ console.log(fmt.status('success', `Added ${commentsAdded} comment(s) to ${docxPath}`));
1143
+ }
1144
+ else {
1145
+ console.log(chalk.dim('No comments added.'));
1146
+ }
1147
+ });
1148
+ // ==========================================================================
1149
+ // CLEAN command - Remove generated files
1150
+ // ==========================================================================
1151
+ program
1152
+ .command('clean')
1153
+ .description('Remove generated files (paper.md, PDFs, DOCXs)')
1154
+ .option('-n, --dry-run', 'Show what would be deleted without deleting')
1155
+ .option('--all', 'Also remove backup and export zips')
1156
+ .action((options) => {
1157
+ let config = {};
1158
+ try {
1159
+ config = loadBuildConfig('.') || {};
1160
+ }
1161
+ catch {
1162
+ // Not in a rev project, that's ok
1163
+ }
1164
+ const projectName = config.title?.toLowerCase().replace(/\s+/g, '-') || 'paper';
1165
+ // Files to clean
1166
+ const patterns = [
1167
+ 'paper.md',
1168
+ '*.pdf',
1169
+ `${projectName}.docx`,
1170
+ `${projectName}.pdf`,
1171
+ `${projectName}.tex`,
1172
+ '.paper-*.md', // Temp build files
1173
+ ];
1174
+ if (options.all) {
1175
+ patterns.push('*.zip', 'backup-*.zip', '*-export.zip');
1176
+ }
1177
+ const toDelete = [];
1178
+ for (const pattern of patterns) {
1179
+ if (pattern.includes('*')) {
1180
+ const regex = new RegExp('^' + pattern.replace(/\./g, '\\.').replace(/\*/g, '.*') + '$');
1181
+ const files = fs.readdirSync('.').filter(f => regex.test(f));
1182
+ toDelete.push(...files);
1183
+ }
1184
+ else if (fs.existsSync(pattern)) {
1185
+ toDelete.push(pattern);
1186
+ }
1187
+ }
1188
+ if (toDelete.length === 0) {
1189
+ console.log(chalk.dim('No generated files to clean.'));
1190
+ return;
1191
+ }
1192
+ console.log(fmt.header('Clean'));
1193
+ console.log();
1194
+ for (const file of toDelete) {
1195
+ if (options.dryRun) {
1196
+ console.log(chalk.dim(` Would delete: ${file}`));
1197
+ }
1198
+ else {
1199
+ fs.unlinkSync(file);
1200
+ console.log(chalk.red(` Deleted: ${file}`));
1201
+ }
1202
+ }
1203
+ console.log();
1204
+ if (options.dryRun) {
1205
+ console.log(chalk.dim(`Would delete ${toDelete.length} file(s). Run without --dry-run to delete.`));
1206
+ }
1207
+ else {
1208
+ console.log(fmt.status('success', `Cleaned ${toDelete.length} file(s)`));
1209
+ }
1210
+ });
1211
+ // ==========================================================================
1212
+ // CHECK command - Pre-submission check
1213
+ // ==========================================================================
1214
+ program
1215
+ .command('check')
1216
+ .description('Run all checks before submission (lint + grammar + citations)')
1217
+ .option('--fix', 'Auto-fix issues where possible')
1218
+ .option('-s, --severity <level>', 'Minimum grammar severity', 'warning')
1219
+ .action(async (options) => {
1220
+ const { validateCitations } = await import('../citations.js');
1221
+ const { checkGrammar, getGrammarSummary } = await import('../grammar.js');
1222
+ console.log(fmt.header('Pre-Submission Check'));
1223
+ console.log();
1224
+ let hasErrors = false;
1225
+ let totalIssues = 0;
1226
+ // 1. Run lint
1227
+ console.log(chalk.cyan.bold('1. Linting...'));
1228
+ let config = {};
1229
+ try {
1230
+ config = loadBuildConfig('.') || {};
1231
+ }
1232
+ catch {
1233
+ // Not in a rev project
1234
+ }
1235
+ let sections = config.sections || [];
1236
+ if (sections.length === 0) {
1237
+ sections = fs.readdirSync('.').filter(f => f.endsWith('.md') && !['README.md', 'CLAUDE.md', 'paper.md'].includes(f));
1238
+ }
1239
+ const lintIssues = [];
1240
+ const lintWarnings = [];
1241
+ for (const file of sections) {
1242
+ if (!fs.existsSync(file))
1243
+ continue;
1244
+ const content = fs.readFileSync(file, 'utf-8');
1245
+ // Check for broken cross-references
1246
+ const refs = content.match(/@(fig|tbl|eq|sec):\w+/g) || [];
1247
+ const anchors = content.match(/\{#(fig|tbl|eq|sec):[^}]+\}/g) || [];
1248
+ const anchorLabels = anchors.map(a => a.match(/#([^}]+)/)[1]);
1249
+ for (const ref of refs) {
1250
+ const label = ref.slice(1);
1251
+ if (!anchorLabels.includes(label)) {
1252
+ lintIssues.push({ file, message: `Broken reference: ${ref}` });
1253
+ }
1254
+ }
1255
+ // Check for unresolved comments
1256
+ const unresolvedComments = (content.match(/\{>>[^<]*<<\}/g) || [])
1257
+ .filter(c => !c.includes('[RESOLVED]'));
1258
+ if (unresolvedComments.length > 0) {
1259
+ lintWarnings.push({ file, message: `${unresolvedComments.length} unresolved comment(s)` });
1260
+ }
1261
+ }
1262
+ if (lintIssues.length > 0) {
1263
+ for (const issue of lintIssues) {
1264
+ console.log(chalk.red(` ✗ ${issue.file}: ${issue.message}`));
1265
+ }
1266
+ hasErrors = true;
1267
+ totalIssues += lintIssues.length;
1268
+ }
1269
+ for (const warning of lintWarnings) {
1270
+ console.log(chalk.yellow(` ⚠ ${warning.file}: ${warning.message}`));
1271
+ totalIssues++;
1272
+ }
1273
+ if (lintIssues.length === 0 && lintWarnings.length === 0) {
1274
+ console.log(chalk.green(' ✓ No lint issues'));
1275
+ }
1276
+ console.log();
1277
+ // 2. Run grammar check
1278
+ console.log(chalk.cyan.bold('2. Grammar check...'));
1279
+ const severityLevels = { error: 3, warning: 2, info: 1 };
1280
+ const minSeverity = severityLevels[options.severity || 'warning'] || 2;
1281
+ let grammarIssues = [];
1282
+ for (const file of sections) {
1283
+ if (!fs.existsSync(file))
1284
+ continue;
1285
+ const text = fs.readFileSync(file, 'utf-8');
1286
+ const issues = checkGrammar(text, { scientific: true });
1287
+ const filtered = issues.filter((i) => severityLevels[i.severity] >= minSeverity);
1288
+ grammarIssues.push(...filtered.map(i => ({ ...i, file })));
1289
+ }
1290
+ const grammarSummary = getGrammarSummary(grammarIssues);
1291
+ if (grammarSummary.errors > 0) {
1292
+ hasErrors = true;
1293
+ }
1294
+ totalIssues += grammarSummary.total;
1295
+ if (grammarSummary.total > 0) {
1296
+ console.log(chalk.yellow(` ⚠ ${grammarSummary.total} grammar issue(s): ${grammarSummary.errors} errors, ${grammarSummary.warnings} warnings`));
1297
+ }
1298
+ else {
1299
+ console.log(chalk.green(' ✓ No grammar issues'));
1300
+ }
1301
+ console.log();
1302
+ // 3. Run citation check
1303
+ console.log(chalk.cyan.bold('3. Citation check...'));
1304
+ const bibFile = config.bibliography || 'references.bib';
1305
+ if (fs.existsSync(bibFile)) {
1306
+ const existingSections = sections.filter(f => fs.existsSync(f));
1307
+ const result = validateCitations(existingSections, bibFile);
1308
+ if (result.missing.length > 0) {
1309
+ console.log(chalk.red(` ✗ ${result.missing.length} missing citation(s): ${result.missing.slice(0, 3).join(', ')}${result.missing.length > 3 ? '...' : ''}`));
1310
+ hasErrors = true;
1311
+ totalIssues += result.missing.length;
1312
+ }
1313
+ if (result.unused.length > 0) {
1314
+ console.log(chalk.yellow(` ⚠ ${result.unused.length} unused citation(s)`));
1315
+ totalIssues += result.unused.length;
1316
+ }
1317
+ if (result.missing.length === 0 && result.unused.length === 0) {
1318
+ console.log(chalk.green(' ✓ All citations valid'));
1319
+ }
1320
+ }
1321
+ else {
1322
+ console.log(chalk.dim(' - No bibliography file found'));
1323
+ }
1324
+ console.log();
1325
+ // Summary
1326
+ console.log(chalk.bold('Summary'));
1327
+ if (hasErrors) {
1328
+ console.log(chalk.red(` ${totalIssues} issue(s) found. Please fix before submission.`));
1329
+ process.exit(1);
1330
+ }
1331
+ else if (totalIssues > 0) {
1332
+ console.log(chalk.yellow(` ${totalIssues} warning(s). Review before submission.`));
1333
+ }
1334
+ else {
1335
+ console.log(chalk.green(' ✓ All checks passed! Ready for submission.'));
1336
+ }
1337
+ });
1338
+ // ==========================================================================
1339
+ // OPEN command - Open project folder or file
1340
+ // ==========================================================================
1341
+ program
1342
+ .command('open')
1343
+ .description('Open project folder or file in default app')
1344
+ .argument('[file]', 'File to open (default: project folder)')
1345
+ .action(async (file, _options) => {
1346
+ const { exec } = await import('child_process');
1347
+ const target = file || '.';
1348
+ if (!fs.existsSync(target)) {
1349
+ console.error(chalk.red(`File not found: ${target}`));
1350
+ process.exit(1);
1351
+ }
1352
+ const platform = process.platform;
1353
+ let command;
1354
+ if (platform === 'darwin') {
1355
+ command = `open "${target}"`;
1356
+ }
1357
+ else if (platform === 'win32') {
1358
+ command = `start "" "${target}"`;
1359
+ }
1360
+ else {
1361
+ command = `xdg-open "${target}"`;
1362
+ }
1363
+ exec(command, (err) => {
1364
+ if (err) {
1365
+ console.error(chalk.red(`Failed to open: ${err.message}`));
1366
+ process.exit(1);
1367
+ }
1368
+ console.log(fmt.status('success', `Opened ${target}`));
1369
+ });
1370
+ });
1371
+ // ==========================================================================
1372
+ // INSTALL-CLI-SKILL command - Install Claude Code skill
1373
+ // ==========================================================================
1374
+ program
1375
+ .command('install-cli-skill')
1376
+ .description('Install docrev skill for Claude Code')
1377
+ .action(() => {
1378
+ const homedir = process.env.HOME || process.env.USERPROFILE;
1379
+ if (!homedir) {
1380
+ console.error(chalk.red('Could not determine home directory'));
1381
+ process.exit(1);
1382
+ }
1383
+ const skillDir = path.join(homedir, '.claude', 'skills', 'docrev');
1384
+ const sourceDir = path.join(import.meta.dirname, '..', '..', 'skill');
1385
+ // Check if source skill files exist
1386
+ const skillFile = path.join(sourceDir, 'SKILL.md');
1387
+ if (!fs.existsSync(skillFile)) {
1388
+ console.error(chalk.red('Skill files not found in package'));
1389
+ process.exit(1);
1390
+ }
1391
+ // Create skill directory
1392
+ fs.mkdirSync(skillDir, { recursive: true });
1393
+ // Copy skill files
1394
+ const files = ['SKILL.md', 'REFERENCE.md'];
1395
+ for (const file of files) {
1396
+ const src = path.join(sourceDir, file);
1397
+ const dest = path.join(skillDir, file);
1398
+ if (fs.existsSync(src)) {
1399
+ fs.copyFileSync(src, dest);
1400
+ }
1401
+ }
1402
+ console.log(fmt.status('success', 'Installed docrev skill for Claude Code'));
1403
+ console.log(chalk.dim(` Location: ${skillDir}`));
1404
+ console.log(chalk.dim(' Restart Claude Code to activate'));
1405
+ });
1406
+ program
1407
+ .command('uninstall-cli-skill')
1408
+ .description('Remove docrev skill from Claude Code')
1409
+ .action(() => {
1410
+ const homedir = process.env.HOME || process.env.USERPROFILE;
1411
+ if (!homedir) {
1412
+ console.error(chalk.red('Could not determine home directory'));
1413
+ process.exit(1);
1414
+ }
1415
+ const skillDir = path.join(homedir, '.claude', 'skills', 'docrev');
1416
+ if (fs.existsSync(skillDir)) {
1417
+ fs.rmSync(skillDir, { recursive: true });
1418
+ console.log(fmt.status('success', 'Removed docrev skill from Claude Code'));
1419
+ }
1420
+ else {
1421
+ console.log(chalk.yellow('Skill not installed'));
1422
+ }
1423
+ });
1424
+ // ==========================================================================
1425
+ // SPELLING command - Spellcheck with global dictionary
1426
+ // ==========================================================================
1427
+ program
1428
+ .command('spelling')
1429
+ .description('Check spelling in markdown files')
1430
+ .argument('[files...]', 'Files to check (default: section files)')
1431
+ .option('--learn <word>', 'Add word to global dictionary')
1432
+ .option('--learn-project <word>', 'Add word to project dictionary')
1433
+ .option('--forget <word>', 'Remove word from global dictionary')
1434
+ .option('--forget-project <word>', 'Remove word from project dictionary')
1435
+ .option('--list', 'List global dictionary words')
1436
+ .option('--list-project', 'List project dictionary words')
1437
+ .option('--list-all', 'List all custom words (global + project)')
1438
+ .option('--british', 'Use British English dictionary')
1439
+ .option('--add-names', 'Add detected names to global dictionary')
1440
+ .action(async (files, options) => {
1441
+ const spelling = await import('../spelling.js');
1442
+ // Handle dictionary management
1443
+ if (options.learn) {
1444
+ const added = spelling.addWord(options.learn, true);
1445
+ if (added) {
1446
+ console.log(fmt.status('success', `Added "${options.learn}" to global dictionary`));
1447
+ }
1448
+ else {
1449
+ console.log(chalk.yellow(`"${options.learn}" already in dictionary`));
1450
+ }
1451
+ return;
1452
+ }
1453
+ if (options.learnProject) {
1454
+ const added = spelling.addWord(options.learnProject, false);
1455
+ if (added) {
1456
+ console.log(fmt.status('success', `Added "${options.learnProject}" to project dictionary`));
1457
+ }
1458
+ else {
1459
+ console.log(chalk.yellow(`"${options.learnProject}" already in dictionary`));
1460
+ }
1461
+ return;
1462
+ }
1463
+ if (options.forget) {
1464
+ const removed = spelling.removeWord(options.forget, true);
1465
+ if (removed) {
1466
+ console.log(fmt.status('success', `Removed "${options.forget}" from global dictionary`));
1467
+ }
1468
+ else {
1469
+ console.log(chalk.yellow(`"${options.forget}" not in dictionary`));
1470
+ }
1471
+ return;
1472
+ }
1473
+ if (options.forgetProject) {
1474
+ const removed = spelling.removeWord(options.forgetProject, false);
1475
+ if (removed) {
1476
+ console.log(fmt.status('success', `Removed "${options.forgetProject}" from project dictionary`));
1477
+ }
1478
+ else {
1479
+ console.log(chalk.yellow(`"${options.forgetProject}" not in dictionary`));
1480
+ }
1481
+ return;
1482
+ }
1483
+ if (options.list) {
1484
+ const words = spelling.listWords(true);
1485
+ console.log(fmt.header('Global Dictionary'));
1486
+ if (words.length === 0) {
1487
+ console.log(chalk.dim(' No custom words'));
1488
+ console.log(chalk.dim(' Use --learn <word> to add words'));
1489
+ }
1490
+ else {
1491
+ for (const word of words) {
1492
+ console.log(` ${word}`);
1493
+ }
1494
+ console.log(chalk.dim(`\n${words.length} word(s)`));
1495
+ }
1496
+ return;
1497
+ }
1498
+ if (options.listProject) {
1499
+ const words = spelling.listWords(false);
1500
+ console.log(fmt.header('Project Dictionary'));
1501
+ if (words.length === 0) {
1502
+ console.log(chalk.dim(' No custom words'));
1503
+ console.log(chalk.dim(' Use --learn-project <word> to add words'));
1504
+ }
1505
+ else {
1506
+ for (const word of words) {
1507
+ console.log(` ${word}`);
1508
+ }
1509
+ console.log(chalk.dim(`\n${words.length} word(s)`));
1510
+ }
1511
+ return;
1512
+ }
1513
+ if (options.listAll) {
1514
+ const globalWords = spelling.listWords(true);
1515
+ const projectWords = spelling.listWords(false);
1516
+ console.log(fmt.header('Global Dictionary'));
1517
+ if (globalWords.length === 0) {
1518
+ console.log(chalk.dim(' No custom words'));
1519
+ }
1520
+ else {
1521
+ for (const word of globalWords) {
1522
+ console.log(` ${word}`);
1523
+ }
1524
+ }
1525
+ console.log(fmt.header('Project Dictionary'));
1526
+ if (projectWords.length === 0) {
1527
+ console.log(chalk.dim(' No custom words'));
1528
+ }
1529
+ else {
1530
+ for (const word of projectWords) {
1531
+ console.log(` ${word}`);
1532
+ }
1533
+ }
1534
+ console.log(chalk.dim(`\nTotal: ${globalWords.length + projectWords.length} word(s)`));
1535
+ return;
1536
+ }
1537
+ // Check spelling in files
1538
+ let filesToCheck = files || [];
1539
+ if (filesToCheck.length === 0) {
1540
+ if (fs.existsSync('rev.yaml')) {
1541
+ try {
1542
+ const config = loadBuildConfig('.');
1543
+ filesToCheck = config?.sections || [];
1544
+ }
1545
+ catch {
1546
+ // Ignore errors
1547
+ }
1548
+ if (filesToCheck.length === 0) {
1549
+ filesToCheck = fs.readdirSync('.')
1550
+ .filter(f => f.endsWith('.md') && !f.startsWith('.'));
1551
+ }
1552
+ }
1553
+ else {
1554
+ filesToCheck = fs.readdirSync('.')
1555
+ .filter(f => f.endsWith('.md') && !f.startsWith('.'));
1556
+ }
1557
+ }
1558
+ if (filesToCheck.length === 0) {
1559
+ console.log(chalk.yellow('No markdown files found'));
1560
+ return;
1561
+ }
1562
+ const lang = options.british ? 'en-gb' : 'en';
1563
+ console.log(fmt.header(`Spelling Check (${options.british ? 'British' : 'US'} English)`));
1564
+ let totalMisspelled = 0;
1565
+ const allNames = new Set();
1566
+ for (const file of filesToCheck) {
1567
+ if (!fs.existsSync(file)) {
1568
+ console.log(chalk.yellow(`File not found: ${file}`));
1569
+ continue;
1570
+ }
1571
+ const result = await spelling.checkFile(file, { projectDir: '.', lang });
1572
+ const { misspelled, possibleNames } = result;
1573
+ // Collect names
1574
+ for (const n of possibleNames) {
1575
+ allNames.add(n.word);
1576
+ }
1577
+ if (misspelled.length > 0) {
1578
+ console.log(chalk.cyan(`\n${file}:`));
1579
+ for (const issue of misspelled) {
1580
+ const suggestions = issue.suggestions.length > 0
1581
+ ? chalk.dim(` → ${issue.suggestions.join(', ')}`)
1582
+ : '';
1583
+ console.log(` ${chalk.yellow(issue.word)} ${chalk.dim(`(line ${issue.line})`)}${suggestions}`);
1584
+ }
1585
+ totalMisspelled += misspelled.length;
1586
+ }
1587
+ }
1588
+ // Show possible names separately
1589
+ if (allNames.size > 0) {
1590
+ const nameList = [...allNames].sort();
1591
+ if (options.addNames) {
1592
+ console.log(fmt.header('Adding Names to Dictionary'));
1593
+ for (const name of nameList) {
1594
+ spelling.addWord(name, true);
1595
+ console.log(chalk.green(` ✓ ${name}`));
1596
+ }
1597
+ console.log(chalk.dim(`\nAdded ${nameList.length} name(s) to global dictionary`));
1598
+ }
1599
+ else {
1600
+ console.log(fmt.header('Possible Names'));
1601
+ console.log(chalk.dim(` ${nameList.join(', ')}`));
1602
+ console.log(chalk.dim(`\n Run with --add-names to add all to dictionary`));
1603
+ }
1604
+ }
1605
+ if (totalMisspelled === 0 && allNames.size === 0) {
1606
+ console.log(fmt.status('success', 'No spelling errors found'));
1607
+ }
1608
+ else {
1609
+ if (totalMisspelled > 0) {
1610
+ console.log(chalk.yellow(`\n${totalMisspelled} spelling error(s)`));
1611
+ }
1612
+ if (allNames.size > 0) {
1613
+ console.log(chalk.blue(`${allNames.size} possible name(s)`));
1614
+ }
1615
+ console.log(chalk.dim('Use --learn <word> to add words to dictionary'));
1616
+ }
1617
+ });
1618
+ // ==========================================================================
1619
+ // UPGRADE command - Self-update via npm
1620
+ // ==========================================================================
1621
+ program
1622
+ .command('upgrade')
1623
+ .description('Check for updates and upgrade docrev')
1624
+ .option('--check', 'Only check for updates, do not install')
1625
+ .action(async (options) => {
1626
+ const { execSync, spawn } = await import('child_process');
1627
+ console.log(chalk.cyan('Checking for updates...'));
1628
+ try {
1629
+ // Get current version
1630
+ const currentVersion = pkg?.version || 'unknown';
1631
+ // Get latest version from npm
1632
+ let latestVersion;
1633
+ try {
1634
+ latestVersion = execSync('npm view docrev version', { encoding: 'utf-8' }).trim();
1635
+ }
1636
+ catch {
1637
+ console.error(chalk.red('Failed to check npm registry'));
1638
+ console.error(chalk.dim('Check your internet connection'));
1639
+ process.exit(1);
1640
+ }
1641
+ if (currentVersion === latestVersion) {
1642
+ console.log(fmt.status('success', `Already on latest version (${currentVersion})`));
1643
+ return;
1644
+ }
1645
+ console.log(` Current: ${chalk.yellow(currentVersion)}`);
1646
+ console.log(` Latest: ${chalk.green(latestVersion)}`);
1647
+ console.log();
1648
+ if (options.check) {
1649
+ console.log(chalk.cyan('Run "rev upgrade" to install the update'));
1650
+ return;
1651
+ }
1652
+ console.log(chalk.cyan('Upgrading...'));
1653
+ // Run npm update
1654
+ const child = spawn('npm', ['install', '-g', 'docrev@latest'], {
1655
+ stdio: 'inherit',
1656
+ shell: true,
1657
+ });
1658
+ child.on('close', (code) => {
1659
+ if (code === 0) {
1660
+ console.log();
1661
+ console.log(fmt.status('success', `Upgraded to ${latestVersion}`));
1662
+ }
1663
+ else {
1664
+ console.error(chalk.red('Upgrade failed'));
1665
+ console.error(chalk.dim('Try running: npm install -g docrev@latest'));
1666
+ process.exit(1);
1667
+ }
1668
+ });
1669
+ child.on('error', (err) => {
1670
+ console.error(chalk.red(`Upgrade failed: ${err.message}`));
1671
+ console.error(chalk.dim('Try running: npm install -g docrev@latest'));
1672
+ process.exit(1);
1673
+ });
1674
+ }
1675
+ catch (err) {
1676
+ console.error(chalk.red(`Error: ${err.message}`));
1677
+ process.exit(1);
1678
+ }
1679
+ });
1680
+ // ==========================================================================
1681
+ // BATCH command - Run operations on multiple documents
1682
+ // ==========================================================================
1683
+ program
1684
+ .command('batch')
1685
+ .description('Run operations on multiple documents')
1686
+ .argument('<command>', 'Command to run (status, strip, resolve)')
1687
+ .argument('[pattern]', 'File pattern (default: *.md)')
1688
+ .option('--parallel', 'Run operations in parallel')
1689
+ .option('--dry-run', 'Preview files without running')
1690
+ .option('-a, --all', 'Include all .md files (not just sections)')
1691
+ .action(async (command, pattern, options) => {
1692
+ const validCommands = ['status', 'strip', 'resolve', 'comments'];
1693
+ if (!validCommands.includes(command)) {
1694
+ console.error(fmt.status('error', `Unknown batch command: ${command}`));
1695
+ console.error(chalk.dim(`Available: ${validCommands.join(', ')}`));
1696
+ process.exit(1);
1697
+ }
1698
+ // Find files
1699
+ let files = [];
1700
+ if (pattern) {
1701
+ if (pattern.includes('*')) {
1702
+ files = fs.readdirSync('.').filter(f => f.endsWith('.md') && !['README.md', 'CLAUDE.md', 'paper.md'].includes(f));
1703
+ }
1704
+ else {
1705
+ files = [pattern];
1706
+ }
1707
+ }
1708
+ else {
1709
+ files = fs.readdirSync('.').filter(f => f.endsWith('.md') &&
1710
+ (options.all || !['README.md', 'CLAUDE.md', 'paper.md'].includes(f)));
1711
+ }
1712
+ if (files.length === 0) {
1713
+ console.error(fmt.status('error', 'No files found'));
1714
+ process.exit(1);
1715
+ }
1716
+ console.log(fmt.header(`Batch ${command} on ${files.length} file(s)`));
1717
+ console.log();
1718
+ if (options.dryRun) {
1719
+ console.log(chalk.dim('Dry run - files that would be processed:'));
1720
+ for (const file of files) {
1721
+ console.log(chalk.dim(` ${file}`));
1722
+ }
1723
+ return;
1724
+ }
1725
+ // Process files
1726
+ const results = [];
1727
+ const progressBar = fmt.progressBar(files.length, 'Processing');
1728
+ progressBar.update(0);
1729
+ for (let i = 0; i < files.length; i++) {
1730
+ const file = files[i];
1731
+ progressBar.update(i + 1);
1732
+ if (!fs.existsSync(file)) {
1733
+ results.push({ file, status: 'not found' });
1734
+ continue;
1735
+ }
1736
+ try {
1737
+ const text = fs.readFileSync(file, 'utf-8');
1738
+ let result = { file, status: 'ok' };
1739
+ switch (command) {
1740
+ case 'status': {
1741
+ const counts = countAnnotations(text);
1742
+ const comments = getComments(text);
1743
+ result.annotations = counts.total;
1744
+ result.comments = comments.length;
1745
+ result.pending = comments.filter(c => !c.resolved).length;
1746
+ break;
1747
+ }
1748
+ case 'comments': {
1749
+ const comments = getComments(text);
1750
+ result.total = comments.length;
1751
+ result.pending = comments.filter(c => !c.resolved).length;
1752
+ result.resolved = comments.filter(c => c.resolved).length;
1753
+ break;
1754
+ }
1755
+ case 'resolve': {
1756
+ const comments = getComments(text);
1757
+ const pending = comments.filter(c => !c.resolved);
1758
+ if (pending.length > 0) {
1759
+ let newText = text;
1760
+ for (const c of pending) {
1761
+ newText = setCommentStatus(newText, c, true);
1762
+ }
1763
+ fs.writeFileSync(file, newText, 'utf-8');
1764
+ result.resolved = pending.length;
1765
+ }
1766
+ else {
1767
+ result.resolved = 0;
1768
+ }
1769
+ break;
1770
+ }
1771
+ case 'strip': {
1772
+ const clean = stripAnnotations(text, { keepComments: false });
1773
+ const hasChanges = clean !== text;
1774
+ if (hasChanges) {
1775
+ fs.writeFileSync(file, clean, 'utf-8');
1776
+ result.stripped = true;
1777
+ }
1778
+ else {
1779
+ result.stripped = false;
1780
+ }
1781
+ break;
1782
+ }
1783
+ }
1784
+ results.push(result);
1785
+ }
1786
+ catch (err) {
1787
+ results.push({ file, status: 'error', error: err.message });
1788
+ }
1789
+ }
1790
+ progressBar.done();
1791
+ console.log();
1792
+ // Show results
1793
+ console.log(fmt.header('Results'));
1794
+ console.log();
1795
+ for (const r of results) {
1796
+ const statusIcon = r.status === 'ok'
1797
+ ? chalk.green('✓')
1798
+ : r.status === 'error'
1799
+ ? chalk.red('✗')
1800
+ : chalk.yellow('?');
1801
+ let details = '';
1802
+ switch (command) {
1803
+ case 'status':
1804
+ details = chalk.dim(`${r.annotations || 0} annotations, ${r.pending || 0} pending comments`);
1805
+ break;
1806
+ case 'comments':
1807
+ details = chalk.dim(`${r.total || 0} total, ${r.pending || 0} pending`);
1808
+ break;
1809
+ case 'resolve':
1810
+ details = r.resolved && r.resolved > 0
1811
+ ? chalk.green(`${r.resolved} resolved`)
1812
+ : chalk.dim('no pending');
1813
+ break;
1814
+ case 'strip':
1815
+ details = r.stripped
1816
+ ? chalk.green('cleaned')
1817
+ : chalk.dim('no changes');
1818
+ break;
1819
+ }
1820
+ console.log(` ${statusIcon} ${r.file} ${details}`);
1821
+ if (r.error) {
1822
+ console.log(chalk.red(` ${r.error}`));
1823
+ }
1824
+ }
1825
+ // Summary
1826
+ console.log();
1827
+ const successful = results.filter(r => r.status === 'ok').length;
1828
+ const failed = results.filter(r => r.status === 'error').length;
1829
+ console.log(chalk.dim(`${successful} succeeded, ${failed} failed`));
1830
+ });
1831
+ }
1832
+ // Helper functions for help text
1833
+ function showFullHelp(pkg) {
1834
+ console.log(`
1835
+ ${chalk.bold.cyan('rev')} ${chalk.dim(`v${pkg?.version || 'unknown'}`)} - Revision workflow for Word ↔ Markdown round-trips
1836
+
1837
+ ${chalk.bold('DESCRIPTION')}
1838
+ Handle reviewer feedback when collaborating on academic papers.
1839
+ Import changes from Word, review them interactively, and preserve
1840
+ comments for discussion with Claude.
1841
+
1842
+ ${chalk.bold('GLOBAL OPTIONS')}
1843
+
1844
+ ${chalk.bold('--no-color')} Disable colored output
1845
+ ${chalk.bold('-q, --quiet')} Suppress non-essential output
1846
+ ${chalk.bold('--json')} Output in JSON format (for scripting)
1847
+
1848
+ ${chalk.bold('TYPICAL WORKFLOW')}
1849
+
1850
+ ${chalk.dim('1.')} Build and send: ${chalk.green('rev build docx')} ${chalk.dim('(or rev b docx)')}
1851
+ ${chalk.dim('2.')} Reviewers return ${chalk.yellow('reviewed.docx')} with edits and comments
1852
+ ${chalk.dim('3.')} Sync their feedback: ${chalk.green('rev sync reviewed.docx')}
1853
+ ${chalk.dim('4.')} Work through comments: ${chalk.green('rev next')} ${chalk.dim('(n)')} / ${chalk.green('rev todo')} ${chalk.dim('(t)')}
1854
+ ${chalk.dim('5.')} Accept/reject changes: ${chalk.green('rev accept -a')} ${chalk.dim('(a)')} or ${chalk.green('rev review')}
1855
+ ${chalk.dim('6.')} Rebuild: ${chalk.green('rev build docx')}
1856
+ ${chalk.dim('7.')} Archive old files: ${chalk.green('rev archive')}
1857
+
1858
+ ${chalk.bold('MORE HELP')}
1859
+
1860
+ rev help workflow Detailed workflow guide
1861
+ rev help syntax Annotation syntax reference
1862
+ rev help commands All commands with options
1863
+ `);
1864
+ }
1865
+ function showWorkflowHelp() {
1866
+ console.log(`
1867
+ ${chalk.bold.cyan('rev')} ${chalk.dim('- Workflow Guide')}
1868
+
1869
+ ${chalk.bold('OVERVIEW')}
1870
+
1871
+ The rev workflow solves a common problem: you write in Markdown,
1872
+ but collaborators review in Word. When they return edited documents,
1873
+ you need to merge their changes back into your source files.
1874
+
1875
+ ${chalk.bold('STEP 1: BUILD & SEND')}
1876
+
1877
+ ${chalk.green('rev build docx')}
1878
+ ${chalk.dim('# Send the .docx to reviewers')}
1879
+
1880
+ ${chalk.bold('STEP 2: RECEIVE FEEDBACK')}
1881
+
1882
+ Reviewers edit the document, adding:
1883
+ ${chalk.dim('•')} Track changes (insertions, deletions)
1884
+ ${chalk.dim('•')} Comments (questions, suggestions)
1885
+
1886
+ ${chalk.bold('STEP 3: SYNC CHANGES')}
1887
+
1888
+ ${chalk.green('rev sync reviewed.docx')}
1889
+ ${chalk.dim('# Or just: rev sync (auto-detects most recent .docx)')}
1890
+
1891
+ Your markdown files now contain their feedback as annotations.
1892
+
1893
+ ${chalk.bold('STEP 4: WORK THROUGH COMMENTS')}
1894
+
1895
+ ${chalk.green('rev todo')} ${chalk.dim('# See all pending comments')}
1896
+ ${chalk.green('rev next')} ${chalk.dim('# Show next pending comment')}
1897
+ ${chalk.green('rev reply file.md -n 1 -m "Done"')}
1898
+ ${chalk.green('rev resolve file.md -n 1')}
1899
+
1900
+ ${chalk.bold('STEP 5: ACCEPT/REJECT CHANGES')}
1901
+
1902
+ ${chalk.green('rev accept file.md -a')} ${chalk.dim('# Accept all changes')}
1903
+ ${chalk.green('rev reject file.md -n 2')} ${chalk.dim('# Reject specific change')}
1904
+ ${chalk.dim('# Or use interactive mode:')}
1905
+ ${chalk.green('rev review file.md')}
1906
+
1907
+ ${chalk.bold('STEP 6: REBUILD')}
1908
+
1909
+ ${chalk.green('rev build docx')}
1910
+ ${chalk.green('rev build docx --dual')} ${chalk.dim('# Clean + comments version')}
1911
+
1912
+ ${chalk.bold('STEP 7: ARCHIVE & REPEAT')}
1913
+
1914
+ ${chalk.green('rev archive')} ${chalk.dim('# Move reviewer files to archive/')}
1915
+ ${chalk.dim('# Send new .docx, repeat cycle')}
1916
+ `);
1917
+ }
1918
+ function showSyntaxHelp() {
1919
+ console.log(`
1920
+ ${chalk.bold.cyan('rev')} ${chalk.dim('- Annotation Syntax (CriticMarkup)')}
1921
+
1922
+ ${chalk.bold('INSERTIONS')}
1923
+
1924
+ Syntax: ${chalk.green('{++inserted text++}')}
1925
+ Meaning: This text was added by the reviewer
1926
+
1927
+ Example:
1928
+ We ${chalk.green('{++specifically++}')} focused on neophytes.
1929
+ → Reviewer added the word "specifically"
1930
+
1931
+ ${chalk.bold('DELETIONS')}
1932
+
1933
+ Syntax: ${chalk.red('{--deleted text--}')}
1934
+ Meaning: This text was removed by the reviewer
1935
+
1936
+ Example:
1937
+ We focused on ${chalk.red('{--recent--}')} neophytes.
1938
+ → Reviewer removed the word "recent"
1939
+
1940
+ ${chalk.bold('SUBSTITUTIONS')}
1941
+
1942
+ Syntax: ${chalk.yellow('{~~old text~>new text~~}')}
1943
+ Meaning: Text was changed from old to new
1944
+
1945
+ Example:
1946
+ The effect was ${chalk.yellow('{~~significant~>substantial~~}')}.
1947
+ → Reviewer changed "significant" to "substantial"
1948
+
1949
+ ${chalk.bold('COMMENTS')}
1950
+
1951
+ Syntax: ${chalk.blue('{>>Author: comment text<<}')}
1952
+ Meaning: Reviewer left a comment at this location
1953
+
1954
+ Example:
1955
+ The results were significant. ${chalk.blue('{>>Dr. Smith: Add p-value<<}')}
1956
+ → Dr. Smith commented asking for a p-value
1957
+
1958
+ Comments are placed ${chalk.bold('after')} the text they reference.
1959
+ `);
1960
+ }
1961
+ function showCommandsHelp() {
1962
+ console.log(`
1963
+ ${chalk.bold.cyan('rev')} ${chalk.dim('- Command Reference')}
1964
+
1965
+ ${chalk.bold('rev import')} <docx> <original-md>
1966
+
1967
+ Import changes from a Word document by comparing against your
1968
+ original Markdown source.
1969
+
1970
+ ${chalk.bold('Arguments:')}
1971
+ docx Word document from reviewer
1972
+ original-md Your original Markdown file
1973
+
1974
+ ${chalk.bold('Options:')}
1975
+ -o, --output <file> Write to different file (default: overwrites original)
1976
+ -a, --author <name> Author name for changes (default: "Reviewer")
1977
+ --dry-run Preview changes without saving
1978
+
1979
+ ${chalk.bold('rev review')} <file>
1980
+
1981
+ Interactively review and accept/reject track changes.
1982
+ Comments are preserved; only track changes are processed.
1983
+
1984
+ ${chalk.bold('Keys:')}
1985
+ a Accept this change
1986
+ r Reject this change
1987
+ s Skip (decide later)
1988
+ A Accept all remaining changes
1989
+ L Reject all remaining changes
1990
+ q Quit without saving
1991
+
1992
+ ${chalk.bold('rev strip')} <file>
1993
+
1994
+ Remove annotations, outputting clean Markdown.
1995
+ Track changes are applied (insertions kept, deletions removed).
1996
+
1997
+ ${chalk.bold('Options:')}
1998
+ -o, --output <file> Write to file (default: stdout)
1999
+ -c, --keep-comments Keep comment annotations
2000
+
2001
+ ${chalk.bold('rev help')} [topic]
2002
+
2003
+ Show help. Optional topics:
2004
+ workflow Step-by-step workflow guide
2005
+ syntax Annotation syntax reference
2006
+ commands This command reference
2007
+ `);
2008
+ }
2009
+ //# sourceMappingURL=utilities.js.map