docrev 0.11.2 → 0.12.0

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 (205) hide show
  1. package/CHANGELOG.md +27 -0
  2. package/LICENSE +21 -0
  3. package/dist/bin/rev.js +29 -21
  4. package/dist/bin/rev.js.map +1 -1
  5. package/dist/lib/annotations.d.ts.map +1 -1
  6. package/dist/lib/annotations.js +28 -0
  7. package/dist/lib/annotations.js.map +1 -1
  8. package/dist/lib/build.d.ts +43 -0
  9. package/dist/lib/build.d.ts.map +1 -1
  10. package/dist/lib/build.js +175 -5
  11. package/dist/lib/build.js.map +1 -1
  12. package/dist/lib/commands/build.d.ts.map +1 -1
  13. package/dist/lib/commands/build.js +39 -125
  14. package/dist/lib/commands/build.js.map +1 -1
  15. package/dist/lib/commands/comments.d.ts.map +1 -1
  16. package/dist/lib/commands/comments.js +61 -31
  17. package/dist/lib/commands/comments.js.map +1 -1
  18. package/dist/lib/commands/context.d.ts +12 -0
  19. package/dist/lib/commands/context.d.ts.map +1 -1
  20. package/dist/lib/commands/context.js +34 -0
  21. package/dist/lib/commands/context.js.map +1 -1
  22. package/dist/lib/commands/core.d.ts.map +1 -1
  23. package/dist/lib/commands/core.js +25 -8
  24. package/dist/lib/commands/core.js.map +1 -1
  25. package/dist/lib/commands/merge-resolve.js +1 -1
  26. package/dist/lib/commands/merge-resolve.js.map +1 -1
  27. package/dist/lib/commands/quality.js +2 -2
  28. package/dist/lib/commands/quality.js.map +1 -1
  29. package/dist/lib/commands/response.js +1 -1
  30. package/dist/lib/commands/response.js.map +1 -1
  31. package/dist/lib/commands/sections.js +1 -1
  32. package/dist/lib/commands/sections.js.map +1 -1
  33. package/dist/lib/commands/text-ops.js +1 -1
  34. package/dist/lib/commands/text-ops.js.map +1 -1
  35. package/dist/lib/commands/utilities.d.ts.map +1 -1
  36. package/dist/lib/commands/utilities.js +5 -2
  37. package/dist/lib/commands/utilities.js.map +1 -1
  38. package/dist/lib/commands/word-tools.js +2 -2
  39. package/dist/lib/commands/word-tools.js.map +1 -1
  40. package/dist/lib/crossref.d.ts.map +1 -1
  41. package/dist/lib/crossref.js +12 -41
  42. package/dist/lib/crossref.js.map +1 -1
  43. package/dist/lib/csl.d.ts.map +1 -1
  44. package/dist/lib/csl.js +14 -22
  45. package/dist/lib/csl.js.map +1 -1
  46. package/dist/lib/diff-engine.js +1 -1
  47. package/dist/lib/diff-engine.js.map +1 -1
  48. package/dist/lib/equations.d.ts.map +1 -1
  49. package/dist/lib/equations.js +12 -3
  50. package/dist/lib/equations.js.map +1 -1
  51. package/dist/lib/errors.d.ts.map +1 -1
  52. package/dist/lib/errors.js +1 -30
  53. package/dist/lib/errors.js.map +1 -1
  54. package/dist/lib/image-registry.d.ts.map +1 -1
  55. package/dist/lib/image-registry.js +4 -0
  56. package/dist/lib/image-registry.js.map +1 -1
  57. package/dist/lib/import.d.ts +15 -1
  58. package/dist/lib/import.d.ts.map +1 -1
  59. package/dist/lib/import.js +24 -1
  60. package/dist/lib/import.js.map +1 -1
  61. package/dist/lib/input.d.ts +56 -0
  62. package/dist/lib/input.d.ts.map +1 -0
  63. package/dist/lib/input.js +129 -0
  64. package/dist/lib/input.js.map +1 -0
  65. package/dist/lib/merge.d.ts.map +1 -1
  66. package/dist/lib/merge.js +9 -1
  67. package/dist/lib/merge.js.map +1 -1
  68. package/dist/lib/ooxml.d.ts +22 -0
  69. package/dist/lib/ooxml.d.ts.map +1 -1
  70. package/dist/lib/ooxml.js +130 -0
  71. package/dist/lib/ooxml.js.map +1 -1
  72. package/dist/lib/orcid.d.ts.map +1 -1
  73. package/dist/lib/orcid.js +16 -7
  74. package/dist/lib/orcid.js.map +1 -1
  75. package/dist/lib/plugins.d.ts.map +1 -1
  76. package/dist/lib/plugins.js +8 -4
  77. package/dist/lib/plugins.js.map +1 -1
  78. package/dist/lib/protect-restore.d.ts.map +1 -1
  79. package/dist/lib/protect-restore.js +7 -5
  80. package/dist/lib/protect-restore.js.map +1 -1
  81. package/dist/lib/response.d.ts +1 -1
  82. package/dist/lib/response.d.ts.map +1 -1
  83. package/dist/lib/response.js +5 -2
  84. package/dist/lib/response.js.map +1 -1
  85. package/dist/lib/restore-references.d.ts.map +1 -1
  86. package/dist/lib/restore-references.js +25 -3
  87. package/dist/lib/restore-references.js.map +1 -1
  88. package/dist/lib/schema.d.ts.map +1 -1
  89. package/dist/lib/schema.js +1 -19
  90. package/dist/lib/schema.js.map +1 -1
  91. package/dist/lib/slides.js +1 -1
  92. package/dist/lib/slides.js.map +1 -1
  93. package/dist/lib/spelling.js +1 -1
  94. package/dist/lib/spelling.js.map +1 -1
  95. package/dist/lib/tui.js +0 -1
  96. package/dist/lib/tui.js.map +1 -1
  97. package/dist/lib/utils.d.ts +14 -0
  98. package/dist/lib/utils.d.ts.map +1 -1
  99. package/dist/lib/utils.js +41 -0
  100. package/dist/lib/utils.js.map +1 -1
  101. package/dist/lib/word-extraction.d.ts +5 -5
  102. package/dist/lib/word-extraction.d.ts.map +1 -1
  103. package/dist/lib/word-extraction.js +25 -106
  104. package/dist/lib/word-extraction.js.map +1 -1
  105. package/dist/lib/word.d.ts +14 -38
  106. package/dist/lib/word.d.ts.map +1 -1
  107. package/dist/lib/word.js +24 -179
  108. package/dist/lib/word.js.map +1 -1
  109. package/dist/lib/wordcomments.d.ts.map +1 -1
  110. package/dist/lib/wordcomments.js +9 -7
  111. package/dist/lib/wordcomments.js.map +1 -1
  112. package/package.json +17 -6
  113. package/.gitattributes +0 -1
  114. package/PLAN-tables-and-postprocess.md +0 -850
  115. package/bin/rev.ts +0 -145
  116. package/docs-src/build.py +0 -113
  117. package/docs-src/extra.css +0 -208
  118. package/docs-src/md-to-html.lua +0 -6
  119. package/docs-src/template.html +0 -116
  120. package/eslint.config.js +0 -27
  121. package/lib/anchor-match.ts +0 -307
  122. package/lib/annotations.ts +0 -664
  123. package/lib/build.ts +0 -2047
  124. package/lib/citations.ts +0 -160
  125. package/lib/commands/build.ts +0 -885
  126. package/lib/commands/citations.ts +0 -515
  127. package/lib/commands/comments.ts +0 -1050
  128. package/lib/commands/context.ts +0 -176
  129. package/lib/commands/core.ts +0 -309
  130. package/lib/commands/doi.ts +0 -451
  131. package/lib/commands/file-ops.ts +0 -372
  132. package/lib/commands/history.ts +0 -320
  133. package/lib/commands/index.ts +0 -87
  134. package/lib/commands/init.ts +0 -259
  135. package/lib/commands/merge-resolve.ts +0 -378
  136. package/lib/commands/preview.ts +0 -178
  137. package/lib/commands/project-info.ts +0 -244
  138. package/lib/commands/quality.ts +0 -517
  139. package/lib/commands/response.ts +0 -454
  140. package/lib/commands/section-boundaries.ts +0 -82
  141. package/lib/commands/sections.ts +0 -451
  142. package/lib/commands/sync.ts +0 -689
  143. package/lib/commands/text-ops.ts +0 -449
  144. package/lib/commands/utilities.ts +0 -448
  145. package/lib/commands/verify-anchors.ts +0 -272
  146. package/lib/commands/word-tools.ts +0 -340
  147. package/lib/comment-realign.ts +0 -99
  148. package/lib/config.ts +0 -84
  149. package/lib/crossref.ts +0 -781
  150. package/lib/csl.ts +0 -191
  151. package/lib/dependencies.ts +0 -132
  152. package/lib/diff-engine.ts +0 -465
  153. package/lib/doi-cache.ts +0 -115
  154. package/lib/doi.ts +0 -879
  155. package/lib/equations.ts +0 -506
  156. package/lib/errors.ts +0 -350
  157. package/lib/format.ts +0 -541
  158. package/lib/git.ts +0 -326
  159. package/lib/grammar.ts +0 -303
  160. package/lib/image-registry.ts +0 -180
  161. package/lib/import.ts +0 -906
  162. package/lib/journals.ts +0 -543
  163. package/lib/macro-filter.lua +0 -201
  164. package/lib/macros.ts +0 -273
  165. package/lib/merge.ts +0 -633
  166. package/lib/ooxml.ts +0 -768
  167. package/lib/orcid.ts +0 -144
  168. package/lib/pdf-comments.ts +0 -263
  169. package/lib/pdf-import.ts +0 -524
  170. package/lib/plugins.ts +0 -362
  171. package/lib/postprocess.ts +0 -188
  172. package/lib/pptx-color-filter.lua +0 -37
  173. package/lib/pptx-template.ts +0 -469
  174. package/lib/pptx-themes/academic.pptx +0 -0
  175. package/lib/pptx-themes/corporate.pptx +0 -0
  176. package/lib/pptx-themes/dark.pptx +0 -0
  177. package/lib/pptx-themes/default.pptx +0 -0
  178. package/lib/pptx-themes/minimal.pptx +0 -0
  179. package/lib/pptx-themes/plant.pptx +0 -0
  180. package/lib/pptx-themes.ts +0 -483
  181. package/lib/protect-restore.ts +0 -520
  182. package/lib/rate-limiter.ts +0 -127
  183. package/lib/response.ts +0 -197
  184. package/lib/restore-references.ts +0 -240
  185. package/lib/review.ts +0 -327
  186. package/lib/schema.ts +0 -494
  187. package/lib/scientific-words.ts +0 -73
  188. package/lib/sections.ts +0 -428
  189. package/lib/slides.ts +0 -756
  190. package/lib/spelling.ts +0 -334
  191. package/lib/templates.ts +0 -526
  192. package/lib/themes.ts +0 -742
  193. package/lib/trackchanges.ts +0 -166
  194. package/lib/tui.ts +0 -450
  195. package/lib/types.ts +0 -546
  196. package/lib/undo.ts +0 -250
  197. package/lib/utils.ts +0 -69
  198. package/lib/variables.ts +0 -179
  199. package/lib/word-extraction.ts +0 -525
  200. package/lib/word.ts +0 -526
  201. package/lib/wordcomments.ts +0 -789
  202. package/mkdocs.yml +0 -64
  203. package/scripts/postbuild.js +0 -47
  204. package/tsconfig.json +0 -26
  205. package/types/index.d.ts +0 -531
