Skip to content

Commit

Permalink
Quick naming refactoring
Browse files Browse the repository at this point in the history
  • Loading branch information
Mpdreamz committed Dec 19, 2024
1 parent c5105be commit d0a5982
Show file tree
Hide file tree
Showing 11 changed files with 137 additions and 104 deletions.
16 changes: 16 additions & 0 deletions src/Elastic.Markdown/Myst/CodeBlocks/CallOut.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
// Licensed to Elasticsearch B.V under one or more agreements.
// Elasticsearch B.V licenses this file to you under the Apache 2.0 License.
// See the LICENSE file in the project root for more information

namespace Elastic.Markdown.Myst.CodeBlocks;

public record CallOut
{
public required int Index { get; init; }
public required string Text { get; init; }
public required bool InlineCodeAnnotation { get; init; }

public required int SliceStart { get; init; }

public required int Line { get; init; }
}
19 changes: 19 additions & 0 deletions src/Elastic.Markdown/Myst/CodeBlocks/CallOutParser.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
// Licensed to Elasticsearch B.V under one or more agreements.
// Elasticsearch B.V licenses this file to you under the Apache 2.0 License.
// See the LICENSE file in the project root for more information

using System.Text.RegularExpressions;

namespace Elastic.Markdown.Myst.CodeBlocks;

public static partial class CallOutParser
{
[GeneratedRegex(@"^.+\S+.*?\s<\d+>$", RegexOptions.IgnoreCase, "en-US")]
public static partial Regex CallOutNumber();

[GeneratedRegex(@"^.+\S+.*?\s(?:\/\/|#)\s[^""]+$", RegexOptions.IgnoreCase, "en-US")]
public static partial Regex MathInlineAnnotation();

[GeneratedRegex(@"\{\{[^\r\n}]+?\}\}", RegexOptions.IgnoreCase, "en-US")]
public static partial Regex MatchSubstitutions();
}
28 changes: 28 additions & 0 deletions src/Elastic.Markdown/Myst/CodeBlocks/EnhancedCodeBlock.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
// Licensed to Elasticsearch B.V under one or more agreements.
// Elasticsearch B.V licenses this file to you under the Apache 2.0 License.
// See the LICENSE file in the project root for more information

using System.IO.Abstractions;
using Elastic.Markdown.Myst.Directives;
using Markdig.Parsers;
using Markdig.Syntax;

namespace Elastic.Markdown.Myst.CodeBlocks;

public class EnhancedCodeBlock(BlockParser parser, ParserContext context)
: FencedCodeBlock(parser), IBlockExtension
{
public BuildContext Build { get; } = context.Build;

public IFileInfo CurrentFile { get; } = context.Path;

public bool SkipValidation { get; } = context.SkipValidation;

public int OpeningLength => Info?.Length ?? 0 + 3;

public List<CallOut>? CallOuts { get; set; }

public bool InlineAnnotations { get; set; }

public string Language { get; set; } = "unknown";
}
Original file line number Diff line number Diff line change
Expand Up @@ -4,55 +4,37 @@

using Elastic.Markdown.Diagnostics;
using Elastic.Markdown.Myst.Directives;
using Markdig;
using Markdig.Parsers;
using Elastic.Markdown.Slices.Directives;
using Markdig.Renderers;
using Markdig.Renderers.Html;
using Markdig.Syntax;
using RazorSlices;

namespace Elastic.Markdown.Myst.CallOutCode;
namespace Elastic.Markdown.Myst.CodeBlocks;

public static class CallOutCodeBuilderExtensions
public class EnhancedCodeBlockHtmlRenderer : HtmlObjectRenderer<EnhancedCodeBlock>
{
public static MarkdownPipelineBuilder UseCallOutAwareCodeBlocks(this MarkdownPipelineBuilder pipeline)
{
pipeline.Extensions.AddIfNotAlready<CallOutCodeMarkdownExtension>();
return pipeline;
}
}

