This repository has been archived on 2023-02-02. You can view files and clone it, but cannot push or open issues or pull requests.
mfgames-markdown-cil/src/MfGames.Markdown.Gemtext/MarkdownGemtext.cs

84 lines
2.7 KiB
C#

using System;
using System.IO;
using Markdig;
using Markdig.Parsers;
using Markdig.Syntax;
using MfGames.Markdown.Gemtext.Renderers;
namespace MfGames.Markdown.Gemtext
{
/// <summary>
/// The static class that corresponds to Markdig.Markdown. This is written
/// with the same pattern, but since `Markdown` is a static, we can't tack
/// onto that.
/// </summary>
public static class MarkdownGemtext
{
private static readonly MarkdownPipeline DefaultPipeline;
static MarkdownGemtext()
{
DefaultPipeline = new MarkdownPipelineBuilder()
.Build();
}
/// <summary>
/// Converts the given Markdown
/// </summary>
/// <param name="markdown">A Markdown text.</param>
/// <param name="pipeline">The pipeline used for the conversion.</param>
/// <param name="context">A parser context used for the parsing.</param>
/// <returns>The result of the conversion</returns>
public static string ToGemtext(
string markdown,
MarkdownPipeline? pipeline = null,
MarkdownParserContext? context = null)
{
if (markdown == null)
{
throw new ArgumentNullException(nameof(markdown));
}
pipeline ??= DefaultPipeline;
MarkdownDocument document = MarkdownParser
.Parse(markdown, pipeline, context);
return ToGemtext(document, pipeline);
}
/// <summary>
/// Converts a Markdown document to HTML.
/// </summary>
/// <param name="document">A Markdown document.</param>
/// <param name="pipeline">The pipeline used for the conversion.</param>
/// <returns>The result of the conversion</returns>
/// <exception cref="ArgumentNullException">if markdown document variable is null</exception>
public static string ToGemtext(
this MarkdownDocument document,
MarkdownPipeline? pipeline = null)
{
// Make sure we have sane parameters.
if (document == null)
{
throw new ArgumentNullException(nameof(document));
}
pipeline ??= DefaultPipeline;
// Set up the writer to contain the markdown and the Gemtext
// renderer.
var writer = new StringWriter();
GemtextRenderer renderer = new(writer);
pipeline.Setup(renderer);
// Render the Markdown into Gemtext and re turn the results.
renderer.Render(document);
renderer.Writer.Flush();
return renderer.Writer.ToString() ?? string.Empty;
}
}
}