@@ -1,201 +0,0 @@
1
- --[[
2
- docrev macro filter.
3
-
4
- Reads a JSON sidecar describing one-argument LaTeX-style macros and expands
5
- them per output FORMAT. Used for the built-in \tofill{X} (bold orange [X]
6
- placeholder) and any user-declared macros from rev.yaml.
7
-
8
- Sidecar path is passed via the DOCREV_MACROS_FILE environment variable, set
9
- by build.ts before spawning pandoc. Env vars (not metadata) because pandoc's
10
- filter traversal runs RawInline/RawBlock BEFORE Meta, so by the time we'd
11
- read metadata the inline expansions have already happened.
12
-
13
- Why raw OpenXML for docx? Pandoc 3.x's docx writer does NOT honor
14
- `Span{style="color: #..."}` — those spans render as plain text with no
15
- <w:color> run property. So for docx we emit raw <w:r> nodes directly. Same
16
- reasoning for the pptx-color-filter.
17
-
18
- For latex/pdf/beamer the markdown source already contains \tofill{X} as a raw
19
- LaTeX inline; we leave it alone because build.ts injects a \providecommand
20
- into header-includes. For html we emit a raw <span> with inline style. For
21
- everything else (markdown, gfm, plain) we degrade to **bold [X]** so the
22
- placeholder never silently disappears.
23
- ]]
24
-
25
- local json = require('pandoc.json')
26
-
27
- local macros_by_name = {}
28
-
29
- local function load_sidecar()
30
- local path = os.getenv('DOCREV_MACROS_FILE')
31
- if not path or path == '' then
32
- return
33
- end
34
- local fh = io.open(path, 'r')
35
- if not fh then
36
- io.stderr:write('docrev macro-filter: cannot read sidecar: ' .. path .. '\n')
37
- return
38
- end
39
- local content = fh:read('*a')
40
- fh:close()
41
- local ok, parsed = pcall(json.decode, content)
42
- if not ok or type(parsed) ~= 'table' or type(parsed.macros) ~= 'table' then
43
- io.stderr:write('docrev macro-filter: malformed sidecar JSON\n')
44
- return
45
- end
46
- for _, m in ipairs(parsed.macros) do
47
- if type(m) == 'table' and type(m.name) == 'string' then
48
- macros_by_name[m.name] = m
49
- end
50
- end
51
- end
52
-
53
- load_sidecar()
54
-
55
- local function xml_escape(s)
56
- return (s:gsub('&', '&amp;'):gsub('<', '&lt;'):gsub('>', '&gt;'))
57
- end
58
-
59
- local function html_escape(s)
60
- return (s
61
- :gsub('&', '&amp;')
62
- :gsub('<', '&lt;')
63
- :gsub('>', '&gt;')
64
- :gsub('"', '&quot;'))
65
- end
66
-
67
- -- Resolve effective style for a macro in the current pandoc format.
68
- -- Per-format entry wins over `default` (replacement, not merge — matches
69
- -- macros.ts semantics).
70
- local function pick_style(macro, format)
71
- if macro.formats and macro.formats[format] then
72
- return macro.formats[format]
73
- end
74
- return macro.default or {}
75
- end
76
-
77
- -- Build the inside of the bracket: [prefix][arg][suffix], optionally without
78
- -- brackets when style.bracket == false.
79
- local function compose_text(style, arg)
80
- local prefix = style.prefix or ''
81
- local suffix = style.suffix or ''
82
- local inner = prefix .. arg .. suffix
83
- if style.bracket == false then
84
- return inner
85
- end
86
- return '[' .. inner .. ']'
87
- end
88
-
89
- local function render_docx_run(style, arg)
90
- local rpr = {}
91
- if style.color then
92
- table.insert(rpr, '<w:color w:val="' .. style.color .. '"/>')
93
- end
94
- if style.bold then
95
- table.insert(rpr, '<w:b/>')
96
- end
97
- if style.italic then
98
- table.insert(rpr, '<w:i/>')
99
- end
100
- local rpr_xml = ''
101
- if #rpr > 0 then
102
- rpr_xml = '<w:rPr>' .. table.concat(rpr) .. '</w:rPr>'
103
- end
104
- local text = xml_escape(compose_text(style, arg))
105
- return '<w:r>' .. rpr_xml ..
106
- '<w:t xml:space="preserve">' .. text .. '</w:t></w:r>'
107
- end
108
-
109
- local function render_html(style, arg)
110
- local css = {}
111
- if style.color then
112
- table.insert(css, 'color:#' .. style.color)
113
- end
114
- if style.bold then
115
- table.insert(css, 'font-weight:bold')
116
- end
117
- if style.italic then
118
- table.insert(css, 'font-style:italic')
119
- end
120
- local text = html_escape(compose_text(style, arg))
121
- if #css == 0 then
122
- return '<span>' .. text .. '</span>'
123
- end
124
- return '<span style="' .. table.concat(css, ';') .. '">' .. text .. '</span>'
125
- end
126
-
127
- -- Fallback path: produce native pandoc inlines so the macro never silently
128
- -- disappears in markdown/gfm/plain output. Used when the current format has
129
- -- no native rich-text path (or we couldn't open the sidecar).
130
- local function fallback_inlines(style, arg)
131
- local doc = pandoc.read(compose_text(style, arg), 'markdown')
132
- local inlines = pandoc.utils.blocks_to_inlines(doc.blocks)
133
- if style.bold then
134
- inlines = { pandoc.Strong(inlines) }
135
- end
136
- if style.italic then
137
- inlines = { pandoc.Emph(inlines) }
138
- end
139
- return inlines
140
- end
141
-
142
- -- Match `\NAME{...}` (with balanced braces inside the argument is NOT
143
- -- supported — the use case is plain placeholder text, mirroring the reference
144
- -- filter; users who need nested braces should use a different mechanism).
145
- local function parse_call(text)
146
- local name, arg = text:match('^\\([A-Za-z][A-Za-z0-9]*)%s*{(.*)}%s*$')
147
- if name and arg and macros_by_name[name] then
148
- return name, arg
149
- end
150
- return nil, nil
151
- end
152
-
153
- local function expand_inline(el)
154
- if el.format ~= 'tex' and el.format ~= 'latex' then
155
- return nil
156
- end
157
- local name, arg = parse_call(el.text)
158
- if not name then return nil end
159
- local macro = macros_by_name[name]
160
- local style = pick_style(macro, FORMAT)
161
-
162
- if FORMAT == 'docx' then
163
- return pandoc.RawInline('openxml', render_docx_run(style, arg))
164
- elseif FORMAT == 'html' or FORMAT == 'html4' or FORMAT == 'html5' or FORMAT == 'chunkedhtml' then
165
- return pandoc.RawInline('html', render_html(style, arg))
166
- elseif FORMAT == 'latex' or FORMAT == 'beamer' or FORMAT == 'context' then
167
- -- Leave the raw LaTeX as-is. build.ts injects \providecommand into
168
- -- header-includes, so the LaTeX engine renders it directly.
169
- return nil
170
- else
171
- return fallback_inlines(style, arg)
172
- end
173
- end
174
-
175
- local function expand_block(el)
176
- if el.format ~= 'tex' and el.format ~= 'latex' then
177
- return nil
178
- end
179
- local name, arg = parse_call(el.text)
180
- if not name then return nil end
181
- local macro = macros_by_name[name]
182
- local style = pick_style(macro, FORMAT)
183
-
184
- if FORMAT == 'docx' then
185
- return pandoc.RawBlock('openxml', '<w:p>' .. render_docx_run(style, arg) .. '</w:p>')
186
- elseif FORMAT == 'html' or FORMAT == 'html4' or FORMAT == 'html5' or FORMAT == 'chunkedhtml' then
187
- return pandoc.RawBlock('html', '<p>' .. render_html(style, arg) .. '</p>')
188
- elseif FORMAT == 'latex' or FORMAT == 'beamer' or FORMAT == 'context' then
189
- return nil
190
- else
191
- return pandoc.Para(fallback_inlines(style, arg))
192
- end
193
- end
194
-
195
- function RawInline(el)
196
- return expand_inline(el)
197
- end
198
-
199
- function RawBlock(el)
200
- return expand_block(el)
201
- end
package/lib/macros.ts DELETED
@@ -1,273 +0,0 @@
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
- }