docrev 0.10.0 → 0.10.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (126) hide show
  1. package/.gitattributes +1 -1
  2. package/CHANGELOG.md +173 -164
  3. package/PLAN-tables-and-postprocess.md +850 -850
  4. package/README.md +431 -431
  5. package/bin/rev.js +11 -11
  6. package/bin/rev.ts +145 -145
  7. package/completions/rev.bash +127 -127
  8. package/completions/rev.ps1 +210 -210
  9. package/completions/rev.zsh +207 -207
  10. package/dist/lib/anchor-match.d.ts +1 -1
  11. package/dist/lib/anchor-match.d.ts.map +1 -1
  12. package/dist/lib/anchor-match.js +17 -47
  13. package/dist/lib/anchor-match.js.map +1 -1
  14. package/dist/lib/build.js +4 -4
  15. package/dist/lib/commands/context.d.ts +1 -1
  16. package/dist/lib/commands/context.d.ts.map +1 -1
  17. package/dist/lib/commands/context.js +1 -1
  18. package/dist/lib/commands/context.js.map +1 -1
  19. package/dist/lib/commands/sections.js +7 -7
  20. package/dist/lib/commands/sections.js.map +1 -1
  21. package/dist/lib/commands/sync.d.ts.map +1 -1
  22. package/dist/lib/commands/sync.js +15 -14
  23. package/dist/lib/commands/sync.js.map +1 -1
  24. package/dist/lib/commands/utilities.js +164 -164
  25. package/dist/lib/commands/verify-anchors.js +6 -6
  26. package/dist/lib/commands/verify-anchors.js.map +1 -1
  27. package/dist/lib/commands/word-tools.js +8 -8
  28. package/dist/lib/grammar.js +3 -3
  29. package/dist/lib/macro-filter.lua +201 -201
  30. package/dist/lib/pdf-comments.js +44 -44
  31. package/dist/lib/plugins.js +57 -57
  32. package/dist/lib/pptx-color-filter.lua +37 -37
  33. package/dist/lib/pptx-themes.js +115 -115
  34. package/dist/lib/sections.d.ts +35 -0
  35. package/dist/lib/sections.d.ts.map +1 -1
  36. package/dist/lib/sections.js +81 -0
  37. package/dist/lib/sections.js.map +1 -1
  38. package/dist/lib/spelling.js +2 -2
  39. package/dist/lib/templates.js +387 -387
  40. package/dist/lib/themes.js +51 -51
  41. package/docs-src/build.py +113 -113
  42. package/docs-src/extra.css +208 -208
  43. package/docs-src/md-to-html.lua +6 -6
  44. package/docs-src/template.html +116 -116
  45. package/eslint.config.js +27 -27
  46. package/lib/anchor-match.ts +276 -308
  47. package/lib/annotations.ts +644 -644
  48. package/lib/build.ts +1766 -1766
  49. package/lib/citations.ts +160 -160
  50. package/lib/commands/build.ts +855 -855
  51. package/lib/commands/citations.ts +515 -515
  52. package/lib/commands/comments.ts +1050 -1050
  53. package/lib/commands/context.ts +176 -174
  54. package/lib/commands/core.ts +309 -309
  55. package/lib/commands/doi.ts +435 -435
  56. package/lib/commands/file-ops.ts +372 -372
  57. package/lib/commands/history.ts +320 -320
  58. package/lib/commands/index.ts +87 -87
  59. package/lib/commands/init.ts +259 -259
  60. package/lib/commands/merge-resolve.ts +378 -378
  61. package/lib/commands/preview.ts +178 -178
  62. package/lib/commands/project-info.ts +244 -244
  63. package/lib/commands/quality.ts +517 -517
  64. package/lib/commands/response.ts +454 -454
  65. package/lib/commands/section-boundaries.ts +82 -82
  66. package/lib/commands/sections.ts +451 -451
  67. package/lib/commands/sync.ts +709 -706
  68. package/lib/commands/text-ops.ts +449 -449
  69. package/lib/commands/utilities.ts +448 -448
  70. package/lib/commands/verify-anchors.ts +272 -272
  71. package/lib/commands/word-tools.ts +340 -340
  72. package/lib/comment-realign.ts +517 -517
  73. package/lib/config.ts +84 -84
  74. package/lib/crossref.ts +781 -781
  75. package/lib/csl.ts +191 -191
  76. package/lib/dependencies.ts +98 -98
  77. package/lib/diff-engine.ts +465 -465
  78. package/lib/doi-cache.ts +115 -115
  79. package/lib/doi.ts +897 -897
  80. package/lib/equations.ts +506 -506
  81. package/lib/errors.ts +346 -346
  82. package/lib/format.ts +541 -541
  83. package/lib/git.ts +326 -326
  84. package/lib/grammar.ts +303 -303
  85. package/lib/image-registry.ts +180 -180
  86. package/lib/import.ts +911 -911
  87. package/lib/journals.ts +543 -543
  88. package/lib/macro-filter.lua +201 -201
  89. package/lib/macros.ts +273 -273
  90. package/lib/merge.ts +633 -633
  91. package/lib/orcid.ts +144 -144
  92. package/lib/pdf-comments.ts +263 -263
  93. package/lib/pdf-import.ts +524 -524
  94. package/lib/plugins.ts +362 -362
  95. package/lib/postprocess.ts +188 -188
  96. package/lib/pptx-color-filter.lua +37 -37
  97. package/lib/pptx-template.ts +469 -469
  98. package/lib/pptx-themes.ts +483 -483
  99. package/lib/protect-restore.ts +520 -520
  100. package/lib/rate-limiter.ts +94 -94
  101. package/lib/response.ts +197 -197
  102. package/lib/restore-references.ts +240 -240
  103. package/lib/review.ts +327 -327
  104. package/lib/schema.ts +488 -488
  105. package/lib/scientific-words.ts +73 -73
  106. package/lib/sections.ts +425 -335
  107. package/lib/slides.ts +756 -756
  108. package/lib/spelling.ts +334 -334
  109. package/lib/templates.ts +526 -526
  110. package/lib/themes.ts +742 -742
  111. package/lib/trackchanges.ts +247 -247
  112. package/lib/tui.ts +450 -450
  113. package/lib/types.ts +550 -550
  114. package/lib/undo.ts +250 -250
  115. package/lib/utils.ts +69 -69
  116. package/lib/variables.ts +179 -179
  117. package/lib/word-extraction.ts +806 -806
  118. package/lib/word.ts +643 -643
  119. package/lib/wordcomments.ts +840 -840
  120. package/mkdocs.yml +64 -64
  121. package/package.json +137 -137
  122. package/scripts/postbuild.js +47 -47
  123. package/skill/REFERENCE.md +539 -539
  124. package/skill/SKILL.md +295 -295
  125. package/tsconfig.json +26 -26
  126. package/types/index.d.ts +525 -525
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
+ }