/// <summary>
/// Extension to allow custom containers.
/// </summary>
/// <seealso cref="IMarkdownExtension" />
public class CallOutCodeMarkdownExtension : IMarkdownExtension
{
public void Setup(MarkdownPipelineBuilder pipeline)
private static void RenderRazorSlice<T>(RazorSlice<T> slice, HtmlRenderer renderer, EnhancedCodeBlock block)
{
pipeline.BlockParsers.Replace<FencedCodeBlockParser>(new CallOutAwareFencedCodeBlockParser());
}

public void Setup(MarkdownPipeline pipeline, IMarkdownRenderer renderer)
{
if (!renderer.ObjectRenderers.Contains<CodeBlockRenderer>())
{
// Must be inserted before CodeBlockRenderer
renderer.ObjectRenderers.InsertBefore<CodeBlockRenderer>(new DirectiveHtmlRenderer());
}

renderer.ObjectRenderers.Replace<CodeBlockRenderer>(new CallOutCodeRenderer());
var html = slice.RenderAsync().GetAwaiter().GetResult();
var blocks = html.Split("[CONTENT]", 2, StringSplitOptions.RemoveEmptyEntries);
renderer.Write(blocks[0]);
renderer.WriteLeafRawLines(block, true, false, false);
renderer.Write(blocks[1]);
}
}

