-
Notifications
You must be signed in to change notification settings - Fork 35
/
Markdown.cs
1699 lines (1417 loc) · 64.1 KB
/
Markdown.cs
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 is a modified version of Jeff Atwood's "MarkdownSharp" (original comments preserved below). The only
* real changes to this file were to reorganize the (important) regexes to a central location and mark them all
* as internally visible.
*
* Since the original is MIT-licensed (license is below), whatever updates I'm making are as well.
*/
/*
* MarkdownSharp
* -------------
* a C# Markdown processor
*
* Markdown is a text-to-HTML conversion tool for web writers
* Copyright (c) 2004 John Gruber
* http://daringfireball.net/projects/markdown/
*
* Markdown.NET
* Copyright (c) 2004-2009 Milan Negovan
* http://www.aspnetresources.com
* http://aspnetresources.com/blog/markdown_announced.aspx
*
* MarkdownSharp
* Copyright (c) 2009 Jeff Atwood
* http://stackoverflow.com
* http://www.codinghorror.com/blog/
* http://block.google.com/p/markdownsharp/
*
* History: Milan ported the Markdown processor to C#. He granted license to me so I can open source it
* and let the community contribute to and improve MarkdownSharp.
*
* 03/28/2015 - EFW - Added support for fenced code blocks.
* 04/02/2015 - EFW - Added code to fully qualify relative image filename paths in literal HTML img elements.
*/
#region Copyright and license
/*
Copyright (c) 2009 Jeff Atwood
http://www.opensource.org/licenses/mit-license.php
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
Copyright (c) 2003-2004 John Gruber
<http://daringfireball.net/>
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 block 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 "Markdown" 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 owner
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.
*/
#endregion
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Text.RegularExpressions;
namespace MarkdownSharp
{
/// <summary>
/// Markdown is a text-to-HTML conversion tool for web writers.
/// Markdown allows you to write using an easy-to-read, easy-to-write plain text format,
/// then convert it to structurally valid XHTML (or HTML).
/// </summary>
public class Markdown
{
#region Configurable options
/// <summary>
/// use ">" for HTML output, or " />" for XHTML output
/// </summary>
public static string EmptyElementSuffix
{
get { return _emptyElementSuffix; }
set { _emptyElementSuffix = value; }
}
private static string _emptyElementSuffix = " />";
/// <summary>
/// Tabs are automatically converted to spaces as part of the transform
/// this variable determines how "wide" those tabs become in spaces
/// WARNING: this configuration option does NOT work yet!
/// </summary>
public static int TabWidth
{
get { return _tabWidth; }
set { _tabWidth = value; }
}
private static int _tabWidth = 4;
/// <summary>
/// when false, email addresses will never be auto-linked
/// WARNING: this is a significant deviation from the markdown spec
/// </summary>
public static bool LinkEmails
{
get { return _linkEmails; }
set { _linkEmails = value; }
}
private static bool _linkEmails = true;
/// <summary>
/// when true, bold and italic require non-word characters on either side
/// WARNING: this is a significant deviation from the markdown spec
/// </summary>
public static bool StrictBoldItalic
{
get { return _strictBoldItalic; }
set { _strictBoldItalic = value; }
}
private static bool _strictBoldItalic = false;
/// <summary>
/// when true, RETURN becomes a literal newline
/// WARNING: this is a significant deviation from the markdown spec
/// </summary>
public static bool AutoNewLines
{
get { return _autoNewlines; }
set { _autoNewlines = value; }
}
private static bool _autoNewlines = false;
/// <summary>
/// when true, (most) bare plain URLs are auto-hyperlinked
/// WARNING: this is a significant deviation from the markdown spec
/// </summary>
public static bool AutoHyperlink
{
get { return _autoHyperlink; }
set { _autoHyperlink = value; }
}
private static bool _autoHyperlink = false;
/// <summary>
/// when true, problematic URL characters like [, ], (, and so forth will be encoded
/// WARNING: this is a significant deviation from the markdown spec
/// </summary>
public static bool EncodeProblemUrlCharacters
{
get { return _encodeProblemUrlCharacters; }
set { _encodeProblemUrlCharacters = value; }
}
private static bool _encodeProblemUrlCharacters = false;
#endregion
private enum HTMLTokenType { Text, Tag }
private struct HTMLToken
{
public HTMLToken(HTMLTokenType type, string value)
{
this.Type = type;
this.Value = value;
}
public HTMLTokenType Type;
public string Value;
}
#region Regexes and static setup
internal static readonly Dictionary<string, string> EscapeTable;
internal static readonly Dictionary<string, string> BackslashEscapeTable;
/// <summary>
/// Static constructor
/// </summary>
/// <remarks>
/// In the static constructor we'll initialize what stays the same across all transforms.
/// </remarks>
static Markdown()
{
// Table of hash values for escaped characters:
EscapeTable = new Dictionary<string, string>();
// Table of hash value for backslash escaped characters:
BackslashEscapeTable = new Dictionary<string, string>();
foreach (char c in @"\`*_{}[]()>#+-.!")
{
string key = c.ToString();
string hash = key.GetHashCode().ToString();
EscapeTable.Add(key, hash);
BackslashEscapeTable.Add(@"\" + key, hash);
}
}
internal static Regex _blankLines = new Regex(@"^[ \t]+$", RegexOptions.Multiline | RegexOptions.Compiled);
internal static Regex _newlinesLeadingTrailing = new Regex(@"^\n+|\n+\z", RegexOptions.Compiled);
internal static Regex _newlinesMultiple = new Regex(@"\n{2,}", RegexOptions.Compiled);
internal static Regex _leadingWhitespace = new Regex(@"^([ \t]*)", RegexOptions.ExplicitCapture | RegexOptions.Compiled);
internal static Regex _entireLines = new Regex(@"^.*$", RegexOptions.Multiline | RegexOptions.Compiled);
// Lists
internal const string MarkerUL = @"[*+-]";
internal const string MarkerOL = @"\d+[.]";
internal static string WholeListRegex = string.Format(@"
( # $1 = whole list
( # $2
[ ]{{0,{1}}}
({0}) # $3 = first list item marker
[ \t]+
)
(?s:.+?)
( # $4
\z
|
\n{{2,}}
(?=\S)
(?! # Negative lookahead for another list item marker
[ \t]*
{0}[ \t]+
)
)
)", string.Format("(?:{0}|{1})", MarkerUL, MarkerOL), _tabWidth - 1);
internal static Regex ListNestedRegex = new Regex(@"^" + WholeListRegex,
RegexOptions.Multiline | RegexOptions.IgnorePatternWhitespace | RegexOptions.Compiled);
internal static Regex ListTopLevelRegex = new Regex(@"(?:(?<=\n\n)|\A\n?)" + WholeListRegex,
RegexOptions.Multiline | RegexOptions.IgnorePatternWhitespace | RegexOptions.Compiled);
// Links
internal static Regex LinkDefRegex = new Regex(string.Format(@"
^[ ]{{0,{0}}}\[(.+)\]: # id = $1
[ \t]*
\n? # maybe *one* newline
[ \t]*
<?(\S+?)>? # url = $2
[ \t]*
\n? # maybe one newline
[ \t]*
(?:
(?<=\s) # lookbehind for whitespace
[\x22(]
(.+?) # title = $3
[\x22)]
[ \t]*
)? # title is optional
(?:\n+|\Z)", _tabWidth - 1), RegexOptions.Multiline | RegexOptions.IgnorePatternWhitespace | RegexOptions.Compiled);
// Anchors
internal static Regex AnchorRefRegex = new Regex(string.Format(@"
( # wrap whole match in $1
\[
({0}) # link text = $2
\]
[ ]? # one optional space
(?:\n[ ]*)? # one optional newline followed by spaces
\[
(.*?) # id = $3
\]
)", GetNestedBracketsPattern()), RegexOptions.Singleline | RegexOptions.IgnorePatternWhitespace | RegexOptions.Compiled);
internal static Regex AnchorInlineRegex = new Regex(string.Format(@"
( # wrap whole match in $1
\[
({0}) # link text = $2
\]
\( # literal paren
[ \t]*
({1}) # href = $3
[ \t]*
( # $4
(['\x22]) # quote char = $5
(.*?) # title = $6
\5 # matching quote
[ \t]* # ignore any spaces/tabs between closing quote and )
)? # title is optional
\)
)", GetNestedBracketsPattern(), GetNestedParensPattern()),
RegexOptions.Singleline | RegexOptions.IgnorePatternWhitespace | RegexOptions.Compiled);
internal static Regex AnchorRefShortcutRegex = new Regex(@"
( # wrap whole match in $1
\[
([^\[\]]+) # link text = $2; can't contain [ or ]
\]
)", RegexOptions.Singleline | RegexOptions.IgnorePatternWhitespace | RegexOptions.Compiled);
// Images
internal static Regex ImagesRefRegex = new Regex(@"
( # wrap whole match in $1
!\[
(.*?) # alt text = $2
\]
[ ]? # one optional space
(?:\n[ ]*)? # one optional newline followed by spaces
\[
(.*?) # id = $3
\]
)", RegexOptions.IgnorePatternWhitespace | RegexOptions.Singleline | RegexOptions.Compiled);
internal static Regex ImagesInlineRegex = new Regex(String.Format(@"
( # wrap whole match in $1
!\[
(.*?) # alt text = $2
\]
\s? # one optional whitespace character
\( # literal paren
[ \t]*
({0}) # href = $3
[ \t]*
( # $4
(['\x22]) # quote char = $5
(.*?) # title = $6
\5 # matching quote
[ \t]*
)? # title is optional
\)
)", GetNestedParensPattern()),
RegexOptions.IgnorePatternWhitespace | RegexOptions.Singleline | RegexOptions.Compiled);
// Headers
internal static Regex HeaderSetextRegex = new Regex(@"
^(.+?)
[ \t]*
\n
(=+|-+) # $1 = string of ='s or -'s
[ \t]*
\n+",
RegexOptions.Multiline | RegexOptions.IgnorePatternWhitespace | RegexOptions.Compiled);
internal static Regex HeaderAtxRegex = new Regex(@"
^(\#{1,6}) # $1 = string of #'s
[ \t]*
(.+?) # $2 = Header text
[ \t]*
\#* # optional closing #'s (not counted)
(?:\z|\n+)",
RegexOptions.Multiline | RegexOptions.IgnorePatternWhitespace | RegexOptions.Compiled);
// Horizontal rule
internal static Regex HorizontalRulesRegex = new Regex(@"
^[ ]{0,3} # Leading space
([-*_]) # $1: First marker
(?> # Repeated marker group
[ ]{0,2} # Zero, one, or two spaces.
\1 # Marker character
){2,} # Group repeated at least twice
[ ]* # Trailing spaces
$ # End of line.
", RegexOptions.Multiline | RegexOptions.IgnorePatternWhitespace | RegexOptions.Compiled);
// Blockquote
internal static Regex BlockquoteRegex = new Regex(@"
( # Wrap whole match in $1
(
^[ \t]*>[ \t]? # '>' at the start of a line
.+\n # rest of the first line
(.+\n)* # subsequent consecutive lines
\n* # blanks
)+
)", RegexOptions.IgnorePatternWhitespace | RegexOptions.Multiline | RegexOptions.Compiled);
// Bold/italic
internal static Regex BoldRegex = new Regex(
_strictBoldItalic ?
@"([\W_]|^) (\*\*|__) (?=\S) ([^\r]*?\S[\*_]*) \2 ([\W_]|$)" :
@"(\*\*|__) (?=\S) (.+?[*_]*) (?<=\S) \1",
RegexOptions.IgnorePatternWhitespace | RegexOptions.Singleline | RegexOptions.Compiled);
internal static Regex ItalicRegex = new Regex(
_strictBoldItalic ?
@"([\W_]|^) (\*|_) (?=\S) ([^\r\*_]*?\S) \2 ([\W_]|$)" :
@"(\*|_) (?=\S) (.+?) (?<=\S) \1",
RegexOptions.IgnorePatternWhitespace | RegexOptions.Singleline | RegexOptions.Compiled);
// Links
internal static Regex AutolinkBareRegex = new Regex(@"(^|\s)(https?|ftp)(://[-A-Z0-9+&@#/%?=~_|\[\]\(\)!:,\.;]*[-A-Z0-9+&@#/%=~_|\[\]])($|\W)",
RegexOptions.IgnoreCase | RegexOptions.Compiled);
// Code
internal static Regex CodeBlockRegex = new Regex(string.Format(@"
(?:\n\n|\A)
( # $1 = the code block -- one or more lines, starting with a space/tab
(?:
(?:[ ]{{{0}}} | \t) # Lines must start with a tab or a tab-width of spaces
.*\n+
)+
)
((?=^[ ]{{0,{0}}}\S)|\Z) # Lookahead for non-space at line-start, or end of doc",
_tabWidth), RegexOptions.Multiline | RegexOptions.IgnorePatternWhitespace | RegexOptions.Compiled);
internal static Regex CodeBlockFencedRegex = new Regex("^```(.*?)\n(.+?)^```",
RegexOptions.Multiline | RegexOptions.Singleline | RegexOptions.Compiled);
internal static Regex CodeSpanRegex = new Regex(@"
(?<!\\) # Character before opening ` can't be a backslash
(`+) # $1 = Opening run of `
(.+?) # $2 = The code block
(?<!`)
\1
(?!`)", RegexOptions.IgnorePatternWhitespace | RegexOptions.Singleline | RegexOptions.Compiled);
// HTML
internal static Regex BlocksHtmlRegex = new Regex(GetBlockPattern(), RegexOptions.Multiline | RegexOptions.IgnorePatternWhitespace);
private static string GetBlockPattern()
{
// Hashify HTML blocks:
// We only want to do this for block-level HTML tags, such as headers,
// lists, and tables. That's because we still want to wrap <p>s around
// "paragraphs" that are wrapped in non-block-level tags, such as anchors,
// phrase emphasis, and spans. The list of tags we're looking for is
// hard-coded:
//
// * List "a" is made of tags which can be both inline or block-level.
// These will be treated block-level when the start tag is alone on
// its line, otherwise they're not matched here and will be taken as
// inline later.
// * List "b" is made of tags which are always block-level;
//
string blockTagsA = "ins|del";
string blockTagsB = "p|div|h[1-6]|blockquote|pre|table|dl|ol|ul|address|script|noscript|form|fieldset|iframe|math";
// Regular expression for the content of a block tag.
string attr = @"
(?> # optional tag attributes
\s # starts with whitespace
(?>
[^>""/]+ # text outside quotes
|
/+(?!>) # slash not followed by >
|
""[^""]*"" # text inside double quotes (tolerate >)
|
'[^']*' # text inside single quotes (tolerate >)
)*
)?
";
string content = RepeatString(@"
(?>
[^<]+ # content without tag
|
<\2 # nested opening tag
" + attr + @" # attributes
(?>
/>
|
>", _nestDepth) + // end of opening tag
".*?" + // last level nested tag content
RepeatString(@"
</\2\s*> # closing nested tag
)
|
<(?!/\2\s*> # other tags with a different name
)
)*", _nestDepth);
string content2 = content.Replace(@"\2", @"\3");
// First, look for nested blocks, e.g.:
// <div>
// <div>
// tags for inner block must be indented.
// </div>
// </div>
//
// The outermost tags must start at the left margin for this to match, and
// the inner nested divs must be indented.
// We need to do this before the next, more liberal match, because the next
// match will start at the first `<div>` and stop at the first `</div>`.
string pattern = @"
(?>
(?>
(?<=\n) # Starting after a blank line
| # or
\A\n? # the beginning of the doc
)
( # save in $1
# Match from `\n<tag>` to `</tag>\n`, handling nested tags
# in between.
[ ]{0,$less_than_tab}
<($block_tags_b_re) # start tag = $2
$attr> # attributes followed by > and \n
$content # content, support nesting
</\2> # the matching end tag
[ ]* # trailing spaces/tabs
(?=\n+|\Z) # followed by a newline or end of document
| # Special version for tags of group a.
[ ]{0,$less_than_tab}
<($block_tags_a_re) # start tag = $3
$attr>[ ]*\n # attributes followed by >
$content2 # content, support nesting
</\3> # the matching end tag
[ ]* # trailing spaces/tabs
(?=\n+|\Z) # followed by a newline or end of document
| # Special case just for <hr />. It was easier to make a special
# case than to make the other regex more complicated.
[ ]{0,$less_than_tab}
<(hr) # start tag = $2
$attr # attributes
/?> # the matching end tag
[ ]*
(?=\n{2,}|\Z) # followed by a blank line or end of document
| # Special case for standalone HTML comments:
[ ]{0,$less_than_tab}
(?s:
<!-- .*? -->
)
[ ]*
(?=\n{2,}|\Z) # followed by a blank line or end of document
| # PHP and ASP-style processor instructions (<? and <%)
[ ]{0,$less_than_tab}
(?s:
<([?%]) # $2
.*?
\2>
)
[ ]*
(?=\n{2,}|\Z) # followed by a blank line or end of document
)
)";
pattern = pattern.Replace("$less_than_tab", (_tabWidth - 1).ToString());
pattern = pattern.Replace("$block_tags_b_re", blockTagsB);
pattern = pattern.Replace("$block_tags_a_re", blockTagsA);
pattern = pattern.Replace("$attr", attr);
pattern = pattern.Replace("$content2", content2);
pattern = pattern.Replace("$content", content);
return pattern;
}
internal static Regex HtmlTokensRegex = new Regex(@"
(<!(?:--.*?--\s*)+>)| # match <!-- foo -->
(<\?.*?\?>)| # match <?foo?> " +
RepeatString(@"
(<[A-Za-z\/!$](?:[^<>]|", _nestDepth) + RepeatString(@")*>)", _nestDepth) +
" # match <tag> and </tag>",
RegexOptions.Multiline | RegexOptions.Singleline | RegexOptions.ExplicitCapture | RegexOptions.IgnorePatternWhitespace | RegexOptions.Compiled);
#endregion
/// <summary>
/// maximum nested depth of [] and () supported by the transform; implementation detail
/// </summary>
private const int _nestDepth = 6;
private readonly Dictionary<string, string> _urls = new Dictionary<string, string>();
private readonly Dictionary<string, string> _titles = new Dictionary<string, string>();
private readonly Dictionary<string, string> _htmlBlocks = new Dictionary<string, string>();
private int _listLevel;
/// <summary>
/// full path to the current markdown file if it exists null otherwise
/// </summary>
private string _filePath;
/// <summary>
/// current version of MarkdownSharp;
/// see http://block.google.com/p/markdownsharp/ for the latest block or to contribute
/// </summary>
public string Version
{
get { return "1.009"; }
}
/// <summary>
/// Transforms the provided Markdown-formatted text to HTML;
/// see http://en.wikipedia.org/wiki/Markdown
/// </summary>
/// <param name="text">
/// Markdown text to be transformed.
/// </param>
/// <param name="filePath">
/// The path to the Markdown file, used as a context to resolve relative paths,
/// null if there is no file.
/// </param>
/// <remarks>
/// The order in which other subs are called here is
/// essential. Link and image substitutions need to happen before
/// EscapeSpecialChars(), so that any *'s or _'s in the a
/// and img tags get encoded.
/// </remarks>
public string Transform(string text, string filePath = null)
{
if (text == null) return "";
Setup(filePath);
// Standardize line endings
text = text.Replace("\r\n", "\n"); // DOS to Unix
text = text.Replace("\r", "\n"); // Mac to Unix
// Make sure $text ends with a couple of newlines:
text += "\n\n";
text = Detab(text);
// Strip any lines consisting only of spaces and tabs.
// This makes subsequent regexen easier to write, because we can
// match consecutive blank lines with /\n+/ instead of something
// contorted like /[ \t]*\n+/ .
text = _blankLines.Replace(text, "");
text = HashHTMLBlocks(text);
text = StripLinkDefinitions(text);
text = RunBlockGamut(text);
text = UnescapeSpecialChars(text);
Cleanup();
return text + "\n";
}
/// <summary>
/// Perform transformations that form block-level tags like paragraphs, headers, and list items.
/// </summary>
private string RunBlockGamut(string text)
{
text = DoHeaders(text);
text = DoHorizontalRules(text);
text = DoLists(text);
text = DoCodeBlocks(text);
text = DoBlockQuotes(text);
// We already ran HashHTMLBlocks() before, in Markdown(), but that
// was to escape raw HTML in the original Markdown source. This time,
// we're escaping the markup we've just created, so that we don't wrap
// <p> tags around block-level tags.
text = HashHTMLBlocks(text);
text = FormParagraphs(text);
return text;
}
/// <summary>
/// Perform transformations that occur *within* block-level tags like paragraphs, headers, and list items.
/// </summary>
private string RunSpanGamut(string text)
{
text = DoCodeSpans(text);
text = EscapeSpecialCharsWithinTagAttributes(text);
text = EncodeBackslashEscapes(text);
// Images must come first, because ![foo][f] looks like an anchor.
text = DoImages(text);
text = DoAnchors(text);
// Must come after DoAnchors(), because you can use < and >
// delimiters in inline links like [this](<url>).
text = DoAutoLinks(text);
text = EncodeAmpsAndAngles(text);
text = DoItalicsAndBold(text);
text = DoHardBreaks(text);
return text;
}
private void Setup(string path)
{
// Clear the global hashes. If we don't clear these, you get conflicts
// from other articles when generating a page which contains more than
// one article (e.g. an index page that shows the N most recent
// articles):
_urls.Clear();
_titles.Clear();
_htmlBlocks.Clear();
_listLevel = 0;
_filePath = path;
}
private void Cleanup()
{
Setup(null);
}
private static string _nestedBracketsPattern;
/// <summary>
/// Reusable pattern to match balanced [brackets]. See Friedl's
/// "Mastering Regular Expressions", 2nd Ed., pp. 328-331.
/// </summary>
private static string GetNestedBracketsPattern()
{
// in other words [this] and [this[also]] and [this[also[too]]]
// up to _nestDepth
if (_nestedBracketsPattern == null)
_nestedBracketsPattern =
RepeatString(@"
(?> # Atomic matching
[^\[\]]+ # Anything other than brackets
|
\[
", _nestDepth) + RepeatString(
@" \]
)*"
, _nestDepth);
return _nestedBracketsPattern;
}
private static string _nestedParensPattern;
/// <summary>
/// Reusable pattern to match balanced (parens). See Friedl's
/// "Mastering Regular Expressions", 2nd Ed., pp. 328-331.
/// </summary>
private static string GetNestedParensPattern()
{
// in other words (this) and (this(also)) and (this(also(too)))
// up to _nestDepth
if (_nestedParensPattern == null)
_nestedParensPattern =
RepeatString(@"
(?> # Atomic matching
[^()\s]+ # Anything other than parens or whitespace
|
\(
", _nestDepth) + RepeatString(
@" \)
)*"
, _nestDepth);
return _nestedParensPattern;
}
/// <summary>
/// Strips link definitions from text, stores the URLs and titles in hash references.
/// </summary>
/// <remarks>
/// ^[id]: url "optional title"
/// </remarks>
private string StripLinkDefinitions(string text)
{
return LinkDefRegex.Replace(text, new MatchEvaluator(LinkEvaluator));
}
private string LinkEvaluator(Match match)
{
string linkID = match.Groups[1].Value.ToLowerInvariant();
_urls[linkID] = EncodeAmpsAndAngles(match.Groups[2].Value);
if (match.Groups[3] != null && match.Groups[3].Length > 0)
_titles[linkID] = match.Groups[3].Value.Replace("\"", """);
return "";
}
/// <summary>
/// replaces any block-level HTML blocks with hash entries
/// </summary>
private string HashHTMLBlocks(string text)
{
return BlocksHtmlRegex.Replace(text, new MatchEvaluator(HtmlEvaluator));
}
private string HtmlEvaluator(Match match)
{
string text = match.Groups[1].Value;
string key = text.GetHashCode().ToString();
_htmlBlocks[key] = text;
return string.Concat("\n\n", key, "\n\n");
}
/// <summary>
/// returns an array of HTML tokens comprising the input string. Each token is
/// either a tag (possibly with nested, tags contained therein, such
/// as <a href="<MTFoo>">, or a run of text between tags. Each element of the
/// array is a two-element array; the first is either 'tag' or 'text'; the second is
/// the actual value.
/// </summary>
private List<HTMLToken> TokenizeHTML(string text)
{
int pos = 0;
int tagStart = 0;
var tokens = new List<HTMLToken>();
// this regex is derived from the _tokenize() subroutine in Brad Choate's MTRegex plugin.
// http://www.bradchoate.com/past/mtregex.php
foreach (Match m in HtmlTokensRegex.Matches(text))
{
tagStart = m.Index;
if (pos < tagStart)
tokens.Add(new HTMLToken(HTMLTokenType.Text, text.Substring(pos, tagStart - pos)));
tokens.Add(new HTMLToken(HTMLTokenType.Tag, m.Value));
pos = tagStart + m.Length;
}
if (pos < text.Length)
tokens.Add(new HTMLToken(HTMLTokenType.Text, text.Substring(pos, text.Length - pos)));
return tokens;
}
/// <summary>
/// Within tags -- meaning between < and > -- encode [\ ` * _] so they
/// don't conflict with their use in Markdown for block, italics and strong.
/// We're replacing each such character with its corresponding hash
/// value; this is likely overkill, but it should prevent us from colliding
/// with the escape values by accident.
/// </summary>
private string EscapeSpecialCharsWithinTagAttributes(string text)
{
var tokens = TokenizeHTML(text);
// now, rebuild text from the tokens
var sb = new StringBuilder(text.Length);
foreach (var token in tokens)
{
string value = token.Value;
if (token.Type == HTMLTokenType.Tag)
{
value = value.Replace(@"\", EscapeTable[@"\"]);
value = Regex.Replace(value, "(?<=.)</?block>(?=.)", EscapeTable[@"`"]);
value = EscapeBoldItalic(value);
}
sb.Append(value);
}
return sb.ToString();
}
/// <summary>
/// Turn Markdown link shortcuts into HTML anchor tags
/// </summary>
/// <remarks>
/// [link text](url "title")
/// [link text][id]
/// [id]
/// </remarks>
private string DoAnchors(string text)
{
// First, handle reference-style links: [link text] [id]
text = AnchorRefRegex.Replace(text, new MatchEvaluator(AnchorRefEvaluator));
// Next, inline-style links: [link text](url "optional title") or [link text](url "optional title")
text = AnchorInlineRegex.Replace(text, new MatchEvaluator(AnchorInlineEvaluator));
// Last, handle reference-style shortcuts: [link text]
// These must come last in case you've also got [link test][1]
// or [link test](/foo)
text = AnchorRefShortcutRegex.Replace(text, new MatchEvaluator(AnchorRefShortcutEvaluator));
return text;
}
private string AnchorRefEvaluator(Match match)
{
string wholeMatch = match.Groups[1].Value;
string linkText = match.Groups[2].Value;
string linkID = match.Groups[3].Value.ToLowerInvariant();
string result;
// for shortcut links like [this][].
if (linkID == "")
linkID = linkText.ToLowerInvariant();
if (_urls.ContainsKey(linkID))
{
string url = _urls[linkID];
url = EscapeBoldItalic(url);
url = EncodeProblemUrlChars(url);
result = "<a href=\"" + url + "\"";
if (_titles.ContainsKey(linkID))
{
string title = _titles[linkID];
title = EscapeBoldItalic(title);
result += " title=\"" + title + "\"";
}
result += ">" + linkText + "</a>";
}
else
result = wholeMatch;
return result;
}
private string AnchorRefShortcutEvaluator(Match match)
{
string wholeMatch = match.Groups[1].Value;
string linkText = match.Groups[2].Value;
string linkID = Regex.Replace(linkText.ToLowerInvariant(), @"[ ]*\n[ ]*", " "); // lower case and remove newlines / extra spaces
string result;
if (_urls.ContainsKey(linkID))
{
string url = _urls[linkID];
url = EscapeBoldItalic(url);
url = EncodeProblemUrlChars(url);
result = "<a href=\"" + url + "\"";
if (_titles.ContainsKey(linkID))
{
string title = _titles[linkID];
title = EscapeBoldItalic(title);
result += " title=\"" + title + "\"";
}
result += ">" + linkText + "</a>";
}
else
result = wholeMatch;
return result;
}
/// <summary>
/// escapes Bold [ * ] and Italic [ _ ] characters
/// </summary>