-
-
Notifications
You must be signed in to change notification settings - Fork 11
/
Copy pathmarkdown.nim
2549 lines (2123 loc) · 77.1 KB
/
markdown.nim
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
## # nim-markdown
##
## Most markdown parsers parse markdown documents in two steps, so does nim-markdown.
## The two-step consists of blocks parsing and inline parsing.
##
## * **Block Parsing**: One or more lines belongs to blocks, such as `<p>`, `<h1>`, etc.
## * **Inline Parsing**: Textual contents within the lines belongs to inlines, such as `<a>`, `<em>`, `<strong>`, etc.
##
## When parsing block elements, nim-markdown follows this algorithm:
##
## * Step 1. Track current position `pos` in the document.
## * Step 2. If the document since pos matches one of our parsers, then apply it.
## * Step 3. After parsing, a new token is appended to the parent token, and then we advance pos.
## * Step 4. Go back to Step 1 until the end of file.
##
## ```
## # Hello World\nWelcome to **nim-markdown**.\nLet's parse it.
## ^ ^ ^
## 0 14 EOF
##
## ^Document, pos=0
##
## ^Heading(level=1, doc="Hello World"), pos=14.
##
## ^Paragraph(doc="Wel..."), pos=EOF.
## ^EOF, exit parsing.
## ```
##
## After the block parsing step, a tree with only Block Tokens is constructed.
##
## ```
## Document()
## +-Heading(level=1, doc="Hello World")
## +-Paragraph(doc="Wel...")
## ```
##
## Then, we proceed to inline parsing. It walks the tree and expands more inline elements.
## The algorithm is the same, except we apply it to every Block Token.
## Eventually, we get something like this:
##
## ```
## Document()
## +-Heading(level=1)
## +-Text("H")
## +-Text("e")
## +-Text("l")
## +-Text("l")
## +-Text("o")
## ...
## +-Paragraph()
## +-Text("W")
## +-Text("e")
## ...
## +-Em()
## +-Text("n")
## +-Text("i")
## +-Text("m")
## ...
## +-Text(".")
## ...
## ```
##
## Finally, All Token types support conversion to HTML strings with the special $ proc,
##
import re
from strformat import fmt, `&`
from uri import encodeUrl
from strutils import join, splitLines, repeat, replace,
strip, split, multiReplace, startsWith, endsWith,
parseInt, intToStr, splitWhitespace, contains, find
from tables import Table, initTable, mgetOrPut, contains, `[]=`, `[]`
import unicode except `strip`, `splitWhitespace`
from lists import DoublyLinkedList, DoublyLinkedNode,
initDoublyLinkedList, newDoublyLinkedNode, prepend, append,
items, mitems, nodes, remove
from htmlgen import nil, p, br, em, strong, a, img, code, del, blockquote,
li, ul, ol, pre, code, table, thead, tbody, th, tr, td, hr
from markdownpkg/entities import htmlEntityToUtf8
var precompiledExp {.threadvar.}: Table[string, re.Regex]
template re(data: string): Regex =
let tmpName = data
# We won't use mgetOrPut directly because otherwise Nim will lazily evaluate
# the argument for mgetOrPut so that we'll have no benefit
if tmpName in precompiledExp:
precompiledExp[tmpName]
else:
precompiledExp.mgetOrPut(tmpName, re.re(tmpName))
template re(data: string, flags: set[RegexFlag]): Regex =
let tmpName = data
if tmpName in precompiledExp:
precompiledExp[tmpName]
else:
precompiledExp.mgetOrPut(tmpName, re.re(tmpName, flags))
type
MarkdownError* = object of ValueError## The error object for markdown parsing and rendering.
## Usually, you should not see MarkdownError raising in your application
## unless it's documented. Otherwise, please report it as an issue.
##
Parser* = ref object of RootObj
MarkdownConfig* = ref object ## Options for configuring parsing or rendering behavior.
escape*: bool ## escape ``<``, ``>``, and ``&`` characters to be HTML-safe
keepHtml*: bool ## deprecated: preserve HTML tags rather than escape it
blockParsers*: seq[Parser]
inlineParsers*: seq[Parser]
ChunkKind* = enum
BlockChunk,
LazyChunk,
InlineChunk
Chunk* = ref object
kind*: ChunkKind
doc*: string
pos*: int
Token* = ref object of RootObj
doc*: string
pos*: int
children*: DoublyLinkedList[Token]
ParseResult* = ref object
token*: Token
pos*: int
Document* = ref object of Token
Block* = ref object of Token
BlanklineParser* = ref object of Parser
ParagraphParser* = ref object of Parser
Paragraph* = ref object of Block
loose*: bool
trailing*: string
ReferenceParser* = ref object of Parser
Reference = ref object of Block
text*: string
title*: string
url*: string
ThematicBreakParser* = ref object of Parser
ThematicBreak* = ref object of Block
SetextHeadingParser* = ref object of Parser
AtxHeadingParser* = ref object of Parser
Heading* = ref object of Block
level*: int
FencedCodeParser* = ref object of Parser
IndentedCodeParser* = ref object of Parser
CodeBlock* = ref object of Block
info*: string
HtmlBlockParser* = ref object of Parser
HtmlBlock* = ref object of Block
BlockquoteParser* = ref object of Parser
Blockquote* = ref object of Block
chunks*: seq[Chunk]
UlParser* = ref object of Parser
Ul* = ref object of Block
OlParser* = ref object of Parser
Ol* = ref object of Block
start*: int
Li* = ref object of Block
loose*: bool
marker*: string
verbatim*: string
HtmlTableParser* = ref object of Parser
HtmlTable* = ref object of Block
THead* = ref object of Block
TBody* = ref object of Block
size*: int
TableRow* = ref object of Block
THeadCell* = ref object of Block
align*: string
TBodyCell* = ref object of Block
align*: string
Inline* = ref object of Token
TextParser* = ref object of Parser
Text* = ref object of Inline
delimiter*: Delimiter
CodeSpanParser* = ref object of Parser
CodeSpan* = ref object of Inline
SoftBreakParser* = ref object of Parser
SoftBreak* = ref object of Inline
HardBreakParser* = ref object of Parser
HardBreak* = ref object of Inline
StrikethroughParser* = ref object of Parser
Strikethrough* = ref object of Inline
EscapeParser* = ref object of Parser
Escape* = ref object of Inline
InlineHtmlParser* = ref object of Parser
InlineHtml* = ref object of Inline
HtmlEntityParser* = ref object of Parser
HtmlEntity* = ref object of Inline
LinkParser* = ref object of Parser
Link* = ref object of Inline
refId*: string
text*: string ## A link contains link text (the visible text).
url*: string ## A link contains destination (the URI that is the link destination).
title*: string ## A link contains a optional title.
AutoLinkParser* = ref object of Parser
AutoLink* = ref object of Inline
text*: string
url*: string
ImageParser* = ref object of Parser
Image* = ref object of Inline
refId*: string
allowNested*: bool
url*: string
alt*: string
title*: string
DelimiterParser* = ref object of Parser
Delimiter* = ref object of Inline
token*: Text
kind*: string
num*: int
originalNum*: int
isActive*: bool
canOpen*: bool
canClose*: bool
Em* = ref object of Inline
Strong* = ref object of Inline
State* = ref object
references*: Table[string, Reference]
config*: MarkdownConfig
proc parse*(state: State, token: Token);
proc render*(token: Token, sep = "\n"): string;
proc parseBlock(state: State, token: Token);
proc parseLeafBlockInlines(state: State, token: Token);
proc getLinkText*(doc: string, start: int, allowNested: bool = false): tuple[slice: Slice[int], size: int];
proc getLinkLabel*(doc: string, start: int): tuple[label: string, size: int];
proc getLinkDestination*(doc: string, start: int): tuple[slice: Slice[int], size: int];
proc getLinkTitle*(doc: string, start: int): tuple[slice: Slice[int], size: int];
proc isContinuationText*(doc: string, start: int = 0, stop: int = 0): bool;
let skipParsing = ParseResult(token: nil, pos: -1)
method parse*(this: Parser, doc: string, start: int): ParseResult {.base.} =
ParseResult(token: Token(), pos: doc.len)
proc appendChild*(token: Token, child: Token) =
if child of Text and token.children.tail != nil and token.children.tail.value of Text and Text(child).delimiter == Text(token.children.tail.value).delimiter:
token.children.tail.value.doc &= child.doc
token.children.tail.value.pos = max(token.children.tail.value.pos, child.pos)
token.children.tail.value.children.append child.children
else:
token.children.append(child)
const THEMATIC_BREAK_RE = r" {0,3}([-*_])(?:[ \t]*\1){2,}[ \t]*(?:\n+|$)"
const HTML_SCRIPT_START = r" {0,3}<(script|pre|style)(?=(\s|>|$))"
const HTML_SCRIPT_END = r"</(script|pre|style)>"
const HTML_COMMENT_START = r" {0,3}<!--"
const HTML_COMMENT_END = r"-->"
const HTML_PROCESSING_INSTRUCTION_START = r" {0,3}<\?"
const HTML_PROCESSING_INSTRUCTION_END = r"\?>"
const HTML_DECLARATION_START = r" {0,3}<\![A-Z]"
const HTML_DECLARATION_END = r">"
const HTML_CDATA_START = r" {0,3}<!\[CDATA\["
const HTML_CDATA_END = r"\]\]>"
const HTML_VALID_TAGS = ["address", "article", "aside", "base", "basefont", "blockquote", "body", "caption", "center", "col", "colgroup", "dd", "details", "dialog", "dir", "div", "dl", "dt", "fieldset", "figcaption", "figure", "footer", "form", "frame", "frameset", "h1", "h2", "h3", "h4", "h5", "h6", "head", "header", "hr", "html", "iframe", "legend", "li", "link", "main", "menu", "menuitem", "meta", "nav", "noframes", "ol", "optgroup", "option", "p", "param", "section", "source", "summary", "table", "tbody", "td", "tfoot", "th", "thead", "title", "tr", "track", "ul"]
const HTML_TAG_START = r" {0,3}</?(" & HTML_VALID_TAGS.join("|") & r")(?=(\s|/?>|$))"
const HTML_TAG_END = r"^\n?$"
const TAGNAME = r"[A-Za-z][A-Za-z0-9-]*"
const ATTRIBUTENAME = r"[a-zA-Z_:][a-zA-Z0-9:._-]*"
const UNQUOTEDVALUE = r"[^""'=<>`\x00-\x20]+"
const DOUBLEQUOTEDVALUE = """"[^"]*""""
const SINGLEQUOTEDVALUE = r"'[^']*'"
const ATTRIBUTEVALUE = "(?:" & UNQUOTEDVALUE & "|" & SINGLEQUOTEDVALUE & "|" & DOUBLEQUOTEDVALUE & ")"
const ATTRIBUTEVALUESPEC = r"(?:\s*=" & r"\s*" & ATTRIBUTEVALUE & r")"
const ATTRIBUTE = r"(?:\s+" & ATTRIBUTENAME & ATTRIBUTEVALUESPEC & r"?)"
const OPEN_TAG = r"<" & TAGNAME & ATTRIBUTE & r"*" & r"\s*/?>"
const CLOSE_TAG = r"</" & TAGNAME & r"\s*[>]"
const HTML_COMMENT = r"<!---->|<!--(?:-?[^>-])(?:-?[^-])*-->"
const PROCESSING_INSTRUCTION = r"[<][?].*?[?][>]"
const DECLARATION = r"<![A-Z]+\s+[^>]*>"
const CDATA_SECTION = r"<!\[CDATA\[[\s\S]*?\]\]>"
const HTML_TAG = (
r"(?:" &
OPEN_TAG & "|" &
CLOSE_TAG & "|" &
HTML_COMMENT & "|" &
PROCESSING_INSTRUCTION & "|" &
DECLARATION & "|" &
CDATA_SECTION &
& r")"
)
const HTML_OPEN_CLOSE_TAG_START = " {0,3}(?:" & OPEN_TAG & "|" & CLOSE_TAG & r")\s*$"
const HTML_OPEN_CLOSE_TAG_END = r"^\n?$"
let HTML_SEQUENCES = @[
(HTML_SCRIPT_START, HTML_SCRIPT_END),
(HTML_COMMENT_START, HTML_COMMENT_END),
(HTML_PROCESSING_INSTRUCTION_START, HTML_PROCESSING_INSTRUCTION_END),
(HTML_DECLARATION_START, HTML_DECLARATION_END),
(HTML_CDATA_START, HTML_CDATA_END),
(HTML_TAG_START, HTML_TAG_END),
(HTML_OPEN_CLOSE_TAG_START, HTML_OPEN_CLOSE_TAG_END),
]
proc `$`*(chunk: Chunk): string =
fmt"{chunk.kind}{[chunk.doc]}"
proc replaceInitialTabs*(doc: string): string =
var n: int
for line in doc.splitLines(keepEol=true):
n = 0
for ch in line:
if ch == '\t':
n += 1
else:
break
if n == 0:
add result, line
else:
add result, " ".repeat(n*4)
add result, substr(line, n, line.len)
proc preProcessing(state: State, token: Token) =
token.doc = token.doc.replace(re"\r\n|\r", "\n")
token.doc = token.doc.replace("\u2424", " ")
token.doc = token.doc.replace("\u0000", "\uFFFD")
token.doc = token.doc.replace("�", "�")
token.doc = token.doc.replaceInitialTabs
proc isBlank(doc: string, start: int = 0, stop: int = 0): bool =
let matchStop = if stop == 0: doc.len else: stop
doc.matchLen(re"[ \t]*\n?$", start, matchStop) != -1
proc findFirstLine(doc: string, start: int): int =
if start >= doc.len:
return 0
let pos = doc.find('\l', start)
if pos == -1:
return doc.len - start
else:
return pos - start # include eol
iterator findRestLines(doc: string, start: int): tuple[start: int, stop: int] =
# left: open, right: closed
var nextStart = start
var nextEnd = start
while nextStart < doc.len:
nextEnd = doc.find('\l', nextStart)
if nextEnd == -1:
yield (nextStart, doc.len)
break
else:
yield (nextStart, nextEnd+1)
nextStart = nextEnd + 1
proc escapeTag(doc: string): string =
## Replace `<` and `>` to HTML-safe characters.
## Example::
## check escapeTag("<tag>") == "<tag>"
result = doc.replace("<", "<")
result = result.replace(">", ">")
proc escapeQuote(doc: string): string =
## Replace `"` to HTML-safe characters.
## Example::
## check escapeTag("'tag'") == ""e;tag"e;"
doc.replace("\"", """)
proc escapeAmpersandChar(doc: string): string =
## Replace character `&` to HTML-safe characters.
## Example::
## check escapeAmpersandChar("&") == "&amp;"
result = doc.replace("&", "&")
let reAmpersandSeq = re"&(?!#?\w+;)"
proc escapeAmpersandSeq(doc: string): string =
## Replace `&` from a sequence of characters starting from it to HTML-safe characters.
## It's useful to keep those have been escaped.
##
## Example::
## check escapeAmpersandSeq("&") == "&"
## escapeAmpersandSeq("&") == "&"
result = doc.replace(sub=reAmpersandSeq, by="&")
proc escapeCode(doc: string): string =
## Make code block in markdown document HTML-safe.
result = doc.escapeAmpersandChar.escapeTag
proc removeBlankLines(doc: string): string =
doc.strip(leading=false, trailing=true, chars={'\n'})
proc escapeInvalidHTMLTag(doc: string): string =
doc.replacef(
re(r"<(title|textarea|style|xmp|iframe|noembed|noframes|script|plaintext)>",
{RegexFlag.reIgnoreCase}),
"<$1>")
const IGNORED_HTML_ENTITY = ["<", ">", "&"]
proc escapeHTMLEntity(doc: string): string =
var entities = doc.findAll(re"&([^;]+);")
result = doc
for entity in entities:
if not IGNORED_HTML_ENTITY.contains(entity):
let utf8Char = entity.htmlEntityToUtf8
if utf8Char == "":
result = result.replace(re(entity), entity.escapeAmpersandChar)
else:
result = result.replace(re(entity), utf8Char)
proc escapeLinkUrl(url: string): string =
encodeUrl(url.escapeHTMLEntity, usePlus=false).multiReplace([
("%40", "@"),
("%3A", ":"),
("%3A", ":"),
("%2B", "+"),
("%3F", "?"),
("%3D", "="),
("%26", "&"),
("%28", "("),
("%29", ")"),
("%25", "%"),
("%23", "#"),
("%2A", "*"),
("%2C", ","),
("%2F", "/"),
])
proc escapeBackslash(doc: string): string =
doc.replacef(re"\\([\\`*{}\[\]()#+\-.!_<>~|""$%&',/:;=?@^])", "$1")
proc reFmt(patterns: varargs[string]): Regex =
var s: string
for p in patterns:
s &= p
re(s)
method `$`*(token: Token): string {.base.} = ""
method `$`*(token: CodeSpan): string =
code(token.doc.escapeAmpersandChar.escapeTag.escapeQuote)
method `$`*(token: SoftBreak): string = "\n"
method `$`*(token: HardBreak): string = br() & "\n"
method `$`*(token: Strikethrough): string =
del(token.doc)
method `$`*(token: ThematicBreak): string =
hr()
method `$`*(token: Escape): string =
token.doc.escapeAmpersandSeq.escapeTag.escapeQuote
method `$`*(token: InlineHtml): string =
token.doc.escapeInvalidHTMLTag
method `$`*(token: HtmlEntity): string =
token.doc.escapeHTMLEntity.escapeQuote
method `$`*(token: Text): string =
token.doc.escapeAmpersandChar.escapeTag.escapeQuote
method `$`*(token: AutoLink): string =
let href = token.url.escapeLinkUrl.escapeAmpersandSeq
let text = token.text.escapeAmpersandSeq
a(href=href, text)
method `$`*(token: CodeBlock): string =
var codeHTML = token.doc.escapeCode.escapeQuote
if codeHTML != "" and not codeHTML.endsWith("\n"):
codeHTML &= "\n"
if token.info == "":
pre(code(codeHTML))
else:
let info = token.info.escapeBackslash.escapeHTMLEntity
let lang = "language-" & info
pre(code(class=lang, codeHTML))
method `$`*(token: HtmlBlock): string =
token.doc.strip(chars={'\n'})
method `$`*(token: Link): string =
let href = token.url.escapeBackslash.escapeLinkUrl
let title = token.title.escapeBackslash.escapeHTMLEntity.escapeAmpersandSeq.escapeQuote
if title == "": a(href=href, token.render(""))
else: a(href=href, title=title, token.render(""))
proc toAlt*(token: Token): string =
if (token of Em) or (token of Strong): token.render("")
elif token of Link: Link(token).text
elif token of Image: Image(token).alt
else: $token
proc childrenToAlt(token: Token): string =
for child in token.children:
result &= child.toAlt
method `$`*(token: Image): string =
let src = token.url.escapeBackslash.escapeLinkUrl
let title=token.title.escapeBackslash.escapeHTMLEntity.escapeAmpersandSeq.escapeQuote
let alt = token.childrenToAlt()
if title == "": img(src=src, alt=alt)
else: img(src=src, alt=alt, title=title)
method `$`*(token: Em): string = em(token.render(""))
method `$`*(token: Strong): string = strong(token.render(""))
method `$`*(token: Paragraph): string =
if token.children.head == nil: ""
elif token.loose: p(token.render(""))
else: token.render("")
method `$`*(token: Heading): string =
let num = $token.level
let child = token.render("")
fmt"<h{num}>{child}</h{num}>"
method `$`*(token: THeadCell): string =
let align = token.align
let child = token.render("")
if align == "": th(child)
else: fmt("<th align=\"{align}\">{child}</th>")
method `$`*(token: TBodyCell): string =
let align = token.align
let child = token.render("")
if align == "": td(child)
else: fmt("<td align=\"{align}\">{child}</td>")
method `$`*(token: TableRow): string =
let cells = token.render("\n")
tr("\n", cells , "\n")
method `$`*(token: TBody): string =
let rows = token.render("\n")
tbody("\n", rows)
method `$`*(token: THead): string =
let tr = $token.children.head.value # table>thead>tr
thead("\n", tr, "\n")
method `$`*(token: HtmlTable): string =
let thead = $token.children.head.value # table>thead
var tbody = $token.children.tail.value
if tbody != "": tbody = "\n" & tbody.strip
table("\n", thead, tbody)
proc renderListItemChildren(token: Li): string =
var html: string
if token.children.head == nil: return ""
for child_node in token.children.nodes:
var child_token = child_node.value
if child_token of Paragraph and not Paragraph(child_token).loose:
if child_node.prev != nil:
result &= "\n"
result &= $child_token
if child_node.next == nil:
return result
else:
html = $child_token
if html != "":
result &= "\n"
result &= html
if token.loose or token.children.tail != nil:
result &= "\n"
method `$`*(token: Li): string =
li(renderListItemChildren(token)) & "\n"
method `$`*(token: Ol): string =
if token.start != 1:
ol(start = $token.start, "\n", render(token))
else:
ol("\n", render(token))
method `$`*(token: Ul): string =
ul("\n", render(token))
method `$`*(token: Blockquote): string =
let content = render(token)
blockquote("\n", if content.len > 0: content & "\n" else: "")
proc render*(token: Token, sep = "\n"): string =
for child in token.children:
if result.len > 0 and not result.endsWith sep:
result &= sep
result &= $child
proc endsWithBlankLine(token: Token): bool =
if token of Paragraph:
Paragraph(token).trailing.len > 1
elif token of Li:
Li(token).verbatim.find(re"\n\n$") != -1
else:
token.doc.find(re"\n\n$") != -1
proc parseLoose(token: Token): bool =
for node in token.children.nodes:
if node.next != nil and node.value.endsWithBlankLine:
return true
for itemNode in node.value.children.nodes:
if itemNode.next != nil and itemNode.value.endsWithBlankLine:
return true
return false
proc parseOrderedListItem*(doc: string, start=0, marker: var string, listItemDoc: var string, index: var int = 1): int =
let markerRegex = re"(?P<leading> {0,3})(?<index>\d{1,9})(?P<marker>\.|\))(?: *$| *\n|(?P<indent> +)([^\n]+(?:\n|$)))"
var matches: array[5, string]
var pos = start
var firstLineSize = doc.matchLen(markerRegex, matches, pos)
if firstLineSize == -1:
return -1
pos += firstLineSize
var leading = matches[0]
if marker == "":
marker = matches[2]
if marker != matches[2]:
return -1
var indexString = matches[1]
index = indexString.parseInt
listItemDoc = matches[4]
var indent = 1
if matches[3].len > 1 and matches[3].len <= 4:
indent = matches[3].len
elif matches[3].len > 4:
listItemDoc = matches[3][1 ..< matches[3].len] & listItemDoc
var padding = indexString.len + marker.len + leading.len + indent
var size = 0
while pos < doc.len:
size = doc.matchLen(re(r"(?:\s*| {" & $padding & r"}([^\n]*))(\n|$)"), matches, pos)
if size != -1:
listItemDoc &= matches[0]
listItemDoc &= matches[1]
if listItemDoc.startswith("\n") and matches[0] == "":
pos += size
break
elif listItemDoc.find(re"\n{2,}$") == -1:
var firstLineSize = findFirstLine(doc, pos)
var firstLineEnd = pos + firstLineSize
if isContinuationText(doc, pos, firstLineEnd):
listItemDoc &= substr(doc, pos, firstLineEnd)
size = firstLineSize
else:
break
else:
break
pos += size
return pos - start
proc parseUnorderedListItem*(doc: string, start=0, marker: var string, listItemDoc: var string): int =
# thematic break takes precedence over list item.
if doc.matchLen(re(THEMATIC_BREAK_RE), start) != -1:
return -1
# OL needs to include <empty> as well.
let markerRegex = re"(?P<leading> {0,3})(?P<marker>[*\-+])(?:(?P<empty> *(?:\n|$))|(?<indent>(?: +|\t+))([^\n]+(?:\n|$)))"
var matches: array[5, string]
var pos = start
var firstLineSize = doc.matchLen(markerRegex, matches, pos)
if firstLineSize == -1:
return -1
pos += firstLineSize
var leading = matches[0]
if marker == "":
marker = matches[1]
if marker != matches[1]:
return -1
if matches[2] != "":
listItemDoc = "\n"
else:
listItemDoc = matches[4]
var indent = 1
if matches[3].contains(re"\t"):
indent = 1
listItemDoc = " ".repeat(matches[3].len * 4 - 2) & listItemDoc
elif matches[3].len > 1 and matches[3].len <= 4:
indent = matches[3].len
elif matches[3].len > 4: # code block indent is still 1.
listItemDoc = matches[3][1 ..< matches[3].len] & listItemDoc
var padding = marker.len + leading.len + indent
var size = 0
while pos < doc.len:
size = doc.matchLen(re(r"(?:[ \t]*| {" & $padding & r"}([^\n]*))(\n|$)"), matches, pos)
if size != -1:
listItemDoc &= matches[0]
listItemDoc &= matches[1]
if listItemDoc.startswith("\n") and matches[0] == "":
pos += size
break
elif listItemDoc.find(re"\n{2,}$") == -1:
var firstLineSize = findFirstLine(doc, pos)
var firstLineEnd = pos + firstLineSize
if isContinuationText(doc, pos, firstLineEnd):
listItemDoc &= substr(doc, pos, firstLineEnd)
size = firstLineSize
else:
break
else:
break
pos += size
return pos - start
method parse*(this: UlParser, doc: string, start: int): ParseResult =
var pos = start
var marker = ""
var listItems: seq[Token]
while pos < doc.len:
var listItemDoc = ""
var itemSize = parseUnorderedListItem(doc, pos, marker, listItemDoc)
if itemSize == -1:
break
listItems.add Li(
doc: listItemDoc.strip(chars={'\n'}),
verbatim: listItemDoc,
marker: marker
)
pos += itemSize
if marker == "":
return ParseResult(token: nil, pos: -1)
var ulToken = Ul(
doc: substr(doc, start, pos-1),
)
for listItem in listItems:
ulToken.appendChild(listItem)
return ParseResult(token: ulToken, pos: pos)
method parse*(this: OlParser, doc: string, start: int): ParseResult =
var pos = start
var marker = ""
var startIndex = 1
var found = false
var index = 1
var listItems: seq[Token]
while pos < doc.len:
var listItemDoc = ""
var itemSize = parseOrderedListItem(doc, pos, marker, listItemDoc, index)
if itemSize == -1:
break
if not found:
startIndex = index
found = true
listItems.add Li(
doc: listItemDoc.strip(chars={'\n'}),
verbatim: listItemDoc,
marker: marker
)
pos += itemSize
if marker == "":
return ParseResult(token: nil, pos: -1)
var olToken = Ol(
doc: substr(doc, start, pos-1),
start: startIndex,
)
for listItem in listItems:
olToken.appendChild(listItem)
return ParseResult(token: olToken, pos: pos)
proc getThematicBreak(doc: string, start: int = 0): tuple[size: int] =
return (size: doc.matchLen(re(THEMATIC_BREAK_RE), start))
method parse*(this: ThematicBreakParser, doc: string, start: int): ParseResult =
let res = doc.getThematicBreak(start)
if res.size == -1: return ParseResult(token: nil, pos: -1)
return ParseResult(
token: ThematicBreak(),
pos: start+res.size
)
proc getFence*(doc: string, start: int = 0): tuple[indent: int, fence: string, size: int] =
var matches: array[2, string]
let size = doc.matchLen(re"((?: {0,3})?)(`{3,}|~{3,})", matches, start)
if size == -1: return (-1, "", -1)
return (
indent: matches[0].len,
fence: substr(doc, start, start+size-1).strip,
size: size
)
proc parseCodeContent*(doc: string, indent: int, fence: string): tuple[code: string, size: int]=
var closeSize = -1
var pos = 0
var codeContent = ""
let closeRe = re(r"(?: {0,3})" & fence & $fence[0] & "{0,}( |\t)*(?:$|\n)")
for line in doc.splitLines(keepEol=true):
closeSize = line.matchLen(closeRe)
if closeSize != -1:
pos += closeSize
break
if line != "\n" and line != "":
codeContent &= line.replacef(re(r"^ {0," & indent.intToStr & r"}([^\n]*)"), "$1")
else:
codeContent &= line
pos += line.len
return (codeContent, pos)
proc parseCodeInfo*(doc: string, start: int = 0): tuple[info: string, size: int] =
var matches: array[1, string]
let size = doc.matchLen(re"(?: |\t)*([^`\n]*)?(?:\n|$)", matches, start)
if size == -1:
return ("", -1)
for item in matches[0].splitWhitespace:
return (item, size)
return ("", size)
proc parseTildeBlockCodeInfo*(doc: string, start: int = 0): tuple[info: string, size: int] =
var matches: array[1, string]
let size = doc.matchLen(re"(?: |\t)*(.*)?(?:\n|$)", matches, start)
if size == -1:
return ("", -1)
for item in matches[0].splitWhitespace:
return (item, size)
return ("", size)
method parse*(this: FencedCodeParser, doc: string, start: int): ParseResult =
var pos = start
var fenceRes = doc.getFence(start)
if fenceRes.size == -1: return ParseResult(token: nil, pos: -1)
var indent = fenceRes.indent
var fence = fenceRes.fence
pos += fenceRes.size
var infoSize = -1
var info: string
if fence.startsWith("`"):
(info, infoSize) = doc.parseCodeInfo(pos)
else:
(info, infosize) = doc.parseTildeBlockCodeInfo(pos)
if infoSize == -1: return ParseResult(token: nil, pos: -1)
pos += infoSize
var res = substr(doc, pos, doc.len-1).parseCodeContent(indent, fence)
var codeContent = res.code
pos += res.size
if doc.matchLen(re"\n$", pos) != -1:
pos += 1
let codeToken = CodeBlock(
doc: codeContent,
info: info,
)
return ParseResult(token: codeToken, pos: pos)
const rIndentedCode = r"(?: {4}| {0,3}\t)(.*\n?)"
proc getIndentedCodeFirstLine*(doc: string, start: int = 0): tuple[code: string, size: int]=
var matches: array[1, string]
if matchLen(doc, re(rIndentedCode), matches, start) == -1: return ("", -1)
if matches[0].isBlank: return ("", -1)
return (code: matches[0], size: findFirstLine(doc, start)+1)
proc getIndentedCodeRestLines*(doc: string, start: int = 0): tuple[code: string, size: int] =
var firstLineSize = findFirstLine(doc, start)
var firstLineEnd = start + firstLineSize
var code: string
var size: int
var matches: array[1, string]
for slice in findRestLines(doc, firstLineEnd+1):
if isBlank(doc, slice.start, slice.stop):
add code, substr(doc, slice.start, slice.stop-1).replace(re"^ {0,4}", "")
size += (slice.stop - slice.start)
elif matchLen(doc, re(rIndentedCode), matches, slice.start, slice.stop) != -1:
add code, matches[0]
size += (slice.stop - slice.start)
else:
break
return (code: code, size: size)
method parse*(this: IndentedCodeParser, doc: string, start: int): ParseResult =
var res = getIndentedCodeFirstLine(doc, start)
if res.size == -1: return ParseResult(token: nil, pos: -1)
var code = res.code
var pos = start + res.size
res = getIndentedCodeRestLines(doc, start)
code &= res.code
code = code.removeBlankLines
pos += res.size
return ParseResult(
token: CodeBlock(doc: code, info: ""),
pos: pos
)
proc parseIndentedCode*(doc: string, start: int): ParseResult =
IndentedCodeParser().parse(doc, start)
proc getSetextHeading*(doc: string, start = 0): tuple[level: int, doc: string, size: int] =
var firstLineSize = findFirstLine(doc, start)
var firstLineEnd = start + firstLineSize
var size = firstLineSize+1
var markerLen = 0
var matches: array[1, string]
let pattern = re(r" {0,3}(=|-)+ *(?:\n+|$)")
var level = 0
for slice in findRestLines(doc, firstLineEnd+1):
if matchLen(doc, re"(?:\n|$)", slice.start, slice.stop) != -1: # found empty line
break
if matchLen(doc, re" {4,}", slice.start, slice.stop) != -1: # found code block
size += slice.stop - slice.start
continue
if matchLen(doc, pattern, matches, slice.start, slice.stop) != -1:
markerLen = slice.stop - slice.start
size += markerLen
if matches[0] == "=":
level = 1
elif matches[0] == "-":
level = 2
break
else:
size += slice.stop - slice.start
if level == 0:
return (level: 0, doc: "", size: -1)
if matchLen(doc, re"(?:\s*\n)+", start, start+size-markerLen) != -1:
return (level: 0, doc: "", size: -1)
let doc = substr(doc, start, start+size-markerLen-1).strip
return (level: level, doc: doc, size: size)
method parse(this: SetextHeadingParser, doc: string, start: int): ParseResult =
let res = getSetextHeading(doc, start)
if res.size == -1: return ParseResult(token: nil, pos: -1)
return ParseResult(
token: Heading(