docrev 0.9.17 → 0.10.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.
- package/CHANGELOG.md +15 -0
- package/README.md +25 -0
- package/dist/lib/build.d.ts +119 -1
- package/dist/lib/build.d.ts.map +1 -1
- package/dist/lib/build.js +409 -23
- package/dist/lib/build.js.map +1 -1
- package/dist/lib/commands/build.d.ts.map +1 -1
- package/dist/lib/commands/build.js +25 -10
- package/dist/lib/commands/build.js.map +1 -1
- package/dist/lib/macro-filter.lua +201 -0
- package/dist/lib/macros.d.ts +102 -0
- package/dist/lib/macros.d.ts.map +1 -0
- package/dist/lib/macros.js +218 -0
- package/dist/lib/macros.js.map +1 -0
- package/dist/lib/pptx-color-filter.lua +37 -0
- package/dist/lib/schema.d.ts.map +1 -1
- package/dist/lib/schema.js +71 -0
- package/dist/lib/schema.js.map +1 -1
- package/lib/build.ts +484 -24
- package/lib/commands/build.ts +32 -10
- package/lib/macro-filter.lua +201 -0
- package/lib/macros.ts +273 -0
- package/lib/schema.ts +71 -0
- package/package.json +1 -1
- package/scripts/postbuild.js +21 -2
- package/skill/REFERENCE.md +66 -0
- package/skill/SKILL.md +25 -4
- package/.claude/settings.local.json +0 -9
package/lib/commands/build.ts
CHANGED
|
@@ -52,6 +52,8 @@ interface BuildOptions {
|
|
|
52
52
|
colortheme?: string;
|
|
53
53
|
aspectratio?: string;
|
|
54
54
|
verbose?: boolean;
|
|
55
|
+
pandocArg?: string[];
|
|
56
|
+
output?: string;
|
|
55
57
|
}
|
|
56
58
|
|
|
57
59
|
/**
|
|
@@ -487,7 +489,14 @@ export function register(program: Command, pkg?: { version?: string }): void {
|
|
|
487
489
|
.option('--theme <name>', 'Beamer theme (default, metropolis, etc.)')
|
|
488
490
|
.option('--colortheme <name>', 'Beamer color theme')
|
|
489
491
|
.option('--aspectratio <ratio>', 'Beamer aspect ratio (169, 43)')
|
|
490
|
-
.option(
|
|
492
|
+
.option(
|
|
493
|
+
'--pandoc-arg <arg>',
|
|
494
|
+
'Extra arg to pass to pandoc (repeatable). Applied to every format being built; appended after rev.yaml pandoc-args so CLI wins.',
|
|
495
|
+
(val: string, prev: string[] = []) => [...prev, val],
|
|
496
|
+
[]
|
|
497
|
+
)
|
|
498
|
+
.option('-o, --output <path>', 'Output filename or path. Relative paths resolve under outputDir; absolute paths bypass it. Extension auto-added if missing. Applied to every format being built; overrides rev.yaml output.<format>.')
|
|
499
|
+
.option('--verbose', 'Show detailed output including postprocess scripts and the pandoc invocation')
|
|
491
500
|
.action(async (formats: string[], options: BuildOptions) => {
|
|
492
501
|
const dir = path.resolve(options.dir);
|
|
493
502
|
|
|
@@ -577,7 +586,7 @@ export function register(program: Command, pkg?: { version?: string }): void {
|
|
|
577
586
|
process.exit(1);
|
|
578
587
|
}
|
|
579
588
|
|
|
580
|
-
const { combineSections,
|
|
589
|
+
const { combineSections, resolveOutputPath } = await import('../build.js');
|
|
581
590
|
const { buildWithTrackChanges } = await import('../trackchanges.js');
|
|
582
591
|
|
|
583
592
|
const spin = fmt.spinner('Building with track changes...').start();
|
|
@@ -588,12 +597,12 @@ export function register(program: Command, pkg?: { version?: string }): void {
|
|
|
588
597
|
console.log(chalk.cyan('Combined sections → paper.md'));
|
|
589
598
|
console.log(chalk.dim(` ${paperPath}\n`));
|
|
590
599
|
|
|
591
|
-
const
|
|
592
|
-
|
|
593
|
-
: '
|
|
594
|
-
|
|
600
|
+
const outputPath = resolveOutputPath(dir, config, 'docx', {
|
|
601
|
+
cliOverride: options.output,
|
|
602
|
+
suffix: '-changes',
|
|
603
|
+
});
|
|
604
|
+
const outDir = path.dirname(outputPath);
|
|
595
605
|
if (!fs.existsSync(outDir)) fs.mkdirSync(outDir, { recursive: true });
|
|
596
|
-
const outputPath = path.join(outDir, `${baseName}-changes.docx`);
|
|
597
606
|
|
|
598
607
|
const spinTc = fmt.spinner('Applying track changes...').start();
|
|
599
608
|
const result = await buildWithTrackChanges(paperPath, outputPath, {
|
|
@@ -625,10 +634,12 @@ export function register(program: Command, pkg?: { version?: string }): void {
|
|
|
625
634
|
const spin = fmt.spinner('Building...').start();
|
|
626
635
|
|
|
627
636
|
try {
|
|
628
|
-
const { results, paperPath, forwardRefsResolved, refsAutoInjected } = await build(dir, targetFormats, {
|
|
637
|
+
const { results, paperPath, forwardRefsResolved, refsAutoInjected, warnings } = await build(dir, targetFormats, {
|
|
629
638
|
crossref: options.crossref,
|
|
630
639
|
config,
|
|
631
640
|
verbose: options.verbose,
|
|
641
|
+
pandocArgs: options.pandocArg,
|
|
642
|
+
output: options.output,
|
|
632
643
|
});
|
|
633
644
|
|
|
634
645
|
spin.stop();
|
|
@@ -643,6 +654,17 @@ export function register(program: Command, pkg?: { version?: string }): void {
|
|
|
643
654
|
}
|
|
644
655
|
console.log('');
|
|
645
656
|
|
|
657
|
+
if (warnings && warnings.length > 0) {
|
|
658
|
+
for (const w of warnings) {
|
|
659
|
+
// Each warning may span multiple lines — colour the first line as
|
|
660
|
+
// a warning header and pass through the rest unchanged.
|
|
661
|
+
const [head, ...rest] = w.split('\n');
|
|
662
|
+
console.log(chalk.yellow(`Warning: ${head}`));
|
|
663
|
+
for (const line of rest) console.log(chalk.yellow(line));
|
|
664
|
+
}
|
|
665
|
+
console.log('');
|
|
666
|
+
}
|
|
667
|
+
|
|
646
668
|
console.log(chalk.cyan('Output:'));
|
|
647
669
|
console.log(formatBuildResults(results));
|
|
648
670
|
|
|
@@ -703,7 +725,7 @@ export function register(program: Command, pkg?: { version?: string }): void {
|
|
|
703
725
|
|
|
704
726
|
const spinBuild = fmt.spinner('Building marked DOCX...').start();
|
|
705
727
|
const markedDocxPath = path.join(dir, '.paper-marked.docx');
|
|
706
|
-
const pandocResult = await runPandoc(markedPath, 'docx', config, { ...options, outputPath: markedDocxPath });
|
|
728
|
+
const pandocResult = await runPandoc(markedPath, 'docx', config, { ...options, outputPath: markedDocxPath, pandocArgs: options.pandocArg });
|
|
707
729
|
spinBuild.stop();
|
|
708
730
|
|
|
709
731
|
if (!pandocResult.success) {
|
|
@@ -786,7 +808,7 @@ export function register(program: Command, pkg?: { version?: string }): void {
|
|
|
786
808
|
|
|
787
809
|
const annotatedPdfPath = pdfResult.outputPath!.replace(/\.pdf$/, '_comments.pdf');
|
|
788
810
|
spinPdf.text = 'Building annotated PDF...';
|
|
789
|
-
const pandocResult = await runPandoc(annotatedPath, 'pdf', annotatedConfig, { ...options, outputPath: annotatedPdfPath });
|
|
811
|
+
const pandocResult = await runPandoc(annotatedPath, 'pdf', annotatedConfig, { ...options, outputPath: annotatedPdfPath, pandocArgs: options.pandocArg });
|
|
790
812
|
spinPdf.stop();
|
|
791
813
|
|
|
792
814
|
if (!process.env.DEBUG) {
|
|
@@ -0,0 +1,201 @@
|
|
|
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('&', '&'):gsub('<', '<'):gsub('>', '>'))
|
|
57
|
+
end
|
|
58
|
+
|
|
59
|
+
local function html_escape(s)
|
|
60
|
+
return (s
|
|
61
|
+
:gsub('&', '&')
|
|
62
|
+
:gsub('<', '<')
|
|
63
|
+
:gsub('>', '>')
|
|
64
|
+
:gsub('"', '"'))
|
|
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
ADDED
|
@@ -0,0 +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
|
+
}
|
package/lib/schema.ts
CHANGED
|
@@ -91,6 +91,23 @@ export const revYamlSchema: Schema = {
|
|
|
91
91
|
type: 'string',
|
|
92
92
|
description: 'Journal profile name for formatting defaults and validation',
|
|
93
93
|
},
|
|
94
|
+
'pandoc-args': {
|
|
95
|
+
type: 'array',
|
|
96
|
+
description: 'Extra pandoc args applied to every format build (e.g. --lua-filter=...). Format-specific lists are appended after these; --pandoc-arg CLI values are appended last.',
|
|
97
|
+
items: { type: 'string' },
|
|
98
|
+
},
|
|
99
|
+
output: {
|
|
100
|
+
type: 'object',
|
|
101
|
+
description: 'Per-format output filenames. Keys are format names (pdf, docx, tex, beamer, pptx); values are paths. Relative paths resolve under outputDir; absolute paths are honored as-is. Extension auto-added if missing. CLI `-o` overrides this map.',
|
|
102
|
+
properties: {
|
|
103
|
+
pdf: { type: 'string' },
|
|
104
|
+
docx: { type: 'string' },
|
|
105
|
+
tex: { type: 'string' },
|
|
106
|
+
beamer: { type: 'string' },
|
|
107
|
+
pptx: { type: 'string' },
|
|
108
|
+
},
|
|
109
|
+
additionalProperties: false,
|
|
110
|
+
},
|
|
94
111
|
sections: {
|
|
95
112
|
type: 'array',
|
|
96
113
|
description: 'Ordered list of section files to include',
|
|
@@ -160,6 +177,11 @@ export const revYamlSchema: Schema = {
|
|
|
160
177
|
toc: { type: 'boolean', default: false },
|
|
161
178
|
header: { type: 'string' },
|
|
162
179
|
footer: { type: 'string' },
|
|
180
|
+
'pandoc-args': {
|
|
181
|
+
type: 'array',
|
|
182
|
+
description: 'Extra pandoc args for PDF builds. Appended after the top-level pandoc-args list.',
|
|
183
|
+
items: { type: 'string' },
|
|
184
|
+
},
|
|
163
185
|
},
|
|
164
186
|
additionalProperties: true,
|
|
165
187
|
},
|
|
@@ -170,6 +192,16 @@ export const revYamlSchema: Schema = {
|
|
|
170
192
|
reference: { type: 'string', description: 'Reference document for styling' },
|
|
171
193
|
keepComments: { type: 'boolean', default: true },
|
|
172
194
|
toc: { type: 'boolean', default: false },
|
|
195
|
+
translateRawFigures: {
|
|
196
|
+
type: 'boolean',
|
|
197
|
+
default: true,
|
|
198
|
+
description: 'Auto-translate the common \\begin{figure}...\\end{figure} shape to portable ![](){#fig: ...} markdown so figures render in docx. Pandoc strips raw LaTeX in docx output silently otherwise.',
|
|
199
|
+
},
|
|
200
|
+
'pandoc-args': {
|
|
201
|
+
type: 'array',
|
|
202
|
+
description: 'Extra pandoc args for DOCX builds. Appended after the top-level pandoc-args list.',
|
|
203
|
+
items: { type: 'string' },
|
|
204
|
+
},
|
|
173
205
|
},
|
|
174
206
|
additionalProperties: true,
|
|
175
207
|
},
|
|
@@ -178,9 +210,48 @@ export const revYamlSchema: Schema = {
|
|
|
178
210
|
description: 'LaTeX output settings',
|
|
179
211
|
properties: {
|
|
180
212
|
standalone: { type: 'boolean', default: true },
|
|
213
|
+
'pandoc-args': {
|
|
214
|
+
type: 'array',
|
|
215
|
+
description: 'Extra pandoc args for TeX builds. Appended after the top-level pandoc-args list.',
|
|
216
|
+
items: { type: 'string' },
|
|
217
|
+
},
|
|
181
218
|
},
|
|
182
219
|
additionalProperties: true,
|
|
183
220
|
},
|
|
221
|
+
macros: {
|
|
222
|
+
type: 'array',
|
|
223
|
+
description: 'Placeholder/highlight macros (e.g. \\tofill{X}). Built-in macros are merged automatically; entries here add new macros or override built-ins by name.',
|
|
224
|
+
items: {
|
|
225
|
+
type: 'object',
|
|
226
|
+
properties: {
|
|
227
|
+
name: {
|
|
228
|
+
type: 'string',
|
|
229
|
+
description: 'Macro command name without leading backslash, e.g. "tofill" for \\tofill{...}',
|
|
230
|
+
pattern: '^[A-Za-z][A-Za-z0-9]*$',
|
|
231
|
+
},
|
|
232
|
+
default: {
|
|
233
|
+
type: 'object',
|
|
234
|
+
description: 'Default rendering rules across formats',
|
|
235
|
+
properties: {
|
|
236
|
+
color: { type: 'string', pattern: '^[0-9A-Fa-f]{6}$' },
|
|
237
|
+
bold: { type: 'boolean' },
|
|
238
|
+
italic: { type: 'boolean' },
|
|
239
|
+
bracket: { type: 'boolean', default: true },
|
|
240
|
+
prefix: { type: 'string' },
|
|
241
|
+
suffix: { type: 'string' },
|
|
242
|
+
},
|
|
243
|
+
additionalProperties: false,
|
|
244
|
+
},
|
|
245
|
+
formats: {
|
|
246
|
+
type: 'object',
|
|
247
|
+
description: 'Per-format overrides (keys: docx, pdf, latex, html, ...)',
|
|
248
|
+
additionalProperties: true,
|
|
249
|
+
},
|
|
250
|
+
},
|
|
251
|
+
required: ['name'],
|
|
252
|
+
additionalProperties: false,
|
|
253
|
+
},
|
|
254
|
+
},
|
|
184
255
|
},
|
|
185
256
|
additionalProperties: true,
|
|
186
257
|
};
|