Repository navigation
Expand file tree
/
Copy pathcode-window.lua
More file actions
1439 lines (1319 loc) · 56.5 KB
/
Copy pathcode-window.lua
File metadata and controls
1439 lines (1319 loc) · 56.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
--- @module "code-window"
--- @license MIT
--- @copyright 2026 Mickaël Canouil
--- @author Mickaël Canouil
--- @brief Code block window decorations with multiple styles
--- @description Adds window chrome (macOS traffic lights, Windows title bar
--- buttons, or plain filename) to code blocks in HTML, Reveal.js, and Typst
--- formats. Registered at pre-quarto to process all formats in a single pass.
-- ============================================================================
-- EXTENSION NAME
-- ============================================================================
local EXTENSION_NAME = 'code-window'
local str = require(quarto.utils.resolve_path('_vendor/quarto-lua-modules/string.lua'):gsub('%.lua$', ''))
local log = require(quarto.utils.resolve_path('_vendor/quarto-lua-modules/logging.lua'):gsub('%.lua$', ''))
local meta_mod = require(quarto.utils.resolve_path('_vendor/quarto-lua-modules/metadata.lua'):gsub('%.lua$', ''))
local pdoc = require(quarto.utils.resolve_path('_vendor/quarto-lua-modules/pandoc-helpers.lua'):gsub('%.lua$', ''))
local html_mod = require(quarto.utils.resolve_path('_vendor/quarto-lua-modules/html.lua'):gsub('%.lua$', ''))
local cell_output = require(quarto.utils.resolve_path('_modules/cell-output.lua'):gsub('%.lua$', ''))
local language = require(quarto.utils.resolve_path('_modules/language.lua'):gsub('%.lua$', ''))
local code_annotations = nil
local checker = nil
-- ============================================================================
-- DEFAULTS AND STATE
-- ============================================================================
--- @class CodeWindowConfig
--- @field enabled boolean Whether code-window styling is enabled
--- @field auto_filename boolean Whether to auto-generate filename from language
--- @field style string Window decoration style ('macos', 'windows', 'default')
--- @field cell_output boolean Whether the output of an executed cell is framed
--- @field typst_wrapper string Typst wrapper function name
--- @field hotfix_code_annotations boolean Whether to apply the code-annotations hot-fix for Typst
--- @field hotfix_skylighting boolean Whether to apply the Skylighting hot-fix for Typst
local VALID_STYLES = { ['default'] = true, ['macos'] = true, ['windows'] = true }
--- Prefix of every code block attribute this extension owns, the ones the
--- schema declares and the internal label the language module writes alike.
local ATTRIBUTE_PREFIX = 'code-window-'
--- Defaults for the two cases where the schema cannot answer: a format the
--- extension does not act on, where the check never runs, and a schema that
--- could not be read, which is a state this extension renders through rather
--- than stopping for. Everywhere else _schema.yml decides these seven, so the
--- values below are a fallback and not a second place to change one of them.
--- The hotfix defaults are a different story, and are still kept by hand in
--- HOTFIX_DEFAULTS: they are nested in the schema and read on their own path,
--- so changing one in _schema.yml alone still changes nothing.
--- All seven stay listed, because the second case has nothing else to read
--- from, and an option added to the schema needs an entry here as well or it
--- has no default at all on a format the extension does not act on.
--- Where the two disagree, the schema wins on html and typst, and a format
--- the extension does not act on reads "enabled" alone, which is the one that
--- chooses whether a block's attributes are checked. So keep that one in step
--- with the schema, and treat a difference in the other six as a thing to
--- correct rather than a thing that shows.
local FALLBACK_DEFAULTS = {
['enabled'] = 'true',
['auto-filename'] = 'true',
['style'] = 'macos',
['cell-output'] = 'false',
['wrapper'] = 'code-window',
['collapse'] = 'false',
['lines-label'] = 'true',
}
local VALID_COLLAPSE = {
['false'] = false,
['true'] = 'closed',
['closed'] = 'closed',
['open'] = 'open',
}
local HOTFIX_DEFAULTS = {
['code-annotations'] = true,
['skylighting'] = true,
}
local CURRENT_FORMAT = nil
local CONFIG = nil
local TYPST_BG_COLOUR = nil
local ANNOTATION_BLOCK_COUNTER = 0
-- ============================================================================
-- CELL OUTPUT
-- ============================================================================
--- Check whether the extension acts on the format being rendered. It draws
--- chrome for html, which covers Reveal.js, and for typst, and leaves every
--- other format as Quarto writes it.
--- @return boolean
local function acts_on_format()
return CURRENT_FORMAT == 'html' or CURRENT_FORMAT == 'typst'
end
--- Check whether this render draws chrome at all: the extension is on, and the
--- format is one it acts on. Every pass that exists only to serve the chrome
--- asks this before it does any work, so none of them has to carry its own
--- copy of the two conditions.
--- @return boolean
local function draws_chrome()
return CONFIG ~= nil and CONFIG.enabled and acts_on_format()
end
--- Check whether a block holds the output of an executed cell that the engine
--- did not name. Such a block keeps the shape Quarto gave it.
--- @param block pandoc.CodeBlock Code block element
--- @return boolean
local function is_unnamed_cell_output(block)
return cell_output.is_marked(block) and str.is_empty(block.attributes['filename'])
end
--- Check whether a block holds a chapter's front matter, which Quarto writes
--- in a book rendered to one file and later replaces with the title block.
--- @param block pandoc.CodeBlock Code block element
--- @return boolean
local function is_quarto_block(block)
return block.classes:includes('quarto-title-block')
end
-- ============================================================================
-- BLOCK-LEVEL STYLE OVERRIDE
-- ============================================================================
--- Turn a schema-resolved boolean back into the "true"/"false" string this
--- file's own comparisons already use. A value the schema rejects arrives
--- here unchanged (the original string the document wrote), and is passed
--- through as-is.
--- @param value any Resolved attribute value
--- @return any
local function stringify_bool(value)
if type(value) == 'boolean' then
return value and 'true' or 'false'
end
return value
end
--- Take the attributes an author can write off a block the filter processes,
--- and answer the label the language module wrote.
--- Pandoc writes an attribute nothing removes into the HTML as
--- data-code-window-*, so a block this filter ran on carries none of them
--- onward: one call per format path, above every early return, is what keeps
--- that true, and an attribute added to the schema later is covered with no
--- change here.
--- Two prefixed attributes are not author-written and are treated on their
--- own terms. code-window-auto-label is returned rather than dropped, because
--- the windowing paths still need its value. The cell-output marker is left
--- alone, because the Typst pass reads it after this runs, and the
--- cell-output module removes it itself.
--- The HTML path writes code-window-lines-label back afterwards, for the
--- injected script to read and remove in the browser.
--- @param block pandoc.CodeBlock Code block element
--- @return string|nil auto_label Label written by the language module, if any
local function take_block_attributes(block)
local auto_label = language.auto_label(block)
local owned = {}
for key, _ in pairs(block.attributes) do
if key:sub(1, #ATTRIBUTE_PREFIX) == ATTRIBUTE_PREFIX and not cell_output.is_marker(key) then
owned[#owned + 1] = key
end
end
for _, key in ipairs(owned) do
block.attributes[key] = nil
end
return auto_label
end
--- Resolve a block's attributes against the schema, then take this
--- extension's attributes off the block.
--- The resolved values are copied into a table of their own before anything
--- is removed. checker:attributes hands back the list it was given when it
--- has no schema to check against, which is a case this extension carries on
--- through by design, and the caller would then hold the block's live
--- attributes. Taking them off would empty the very table every reader below
--- reads, and each per-block override would be ignored with no warning.
--- @param block pandoc.CodeBlock Code block element
--- @return table<string, any> resolved What this block's attributes resolve to
--- @return string|nil auto_label Label written by the language module, if any
local function resolve_and_take(block)
local resolved = {}
for key, value in pairs(checker:attributes(block.attributes, 'CodeBlock')) do
resolved[key] = value
end
return resolved, take_block_attributes(block)
end
--- Read the block-level style override from code-window-style attribute.
--- Returns the validated style value or nil.
--- An unrecognised value is not warned about here: the schema check this
--- block's caller already ran (checker:attributes, group "CodeBlock") reports
--- the same mistake in its own words, and this file's own message added
--- nothing beyond restating the fallback, which the schema check's
--- documented policy ("no finding stops a render") already implies for every
--- attribute.
--- @param resolved table<string, any> This block's attributes, resolved against the schema
--- @return string|nil Style override value
local function read_block_style(resolved)
local block_style = resolved['code-window-style']
if not block_style or block_style == '' then
return nil
end
if type(block_style) == 'string' and VALID_STYLES[block_style] then
return block_style
end
return nil
end
--- Resolve a collapse value coming from extension options or a code-block
--- attribute. Returns "open"/"closed" when the window should be collapsible,
--- nil when collapsing is off or the value is unrecognised.
--- Both callers are now covered by a schema check that reports an
--- unrecognised value in its own words: the "collapse" document option by
--- checker:options (Meta, below), and the "code-window-collapse" block
--- attribute by checker:attributes on the "CodeBlock" group
--- (read_block_collapse, below). This function used to warn again for both,
--- restating the same enum with no remedy, legal alternative, or
--- format-specific consequence the schema message lacks, so neither call
--- site asks for it any more.
--- raw is never a Lua boolean here, for either caller: the "collapse"
--- document option is read through meta_mod.get_options, which always
--- stringifies, and "code-window-collapse" declares type: string in
--- _schema.yml (not a [boolean, string] union), specifically because a
--- Pandoc attribute value is always a string, so a union type paired with
--- an enum holding an unquoted true/false can never match it: `_coerce`
--- returns a value unchanged as soon as its current Lua type already
--- matches a member of the declared type list, so the string always wins
--- and boolean coercion is never attempted, which made the enum check
--- compare the string "true" against the schema's own boolean `true` and
--- fail on every legal value. No stringify step is needed on this path.
--- @param raw string|nil Raw collapse value
--- @return string|nil Resolved collapse mode ("open"/"closed") or nil
local function resolve_collapse(raw)
if raw == nil or raw == '' then
return nil
end
local resolved = VALID_COLLAPSE[raw]
if resolved == nil then
return nil
end
if resolved == false then
return nil
end
return resolved
end
--- Read the per-block collapse override from code-window-collapse attribute.
--- code-window-collapse layers over the "collapse" document option
--- (CONFIG.collapse), which is the reason it must not be read with a bare
--- "or": a resolved boolean false has to reach resolve_collapse and disable
--- collapsing, not fall through to the document option. The schema declares
--- no default for this attribute, so the merged table already answers nil
--- exactly when the document left it unwritten, with no separate presence
--- test needed.
--- @param resolved table<string, any> This block's attributes, resolved against the schema
--- @return string|nil Resolved collapse mode ("open"/"closed") or nil when off
--- @return boolean Whether this block decided, which is what separates an
--- explicit "false" from an attribute the block never wrote
local function read_block_collapse(resolved)
local raw = resolved['code-window-collapse']
if raw == nil then
return nil, false
end
local mode = VALID_COLLAPSE[raw]
if mode == nil then
-- A value the schema does not accept. The check reports it, and the
-- document option decides as though the block had written nothing.
return nil, false
end
return mode or nil, true
end
--- Read a highlight-lines spec from the block, looking at the
--- code-window-lines attribute first and falling back to Quarto's
--- code-line-numbers attribute when it carries a non-boolean spec.
--- Returns the cleaned spec string or nil.
--- The "lines-label" option is answered here rather than at each call site,
--- so neither format path repeats the test. code-line-numbers belongs to
--- Quarto and is read, never written.
--- @param block pandoc.CodeBlock Code block element
--- @param resolved table<string, any> This block's attributes, resolved against the schema
--- @return string|nil Line spec to display in the title bar
local function read_block_lines_label(block, resolved)
if not CONFIG.lines_label then
return nil
end
local raw = resolved['code-window-lines']
if raw ~= nil and raw ~= '' then
return raw
end
local cln = block.attributes['code-line-numbers']
if not cln or cln == '' or cln == 'true' or cln == 'false' then
return nil
end
return cln
end
--- @class WindowOverrides
--- @field enabled boolean Whether this block asks for chrome at all
--- @field style string|nil Style this block asks for, in place of the document's
--- @field lines_label string|nil Highlighted-lines spec for the title bar
--- @field no_auto_filename boolean Whether this block refuses a derived name
--- Read what a block asks of the chrome, in the order and the way both format
--- paths ask for it. Collapse is left out, because it is the one override that
--- is HTML only and the Typst path never reads.
--- code-window-enabled declares default: true, and code-window-no-auto-filename
--- declares default: false, each matching this file's own fallback. Neither
--- layers over a document option, so the resolved value answers directly, and
--- the stringified value decides the flag, which is what makes an explicit
--- "false" behave like absence rather than like "true".
--- All four are lookups on the resolved table and on the block, and take
--- nothing off the block, which take_block_attributes already did. So a caller
--- may read them all before it tests the opt-out, and their order is free.
--- @param block pandoc.CodeBlock Code block element
--- @param resolved table<string, any> This block's attributes, resolved against the schema
--- @return WindowOverrides
local function read_window_overrides(block, resolved)
return {
enabled = stringify_bool(resolved['code-window-enabled']) ~= 'false',
style = read_block_style(resolved),
lines_label = read_block_lines_label(block, resolved),
no_auto_filename = stringify_bool(resolved['code-window-no-auto-filename']) == 'true',
}
end
-- ============================================================================
-- TYPST FUNCTION DEFINITION
-- ============================================================================
--- Typst colour helpers for adaptive theme support, and the theme state.
--- Always injected so the code-window function can derive border, surface,
--- muted, and label colours from the page background at render time.
--- A template sets state("code-window-theme") to replace any derived value;
--- the state is keyed by name, so the template needs none of these helpers.
local TYPST_COLOUR_HELPERS = [==[
// code-window: theme tokens that a template sets before the body
#let _cw-theme = state("code-window-theme", (:))
// the colour keys (border, surface, label, muted) derive from the page fill
#let _cw-theme-defaults = (
radius: 8pt,
stroke-thickness: 1pt,
stroke-dash: none,
title-inset: (x: 1em, y: 0.6em),
body-inset: 8pt,
traffic-light-size: 0.85em,
traffic-light-gap: 0.425em,
traffic-light-colours: (rgb("#ff5f56"), rgb("#ffbd2e"), rgb("#27c93f")),
)
// the inset of a code block: the theme's body-inset inside a window
#let _cw-body-inset = state("cw-body-inset", _cw-theme-defaults.body-inset)
// code-window: adaptive colour helpers (derive UI tones from page background)
#let _cw-page-bg() = {
let f = page.fill
if type(f) == color { f } else { luma(255) }
}
#let _cw-fg(bg) = {
let comps = bg.components(alpha: false)
let lum = if comps.len() == 1 {
comps.at(0) / 100%
} else {
0.2126 * comps.at(0) / 100% + 0.7152 * comps.at(1) / 100% + 0.0722 * comps.at(2) / 100%
}
if lum < 0.5 { luma(255) } else { luma(0) }
}
]==]
--- Typst annotation helper functions (state, colour, circled numbers, annotation items).
--- Only injected when at least one hot-fix is active.
local TYPST_ANNOTATION_DEF = [==[
// code-window: annotation state passed to Skylighting via Typst state
#let _cw-annotations = state("cw-annotations", none)
// Derive a contrasting annotation colour from a background fill.
// Light backgrounds get dark circles; dark backgrounds get light circles.
// Uses ITU-R BT.709 luminance coefficients, matching quarto-cli PR #14170.
#let code-window-annote-colour(bg) = {
if type(bg) == color {
let comps = bg.components(alpha: false)
let lum = if comps.len() == 1 {
comps.at(0) / 100%
} else {
0.2126 * comps.at(0) / 100% + 0.7152 * comps.at(1) / 100% + 0.0722 * comps.at(2) / 100%
}
if lum < 0.5 { luma(200) } else { luma(60) }
} else {
luma(60)
}
}
#let code-window-circled-number(n, bg-colour: none) = {
let c = if bg-colour != none { code-window-annote-colour(bg-colour) } else { luma(120) }
box(baseline: 20%, circle(
radius: 4.5pt,
stroke: 0.5pt + c,
)[#set text(size: 5.5pt, fill: c); #align(center + horizon, str(n))])
}
#let code-window-annotation-item(block-id, n, content) = {
let lbl-prefix = "cw-" + str(block-id) + "-"
context {
let target = label(lbl-prefix + "line-" + str(n))
let has-target = query(target).len() > 0
[#block(above: 0.4em, below: 0.4em)[
#if has-target {
link(target)[#code-window-circled-number(n)]
} else {
code-window-circled-number(n)
}
#h(0.4em)
#content
] #label(lbl-prefix + "item-" + str(n))]
}
}
#let code-window-annotated-content(content, annotations: (:), bg-colour: none, block-id: 0) = {
if annotations.len() > 0 {
_cw-annotations.update((annotations: annotations, bg-colour: bg-colour, block-id: block-id))
content
_cw-annotations.update(none)
} else {
content
}
}
]==]
--- Typst code-window body content template.
--- Uses annotation wrapper when hot-fixes are active, plain content otherwise.
local TYPST_CONTENT_WITH_ANNOTATIONS = [==[
code-window-annotated-content(
content,
annotations: annotations,
bg-colour: bg-colour,
block-id: block-id,
)
]==]
local TYPST_CONTENT_PLAIN = [==[
content
]==]
--- Build the complete Typst code-window function definition.
--- @param has_hotfixes boolean Whether at least one hot-fix is active
--- @param has_own_wrapper boolean Whether the document defines the wrapper itself
--- @return string Typst function definition(s)
local function build_typst_function_def(has_hotfixes, has_own_wrapper)
local content_block = has_hotfixes
and TYPST_CONTENT_WITH_ANNOTATIONS
or TYPST_CONTENT_PLAIN
local fn_def = string.format([==[
#let code-window(
content,
filename: none,
is-auto: false,
style: "macos",
annotations: (:),
bg-colour: none,
block-id: 0,
lines-label: none,
) = {
context {
let page-bg = _cw-page-bg()
let fg = _cw-fg(page-bg)
let defaults = _cw-theme-defaults + (
border: color.mix((fg, 15%%), (page-bg, 85%%)),
surface: color.mix((fg, 5%%), (page-bg, 95%%)),
label: color.mix((fg, 65%%), (page-bg, 35%%)),
muted: color.mix((fg, 50%%), (page-bg, 50%%)),
)
let theme = _cw-theme.get()
for key in theme.keys() {
if key not in defaults {
panic("code-window: unknown key \"" + key + "\" in state(\"code-window-theme\"). "
+ "Known keys: " + defaults.keys().join(", ") + ".")
}
}
let theme = defaults + theme
let border-colour = theme.border
let muted-colour = theme.muted
let label-colour = theme.label
let window-stroke = (
paint: border-colour,
thickness: theme.stroke-thickness,
dash: theme.stroke-dash,
)
let filename-label = if filename != none {
text(
size: if is-auto { 0.7em } else { 0.85em },
weight: 500,
fill: label-colour,
if is-auto { upper(filename) } else { filename },
)
}
let lines-chip = if lines-label != none {
box(
inset: (x: 0.4em, y: 0.05em),
outset: (y: 0.15em),
radius: 3pt,
fill: color.mix((fg, 10%%), (page-bg, 90%%)),
stroke: 0.5pt + border-colour,
text(size: 0.7em, weight: 500, fill: label-colour, lines-label),
)
}
let traffic-lights = box(
inset: (right: 0.5em),
stack(
dir: ltr,
spacing: theme.traffic-light-gap,
..theme.traffic-light-colours.map(c => circle(radius: theme.traffic-light-size / 2, fill: c, stroke: none)),
),
)
let window-buttons = box(
inset: (left: 0.5em),
{
set line(stroke: 1pt + muted-colour)
stack(
dir: ltr,
spacing: 0.8em,
// Minimise (horizontal line)
box(width: 0.6em, height: 0.6em, align(horizon, line(length: 100%%))),
// Maximise (square)
box(width: 0.6em, height: 0.6em, stroke: 1pt + muted-colour),
// Close (x)
box(width: 0.6em, height: 0.6em, {
place(line(start: (0%%, 0%%), end: (100%%, 100%%)))
place(line(start: (100%%, 0%%), end: (0%%, 100%%)))
}),
)
},
)
let _label-with-chip = if lines-chip != none {
stack(dir: ltr, spacing: 0.5em, filename-label, lines-chip)
} else {
filename-label
}
let title-bar = if style == "macos" {
grid(
columns: (auto, 1fr),
align: (left + horizon, right + horizon),
gutter: 0.5em,
stroke: 0pt,
traffic-lights,
_label-with-chip,
)
} else if style == "windows" {
grid(
columns: (1fr, auto),
align: (left + horizon, right + horizon),
gutter: 0.5em,
stroke: 0pt,
_label-with-chip,
window-buttons,
)
} else {
// default: plain filename, left-aligned
_label-with-chip
}
block(
width: 100%%,
stroke: window-stroke,
radius: theme.radius,
clip: true,
{
block(
width: 100%%,
fill: theme.surface,
inset: theme.title-inset,
below: 0pt,
radius: 0pt,
stroke: (bottom: window-stroke),
sticky: true,
title-bar,
)
// Strip code block chrome so content fills flush against the window body.
// set block() provides defaults for Skylighting blocks (explicit fill preserved).
// show raw overrides the document-level raw block styling (fill, radius).
{
set block(
width: 100%%,
inset: theme.body-inset,
radius: 0pt,
stroke: none,
above: 0pt,
below: 0pt,
)
show raw.where(block: true): set block(
fill: none,
width: 100%%,
radius: 0pt,
stroke: none,
above: 0pt,
below: 0pt,
)
_cw-body-inset.update(theme.body-inset)
%s _cw-body-inset.update(_cw-theme-defaults.body-inset)
}
},
)
}
}
]==], content_block)
local result = TYPST_COLOUR_HELPERS
-- A document's own wrapper calls the annotation helper to show annotations,
-- so the helper is written for it whatever the hot-fixes say.
if has_hotfixes or has_own_wrapper then
result = result .. TYPST_ANNOTATION_DEF
end
if has_own_wrapper then
return result
end
return result .. fn_def
end
-- ============================================================================
-- TYPST PROCESSING
-- ============================================================================
--- Get the next unique block ID for annotation linking.
--- @return integer
local function next_block_id()
ANNOTATION_BLOCK_COUNTER = ANNOTATION_BLOCK_COUNTER + 1
return ANNOTATION_BLOCK_COUNTER
end
--- Build the Typst bg-colour parameter string.
--- @return string Empty string or ', bg-colour: rgb("...")'
local function typst_bg_colour_param()
if not TYPST_BG_COLOUR then
return ''
end
return string.format(', bg-colour: rgb("%s")', TYPST_BG_COLOUR)
end
--- Escape a string for embedding in a Typst double-quoted string literal.
--- @param s string
--- @return string
local function typst_escape_string(s)
return (s:gsub('\\', '\\\\'):gsub('"', '\\"'))
end
--- Build a code-window opening RawBlock for Typst.
--- @param filename string
--- @param is_auto boolean
--- @param style string
--- @param annotations table|nil
--- @param block_id integer
--- @param lines_label string|nil Highlighted-lines spec to display in the title bar
--- @return pandoc.RawBlock
local function typst_code_window_open(filename, is_auto, style, annotations, block_id, lines_label)
local annot_param = ''
if annotations and next(annotations) then
annot_param = string.format(', annotations: %s, block-id: %d',
code_annotations.annotations_to_typst_dict(annotations), block_id)
end
local lines_param = ''
if lines_label and lines_label ~= '' then
lines_param = string.format(', lines-label: "%s"', typst_escape_string(lines_label))
end
return pandoc.RawBlock('typst', string.format(
'#%s(filename: "%s", is-auto: %s, style: "%s"%s%s%s)[',
CONFIG.typst_wrapper,
typst_escape_string(filename),
is_auto and 'true' or 'false',
style,
annot_param,
typst_bg_colour_param(),
lines_param
))
end
--- Build a standalone annotation wrapper for non-windowed blocks.
--- @param annotations table
--- @param block_id integer
--- @return pandoc.RawBlock opening, pandoc.RawBlock closing
local function typst_annotation_wrapper(annotations, block_id)
local open = pandoc.RawBlock('typst', string.format(
'#%s-annotated-content(annotations: %s, block-id: %d%s)[',
CONFIG.typst_wrapper,
code_annotations.annotations_to_typst_dict(annotations),
block_id,
typst_bg_colour_param()
))
local close = pandoc.RawBlock('typst', ']')
return open, close
end
-- ============================================================================
-- HTML PROCESSING
-- ============================================================================
--- Process CodeBlock for HTML/Reveal.js formats.
--- Explicit-filename blocks are returned for Quarto to wrap; a marker class
--- is added when a block-level style override is present.
--- Auto-filename blocks are returned inside the window node Quarto builds for
--- an explicit filename, so the title bar is in the rendered page.
--- The block reaches here with its code-window attributes already taken off
--- by take_block_attributes, so every value below is read from the resolved
--- table and the block carries none of them onward.
--- @param block pandoc.CodeBlock Code block element
--- @param resolved table<string, any> This block's attributes, resolved against the schema
--- @param auto_label string|nil Label written by the language module, if any
--- @return pandoc.Block DecoratedCodeBlock or original block
local function process_html(block, resolved, auto_label)
local overrides = read_window_overrides(block, resolved)
-- Per-block opt-out: code-window-enabled="false" skips window chrome.
if not overrides.enabled then
return block
end
local block_collapse, block_decided = read_block_collapse(resolved)
local effective_collapse = block_collapse
if not block_decided then
effective_collapse = CONFIG.collapse
end
local explicit_filename = block.attributes['filename']
-- Add the marker classes and the chip the injected script reads. Both
-- branches below end this way, on the same block this closure captures.
local function mark()
if overrides.style then
table.insert(block.classes, 'cw-style-' .. overrides.style)
end
-- A block that turned collapsing off is marked as well. The script reads
-- the absence of a marker as "this block said nothing" and falls back to
-- the document setting, so an opt-out needs a marker of its own.
if effective_collapse then
table.insert(block.classes, 'cw-collapse-' .. effective_collapse)
elseif block_decided and CONFIG.collapse then
table.insert(block.classes, 'cw-collapse-none')
end
if overrides.lines_label then
block.attributes['code-window-lines-label'] = overrides.lines_label
end
end
-- Quarto builds a window for any filename attribute, an empty one included,
-- so a block that carries one is already inside a window.
if explicit_filename ~= nil then
-- Let Quarto create the .code-with-filename wrapper, and mark the block so
-- the injected script can promote a block-level override onto that wrapper.
mark()
return block
end
if overrides.no_auto_filename or not (auto_label or CONFIG.auto_filename) then
return block
end
-- Blocks with a language of their own are labelled with its class.
-- Quarto turns a filename into its window node while it reads the document,
-- before this filter runs, so a filename set here would come too late. The
-- filter builds the same node instead. Quarto then renders the title bar as
-- for an explicit filename, and its code-annotations processor still finds
-- the CodeBlock and the OrderedList side by side. The cw-auto class tells the
-- post-render pass which windows hold a derived name. The filename
-- attribute stays as well, so the page carries data-filename like a block
-- with an explicit name.
local label = auto_label or block.classes[1]
block.attributes['filename'] = label
table.insert(block.classes, 'cw-auto')
mark()
return quarto.DecoratedCodeBlock({ filename = label, code_block = block })
end
-- ============================================================================
-- FILTER HANDLERS
-- ============================================================================
--- Generate a JS snippet that applies the configured default style class to
--- all .code-with-filename wrappers,
--- promotes block-level cw-style-* / cw-collapse-* marker classes, inserts
--- a highlighted-lines chip when data-code-window-lines-label is set on the inner
--- pre, and wraps collapsible windows in a <details> element where the
--- title bar acts as the <summary>.
--- @param default_style string The configured default style
--- @param default_collapse string|nil Default collapse mode ("open"/"closed"/nil)
--- @return string JavaScript code
local function make_style_js(default_style, default_collapse)
local default_collapse_js = default_collapse and ('"' .. default_collapse .. '"') or 'null'
return string.format([=[
document.addEventListener("DOMContentLoaded",function(){
var DEFAULT_COLLAPSE=%s;
function findMarkerSource(el){
return el.querySelector('pre[class*="cw-style-"],pre[class*="cw-collapse-"],pre[data-code-window-lines-label]')
||el.querySelector('[class*="cw-style-"],[class*="cw-collapse-"],[data-code-window-lines-label]');
}
document.querySelectorAll(".code-with-filename").forEach(function(el){
var marker=findMarkerSource(el);
var styleApplied=/\bcode-window-(macos|windows|default)\b/.test(el.className);
if(!styleApplied){
var sm=marker&&marker.className.match(/cw-style-(\w+)/);
if(sm){el.classList.add("code-window-"+sm[1]);marker.classList.remove(sm[0]);}
else{el.classList.add("code-window-%s");}
}
var collapse=null;
if(marker){
var cm=marker.className.match(/cw-collapse-(open|closed|none)/);
if(cm){collapse=cm[1]==='none'?false:cm[1];marker.classList.remove(cm[0]);}
}
if(collapse===null&&DEFAULT_COLLAPSE){collapse=DEFAULT_COLLAPSE;}
if(marker&&marker.hasAttribute("data-code-window-lines-label")){
var spec=marker.getAttribute("data-code-window-lines-label");
marker.removeAttribute("data-code-window-lines-label");
var titleBar=el.querySelector(".code-with-filename-file");
if(titleBar&&!titleBar.querySelector(".code-with-filename-lines")){
var chip=document.createElement("span");
chip.className="code-with-filename-lines";
chip.textContent="L"+spec.replace(/,/g,",\u200B");
titleBar.appendChild(chip);
}
}
if(collapse&&!el.classList.contains("code-window-collapsible")){
var titleBar=el.querySelector(".code-with-filename-file");
if(titleBar){
var details=document.createElement("details");
details.className=el.className+" code-window-collapsible";
if(collapse==="open"){details.open=true;}
var summaryEl=document.createElement("summary");
summaryEl.className="code-with-filename-file";
while(titleBar.firstChild){summaryEl.appendChild(titleBar.firstChild);}
titleBar.parentNode.removeChild(titleBar);
details.appendChild(summaryEl);
while(el.firstChild){details.appendChild(el.firstChild);}
el.parentNode.replaceChild(details,el);
}
}
});
});]=], default_collapse_js, default_style)
end
--- Load configuration and inject CSS/JS dependencies.
function Meta(meta)
CURRENT_FORMAT = pdoc.get_quarto_format()
-- This is the pass that reads the configuration, so the check runs here,
-- before the first option is read. An option the check rejects is still
-- read below, because the report says what the extension cannot use and the
-- document renders either way. Only a format the extension acts on reports,
-- because nothing it could say applies anywhere else.
-- The check also answers what the schema declares each option defaults to,
-- so those values are kept rather than dropped and rebuilt by hand here.
-- They arrive typed, and every comparison below reads a string, so each one
-- goes through stringify_bool on the way into the table.
local schema_defaults = {}
if acts_on_format() then
schema_defaults = checker:options(meta)
end
-- The schema is read first and the fallback fills only what it leaves
-- unanswered, so on html and typst an option added to _schema.yml and to the
-- key list below needs nothing more. Anywhere else the check above never
-- runs, so the same option also needs an entry in FALLBACK_DEFAULTS or it
-- has no default there. Reading the fallback first would have made it the
-- list of options allowed to have a default at all, on every format, which
-- is the coupling this change exists to remove. What arrives is one entry
-- per option that declares a default of its own, and get_options reads only
-- the keys named below.
local defaults = {}
for key, declared in pairs(schema_defaults) do
defaults[key] = stringify_bool(declared)
end
for key, fallback in pairs(FALLBACK_DEFAULTS) do
if defaults[key] == nil then
defaults[key] = fallback
end
end
local opts = meta_mod.get_options({
extension = EXTENSION_NAME,
keys = {
'enabled', 'auto-filename', 'style', 'cell-output', 'wrapper', 'collapse', 'lines-label',
},
meta = meta,
defaults = defaults,
})
-- checker:options (above) already reports an unrecognised "style" value in
-- its own words; this used to warn again with no remedy, legal
-- alternative, or format-specific consequence the schema message lacks
-- (the same shape already removed for "collapse"), so it is silent here.
-- The fallback (VALID_STYLES[opts['style']] and opts['style'] or 'macos',
-- below in CONFIG) is unchanged.
local global_collapse = resolve_collapse(opts['collapse'])
-- Read code-annotations metadata (Quarto standard option).
local annot_meta = meta['code-annotations']
local annot_value = annot_meta and pandoc.utils.stringify(annot_meta) or ''
local annotations_enabled = annot_value ~= 'none' and annot_value ~= 'false'
-- Read hotfix sub-table from extensions.code-window.hotfix.
local ext_config = meta_mod.get_extension_config(meta, EXTENSION_NAME)
local hotfix_meta = ext_config and ext_config['hotfix'] or nil
-- Deprecation check for old flat skylighting-fix key.
if ext_config and ext_config['skylighting-fix'] ~= nil then
log.log_warning(EXTENSION_NAME,
'"skylighting-fix" is deprecated. Use "hotfix: { skylighting: true/false }" instead.')
end
-- Parse hotfix options with per-hotfix version-based auto-disable.
-- Each hotfix value can be:
-- boolean/string: true/false to enable/disable
-- map: { enabled: true/false, quarto-version: "x.y.z" }
local hotfix = {}
for key, default in pairs(HOTFIX_DEFAULTS) do
local entry = hotfix_meta and hotfix_meta[key]
if entry ~= nil and pandoc.utils.type(entry) == 'table' then
-- Map form: { enabled: bool, quarto-version: "x.y.z" }
local enabled = true
if entry['enabled'] ~= nil then
enabled = pandoc.utils.stringify(entry['enabled']) == 'true'
end
local ver = entry['quarto-version']
if ver then
ver = pandoc.utils.stringify(ver)
if ver ~= '' then
local ok, threshold = pcall(pandoc.types.Version, ver)
if ok and quarto.version >= threshold then
enabled = false
end
end
end
hotfix[key] = enabled
elseif entry ~= nil then
-- Simple boolean/string form
hotfix[key] = pandoc.utils.stringify(entry) == 'true'
else
hotfix[key] = default
end
end
CONFIG = {
enabled = opts['enabled'] == 'true',
auto_filename = opts['auto-filename'] == 'true',
style = VALID_STYLES[opts['style']] and opts['style'] or 'macos',
cell_output = opts['cell-output'] == 'true',
typst_wrapper = opts['wrapper'],
collapse = global_collapse,
lines_label = opts['lines-label'] == 'true',
hotfix_code_annotations = hotfix['code-annotations'],
hotfix_skylighting = hotfix['skylighting'],
code_annotations = annotations_enabled,
}
-- Cache syntax highlighting background colour for Typst contrast-aware annotations.
if CURRENT_FORMAT == 'typst' then
local hm = PANDOC_WRITER_OPTIONS and PANDOC_WRITER_OPTIONS.highlight_method
if hm then
local bg = hm['background-color']
if bg and type(bg) == 'string' then
TYPST_BG_COLOUR = bg
end
end
end
if CURRENT_FORMAT == 'html' and CONFIG.enabled then
html_mod.ensure_html_dependency({
name = EXTENSION_NAME,
stylesheets = { 'style.css' },
})
html_mod.ensure_html_dependency({
name = EXTENSION_NAME .. '-style-init',
head = '<script>' .. make_style_js(CONFIG.style, CONFIG.collapse) .. '</script>',
})
end
return meta
end
--- Process CodeBlock elements for HTML/Reveal.js only.
--- Typst processing is handled by the Blocks filter.
--- This handler runs on every CodeBlock structurally, for every format,
--- because a plain `CodeBlock` filter entry is not format-scoped the way
--- CONFIG.enabled or CURRENT_FORMAT are. For a Typst render, the same block
--- is already checked once by process_typst_block through the Pandoc filter
--- above it in main.lua's filter list, so checker:attributes is called here
--- only in the two branches that do not overlap with that pass: the
--- disabled/unconfigured branch (where the Typst pass never runs at all,
--- because Pandoc() returns before reaching it) and the html branch (where
--- the Typst pass never runs either, because it is typst-only). Calling it