-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMarkdownHelpRenderer.cs
More file actions
94 lines (83 loc) · 2.79 KB
/
Copy pathMarkdownHelpRenderer.cs
File metadata and controls
94 lines (83 loc) · 2.79 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
using Markdig;
using Markdig.Extensions.Tables;
using Markdig.Syntax;
namespace HelpLine.Docs;
/// <summary>
/// Renders Markdown content in a console-friendly form.
/// </summary>
public sealed class MarkdownHelpRenderer
{
internal static readonly MarkdownPipeline Pipeline = new MarkdownPipelineBuilder()
.UseAutoLinks()
.UsePipeTables()
.Build();
/// <summary>
/// Renders Markdown content to the provided text writer.
/// </summary>
public void Render(string markdown, TextWriter writer)
{
ArgumentNullException.ThrowIfNull(writer);
if (string.IsNullOrWhiteSpace(markdown))
{
writer.WriteLine("No help content is available.");
return;
}
Render(Markdown.Parse(markdown, Pipeline), writer);
}
/// <summary>
/// Renders an already-parsed Markdown document to the provided text writer.
/// </summary>
public void Render(MarkdownDocument document, TextWriter writer)
{
ArgumentNullException.ThrowIfNull(document);
ArgumentNullException.ThrowIfNull(writer);
IMarkdownVisitor visitor = ShouldUseSpectre(writer)
? new SpectreMarkdownVisitor()
: new PlainTextMarkdownVisitor(writer);
Walk(document, visitor);
}
private static bool ShouldUseSpectre(TextWriter writer)
{
return ReferenceEquals(writer, Console.Out) && !Console.IsOutputRedirected;
}
private static void Walk(MarkdownDocument document, IMarkdownVisitor visitor)
{
foreach (var block in document)
{
VisitBlock(block, visitor);
}
}
internal static void VisitBlock(Block block, IMarkdownVisitor visitor)
{
switch (block)
{
case HeadingBlock heading:
visitor.VisitHeading(heading);
break;
case ParagraphBlock paragraph:
visitor.VisitParagraph(paragraph);
break;
case FencedCodeBlock fenced:
visitor.VisitFencedCode(fenced);
break;
case CodeBlock code:
visitor.VisitCode(code);
break;
case ListBlock list:
foreach (var item in list.OfType<ListItemBlock>())
{
visitor.VisitListItem(item, list.IsOrdered);
}
break;
case QuoteBlock quote:
visitor.VisitQuote(quote);
break;
case ThematicBreakBlock rule:
visitor.VisitThematicBreak(rule);
break;
case Table table:
visitor.VisitTable(table);
break;
}
}
}