-
Notifications
You must be signed in to change notification settings - Fork 2
/
shortcodes.lua
944 lines (812 loc) · 23.9 KB
/
shortcodes.lua
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
-- shortcodes.lua
-- Copyright (C) 2020 by RStudio, PBC
-- actively prevent running in quarto (as all of this is already included there)
if os.getenv("QUARTO_FILTER_PARAMS") ~= nil then
io.stderr:write("ERROR: shortcodes.lua should not be used within quarto " ..
"(quarto already includes an identical implementation)")
os.exit(1)
end
-------- debug helpers --------
-- improved formatting for dumping tables
local function tdump (tbl, indent)
if not indent then indent = 0 end
if tbl.t then
print(string.rep(" ", indent) .. tbl.t)
end
for k, v in pairs(tbl) do
formatting = string.rep(" ", indent) .. k .. ": "
if type(v) == "table" then
print(formatting)
tdump(v, indent+1)
elseif type(v) == 'boolean' then
print(formatting .. tostring(v))
elseif (v ~= nil) then
print(formatting .. tostring(v))
else
print(formatting .. 'nil')
end
end
end
-- dump an object to stdout
local function dump(o)
if type(o) == 'table' then
tdump(o)
else
print(tostring(o) .. "\n")
end
end
-------- table helpers --------
-- slice elements out of a table
local function tslice(t, first, last, step)
local sliced = {}
for i = first or 1, last or #t, step or 1 do
sliced[#sliced+1] = t[i]
end
return sliced
end
-- append values to table
local function tappend(t, values)
for i,value in pairs(values) do
table.insert(t, value)
end
end
-- does the table contain a value
local function tcontains(t,value)
if t and type(t)=="table" and value then
for _, v in ipairs (t) do
if v == value then
return true
end
end
return false
end
return false
end
-- is the table a simple array?
-- see: https://web.archive.org/web/20140227143701/http://ericjmritz.name/2014/02/26/lua-is_array/
local function tisarray(t)
local i = 0
for _ in pairs(t) do
i = i + 1
if t[i] == nil then return false end
end
return true
end
local function filter(list, test)
local result = {}
for index, value in ipairs(list) do
if test(value, index) then
result[#result + 1] = value
end
end
return result
end
-------- string helpers --------
-- tests whether a string ends with another string
local function endsWith(str, ending)
return ending == "" or str:sub(-#ending) == ending
end
local function startsWith(str, starting)
return starting == "" or str:sub(1, #starting) == starting
end
-- splits a string on a separator
local function split(str, sep)
local fields = {}
local sep = sep or " "
local pattern = string.format("([^%s]+)", sep)
string.gsub(str, pattern, function(c) fields[#fields + 1] = c end)
return fields
end
local function trimEmpty(contents)
local firstNonEmpty = 1
for i, el in ipairs(contents) do
if el.t == "Str" and el.text == "" then
firstNonEmpty = firstNonEmpty + 1
else
break
end
end
if firstNonEmpty > 1 then
contents = tslice(contents, firstNonEmpty, #contents)
end
local lastNonEmptyEl = nil
for i = #contents, 1, -1 do
el = contents[i]
if el.t == "Str" and el.text == "" then
contents = tslice(contents, 1, #contents - 1)
else
break
end
end
return contents
end
-------- pandoc helpers --------
-- list of inlines to string
local function inlinesToString(inlines)
return pandoc.utils.stringify(pandoc.Span(inlines))
end
-- lua string with markdown to pandoc inlines
local function markdownToInlines(str)
if str then
local doc = pandoc.read(str)
return doc.blocks[1].content
else
return nil
end
end
local kBlockTypes = {
"BlockQuote",
"BulletList",
"CodeBlock ",
"DefinitionList",
"Div",
"Header",
"HorizontalRule",
"LineBlock",
"Null",
"OrderedList",
"Para",
"Plain",
"RawBlock",
"Table"
}
local function isBlockEl(el)
return tcontains(kBlockTypes, el.t)
end
local function isInlineEl(el)
return not isBlockEl(el)
end
local function trimEmpty(contents)
local firstNonEmpty = 1
for i, el in ipairs(contents) do
if el.t == "Str" and el.text == "" then
firstNonEmpty = firstNonEmpty + 1
else
break
end
end
if firstNonEmpty > 1 then
contents = tslice(contents, firstNonEmpty, #contents)
end
local lastNonEmptyEl = nil
for i = #contents, 1, -1 do
el = contents[i]
if el.t == "Str" and el.text == "" then
contents = tslice(contents, 1, #contents - 1)
else
break
end
end
return contents
end
-------- option handling --------
local allOptions = {} -- read from Meta during init
local function readMetaOptions(meta)
local options = {}
for key,value in pairs(meta) do
if type(value) == "table" and value.clone ~= nil then
options[key] = value:clone()
else
options[key] = value
end
end
return options
end
-- get option value
local function readOption(options, name, default)
local value = options[name]
if value == nil then
value = default
end
if type(value) == "table" and value.clone ~= nil then
return value:clone()
else
return value;
end
end
-- parse option from . delimited name
local function parseOption(name, options, def)
local keys = split(name, ".")
local value = nil
for i, key in ipairs(keys) do
if value == nil then
value = readOption(options, key, nil)
else
value = value[key]
-- the key doesn't match a value, stop indexing
if value == nil then
break
end
end
end
if value == nil then
return def
else
return value
end
end
-- get option value
local function option(name, def)
return parseOption(name, allOptions, def)
end
-------- shortcode handlers --------
local function shortcodeMetatable(scriptFile)
return {
-- https://www.lua.org/manual/5.3/manual.html#6.1
assert = assert,
collectgarbage = collectgarbage,
dofile = dofile,
error = error,
getmetatable = getmetatable,
ipairs = ipairs,
load = load,
loadfile = loadfile,
next = next,
pairs = pairs,
pcall = pcall,
print = print,
rawequal = rawequal,
rawget = rawget,
rawlen = rawlen,
rawset = rawset,
select = select,
setmetatable = setmetatable,
tonumber = tonumber,
tostring = tostring,
type = type,
_VERSION = _VERSION,
xpcall = xpcall,
coroutine = coroutine,
require = require,
package = package,
string = string,
utf8 = utf8,
table = table,
math = math,
io = io,
file = file,
os = os,
debug = debug,
-- https://pandoc.org/lua-filters.html
FORMAT = FORMAT,
PANDOC_READER_OPTIONS = PANDOC_READER_OPTIONS,
PANDOC_WRITER_OPTIONS = PANDOC_WRITER_OPTIONS,
PANDOC_VERSION = PANDOC_VERSION,
PANDOC_API_VERSION = PANDOC_API_VERSION,
PANDOC_SCRIPT_FILE = scriptFile,
PANDOC_STATE = PANDOC_STATE,
pandoc = pandoc,
lpeg = lpeg,
re = re,
-- extra helpers
dump = dump
}
end
local handlers = {}
local function initShortcodeHandlers(shortcodeFiles)
-- user provided handlers
for _,shortcodeFile in ipairs(shortcodeFiles) do
local file = inlinesToString(shortcodeFile)
local env = setmetatable({}, {__index = shortcodeMetatable(file)})
local chunk, err = loadfile(file, "bt", env)
if not err then
local result = chunk()
if result then
for k,v in pairs(result) do
handlers[k] = v
end
else
for k,v in pairs(env) do
handlers[k] = v
end
end
else
io.stderr:write(err .. "\n")
os.exit(1)
end
end
-- built in handlers (these override any user handlers)
handlers['meta'] = handleMeta
handlers['env'] = handleEnv
handlers['pagebreak'] = handlePagebreak
end
local function handlerForShortcode(shortCode)
return handlers[shortCode.name]
end
-- call a handler w/ args & kwargs
local function callShortcodeHandler(handler, shortCode)
local args = pandoc.List()
local kwargs = setmetatable({}, { __index = function () return pandoc.Inlines({}) end })
for _,arg in ipairs(shortCode.args) do
if arg.name then
kwargs[arg.name] = arg.value
else
args:insert(arg.value)
end
end
local meta = setmetatable({}, { __index = function(t, i)
return readMetadata(i)
end})
return handler(args, kwargs, meta)
end
-------- shortcode processing --------
-- The open and close shortcode indicators
local kOpenShortcode = "{{<"
local kOpenShortcodeEscape = "/*"
local kCloseShortcode = ">}}"
local kCloseShortcodeEscape = "*/"
-- processes inlines into a shortcode data structure
local function processShortCode(inlines)
local kSep = "="
local shortCode = nil
local args = pandoc.List()
-- slice off the open and close tags
inlines = tslice(inlines, 2, #inlines - 1)
-- handling for names with accompanying values
local pendingName = nil
notePendingName = function(el)
pendingName = el.text:sub(1, -2)
end
-- Adds an argument to the args list (either named or unnamed args)
insertArg = function(argInlines)
if pendingName ~= nil then
-- there is a pending name, insert this arg
-- with that name
args:insert(
{
name = pendingName,
value = argInlines
})
pendingName = nil
else
-- split the string on equals
if #argInlines == 1 and argInlines[1].t == "Str" and string.match(argInlines[1].text, kSep) then
-- if we can, split the string and assign name / value arg
-- otherwise just put the whole thing in unnamed
local parts = split(argInlines[1].text, kSep)
if #parts == 2 then
args:insert(
{
name = parts[1],
value = stringToInlines(parts[2])
})
else
args:insert(
{
value = argInlines
})
end
else
-- this is an unnamed argument
args:insert(
{
value = argInlines
})
end
end
end
-- The core loop
for i, el in ipairs(inlines) do
if el.t == "Str" then
if shortCode == nil then
-- the first value is a pure text code name
shortCode = el.text
else
-- if we've already captured the code name, proceed to gather args
if endsWith(el.text, kSep) then
-- this is the name of an argument
notePendingName(el)
else
-- this is either an unnamed arg or an arg value
insertArg({el})
end
end
elseif el.t == "Quoted" then
-- this is either an unnamed arg or an arg value
insertArg(el.content)
elseif el.t ~= "Space" then
insertArg({el})
end
end
return {
args = args,
name = shortCode
}
end
-- check if a block is composed of a single shortcode
local function onlyShortcode(contents)
-- trim leading and trailing empty strings
contents = trimEmpty(contents)
if #contents < 1 then
return nil
end
-- starts with a shortcode
local startsWithShortcode = contents[1].t == "Str" and contents[1].text == kOpenShortcode
if not startsWithShortcode then
return nil
end
-- ends with a shortcode
local endsWithShortcode = contents[#contents].t == "Str" and contents[#contents].text == kCloseShortcode
if not endsWithShortcode then
return nil
end
-- has only one open shortcode
local openShortcodes = filter(contents, function(el)
return el.t == "Str" and el.text == kOpenShortcode
end)
if #openShortcodes ~= 1 then
return nil
end
-- has only one close shortcode
local closeShortcodes = filter(contents, function(el)
return el.t == "Str" and el.text == kCloseShortcode
end)
if #closeShortcodes ~= 1 then
return nil
end
return contents
end
-- coerce any shortcode result to a list of inlines
local function shortcodeResultAsInlines(result, name)
local type = pandoc.utils.type(result)
if type == "Inlines" then
return result
elseif type == "Blocks" then
return pandoc.utils.blocks_to_inlines(result, { pandoc.Space() })
elseif type == "string" then
return pandoc.Inlines( { pandoc.Str(result) })
elseif tisarray(result) then
local items = pandoc.List(result)
local inlines = items:filter(isInlineEl)
if #inlines > 0 then
return pandoc.Inlines(inlines)
else
local blocks = items:filter(isBlockEl)
return pandoc.utils.blocks_to_inlines(blocks, { pandoc.Space() })
end
elseif isInlineEl(result) then
return pandoc.Inlines( { result })
elseif isBlockEl(result) then
return pandoc.utils.blocks_to_inlines( { result }, { pandoc.Space() })
else
error("Unexepected result from shortcode " .. name .. "")
dump(result)
os.exit(1)
end
end
-- coerce any shortcode result to a list of blocks
local function shortcodeResultAsBlocks(result, name)
local type = pandoc.utils.type(result)
if type == "Blocks" then
return result
elseif type == "Inlines" then
return pandoc.Blocks( {pandoc.Para(result) })
elseif type == "string" then
return pandoc.Blocks( {pandoc.Para({pandoc.Str(result)})} )
elseif tisarray(result) then
local items = pandoc.List(result)
local blocks = items:filter(isBlockEl)
if #blocks > 0 then
return pandoc.Blocks(blocks)
else
local inlines = items:filter(isInlineEl)
return pandoc.Blocks({pandoc.Para(inlines)})
end
elseif isBlockEl(result) then
return pandoc.Blocks( { result } )
elseif isInlineEl(result) then
return pandoc.Blocks( {pandoc.Para( {result} ) })
else
error("Unexepected result from shortcode " .. name .. "")
print(result)
os.exit(1)
end
end
-- scans through a list of inlines, finds shortcodes, and processes them
local function transformShortcodeInlines(inlines)
local transformed = false
local outputInlines = pandoc.List()
local shortcodeInlines = pandoc.List()
local accum = outputInlines
-- iterate through any inlines and process any shortcodes
for i, el in ipairs(inlines) do
if el.t == "Str" then
-- find escaped shortcodes
local beginEscapeMatch = el.text:match("^%{%{%{+<")
local endEscapeMatch = el.text:match(">%}%}%}+$")
-- handle shocrtcode escape -- e.g. {{{< >}}}
if beginEscapeMatch then
transformed = true
accum:insert(pandoc.Str(beginEscapeMatch:sub(2)))
elseif endEscapeMatch then
transformed = true
accum:insert(endEscapeMatch:sub(1, #endEscapeMatch-1))
-- handle shortcode escape -- e.g. {{</* shortcode_name */>}}
elseif endsWith(el.text, kOpenShortcode .. kOpenShortcodeEscape) then
-- This is an escape, so insert the raw shortcode as text (remove the comment chars)
transformed = true
accum:insert(pandoc.Str(kOpenShortcode))
elseif startsWith(el.text, kCloseShortcodeEscape .. kCloseShortcode) then
-- This is an escape, so insert the raw shortcode as text (remove the comment chars)
transformed = true
accum:insert(pandoc.Str(kCloseShortcode))
elseif endsWith(el.text, kOpenShortcode) then
-- note that the text might have other text with it (e.g. a case like)
-- This is my inline ({{< foo bar >}}).
-- Need to pare off prefix and suffix and preserve them
local prefix = el.text:sub(1, #el.text - #kOpenShortcode)
if prefix then
accum:insert(pandoc.Str(prefix))
end
-- the start of a shortcode, start accumulating the shortcode
accum = shortcodeInlines
accum:insert(pandoc.Str(kOpenShortcode))
elseif startsWith(el.text, kCloseShortcode) then
-- since we closed a shortcode, mark this transformed
transformed = true
-- the end of the shortcode, stop accumulating the shortcode
accum:insert(pandoc.Str(kCloseShortcode))
accum = outputInlines
-- process the shortcode
local shortCode = processShortCode(shortcodeInlines)
-- find the handler for this shortcode and transform
local handler = handlerForShortcode(shortCode)
if handler ~= nil then
local expanded = callShortcodeHandler(handler, shortCode)
if expanded ~= nil then
-- process recursively
expanded = shortcodeResultAsInlines(expanded, shortCode.name)
local expandedAgain = transformShortcodeInlines(expanded)
if (expandedAgain ~= nil) then
tappend(accum, expandedAgain)
else
tappend(accum, expanded)
end
end
else
tappend(accum, shortcodeInlines)
end
local suffix = el.text:sub(#kCloseShortcode + 1)
if suffix then
accum:insert(pandoc.Str(suffix))
end
-- clear the accumulated shortcode inlines
shortcodeInlines = pandoc.List()
else
-- not a shortcode, accumulate
accum:insert(el)
end
else
-- not a string, accumulate
accum:insert(el)
end
end
if transformed then
return outputInlines
else
return nil
end
end
-- transforms shortcodes inside code
local function transformShortcodeCode(el)
-- don't process shortcodes in code output from engines
-- (anything in an engine processed code block was actually
-- proccessed by the engine, so should be printed as is)
if el.attr and el.attr.classes:includes("cell-code") then
return
end
-- don't process shortcodes if they are explicitly turned off
if el.attr and el.attr.attributes["shortcodes"] == "false" then
return
end
-- process shortcodes
local text = el.text:gsub("(%{%{%{*<)" .. "(.-)" .. "(>%}%}%}*)", function(beginCode, code, endCode)
if #beginCode > 3 or #endCode > 3 then
return beginCode:sub(2) .. code .. endCode:sub(1, #endCode-1)
else
-- see if any of the shortcode handlers want it (and transform results to plain text)
local inlines = markdownToInlines(kOpenShortcode .. code .. kCloseShortcode)
local transformed = transformShortcodeInlines(inlines)
if transformed ~= nil then
return inlinesToString(transformed)
else
return beginCode .. code .. endCode
end
end
end)
-- return new element if the text changd
if text ~= el.text then
el.text = text
return el
end
end
-- finds blocks that only contain a shortcode and processes them
local function transformShortcodeBlocks(blocks)
local transformed = false
local scannedBlocks = pandoc.List()
for i,block in ipairs(blocks) do
-- inspect para and plain blocks for shortcodes
if block.t == "Para" or block.t == "Plain" then
-- if contents are only a shortcode, process and return
local onlyShortcode = onlyShortcode(block.content)
if onlyShortcode ~= nil then
-- there is a shortcode here, process it and return the blocks
local shortCode = processShortCode(onlyShortcode)
local handler = handlerForShortcode(shortCode)
if handler ~= nil then
local transformedShortcode = callShortcodeHandler(handler, shortCode)
if transformedShortcode ~= nil then
tappend(scannedBlocks, shortcodeResultAsBlocks(transformedShortcode, shortCode.name))
transformed = true
end
else
scannedBlocks:insert(block)
end
else
scannedBlocks:insert(block)
end
else
scannedBlocks:insert(block)
end
end
-- if we didn't transform any shortcodes, just return nil to signal
-- no changes
if transformed then
return scannedBlocks
else
return nil
end
end
-- transforms shortcodes in a string
local function transformString(str)
if string.find(str, kOpenShortcode) then
local inlines = markdownToInlines(str)
if inlines ~= nil then
local mutatedTarget = transformShortcodeInlines(inlines)
if mutatedTarget ~= nil then
return inlinesToString(mutatedTarget)
end
end
end
return nil
end
-- decode a url
local function urldecode(url)
if url == nil then
return
end
url = url:gsub("+", " ")
url = url:gsub("%%(%x%x)", function(x)
return string.char(tonumber(x, 16))
end)
return url
end
-- transforms shortcodes in link targets
local function transformLink(el)
local target = urldecode(el.target)
local tranformed = transformString(target);
if tranformed ~= nil then
el.target = tranformed
return el
end
end
-- transforms shortcodes in img srcs
local function transformImage(el)
local target = urldecode(el.src)
local tranformed = transformString(target);
if tranformed ~= nil then
el.src = tranformed
return el
end
end
-------- meta shortcode --------
-- Implements reading values from document metadata
-- as {{< meta title >}}
-- or {{< meta key.subkey.subkey >}}
-- This only supports emitting simple types (not arrays or maps)
local function processValue(val, name, t)
if type(val) == "table" then
if #val == 0 then
return { pandoc.Str( "") }
elseif pandoc.utils.type(val) == "Inlines" then
return val
elseif pandoc.utils.type(val) == "Blocks" then
return pandoc.utils.blocks_to_inlines(val)
else
warn("Unsupported type '" .. pandoc.utils.type(val) .. "' for key " .. name .. " in a " .. t .. " shortcode.")
return { pandoc.Strong({pandoc.Str("?invalid " .. t .. " type:" .. name)}) }
end
else
return { pandoc.Str( tostring(val) ) }
end
end
local function handleMeta(args)
if #args > 0 then
-- the args are the var name
local varName = inlinesToString(args[1])
-- read the option value
local optionValue = option(varName, nil)
if optionValue ~= nil then
return processValue(optionValue, varName, "meta")
else
warn("Unknown meta key " .. varName .. " specified in a metadata Shortcode.")
return { pandoc.Strong({pandoc.Str("?meta:" .. varName)}) }
end
else
-- no args, we can't do anything
return nil
end
end
-------- env shortcode --------
-- Implements reading values from envrionment variables
local function handleEnv(args)
if #args > 0 then
-- the args are the var name
local varName = inlinesToString(args[1])
-- read the environment variable
local envValue = os.getenv(varName)
if envValue ~= nil then
return { pandoc.Str(envValue) }
else
warn("Unknown variable " .. varName .. " specified in an env Shortcode.")
return { pandoc.Strong({pandoc.Str("?env:" .. varName)}) }
end
else
-- no args, we can't do anything
return nil
end
end
-------- pagebreak shortcode --------
local function handlePagebreak()
local pagebreak = {
epub = '<p style="page-break-after: always;"> </p>',
html = '<div style="page-break-after: always;"></div>',
latex = '\\newpage{}',
ooxml = '<w:p><w:r><w:br w:type="page"/></w:r></w:p>',
odt = '<text:p text:style-name="Pagebreak"/>',
context = '\\page'
}
if FORMAT == 'docx' then
return pandoc.RawBlock('openxml', pagebreak.ooxml)
elseif FORMAT:match 'latex' then
return pandoc.RawBlock('tex', pagebreak.latex)
elseif FORMAT:match 'odt' then
return pandoc.RawBlock('opendocument', pagebreak.odt)
elseif FORMAT:match 'html.*' then
return pandoc.RawBlock('html', pagebreak.html)
elseif FORMAT:match 'epub' then
return pandoc.RawBlock('html', pagebreak.epub)
elseif FORMAT:match 'context' then
return pandoc.RawBlock('context', pagebreak.context)
else
-- fall back to insert a form feed character
return pandoc.Para{pandoc.Str '\f'}
end
end
return {
-- init
{
Meta = function(meta)
if meta ~= nil then
-- pre-read metadata
allOptions = readMetaOptions(meta)
end
-- install shortocde handlers
initShortcodeHandlers(pandoc.List(option("shortcodes", {})))
end
},
-- blocks
{
Blocks = transformShortcodeBlocks,
CodeBlock = transformShortcodeCode,
RawBlock = transformShortcodeCode
},
-- inlines
{
Inlines = transformShortcodeInlines,
Code = transformShortcodeCode,
RawInline = transformShortcodeCode,
Link = transformLink,
Image = transformImage
}
}