-
Notifications
You must be signed in to change notification settings - Fork 61
/
markdown.lua
1943 lines (1661 loc) · 77.3 KB
/
markdown.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
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
-- (c) 2009-2011 John MacFarlane, Hans Hagen. Released under MIT license.
-- See the file LICENSE in the source for details.
local util = require("lunamark.util")
local lpeg = require("lpeg")
local entities = require("lunamark.entities")
local lower, upper, gsub, format, length =
string.lower, string.upper, string.gsub, string.format, string.len
local P, R, S, V, C, Cg, Cb, Cmt, Cc, Ct, B, Cs, Cf =
lpeg.P, lpeg.R, lpeg.S, lpeg.V, lpeg.C, lpeg.Cg, lpeg.Cb,
lpeg.Cmt, lpeg.Cc, lpeg.Ct, lpeg.B, lpeg.Cs, lpeg.Cf
local lpegmatch = lpeg.match
local expand_tabs_in_line = util.expand_tabs_in_line
local utf8_lower do
if pcall(require, "lua-utf8") then -- try luautf8
local luautf8 = require("lua-utf8")
utf8_lower = luautf8.lower
elseif pcall(require, "unicode") then -- try slnunicode
local slnunicde = require "unicode"
utf8_lower = slnunicde.utf8.lower
else
error "no unicode library found"
end
end
local load = load -- lua 5.2/5.3 style `load` function
if _VERSION == "Lua 5.1" then
function load(ld, source, mode, env)
assert(mode == "t")
if ld:sub(1,1) == "\27" then
error("attempt to load a binary chunk (mode is 'text')")
end
local chunk, msg = loadstring(ld, source)
if not chunk then
return chunk, msg
end
if env ~= nil then
setfenv(chunk, env)
end
return chunk
end
end
local M = {}
local rope_to_string = util.rope_to_string
-- Normalize a markdown reference tag. (Make lowercase, and collapse
-- adjacent whitespace characters.)
local function normalize_tag(tag)
return utf8_lower(gsub(rope_to_string(tag), "[ \n\r\t]+", " "))
end
------------------------------------------------------------------------------
local parsers = {}
------------------------------------------------------------------------------
-- Basic parsers
------------------------------------------------------------------------------
parsers.percent = P("%")
parsers.at = P("@")
parsers.comma = P(",")
parsers.asterisk = P("*")
parsers.dash = P("-")
parsers.plus = P("+")
parsers.underscore = P("_")
parsers.period = P(".")
parsers.hash = P("#")
parsers.ampersand = P("&")
parsers.backtick = P("`")
parsers.less = P("<")
parsers.more = P(">")
parsers.space = P(" ")
parsers.squote = P("'")
parsers.dquote = P('"')
parsers.lparent = P("(")
parsers.rparent = P(")")
parsers.lbracket = P("[")
parsers.rbracket = P("]")
parsers.circumflex = P("^")
parsers.slash = P("/")
parsers.equal = P("=")
parsers.colon = P(":")
parsers.semicolon = P(";")
parsers.exclamation = P("!")
parsers.pipe = P("|")
parsers.tilde = P("~")
parsers.tab = P("\t")
parsers.newline = P("\n")
parsers.tightblocksep = P("\001")
parsers.digit = R("09")
parsers.hexdigit = R("09","af","AF")
parsers.letter = R("AZ","az")
parsers.alphanumeric = R("AZ","az","09")
parsers.keyword = parsers.letter
* parsers.alphanumeric^0
parsers.citation_chars = parsers.alphanumeric
+ S("#$%&-+<>~/_")
parsers.internal_punctuation = S(":;,.?")
parsers.doubleasterisks = P("**")
parsers.doubleunderscores = P("__")
parsers.doubletildes = P("~~")
parsers.fourspaces = P(" ")
parsers.any = P(1)
parsers.fail = parsers.any - 1
parsers.escapable = S("\\`*_{}[]()+_.!<>#-~:^@;")
parsers.anyescaped = P("\\") / "" * parsers.escapable
+ parsers.any
parsers.spacechar = S("\t ")
parsers.spacing = S(" \n\r\t")
parsers.nonspacechar = parsers.any - parsers.spacing
parsers.optionalspace = parsers.spacechar^0
parsers.eof = -parsers.any
parsers.nonindentspace = parsers.space^-3 * -parsers.spacechar
parsers.indent = parsers.space^-3 * parsers.tab
+ parsers.fourspaces / ""
parsers.linechar = P(1 - parsers.newline)
parsers.blankline = parsers.optionalspace
* parsers.newline / "\n"
parsers.blanklines = parsers.blankline^0
parsers.skipblanklines = (parsers.optionalspace * parsers.newline)^0
parsers.indentedline = parsers.indent /""
* C(parsers.linechar^1 * parsers.newline^-1)
parsers.optionallyindentedline = parsers.indent^-1 /""
* C(parsers.linechar^1 * parsers.newline^-1)
parsers.sp = parsers.spacing^0
parsers.spnl = parsers.optionalspace
* (parsers.newline * parsers.optionalspace)^-1
parsers.line = parsers.linechar^0 * parsers.newline
parsers.nonemptyline = parsers.line - parsers.blankline
parsers.chunk = parsers.line * (parsers.optionallyindentedline
- parsers.blankline)^0
-- block followed by 0 or more optionally
-- indented blocks with first line indented.
parsers.indented_blocks = function(bl)
return Cs( bl
* (parsers.blankline^1 * parsers.indent * -parsers.blankline * bl)^0
* parsers.blankline^1 )
end
-- Attributes list as in Pandoc {#id .class .class-other key=value key2="value 2"}
parsers.identifier = parsers.letter
* (parsers.alphanumeric + S("_-"))^0
parsers.attrvalue = (parsers.dquote * C((parsers.alphanumeric + S("._- "))^1) * parsers.dquote)
+ C((parsers.alphanumeric + S("._-"))^1)
parsers.attrpair = Cg(C((parsers.identifier)^1)
* parsers.optionalspace * parsers.equal * parsers.optionalspace
* parsers.attrvalue)
* parsers.optionalspace^-1
parsers.attrlist = Cf(Ct("") * parsers.attrpair^0, rawset)
parsers.class = (P("-") * Cc("unnumbered")) + (parsers.period * C((parsers.identifier)^1))
parsers.classes = (parsers.class * parsers.optionalspace)^0
parsers.hashid = parsers.hash * C((parsers.identifier)^1)
parsers.attributes = P("{") * parsers.optionalspace
* Cg(parsers.hashid^-1) * parsers.optionalspace
* Ct(parsers.classes) * Cg(parsers.attrlist)
* parsers.optionalspace * P("}")
/ function (hashid, classes, attr)
attr.id = hashid ~= "" and hashid or nil
attr.class = table.concat(classes or {}, " ")
return attr
end
-- Raw attributes similar to Pandoc (=format key=value key2="value 2")
parsers.raw = parsers.equal * C((parsers.identifier)^1) * parsers.optionalspace
parsers.rawattributes = P("{") * parsers.optionalspace
* parsers.raw * Cg(parsers.attrlist)
* parsers.optionalspace * P("}")
-----------------------------------------------------------------------------
-- Parsers used for markdown lists
-----------------------------------------------------------------------------
parsers.bulletchar = C(parsers.plus + parsers.asterisk + parsers.dash)
parsers.bullet = ( parsers.bulletchar * #parsers.spacing
* (parsers.tab + parsers.space^-3)
+ parsers.space * parsers.bulletchar * #parsers.spacing
* (parsers.tab + parsers.space^-2)
+ parsers.space * parsers.space * parsers.bulletchar
* #parsers.spacing
* (parsers.tab + parsers.space^-1)
+ parsers.space * parsers.space * parsers.space
* parsers.bulletchar * #parsers.spacing
)
-----------------------------------------------------------------------------
-- Parsers used for markdown code spans
-----------------------------------------------------------------------------
parsers.openticks = Cg(parsers.backtick^1, "ticks")
local function captures_equal_length(_,i,a,b)
return #a == #b and i
end
parsers.closeticks = parsers.space^-1
* Cmt(C(parsers.backtick^1)
* Cb("ticks"), captures_equal_length)
parsers.intickschar = (parsers.any - S(" \n\r`"))
+ (parsers.newline * -parsers.blankline)
+ (parsers.space - parsers.closeticks)
+ (parsers.backtick^1 - parsers.closeticks)
parsers.inticks = parsers.openticks * parsers.space^-1
* C(parsers.intickschar^1) * parsers.closeticks
-----------------------------------------------------------------------------
-- Parsers used for fenced code blocks
-----------------------------------------------------------------------------
local function captures_geq_length(_,i,a,b)
return #a >= #b and i
end
parsers.tilde_infostring
= C((parsers.linechar
- (parsers.spacechar^1 * parsers.newline))^0)
* parsers.optionalspace
* (parsers.newline + parsers.eof)
parsers.backtick_infostring
= C((parsers.linechar
- (parsers.backtick
+ parsers.spacechar^1 * parsers.newline))^0)
* parsers.optionalspace
* (parsers.newline + parsers.eof)
local fenceindent
parsers.fencehead = function(char, infostring)
return C(parsers.nonindentspace) / function(s)
fenceindent = #s
end
* Cg(char^3, "fencelength")
* parsers.optionalspace * infostring
end
parsers.fencetail = function(char)
return parsers.nonindentspace
* Cmt(C(char^3) * Cb("fencelength"), captures_geq_length)
* parsers.optionalspace * (parsers.newline + parsers.eof)
end
parsers.fencedline = function(char)
return C(parsers.line - parsers.fencetail(char))
/ function(s)
return s:gsub("^" .. string.rep(" ?", fenceindent), "")
end
end
------------------------------------------------------------------------------
-- Parsers used for fenced divs
------------------------------------------------------------------------------
parsers.fenced_div_infostring
= C((parsers.linechar
- ( parsers.spacechar^1
* parsers.colon^1))^1)
parsers.fenced_div_begin = parsers.nonindentspace
* parsers.colon^3
* parsers.optionalspace
* parsers.fenced_div_infostring
* ( parsers.spacechar^1
* parsers.colon^1)^0
* parsers.optionalspace
* (parsers.newline + parsers.eof)
parsers.fenced_div_end = parsers.nonindentspace
* parsers.colon^3
* parsers.optionalspace
* (parsers.newline + parsers.eof)
-----------------------------------------------------------------------------
-- Parsers used for markdown tags and links
-----------------------------------------------------------------------------
parsers.leader = parsers.space^-3
-- in balanced brackets, parentheses, quotes:
parsers.bracketed = P{ parsers.lbracket
* ((parsers.anyescaped - (parsers.lbracket
+ parsers.rbracket
+ parsers.blankline^2)
) + V(1))^0
* parsers.rbracket }
parsers.inparens = P{ parsers.lparent
* ((parsers.anyescaped - (parsers.lparent
+ parsers.rparent
+ parsers.blankline^2)
) + V(1))^0
* parsers.rparent }
parsers.squoted = P{ parsers.squote * parsers.alphanumeric
* ((parsers.anyescaped - (parsers.squote
+ parsers.blankline^2)
) + V(1))^0
* parsers.squote }
parsers.dquoted = P{ parsers.dquote * parsers.alphanumeric
* ((parsers.anyescaped - (parsers.dquote
+ parsers.blankline^2)
) + V(1))^0
* parsers.dquote }
-- bracketed 'tag' for markdown links, allowing nested brackets:
parsers.tag = parsers.lbracket
* Cs((parsers.alphanumeric^1
+ parsers.bracketed
+ parsers.inticks
+ (parsers.anyescaped - (parsers.rbracket
+ parsers.blankline^2)))^0)
* parsers.rbracket
-- url for markdown links, allowing balanced parentheses:
parsers.url = parsers.less * Cs((parsers.anyescaped-parsers.more)^0)
* parsers.more
+ Cs((parsers.inparens + (parsers.anyescaped
-parsers.spacing-parsers.rparent))^1)
-- quoted text possibly with nested quotes:
parsers.title_s = parsers.squote * Cs(((parsers.anyescaped-parsers.squote)
+ parsers.squoted)^0)
* parsers.squote
parsers.title_d = parsers.dquote * Cs(((parsers.anyescaped-parsers.dquote)
+ parsers.dquoted)^0)
* parsers.dquote
parsers.title_p = parsers.lparent
* Cs((parsers.inparens + (parsers.anyescaped-parsers.rparent))^0)
* parsers.rparent
parsers.title = parsers.title_d + parsers.title_s + parsers.title_p
parsers.optionaltitle
= parsers.spnl * parsers.title * parsers.spacechar^0
+ Cc("")
------------------------------------------------------------------------------
-- Parsers used for citations
------------------------------------------------------------------------------
parsers.citation_name = Cs(parsers.dash^-1) * parsers.at
* Cs(parsers.citation_chars
* (((parsers.citation_chars + parsers.internal_punctuation
- parsers.comma - parsers.semicolon)
* -#((parsers.internal_punctuation - parsers.comma
- parsers.semicolon)^0
* -(parsers.citation_chars + parsers.internal_punctuation
- parsers.comma - parsers.semicolon)))^0
* parsers.citation_chars)^-1)
parsers.citation_body_prenote
= Cs((parsers.alphanumeric^1
+ parsers.bracketed
+ parsers.inticks
+ (parsers.anyescaped
- (parsers.rbracket + parsers.blankline^2))
- (parsers.spnl * parsers.dash^-1 * parsers.at))^0)
parsers.citation_body_postnote
= Cs((parsers.alphanumeric^1
+ parsers.bracketed
+ parsers.inticks
+ (parsers.anyescaped
- (parsers.rbracket + parsers.semicolon
+ parsers.blankline^2))
- (parsers.spnl * parsers.rbracket))^0)
parsers.citation_body_chunk
= parsers.citation_body_prenote
* parsers.spnl * parsers.citation_name
* ((parsers.internal_punctuation - parsers.semicolon)
* parsers.spnl)^-1
* parsers.citation_body_postnote
parsers.citation_body
= parsers.citation_body_chunk
* (parsers.semicolon * parsers.spnl
* parsers.citation_body_chunk)^0
parsers.citation_headless_body
= Cs((parsers.alphanumeric^1
+ parsers.bracketed
+ parsers.inticks
+ (parsers.anyescaped
- (parsers.rbracket + parsers.at
+ parsers.semicolon + parsers.blankline^2))
- (parsers.spnl * parsers.rbracket))^0)
* (parsers.sp * parsers.semicolon * parsers.spnl
* parsers.citation_body_chunk)^0
------------------------------------------------------------------------------
-- Parsers used for footnotes
------------------------------------------------------------------------------
local function strip_first_char(s)
return s:sub(2)
end
parsers.RawNoteRef = #(parsers.lbracket * parsers.circumflex)
* parsers.tag / strip_first_char
------------------------------------------------------------------------------
-- Parsers used for HTML
------------------------------------------------------------------------------
-- case-insensitive match (we assume s is lowercase). must be single byte encoding
parsers.keyword_exact = function(s)
local parser = P(0)
for i=1,#s do
local c = s:sub(i,i)
local m = c .. upper(c)
parser = parser * S(m)
end
return parser
end
parsers.block_keyword =
parsers.keyword_exact("address") + parsers.keyword_exact("blockquote") +
parsers.keyword_exact("center") + parsers.keyword_exact("del") +
parsers.keyword_exact("dir") + parsers.keyword_exact("div") +
parsers.keyword_exact("p") + parsers.keyword_exact("pre") +
parsers.keyword_exact("li") + parsers.keyword_exact("ol") +
parsers.keyword_exact("ul") + parsers.keyword_exact("dl") +
parsers.keyword_exact("dd") + parsers.keyword_exact("form") +
parsers.keyword_exact("fieldset") + parsers.keyword_exact("isindex") +
parsers.keyword_exact("ins") + parsers.keyword_exact("menu") +
parsers.keyword_exact("noframes") + parsers.keyword_exact("frameset") +
parsers.keyword_exact("h1") + parsers.keyword_exact("h2") +
parsers.keyword_exact("h3") + parsers.keyword_exact("h4") +
parsers.keyword_exact("h5") + parsers.keyword_exact("h6") +
parsers.keyword_exact("hr") + parsers.keyword_exact("script") +
parsers.keyword_exact("noscript") + parsers.keyword_exact("table") +
parsers.keyword_exact("tbody") + parsers.keyword_exact("tfoot") +
parsers.keyword_exact("thead") + parsers.keyword_exact("th") +
parsers.keyword_exact("td") + parsers.keyword_exact("tr")
-- There is no reason to support bad html, so we expect quoted attributes
parsers.htmlattributevalue
= parsers.squote * (parsers.any - (parsers.blankline
+ parsers.squote))^0
* parsers.squote
+ parsers.dquote * (parsers.any - (parsers.blankline
+ parsers.dquote))^0
* parsers.dquote
parsers.htmlattribute = parsers.spacing^1
* (parsers.alphanumeric + S("_-"))^1
* parsers.sp * parsers.equal * parsers.sp
* parsers.htmlattributevalue
parsers.htmlcomment = P("<!--") * (parsers.any - P("-->"))^0 * P("-->")
parsers.htmlinstruction = P("<?") * (parsers.any - P("?>" ))^0 * P("?>" )
parsers.openelt_any = parsers.less * parsers.keyword * parsers.htmlattribute^0
* parsers.sp * parsers.more
parsers.openelt_exact = function(s)
return parsers.less * parsers.sp * parsers.keyword_exact(s)
* parsers.htmlattribute^0 * parsers.sp * parsers.more
end
parsers.openelt_block = parsers.sp * parsers.block_keyword
* parsers.htmlattribute^0 * parsers.sp * parsers.more
parsers.closeelt_any = parsers.less * parsers.sp * parsers.slash
* parsers.keyword * parsers.sp * parsers.more
parsers.closeelt_exact = function(s)
return parsers.less * parsers.sp * parsers.slash * parsers.keyword_exact(s)
* parsers.sp * parsers.more
end
parsers.emptyelt_any = parsers.less * parsers.sp * parsers.keyword
* parsers.htmlattribute^0 * parsers.sp * parsers.slash
* parsers.more
parsers.emptyelt_block = parsers.less * parsers.sp * parsers.block_keyword
* parsers.htmlattribute^0 * parsers.sp * parsers.slash
* parsers.more
parsers.displaytext = (parsers.any - parsers.less)^1
-- return content between two matched HTML tags
parsers.in_matched = function(s)
return { parsers.openelt_exact(s)
* (V(1) + parsers.displaytext
+ (parsers.less - parsers.closeelt_exact(s)))^0
* parsers.closeelt_exact(s) }
end
local function parse_matched_tags(s,pos)
local t = lower(lpegmatch(C(parsers.keyword),s,pos))
return lpegmatch(parsers.in_matched(t),s,pos-1)
end
parsers.in_matched_block_tags = parsers.less
* Cmt(#parsers.openelt_block, parse_matched_tags)
parsers.displayhtml = parsers.htmlcomment
+ parsers.emptyelt_block
+ parsers.openelt_exact("hr")
+ parsers.in_matched_block_tags
+ parsers.htmlinstruction
parsers.inlinehtml = parsers.emptyelt_any
+ parsers.htmlcomment
+ parsers.htmlinstruction
+ parsers.openelt_any
+ parsers.closeelt_any
------------------------------------------------------------------------------
-- Parsers used for HTML entities
------------------------------------------------------------------------------
parsers.hexentity = parsers.ampersand * parsers.hash * S("Xx")
* C(parsers.hexdigit^1) * parsers.semicolon
parsers.decentity = parsers.ampersand * parsers.hash
* C(parsers.digit^1) * parsers.semicolon
parsers.tagentity = parsers.ampersand * C(parsers.alphanumeric^1)
* parsers.semicolon
------------------------------------------------------------------------------
-- Helpers for links and references
------------------------------------------------------------------------------
-- parse a reference definition: [foo]: /bar "title"
parsers.define_reference_parser = parsers.leader * parsers.tag * parsers.colon
* parsers.spacechar^0 * parsers.url
* parsers.optionaltitle * parsers.blankline^1
------------------------------------------------------------------------------
-- Inline elements
------------------------------------------------------------------------------
parsers.Inline = V("Inline")
parsers.squote_start = parsers.squote * -parsers.spacing
parsers.squote_end = parsers.squote * B(parsers.nonspacechar*1, 2)
parsers.Apostrophe = parsers.squote * B(parsers.nonspacechar*1, 2) / "’"
-- parse many p between starter and ender
parsers.between = function(p, starter, ender)
local ender2 = B(parsers.nonspacechar) * ender
return (starter * #parsers.nonspacechar * Ct(p * (p - ender2)^0) * ender2)
end
parsers.urlchar = parsers.anyescaped - parsers.newline - parsers.more
------------------------------------------------------------------------------
-- Block elements
------------------------------------------------------------------------------
parsers.Block = V("Block")
parsers.TildeFencedCodeBlock
= parsers.fencehead(parsers.tilde,
parsers.tilde_infostring)
* Cs(parsers.fencedline(parsers.tilde)^0)
* parsers.fencetail(parsers.tilde)
parsers.BacktickFencedCodeBlock
= parsers.fencehead(parsers.backtick,
parsers.backtick_infostring)
* Cs(parsers.fencedline(parsers.backtick)^0)
* parsers.fencetail(parsers.backtick)
parsers.lineof = function(c)
return (parsers.leader * (P(c) * parsers.optionalspace)^3
* parsers.newline * parsers.blankline^1)
end
------------------------------------------------------------------------------
-- Lists
------------------------------------------------------------------------------
parsers.defstartchar = S("~:")
parsers.defstart = ( parsers.defstartchar * #parsers.spacing
* (parsers.tab + parsers.space^-3)
+ parsers.space * parsers.defstartchar * #parsers.spacing
* (parsers.tab + parsers.space^-2)
+ parsers.space * parsers.space * parsers.defstartchar
* #parsers.spacing
* (parsers.tab + parsers.space^-1)
+ parsers.space * parsers.space * parsers.space
* parsers.defstartchar * #parsers.spacing
)
parsers.dlchunk = Cs(parsers.line * (parsers.indentedline - parsers.blankline)^0)
------------------------------------------------------------------------------
-- Pandoc title block parser
------------------------------------------------------------------------------
parsers.pandoc_author = parsers.spacechar * parsers.optionalspace
* C((parsers.anyescaped
- parsers.newline
- parsers.semicolon)^0)
* (parsers.semicolon + parsers.newline)
------------------------------------------------------------------------------
-- Headers
------------------------------------------------------------------------------
-- parse Atx heading start and return level
parsers.HeadingStart = #parsers.hash * C(parsers.hash^-6)
* -parsers.hash / length
-- parse setext header ending and return level
parsers.HeadingLevel = parsers.equal^1 * Cc(1) + parsers.dash^1 * Cc(2)
local function strip_atx_end(s)
return s:gsub("[#%s]*[\n]*$","")
end
--- Create a new markdown parser.
--
-- * `writer` is a writer table (see [lunamark.writer.generic]).
--
-- * `options` is a table with parsing options.
-- The following fields are significant:
--
-- `alter_syntax`
-- : Function from syntax table to syntax table,
-- allowing the user to change or extend the markdown syntax.
-- For an example, see the documentation for `lunamark`.
--
-- `references`
-- : A table of references to be used in resolving links
-- in the document. The keys should be all lowercase, with
-- spaces and newlines collapsed into single spaces.
-- Example:
--
-- { foo: { url = "/url", title = "my title" },
-- bar: { url = "http://fsf.org" } }
--
-- `preserve_tabs`
-- : Preserve tabs instead of converting to spaces.
--
-- `smart`
-- : Parse quotation marks, dashes, ellipses intelligently.
--
-- `startnum`
-- : Make the opening number in an ordered list significant.
--
-- `notes`
-- : Enable footnotes as in pandoc.
--
-- `inline_notes`
-- : Inline footnotes. An inline footnote is like a markdown bracketed
-- reference, but preceded with a circumflex (`^`).
--
-- `definition_lists`
-- : Enable definition lists as in pandoc.
--
-- `citations`
-- : Enable citations as in pandoc.
--
-- `fenced_code_blocks`
-- : Enable fenced code blocks.
--
-- `pandoc_title_blocks`
-- : Parse pandoc-style title block at the beginning of document:
--
-- % Title
-- % Author1; Author2
-- % Date
--
-- `lua_metadata`
-- : Enable lua metadata. This is an HTML comment block
-- that starts with `<!--@` and contains lua code.
-- The lua code is interpreted in a sandbox, and
-- any variables defined are added to the metadata.
-- The function `markdown` (also `m`) is defined and can
-- be used to ensure that string fields are parsed
-- as markdown; otherwise, they will be read literally.
--
-- `require_blank_before_blockquote`
-- : Require a blank line between a paragraph and a following
-- block quote.
--
-- `require_blank_before_header`
-- : Require a blank line between a paragraph and a following
-- header.
--
-- `require_blank_before_fenced_code_block`
-- : Require a blank line between a paragraph and a following
-- fenced code block.
--
-- `hash_enumerators`
-- : Allow `#` instead of a digit for an ordered list enumerator
-- (equivalent to `1`).
--
-- `task_list`
-- : GitHub-Flavored Markdown (GFM) task list extension to standard
-- bullet lists. Items starting with `[ ]`, `[x]` or `[X]` after the
-- bullet are processed as first-class structures by the Markdown reader
-- when this option is enabled, possibly allowing writers to handle
-- them more efficiently with a finer-grain logic.
--
-- `fancy_lists`
-- : Allow ordered list items to use a roman number or a letter
-- as anumerator, instead of a digit, and to use a closing parenthesis
-- as end delimiter, instead of a period.
--
-- Depending on the selected writer, the numbering scheme and delimeter
-- may be honored or just ignored.
--
-- If the `startnum` option is enabled, the starting value is converted
-- to decimal, when necessary, so that the list at least starts at the
-- appropriate value.
--
-- So in the minimal case, this option allows such lists to be processed,
-- albeit rendered as regular ordered lists.
--
-- Compared to the Pandoc option by the same name, the implementation
-- does not support currently list markers enclosed in parentheses.
--
-- `strikeout`
-- : Enable strike-through support for a text enclosed within double
-- tildes, as in `~~deleted~~`.
--
-- `superscript`
-- : Enable superscript support. Superscripts may be written by surrounding
-- the superscripted text by `^` characters, as in `2^10^.
--
-- The text thus marked may not contain spaces or newlines.
-- If the superscripted text contains spaces, these spaces must be escaped
-- with backslashes.
--
-- `subscript`
-- : Enable superscript support. Superscripts may be written by surrounding
-- the subscripted text by `~` characters, as in `2~10~`.
--
-- The text thus marked may not contain spaces or newlines.
-- If the supbscripted text contains spaces, these spaces must be escaped
-- with backslashes.
--
-- `bracketed_spans`
-- : When enabled, a bracketed sequence of inlines (as one would use to
-- begin a link), is treated as a Span with attributes if it is
-- followed immediately by attributes, e.g. `[text]{.class key=value}`.
--
-- `fenced_divs`
-- : Allow special fenced syntax for native Div blocks. A Div starts with a
-- fence containing at least three consecutive colons plus some attributes.
--
-- The Div ends with another line containing a string of at least
-- three consecutive colons. The fenced Div should be separated by blank
-- lines from preceding and following blocks.
--
-- Current implementation restrictions and differences with the Pandoc
-- option by the same name: fenced Divs cannot be nested, the attributes
-- cannot be followed by another optional string of consecutive colons,
-- attributes have to be in curly braces (and cannot be a single unbraced
-- word.
--
-- `raw_attribute`
-- : When enabled, inline code and fenced code blocks with a special kind
-- of attribute will be parsed as raw content with the designated format,
-- e.g. `{=format}`. Writers may pass relevant raw content to the
-- target formatter.
--
-- To use a raw attribute with fenced code blocks, `fenced_code_blocks`
-- must be enabled.
--
-- As opposed to the Pandoc option going by the same name, raw
-- attributes can be continued with key=value pairs.
--
-- How these constructs are honored depends on the writer. In the
-- minimal case, they are ignored, as if they were stripped from
-- the input.
--
-- `fenced_code_attributes`
-- : Allow attaching attributes to fenced code blocks, if the latter.
-- are enabled.
--
-- Current implementation restrictions and differences with the Pandoc
-- option by the same name: attributes can only be set on fenced
-- code blocks.
--
-- `link_attributes`
-- : Allow attaching attributes to direct images.
--
-- Current implementation restrictions and differences with the Pandoc
-- option by the same name: attributes cannot be set on links
-- and indirect images (i.e. only direct images support them).
--
-- `pipe_tables`
-- : Support "Pipe Tables", as with Pandoc's option by the same name,
-- following the syntax introduced in PHP Markdown Extra.
--
-- `table_captions`
-- : Enable the Pandoc `table_captions` syntax extension for
-- tables.
--
-- `header_attributes`
-- : Headings can be assigned attributes at the end of the line containing
-- the heading text.
--
-- `line_blocks`
-- : A line block is a sequence of lines beginning with a vertical bar
-- followed by a space. The division into lines will be preserved in the
-- output, as will any leading spaces; otherwise, the lines will be
-- formatted as Markdown.
--
-- Inline formatting (such as emphasis) is allowed
-- in the content, but not block-level formatting (such as block quotes or
-- lists).
--
-- The lines can be hard-wrapped if needed, but the continuation line must
-- begin with a space.
--
-- `escaped_line_breaks`
-- : When enabled, a backslash followed by a newline is also a hard line
-- break. This is a nice alternative to Markdown's "invisible" way of
-- indicating hard line breaks using two trailing spaces at the end of
-- a line.
--
-- * Returns a converter function that converts a markdown string
-- using `writer`, returning the parsed document as first result,
-- and a table containing any extracted metadata as the second
-- result. The converter assumes that the input has unix
-- line endings (newline). If the input might have DOS
-- line endings, a simple `gsub("\r","")` should take care of them.
function M.new(writer, options)
options = options or {}
local larsers = {} -- locally defined parsers
local function expandtabs(s)
if s:find("\t") then
return s:gsub("[^\n]*",expand_tabs_in_line)
else
return s
end
end
if options.preserve_tabs then
expandtabs = function(s) return s end
end
------------------------------------------------------------------------------
-- Top-level parser functions
------------------------------------------------------------------------------
local function create_parser(name, grammar)
return function(str)
local res = lpeg.match(grammar(), str)
if res == nil then
error(format("%s failed on:\n%s", name, str:sub(1,20)))
else
return res
end
end
end
local parse_blocks
= create_parser("parse_blocks",
function()
return larsers.blocks
end)
local parse_inlines
= create_parser("parse_inlines",
function()
return larsers.inlines
end)
local parse_inlines_no_link
= create_parser("parse_inlines_no_link",
function()
return larsers.inlines_no_link
end)
local parse_inlines_no_inline_note
= create_parser("parse_inlines_no_inline_note",
function()
return larsers.inlines_no_inline_note
end)
local parse_inlines_nbsp
= create_parser("parse_inlines_nbsp",
function()
return larsers.inlines_nbsp
end)
local parse_markdown
------------------------------------------------------------------------------
-- Basic parsers (local)
------------------------------------------------------------------------------
if options.smart then
larsers.specialchar = S("*_~`&[]<!\\'\"-.@^")
else
larsers.specialchar = S("*_~`&[]<!\\-@^")
end
larsers.normalchar = parsers.any - (larsers.specialchar
+ parsers.spacing
+ parsers.tightblocksep)
-----------------------------------------------------------------------------
-- Parsers used for markdown lists (local)
-----------------------------------------------------------------------------
if options.hash_enumerators then
larsers.dig = parsers.digit + parsers.hash
else
larsers.dig = parsers.digit
end
larsers.numdelim = parsers.period
if options.fancy_lists then
larsers.dig = larsers.dig + parsers.letter
larsers.numdelim = larsers.numdelim + parsers.rparent
end
larsers.enumerator = C(larsers.dig^3 * larsers.numdelim) * #parsers.spacing
+ C(larsers.dig^2 * larsers.numdelim) * #parsers.spacing
* (parsers.tab + parsers.space^1)
+ C(larsers.dig * larsers.numdelim) * #parsers.spacing
* (parsers.tab + parsers.space^-2)
+ parsers.space * C(larsers.dig^2 * larsers.numdelim)
* #parsers.spacing
+ parsers.space * C(larsers.dig * larsers.numdelim)
* #parsers.spacing
* (parsers.tab + parsers.space^-1)
+ parsers.space * parsers.space * C(larsers.dig^1
* larsers.numdelim) * #parsers.spacing
------------------------------------------------------------------------------
-- Parsers used for citations (local)
------------------------------------------------------------------------------
larsers.citations = function(text_cites, raw_cites)
local function normalize(str)
if str == "" then
str = nil
else
str = (options.citation_nbsps and parse_inlines_nbsp or
parse_inlines)(str)
end
return str
end
local cites = {}
for i = 1,#raw_cites,4 do
cites[#cites+1] = {
prenote = normalize(raw_cites[i]),
suppress_author = raw_cites[i+1] == "-",
name = writer.citation(raw_cites[i+2]),
postnote = normalize(raw_cites[i+3]),
}
end
return writer.citations(text_cites, cites)
end
------------------------------------------------------------------------------
-- Parsers used for footnotes (local)
------------------------------------------------------------------------------
local rawnotes = {}
-- like indirect_link
local function lookup_note(ref)
return function()
local found = rawnotes[normalize_tag(ref)]
if found then
return writer.note(parse_blocks(found))
else
return {"[", parse_inlines("^" .. ref), "]"}
end
end
end
local function register_note(ref,rawnote)
rawnotes[normalize_tag(ref)] = rawnote