diff --git a/CHANGELOG.md b/CHANGELOG.md index 025bf9a..62700da 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -8,6 +8,22 @@ follows [Semantic Versioning](https://semver.org/spec/v2.0.0.html). ## Unreleased +### Added + +- `ElementMarkup`, data markup that numbers the element text is in, and `DecodeContext.NextElement()`. Stored by + the serializer like the other shared markup. + +### Fixed + +- Two equal elements side by side stay two. Before, an element closed and an equal one opened straight after it + became one run, so a client saw one thing where the server sent two. This happened with two exits of one + flagged element (`northsouth` read as one exit, `northsouth`), two ``s, ``s + or OSC 8 or MSLP links to one place, two ``s of one variable, and two pictures of one file (MXP + ``, Pueblo ``), which `SpanRenderer` also drew as one picture. The decoder now puts an + `ElementMarkup` on each link, menu, picture, variable and flagged element, and `SpanRenderer` joins spans + only within one element. An OSC 8 link opened again with the same address before it ends is still one + link, and an OSC 8 `id` still joins links. Elements that only style text (bold, a colour) are unchanged. + ## 2.28.1 — 2026-11-10 ### Fixed diff --git a/MarkupString.Ansi/Decoding/VtPlugins.cs b/MarkupString.Ansi/Decoding/VtPlugins.cs index d86188e..69809f6 100644 --- a/MarkupString.Ansi/Decoding/VtPlugins.cs +++ b/MarkupString.Ansi/Decoding/VtPlugins.cs @@ -35,7 +35,10 @@ public static class VtPens /// The OSC 8 or MSLP link, an with only a link. public const string Link = "link"; - /// The OSC 8 link's id, a , set and cleared with . + /// + /// The OSC 8 link's id, a , set and cleared with . A link with + /// no id, and an MSLP link, has an here instead, which keeps it apart from the next. + /// public const string LinkGroup = "link-group"; } @@ -65,6 +68,7 @@ public void Register(DecoderBuilder builder) { // The underline is an MSLP link's extent. context.SetPen(VtPens.Link, null); + context.SetPen(VtPens.LinkGroup, null); state.MslpUnderlined = false; } else if (!before.Underlined && state.Style.Underlined && context.Pen(VtPens.Link) is AnsiMarkup { Style.LinkKind: LinkKind.Command }) @@ -398,9 +402,17 @@ public void Register(DecoderBuilder builder) var target = uri.ToString(); var safe = context.Options.Links.IsAllowed(target); - context.SetPen(VtPens.Link, safe ? new AnsiMarkup(new AnsiStyle { LinkUrl = target, LinkKind = LinkKind.Url }) : null); var id = safe ? LinkId(payload[..separator]) : null; - context.SetPen(VtPens.LinkGroup, id is null ? null : new LinkGroupMarkup(id)); + + // With no id, each link is its own (an ElementMarkup), so two to one place side by side stay two. The + // same link opened again before it was ended, as a program does around a colour change, is still one. + IMarkup? group = id is not null ? new LinkGroupMarkup(id) + : !safe ? null + : context.Pen(VtPens.Link) is AnsiMarkup { Style: { LinkKind: LinkKind.Url } open } && open.LinkUrl == target + && context.Pen(VtPens.LinkGroup) is ElementMarkup current ? current + : context.NextElement(); + context.SetPen(VtPens.Link, safe ? new AnsiMarkup(new AnsiStyle { LinkUrl = target, LinkKind = LinkKind.Url }) : null); + context.SetPen(VtPens.LinkGroup, group); return true; }) .OnOsc(68, static (payload, context) => @@ -410,7 +422,7 @@ public void Register(DecoderBuilder builder) if (parts is not ["1", var type, var command] || command.Length == 0) return false; if (!type.Equals("SEND", StringComparison.OrdinalIgnoreCase)) return false; context.SetPen(VtPens.Link, new AnsiMarkup(new AnsiStyle { LinkUrl = command, LinkKind = LinkKind.Command })); - context.SetPen(VtPens.LinkGroup, null); + context.SetPen(VtPens.LinkGroup, context.NextElement()); context.State().MslpUnderlined = false; return true; }) @@ -420,6 +432,7 @@ public void Register(DecoderBuilder builder) if (context.Pen(VtPens.Link) is AnsiMarkup { Style.LinkKind: LinkKind.Command }) { context.SetPen(VtPens.Link, null); + context.SetPen(VtPens.LinkGroup, null); context.State().MslpUnderlined = false; } }) diff --git a/MarkupString.Mxp/Decoding/MxpDecoding.cs b/MarkupString.Mxp/Decoding/MxpDecoding.cs index 2e953ed..f006187 100644 --- a/MarkupString.Mxp/Decoding/MxpDecoding.cs +++ b/MarkupString.Mxp/Decoding/MxpDecoding.cs @@ -281,7 +281,7 @@ internal sealed class MxpState public int CaptureDepth { get; set; } - public List<(ImageMarkup Image, int Rows, int Columns, int Column, int Next, MarkupText Inline)> Overlays { get; } = []; + public List<(ImageMarkup Image, ElementMarkup Element, int Rows, int Columns, int Column, int Next, MarkupText Inline)> Overlays { get; } = []; public int ExpansionDepth { get; set; } @@ -410,8 +410,12 @@ internal static void LineMode(int mode, DecodeContext context) { LeaveOpen(context); state.Line = MxpMode.Secure; - var markup = new MxpFlagMarkup(flag); - if (context.Open(markup)) state.Open.Add(new MxpOpenElement(flag, markup, openMode: false, lineTag: true)); + var flagged = context.NextElement(); + if (context.Open(flagged)) + { + context.Open(new MxpFlagMarkup(flag)); + state.Open.Add(new MxpOpenElement(flag, flagged, openMode: false, lineTag: true)); + } } // A number with no meaning moves nothing, in either direction. @@ -594,7 +598,7 @@ private bool Element(ParsedTag tag, bool openMode) IMarkup? link = href is not null && Context.Options.Links.IsAllowed(href) ? new AnsiMarkup(new AnsiStyle { LinkUrl = href, LinkKind = LinkKind.Url, LinkText = tag.Get("HINT", 1) }) : null; - OpenElement(tag.Name, link is null ? [] : [link], openMode, lineTag: true); + OpenElement(tag.Name, link is null ? [] : [Context.NextElement(), link], openMode, lineTag: true); return true; } case "SEND": @@ -773,13 +777,13 @@ private void OpenSend(ParsedTag tag, string href, bool openMode) var link = new AnsiMarkup(new AnsiStyle { LinkUrl = commands[0], LinkKind = LinkKind.Command, LinkText = hint }); if (commands.Length == 1 && !prompt) { - OpenElement(tag.Name, [link], openMode, lineTag: true); + OpenElement(tag.Name, [Context.NextElement(), link], openMode, lineTag: true); return; } var choices = new CommandChoice[commands.Length]; for (var i = 0; i < commands.Length; i++) choices[i] = new CommandChoice(labels[i], commands[i]); - OpenElement(tag.Name, [new CommandMenuMarkup(choices, hint, prompt), link], openMode, lineTag: true); + OpenElement(tag.Name, [Context.NextElement(), new CommandMenuMarkup(choices, hint, prompt), link], openMode, lineTag: true); } /// @@ -801,7 +805,7 @@ private void OpenCustom(MxpElementDefinition definition, ParsedTag tag, bool lin var before = Context.Elements.Count; var opened = state.Open.Count; - if (definition.Flag is { } flag) Context.Open(new MxpFlagMarkup(flag)); + if (definition.Flag is { } flag && Context.Open(Context.NextElement())) Context.Open(new MxpFlagMarkup(flag)); // The definition's tags, with the element's attributes put in for &name;, run as secure tags. var expanded = Expand(definition, tag); @@ -1009,7 +1013,7 @@ private void FinishCapture() if (!tag.Has("PRIVATE")) Context.Raise(new VariableEvent(variable, text)); } - OpenElement(tag.Name, [new VariableMarkup(variable)], openMode: false); + OpenElement(tag.Name, [Context.NextElement(), new VariableMarkup(variable)], openMode: false); } else { @@ -1043,16 +1047,18 @@ private void Image(ParsedTag tag) var align = Enum.TryParse(tag.Get("ALIGN"), ignoreCase: true, out var parsed) ? parsed : (ImageAlign?)null; var image = new ImageMarkup(source, null, width, height, align); + // Each picture is its own, so two of one file side by side stay two. + var element = Context.NextElement(); if (widthCells > 0 && heightCells > 0) { // Sized in cells: drawn over the cells the server leaves for it on this line and the ones after. If it left // none, the picture goes in the line where its tag was, as one sized in pixels does. var set = Context.CurrentMarkup; - var layers = new IMarkup[(set?.Count ?? 0) + 1]; - layers[0] = image; - for (var i = 1; i < layers.Length; i++) layers[i] = set![i - 1]; + var layers = new IMarkup[(set?.Count ?? 0) + 2]; layers[0] = image with { Width = widthCells * Context.Identity.CellWidth, Height = heightCells * Context.Identity.CellHeight }; - State.Overlays.Add((image, heightCells, widthCells, Context.Column, 0, MarkupText.Wrap(MarkupSet.Of(layers.AsSpan()), file))); + layers[1] = element; + for (var i = 2; i < layers.Length; i++) layers[i] = set![i - 2]; + State.Overlays.Add((image, element, heightCells, widthCells, Context.Column, 0, MarkupText.Wrap(MarkupSet.Of(layers.AsSpan()), file))); return; } @@ -1061,7 +1067,22 @@ private void Image(ParsedTag tag) height ??= heightCells > 0 ? heightCells * Context.Identity.CellHeight : null; image = image with { Width = width, Height = height }; - Context.Write(file, image); + WriteIn(element, file, image); + } + + /// Writes under inside . + private void WriteIn(ElementMarkup element, string text, IMarkup inner) => WriteIn(Context, element, text, inner); + + private static void WriteIn(DecodeContext context, ElementMarkup element, string text, IMarkup inner) + { + if (!context.Open(element)) + { + context.Write(text, inner); + return; + } + + context.Write(text, inner); + context.Close(element); } private static (int? Pixels, int Cells) Size(string? value) @@ -1085,7 +1106,7 @@ private void DrawOverlays() List<(int Column, int Width)>? inserted = null; for (var i = 0; i < overlays.Count; i++) { - var (image, rows, columns, column, next, inline) = overlays[i]; + var (image, element, rows, columns, column, next, inline) = overlays[i]; // A picture put inline earlier on this line moved the cells after it to the right. var at = column; @@ -1103,7 +1124,7 @@ private void DrawOverlays() context.Insert(at, inline); if (cursor >= at) cursor += inline.DisplayWidth; (inserted ??= []).Add((column, inline.DisplayWidth)); - overlays[i] = (image, rows, columns, column, rows, inline); + overlays[i] = (image, element, rows, columns, column, rows, inline); continue; } @@ -1111,10 +1132,10 @@ private void DrawOverlays() if (next == 0 || Blank(context.PendingLine, at, columns)) { context.MoveToColumn(at); - context.Write(new string(' ', columns), image with { Row = new PictureRow(next, rows, columns) }); + WriteIn(context, element, new string(' ', columns), image with { Row = new PictureRow(next, rows, columns) }); } - overlays[i] = (image, rows, columns, column, next + 1, inline); + overlays[i] = (image, element, rows, columns, column, next + 1, inline); } overlays.RemoveAll(overlay => overlay.Next >= overlay.Rows); diff --git a/MarkupString.Pueblo/Decoding/PuebloDecoding.cs b/MarkupString.Pueblo/Decoding/PuebloDecoding.cs index 50ded05..a0e7c84 100644 --- a/MarkupString.Pueblo/Decoding/PuebloDecoding.cs +++ b/MarkupString.Pueblo/Decoding/PuebloDecoding.cs @@ -205,7 +205,7 @@ private bool Element(ParsedTag tag, string name) { // xch_mode=prompt puts the command on the player's input line instead of sending it. // One entry for both, so closes the menu and the link together. - OpenElement(name, new CommandMenuMarkup([new CommandChoice(command, command)], hint, Prompt: true), new AnsiMarkup(link.Value)); + OpenLink(name, new CommandMenuMarkup([new CommandChoice(command, command)], hint, Prompt: true), new AnsiMarkup(link.Value)); return true; } } @@ -214,7 +214,8 @@ private bool Element(ParsedTag tag, string name) link = new AnsiStyle { LinkUrl = href, LinkKind = LinkKind.Url, LinkText = hint }; } - OpenElement(name, link is { } style ? new AnsiMarkup(style) : null); + if (link is { } style) OpenLink(name, new AnsiMarkup(style)); + else OpenElement(name, null); return true; } case "send": @@ -286,7 +287,19 @@ private void Image(ParsedTag tag) int? height = int.TryParse(tag.Get("height"), NumberStyles.None, CultureInfo.InvariantCulture, out var h) && h > 0 ? h : null; var align = Enum.TryParse(tag.Get("align"), ignoreCase: true, out var parsed) ? parsed : (ImageAlign?)null; var image = new ImageMarkup(src, string.IsNullOrEmpty(alt) ? null : alt, width, height, align); - context.Write(string.IsNullOrEmpty(alt) ? " " : alt, image); + + // Each picture is its own, so two of one file side by side stay two. + var element = context.NextElement(); + var text = string.IsNullOrEmpty(alt) ? " " : alt; + if (context.Open(element)) + { + context.Write(text, image); + context.Close(element); + } + else + { + context.Write(text, image); + } } private void Pane(ParsedTag tag) @@ -313,13 +326,25 @@ private void OpenElement(string name, IMarkup? markup) State.Open.Add((name, markup)); } - /// Opens several markups as one element: closing it closes them all. - private void OpenElement(string name, IMarkup first, IMarkup second) + /// + /// Opens a link, or a menu and its link, as one element of its own, so two links to one place side by side stay + /// two: closing it closes them all. + /// + private void OpenLink(string name, params IMarkup[] markups) { - IMarkup? opened = null; - if (Context.Open(first)) opened = first; - if (Context.Open(second)) opened ??= second; - State.Open.Add((name, opened)); + var element = Context.NextElement(); + if (!Context.Open(element)) + { + State.Open.Add((name, null)); + return; + } + + foreach (var markup in markups) + { + if (!Context.Open(markup)) break; + } + + State.Open.Add((name, element)); } /// @@ -332,7 +357,7 @@ private void OpenSend(string name, string href, string? hintText) var link = new AnsiMarkup(new AnsiStyle { LinkUrl = commands[0], LinkKind = LinkKind.Command, LinkText = commands.Length == 1 ? hintText : null }); if (commands.Length == 1) { - OpenElement(name, link); + OpenLink(name, link); return; } @@ -356,7 +381,7 @@ private void OpenSend(string name, string href, string? hintText) link = new AnsiMarkup(new AnsiStyle { LinkUrl = commands[0], LinkKind = LinkKind.Command, LinkText = hint }); var choices = new CommandChoice[commands.Length]; for (var i = 0; i < commands.Length; i++) choices[i] = new CommandChoice(labels[i], commands[i]); - OpenElement(name, new CommandMenuMarkup(choices, hint), link); + OpenLink(name, new CommandMenuMarkup(choices, hint), link); } private void Close(string name) diff --git a/MarkupString.Tests/Decoding/MxpDecodingTests.cs b/MarkupString.Tests/Decoding/MxpDecodingTests.cs index 2b8fe2c..b30dd84 100644 --- a/MarkupString.Tests/Decoding/MxpDecodingTests.cs +++ b/MarkupString.Tests/Decoding/MxpDecodingTests.cs @@ -145,6 +145,62 @@ public async Task CustomElements() await Assert.That(spans[1].Style).IsEqualTo(DisplayStyle.Plain); } + /// The pieces of under each element, by its number, in order. + private static List ByElement(DisplayLine line) + { + var pieces = new List(); + ElementMarkup? last = null; + foreach (var run in line.Content.Runs) + { + var element = run.Markups.OfType().FirstOrDefault(); + var text = line.Content.Text.Substring(run.Start, run.Length); + if (element is not null && Equals(element, last)) pieces[^1] += text; + else pieces.Add(text); + last = element; + } + + return pieces; + } + + [Test] + [Arguments("\e[1z\n\e[1znorthsouth\n")] + [Arguments("\e[1znorthsouth\n")] + [Arguments("\e[1znorthsouth\n")] + [Arguments("\e[1znorthsouth\n")] + [Arguments("\e[1znorthsouth\n")] + [Arguments("\e[1z\n")] + public async Task TwoEqualElementsSideBySide_StayTwo(string input) + { + var (lines, _, _) = Decode(input); + var line = lines[^1]; + await Assert.That(ByElement(line)).IsEquivalentTo(new[] { "north", "south" }); + await Assert.That(SpanRenderer.Render(line.Content, AnsiDisplay.Default, new DisplayOptions()).Count).IsEqualTo(2); + } + + [Test] + public async Task TwoPicturesOfOneFileSideBySide_AreTwoPictures() + { + var (lines, _, _) = Decode("\e[1z\n"); + var spans = SpanRenderer.Render(lines[0].Content, AnsiDisplay.Default, new DisplayOptions()); + await Assert.That(spans.Select(span => span.Text)).IsEquivalentTo(new[] { "m.png", "m.png" }); + } + + [Test] + public async Task AnElementStaysOneAcrossItsStyles() + { + var (lines, _, _) = Decode("\e[1zabc\n"); + await Assert.That(ByElement(lines[0])).IsEquivalentTo(new[] { "abc" }); + } + + [Test] + public async Task AnElementIsStoredAndReadBack() + { + var registry = MarkupRegistry.Empty.WithAnsi().With(MxpDecoding.FlagCodec); + var (lines, _, _) = Decode("\e[10zThe Square\n"); + var back = MarkupTextSerializer.Deserialize(MarkupTextSerializer.Serialize(lines[0].Content, registry), registry); + await Assert.That(back.Runs.Single().Markups).IsEquivalentTo(lines[0].Content.Runs.Single().Markups); + } + [Test] public async Task LineTags_MarkTheLine() { diff --git a/MarkupString.Tests/Decoding/PuebloDecodingTests.cs b/MarkupString.Tests/Decoding/PuebloDecodingTests.cs index ee171ff..96a8e24 100644 --- a/MarkupString.Tests/Decoding/PuebloDecodingTests.cs +++ b/MarkupString.Tests/Decoding/PuebloDecodingTests.cs @@ -23,6 +23,23 @@ private static List Decode(string text) private static IEnumerable Markups(DisplayLine line) => line.Content.Runs.SelectMany(run => run.Markups); + [Test] + [Arguments("northsouth\n")] + [Arguments("northsouth\n")] + [Arguments("northsouth\n")] + public async Task TwoEqualElementsSideBySide_StayTwo(string input) + { + var lines = Decode(input); + await Assert.That(Spans(lines[^1]).Select(span => span.Text)).IsEquivalentTo(new[] { "north", "south" }); + } + + [Test] + public async Task TwoPicturesOfOneFileSideBySide_AreTwoPictures() + { + var lines = Decode("\"map\"\"map\"\n"); + await Assert.That(Spans(lines[^1]).Select(span => span.Text)).IsEquivalentTo(new[] { "map", "map" }); + } + [Test] public async Task MudText_TagsAreText() { diff --git a/MarkupString.Tests/Decoding/VtDecodingTests.cs b/MarkupString.Tests/Decoding/VtDecodingTests.cs index b6f8ba7..8af9936 100644 --- a/MarkupString.Tests/Decoding/VtDecodingTests.cs +++ b/MarkupString.Tests/Decoding/VtDecodingTests.cs @@ -180,6 +180,20 @@ public async Task Osc8_Id_GroupsTheLinkAcrossLines() await Assert.That(second[2].Style.Interaction).IsEqualTo(new Interaction(InteractionKind.Url, "https://example.com")); } + [Test] + public async Task Osc8_TwoLinksToOnePlaceSideBySide_AreTwo() + { + var lines = Decode("\e]8;;https://example.com\e\\one\e]8;;\e\\\e]8;;https://example.com\e\\two\e]8;;\e\\\n"); + await Assert.That(Spans(lines[0].Content).Select(span => span.Text)).IsEquivalentTo(["one", "two"]); + } + + [Test] + public async Task Osc8_TheSameLinkOpenedAgainBeforeItEnds_IsOne() + { + var lines = Decode("\e]8;;https://example.com\e\\one\e]8;;https://example.com\e\\two\e]8;;\e\\\n"); + await Assert.That(Spans(lines[0].Content).Select(span => span.Text)).IsEquivalentTo(["onetwo"]); + } + [Test] public async Task Osc8_UnsafeScheme_IsText() { @@ -187,6 +201,20 @@ public async Task Osc8_UnsafeScheme_IsText() await Assert.That(Spans(lines[0].Content).Single().Style.Interaction).IsNull(); } + [Test] + public async Task Mslp_TwoLinksSideBySide_AreTwo() + { + var lines = Decode("\e]68;1;SEND;look\a\e[4mone\e[24m\e]68;1;SEND;look\a\e[4mtwo\e[24m\n"); + await Assert.That(Spans(lines[0].Content).Select(span => span.Text)).IsEquivalentTo(["one", "two"]); + } + + [Test] + public async Task Mslp_EndingTheLinkLeavesNoElementBehind() + { + var lines = Decode("\e]68;1;SEND;look\a\e[4mone\e[24m after\n"); + await Assert.That(lines[0].Content.Runs.Where(run => run.Markups.OfType().Any()).Count()).IsEqualTo(1); + } + [Test] public async Task Mslp_LinkLastsAsLongAsTheUnderline() { diff --git a/MarkupString/Decoding/DecodeContext.cs b/MarkupString/Decoding/DecodeContext.cs index 0dd1ffb..c3bcce1 100644 --- a/MarkupString/Decoding/DecodeContext.cs +++ b/MarkupString/Decoding/DecodeContext.cs @@ -21,6 +21,7 @@ public sealed class DecodeContext private readonly Dictionary _protocols = new(StringComparer.OrdinalIgnoreCase); private MarkupSet? _set; private bool _setValid; + private int _elementNumbers; private ITextProtocol? _active; private long _sequence; @@ -104,6 +105,12 @@ public void SetPen(string slot, IMarkup? markup) return null; } + /// + /// A new , numbered after the last this decoder made. Opened before an element's own + /// markup, it keeps the element apart from an equal one beside it; closing it closes the element. + /// + public ElementMarkup NextElement() => new(++_elementNumbers); + /// Opens over the text that follows, until . /// False when are already open; nothing is opened. public bool Open(IMarkup markup) diff --git a/MarkupString/Display/SpanRenderer.cs b/MarkupString/Display/SpanRenderer.cs index ddc7118..8244541 100644 --- a/MarkupString/Display/SpanRenderer.cs +++ b/MarkupString/Display/SpanRenderer.cs @@ -33,9 +33,13 @@ public static IReadOnlyList Render(MarkupText text, IStyleResolver var source = text.Text; var at = 0; + // The element the last span is in: spans that look alike are one span only within one element, so two pictures + // or two links side by side stay two. + ElementMarkup? element = null; + foreach (var run in text.Runs) { - if (run.Start > at) Add(spans, source[at..run.Start], DisplayStyle.Plain, fold); + if (run.Start > at) Add(spans, source[at..run.Start], DisplayStyle.Plain, fold, null, ref element); var point = FindPoint(run.Markups); if (point is not null) @@ -49,13 +53,13 @@ public static IReadOnlyList Render(MarkupText text, IStyleResolver styles[run.Markups] = style = registry.Resolve(run.Markups, options); } - Add(spans, source.Substring(run.Start, run.Length), style, fold); + Add(spans, source.Substring(run.Start, run.Length), style, fold, ElementOf(run.Markups), ref element); } at = run.End; } - if (at < source.Length) Add(spans, source[at..], DisplayStyle.Plain, fold); + if (at < source.Length) Add(spans, source[at..], DisplayStyle.Plain, fold, null, ref element); return spans; } @@ -127,19 +131,32 @@ public static string CssClasses(DisplayStyle style) _ => true, }; - private static void Add(List spans, string text, DisplayStyle style, bool fold) + private static void Add(List spans, string text, DisplayStyle style, bool fold, ElementMarkup? element, ref ElementMarkup? last) { if (text.Length == 0) return; if (fold) text = AsciiFold.Default.Fold(text); - if (spans.Count > 0 && spans[^1] is { Point: null } last && last.Style == style) + var same = Equals(element, last); + last = element; + if (same && spans.Count > 0 && spans[^1] is { Point: null } previous && previous.Style == style) { - spans[^1] = last with { Text = last.Text + text }; + spans[^1] = previous with { Text = previous.Text + text }; return; } spans.Add(new DisplaySpan(text, style)); } + /// The innermost element are in, or null. + private static ElementMarkup? ElementOf(MarkupSet markups) + { + foreach (var markup in markups) + { + if (markup is ElementMarkup element) return element; + } + + return null; + } + private static void Append(StringBuilder css, string property, string value) { if (css.Length > 0) css.Append(';'); diff --git a/MarkupString/Elements/ElementCodecs.cs b/MarkupString/Elements/ElementCodecs.cs index 1f2ba3c..81b86d3 100644 --- a/MarkupString/Elements/ElementCodecs.cs +++ b/MarkupString/Elements/ElementCodecs.cs @@ -143,6 +143,9 @@ internal static class ElementCodecs new Codec("link-group", static (w, m) => w.WriteString("g", m.Group), static e => new LinkGroupMarkup(String(e, "g") ?? string.Empty)), + new Codec("element", + static (w, m) => w.WriteNumber("n", m.Number), + static e => new ElementMarkup(Int(e, "n") ?? 0)), new Codec("standin", static (w, m) => w.WriteString("t", m.Text), static e => new StandInMarkup(String(e, "t") ?? string.Empty)), diff --git a/MarkupString/Elements/ElementMarkup.cs b/MarkupString/Elements/ElementMarkup.cs new file mode 100644 index 0000000..7c22f5d --- /dev/null +++ b/MarkupString/Elements/ElementMarkup.cs @@ -0,0 +1,14 @@ +namespace MarkupString; + +/// +/// Which element the text is in, numbered by the decoder that read it. Two elements that are otherwise equal, such as +/// two links to one place or two pictures of one file side by side, differ by it, so they stay two runs (and two links, +/// two pictures) rather than becoming one. +/// +/// +/// A decoder adds one to the elements whose every occurrence is its own thing: links, menus, pictures, variables and +/// flagged elements. Elements that only style the text (bold, a colour) need none, since two of them side by side look +/// as one would. No format writes anything for it (). +/// +/// The decoder's number for the element, from 1. +public sealed record ElementMarkup(int Number) : IDataMarkup; diff --git a/MarkupString/PublicAPI.Unshipped.txt b/MarkupString/PublicAPI.Unshipped.txt index 59af5dc..9f170de 100644 --- a/MarkupString/PublicAPI.Unshipped.txt +++ b/MarkupString/PublicAPI.Unshipped.txt @@ -862,3 +862,16 @@ MarkupString.Layout.BorderStyle.Cross.get -> MarkupString.MarkupText! MarkupString.Layout.BorderStyle.Cross.init -> void MarkupString.Layout.Flex.Join.get -> bool MarkupString.Layout.Flex.Join.init -> void +MarkupString.ElementMarkup +MarkupString.ElementMarkup.$() -> MarkupString.ElementMarkup! +MarkupString.ElementMarkup.Deconstruct(out int Number) -> void +MarkupString.ElementMarkup.ElementMarkup(int Number) -> void +MarkupString.ElementMarkup.Equals(MarkupString.ElementMarkup? other) -> bool +MarkupString.ElementMarkup.Number.get -> int +MarkupString.ElementMarkup.Number.init -> void +MarkupString.Decoding.DecodeContext.NextElement() -> MarkupString.ElementMarkup! +override MarkupString.ElementMarkup.Equals(object? obj) -> bool +override MarkupString.ElementMarkup.GetHashCode() -> int +override MarkupString.ElementMarkup.ToString() -> string! +static MarkupString.ElementMarkup.operator !=(MarkupString.ElementMarkup? left, MarkupString.ElementMarkup? right) -> bool +static MarkupString.ElementMarkup.operator ==(MarkupString.ElementMarkup? left, MarkupString.ElementMarkup? right) -> bool