-
Notifications
You must be signed in to change notification settings - Fork 144
Expand file tree
/
Copy pathHtmlFormatter.cs
More file actions
690 lines (574 loc) · 24.8 KB
/
HtmlFormatter.cs
File metadata and controls
690 lines (574 loc) · 24.8 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
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using CommonMark.Syntax;
namespace CommonMark.Formatters
{
/// <summary>
/// An extendable implementation for writing CommonMark data as HTML.
/// </summary>
public class HtmlFormatter
{
private readonly HtmlTextWriter _target;
private readonly CommonMarkSettings _settings;
private readonly Stack<bool> _renderTightParagraphs = new Stack<bool>(new[] { false });
private readonly Stack<bool> _renderPlainTextInlines = new Stack<bool>(new[] { false });
private readonly Stack<char> _endPlaceholders = new Stack<char>();
/// <summary>
/// Gets a stack of values indicating whether the paragraph tags should be ommitted.
/// Every element that impacts this setting has to push a value when opening and pop it when closing.
/// The most recent value is used to determine the current state.
/// </summary>
protected Stack<bool> RenderTightParagraphs { get { return _renderTightParagraphs; } }
/// <summary>
/// Gets a stack of values indicating whether the inline elements should be rendered as plain text
/// (without formatting). This usually is done within image description attributes that do not support
/// HTML tags.
/// Every element that impacts this setting has to push a value when opening and pop it when closing.
/// The most recent value is used to determine the current state.
/// </summary>
protected Stack<bool> RenderPlainTextInlines { get { return _renderPlainTextInlines; } }
/// <summary>Initializes a new instance of the <see cref="HtmlFormatter" /> class.</summary>
/// <param name="target">The target text writer.</param>
/// <param name="settings">The settings used when formatting the data.</param>
/// <exception cref="ArgumentNullException">when <paramref name="target"/> is <see langword="null"/></exception>
public HtmlFormatter(TextWriter target, CommonMarkSettings settings)
{
if (target == null)
throw new ArgumentNullException(nameof(target));
if (settings == null)
settings = CommonMarkSettings.Default;
_target = new HtmlTextWriter(target);
_settings = settings;
}
/// <summary>
/// Gets the settings used for formatting data.
/// </summary>
protected CommonMarkSettings Settings { get { return _settings; } }
/// <summary>
/// Writes the given CommonMark document to the output stream as HTML.
/// </summary>
public void WriteDocument(Block document)
{
if (document == null)
throw new ArgumentNullException(nameof(document));
bool ignoreChildNodes;
Block ignoreUntilBlockCloses = null;
Inline ignoreUntilInlineCloses = null;
foreach (var node in document.AsEnumerable())
{
if (node.Block != null)
{
if (ignoreUntilBlockCloses != null)
{
if (ignoreUntilBlockCloses != node.Block)
continue;
ignoreUntilBlockCloses = null;
}
WriteBlock(node.Block, node.IsOpening, node.IsClosing, out ignoreChildNodes);
if (ignoreChildNodes && !node.IsClosing)
ignoreUntilBlockCloses = node.Block;
}
else if (ignoreUntilBlockCloses == null && node.Inline != null)
{
if (ignoreUntilInlineCloses != null)
{
if (ignoreUntilInlineCloses != node.Inline)
continue;
ignoreUntilInlineCloses = null;
}
WriteInline(node.Inline, node.IsOpening, node.IsClosing, out ignoreChildNodes);
if (ignoreChildNodes && !node.IsClosing)
ignoreUntilInlineCloses = node.Inline;
}
}
}
/// <summary>
/// Writes the specified block element to the output stream. Does not write the child nodes, instead
/// the <paramref name="ignoreChildNodes"/> is used to notify the caller whether it should recurse
/// into the child nodes.
/// </summary>
/// <param name="block">The block element to be written to the output stream.</param>
/// <param name="isOpening">Specifies whether the block element is being opened (or started).</param>
/// <param name="isClosing">Specifies whether the block element is being closed. If the block does not
/// have child nodes, then both <paramref name="isClosing"/> and <paramref name="isOpening"/> can be
/// <see langword="true"/> at the same time.</param>
/// <param name="ignoreChildNodes">Instructs the caller whether to skip processing of child nodes or not.</param>
protected virtual void WriteBlock(Block block, bool isOpening, bool isClosing, out bool ignoreChildNodes)
{
ignoreChildNodes = false;
int x;
switch (block.Tag)
{
case BlockTag.Document:
break;
case BlockTag.Paragraph:
if (RenderTightParagraphs.Peek())
break;
if (isOpening)
{
EnsureNewLine();
Write("<p");
if (Settings.TrackSourcePosition) WritePositionAttribute(block);
Write('>');
}
if (isClosing)
WriteLine("</p>");
break;
case BlockTag.BlockQuote:
if (isOpening)
{
EnsureNewLine();
Write("<blockquote");
if (Settings.TrackSourcePosition) WritePositionAttribute(block);
WriteLine(">");
RenderTightParagraphs.Push(false);
}
if (isClosing)
{
RenderTightParagraphs.Pop();
WriteLine("</blockquote>");
}
break;
case BlockTag.ListItem:
if (isOpening)
{
EnsureNewLine();
Write("<li");
if (Settings.TrackSourcePosition) WritePositionAttribute(block);
Write('>');
}
if (isClosing)
WriteLine("</li>");
break;
case BlockTag.List:
var data = block.ListData;
if (isOpening)
{
EnsureNewLine();
Write(data.ListType == ListType.Bullet ? "<ul" : "<ol");
if (data.Start != 1)
{
Write(" start=\"");
Write(data.Start.ToString(CultureInfo.InvariantCulture));
Write('\"');
}
if (Settings.TrackSourcePosition) WritePositionAttribute(block);
WriteLine(">");
RenderTightParagraphs.Push(data.IsTight);
}
if (isClosing)
{
WriteLine(data.ListType == ListType.Bullet ? "</ul>" : "</ol>");
RenderTightParagraphs.Pop();
}
break;
case BlockTag.AtxHeading:
case BlockTag.SetextHeading:
x = block.Heading.Level;
if (isOpening)
{
EnsureNewLine();
Write("<h" + x.ToString(CultureInfo.InvariantCulture));
if (Settings.TrackSourcePosition)
WritePositionAttribute(block);
Write('>');
}
if (isClosing)
WriteLine("</h" + x.ToString(CultureInfo.InvariantCulture) + ">");
break;
case BlockTag.IndentedCode:
case BlockTag.FencedCode:
case BlockTag.YamlBlock:
ignoreChildNodes = true;
EnsureNewLine();
Write("<pre><code");
if (Settings.TrackSourcePosition) WritePositionAttribute(block);
var info = block.FencedCodeData == null ? null : block.FencedCodeData.Info;
if (info != null && info.Length > 0)
{
x = info.IndexOf(' ');
if (x == -1)
x = info.Length;
Write(" class=\"language-");
WriteEncodedHtml(new StringPart(info, 0, x));
Write('\"');
}
else if (block.Tag == BlockTag.YamlBlock)
{
Write(" class=\"language-yaml\"");
}
Write('>');
WriteEncodedHtml(block.StringContent);
WriteLine("</code></pre>");
break;
case BlockTag.HtmlBlock:
ignoreChildNodes = true;
// cannot output source position for HTML blocks
Write(block.StringContent);
break;
case BlockTag.ThematicBreak:
ignoreChildNodes = true;
if (Settings.TrackSourcePosition)
{
Write("<hr");
WritePositionAttribute(block);
WriteLine();
}
else
{
WriteLine("<hr />");
}
break;
case BlockTag.ReferenceDefinition:
break;
default:
throw new CommonMarkException("Block type " + block.Tag + " is not supported.", block);
}
if (ignoreChildNodes && !isClosing)
throw new InvalidOperationException("Block of type " + block.Tag + " cannot contain child nodes.");
}
/// <summary>
/// Writes the specified inline element to the output stream. Does not write the child nodes, instead
/// the <paramref name="ignoreChildNodes"/> is used to notify the caller whether it should recurse
/// into the child nodes.
/// </summary>
/// <param name="inline">The inline element to be written to the output stream.</param>
/// <param name="isOpening">Specifies whether the inline element is being opened (or started).</param>
/// <param name="isClosing">Specifies whether the inline element is being closed. If the inline does not
/// have child nodes, then both <paramref name="isClosing"/> and <paramref name="isOpening"/> can be
/// <see langword="true"/> at the same time.</param>
/// <param name="ignoreChildNodes">Instructs the caller whether to skip processing of child nodes or not.</param>
protected virtual void WriteInline(Inline inline, bool isOpening, bool isClosing, out bool ignoreChildNodes)
{
if (RenderPlainTextInlines.Peek())
{
switch (inline.Tag)
{
case InlineTag.String:
case InlineTag.Code:
case InlineTag.RawHtml:
WriteEncodedHtml(inline.LiteralContentValue);
break;
case InlineTag.LineBreak:
case InlineTag.SoftBreak:
WriteLine();
break;
case InlineTag.Image:
if (isOpening)
RenderPlainTextInlines.Push(true);
if (isClosing)
{
RenderPlainTextInlines.Pop();
if (!RenderPlainTextInlines.Peek())
goto useFullRendering;
}
break;
case InlineTag.Link:
case InlineTag.Strong:
case InlineTag.Emphasis:
case InlineTag.Strikethrough:
case InlineTag.Placeholder:
break;
default:
throw new CommonMarkException("Inline type " + inline.Tag + " is not supported.", inline);
}
ignoreChildNodes = false;
return;
}
useFullRendering:
switch (inline.Tag)
{
case InlineTag.String:
ignoreChildNodes = true;
if (Settings.TrackSourcePosition)
{
Write("<span");
WritePositionAttribute(inline);
Write('>');
WriteEncodedHtml(inline.LiteralContentValue);
Write("</span>");
}
else
{
WriteEncodedHtml(inline.LiteralContentValue);
}
break;
case InlineTag.LineBreak:
ignoreChildNodes = true;
WriteLine("<br />");
break;
case InlineTag.SoftBreak:
ignoreChildNodes = true;
if (Settings.RenderSoftLineBreaksAsLineBreaks)
WriteLine("<br />");
else
WriteLine();
break;
case InlineTag.Code:
ignoreChildNodes = true;
Write("<code");
if (Settings.TrackSourcePosition) WritePositionAttribute(inline);
Write('>');
WriteEncodedHtml(inline.LiteralContentValue);
Write("</code>");
break;
case InlineTag.RawHtml:
ignoreChildNodes = true;
// cannot output source position for HTML blocks
Write(inline.LiteralContentValue);
break;
case InlineTag.Link:
ignoreChildNodes = false;
if (isOpening)
{
Write("<a href=\"");
var uriResolver = Settings.UriResolver;
if (uriResolver != null)
WriteEncodedUrl(uriResolver(inline.TargetUrl));
else
WriteEncodedUrl(inline.TargetUrl);
Write('\"');
if (inline.LiteralContentValue.Length > 0)
{
Write(" title=\"");
WriteEncodedHtml(inline.LiteralContentValue);
Write('\"');
}
if (Settings.TrackSourcePosition) WritePositionAttribute(inline);
Write('>');
}
if (isClosing)
{
Write("</a>");
}
break;
case InlineTag.Image:
ignoreChildNodes = false;
if (isOpening)
{
Write("<img src=\"");
var uriResolver = Settings.UriResolver;
if (uriResolver != null)
WriteEncodedUrl(uriResolver(inline.TargetUrl));
else
WriteEncodedUrl(inline.TargetUrl);
Write("\" alt=\"");
if (!isClosing)
RenderPlainTextInlines.Push(true);
}
if (isClosing)
{
// this.RenderPlainTextInlines.Pop() is done by the plain text renderer above.
Write('\"');
if (inline.LiteralContentValue.Length > 0)
{
Write(" title=\"");
WriteEncodedHtml(inline.LiteralContentValue);
Write('\"');
}
if (Settings.TrackSourcePosition) WritePositionAttribute(inline);
Write(" />");
}
break;
case InlineTag.Strong:
ignoreChildNodes = false;
if (isOpening)
{
Write("<strong");
if (Settings.TrackSourcePosition) WritePositionAttribute(inline);
Write('>');
}
if (isClosing)
{
Write("</strong>");
}
break;
case InlineTag.Emphasis:
ignoreChildNodes = false;
if (isOpening)
{
Write("<em");
if (Settings.TrackSourcePosition) WritePositionAttribute(inline);
Write('>');
}
if (isClosing)
{
Write("</em>");
}
break;
case InlineTag.Strikethrough:
ignoreChildNodes = false;
if (isOpening)
{
Write("<del");
if (Settings.TrackSourcePosition) WritePositionAttribute(inline);
Write('>');
}
if (isClosing)
{
Write("</del>");
}
break;
case InlineTag.Placeholder:
ignoreChildNodes = false;
if (isOpening)
{
string placeholderSubstitute = null;
try
{
placeholderSubstitute = (_placeholderResolver != null) ? _placeholderResolver(inline.TargetUrl) : null;
}
catch (Exception ex)
{
throw new CommonMarkException("An error occurred while resolving a placeholder.", ex);
}
if (placeholderSubstitute != null)
{
ignoreChildNodes = true;
if (Settings.TrackSourcePosition) WritePositionAttribute(inline);
Write(placeholderSubstitute);
_endPlaceholders.Push('\0');
}
else
{
ignoreChildNodes = false;
Write("[");
_endPlaceholders.Push(']');
}
}
if (isClosing)
{
var closingChar = _endPlaceholders.Pop();
if (closingChar != '\0')
{
Write(closingChar);
}
}
break;
default:
throw new CommonMarkException("Inline type " + inline.Tag + " is not supported.", inline);
}
}
/// <summary>
/// Writes the specified text to the target writer.
/// </summary>
protected void Write(string text)
{
if (text == null)
return;
_target.Write(new StringPart(text, 0, text.Length));
}
private void Write(StringPart text)
{
_target.Write(text);
}
/// <summary>
/// Writes the specified text to the target writer.
/// </summary>
protected void Write(StringContent text)
{
if (text == null)
return;
text.WriteTo(_target);
}
/// <summary>
/// Writes the specified character to the target writer.
/// </summary>
protected void Write(char c)
{
_target.Write(c);
}
/// <summary>
/// Ensures that the output ends with a newline. This means that newline character will be written
/// only if the writer does not currently end with a newline.
/// </summary>
protected void EnsureNewLine()
{
_target.EnsureLine();
}
/// <summary>
/// Writes a newline to the target writer.
/// </summary>
protected void WriteLine()
{
_target.WriteLine();
}
/// <summary>
/// Writes the specified text and a newline to the target writer.
/// </summary>
protected void WriteLine(string text)
{
_target.Write(new StringPart(text, 0, text.Length));
_target.WriteLine();
}
/// <summary>
/// Encodes the given text with HTML encoding (ampersand-encoding) and writes the result to the target writer.
/// </summary>
protected void WriteEncodedHtml(StringContent text)
{
if (text == null)
return;
HtmlFormatterSlim.EscapeHtml(text, _target);
}
/// <summary>
/// Encodes the given text with HTML encoding (ampersand-encoding) and writes the result to the target writer.
/// </summary>
protected void WriteEncodedHtml(string text)
{
if (text == null)
return;
HtmlFormatterSlim.EscapeHtml(new StringPart(text, 0, text.Length), _target);
}
private void WriteEncodedHtml(StringPart text)
{
HtmlFormatterSlim.EscapeHtml(text, _target);
}
/// <summary>
/// Encodes the given text with URL encoding (percent-encoding) and writes the result to the target writer.
/// Note that the result is intended to be written to HTML attribute so this also encodes <c>&</c> character
/// as <c>&amp;</c>.
/// </summary>
protected void WriteEncodedUrl(string url)
{
HtmlFormatterSlim.EscapeUrl(url, _target);
}
/// <summary>
/// Writes a <c>data-sourcepos="start-end"</c> attribute to the target writer.
/// This method should only be called if <see cref="CommonMarkSettings.TrackSourcePosition"/> is set to <see langword="true"/>.
/// Note that the attribute is preceded (but not succeeded) by a single space.
/// </summary>
protected void WritePositionAttribute(Block block)
{
HtmlFormatterSlim.PrintPosition(_target, block);
}
/// <summary>
/// Writes a <c>data-sourcepos="start-end"</c> attribute to the target writer.
/// This method should only be called if <see cref="CommonMarkSettings.TrackSourcePosition"/> is set to <see langword="true"/>.
/// Note that the attribute is preceded (but not succeeded) by a single space.
/// </summary>
protected void WritePositionAttribute(Inline inline)
{
HtmlFormatterSlim.PrintPosition(_target, inline);
}
private Func<string, string> _placeholderResolver;
/// <summary>
/// Provides an optional function that can provide substitute strings for placeholders.
/// The argument contains the placeholder text. If the function returns <see langword="null"/>,
/// the placeholder was not resolved and will be rendered as a literal, otherwise, the
/// returned string will be output instead of the placeholder.
/// </summary>
public Func<string, string> PlaceholderResolver
{
get
{
return _placeholderResolver;
}
set
{
_placeholderResolver = value;
}
}
}
}