docrev 0.10.1 → 0.10.2

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 (119) hide show
  1. package/.gitattributes +1 -1
  2. package/CHANGELOG.md +184 -173
  3. package/PLAN-tables-and-postprocess.md +850 -850
  4. package/README.md +431 -431
  5. package/bin/rev.js +11 -11
  6. package/bin/rev.ts +145 -145
  7. package/completions/rev.bash +127 -127
  8. package/completions/rev.ps1 +210 -210
  9. package/completions/rev.zsh +207 -207
  10. package/dist/lib/anchor-match.d.ts +1 -1
  11. package/dist/lib/anchor-match.d.ts.map +1 -1
  12. package/dist/lib/anchor-match.js +47 -17
  13. package/dist/lib/anchor-match.js.map +1 -1
  14. package/dist/lib/build.js +4 -4
  15. package/dist/lib/commands/sync.d.ts.map +1 -1
  16. package/dist/lib/commands/sync.js +78 -100
  17. package/dist/lib/commands/sync.js.map +1 -1
  18. package/dist/lib/commands/utilities.js +164 -164
  19. package/dist/lib/commands/word-tools.js +8 -8
  20. package/dist/lib/grammar.js +3 -3
  21. package/dist/lib/macro-filter.lua +201 -201
  22. package/dist/lib/pdf-comments.js +44 -44
  23. package/dist/lib/plugins.js +57 -57
  24. package/dist/lib/pptx-color-filter.lua +37 -37
  25. package/dist/lib/pptx-themes.js +115 -115
  26. package/dist/lib/sections.d.ts.map +1 -1
  27. package/dist/lib/sections.js +5 -2
  28. package/dist/lib/sections.js.map +1 -1
  29. package/dist/lib/spelling.js +2 -2
  30. package/dist/lib/templates.js +387 -387
  31. package/dist/lib/themes.js +51 -51
  32. package/eslint.config.js +27 -27
  33. package/issues.md +180 -0
  34. package/lib/anchor-match.ts +308 -276
  35. package/lib/annotations.ts +644 -644
  36. package/lib/build.ts +1766 -1766
  37. package/lib/citations.ts +160 -160
  38. package/lib/commands/build.ts +855 -855
  39. package/lib/commands/citations.ts +515 -515
  40. package/lib/commands/comments.ts +1050 -1050
  41. package/lib/commands/context.ts +176 -176
  42. package/lib/commands/core.ts +309 -309
  43. package/lib/commands/doi.ts +435 -435
  44. package/lib/commands/file-ops.ts +372 -372
  45. package/lib/commands/history.ts +320 -320
  46. package/lib/commands/index.ts +87 -87
  47. package/lib/commands/init.ts +259 -259
  48. package/lib/commands/merge-resolve.ts +378 -378
  49. package/lib/commands/preview.ts +178 -178
  50. package/lib/commands/project-info.ts +244 -244
  51. package/lib/commands/quality.ts +517 -517
  52. package/lib/commands/response.ts +454 -454
  53. package/lib/commands/section-boundaries.ts +82 -82
  54. package/lib/commands/sections.ts +451 -451
  55. package/lib/commands/sync.ts +676 -709
  56. package/lib/commands/text-ops.ts +449 -449
  57. package/lib/commands/utilities.ts +448 -448
  58. package/lib/commands/verify-anchors.ts +272 -272
  59. package/lib/commands/word-tools.ts +340 -340
  60. package/lib/comment-realign.ts +517 -517
  61. package/lib/config.ts +84 -84
  62. package/lib/crossref.ts +781 -781
  63. package/lib/csl.ts +191 -191
  64. package/lib/dependencies.ts +98 -98
  65. package/lib/diff-engine.ts +465 -465
  66. package/lib/doi-cache.ts +115 -115
  67. package/lib/doi.ts +897 -897
  68. package/lib/equations.ts +506 -506
  69. package/lib/errors.ts +346 -346
  70. package/lib/format.ts +541 -541
  71. package/lib/git.ts +326 -326
  72. package/lib/grammar.ts +303 -303
  73. package/lib/image-registry.ts +180 -180
  74. package/lib/import.ts +911 -911
  75. package/lib/journals.ts +543 -543
  76. package/lib/macro-filter.lua +201 -201
  77. package/lib/macros.ts +273 -273
  78. package/lib/merge.ts +633 -633
  79. package/lib/orcid.ts +144 -144
  80. package/lib/pdf-comments.ts +263 -263
  81. package/lib/pdf-import.ts +524 -524
  82. package/lib/plugins.ts +362 -362
  83. package/lib/postprocess.ts +188 -188
  84. package/lib/pptx-color-filter.lua +37 -37
  85. package/lib/pptx-template.ts +469 -469
  86. package/lib/pptx-themes.ts +483 -483
  87. package/lib/protect-restore.ts +520 -520
  88. package/lib/rate-limiter.ts +94 -94
  89. package/lib/response.ts +197 -197
  90. package/lib/restore-references.ts +240 -240
  91. package/lib/review.ts +327 -327
  92. package/lib/schema.ts +488 -488
  93. package/lib/scientific-words.ts +73 -73
  94. package/lib/sections.ts +428 -425
  95. package/lib/slides.ts +756 -756
  96. package/lib/spelling.ts +334 -334
  97. package/lib/templates.ts +526 -526
  98. package/lib/themes.ts +742 -742
  99. package/lib/trackchanges.ts +247 -247
  100. package/lib/tui.ts +450 -450
  101. package/lib/types.ts +550 -550
  102. package/lib/undo.ts +250 -250
  103. package/lib/utils.ts +69 -69
  104. package/lib/variables.ts +179 -179
  105. package/lib/word-extraction.ts +806 -806
  106. package/lib/word.ts +643 -643
  107. package/lib/wordcomments.ts +840 -840
  108. package/package.json +137 -137
  109. package/scripts/postbuild.js +47 -47
  110. package/site/assets/extra.css +208 -0
  111. package/site/commands.html +926 -0
  112. package/site/configuration.html +469 -0
  113. package/site/index.html +288 -0
  114. package/site/troubleshooting.html +461 -0
  115. package/site/workflow.html +518 -0
  116. package/skill/REFERENCE.md +539 -539
  117. package/skill/SKILL.md +295 -295
  118. package/tsconfig.json +26 -26
  119. package/types/index.d.ts +525 -525
