|
| 1 | +// Licensed to Elasticsearch B.V under one or more agreements. |
| 2 | +// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. |
| 3 | +// See the LICENSE file in the project root for more information |
| 4 | + |
| 5 | +using System.Text.RegularExpressions; |
| 6 | +using Markdig; |
| 7 | +using Markdig.Helpers; |
| 8 | +using Markdig.Parsers; |
| 9 | +using Markdig.Parsers.Inlines; |
| 10 | +using Markdig.Renderers; |
| 11 | +using Markdig.Syntax; |
| 12 | + |
| 13 | +namespace Elastic.Markdown.Myst.InlineParsers; |
| 14 | + |
| 15 | +public static class HeadingBlockWithSlugBuilderExtensions |
| 16 | +{ |
| 17 | + public static MarkdownPipelineBuilder UseHeadingsWithSlugs(this MarkdownPipelineBuilder pipeline) |
| 18 | + { |
| 19 | + pipeline.Extensions.AddIfNotAlready<HeadingBlockWithSlugBuilderExtension>(); |
| 20 | + return pipeline; |
| 21 | + } |
| 22 | +} |
| 23 | + |
| 24 | +public class HeadingBlockWithSlugBuilderExtension : IMarkdownExtension |
| 25 | +{ |
| 26 | + public void Setup(MarkdownPipelineBuilder pipeline) => |
| 27 | + pipeline.BlockParsers.Replace<HeadingBlockParser>(new HeadingBlockWithSlugParser()); |
| 28 | + |
| 29 | + public void Setup(MarkdownPipeline pipeline, IMarkdownRenderer renderer) { } |
| 30 | +} |
| 31 | + |
| 32 | +public class HeadingBlockWithSlugParser : HeadingBlockParser |
| 33 | +{ |
| 34 | + public override bool Close(BlockProcessor processor, Block block) |
| 35 | + { |
| 36 | + if (block is not HeadingBlock headerBlock) |
| 37 | + return base.Close(processor, block); |
| 38 | + |
| 39 | + var text = headerBlock.Lines.Lines[0].Slice.AsSpan(); |
| 40 | + headerBlock.SetData("header", text.ToString()); |
| 41 | + |
| 42 | + if (!HeadingAnchorParser.MatchAnchorLine().IsMatch(text)) |
| 43 | + return base.Close(processor, block); |
| 44 | + |
| 45 | + var splits = HeadingAnchorParser.MatchAnchor().EnumerateMatches(text); |
| 46 | + |
| 47 | + foreach (var match in splits) |
| 48 | + { |
| 49 | + var header = text.Slice(0, match.Index); |
| 50 | + var anchor = text.Slice(match.Index, match.Length); |
| 51 | + |
| 52 | + var newSlice = new StringSlice(header.ToString()); |
| 53 | + headerBlock.Lines.Lines[0] = new StringLine(ref newSlice); |
| 54 | + headerBlock.SetData("anchor", anchor.ToString()); |
| 55 | + headerBlock.SetData("header", header.ToString()); |
| 56 | + return base.Close(processor, block); |
| 57 | + } |
| 58 | + |
| 59 | + return base.Close(processor, block); |
| 60 | + } |
| 61 | +} |
| 62 | + |
| 63 | +public static partial class HeadingAnchorParser |
| 64 | +{ |
| 65 | + [GeneratedRegex(@"^.*(?:\[[^[]+\])\s*$", RegexOptions.IgnoreCase, "en-US")] |
| 66 | + public static partial Regex MatchAnchorLine(); |
| 67 | + |
| 68 | + [GeneratedRegex(@"(?:\[[^[]+\])\s*$", RegexOptions.IgnoreCase, "en-US")] |
| 69 | + public static partial Regex MatchAnchor(); |
| 70 | +} |
0 commit comments