-
Notifications
You must be signed in to change notification settings - Fork 83
Expand file tree
/
Copy pathMarkdownDocument.cs
More file actions
6661 lines (5679 loc) · 179 KB
/
MarkdownDocument.cs
File metadata and controls
6661 lines (5679 loc) · 179 KB
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
using SkiaSharp;
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Reflection;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Xml;
using Waher.Content.Emoji;
using Waher.Content.Json;
using Waher.Content.Markdown.Functions;
using Waher.Content.Markdown.Model;
using Waher.Content.Markdown.Model.Atoms;
using Waher.Content.Markdown.Model.BlockElements;
using Waher.Content.Markdown.Model.SpanElements;
using Waher.Content.Markdown.Rendering;
using Waher.Content.Xml;
using Waher.Events;
using Waher.Runtime.Collections;
using Waher.Runtime.Inventory;
using Waher.Runtime.IO;
using Waher.Runtime.Text;
using Waher.Script;
using Waher.Script.Abstraction.Elements;
using Waher.Script.Graphs;
using Waher.Script.Model;
using Waher.Script.Operators.Matrices;
namespace Waher.Content.Markdown
{
/// <summary>
/// Delegate for markdown element callback methods.
/// </summary>
/// <param name="Element">Markdown element</param>
/// <param name="State">State object.</param>
/// <returns>If process should continue.</returns>
public delegate bool MarkdownElementHandler(MarkdownElement Element, object State);
/// <summary>
/// Delegate used for callback methods performing asynchronous Markdown processing
/// </summary>
/// <param name="State">State object.</param>
public delegate Task AsyncMarkdownProcessing(object State);
/// <summary>
/// Contains a markdown document. This markdown document class supports original markdown, as well as several markdown extensions.
/// See the markdown reference documentation provided with the library for more information.
/// </summary>
public class MarkdownDocument : IFileNameResource, IEnumerable<MarkdownElement>, IJsonEncodingHint
{
/// <summary>
/// Variable name used for storing Markdown settings.
/// </summary>
public const string MarkdownSettingsVariableName = " MarkdownSettings ";
internal static readonly Regex endOfHeader = new Regex(@"\n\s*\n", RegexOptions.Multiline | RegexOptions.Compiled);
internal static readonly Regex scriptHeader = new Regex(@"^(?'Tag'(([Ss][Cc][Rr][Ii][Pp][Tt])|([Ii][Nn][Ii][Tt]))):\s*(?'ScriptFile'[^\r\n]*)", RegexOptions.Multiline | RegexOptions.Compiled);
private readonly ChunkedList<KeyValuePair<AsyncMarkdownProcessing, object>> asyncTasks = new ChunkedList<KeyValuePair<AsyncMarkdownProcessing, object>>();
private readonly Dictionary<string, Multimedia> references = new Dictionary<string, Multimedia>();
private readonly Dictionary<string, KeyValuePair<string, bool>[]> metaData = new Dictionary<string, KeyValuePair<string, bool>[]>();
private Dictionary<string, int> footnoteNumberByKey = null;
private Dictionary<string, Footnote> footnotes = null;
private SortedDictionary<int, char> toInsert = null;
private readonly Type[] transparentExceptionTypes;
private ChunkedList<string> footnoteOrder = null;
private ChunkedList<MarkdownElement> elements;
private readonly ChunkedList<Header> headers = new ChunkedList<Header>();
private readonly IEmojiSource emojiSource;
private string markdownText;
private string fileName = string.Empty;
private string resourceName = string.Empty;
private string url = string.Empty;
private MarkdownDocument master = null;
private MarkdownDocument detail = null;
private readonly MarkdownSettings settings;
private int lastFootnote = 0;
private bool syntaxHighlighting = false;
private bool includesTableOfContents = false;
private bool isDynamic = false;
private bool? allowScriptTag = null;
private object tag = null;
/// <summary>
/// Contains a markdown document. This markdown document class supports original markdown, as well as several markdown extensions.
/// </summary>
/// <param name="MarkdownText">Markdown text.</param>
/// <param name="TransparentExceptionTypes">If an exception is thrown when processing script in markdown, and the exception is of
/// any of these types, the exception will be rethrown, instead of shown as an error in the generated output.</param>
public static Task<MarkdownDocument> CreateAsync(string MarkdownText, params Type[] TransparentExceptionTypes)
{
return CreateAsync(MarkdownText, new MarkdownSettings(), string.Empty, string.Empty, string.Empty, TransparentExceptionTypes);
}
/// <summary>
/// Contains a markdown document. This markdown document class supports original markdown, as well as several markdown extensions.
/// </summary>
/// <param name="MarkdownText">Markdown text.</param>
/// <param name="Settings">Parser settings.</param>
/// <param name="TransparentExceptionTypes">If an exception is thrown when processing script in markdown, and the exception is of
/// any of these types, the exception will be rethrown, instead of shown as an error in the generated output.</param>
public static Task<MarkdownDocument> CreateAsync(string MarkdownText, MarkdownSettings Settings, params Type[] TransparentExceptionTypes)
{
return CreateAsync(MarkdownText, Settings, string.Empty, string.Empty, string.Empty, TransparentExceptionTypes);
}
/// <summary>
/// Contains a markdown document. This markdown document class supports original markdown, as well as several markdown extensions.
/// </summary>
/// <param name="MarkdownText">Markdown text.</param>
/// <param name="Settings">Parser settings.</param>
/// <param name="FileName">If the content is coming from a file, this parameter contains the name of that file.
/// Otherwise, the parameter is the empty string.</param>
/// <param name="ResourceName">Local resource name of file, if accessed from a web server.</param>
/// <param name="URL">Full URL of resource hosting the content, if accessed from a web server.</param>
/// <param name="TransparentExceptionTypes">If an exception is thrown when processing script in markdown, and the exception is of
/// any of these types, the exception will be rethrown, instead of shown as an error in the generated output.</param>
public static async Task<MarkdownDocument> CreateAsync(string MarkdownText, MarkdownSettings Settings, string FileName, string ResourceName, string URL,
params Type[] TransparentExceptionTypes)
{
bool IsDynamic = false;
if (!(Settings.Variables is null))
{
KeyValuePair<string, bool> P = await Preprocess(MarkdownText, Settings, FileName, TransparentExceptionTypes);
MarkdownText = P.Key;
IsDynamic = P.Value;
}
MarkdownDocument Result = new MarkdownDocument(MarkdownText, IsDynamic, Settings, FileName, ResourceName, URL, TransparentExceptionTypes);
ICodecProgress Progress = Settings?.Progress;
ChunkedList<Block> Blocks = ParseTextToBlocks(Result.markdownText);
ChunkedList<KeyValuePair<string, bool>> Values = new ChunkedList<KeyValuePair<string, bool>>();
Block Block;
KeyValuePair<string, bool>[] Prev;
bool HasProgress = !(Progress is null);
string s, s2;
string Key = null;
int Start = 0;
int End = Blocks.Count - 1;
int i, j;
if (Settings.ParseMetaData && Blocks.Count > 0)
{
Block = Blocks[0];
for (i = Block.Start; i <= Block.End; i++)
{
s = Block.Rows[i];
j = s.IndexOf(':');
if (j < 0)
{
if (string.IsNullOrEmpty(Key))
break;
Values.Add(new KeyValuePair<string, bool>(s.Trim(), s.EndsWith(" ")));
}
else
{
s2 = s.Substring(0, j).TrimEnd().ToUpper();
if (string.IsNullOrEmpty(Key))
{
foreach (char ch in s2)
{
if (!char.IsLetter(ch) && !char.IsWhiteSpace(ch))
{
s2 = null;
break;
}
}
if (s2 is null)
break;
}
else
{
if (HasProgress)
await CheckEarlyHints(Result.settings.Progress, Key, Values);
if (Result.metaData.TryGetValue(Key, out Prev))
Values.AddRangeFirst(Prev);
else if (Key == "LOGIN")
Result.isDynamic = true;
Result.metaData[Key] = Values.ToArray();
}
Values.Clear();
Key = s2;
Values.Add(new KeyValuePair<string, bool>(s.Substring(j + 1).Trim(), s.EndsWith(" ")));
}
}
if (!string.IsNullOrEmpty(Key))
{
if (HasProgress)
await CheckEarlyHints(Result.settings.Progress, Key, Values);
if (Result.metaData.TryGetValue(Key, out Prev))
Values.AddRangeFirst(Prev);
else if (Key == "LOGIN")
Result.isDynamic = true;
Result.metaData[Key] = Values.ToArray();
Start++;
}
}
if (HasProgress)
await Progress.HeaderProcessed();
Result.elements = await Result.ParseBlocks(Blocks, Start, End);
if (HasProgress)
await Progress.BodyProcessed();
if (!(Result.toInsert is null))
{
StringBuilder sb = new StringBuilder();
int Last = 0;
foreach (KeyValuePair<int, char> P in Result.toInsert)
{
if (P.Key > Last)
sb.Append(Result.markdownText.Substring(Last, P.Key - Last));
sb.Append(P.Value);
Last = P.Key;
}
Result.markdownText = sb.ToString();
}
return Result;
}
private MarkdownDocument(string MarkdownText, bool IsDynamic, MarkdownSettings Settings, string FileName, string ResourceName, string URL,
params Type[] TransparentExceptionTypes)
{
this.markdownText = MarkdownText?.Replace("\r\n", "\n").Replace('\r', '\n') ?? string.Empty;
this.isDynamic = IsDynamic;
this.emojiSource = Settings.EmojiSource;
this.settings = Settings;
this.fileName = FileName;
this.resourceName = ResourceName;
this.url = URL;
this.transparentExceptionTypes = TransparentExceptionTypes;
}
private static async Task CheckEarlyHints(ICodecProgress Progress, string Key,
IEnumerable<KeyValuePair<string, bool>> Values)
{
switch (Key)
{
case "JAVASCRIPT":
foreach (KeyValuePair<string, bool> P in Values)
{
await Progress.EarlyHint(P.Key, "preload",
new KeyValuePair<string, string>("as", "script"));
}
break;
case "CSS":
foreach (KeyValuePair<string, bool> P in Values)
{
await Progress.EarlyHint(P.Key, "preload",
new KeyValuePair<string, string>("as", "style"));
}
break;
}
}
/// <summary>
/// Markdown text. This text might differ slightly from the original text passed to the document.
/// </summary>
[Obsolete("Use GenerateMarkdown() instead.")]
public string MarkdownText
{
get
{
return this.GenerateMarkdown(false).Result;
}
}
/// <summary>
/// If an exception is thrown when processing script in markdown, and the exception is of
/// any of these types, the exception will be rethrown, instead of shown as an error in the generated output.
/// </summary>
public Type[] TransparentExceptionTypes => this.transparentExceptionTypes;
/// <summary>
/// Gets the end position of the header, if one is found, null otherwise.
/// </summary>
/// <param name="Markdown">Markdown</param>
/// <returns>Position of end of header, if found.</returns>
public static int? HeaderEndPosition(string Markdown)
{
Match M = endOfHeader.Match(Markdown);
if (!M.Success)
return null;
string Header = Markdown.Substring(0, M.Index);
string[] Rows = Header.Split(CommonTypes.CRLF, StringSplitOptions.RemoveEmptyEntries);
string s;
foreach (string Row in Rows)
{
s = Row.Trim();
if (string.IsNullOrEmpty(s))
continue;
if (s.IndexOf(':') < 0)
return null;
}
return M.Index;
}
/// <summary>
/// Preprocesses markdown text.
/// </summary>
/// <param name="Markdown">Markdown text</param>
/// <param name="Settings">Markdown settings.</param>
/// <param name="TransparentExceptionTypes">If an exception is thrown when processing script in markdown, and the exception is of
/// any of these types, the exception will be rethrown, instead of shown as an error in the generated output.</param>
/// <returns>Preprocessed markdown.</returns>
public static async Task<string> Preprocess(string Markdown, MarkdownSettings Settings, params Type[] TransparentExceptionTypes)
{
KeyValuePair<string, bool> P = await Preprocess(Markdown, Settings, string.Empty, TransparentExceptionTypes);
return P.Key;
}
/// <summary>
/// Preprocesses markdown text.
/// </summary>
/// <param name="Markdown">Markdown text</param>
/// <param name="Settings">Markdown settings.</param>
/// <param name="FileName">Filename of markdown.</param>
/// <param name="TransparentExceptionTypes">If an exception is thrown when processing script in markdown, and the exception is of
/// any of these types, the exception will be rethrown, instead of shown as an error in the generated output.</param>
/// <returns>Preprocessed markdown, and if the markdown contains script, making the markdown dynamic.</returns>
public static async Task<KeyValuePair<string, bool>> Preprocess(string Markdown, MarkdownSettings Settings, string FileName, params Type[] TransparentExceptionTypes)
{
if (Settings.Variables is null)
Settings.Variables = new Variables();
Variables Variables = Settings.Variables;
Expression Exp;
string Script, s2;
int i, j;
bool IsDynamic = false;
if (!string.IsNullOrEmpty(FileName))
{
Match M = endOfHeader.Match(Markdown);
if (M.Success)
{
s2 = Markdown.Substring(0, M.Index);
foreach (Match M2 in scriptHeader.Matches(s2))
{
if (M.Success)
{
string Tag = M2.Groups["Tag"].Value.ToUpper();
string FileName2 = M2.Groups["ScriptFile"].Value;
FileName2 = Settings.GetFileName(FileName, FileName2);
if (Tag == "INIT" && !await InitScriptFile.NeedsExecution(FileName2))
continue;
try
{
Script = await Files.ReadAllTextAsync(FileName2);
if (!IsDynamic)
{
IsDynamic = true;
Variables.Add(MarkdownSettingsVariableName, Settings);
}
Exp = new Expression(Script, FileName2);
if (!(Settings.AuthorizeExpression is null))
{
ScriptNode Prohibited = await Settings.AuthorizeExpression(Exp);
if (!(Prohibited is null))
throw new UnauthorizedAccessException("Expression not permitted: " + Prohibited.SubExpression);
}
await Exp.EvaluateAsync(Variables);
}
catch (Exception ex)
{
Log.Exception(ex, FileName2);
}
}
}
}
}
i = Markdown.IndexOf("{{");
if (i < 0)
return new KeyValuePair<string, bool>(Markdown, IsDynamic);
StringBuilder Transformed = new StringBuilder();
int From = 0;
bool UsesImplicitPrint = false;
bool HasImplicitPrint = false;
object Result;
while (i >= 0)
{
j = Markdown.IndexOf("}}", i + 2);
if (j < 0)
{
if (From == 0)
return new KeyValuePair<string, bool>(Markdown, IsDynamic);
else
break;
}
if (i > From)
Transformed.Append(Markdown.Substring(From, i - From));
From = j + 2;
Script = Markdown.Substring(i + 2, j - i - 2);
try
{
Exp = new Expression(Script, FileName);
if (!(Settings.AuthorizeExpression is null))
{
ScriptNode Prohibited = await Settings.AuthorizeExpression(Exp);
if (!(Prohibited is null))
throw new UnauthorizedAccessException("Expression not permitted: " + Prohibited.SubExpression);
}
if (!IsDynamic)
{
IsDynamic = true;
Variables.Add(MarkdownSettingsVariableName, Settings);
}
HasImplicitPrint = Exp.ContainsImplicitPrint;
if (!HasImplicitPrint && UsesImplicitPrint && Exp.ReferencesImplicitPrint(Variables))
HasImplicitPrint = true;
if (HasImplicitPrint)
{
UsesImplicitPrint = true;
ValuePrinter PrinterBak = Variables.Printer;
TextWriter Bak = Variables.ConsoleOut;
StringBuilder sb = new StringBuilder();
Variables.ConsoleOut = new StringWriter(sb);
Variables.Printer = PrintMarkdown;
try
{
await Exp.EvaluateAsync(Variables);
}
finally
{
Variables.ConsoleOut?.Flush();
Variables.ConsoleOut = Bak;
Variables.Printer = PrinterBak;
}
Result = sb.ToString();
}
else
Result = await Exp.EvaluateAsync(Variables);
}
catch (Exception ex)
{
ex = Log.UnnestException(ex);
Transformed.AppendLine("<font class=\"error\">");
if (ex is AggregateException ex2)
{
foreach (Exception ex3 in ex2.InnerExceptions)
{
CheckException(ex3, TransparentExceptionTypes);
Log.Exception(ex3, FileName);
Transformed.Append("<p>");
Transformed.Append(XML.HtmlValueEncode(ex3.Message));
Transformed.AppendLine("</p>");
}
}
else
{
CheckException(ex, TransparentExceptionTypes);
Log.Exception(ex, FileName);
Transformed.AppendLine(XML.HtmlValueEncode(ex.Message));
}
Transformed.AppendLine("</font>");
Result = null;
}
if (!(Result is null))
{
if (!(Result is string s3))
s3 = await PrintMarkdown(Result, Variables);
Transformed.Append(s3);
}
i = Markdown.IndexOf("{{", From);
}
if (From < Markdown.Length)
Transformed.Append(Markdown.Substring(From));
return new KeyValuePair<string, bool>(Transformed.ToString(), IsDynamic);
}
private static async Task<string> PrintMarkdown(object Value, Variables Variables)
{
if (Expression.IsNullOrVoid(Value))
return string.Empty;
if (Value.GetType().IsValueType || Value is string)
return Value.ToString();
if (Value is XmlDocument ||
Value is IToMatrix ||
Value is Graph ||
Value is PixelInformation ||
Value is SKImage ||
Value is MarkdownDocument ||
Value is MarkdownContent ||
Value is Exception ||
Value is IMatrix ||
Value is Array)
{
using (MarkdownRenderer Renderer = new MarkdownRenderer())
{
await Renderer.RenderObject(Value, false, Variables);
return Renderer.ToString();
}
}
else
return Value.ToString();
}
internal void CheckException(Exception ex)
{
CheckException(ex, this.transparentExceptionTypes);
}
internal static void CheckException(Exception ex, Type[] TransparentExceptionTypes)
{
TypeInfo ExceptionType = ex.GetType().GetTypeInfo();
foreach (Type T in TransparentExceptionTypes)
{
if (T.IsAssignableFrom(ExceptionType))
System.Runtime.ExceptionServices.ExceptionDispatchInfo.Capture(ex).Throw();
}
}
private Task<ChunkedList<MarkdownElement>> ParseBlocks(ChunkedList<Block> Blocks)
{
return this.ParseBlocks(Blocks, 0, Blocks.Count - 1);
}
private async Task<ChunkedList<MarkdownElement>> ParseBlocks(ChunkedList<Block> Blocks, int StartBlock, int EndBlock)
{
ChunkedList<MarkdownElement> Elements = new ChunkedList<MarkdownElement>();
ChunkedList<MarkdownElement> Content;
ChunkedList<Block> AlignedBlocks;
Block NextBlock;
Block Block;
string[] Rows;
string s, s2;
string InitialSectionSeparator = null;
int BlockIndex;
int i, j, c, d;
int Index;
int SectionNr = 0;
int InitialNrColumns = 1;
bool LastHtmlIndent = false;
bool HasSections = false;
for (BlockIndex = StartBlock; BlockIndex <= EndBlock; BlockIndex++)
{
Block = Blocks[BlockIndex];
if (Block.Indent > 0)
{
if (LastHtmlIndent || Block.Rows[Block.Start].StartsWith("<")) // HTML allowed to indent.
{
LastHtmlIndent = true;
Block.Indent = 0;
Content = await this.ParseBlock(Block);
Elements.AddRange(Content);
continue;
}
c = Block.Indent;
i = BlockIndex + 1;
while (i <= EndBlock && (j = Blocks[i].Indent) > 0)
{
i++;
if (j < c)
c = j;
}
if (i == BlockIndex + 1)
Elements.Add(new CodeBlock(this, Block.Rows, Block.Start, Block.End, c - 1));
else
{
ChunkedList<string> CodeBlock = new ChunkedList<string>();
while (BlockIndex < i)
{
if (CodeBlock.Count > 0)
CodeBlock.Add(string.Empty);
Block = Blocks[BlockIndex++];
if (Block.Indent == c)
{
for (j = Block.Start; j <= Block.End; j++)
CodeBlock.Add(Block.Rows[j]);
}
else
{
s = new string('\t', Block.Indent - c);
for (j = Block.Start; j <= Block.End; j++)
CodeBlock.Add(s + Block.Rows[j]);
}
}
Elements.Add(new CodeBlock(this, CodeBlock.ToArray(), 0, CodeBlock.Count - 1, c - 1));
BlockIndex--;
}
continue;
}
else
{
LastHtmlIndent = false;
if (Block.IsPrefixedBy("```", false))
{
s = Block.Rows[Block.Start];
i = 0;
foreach (char ch in s)
{
if (ch == '`')
i++;
else
break;
}
s = s.Substring(0, i);
i = BlockIndex;
while (i <= EndBlock &&
(!(Block = Blocks[i]).Rows[Block.End].StartsWith(s) ||
(i == BlockIndex && Block.Start == Block.End)))
{
i++;
}
ChunkedList<string> Code = new ChunkedList<string>();
bool Complete = true;
if (i > EndBlock)
{
i = EndBlock;
Complete = false;
}
for (j = BlockIndex; j <= i; j++)
{
Block = Blocks[j];
if (j == BlockIndex)
Index = Block.Start + 1;
else
{
Code.Add(string.Empty);
Index = Block.Start;
}
if (j == i && Complete)
c = Block.End - 1;
else
c = Block.End;
while (Index <= c)
{
Code.Add(Block.Rows[Index]);
Index++;
}
}
Block = Blocks[BlockIndex];
s = Block.Rows[Block.Start].Substring(3).Trim('`', ' ', '\t');
CodeBlock CodeBlock;
if (s.StartsWith("base64", StringComparison.CurrentCultureIgnoreCase))
{
try
{
byte[] Bin = Convert.FromBase64String(Code.Concatenate());
s2 = Encoding.UTF8.GetString(Bin);
Rows = s2.Replace("\r\n", "\n").Replace("\r", "\n").Split('\n');
CodeBlock = new CodeBlock(this, Rows, 0, Rows.Length - 1, 0, s.Substring(6));
}
catch (Exception)
{
CodeBlock = new CodeBlock(this, Code.ToArray(), 0, Code.Count - 1, 0, s);
}
}
else
CodeBlock = new CodeBlock(this, Code.ToArray(), 0, Code.Count - 1, 0, s);
Elements.Add(CodeBlock);
if (!this.syntaxHighlighting && !string.IsNullOrEmpty(CodeBlock.Language))
{
ICodeContentHtmlRenderer HtmlRenderer = CodeBlock.CodeContentHandler<ICodeContentHtmlRenderer>();
if (HtmlRenderer is null)
this.syntaxHighlighting = true;
}
BlockIndex = i;
continue;
}
}
if (Block.IsPrefixedBy(">", false))
{
if (Block.IsSuffixedBy("<<") && Block.IsPrefixedBy(">>", false))
{
AlignedBlocks = Block.RemovePrefixAndSuffix(">>", 2, "<<");
while (BlockIndex < EndBlock &&
(NextBlock = Blocks[BlockIndex + 1]).IsPrefixedBy(">>", false) &&
NextBlock.IsSuffixedBy("<<"))
{
BlockIndex++;
AlignedBlocks.AddRange(NextBlock.RemovePrefixAndSuffix(">>", 2, "<<"));
}
Content = await this.ParseBlocks(AlignedBlocks);
if (Elements.HasLastItem && Elements.LastItem is CenterAligned CenterAligned)
CenterAligned.AddChildren(Content);
else
Elements.Add(new CenterAligned(this, Content));
}
else if (Block.IsSuffixedBy(">>"))
{
AlignedBlocks = Block.RemoveSuffix(">>");
while (BlockIndex < EndBlock &&
(NextBlock = Blocks[BlockIndex + 1]).IsSuffixedBy(">>"))
{
BlockIndex++;
AlignedBlocks.AddRange(NextBlock.RemoveSuffix(">>"));
}
Content = await this.ParseBlocks(AlignedBlocks);
if (Elements.HasLastItem && Elements.LastItem is RightAligned RightAligned)
RightAligned.AddChildren(Content);
else
Elements.Add(new RightAligned(this, Content));
}
else
{
Content = await this.ParseBlocks(Block.RemovePrefix(">", 2));
if (Elements.HasLastItem && Elements.LastItem is BlockQuote BlockQuote)
BlockQuote.AddChildren(Content);
else
Elements.Add(new BlockQuote(this, Content));
}
continue;
}
else if (Block.IsPrefixedBy("<<", false))
{
if (Block.IsSuffixedBy(">>"))
{
AlignedBlocks = Block.RemovePrefixAndSuffix("<<", 2, ">>");
while (BlockIndex < EndBlock &&
(NextBlock = Blocks[BlockIndex + 1]).IsPrefixedBy("<<", false) &&
NextBlock.IsSuffixedBy(">>"))
{
BlockIndex++;
AlignedBlocks.AddRange(NextBlock.RemovePrefixAndSuffix("<<", 2, ">>"));
}
Content = await this.ParseBlocks(AlignedBlocks);
if (Elements.HasLastItem && Elements.LastItem is MarginAligned MarginAligned)
MarginAligned.AddChildren(Content);
else
Elements.Add(new MarginAligned(this, Content));
}
else
{
AlignedBlocks = Block.RemovePrefix("<<", 2);
while (BlockIndex < EndBlock &&
(NextBlock = Blocks[BlockIndex + 1]).IsPrefixedBy("<<", false))
{
BlockIndex++;
AlignedBlocks.AddRange(NextBlock.RemovePrefix("<<", 2));
}
Content = await this.ParseBlocks(AlignedBlocks);
if (Elements.HasLastItem && Elements.LastItem is LeftAligned LeftAligned)
LeftAligned.AddChildren(Content);
else
Elements.Add(new LeftAligned(this, Content));
}
continue;
}
else if (Block.IsSuffixedBy(">>"))
{
Content = await this.ParseBlocks(Block.RemoveSuffix(">>"));
if (Elements.HasLastItem && Elements.LastItem is RightAligned RightAligned)
RightAligned.AddChildren(Content);
else
Elements.Add(new RightAligned(this, Content));
continue;
}
else if (Block.IsPrefixedBy("+>", false))
{
Content = await this.ParseBlocks(Block.RemovePrefix("+>", 3));
if (Elements.HasLastItem && Elements.LastItem is InsertBlocks InsertBlocks)
InsertBlocks.AddChildren(Content);
else
Elements.Add(new InsertBlocks(this, Content));
continue;
}
else if (Block.IsPrefixedBy("->", false))
{
Content = await this.ParseBlocks(Block.RemovePrefix("->", 3));
if (Elements.HasLastItem && Elements.LastItem is DeleteBlocks DeleteBlocks)
DeleteBlocks.AddChildren(Content);
else
Elements.Add(new DeleteBlocks(this, Content));
continue;
}
else if (Block.IsPrefixedBy("//", false))
{
string[] Comment = new string[Block.End - Block.Start + 1];
for (i = Block.Start; i <= Block.End; i++)
Comment[i] = Block.Rows[i].Substring(2);
Elements.Add(new CommentBlock(this, Comment));
continue;
}
else if (Block.End == Block.Start && (IsUnderline(Block.Rows[0], '-', true, true) || IsUnderline(Block.Rows[0], '*', true, true)))
{
Elements.Add(new HorizontalRule(this, Block.Rows[0]));
continue;
}
else if (Block.End == Block.Start && IsUnderline(Block.Rows[0], '=', true, false))
{
int NrColumns = Block.Rows[0].Split(whiteSpace, StringSplitOptions.RemoveEmptyEntries).Length;
HasSections = true;
if (!Elements.HasFirstItem)
{
InitialNrColumns = NrColumns;
InitialSectionSeparator = Block.Rows[0];
}
else
Elements.Add(new SectionSeparator(this, ++SectionNr, NrColumns, Block.Rows[0]));
continue;
}
else if (Block.End == Block.Start && IsUnderline(Block.Rows[0], '~', false, false))
{
Elements.Add(new InvisibleBreak(this, Block.Rows[0]));
continue;
}
else if (Block.IsPrefixedBy(s2 = "*", true) ||
Block.IsPrefixedBy(s2 = "+", true) ||
Block.IsPrefixedBy(s2 = "-", true))
{
ChunkedList<Block> Segments = null;
i = 0;
c = Block.End;
for (d = Block.Start + 1; d <= c; d++)
{
s = Block.Rows[d];
if (IsPrefixedBy(s, s2, true))
{
if (Segments is null)
Segments = new ChunkedList<Block>();
Segments.Add(new Block(Block.Rows, Block.Positions, 0, i, d - 1));
i = d;
}
}
Segments?.Add(new Block(Block.Rows, Block.Positions, 0, i, c));
ChunkedList<MarkdownElement> Items;
UnnumberedItem LastItem;
if (Segments is null)
{
ChunkedList<Block> SubBlocks = Block.RemovePrefix(s2, 4);
while (BlockIndex < EndBlock && (Block = Blocks[BlockIndex + 1]).Indent > 1)
{
BlockIndex++;
Block.Indent--;
SubBlocks.Add(Block);
}
Items = await this.ParseBlocks(SubBlocks);
LastItem = new UnnumberedItem(this, s2, new NestedBlock(this, Items));
if (Elements.HasLastItem && Elements.LastItem is BulletList BulletList)
BulletList.AddChild(LastItem);
else
Elements.Add(new BulletList(this, LastItem));
}
else
{
Items = await this.ParseUnnumberedItems(Segments, s2);
if (Elements.HasLastItem && Elements.LastItem is BulletList BulletList)
BulletList.AddChildren(Items);
else
Elements.Add(new BulletList(this, Items));
if (Items.HasLastItem)
LastItem = Items.LastItem as UnnumberedItem;
else
LastItem = null;
}
if (!(LastItem is null))
{
i = BlockIndex;
while (BlockIndex < EndBlock && (Block = Blocks[BlockIndex + 1]).Indent > 0)
{
BlockIndex++;
Block.Indent--;
}
if (BlockIndex > i)
{
Items = await this.ParseBlocks(Blocks, i + 1, BlockIndex);
if (LastItem.Child is NestedBlock LastItemChildren)
{
if (LastItemChildren.IsBlockElement)
LastItemChildren.AddChildren(Items);
else
{
Items.AddFirstItem(new Paragraph(this, LastItemChildren.Children, true));
LastItem.Child = new NestedBlock(this, Items);
}
}
else
{
if (LastItem.Child.IsBlockElement)
Items.AddFirstItem(LastItem.Child);
else
Items.AddFirstItem(new Paragraph(this, new ChunkedList<MarkdownElement>(LastItem.Child), true));
LastItem.Child = new NestedBlock(this, Items);