Skip to content

Commit

Permalink
Allow YAML front matter in the middle of the document
Browse files Browse the repository at this point in the history
  • Loading branch information
yufeih committed Feb 23, 2023
1 parent 8f8a145 commit 9df67b7
Show file tree
Hide file tree
Showing 3 changed files with 25 additions and 2 deletions.
13 changes: 13 additions & 0 deletions src/Markdig.Tests/TestYamlFrontMatterExtension.cs
Expand Up @@ -18,6 +18,19 @@ public void ProperYamlFrontMatterRenderersAdded(IMarkdownObjectRenderer[] object
Assert.That(markdownRenderer.ObjectRenderers.Contains<YamlFrontMatterRoundtripRenderer>(), Is.EqualTo(hasYamlFrontMatterRoundtripRenderer));
}

[Test]
public void AllowYamlFrontMatterInMiddleOfDocument()
{
var pipeline = new MarkdownPipelineBuilder()
.Use(new YamlFrontMatterExtension { AllowInMiddleOfDocument = true })
.Build();

TestParser.TestSpec(
"This is a text1\n---\nthis: is a frontmatter\n---\nThis is a text2",
"<p>This is a text1</p>\n<p>This is a text2</p>",
pipeline);
}

private static IEnumerable<TestCaseData> TestCases()
{
yield return new TestCaseData(new IMarkdownObjectRenderer[]
Expand Down
7 changes: 6 additions & 1 deletion src/Markdig/Extensions/Yaml/YamlFrontMatterExtension.cs
Expand Up @@ -12,12 +12,17 @@ namespace Markdig.Extensions.Yaml;
/// </summary>
public class YamlFrontMatterExtension : IMarkdownExtension
{
/// <summary>
/// Allows the <see cref="YamlFrontMatterBlock"/> to appear in the middle of the markdown file.
/// </summary>
public bool AllowInMiddleOfDocument { get; set; }

public void Setup(MarkdownPipelineBuilder pipeline)
{
if (!pipeline.BlockParsers.Contains<YamlFrontMatterParser>())
{
// Insert the YAML parser before the thematic break parser, as it is also triggered on a --- dash
pipeline.BlockParsers.InsertBefore<ThematicBreakParser>(new YamlFrontMatterParser());
pipeline.BlockParsers.InsertBefore<ThematicBreakParser>(new YamlFrontMatterParser { AllowInMiddleOfDocument = AllowInMiddleOfDocument });
}
}

Expand Down
7 changes: 6 additions & 1 deletion src/Markdig/Extensions/Yaml/YamlFrontMatterParser.cs
Expand Up @@ -16,6 +16,11 @@ public class YamlFrontMatterParser : BlockParser
{
// We reuse a FencedCodeBlock parser to grab a frontmatter, only active if it happens on the first line of the document.

/// <summary>
/// Allows the <see cref="YamlFrontMatterBlock"/> to appear in the middle of the markdown file.
/// </summary>
public bool AllowInMiddleOfDocument { get; set; }

/// <summary>
/// Initializes a new instance of the <see cref="YamlFrontMatterParser"/> class.
/// </summary>
Expand Down Expand Up @@ -48,7 +53,7 @@ public override BlockState TryOpen(BlockProcessor processor)
}

// Only accept a frontmatter at the beginning of the file
if (processor.Start != 0)
if (!AllowInMiddleOfDocument && processor.Start != 0)
{
return BlockState.None;
}
Expand Down

0 comments on commit 9df67b7

Please sign in to comment.