public class CallOutCodeRenderer : HtmlObjectRenderer<CodeBlockWithCallOuts>
{
protected override void Write(HtmlRenderer renderer, CodeBlockWithCallOuts block)
protected override void Write(HtmlRenderer renderer, EnhancedCodeBlock block)
{
var callOuts = block.CallOuts ?? [];

renderer.WriteLine("<code><pre>");
renderer.WriteLeafRawLines(block, true, false, false);
renderer.WriteLine("</pre></code>");
var slice = Code.Create(new CodeViewModel
{
CrossReferenceName = string.Empty,// block.CrossReferenceName,
Language = block.Language,
Caption = string.Empty
});

RenderRazorSlice(slice, renderer, block);

if (!block.InlineAnnotations && callOuts.Count > 0)
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,70 +2,34 @@
// Elasticsearch B.V licenses this file to you under the Apache 2.0 License.
// See the LICENSE file in the project root for more information

using System.Collections.Frozen;
using System.IO.Abstractions;
using System.Text.RegularExpressions;
using Elastic.Markdown.Diagnostics;
using Elastic.Markdown.Myst.Directives;
using Markdig.Helpers;
using Markdig.Parsers;
using Markdig.Syntax;

namespace Elastic.Markdown.Myst.CallOutCode;
namespace Elastic.Markdown.Myst.CodeBlocks;

public record CallOut
{
public required int Index { get; init; }
public required string Text { get; init; }
public required bool InlineCodeAnnotation { get; init; }

public required int SliceStart { get; init; }

public required int Line { get; init; }
}

public class CodeBlockWithCallOuts(BlockParser parser, ParserContext context)
: FencedCodeBlock(parser), IBlockExtension
{
public BuildContext Build { get; } = context.Build;

public IFileInfo CurrentFile { get; } = context.Path;

public bool SkipValidation { get; } = context.SkipValidation;

public int OpeningLength => Info?.Length ?? 0 + 3;

public List<CallOut>? CallOuts { get; set; }

public bool InlineAnnotations { get; set; }

public string Language { get; set; } = "unknown";
}

/// <summary>
/// Parser for a <see cref="FencedCodeBlock"/>.
/// </summary>
/// <seealso cref="BlockParser" />
public class CallOutAwareFencedCodeBlockParser : FencedBlockParserBase<CodeBlockWithCallOuts>
public class EnhancedCodeBlockParser : FencedBlockParserBase<EnhancedCodeBlock>
{
private const string DefaultInfoPrefix = "language-";

/// <summary>
/// Initializes a new instance of the <see cref="FencedCodeBlockParser"/> class.
/// </summary>
public CallOutAwareFencedCodeBlockParser()
public EnhancedCodeBlockParser()
{
OpeningCharacters = ['`'];
InfoPrefix = DefaultInfoPrefix;
InfoParser = RoundtripInfoParser;
}

protected override CodeBlockWithCallOuts CreateFencedBlock(BlockProcessor processor)
protected override EnhancedCodeBlock CreateFencedBlock(BlockProcessor processor)
{
if (processor.Context is not ParserContext context)
throw new Exception("Expected parser context to be of type ParserContext");

var codeBlock = new CodeBlockWithCallOuts(this, context) { IndentCount = processor.Indent };
var codeBlock = new EnhancedCodeBlock(this, context) { IndentCount = processor.Indent };

if (processor.TrackTrivia)
{
Expand All @@ -85,7 +49,7 @@ public override BlockState TryContinue(BlockProcessor processor, Block block)
var result = base.TryContinue(processor, block);
if (result == BlockState.Continue && !processor.TrackTrivia)
{
var fence = (CodeBlockWithCallOuts)block;
var fence = (EnhancedCodeBlock)block;
// Remove any indent spaces
var c = processor.CurrentChar;
var indentCount = fence.IndentCount;
Expand All @@ -101,7 +65,7 @@ public override BlockState TryContinue(BlockProcessor processor, Block block)

public override bool Close(BlockProcessor processor, Block block)
{
if (block is not CodeBlockWithCallOuts codeBlock)
if (block is not EnhancedCodeBlock codeBlock)
return base.Close(processor, block);

if (processor.Context is not ParserContext context)
Expand All @@ -111,7 +75,7 @@ public override bool Close(BlockProcessor processor, Block block)
(codeBlock.Info?.IndexOf("{") ?? -1) != -1
? codeBlock.Arguments
: codeBlock.Info
) ?? "unknown";
) ?? "unknown";

var lines = codeBlock.Lines;
var callOutIndex = 0;
Expand Down Expand Up @@ -153,7 +117,10 @@ public override bool Close(BlockProcessor processor, Block block)
foreach (var callout in codeBlock.CallOuts)
{
var line = lines.Lines[callout.Line - 1];
line.Slice.End = line.Slice.Start + callout.SliceStart;

var newSpan = line.Slice.AsSpan()[..callout.SliceStart];
var s = new StringSlice(newSpan.ToString());
lines.Lines[callout.Line -1 ] = new StringLine(ref s);

}
}
Expand Down Expand Up @@ -234,15 +201,3 @@ private static bool ReplaceSubstitutions(ParserContext context, ReadOnlySpan<cha
return null;
}
}

public static partial class CallOutParser
{
[GeneratedRegex(@"^.+\S+.*?\s<\d+>$", RegexOptions.IgnoreCase, "en-US")]
public static partial Regex CallOutNumber();

[GeneratedRegex(@"^.+\S+.*?\s(?:\/\/|#)\s[^""]+$", RegexOptions.IgnoreCase, "en-US")]
public static partial Regex MathInlineAnnotation();

[GeneratedRegex(@"\{\{[^\r\n}]+?\}\}", RegexOptions.IgnoreCase, "en-US")]
public static partial Regex MatchSubstitutions();
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
// Licensed to Elasticsearch B.V under one or more agreements.
// Elasticsearch B.V licenses this file to you under the Apache 2.0 License.
// See the LICENSE file in the project root for more information

using Elastic.Markdown.Myst.Directives;
using Markdig;
using Markdig.Parsers;
using Markdig.Renderers;
using Markdig.Renderers.Html;

namespace Elastic.Markdown.Myst.CodeBlocks;

public static class EnhancedCodeBuilderExtensions
{
public static MarkdownPipelineBuilder UseEnhancedCodeBlocks(this MarkdownPipelineBuilder pipeline)
{
pipeline.Extensions.AddIfNotAlready<EnhancedCodeBlockExtension>();
return pipeline;
}
}

/// <summary>
/// Extension to allow custom containers.
/// </summary>
/// <seealso cref="IMarkdownExtension" />
public class EnhancedCodeBlockExtension : IMarkdownExtension
{
public void Setup(MarkdownPipelineBuilder pipeline) =>
pipeline.BlockParsers.Replace<FencedCodeBlockParser>(new EnhancedCodeBlockParser());

public void Setup(MarkdownPipeline pipeline, IMarkdownRenderer renderer) =>
renderer.ObjectRenderers.Replace<CodeBlockRenderer>(new EnhancedCodeBlockHtmlRenderer());
}
4 changes: 2 additions & 2 deletions src/Elastic.Markdown/Myst/Directives/DirectiveHtmlRenderer.cs
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
// See the license.txt file in the project root for more information.

using Elastic.Markdown.Diagnostics;
using Elastic.Markdown.Myst.CallOutCode;
using Elastic.Markdown.Myst.CodeBlocks;
using Elastic.Markdown.Myst.FrontMatter;
using Elastic.Markdown.Myst.Settings;
using Elastic.Markdown.Myst.Substitution;
Expand Down Expand Up @@ -162,7 +162,7 @@ private void WriteDropdown(HtmlRenderer renderer, DropdownBlock block)
RenderRazorSlice(slice, renderer, block);
}

private void WriteCode(HtmlRenderer renderer, CodeBlockWithCallOuts block)
private void WriteCode(HtmlRenderer renderer, EnhancedCodeBlock block)
{
var slice = Code.Create(new CodeViewModel
{
Expand Down
4 changes: 2 additions & 2 deletions src/Elastic.Markdown/Myst/MarkdownParser.cs
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
using System.IO.Abstractions;
using Cysharp.IO;
using Elastic.Markdown.IO;
using Elastic.Markdown.Myst.CallOutCode;
using Elastic.Markdown.Myst.CodeBlocks;
using Elastic.Markdown.Myst.Comments;
using Elastic.Markdown.Myst.Directives;
using Elastic.Markdown.Myst.FrontMatter;
Expand Down Expand Up @@ -49,7 +49,7 @@ public class MarkdownParser(
.UseGridTables()
.UsePipeTables()
.UseDirectives()
.UseCallOutAwareCodeBlocks()
.UseEnhancedCodeBlocks()
.DisableHtml()
.Build();

Expand Down
4 changes: 2 additions & 2 deletions tests/Elastic.Markdown.Tests/CodeBlocks/CallOutTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
// Elasticsearch B.V licenses this file to you under the Apache 2.0 License.
// See the LICENSE file in the project root for more information

using Elastic.Markdown.Myst.CallOutCode;
using Elastic.Markdown.Myst.CodeBlocks;
using Elastic.Markdown.Tests.Inline;
using FluentAssertions;
using JetBrains.Annotations;
Expand All @@ -16,7 +16,7 @@ public abstract class CodeBlockCallOutTests(
[LanguageInjection("csharp")] string code,
[LanguageInjection("markdown")] string? markdown = null
)
: BlockTest<CodeBlockWithCallOuts>(output,
: BlockTest<EnhancedCodeBlock>(output,
$$"""
```{{language}}
{{code}}
Expand Down
4 changes: 2 additions & 2 deletions tests/Elastic.Markdown.Tests/CodeBlocks/CodeTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2,15 +2,15 @@
// Elasticsearch B.V licenses this file to you under the Apache 2.0 License.
// See the LICENSE file in the project root for more information

using Elastic.Markdown.Myst.CallOutCode;
using Elastic.Markdown.Myst.CodeBlocks;
using Elastic.Markdown.Tests.Inline;
using FluentAssertions;
using Xunit.Abstractions;

namespace Elastic.Markdown.Tests.CodeBlocks;

public abstract class CodeBlockTests(ITestOutputHelper output, string directive, string? language = null)
: BlockTest<CodeBlockWithCallOuts>(output,
: BlockTest<EnhancedCodeBlock>(output,
$$"""
```{{directive}} {{language}}
var x = 1;
Expand Down
4 changes: 2 additions & 2 deletions tests/Elastic.Markdown.Tests/Inline/SubstitutionTest.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
// Elasticsearch B.V licenses this file to you under the Apache 2.0 License.
// See the LICENSE file in the project root for more information

using Elastic.Markdown.Myst.CallOutCode;
using Elastic.Markdown.Myst.CodeBlocks;
using Elastic.Markdown.Myst.Substitution;
using FluentAssertions;
using Xunit.Abstractions;
Expand Down Expand Up @@ -65,7 +65,7 @@ public void GeneratesAttributesInHtml() =>
);
}

public class SubstitutionInCodeBlockTest(ITestOutputHelper output) : BlockTest<CodeBlockWithCallOuts>(output,
public class SubstitutionInCodeBlockTest(ITestOutputHelper output) : BlockTest<EnhancedCodeBlock>(output,
"""
---
sub:
Expand Down

0 comments on commit d0a5982

Please sign in to comment.