using System;
using System.IO;
using Markdig;
using Markdig.Parsers;
using Markdig.Syntax;
using MfGames.Markdown.Gemtext.Renderers;
namespace MfGames.Markdown.Gemtext
{
///
/// 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.
///
public static class MarkdownGemtext
{
private static readonly MarkdownPipeline DefaultPipeline;
static MarkdownGemtext()
{
DefaultPipeline = new MarkdownPipelineBuilder()
.Build();
}
///
/// Converts the given Markdown
///
/// A Markdown text.
/// The pipeline used for the conversion.
/// A parser context used for the parsing.
/// The result of the conversion
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);
}
///
/// Converts a Markdown document to HTML.
///
/// A Markdown document.
/// The pipeline used for the conversion.
/// The result of the conversion
/// if markdown document variable is null
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;
}
}
}