docrev 0.11.1 → 0.11.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 (116) hide show
  1. package/.gitattributes +1 -1
  2. package/CHANGELOG.md +202 -197
  3. package/PLAN-tables-and-postprocess.md +850 -850
  4. package/README.md +433 -433
  5. package/bin/rev.js +11 -11
  6. package/bin/rev.ts +145 -145
  7. package/completions/rev.bash +127 -127
  8. package/completions/rev.ps1 +210 -210
  9. package/completions/rev.zsh +207 -207
  10. package/dist/lib/build.d.ts +28 -0
  11. package/dist/lib/build.d.ts.map +1 -1
  12. package/dist/lib/build.js +81 -4
  13. package/dist/lib/build.js.map +1 -1
  14. package/dist/lib/commands/utilities.js +164 -164
  15. package/dist/lib/commands/word-tools.js +8 -8
  16. package/dist/lib/grammar.js +3 -3
  17. package/dist/lib/macro-filter.lua +201 -201
  18. package/dist/lib/pdf-comments.js +44 -44
  19. package/dist/lib/plugins.js +57 -57
  20. package/dist/lib/pptx-color-filter.lua +37 -37
  21. package/dist/lib/pptx-themes.js +115 -115
  22. package/dist/lib/schema.d.ts.map +1 -1
  23. package/dist/lib/schema.js +8 -2
  24. package/dist/lib/schema.js.map +1 -1
  25. package/dist/lib/spelling.js +2 -2
  26. package/dist/lib/templates.js +387 -387
  27. package/dist/lib/themes.js +51 -51
  28. package/eslint.config.js +27 -27
  29. package/lib/anchor-match.ts +307 -307
  30. package/lib/annotations.ts +664 -664
  31. package/lib/build.ts +2047 -1956
  32. package/lib/citations.ts +160 -160
  33. package/lib/commands/build.ts +885 -885
  34. package/lib/commands/citations.ts +515 -515
  35. package/lib/commands/comments.ts +1050 -1050
  36. package/lib/commands/context.ts +176 -176
  37. package/lib/commands/core.ts +309 -309
  38. package/lib/commands/doi.ts +451 -451
  39. package/lib/commands/file-ops.ts +372 -372
  40. package/lib/commands/history.ts +320 -320
  41. package/lib/commands/index.ts +87 -87
  42. package/lib/commands/init.ts +259 -259
  43. package/lib/commands/merge-resolve.ts +378 -378
  44. package/lib/commands/preview.ts +178 -178
  45. package/lib/commands/project-info.ts +244 -244
  46. package/lib/commands/quality.ts +517 -517
  47. package/lib/commands/response.ts +454 -454
  48. package/lib/commands/section-boundaries.ts +82 -82
  49. package/lib/commands/sections.ts +451 -451
  50. package/lib/commands/sync.ts +689 -689
  51. package/lib/commands/text-ops.ts +449 -449
  52. package/lib/commands/utilities.ts +448 -448
  53. package/lib/commands/verify-anchors.ts +272 -272
  54. package/lib/commands/word-tools.ts +340 -340
  55. package/lib/comment-realign.ts +99 -99
  56. package/lib/config.ts +84 -84
  57. package/lib/crossref.ts +781 -781
  58. package/lib/csl.ts +191 -191
  59. package/lib/dependencies.ts +132 -132
  60. package/lib/diff-engine.ts +465 -465
  61. package/lib/doi-cache.ts +115 -115
  62. package/lib/doi.ts +879 -879
  63. package/lib/equations.ts +506 -506
  64. package/lib/errors.ts +350 -350
  65. package/lib/format.ts +541 -541
  66. package/lib/git.ts +326 -326
  67. package/lib/grammar.ts +303 -303
  68. package/lib/image-registry.ts +180 -180
  69. package/lib/import.ts +906 -906
  70. package/lib/journals.ts +543 -543
  71. package/lib/macro-filter.lua +201 -201
  72. package/lib/macros.ts +273 -273
  73. package/lib/merge.ts +633 -633
  74. package/lib/ooxml.ts +768 -768
  75. package/lib/orcid.ts +144 -144
  76. package/lib/pdf-comments.ts +263 -263
  77. package/lib/pdf-import.ts +524 -524
  78. package/lib/plugins.ts +362 -362
  79. package/lib/postprocess.ts +188 -188
  80. package/lib/pptx-color-filter.lua +37 -37
  81. package/lib/pptx-template.ts +469 -469
  82. package/lib/pptx-themes.ts +483 -483
  83. package/lib/protect-restore.ts +520 -520
  84. package/lib/rate-limiter.ts +127 -127
  85. package/lib/response.ts +197 -197
  86. package/lib/restore-references.ts +240 -240
  87. package/lib/review.ts +327 -327
  88. package/lib/schema.ts +494 -488
  89. package/lib/scientific-words.ts +73 -73
  90. package/lib/sections.ts +428 -428
  91. package/lib/slides.ts +756 -756
  92. package/lib/spelling.ts +334 -334
  93. package/lib/templates.ts +526 -526
  94. package/lib/themes.ts +742 -742
  95. package/lib/trackchanges.ts +166 -166
  96. package/lib/tui.ts +450 -450
  97. package/lib/types.ts +546 -546
  98. package/lib/undo.ts +250 -250
  99. package/lib/utils.ts +69 -69
  100. package/lib/variables.ts +179 -179
  101. package/lib/word-extraction.ts +525 -525
  102. package/lib/word.ts +526 -526
  103. package/lib/wordcomments.ts +789 -789
  104. package/package.json +1 -1
  105. package/scripts/postbuild.js +47 -47
  106. package/skill/REFERENCE.md +550 -550
  107. package/skill/SKILL.md +302 -302
  108. package/tsconfig.json +26 -26
  109. package/types/index.d.ts +531 -531
  110. package/issues.md +0 -180
  111. package/site/assets/extra.css +0 -208
  112. package/site/commands.html +0 -926
  113. package/site/configuration.html +0 -469
  114. package/site/index.html +0 -288
  115. package/site/troubleshooting.html +0 -461
  116. package/site/workflow.html +0 -518
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
+ }