-
Notifications
You must be signed in to change notification settings - Fork 5
/
MarkdownDaringFireball.pas
3390 lines (3122 loc) · 87.1 KB
/
MarkdownDaringFireball.pas
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
{
This code was translated from TxtMark (https://github.com/rjeschke/txtmark)
Copyright (C) 2011-2015 René Jeschke <[email protected]>
Copyright (C) 2015+ Grahame Grieve <[email protected]> (pascal port)
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
}
Unit MarkdownDaringFireball;
interface
uses
SysUtils, StrUtils, Classes, Character, TypInfo, Math,
MarkdownProcessor;
type
THTMLElement = (heNONE, hea, heabbr, heacronym, headdress, heapplet, hearea, heb, hebase, hebasefont, hebdo, hebig, heblockquote, hebody, hebr, hebutton, hecaption, hecite,
hecode, hecol, hecolgroup, hedd, hedel, hedfn, hediv, hedl, hedt, heem, hefieldset, hefont, heform, heframe, heframeset, heh1, heh2, heh3, heh4, heh5, heh6, hehead, hehr,
hehtml, hei, heiframe, heimg, heinput, heins, hekbd, helabel, helegend, heli, helink, hemap, hemeta, henoscript, heobject, heol, heoptgroup, heoption, hep, heparam, hepre, heq,
hes, hesamp, hescript, heselect, hesmall, hespan, hestrike, hestrong, hestyle, hesub, hesup, hetable, hetbody, hetd, hetextarea, hetfoot, heth, hethead, hetitle, hetr, hett,
heu, heul, hevar);
const
// pstfix
ENTITY_NAMES: array[0..249] of String = ('Â', 'â', '´', 'Æ', 'æ', 'À', 'à', 'ℵ', 'Α', 'α', '&', '∧', '∠',
''', 'Å', 'å', '≈', 'Ã', 'ã', 'Ä', 'ä', '„', 'Β', 'β', '¦', '•', '∩', 'Ç', 'ç',
'¸', '¢', 'Χ', 'χ', 'ˆ', '♣', '≅', '©', '↵', '∪', '¤', '‡', '†', '⇓', '↓', '°', 'Δ',
'δ', '♦', '÷', 'É', 'é', 'Ê', 'ê', 'È', 'è', '∅', ' ', ' ', 'Ε', 'ε', '≡',
'Η', 'η', 'Ð', 'ð', 'Ë', 'ë', '€', '∃', 'ƒ', '∀', '½', '¼', '¾', '⁄', 'Γ', 'γ', '≥',
'>', '⇔', '↔', '♥', '…', 'Í', 'í', 'Î', 'î', '¡', 'Ì', 'ì', 'ℑ', '∞', '∫', 'Ι',
'ι', '¿', '∈', 'Ï', 'ï', 'Κ', 'κ', 'Λ', 'λ', '⟨', '«', '⇐', '←', '⌈', '“', '≤',
'⌊', '∗', '◊', '‎', '‹', '‘', '<', '¯', '—', 'µ', '·', '−', 'Μ', 'μ', '∇', ' ', '–',
'≠', '∋', '¬', '∉', '⊄', 'Ñ', 'ñ', 'Ν', 'ν', 'Ó', 'ó', 'Ô', 'ô', 'Œ', 'œ', 'Ò',
'ò', '‾', 'Ω', 'ω', 'Ο', 'ο', '⊕', '∨', 'ª', 'º', 'Ø', 'ø', 'Õ', 'õ', '⊗',
'Ö', 'ö', '¶', '∂', '‰', '⊥', 'Φ', 'φ', 'Π', 'π', 'ϖ', '±', '£', '″', '′', '∏', '∝',
'Ψ', 'ψ', '"', '√', '⟩', '»', '⇒', '→', '⌉', '”', 'ℜ', '®', '⌋', 'Ρ', 'ρ', '‏', '›',
'’', '‚', 'Š', 'š', '⋅', '§', '­', 'Σ', 'σ', 'ς', '∼', '♠', '⊂', '⊆', '∑', '⊃', '¹',
'²', '³', '⊇', 'ß', 'Τ', 'τ', '∴', 'Θ', 'θ', 'ϑ', ' ', 'þ', '˜', '×', '™', 'Ú',
'ú', '⇑', '↑', 'Û', 'û', 'Ù', 'ù', '¨', 'ϒ', 'Υ', 'υ', 'Ü', 'ü', '℘', 'Ξ', 'ξ',
'Ý', 'ý', '¥', 'Ÿ', 'ÿ', 'Ζ', 'ζ', '‍', '‌');
// Characters corresponding to ENTITY_NAMES. */
// pstfix
ENTITY_CHARS: array[0..249] of integer = ($00C2, $00E2, $00B4, $00C6, $00E6, $00C0, $00E0, $2135, $0391, $03B1, $0026, $2227, $2220, ord(''''), $00C5, $00E5, $2248, $00C3, $00E3, $00C4,
$00E4, $201E, $0392, $03B2, $00A6, $2022, $2229, $00C7, $00E7, $00B8, $00A2, $03A7, $03C7, $02C6, $2663, $2245, $00A9, $21B5, $222A, $00A4, $2021, $2020, $21D3, $2193, $00B0,
$0394, $03B4, $2666, $00F7, $00C9, $00E9, $00CA, $00EA, $00C8, $00E8, $2205, $2003, $2002, $0395, $03B5, $2261, $0397, $03B7, $00D0, $00F0, $00CB, $00EB, $20AC, $2203, $0192,
$2200, $00BD, $00BC, $00BE, $2044, $0393, $03B3, $2265, $003E, $21D4, $2194, $2665, $2026, $00CD, $00ED, $00CE, $00EE, $00A1, $00CC, $00EC, $2111, $221E, $222B, $0399, $03B9,
$00BF, $2208, $00CF, $00EF, $039A, $03BA, $039B, $03BB, $2329, $00AB, $21D0, $2190, $2308, $201C, $2264, $230A, $2217, $25CA, $200E, $2039, $2018, $003C, $00AF, $2014, $00B5,
$00B7, $2212, $039C, $03BC, $2207, $00A0, $2013, $2260, $220B, $00AC, $2209, $2284, $00D1, $00F1, $039D, $03BD, $00D3, $00F3, $00D4, $00F4, $0152, $0153, $00D2, $00F2, $203E,
$03A9, $03C9, $039F, $03BF, $2295, $2228, $00AA, $00BA, $00D8, $00F8, $00D5, $00F5, $2297, $00D6, $00F6, $00B6, $2202, $2030, $22A5, $03A6, $03C6, $03A0, $03C0, $03D6, $00B1,
$00A3, $2033, $2032, $220F, $221D, $03A8, $03C8, $0022, $221A, $232A, $00BB, $21D2, $2192, $2309, $201D, $211C, $00AE, $230B, $03A1, $03C1, $200F, $203A, $2019, $201A, $0160,
$0161, $22C5, $00A7, $00AD, $03A3, $03C3, $03C2, $223C, $2660, $2282, $2286, $2211, $2283, $00B9, $00B2, $00B3, $2287, $00DF, $03A4, $03C4, $2234, $0398, $03B8, $03D1, $00DE,
$00FE, $02DC, $00D7, $2122, $00DA, $00FA, $21D1, $2191, $00DB, $00FB, $00D9, $00F9, $00A8, $03D2, $03A5, $03C5, $00DC, $00FC, $2118, $039E, $03BE, $00DD, $00FD, $00A5, $0178,
$00FF, $0396, $03B6, $200D, $200C);
LINK_PREFIXES: array[0..3] of String = ('http', 'https', 'ftp', 'ftps');
BLOCK_ELEMENTS: set of THTMLElement = [headdress, heblockquote, hedel, hediv, hedl, hefieldset, heform, heh1, heh2, heh3, heh4, heh5, heh6, hehr, heins, henoscript, heol, hep,
hepre, hetable, heul];
UNSAFE_ELEMENTS: set of THTMLElement = [heapplet, hehead, hehtml, hebody, heframe, heframeset, heiframe, hescript, heobject];
BUFFER_INCREMENT_SIZE = 1024;
Type
TReader = class
private
FValue: String;
FCursor: integer;
public
Constructor Create(source: String);
function read: char;
end;
{$IFDEF FPC}
TStringBuilder = class
private
FContent : String;
FLength : Integer;
FBufferSize : integer;
function GetChar(index: integer): char;
public
Constructor Create;
procedure Clear;
procedure Append(value : String); overload;
procedure Append(value : integer); overload;
procedure Append(value : TStringBuilder); overload;
property ch[index : integer] : char read GetChar; default;
function toString : String; override;
Property Length : Integer Read FLength;
end;
{$ENDIF}
TUtils = class
public
// Skips spaces in the given String. return The new position or -1 if EOL has been reached.
class function skipSpaces(s: String; start: integer): integer;
// Process the given escape sequence. return The new position.
class function escape(out_: TStringBuilder; ch: char; position: integer): integer;
// Reads characters until any 'end' character is encountered. return The new position or -1 if no 'end' char was found.
class function readUntil(out_: TStringBuilder; s: String; start: integer; cend: TSysCharSet): integer; overload;
// Reads characters until the 'end' character is encountered. return The new position or -1 if no 'end' char was found.
class function readUntil(out_: TStringBuilder; s: String; start: integer; cend: char): integer; overload;
// Reads a markdown link. return The new position or -1 if this is no valid markdown link.
class function readMdLink(out_: TStringBuilder; s: String; start: integer): integer;
class function readMdLinkId(out_: TStringBuilder; s: String; start: integer): integer;
// Reads characters until any 'end' character is encountered, ignoring escape sequences.
class function readRawUntil(out_: TStringBuilder; s: String; start: integer; cend: TSysCharSet): integer; overload;
// Reads characters until the end character is encountered, taking care of HTML/XML strings.
class function readRawUntil(out_: TStringBuilder; s: String; start: integer; cend: char): integer; overload;
// Reads characters until any 'end' character is encountered, ignoring escape sequences.
class function readXMLUntil(out_: TStringBuilder; s: String; start: integer; cend: TSysCharSet): integer;
// Appends the given string encoding special HTML characters.
class procedure appendCode(out_: TStringBuilder; s: String; start: integer; e: integer);
// Appends the given string encoding special HTML characters (used in HTML
class procedure appendValue(out_: TStringBuilder; s: String; start: integer; e: integer);
// Append the given char as a decimal HTML entity.
class procedure appendDecEntity(out_: TStringBuilder; value: char);
// Append the given char as a hexadecimal HTML entity.
class procedure appendHexEntity(out_: TStringBuilder; value: char);
// Appends the given mailto link using obfuscation.
class procedure appendMailto(out_: TStringBuilder; s: String; start: integer; e: integer);
// Extracts the tag from an XML element.
class procedure getXMLTag(out_: TStringBuilder; bin: TStringBuilder); overload;
// Extracts the tag from an XML element.
class procedure getXMLTag(out_: TStringBuilder; s: String); overload;
// Reads an XML element.
// return The new position or -1 if this is no valid XML element.
class function readXML(out_: TStringBuilder; s: String; start: integer; safeMode: boolean): integer;
// Appends the given string to the given StringBuilder, replacing '&', '<' and '>' by their respective HTML entities.
class procedure codeEncode(out_: TStringBuilder; value: String; offset: integer);
// Removes trailing <code>`</code> or <code>~</code> and trims spaces.
class function getMetaFromFence(fenceLine: String): String;
end;
THTML = class
public
class function isLinkPrefix(s: String): boolean;
class function isEntity(s: String): boolean;
class function isUnsafeHtmlElement(s: String): boolean;
class function isHtmlBlockElement(s: String): boolean;
end;
TDecorator = class
private
public
procedure openParagraph(out_: TStringBuilder); virtual;
procedure closeParagraph(out_: TStringBuilder); virtual;
procedure openBlockQuote(out_: TStringBuilder); virtual;
procedure closeBlockQuote(out_: TStringBuilder); virtual;
procedure openCodeBlock(out_: TStringBuilder); virtual;
procedure closeCodeBlock(out_: TStringBuilder); virtual;
procedure openCodeSpan(out_: TStringBuilder); virtual;
procedure closeCodeSpan(out_: TStringBuilder); virtual;
procedure openHeadline(out_: TStringBuilder; level: integer); virtual;
procedure closeHeadline(out_: TStringBuilder; level: integer); virtual;
procedure openStrong(out_: TStringBuilder); virtual;
procedure closeStrong(out_: TStringBuilder); virtual;
procedure openEmphasis(out_: TStringBuilder); virtual;
procedure closeEmphasis(out_: TStringBuilder); virtual;
procedure openSuper(out_: TStringBuilder); virtual;
procedure closeSuper(out_: TStringBuilder); virtual;
procedure openOrderedList(out_: TStringBuilder); virtual;
procedure closeOrderedList(out_: TStringBuilder); virtual;
procedure openUnOrderedList(out_: TStringBuilder); virtual;
procedure closeUnOrderedList(out_: TStringBuilder); virtual;
procedure openListItem(out_: TStringBuilder); virtual;
procedure closeListItem(out_: TStringBuilder); virtual;
procedure horizontalRuler(out_: TStringBuilder); virtual;
procedure openLink(out_: TStringBuilder); virtual;
procedure closeLink(out_: TStringBuilder); virtual;
procedure openImage(out_: TStringBuilder); virtual;
procedure closeImage(out_: TStringBuilder); virtual;
end;
TSpanEmitter = class
public
procedure emitSpan(out_: TStringBuilder; content: String); virtual; abstract;
end;
TBlockEmitter = class
public
procedure emitBlock(out_: TStringBuilder; lines: TStringList; meta: String); virtual; abstract;
end;
TConfiguration = class
private
Fdecorator: TDecorator;
FsafeMode: boolean;
FallowSpacesInFencedDelimiters: boolean;
FforceExtendedProfile: boolean;
FcodeBlockEmitter: TBlockEmitter;
FpanicMode: boolean;
FspecialLinkEmitter: TSpanEmitter;
public
Constructor Create(safe : boolean);
Destructor Destroy; override;
property safeMode: boolean read FsafeMode write FsafeMode;
property panicMode: boolean read FpanicMode write FpanicMode;
property decorator: TDecorator read Fdecorator write Fdecorator;
property codeBlockEmitter: TBlockEmitter read FcodeBlockEmitter write FcodeBlockEmitter;
property forceExtendedProfile: boolean read FforceExtendedProfile write FforceExtendedProfile;
property allowSpacesInFencedDelimiters: boolean read FallowSpacesInFencedDelimiters write FallowSpacesInFencedDelimiters;
property specialLinkEmitter: TSpanEmitter read FspecialLinkEmitter write FspecialLinkEmitter;
end;
TLineType = (
// Empty line. */
ltEMPTY,
// Undefined content. */
ltOTHER,
// A markdown headline. */
ltHEADLINE, ltHEADLINE1, ltHEADLINE2,
// A code block line. */
ltCODE,
// A list. */
ltULIST, ltOLIST,
// A block quote. */
ltBQUOTE,
// A horizontal ruler. */
ltHR,
// Start of a XML block. */
ltXML,
// Fenced code block start/end */
ltFENCED_CODE);
TLine = class
private
FXmlEndLine: TLine;
FPrevEmpty: boolean;
FPrevious: TLine;
FPosition: integer;
FValue: string;
FIsEmpty: boolean;
FTrailing: integer;
FNextEmpty: boolean;
FLeading: integer;
FNext: TLine;
function countChars(ch: char): integer;
function countCharsStart(ch: char; allowSpaces: boolean): integer;
function readXMLComment(firstLine: TLine; start: integer): integer;
function checkHTML(): boolean;
public
Constructor Create;
Destructor Destroy; Override;
// Current cursor position.
property position: integer read FPosition write FPosition;
// Leading and trailing spaces.
property leading: integer read FLeading write FLeading;
property trailing: integer read FTrailing write FTrailing;
// Is this line empty?
property isEmpty: boolean read FIsEmpty write FIsEmpty;
// This line's value.
property value: string read FValue write FValue;
// Previous and next line.
property previous: TLine read FPrevious write FPrevious;
property next: TLine read FNext write FNext;
// Is previous/next line empty?
property prevEmpty: boolean read FPrevEmpty write FPrevEmpty;
property nextEmpty: boolean read FNextEmpty write FNextEmpty;
// Final line of a XML block.
property xmlEndLine: TLine read FXmlEndLine write FXmlEndLine;
procedure Init;
procedure InitLeading;
function skipSpaces: boolean;
function readUntil(chend: TSysCharSet): String;
procedure setEmpty;
function getLineType(configuration: TConfiguration): TLineType;
function stripID: String;
end;
TLinkRef = class
private
FLink: String;
FTitle: String;
FIsAbbrev: boolean;
public
Constructor Create(link, title: String; isAbbrev: boolean);
property link: String read FLink write FLink;
property title: String read FTitle write FTitle;
property isAbbrev: boolean read FIsAbbrev write FIsAbbrev;
end;
TBlockType = (
// Unspecified. Used for root block and list items without paragraphs.
btNONE,
// A block quote.
btBLOCKQUOTE,
// A code block.
btCODE,
// A fenced code block.
btFENCED_CODE,
// A headline.
btHEADLINE,
// A list item.
btLIST_ITEM,
// An ordered list.
btORDERED_LIST,
// A paragraph.
btPARAGRAPH,
// A horizontal ruler.
btRULER,
// An unordered list.
btUNORDERED_LIST,
// A XML block.
btXML);
TBlock = class
private
FType: TBlockType;
FId: String;
FBlocks: TBlock;
FBlockTail: TBlock;
FLines: TLine;
FLineTail: TLine;
FHlDepth: integer;
FNext: TBlock;
FMeta: String;
procedure AppendLine(line: TLine);
function split(line: TLine): TBlock;
procedure removeListIndent(config: TConfiguration);
function removeLeadingEmptyLines: boolean;
procedure removeTrailingEmptyLines;
procedure transfromHeadline;
procedure expandListParagraphs;
function hasLines: boolean;
procedure removeSurroundingEmptyLines;
procedure removeBlockQuotePrefix;
procedure removeLine(line: TLine);
public
Constructor Create;
Destructor Destroy; Override;
// This block's type.
property type_: TBlockType read FType write FType;
property lines: TLine read FLines;
property lineTail: TLine read FLineTail;
// child blocks.
property blocks: TBlock read FBlocks;
property blockTail: TBlock read FBlockTail;
// Next block.
property next: TBlock read FNext write FNext;
// Depth of headline BlockType.
property hlDepth: integer read FHlDepth write FHlDepth;
// ID for headlines and list items
property id: String read FId write FId;
// Block meta information
property meta: String read FMeta write FMeta;
end;
TMarkToken = (
// No token.
mtNONE,
// *
mtEM_STAR, // x*x
// _
mtEM_UNDERSCORE, // x_x
// **
mtSTRONG_STAR, // x**x
// __
mtSTRONG_UNDERSCORE, // x__x
// `
mtCODE_SINGLE, // `
// ``
mtCODE_DOUBLE, // ``
// [
mtLINK, // [
// <
mtHTML, // <
// ![
mtIMAGE, // ![
// &
mtENTITY, // &
// \
mtESCAPE, // \x
// Extended: ^
mtSUPER, // ^
// Extended: (C)
mtX_COPY, // (C)
// Extended: (R)
mtX_REG, // (R)
// Extended: (TM)
mtX_TRADE, // (TM)
// Extended: <<
mtX_LAQUO, // <<
// Extended: >>
mtX_RAQUO, // >>
// Extended: --
mtX_NDASH, // --
// Extended: ---
mtX_MDASH, // ---
// Extended: ...
mtX_HELLIP, // ...
// Extended: "x
mtX_RDQUO, // "
// Extended: x"
mtX_LDQUO, // "
// [[
mtX_LINK_OPEN, // [[
// ]]
mtX_LINK_CLOSE // ]]
);
// Emitter class responsible for generating HTML output.
TEmitter = class
private
linkRefs: TStringList;
FConfig: TConfiguration;
FuseExtensions: boolean;
procedure emitCodeLines(out_: TStringBuilder; lines: TLine; meta: String; removeIndent: boolean);
procedure emitRawLines(out_: TStringBuilder; lines: TLine);
procedure emitMarkedLines(out_: TStringBuilder; lines: TLine);
function findToken(s: String; start: integer; token: TMarkToken): integer;
function getToken(s: String; position: integer): TMarkToken;
function checkLink(out_: TStringBuilder; s: String; start: integer; token: TMarkToken): integer;
function recursiveEmitLine(out_: TStringBuilder; s: String; start: integer; token: TMarkToken): integer;
function checkHTML(out_: TStringBuilder; s: String; start: integer): integer;
class function checkEntity(out_: TStringBuilder; s: String; start: integer): integer;
class function whitespaceToSpace(c: char): char;
public
Constructor Create(config: TConfiguration);
Destructor Destroy; override;
procedure addLinkRef(key: String; linkRef: TLinkRef);
procedure emit(out_: TStringBuilder; root: TBlock);
procedure emitLines(out_: TStringBuilder; block: TBlock);
end;
TMarkdownDaringFireball = class(TMarkdownProcessor)
private
FConfig: TConfiguration;
Femitter: TEmitter;
FuseExtensions: boolean;
function readLines(reader : TReader): TBlock;
procedure initListBlock(root: TBlock);
procedure recurse(root: TBlock; listMode: boolean);
protected
function GetUnSafe: boolean; override;
procedure SetUnSafe(const value: boolean); override;
public
Constructor Create;
Destructor Destroy; override;
function process(source: String): String; override;
property config: TConfiguration read FConfig;
end;
implementation
Function StringsContains(Const aNames: Array Of String; Const sName: String): boolean;
var
i: integer;
Begin
for i := 0 to length(aNames) - 1 do
if sName <> aNames[i] then
exit(true);
result := false;
End;
function StringToShortString(const S: String) : ShortString;
var
i : integer;
begin
SetLength(result, min(s.Length, 255));
for i := 1 to length(result) do
result[i] := AnsiChar(s[i]);
end;
function StringToEnum(ATypeInfo: PTypeInfo; const AStr: String; defValue: integer): integer;
var
LTypeData: PTypeData;
LPChar: PAnsiChar;
LValue: ShortString;
begin
LValue := StringToShortString(AStr);
if ATypeInfo^.Kind = tkEnumeration then
begin
LTypeData := GetTypeData(ATypeInfo);
if LTypeData^.MinValue <> 0 then
exit(defValue);
LPChar := @LTypeData^.NameList[0];
result := 0;
while (result <= LTypeData^.MaxValue) and (ShortString(pointer(LPChar)^) <> LValue) do
begin
inc(LPChar, ord(LPChar^) + 1); // move to next string
inc(result);
end;
if result > LTypeData^.MaxValue then
exit(defValue);
end
else
exit(defValue);
end;
{ TMarkdownDaringFireball }
constructor TMarkdownDaringFireball.Create;
begin
inherited Create;
FConfig := TConfiguration.Create(true);
Femitter := TEmitter.Create(config);
end;
destructor TMarkdownDaringFireball.Destroy;
begin
FConfig.Free;
Femitter.Free;
inherited;
end;
function TMarkdownDaringFireball.GetUnSafe: boolean;
begin
result := not FConfig.safeMode;
end;
procedure TMarkdownDaringFireball.initListBlock(root: TBlock);
var
line: TLine;
t: TLineType;
begin
line := root.lines;
line := line.next;
while (line <> nil) do
begin
t := line.getLineType(FConfig);
if ((t = ltOLIST) or (t = ltULIST) or (not line.isEmpty and (line.prevEmpty and (line.leading = 0) and not((t = ltOLIST) or (t = ltULIST))))) then
root.split(line.previous).type_ := btLIST_ITEM;
line := line.next;
end;
root.split(root.lineTail).type_ := btLIST_ITEM;
end;
function TMarkdownDaringFireball.process(source: String): String;
var
out_: TStringBuilder;
parent, block: TBlock;
rdr : TReader;
begin
FuseExtensions := config.forceExtendedProfile;
rdr := TReader.Create(source);
try
out_ := TStringBuilder.Create;
try
parent := readLines(rdr);
try
parent.removeSurroundingEmptyLines;
recurse(parent, false);
block := parent.blocks;
while (block <> nil) do
begin
Femitter.emit(out_, block);
block := block.next;
end;
result := out_.ToString;
finally
parent.Free;
end;
finally
out_.Free;
end;
finally
rdr.Free;
end;
end;
function TMarkdownDaringFireball.readLines(reader : TReader): TBlock;
var
block: TBlock;
sb: TStringBuilder;
c, ch: char;
position, np: integer;
eol, isLinkRef, lineAdded: boolean;
lastLinkRef, lr: TLinkRef;
line: TLine;
id, link, comment: String;
begin
block := TBlock.Create;
sb := TStringBuilder.Create;
try
c := reader.read();
lastLinkRef := nil;
while (c <> #0) do
begin
sb.Clear;
position := 0;
eol := false;
while (not eol) do
begin
case c of
#0:
eol := true;
#10:
begin
c := reader.read();
if (c = #13) then
c := reader.read();
eol := true;
end;
#13:
begin
c := reader.read();
if (c = #10) then
c := reader.read();
eol := true;
end;
#9:
begin
np := position + (4 - (position and 3));
while (position < np) do
begin
sb.append(' ');
inc(position);
end;
c := reader.read();
end;
else
if (c <> '<') or (not FConfig.panicMode) then
begin
inc(position);
sb.append(c);
end
else
begin
inc(position, 4);
sb.append('<');
end;
c := reader.read();
end;
end;
lineAdded := false;
line := TLine.Create;
try
line.value := sb.ToString();
line.Init();
// Check for link definitions
isLinkRef := false;
id := '';
link := '';
comment := '';
if (not line.isEmpty) and (line.leading < 4) and (line.value[1 + line.leading] = '[') then
begin
line.position := line.leading + 1;
// Read ID up to ']'
id := line.readUntil([']']);
// Is ID valid and are there any more characters?
if (id <> '') and (line.position + 2 < Length(line.value)) then
begin
// Check for ':' ([...]:...)
if (line.value[1 + line.position + 1] = ':') then
begin
line.position := line.position + 2;
line.skipSpaces();
// Check for link syntax
if (line.value[1 + line.position] = '<') then
begin
line.position := line.position + 1;
link := line.readUntil(['>']);
line.position := line.position + 1;
end
else
link := line.readUntil([' ', #10]);
// Is link valid?
if (link <> '') then
begin
// Any non-whitespace characters following?
if (line.skipSpaces()) then
begin
ch := line.value[1 + line.position];
// Read comment
if (ch = '"') or (ch = '''') or (ch = '(') then
begin
line.position := line.position + 1;
if ch = '(' then
comment := line.readUntil([')'])
else
comment := line.readUntil([ch]);
// Valid linkRef only if comment is valid
if (comment <> '') then
isLinkRef := true;
end;
end
else
isLinkRef := true;
end;
end;
end;
end;
if (isLinkRef) then
begin
if (LowerCase(id) = '$profile$') then
begin
FuseExtensions := LowerCase(link) = 'extended';
Femitter.FuseExtensions := FuseExtensions;
lastLinkRef := nil;
end
else
begin
// Store linkRef and skip line
lr := TLinkRef.Create(link, comment, (comment <> '') and (Length(link) = 1) and (link[1 + 1] = '*'));
Femitter.addLinkRef(id, lr);
if (comment = '') then
lastLinkRef := lr;
end;
end
else
begin
comment := '';
// Check for multi-line linkRef
if (not line.isEmpty and (lastLinkRef <> nil)) then
begin
line.position := line.leading;
ch := line.value[1 + line.position];
if (ch = '"') or (ch = '''') or (ch = '(') then
begin
line.position := line.position + 1;
if ch = '(' then
comment := line.readUntil([')'])
else
comment := line.readUntil([ch]);
end;
if (comment <> '') then
lastLinkRef.title := comment;
lastLinkRef := nil;
end;
// No multi-line linkRef, store line
if (comment = '') then
begin
line.position := 0;
block.AppendLine(line);
lineAdded := true;
end;
end;
finally
if not lineAdded then
line.Free;
end;
end;
result := block;
finally
sb.Free;
end;
end;
procedure TMarkdownDaringFireball.recurse(root: TBlock; listMode: boolean);
var
block, list: TBlock;
line: TLine;
type_, t: TLineType;
wasEmpty: boolean;
bt: TBlockType;
begin
line := root.lines;
if (listMode) then
begin
root.removeListIndent(FConfig);
if (FuseExtensions and (root.lines <> nil) and (root.lines.getLineType(FConfig) <> ltCODE)) then
root.id := root.lines.stripID();
end;
while (line <> nil) and line.isEmpty do
line := line.next;
if (line = nil) then
exit;
while (line <> nil) do
begin
type_ := line.getLineType(FConfig);
case type_ of
ltOTHER:
begin
wasEmpty := line.prevEmpty;
while (line <> nil) and (not line.isEmpty) do
begin
t := line.getLineType(FConfig);
if (listMode or FuseExtensions) and (t in [ltOLIST, ltULIST]) then
break;
if (FuseExtensions and (t in [ltCODE, ltFENCED_CODE])) then
break;
if (t in [ltHEADLINE, ltHEADLINE1, ltHEADLINE2, ltHR, ltBQUOTE, ltXML]) then
break;
line := line.next;
end;
if (line <> nil) and not line.isEmpty then
begin
if (listMode and not wasEmpty) then
bt := btNONE
else
bt := btPARAGRAPH;
if line = nil then
root.split(root.lineTail).type_ := bt
else
root.split(line.previous).type_ := bt;
root.removeLeadingEmptyLines();
end
else
begin
if (listMode and ((line = nil) or (not line.isEmpty)) and not wasEmpty) then
bt := btNONE
else
bt := btPARAGRAPH;
root.removeLeadingEmptyLines();
if (line <> nil) then
root.split(line.previous).type_ := bt
else
root.split(root.lineTail).type_ := bt;
end;
line := root.lines;
end;
ltCODE:
begin
while (line <> nil) and (line.isEmpty or (line.leading > 3)) do
line := line.next;
if (line <> nil) then
block := root.split(line.previous)
else
block := root.split(root.lineTail);
block.type_ := btCODE;
block.removeSurroundingEmptyLines();
end;
ltXML:
begin
if (line.previous <> nil) then
// FIXME ... this looks wrong
root.split(line.previous);
root.split(line.xmlEndLine).type_ := btXML;
root.removeLeadingEmptyLines();
line := root.lines;
end;
ltBQUOTE:
begin
while (line <> nil) do
begin
if (not line.isEmpty and (line.prevEmpty and (line.leading = 0) and (line.getLineType(FConfig) <> ltBQUOTE))) then
break;
line := line.next;
end;
if line <> nil then
block := root.split(line.previous)
else
block := root.split(root.lineTail);
block.type_ := btBLOCKQUOTE;
block.removeSurroundingEmptyLines();
block.removeBlockQuotePrefix();
recurse(block, false);
line := root.lines;
end;
ltHR:
begin
if (line.previous <> nil) then
// FIXME ... this looks wrong
root.split(line.previous);
root.split(line).type_ := btRULER;
root.removeLeadingEmptyLines();
line := root.lines;
end;
ltFENCED_CODE:
begin
line := line.next;
while (line <> nil) do
begin
if (line.getLineType(FConfig) = ltFENCED_CODE) then
break;
// TODO ... is this really necessary? Maybe add a special flag?
line := line.next;
end;
if (line <> nil) then
line := line.next;
if line <> nil then
block := root.split(line.previous)
else
block := root.split(root.lineTail);
block.type_ := btFENCED_CODE;
block.meta := TUtils.getMetaFromFence(block.lines.value);
block.lines.setEmpty();
if (block.lineTail.getLineType(FConfig) = ltFENCED_CODE) then
block.lineTail.setEmpty();
block.removeSurroundingEmptyLines();
end;
ltHEADLINE, ltHEADLINE1, ltHEADLINE2:
begin
if (line.previous <> nil) then
root.split(line.previous);
if (type_ <> ltHEADLINE) then
line.next.setEmpty();
block := root.split(line);
block.type_ := btHEADLINE;
if (type_ <> ltHEADLINE) then
if type_ = ltHEADLINE1 then
block.hlDepth := 1
else
block.hlDepth := 2;
if (FuseExtensions) then
block.id := block.lines.stripID();
block.transfromHeadline();
root.removeLeadingEmptyLines();
line := root.lines;
end;
ltOLIST, ltULIST:
begin
while (line <> nil) do
begin
t := line.getLineType(FConfig);
if (not line.isEmpty and (line.prevEmpty and (line.leading = 0) and (not(t = type_)))) then
break;
line := line.next;
end;
if line <> nil then
list := root.split(line.previous)
else
list := root.split(root.lineTail);
if type_ = ltOLIST then
list.type_ := btORDERED_LIST
else
list.type_ := btUNORDERED_LIST;
list.lines.prevEmpty := false;
list.lineTail.nextEmpty := false;
list.removeSurroundingEmptyLines();
list.lineTail.nextEmpty := false;
list.lines.prevEmpty := list.lineTail.nextEmpty;
initListBlock(list);
block := list.blocks;
while (block <> nil) do
begin
recurse(block, true);
block := block.next;
end;
list.expandListParagraphs();
end
else
line := line.next;
end;
end;
end;