|
| 1 | +using System.Buffers; |
| 2 | +namespace MarkupString.Ansi; |
| 3 | + |
| 4 | +/// <summary> |
| 5 | +/// Renders a run as GitHub-flavoured Markdown: bold as <c>**</c>, italic as <c>*</c>, strikethrough as |
| 6 | +/// <c>~~</c>, and a URL link as <c>[text](address)</c>. Markdown has no colour, underline, faint, blink, |
| 7 | +/// overline or reverse video, so those are dropped and the text kept; so is a command link, which a page |
| 8 | +/// has nowhere to send. |
| 9 | +/// </summary> |
| 10 | +/// <remarks> |
| 11 | +/// <para>Markdown spells nesting with delimiters that have to pair up, so emphasis that carries on from one |
| 12 | +/// run into the next is written once round both — <c>**a *b***</c>, not <c>**a*****b***</c> — the way the |
| 13 | +/// ANSI emitter writes only what changed. A run decides that from its neighbours alone |
| 14 | +/// (<see cref="EmitContext.Previous"/> and <see cref="EmitContext.Next"/>), the two sides agree on what stays |
| 15 | +/// open, and a run next to a point, a block or a layer drawn by another package's emitter closes everything |
| 16 | +/// it opened.</para> |
| 17 | +/// <para>A delimiter is kept off the whitespace at either end of what it covers, where Markdown would not |
| 18 | +/// read it as one, and is closed before a line ending and opened again after it, since emphasis cannot cross |
| 19 | +/// a blank line. A run of nothing but whitespace is not wrapped at all.</para> |
| 20 | +/// </remarks> |
| 21 | +public sealed class AnsiMarkdownEmitter : IMarkupSetEmitter |
| 22 | +{ |
| 23 | + /// <inheritdoc/> |
| 24 | + public MarkupFormat Format => MarkupFormat.Markdown; |
| 25 | + |
| 26 | + /// <inheritdoc/> |
| 27 | + public bool TryEmit(MarkupSet set, ReadOnlySpan<char> body, in EmitContext context, IBufferWriter<char> output) |
| 28 | + { |
| 29 | + ArgumentNullException.ThrowIfNull(set); |
| 30 | + ArgumentNullException.ThrowIfNull(output); |
| 31 | + |
| 32 | + if (StandsAlone(context.Markups, context) || AnsiEmitterSupport.HasDelegatedLayer(set, context)) |
| 33 | + { |
| 34 | + AnsiEmitterSupport.EmitSegmented(set, body, context, output, WriteAlone); |
| 35 | + return true; |
| 36 | + } |
| 37 | + |
| 38 | + var own = Delimiters(AnsiEmitterSupport.Fold(set, context.Format)); |
| 39 | + WriteDelimited(own, Shared(own, context.Previous, context), Shared(own, context.Next, context), body, output); |
| 40 | + return true; |
| 41 | + } |
| 42 | + |
| 43 | + /// <summary>One delimiter pair: what opens a span and what closes it.</summary> |
| 44 | + private readonly record struct Delimiter(string Open, string Close); |
| 45 | + |
| 46 | + private static readonly Delimiter Strike = new("~~", "~~"); |
| 47 | + private static readonly Delimiter Strong = new("**", "**"); |
| 48 | + private static readonly Delimiter Emphasis = new("*", "*"); |
| 49 | + |
| 50 | + /// <summary> |
| 51 | + /// The delimiters <paramref name="style"/> is written with, outermost first, always in the same order — |
| 52 | + /// a link, then strikethrough, bold and italic — so two runs that share some of them share the outermost. |
| 53 | + /// </summary> |
| 54 | + private static List<Delimiter> Delimiters(in AnsiStyle style) |
| 55 | + { |
| 56 | + var delimiters = new List<Delimiter>(4); |
| 57 | + if (style.LinkKind == LinkKind.Url |
| 58 | + && style.LinkUrl is { Length: > 0 } url |
| 59 | + && UrlSafety.IsSafeNavigableUrl(url)) |
| 60 | + delimiters.Add(new Delimiter("[", "](" + MarkdownSyntax.Destination(url) + ")")); |
| 61 | + if (style.StrikeThrough) delimiters.Add(Strike); |
| 62 | + if (style.Bold) delimiters.Add(Strong); |
| 63 | + if (style.Italic) delimiters.Add(Emphasis); |
| 64 | + return delimiters; |
| 65 | + } |
| 66 | + |
| 67 | + /// <summary> |
| 68 | + /// Whether a run is written with nothing left open on either side: one that carries a point (written by |
| 69 | + /// its own emitter, or not at all), a block (drawn whole, or not as runs of this emitter's), or a layer |
| 70 | + /// another package writes between the stretches of styling. |
| 71 | + /// </summary> |
| 72 | + private static bool StandsAlone(MarkupSet markups, in EmitContext context) |
| 73 | + { |
| 74 | + foreach (var markup in markups) |
| 75 | + if (markup is IPointMarkup or IBlockMarkup) return true; |
| 76 | + return AnsiEmitterSupport.HasDelegatedLayer(markups, context); |
| 77 | + } |
| 78 | + |
| 79 | + /// <summary>How many of <paramref name="own"/>'s outermost delimiters stay open into, or from, <paramref name="neighbour"/>.</summary> |
| 80 | + private static int Shared(List<Delimiter> own, MarkupSet? neighbour, in EmitContext context) |
| 81 | + { |
| 82 | + if (own.Count == 0 || neighbour is null || StandsAlone(neighbour, context)) return 0; |
| 83 | + var theirs = Delimiters(AnsiEmitterSupport.Fold(neighbour, context.Format)); |
| 84 | + var shared = 0; |
| 85 | + while (shared < own.Count && shared < theirs.Count && own[shared] == theirs[shared]) shared++; |
| 86 | + return shared; |
| 87 | + } |
| 88 | + |
| 89 | + private static void WriteAlone(in AnsiStyle style, ReadOnlySpan<char> body, in EmitContext context, IBufferWriter<char> output) => |
| 90 | + WriteDelimited(Delimiters(style), 0, 0, body, output); |
| 91 | + |
| 92 | + /// <summary> |
| 93 | + /// Writes <paramref name="body"/> inside <paramref name="delimiters"/>, the first <paramref name="opened"/> of |
| 94 | + /// them already open before it and the first <paramref name="kept"/> left open after it. |
| 95 | + /// </summary> |
| 96 | + private static void WriteDelimited(List<Delimiter> delimiters, int opened, int kept, ReadOnlySpan<char> body, IBufferWriter<char> output) |
| 97 | + { |
| 98 | + if (delimiters.Count == 0) |
| 99 | + { |
| 100 | + output.Write(body); |
| 101 | + return; |
| 102 | + } |
| 103 | + |
| 104 | + while (true) |
| 105 | + { |
| 106 | + var newline = body.IndexOf('\n'); |
| 107 | + if (newline < 0) |
| 108 | + { |
| 109 | + WriteLine(delimiters, opened, kept, body, output); |
| 110 | + return; |
| 111 | + } |
| 112 | + |
| 113 | + // Everything is closed before the line ending and opened again after it. |
| 114 | + WriteLine(delimiters, opened, 0, body[..newline], output); |
| 115 | + output.Write("\n"); |
| 116 | + body = body[(newline + 1)..]; |
| 117 | + opened = 0; |
| 118 | + } |
| 119 | + } |
| 120 | + |
| 121 | + /// <summary>One line of a run: the delimiters it opens after its leading whitespace, and those it closes before its trailing whitespace.</summary> |
| 122 | + private static void WriteLine(List<Delimiter> delimiters, int opened, int kept, ReadOnlySpan<char> line, IBufferWriter<char> output) |
| 123 | + { |
| 124 | + var start = line.IndexOfAnyExcept(' ', '\t'); |
| 125 | + if (start < 0) |
| 126 | + { |
| 127 | + // Nothing to cover. What was open before closes here and what stays open after opens here, against |
| 128 | + // the text either side of the whitespace; a pair that would open and close round nothing is left out. |
| 129 | + for (var i = opened - 1; i >= kept; i--) output.Write(delimiters[i].Close); |
| 130 | + output.Write(line); |
| 131 | + for (var i = opened; i < kept; i++) output.Write(delimiters[i].Open); |
| 132 | + return; |
| 133 | + } |
| 134 | + |
| 135 | + var end = line.LastIndexOfAnyExcept(' ', '\t') + 1; |
| 136 | + output.Write(line[..start]); |
| 137 | + for (var i = opened; i < delimiters.Count; i++) output.Write(delimiters[i].Open); |
| 138 | + output.Write(line[start..end]); |
| 139 | + for (var i = delimiters.Count - 1; i >= kept; i--) output.Write(delimiters[i].Close); |
| 140 | + output.Write(line[end..]); |
| 141 | + } |
| 142 | +} |
0 commit comments