-
Notifications
You must be signed in to change notification settings - Fork 56
/
MarkdownCommonMark.pas
3694 lines (3389 loc) · 98.6 KB
/
MarkdownCommonMark.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
Unit MarkdownCommonMark;
{
Copyright (c) 2011+, Health Intersections Pty Ltd (http://www.healthintersections.com.au)
All rights reserved.
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
* Neither the name of HL7 nor the names of its contributors may be used to
endorse or promote products derived from this software without specific
prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 'AS IS' AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
}
{$IFDEF FPC}{$MODE DELPHI}{$ENDIF}
{
How to use this - see MarkdownProcessor; this unit is not intended to be used directly
Still to do:
- link references
- follow up on a few failing tests that I don't understand - see mode : too-hard
- test under FPC
not planned to be supported
- HTML blocks
note: tests related to link references and HTML blocks run (to check that the processing doesn't blow up), but output comparison is never checked
note about GFM:
the GFM tests and the CommonMark tests disagree about proper
processing of lists indented more than 3 spaces. This is probably
just poor quality in the GFM tests, which do have a number of inconsistencies
}
interface
uses
SysUtils, Classes, Math, Generics.Collections, Character,
MarkdownUnicodeUtils,
{$IFDEF FPC}
RegExpr,
UnicodeData,
{$ELSE}
System.RegularExpressions,
{$ENDIF}
MarkdownHTMLEntities,
MarkdownProcessor;
const
LENGTH_INCREMENT = 116;
EMAIL_REGEX = '^[a-zA-Z0-9.!#$%&''*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$';
TEST_STYLING = false; // set this true to check style tracking while doing unit tests (10% speed hit)
type
TCommonMarkStyle = (cmUnknown, cmText, cmEntity, cmControlChar, cmDelimiter, cmCode, cmURL, cmTableMarker, cmDel);
{$IFDEF FPC}
{ TStringBuilder }
TStringBuilder = class
private
FBuild : String;
FLength : integer;
public
procedure clear;
procedure append(c : char); overload;
procedure append(s : String); overload;
function toString : String; override;
end;
{ TRegEx }
TRegEx = class
public
class function isMatch(cnt, regex : String) : boolean;
end;
{$ENDIF}
TCMWhitespaceMode = (wsLeave, wsTrim, wsStrip);
// parser location tracking is done to support syntax highlighting. The parser won't report any errors from the markdown
TLocation = record
line : integer;
col : integer;
end;
// Abstract Syntax Tree
// inlines
TCMTextNode = class
private
FName: String;
FAttrs: TDictionary<String, String>;
FContent : String;
FBuild : String;
FLength : integer;
FOpener, FCloser : boolean;
FActive: boolean;
FPos : TLocation; // start offset in this text
// Start : Integer;
function GetAttrs: TDictionary<String, String>;
function renderAttrs : String;
procedure render(b : TStringBuilder);
function getText : String;
procedure SetName(const Value: String);
procedure SetActive(const Value: boolean);
public
constructor Create(loc : TLocation);
destructor Destroy; override;
property name : String read FName write SetName; // '' means just a test node
property attrs : TDictionary<String,String> read GetAttrs;
property opener : boolean read FOpener write FOpener;
property closer : boolean read FCloser write FCloser;
property active : boolean read FActive write SetActive;
procedure addText(ch : char); overload;
procedure addText(s : String); overload;
procedure removeChars(count : integer);
function isEmpty : boolean;
end;
TCMTextNodes = class (TObjectList<TCMTextNode>)
public
function addOpener(loc : TLocation; name : String) : TCMTextNode;
function addText(loc : TLocation; cnt : String) : TCMTextNode; // if the last is text and active, add to that
function addTextNode(loc : TLocation; cnt : String) : TCMTextNode; // always make a new node, and make it inactive
function addCloser(loc : TLocation; name : String) : TCMTextNode;
// image parsing
function plainTextSince(node : TCMTextNode) : String;
procedure removeAfter(node : TCMTextNode);
// emph processing
procedure addOpenerAfter(name : String; node : TCMTextNode); // line/col = 0,0
procedure addCloserBefore(name : String; node : TCMTextNode); // line/col = 0,0
end;
// blocks
TCMBlock = class abstract (TObject)
private
FClosed: boolean;
FLine : integer;
protected
procedure render(parent : TCMBlock; b : TStringBuilder); virtual; abstract;
function wsMode : TCMWhitespaceMode; virtual;
public
constructor Create(line : Integer);
property closed : boolean read FClosed write FClosed;
property line : Integer read FLine;
end;
TCMContainerBlock = class abstract (TCMBlock)
private
FBlocks: TObjectList<TCMBlock>;
protected
procedure render(parent : TCMBlock; b : TStringBuilder); override;
public
constructor Create(line : Integer);
destructor Destroy; override;
property blocks : TObjectList<TCMBlock> read FBlocks;
end;
TCommonMarkDocument = class (TCMContainerBlock);
TCMParagraphBlock = class (TCMContainerBlock)
private
FHeader: integer;
protected
procedure render(parent : TCMBlock; b : TStringBuilder); override;
public
function isPlainPara : boolean; virtual;
property header : integer read FHeader write FHeader;
end;
TCMQuoteBlock = class (TCMParagraphBlock)
protected
procedure render(parent : TCMBlock; b : TStringBuilder); override;
public
function isPlainPara : boolean; override;
end;
TCMListBlock = class (TCMContainerBlock)
private
FOrdered: boolean;
FStart: String;
FMarker: String;
FLoose: boolean;
FLastIndent: integer;
FBaseIndent: integer;
FHasSeenEmptyLine : boolean; // parser state
function grace : integer;
protected
procedure render(parent : TCMBlock; b : TStringBuilder); override;
public
property ordered : boolean read FOrdered write FOrdered;
property baseIndent : integer read FBaseIndent write FBaseIndent;
property lastIndent : integer read FLastIndent write FLastIndent;
property start : String read FStart write FStart;
property marker : String read FMarker write FMarker;
property loose : boolean read FLoose write FLoose;
end;
TCMListItemBlock = class (TCMParagraphBlock)
protected
procedure render(parent : TCMBlock; b : TStringBuilder); override;
public
function isPlainPara : boolean; override;
end;
TCMHeadingBlock = class (TCMContainerBlock)
private
FLevel: integer;
protected
procedure render(parent : TCMBlock; b : TStringBuilder); override;
public
constructor Create(line, level : Integer);
property level : integer read FLevel write FLevel;
end;
TCMCodeBlock = class (TCMContainerBlock)
private
FFenced: boolean;
FLang: String;
protected
procedure render(parent : TCMBlock; b : TStringBuilder); override;
function wsMode : TCMWhitespaceMode; override;
public
property fenced : boolean read FFenced write FFenced;
property lang : String read FLang write FLang;
end;
// contained blocks are cells
TCMTableRowBlock = class (TCMContainerBlock)
protected
procedure render(parent : TCMBlock; b : TStringBuilder); override;
end;
TTextAlign = (taLeft, taCenter, taRight);
// contained blocks are rows. The first row is the title row
TCMTableBlock = class (TCMContainerBlock)
private
FColumns: TArray<TTextAlign>;
protected
procedure render(parent : TCMBlock; b : TStringBuilder); override;
public
property columns : TArray<TTextAlign> read FColumns;
end;
TCMLeafBlock = class abstract (TCMBlock);
TCMThematicBreakBlock = class (TCMLeafBlock)
protected
procedure render(parent : TCMBlock; b : TStringBuilder); override;
end;
TCMTextBlock = class (TCMLeafBlock)
private
FText: String;
FNodes : TCMTextNodes;
protected
procedure render(parent : TCMBlock; b : TStringBuilder); override;
public
constructor Create(line : integer; text : String);
destructor Destroy; override;
property text : String read FText write FText;
end;
// Parser Infrastructure
TCommonMarkEngine = class;
TCMLine = class
private
FLine : String;
FIndex : integer;
FCursor : integer; // fCursor is the corrected character cursor, not the character offset
FMark : integer;
FStyling : boolean;
FStyles : Array of TCommonMarkStyle;
FBlockOffset : integer;
FBlockPreSpaces : integer;
procedure getOffset(position : integer; var index : integer; var preSpaces : integer);
procedure reset;
procedure markBlock(stop : integer);
procedure markStyle(stop : integer; style : TCommonMarkStyle);
procedure updateStyle(start, length : integer; style : TCommonMarkStyle);
procedure markRemainder(style : TCommonMarkStyle);
function GetStyle(index: integer): TCommonMarkStyle;
function GetStyleCount: integer;
public
constructor create(styling : boolean; line : string; index : integer);
procedure mark;
procedure rewind;
procedure advance(len : integer); // advance x number of spaces or characters
procedure skipWS; // advance from the current cursor until not pointing at whitespace
function isEmpty : boolean; // is cursor at end of string
function focus : String; // what is left after cursor
function countWS : integer; // whitespace count from cursor
function isWhitespace : boolean; // if everything after cursor is whitespace
property Styles[index : integer] : TCommonMarkStyle read GetStyle;
property StyleCount : integer read GetStyleCount;
end;
TCMBlockProcessingContext = (bpGeneral, bpCodeBlock, bpFencedCodeBlock);
TCMBlockProcessor = class abstract (TObject)
protected
FParent : TCMBlockProcessor;
// this procedure processes a line for nested blocks
// return true if the block is done.
// if false, modify the line, removing prepended characters, and remember to grab the characters as you go
function processLine(line : TCMLine; root : boolean; context : TCMBlockProcessingContext; isGFM : boolean; var isLazy : boolean) : boolean; virtual; abstract;
function isList(ordered : boolean; marker : String; indent : integer) : boolean; virtual;
function inListOrQuote : boolean; virtual;
function parser : TCommonMarkEngine; virtual;
public
constructor Create(processor : TCMBlockProcessor);
end;
// this anchors the chain
TCMDocumentProcessor = class (TCMBlockProcessor)
private
FParser : TCommonMarkEngine;
protected
function processLine(line : TCMLine; root : boolean; context : TCMBlockProcessingContext; isGFM : boolean; var isLazy : boolean) : boolean; override;
function parser : TCommonMarkEngine; override;
public
constructor Create(parser : TCommonMarkEngine);
end;
TCMQuoteProcessor = class (TCMBlockProcessor)
private
quote : TCMQuoteBlock;
protected
function processLine(line : TCMLine; root : boolean; context : TCMBlockProcessingContext; isGFM : boolean; var isLazy : boolean) : boolean; override;
function inListOrQuote : boolean; override;
public
constructor Create(processor : TCMBlockProcessor; q : TCMQuoteBlock);
end;
TCMListProcessor = class (TCMBlockProcessor)
private
FList : TCMListBlock;
FItem : TCMListItemBlock;
FHasContent : boolean;
FEmptyLine : integer;
protected
function processLine(line : TCMLine; root : boolean; context : TCMBlockProcessingContext; isGFM : boolean; var isLazy : boolean) : boolean; override;
function isList(ordered : boolean; marker : String; indent : integer) : boolean; override;
function inListOrQuote : boolean; override;
public
constructor Create(processor : TCMBlockProcessor; list : TCMListBlock; item : TCMListItemBlock);
destructor Destroy; override;
end;
TCMTextLexer = class
private
FText : String;
FCursor : integer;
FMark, FMarkCol, FMarkLine : Integer;
FBuilder : TStringBuilder;
FLine : integer;
FCol : integer;
FStartLine : integer;
FLines : TObjectList<TCMLine>;
FStyling : boolean;
function GetDone: boolean;
function GetPeek: char;
function GetPeekNext: char;
function GetPeekLast: char;
function GetPeekEndRun: char;
public
constructor Create(text : String; lines : TObjectList<TCMLine>; startline : integer; styling : boolean);
destructor Destroy; override;
procedure mark;
procedure rewind;
property done : boolean read GetDone;
property peek : char read GetPeek;
property peekNext : char read GetPeekNext;
property peekLast : char read GetPeekLast;
property peekEndRun : char read GetPeekEndRun;
function peekRun(checkBefore : boolean): String;
function peekLen(length : integer) : String;
function peekUntil(chs : TSysCharSet) : String;
function peekWhile(chs : TSysCharSet) : String;
function grab(style : TCommonMarkStyle) : char; overload;
function grabRun(style : TCommonMarkStyle) : String; overload;
function grab(style : TCommonMarkStyle; length : integer) : String; overload;
function has(s : string) : boolean;
function runExistsAfter(s : String) : boolean;
function runExistsAfterBeforeChar(s : String; c : char) : boolean;
procedure skipWS;
function location : TLocation;
end;
TCMDelimiterMode = (dmNeither, dmOpener, dmCloser, dmBoth);
TCMDelimiter = class
private
Fmode: TCMDelimiterMode;
Fdelimiter: String;
Factive: boolean;
FNode: TCMTextNode;
public
constructor Create(node : TCMTextNode; delimiter : String; mode : TCMDelimiterMode);
function isOpener : boolean;
function isCloser : boolean;
property node : TCMTextNode read FNode;
property delimiter : String read Fdelimiter write Fdelimiter;
property active : boolean read Factive write Factive;
property mode : TCMDelimiterMode read Fmode write Fmode;
function isEmph : boolean;
end;
TCommonMarkEngine = class
private
FLines : TObjectList<TCMLine>;
FCurrentLine : integer;
FBuilder : TStringBuilder;
FEntities : TDictionary<String, String>;
FStack : TObjectList<TCMDelimiter>;
FStyling : boolean;
FGFMExtensions : boolean;
// line operations
procedure parseLines(src : String);
function grabLine : TCMLine;
function peekLine : TCMLine;
procedure redoLine;
function done : boolean;
// string operations
function allCharsSame(s : String) : boolean;
function copyTo(s : String; chs : TSysCharSet) : String;
function after(s : String; chs : TSysCharSet) : String;
function copyWhile(s : String; chs : TSysCharSet) : String;
function startsWithWS(s : String; c : char; out length : integer; wsLen : integer = 3) : boolean; overload;
function startsWithWS(s : String; c : String; out length : integer; wsLen : integer = 3) : boolean; overload;
function countWS(s : String) : integer;
function lengthWSCorrected(s : String) : integer;
function removeWS(s : String; count : integer) : String;
function stripWhitespace(s : String) : String;
function htmlEscape(s : String) : String; overload;
function htmlEscape(c : char) : String; overload;
function urlEscape(s : String; ignoreExisting : boolean = false) : String; overload;
function urlEscape(c : UnicodeChar) : String; overload;
function parseEntityString(entity : String): String;
function isEndOfTable(line : TCMLine) : boolean;
procedure parseTableLine(t : TCMTableBlock; line : TCMLine);
// status
function inPara(blocks : TObjectList<TCMBlock>; canBeQuote : boolean) : boolean;
function inList(blocks : TObjectList<TCMBlock>; ordered : boolean; marker : String; indent : integer; grace : integer; out list : TCMListBlock) : boolean;
function isBlock(cont : TCMBlock; blocks : TObjectList<TCMBlock>; line : String; wsLen : integer = 3) : boolean;
// block parsing
function parseThematicBreak(blocks : TObjectList<TCMBlock>; line : TCMLine) : boolean;
function parseHeader(blocks : TObjectList<TCMBlock>; line : TCMLine) : boolean;
function parseCodeBlock(blocks : TObjectList<TCMBlock>; line : TCMLine; processor : TCMBlockProcessor) : boolean;
function parseFencedCodeBlock(blocks : TObjectList<TCMBlock>; line : TCMLine; processor : TCMBlockProcessor) : boolean;
function parseSeTextHeader(blocks : TObjectList<TCMBlock>; line : TCMLine; isLazy : boolean; processor : TCMBlockProcessor) : boolean;
function parseQuoteBlock(blocks : TObjectList<TCMBlock>; line : TCMLine; processor : TCMBlockProcessor) : boolean;
function parseUListBlock(blocks : TObjectList<TCMBlock>; line : TCMLine; processor : TCMBlockProcessor) : boolean;
function parseOListBlock(blocks : TObjectList<TCMBlock>; line : TCMLine; processor : TCMBlockProcessor) : boolean;
function parseTableBlock(blocks : TObjectList<TCMBlock>; line : TCMLine; processor : TCMBlockProcessor) : boolean;
procedure parse(block : TCMContainerBlock; processor : TCMBlockProcessor); overload;
// link references
procedure parseLinkReferences;
// inlines
function hasEmailAddress(lexer: TCMTextLexer; var len : integer) : boolean;
procedure parseTextEscape(lexer : TCMTextLexer; nodes: TCMTextNodes; wsMode : TCMWhitespaceMode);
procedure parseEntity(lexer : TCMTextLexer; nodes : TCMTextNodes; wsMode : TCMWhitespaceMode);
function parseEntityInner(lexer : TCMTextLexer) : String;
procedure parseBackTick(lexer : TCMTextLexer; nodes: TCMTextNodes; wsMode : TCMWhitespaceMode);
procedure parseTilde(lexer : TCMTextLexer; nodes: TCMTextNodes; wsMode : TCMWhitespaceMode);
procedure parseAutoLink(lexer : TCMTextLexer; nodes : TCMTextNodes; wsMode : TCMWhitespaceMode);
procedure parseExtendedAutoLinkWeb(lexer : TCMTextLexer; nodes : TCMTextNodes; wsMode : TCMWhitespaceMode; start, linkStart : String);
procedure parseExtendedAutoLinkEmail(lexer : TCMTextLexer; nodes : TCMTextNodes; len : integer);
procedure parseDelimiter(lexer : TCMTextLexer; nodes : TCMTextNodes; wsMode : TCMWhitespaceMode; canRun : boolean);
procedure parseCloseDelimiter(lexer : TCMTextLexer; nodes : TCMTextNodes; wsMode : TCMWhitespaceMode);
function processInlineLink(lexer : TCMTextLexer; nodes : TCMTextNodes; del : TCMDelimiter) : boolean;
procedure parseTextCore(lexer : TCMTextLexer; nodes : TCMTextNodes; wsMode : TCMWhitespaceMode);
procedure parseText(lexer : TCMTextLexer; nodes : TCMTextNodes; wsMode : TCMWhitespaceMode);
function processText(text : String; wsMode : TCMWhitespaceMode; startLine : integer) : TCMTextNodes;
procedure parseInline(blocks : TObjectList<TCMBlock>; line : String);
procedure processInlines(block : TCMBlock; wsMode : TCMWhitespaceMode);
procedure processEmphasis(nodes : TCMTextNodes; stopDel : TCMDelimiter);
procedure checkLines;
public
Constructor Create;
Destructor Destroy; override;
property GFMExtensions : boolean read FGFMExtensions write FGFMExtensions;
class function process(src : String; gfm : boolean) : String;
// divided into 2 steps in case some consumer wants to process the syntax tree
class function parse(src : String; gfm : boolean) : TCommonMarkDocument; overload;
class function parseStyles(src : String; gfm : boolean) : TObjectList<TCMLine>; overload;
class function render(doc : TCommonMarkDocument) : String;
end;
TCommonMarkProcessor = class (TMarkdownProcessor)
protected
function GetUnSafe: boolean; override;
procedure SetUnSafe(const value: boolean); override;
public
function process(source : String) : String; override; // want to process the syntax tree? Use the TCommonMarkEngine Directly
end;
implementation
function null_loc : TLocation;
begin
result.line := 0;
result.col := 0;
end;
procedure debug(s : String);
begin
// writeln(s);
end;
function isWhitespaceChar(ch: char): boolean;
begin
result := CharInSet(ch, [#10, #9, ' ']);
end;
function isWhitespace(s: String): boolean;
var
ch : char;
begin
result := true;
for ch in s do
if not isWhitespaceChar(ch) then
exit(false);
end;
function isEscapable(ch : char) : boolean;
begin
result := CharInSet(ch, ['!', '"', '#', '$', '%', '&', '''', '(', ')', '*', '+', ',', '-', '.', '/', ':', ';', '<', '=', '>', '?',
'@', '[', '\', ']', '^', '_', '`', '{', '|', '}', '~']);
end;
function isUnicodePunctuation(ch : char) : boolean;
{$IFDEF FPC}
var
NType: byte;
{$ENDIF}
begin
{$IFDEF FPC}
case ch of
'0'..'9',
'a'..'z',
'A'..'Z',
'_': exit(false);
end;
if Ord(ch)<128 then
Result:= true
else if Ord(ch) >= LOW_SURROGATE_BEGIN then
exit(true)
else
begin
NType:= GetProps(Ord(ch))^.Category;
Result := not (NType<=UGC_OtherNumber);
end;
{$ELSE}
result := (ch.GetUnicodeCategory in [TUnicodeCategory.ucConnectPunctuation, TUnicodeCategory.ucDashPunctuation, TUnicodeCategory.ucClosePunctuation,
TUnicodeCategory.ucFinalPunctuation, TUnicodeCategory.ucInitialPunctuation, TUnicodeCategory.ucOtherPunctuation, TUnicodeCategory.ucOpenPunctuation, TUnicodeCategory.ucMathSymbol]);
{$ENDIF}
end;
{$IFDEF FPC}
{ TRegEx }
class function TRegEx.isMatch(cnt, regex: String): boolean;
var
r : TRegExpr;
begin
if cnt = '' then
result := false
else
begin
r := TRegExpr.create(regex);
try
result := r.exec(cnt);
finally
r.free;
end;
end;
end;
{ TStringBuilder }
procedure TStringBuilder.clear;
begin
FLength := 0;
end;
procedure TStringBuilder.append(c: char);
begin
if FLength+1 > FBuild.Length then
setLength(FBuild, FBuild.Length+LENGTH_INCREMENT);
inc(FLength);
FBuild[FLength] := c;
end;
procedure TStringBuilder.append(s: String);
var
i : integer;
begin
if FLength+length(s) > FBuild.Length then
setLength(FBuild, FBuild.Length+length(s)+LENGTH_INCREMENT);
for i := 1 to length(s) do
FBuild[FLength+i] := s[i];
inc(FLength, length(s));
end;
function TStringBuilder.toString: String;
begin
result := Copy(FBuild, 1, FLength);
end;
{$ENDIF}
{ TCMTextNode }
procedure TCMTextNode.addText(s: String);
var
ch : char;
begin
for ch in s do
addText(ch);
end;
constructor TCMTextNode.Create;
begin
inherited Create;
FActive := true;
FPos := loc;
end;
procedure TCMTextNode.addText(ch: char);
begin
if FLength+1 > FBuild.Length then
setLength(FBuild, FBuild.Length+LENGTH_INCREMENT);
inc(FLength);
FBuild[FLength] := ch;
end;
destructor TCMTextNode.Destroy;
begin
FAttrs.Free;
inherited;
end;
function TCMTextNode.GetAttrs: TDictionary<String, String>;
begin
if FAttrs = nil then
FAttrs := TDictionary<String, String>.create;
result := FAttrs;
end;
function TCMTextNode.getText: String;
begin
Active := false;
result := FContent;
end;
function TCMTextNode.isEmpty: boolean;
begin
result := FContent = '';
end;
procedure TCMTextNode.removeChars(count : integer);
begin
active := false;
delete(FContent, 1, count);
end;
procedure TCMTextNode.render(b: TStringBuilder);
begin
if FOpener then
begin
b.Append('<');
b.Append(FName);
b.Append(renderAttrs);
if FCloser then
b.Append(' />')
else
b.Append('>');
end
else if FCloser then
begin
b.Append('</');
b.Append(FName);
b.Append('>');
end
else
begin
active := false;
b.Append(Copy(FContent, 1, FLength));
end;
end;
function TCMTextNode.renderAttrs: String;
var
s : String;
begin
result := '';
if FAttrs <> nil then
begin
// arbitrary order to pass the standard tests
if FAttrs.TryGetValue('src', s) then
result := result + ' src="'+s+'"';
if FAttrs.TryGetValue('alt', s) then
result := result + ' alt="'+s+'"';
if FAttrs.TryGetValue('href', s) then
result := result + ' href="'+s+'"';
if FAttrs.TryGetValue('title', s) then
result := result + ' title="'+s+'"';
for s in FAttrs.Keys do
if (s <> 'src') and (s <> 'alt') and (s <> 'href') and (s <> 'title') then
result := result + ' '+s+'="'+FAttrs[s]+'"';
end;
end;
procedure TCMTextNode.SetActive(const Value: boolean);
begin
if active <> Value then
begin
Factive := value;
if not active then
FContent := Copy(FBuild, 1, FLength);
end;
end;
procedure TCMTextNode.SetName(const Value: String);
begin
FContent := '';
FLength := 0;
FName := Value;
active := false;
end;
{ TCMTextNodes }
function TCMTextNodes.addCloser(loc : TLocation; name: String): TCMTextNode;
begin
if count > 0 then
last.active := false;
result := TCMTextNode.Create(loc);
add(result);
result.name := name;
result.closer := true;
end;
procedure TCMTextNodes.addCloserBefore(name: String; node: TCMTextNode);
var
n : TCMTextNode;
begin
n := TCMTextNode.Create(null_loc);
insert(IndexOf(node), n);
n.name := name;
n.closer := true;
end;
function TCMTextNodes.addOpener(loc : TLocation; name: String): TCMTextNode;
begin
if count > 0 then
last.active := false;
result := TCMTextNode.Create(loc);
add(result);
result.name := name;
result.opener := true;
end;
procedure TCMTextNodes.addOpenerAfter(name: String; node: TCMTextNode);
var
n : TCMTextNode;
begin
n := TCMTextNode.Create(null_loc);
Insert(IndexOf(node)+1, n);
n.name := name;
n.opener := true;
end;
function TCMTextNodes.addText(loc : TLocation; cnt: String): TCMTextNode;
begin
if (count = 0) or (not last.active or last.opener or last.closer) then
begin
result := TCMTextNode.Create(loc);
add(result);
end
else
result := last;
result.addText(cnt);
end;
function TCMTextNodes.addTextNode(loc : TLocation; cnt: String): TCMTextNode;
begin
if count > 0 then
last.active := false;
result := TCMTextNode.Create(loc);
add(result);
result.addText(cnt);
result.active := false;
end;
function TCMTextNodes.plainTextSince(node: TCMTextNode): String;
var
i : integer;
begin
result := '';
for i := IndexOf(node)+1 to count - 1 do
if Items[i].name = 'img' then
result := result + Items[i].attrs['alt']
else
result := result + Items[i].getText;
end;
procedure TCMTextNodes.removeAfter(node: TCMTextNode);
var
i : integer;
ndx : integer;
begin
ndx := indexOf(node);
for i := count - 1 downto ndx + 1 do
Delete(i);
end;
{ TCMBlock }
constructor TCMBlock.Create(line: Integer);
begin
Inherited Create;
FLine := line;
end;
function TCMBlock.wsMode: TCMWhitespaceMode;
begin
result := wsTrim;
end;
{ TCMContainerBlock }
constructor TCMContainerBlock.Create;
begin
inherited create(line);
FBlocks := TObjectList<TCMBlock>.create(true);
end;
destructor TCMContainerBlock.Destroy;
begin
FBlocks.Free;
inherited Destroy;
end;
procedure TCMContainerBlock.render(parent : TCMBlock; b: TStringBuilder);
var
c : TCMBlock;
begin
for c in FBlocks do
c.render(self, b);
end;
{ TCMParagraphBlock }
function TCMParagraphBlock.isPlainPara: boolean;
begin
result := FHeader = 0;
end;
procedure TCMParagraphBlock.render(parent : TCMBlock; b: TStringBuilder);
var
c : TCMBlock;
first : boolean;
begin
case header of
0: b.Append('<p>');
1: b.Append('<h1>');
2: b.Append('<h2>');
end;
first := true;
for c in FBlocks do
begin
if first then
first := false
else
b.Append(#10);
c.render(self, b);
end;
case header of
0: b.Append('</p>');
1: b.Append('</h1>');
2: b.Append('</h2>');
end;
b.Append(#10);
end;
{ TCMQuoteBlock }
function TCMQuoteBlock.isPlainPara: boolean;
begin
result := false;
end;
procedure TCMQuoteBlock.render(parent : TCMBlock; b: TStringBuilder);
var
c : TCMBlock;
begin
b.Append('<blockquote>'#10);
for c in FBlocks do
c.render(self, b);
b.Append('</blockquote>'#10);
end;
{ TCMListBlock }
function TCMListBlock.grace: integer;
begin
if ordered then
result := 2
else
result := 1;
end;
procedure TCMListBlock.render(parent : TCMBlock; b: TStringBuilder);
var
c : TCMBlock;
begin
if not ordered then
b.Append('<ul>'#10)
else if start = '1' then
b.Append('<ol>'#10)
else
b.Append('<ol start="'+start+'">'#10);
for c in FBlocks do
c.render(self, b);
if ordered then
b.Append('</ol>'#10)
else
b.Append('</ul>'#10);
end;
{ TCMListItemBlock }
function TCMListItemBlock.isPlainPara: boolean;
begin
result := false;
end;
procedure TCMListItemBlock.render(parent : TCMBlock; b: TStringBuilder);
var
c, cp : TCMBlock;
first, rFirst : boolean;
begin
if Blocks.Count = 0 then
b.Append('<li>')
else
begin
b.Append('<li>');
rFirst := true;
for c in FBlocks do
if (c is TCMParagraphBlock) and (c as TCMParagraphBlock).isPlainPara and not (parent as TCMListBlock).loose then
begin
first := true;
for cp in (c as TCMParagraphBlock).Blocks do
begin
if first then
first := false
else