package/lib/macros.ts CHANGED
@@ -1,273 +1,273 @@
1
- /**
2
- * Placeholder/highlight macros for docrev.
3
- *
4
- * Users write `\tofill{X}` (or any custom macro they declare) in markdown
5
- * source and the build pipeline expands it per output format:
6
- *
7
- * - docx: raw OpenXML run with explicit color + bold (Span+style is NOT
8
- * honored by pandoc's docx writer, so we emit raw <w:r> nodes).
9
- * - pdf / tex / beamer: a `\providecommand` is injected via header-includes,
10
- * so the LaTeX command works directly. `\providecommand` means the user
11
- * can still override with `\renewcommand` in their own preamble.
12
- * - html: raw HTML span with inline style.
13
- * - everything else (markdown, gfm, etc.): bold [X] fallback. Never silently
14
- * dropped.
15
- *
16
- * The mechanism is generic: `\tofill` is the first built-in. Users can add
17
- * their own macros under `macros:` in rev.yaml, and override the built-in by
18
- * declaring a macro with the same name.
19
- */
20
-
21
- import * as fs from 'fs';
22
- import * as path from 'path';
23
- import { fileURLToPath } from 'url';
24
-
25
- // =============================================================================
26
- // Types
27
- // =============================================================================
28
-
29
- /**
30
- * Per-format rendering rules for a macro.
31
- *
32
- * Fields are independent — set any subset. Unset fields fall back to defaults
33
- * (no color, no bold, no italic, bracket wrap on, etc.).
34
- */
35
- export interface MacroFormatStyle {
36
- /** Hex color without '#' (e.g. "C2410C"). */
37
- color?: string;
38
- /** Wrap the rendered content in bold. */
39
- bold?: boolean;
40
- /** Wrap the rendered content in italic. */
41
- italic?: boolean;
42
- /** Wrap the content in [...] brackets. Default: true. */
43
- bracket?: boolean;
44
- /** Optional literal prefix string inside the brackets (e.g. "NOTE: "). */
45
- prefix?: string;
46
- /** Optional literal suffix string inside the brackets. */
47
- suffix?: string;
48
- }
49
-
50
- /**
51
- * Macro definition. `name` is the LaTeX command name without the leading
52
- * backslash (e.g. "tofill" → \tofill{...}). `formats` holds per-format rules;
53
- * a missing format key inherits from `default`.
54
- */
55
- export interface MacroDef {
56
- name: string;
57
- /** Default rendering rules; used when a format-specific override is absent. */
58
- default?: MacroFormatStyle;
59
- /** Per-format overrides, keyed by pandoc format (docx, pdf, html, ...). */
60
- formats?: Record<string, MacroFormatStyle>;
61
- }
62
-
63
- /**
64
- * Built-in macros shipped with docrev. The first entry is the original use
65
- * case: \tofill{X} → bold orange [X] placeholder.
66
- */
67
- export const BUILTIN_MACROS: MacroDef[] = [
68
- {
69
- name: 'tofill',
70
- default: { color: 'C2410C', bold: true, bracket: true },
71
- },
72
- ];
73
-
74
- // =============================================================================
75
- // Validation
76
- // =============================================================================
77
-
78
- const MACRO_NAME_RE = /^[A-Za-z][A-Za-z0-9]*$/;
79
- const HEX_COLOR_RE = /^[0-9A-Fa-f]{6}$/;
80
-
81
- /**
82
- * Validate a user-declared macro entry. Returns a list of error strings;
83
- * empty means the macro is valid.
84
- */
85
- export function validateMacro(macro: unknown): string[] {
86
- const errors: string[] = [];
87
-
88
- if (!macro || typeof macro !== 'object' || Array.isArray(macro)) {
89
- return ['macro must be an object'];
90
- }
91
- const m = macro as Partial<MacroDef>;
92
-
93
- if (!m.name || typeof m.name !== 'string') {
94
- errors.push('macro.name is required');
95
- } else if (!MACRO_NAME_RE.test(m.name)) {
96
- errors.push(`macro.name "${m.name}" must match [A-Za-z][A-Za-z0-9]*`);
97
- }
98
-
99
- const checkStyle = (style: unknown, key: string): void => {
100
- if (style === undefined) return;
101
- if (!style || typeof style !== 'object' || Array.isArray(style)) {
102
- errors.push(`${key} must be an object`);
103
- return;
104
- }
105
- const s = style as MacroFormatStyle;
106
- if (s.color !== undefined && (typeof s.color !== 'string' || !HEX_COLOR_RE.test(s.color))) {
107
- errors.push(`${key}.color must be a 6-digit hex string without '#' (got "${s.color}")`);
108
- }
109
- for (const flag of ['bold', 'italic', 'bracket'] as const) {
110
- if (s[flag] !== undefined && typeof s[flag] !== 'boolean') {
111
- errors.push(`${key}.${flag} must be a boolean`);
112
- }
113
- }
114
- for (const text of ['prefix', 'suffix'] as const) {
115
- if (s[text] !== undefined && typeof s[text] !== 'string') {
116
- errors.push(`${key}.${text} must be a string`);
117
- }
118
- }
119
- };
120
-
121
- checkStyle(m.default, 'macro.default');
122
- if (m.formats !== undefined) {
123
- if (!m.formats || typeof m.formats !== 'object' || Array.isArray(m.formats)) {
124
- errors.push('macro.formats must be an object keyed by format name');
125
- } else {
126
- for (const [fmt, style] of Object.entries(m.formats)) {
127
- checkStyle(style, `macro.formats.${fmt}`);
128
- }
129
- }
130
- }
131
-
132
- return errors;
133
- }
134
-
135
- // =============================================================================
136
- // Merge
137
- // =============================================================================
138
-
139
- /**
140
- * Merge built-in macros with user-declared macros. User entries override
141
- * built-ins by `name` (case-sensitive). Invalid entries are dropped with a
142
- * console warning so a malformed user macro never silently disables the
143
- * built-in.
144
- */
145
- export function mergeMacros(userMacros: unknown): MacroDef[] {
146
- const builtins = new Map<string, MacroDef>();
147
- for (const m of BUILTIN_MACROS) builtins.set(m.name, m);
148
-
149
- if (!userMacros) return [...builtins.values()];
150
- if (!Array.isArray(userMacros)) {
151
- console.warn('macros: rev.yaml `macros` must be a list; ignoring');
152
- return [...builtins.values()];
153
- }
154
-
155
- for (const raw of userMacros) {
156
- const errors = validateMacro(raw);
157
- if (errors.length > 0) {
158
- console.warn(`macros: skipping invalid macro: ${errors.join('; ')}`);
159
- continue;
160
- }
161
- const def = raw as MacroDef;
162
- builtins.set(def.name, def);
163
- }
164
-
165
- return [...builtins.values()];
166
- }
167
-
168
- // =============================================================================
169
- // LaTeX preamble generation (PDF / tex / beamer)
170
- // =============================================================================
171
-
172
- /**
173
- * Build the LaTeX color spec for a style. Returns the wrapping LaTeX with a
174
- * `#1` placeholder where the argument lands.
175
- */
176
- function latexCommandBody(style: MacroFormatStyle): string {
177
- const prefix = style.prefix ? escapeLatex(style.prefix) : '';
178
- const suffix = style.suffix ? escapeLatex(style.suffix) : '';
179
- const inner = `${prefix}#1${suffix}`;
180
- const bracketed = style.bracket === false ? inner : `[${inner}]`;
181
-
182
- let body = bracketed;
183
- if (style.italic) body = `\\textit{${body}}`;
184
- if (style.bold) body = `\\textbf{${body}}`;
185
- if (style.color) body = `\\textcolor[HTML]{${style.color.toUpperCase()}}{${body}}`;
186
- return body;
187
- }
188
-
189
- /**
190
- * Generate `\providecommand` definitions for all macros. `\providecommand`
191
- * means user-supplied `\renewcommand` (in a custom header-includes file) still
192
- * wins, preserving backwards compat with existing projects.
193
- *
194
- * Returns an empty string when the macro list is empty.
195
- */
196
- export function generateLatexPreamble(macros: MacroDef[]): string {
197
- const lines: string[] = ['% docrev: placeholder macros'];
198
- // \textcolor in [HTML]{...} requires xcolor with the [HTML] option.
199
- lines.push('\\PassOptionsToPackage{HTML}{xcolor}');
200
- // Some templates already load xcolor; \usepackage tolerates duplicates with
201
- // the same options.
202
- lines.push('\\usepackage[HTML]{xcolor}');
203
-
204
- for (const m of macros) {
205
- const style = pickStyle(m, 'latex');
206
- const body = latexCommandBody(style);
207
- lines.push(`\\providecommand{\\${m.name}}[1]{${body}}`);
208
- }
209
-
210
- return lines.join('\n');
211
- }
212
-
213
- function escapeLatex(s: string): string {
214
- // Conservative escape — these are user-authored short literals (prefix/suffix).
215
- return s
216
- .replace(/\\/g, '\\textbackslash{}')
217
- .replace(/([&%$#_{}])/g, '\\$1')
218
- .replace(/~/g, '\\textasciitilde{}')
219
- .replace(/\^/g, '\\textasciicircum{}');
220
- }
221
-
222
- // =============================================================================
223
- // Style resolution per format
224
- // =============================================================================
225
-
226
- /**
227
- * Resolve the effective style for a macro in a given pandoc format. Per-format
228
- * override wins over the macro's default; both can be partial — fields are
229
- * not merged across `default` and `formats[fmt]` (the format-specific entry
230
- * replaces `default` entirely when present), keeping rev.yaml semantics
231
- * predictable.
232
- *
233
- * Falls back to `default` when no `formats[fmt]` exists, and to an empty
234
- * style ({}) when neither is set.
235
- */
236
- export function pickStyle(macro: MacroDef, format: string): MacroFormatStyle {
237
- const fmt = macro.formats?.[format];
238
- if (fmt) return fmt;
239
- return macro.default ?? {};
240
- }
241
-
242
- // =============================================================================
243
- // Lua filter sidecar
244
- // =============================================================================
245
-
246
- /**
247
- * Serialize the macro list to a compact JSON sidecar consumed by the lua
248
- * filter at build time. The lua filter reads this file at startup and uses it
249
- * to expand `\tofill{X}` (or any other declared macro) per FORMAT.
250
- *
251
- * Returns the absolute path to the written sidecar.
252
- */
253
- export function writeMacrosSidecar(directory: string, macros: MacroDef[]): string {
254
- const sidecarPath = path.join(directory, '.macros.json');
255
- fs.writeFileSync(sidecarPath, JSON.stringify({ macros }), 'utf-8');
256
- return sidecarPath;
257
- }
258
-
259
- /**
260
- * Resolve the absolute path to the bundled lua filter. Works both from source
261
- * (`lib/macro-filter.lua`) and from the compiled package (`dist/lib/...`)
262
- * because the postbuild script copies .lua files alongside the .js output.
263
- */
264
- export function getMacroFilterPath(): string {
265
- // import.meta.url points to the running file: lib/macros.ts in source,
266
- // dist/lib/macros.js when published. The filter sits next to it.
267
- //
268
- // Use fileURLToPath so paths with spaces (Windows: "C:\Users\Gilles Colling\…")
269
- // resolve correctly. The naive `new URL(...).pathname` returns URL-encoded
270
- // `%20` segments and fs.existsSync silently fails.
271
- const here = path.dirname(fileURLToPath(import.meta.url));
272
- return path.join(here, 'macro-filter.lua');
273
- }
1
+ /**
2
+ * Placeholder/highlight macros for docrev.
3
+ *
4
+ * Users write `\tofill{X}` (or any custom macro they declare) in markdown
5
+ * source and the build pipeline expands it per output format:
6
+ *
7
+ * - docx: raw OpenXML run with explicit color + bold (Span+style is NOT
8
+ * honored by pandoc's docx writer, so we emit raw <w:r> nodes).
9
+ * - pdf / tex / beamer: a `\providecommand` is injected via header-includes,
10
+ * so the LaTeX command works directly. `\providecommand` means the user
11
+ * can still override with `\renewcommand` in their own preamble.
12
+ * - html: raw HTML span with inline style.
13
+ * - everything else (markdown, gfm, etc.): bold [X] fallback. Never silently
14
+ * dropped.
15
+ *
16
+ * The mechanism is generic: `\tofill` is the first built-in. Users can add
17
+ * their own macros under `macros:` in rev.yaml, and override the built-in by
18
+ * declaring a macro with the same name.
19
+ */
20
+
21
+ import * as fs from 'fs';
22
+ import * as path from 'path';
23
+ import { fileURLToPath } from 'url';
24
+
25
+ // =============================================================================
26
+ // Types
27
+ // =============================================================================
28
+
29
+ /**
30
+ * Per-format rendering rules for a macro.
31
+ *
32
+ * Fields are independent — set any subset. Unset fields fall back to defaults
33
+ * (no color, no bold, no italic, bracket wrap on, etc.).
34
+ */
35
+ export interface MacroFormatStyle {
36
+ /** Hex color without '#' (e.g. "C2410C"). */
37
+ color?: string;
38
+ /** Wrap the rendered content in bold. */
39
+ bold?: boolean;
40
+ /** Wrap the rendered content in italic. */
41
+ italic?: boolean;
42
+ /** Wrap the content in [...] brackets. Default: true. */
43
+ bracket?: boolean;
44
+ /** Optional literal prefix string inside the brackets (e.g. "NOTE: "). */
45
+ prefix?: string;
46
+ /** Optional literal suffix string inside the brackets. */
47
+ suffix?: string;
48
+ }
49
+
50
+ /**
51
+ * Macro definition. `name` is the LaTeX command name without the leading
52
+ * backslash (e.g. "tofill" → \tofill{...}). `formats` holds per-format rules;
53
+ * a missing format key inherits from `default`.
54
+ */
55
+ export interface MacroDef {
56
+ name: string;
57
+ /** Default rendering rules; used when a format-specific override is absent. */
58
+ default?: MacroFormatStyle;
59
+ /** Per-format overrides, keyed by pandoc format (docx, pdf, html, ...). */
60
+ formats?: Record<string, MacroFormatStyle>;
61
+ }
62
+
63
+ /**
64
+ * Built-in macros shipped with docrev. The first entry is the original use
65
+ * case: \tofill{X} → bold orange [X] placeholder.
66
+ */
67
+ export const BUILTIN_MACROS: MacroDef[] = [
68
+ {
69
+ name: 'tofill',
70
+ default: { color: 'C2410C', bold: true, bracket: true },
71
+ },
72
+ ];
73
+
74
+ // =============================================================================
75
+ // Validation
76
+ // =============================================================================
77
+
78
+ const MACRO_NAME_RE = /^[A-Za-z][A-Za-z0-9]*$/;
79
+ const HEX_COLOR_RE = /^[0-9A-Fa-f]{6}$/;
80
+
81
+ /**
82
+ * Validate a user-declared macro entry. Returns a list of error strings;
83
+ * empty means the macro is valid.
84
+ */
85
+ export function validateMacro(macro: unknown): string[] {
86
+ const errors: string[] = [];
87
+
88
+ if (!macro || typeof macro !== 'object' || Array.isArray(macro)) {
89
+ return ['macro must be an object'];
90
+ }
91
+ const m = macro as Partial<MacroDef>;
92
+
93
+ if (!m.name || typeof m.name !== 'string') {
94
+ errors.push('macro.name is required');
95
+ } else if (!MACRO_NAME_RE.test(m.name)) {
96
+ errors.push(`macro.name "${m.name}" must match [A-Za-z][A-Za-z0-9]*`);
97
+ }
98
+
99
+ const checkStyle = (style: unknown, key: string): void => {
100
+ if (style === undefined) return;
101
+ if (!style || typeof style !== 'object' || Array.isArray(style)) {
102
+ errors.push(`${key} must be an object`);
103
+ return;
104
+ }
105
+ const s = style as MacroFormatStyle;
106
+ if (s.color !== undefined && (typeof s.color !== 'string' || !HEX_COLOR_RE.test(s.color))) {
107
+ errors.push(`${key}.color must be a 6-digit hex string without '#' (got "${s.color}")`);
108
+ }
109
+ for (const flag of ['bold', 'italic', 'bracket'] as const) {
110
+ if (s[flag] !== undefined && typeof s[flag] !== 'boolean') {
111
+ errors.push(`${key}.${flag} must be a boolean`);
112
+ }
113
+ }
114
+ for (const text of ['prefix', 'suffix'] as const) {
115
+ if (s[text] !== undefined && typeof s[text] !== 'string') {
116
+ errors.push(`${key}.${text} must be a string`);
117
+ }
118
+ }
119
+ };
120
+
121
+ checkStyle(m.default, 'macro.default');
122
+ if (m.formats !== undefined) {
123
+ if (!m.formats || typeof m.formats !== 'object' || Array.isArray(m.formats)) {
124
+ errors.push('macro.formats must be an object keyed by format name');
125
+ } else {
126
+ for (const [fmt, style] of Object.entries(m.formats)) {
127
+ checkStyle(style, `macro.formats.${fmt}`);
128
+ }
129
+ }
130
+ }
131
+
132
+ return errors;
133
+ }
134
+
135
+ // =============================================================================
136
+ // Merge
137
+ // =============================================================================
138
+
139
+ /**
140
+ * Merge built-in macros with user-declared macros. User entries override
141
+ * built-ins by `name` (case-sensitive). Invalid entries are dropped with a
142
+ * console warning so a malformed user macro never silently disables the
143
+ * built-in.
144
+ */
145
+ export function mergeMacros(userMacros: unknown): MacroDef[] {
146
+ const builtins = new Map<string, MacroDef>();
147
+ for (const m of BUILTIN_MACROS) builtins.set(m.name, m);
148
+
149
+ if (!userMacros) return [...builtins.values()];
150
+ if (!Array.isArray(userMacros)) {
151
+ console.warn('macros: rev.yaml `macros` must be a list; ignoring');
152
+ return [...builtins.values()];
153
+ }
154
+
155
+ for (const raw of userMacros) {
156
+ const errors = validateMacro(raw);
157
+ if (errors.length > 0) {
158
+ console.warn(`macros: skipping invalid macro: ${errors.join('; ')}`);
159
+ continue;
160
+ }
161
+ const def = raw as MacroDef;
162
+ builtins.set(def.name, def);
163
+ }
164
+
165
+ return [...builtins.values()];
166
+ }
167
+
168
+ // =============================================================================
169
+ // LaTeX preamble generation (PDF / tex / beamer)
170
+ // =============================================================================
171
+
172
+ /**
173
+ * Build the LaTeX color spec for a style. Returns the wrapping LaTeX with a
174
+ * `#1` placeholder where the argument lands.
175
+ */
176
+ function latexCommandBody(style: MacroFormatStyle): string {
177
+ const prefix = style.prefix ? escapeLatex(style.prefix) : '';
178
+ const suffix = style.suffix ? escapeLatex(style.suffix) : '';
179
+ const inner = `${prefix}#1${suffix}`;
180
+ const bracketed = style.bracket === false ? inner : `[${inner}]`;
181
+
182
+ let body = bracketed;
183
+ if (style.italic) body = `\\textit{${body}}`;
184
+ if (style.bold) body = `\\textbf{${body}}`;
185
+ if (style.color) body = `\\textcolor[HTML]{${style.color.toUpperCase()}}{${body}}`;
186
+ return body;
187
+ }
188
+
189
+ /**
190
+ * Generate `\providecommand` definitions for all macros. `\providecommand`
191
+ * means user-supplied `\renewcommand` (in a custom header-includes file) still
192
+ * wins, preserving backwards compat with existing projects.
193
+ *
194
+ * Returns an empty string when the macro list is empty.
195
+ */
196
+ export function generateLatexPreamble(macros: MacroDef[]): string {
197
+ const lines: string[] = ['% docrev: placeholder macros'];
198
+ // \textcolor in [HTML]{...} requires xcolor with the [HTML] option.
199
+ lines.push('\\PassOptionsToPackage{HTML}{xcolor}');
200
+ // Some templates already load xcolor; \usepackage tolerates duplicates with
201
+ // the same options.
202
+ lines.push('\\usepackage[HTML]{xcolor}');
203
+
204
+ for (const m of macros) {
205
+ const style = pickStyle(m, 'latex');
206
+ const body = latexCommandBody(style);
207
+ lines.push(`\\providecommand{\\${m.name}}[1]{${body}}`);
208
+ }
209
+
210
+ return lines.join('\n');
211
+ }
212
+
213
+ function escapeLatex(s: string): string {
214
+ // Conservative escape — these are user-authored short literals (prefix/suffix).
215
+ return s
216
+ .replace(/\\/g, '\\textbackslash{}')
217
+ .replace(/([&%$#_{}])/g, '\\$1')
218
+ .replace(/~/g, '\\textasciitilde{}')
219
+ .replace(/\^/g, '\\textasciicircum{}');
220
+ }
221
+
222
+ // =============================================================================
223
+ // Style resolution per format
224
+ // =============================================================================
225
+
226
+ /**
227
+ * Resolve the effective style for a macro in a given pandoc format. Per-format
228
+ * override wins over the macro's default; both can be partial — fields are
229
+ * not merged across `default` and `formats[fmt]` (the format-specific entry
230
+ * replaces `default` entirely when present), keeping rev.yaml semantics
231
+ * predictable.
232
+ *
233
+ * Falls back to `default` when no `formats[fmt]` exists, and to an empty
234
+ * style ({}) when neither is set.
235
+ */
236
+ export function pickStyle(macro: MacroDef, format: string): MacroFormatStyle {
237
+ const fmt = macro.formats?.[format];
238
+ if (fmt) return fmt;
239
+ return macro.default ?? {};
240
+ }
241
+
242
+ // =============================================================================
243
+ // Lua filter sidecar
244
+ // =============================================================================
245
+
246
+ /**
247
+ * Serialize the macro list to a compact JSON sidecar consumed by the lua
248
+ * filter at build time. The lua filter reads this file at startup and uses it
249
+ * to expand `\tofill{X}` (or any other declared macro) per FORMAT.
250
+ *
251
+ * Returns the absolute path to the written sidecar.
252
+ */
253
+ export function writeMacrosSidecar(directory: string, macros: MacroDef[]): string {
254
+ const sidecarPath = path.join(directory, '.macros.json');
255
+ fs.writeFileSync(sidecarPath, JSON.stringify({ macros }), 'utf-8');
256
+ return sidecarPath;
257
+ }
258
+
259
+ /**
260
+ * Resolve the absolute path to the bundled lua filter. Works both from source
261
+ * (`lib/macro-filter.lua`) and from the compiled package (`dist/lib/...`)
262
+ * because the postbuild script copies .lua files alongside the .js output.
263
+ */
264
+ export function getMacroFilterPath(): string {
265
+ // import.meta.url points to the running file: lib/macros.ts in source,
266
+ // dist/lib/macros.js when published. The filter sits next to it.
267
+ //
268
+ // Use fileURLToPath so paths with spaces (Windows: "C:\Users\Gilles Colling\…")
269
+ // resolve correctly. The naive `new URL(...).pathname` returns URL-encoded
270
+ // `%20` segments and fs.existsSync silently fails.
271
+ const here = path.dirname(fileURLToPath(import.meta.url));
272
+ return path.join(here, 'macro-filter.lua');
273
+ }