docrev 0.11.1 → 0.11.3

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