Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 16 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 (`<Exit>north</Exit><Exit>south</Exit>` read as one exit, `northsouth`), two `<SEND>`s, `<A>`s
or OSC 8 or MSLP links to one place, two `<VAR>`s of one variable, and two pictures of one file (MXP
`<IMAGE>`, Pueblo `<img>`), 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
Expand Down
21 changes: 17 additions & 4 deletions MarkupString.Ansi/Decoding/VtPlugins.cs
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,10 @@ public static class VtPens
/// <summary>The OSC 8 or MSLP link, an <see cref="AnsiMarkup"/> with only a link.</summary>
public const string Link = "link";

/// <summary>The OSC 8 link's <c>id</c>, a <see cref="LinkGroupMarkup"/>, set and cleared with <see cref="Link"/>.</summary>
/// <summary>
/// The OSC 8 link's <c>id</c>, a <see cref="LinkGroupMarkup"/>, set and cleared with <see cref="Link"/>. A link with
/// no id, and an MSLP link, has an <see cref="ElementMarkup"/> here instead, which keeps it apart from the next.
/// </summary>
public const string LinkGroup = "link-group";
}

Expand Down Expand Up @@ -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 })
Expand Down Expand Up @@ -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) =>
Expand All @@ -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<VtState>().MslpUnderlined = false;
return true;
})
Expand All @@ -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<VtState>().MslpUnderlined = false;
}
})
Expand Down
55 changes: 38 additions & 17 deletions MarkupString.Mxp/Decoding/MxpDecoding.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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; }

Expand Down Expand Up @@ -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.
Expand Down Expand Up @@ -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":
Expand Down Expand Up @@ -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);
}

/// <summary>
Expand All @@ -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);
Expand Down Expand Up @@ -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
{
Expand Down Expand Up @@ -1043,16 +1047,18 @@ private void Image(ParsedTag tag)
var align = Enum.TryParse<ImageAlign>(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;
}

Expand All @@ -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);
}

/// <summary>Writes <paramref name="text"/> under <paramref name="inner"/> inside <paramref name="element"/>.</summary>
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)
Expand All @@ -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;
Expand All @@ -1103,18 +1124,18 @@ 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;
}

// A later row drawn over text would hide it; that row of the picture is left out instead.
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);
Expand Down
47 changes: 36 additions & 11 deletions MarkupString.Pueblo/Decoding/PuebloDecoding.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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 </a> 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;
}
}
Expand All @@ -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":
Expand Down Expand Up @@ -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<ImageAlign>(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)
Expand All @@ -313,13 +326,25 @@ private void OpenElement(string name, IMarkup? markup)
State.Open.Add((name, markup));
}

/// <summary>Opens several markups as one element: closing it closes them all.</summary>
private void OpenElement(string name, IMarkup first, IMarkup second)
/// <summary>
/// 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.
/// </summary>
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));
}

/// <summary>
Expand All @@ -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;
}

Expand All @@ -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)
Expand Down
56 changes: 56 additions & 0 deletions MarkupString.Tests/Decoding/MxpDecodingTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -145,6 +145,62 @@ public async Task CustomElements()
await Assert.That(spans[1].Style).IsEqualTo(DisplayStyle.Plain);
}

/// <summary>The pieces of <paramref name="line"/> under each element, by its number, in order.</summary>
private static List<string> ByElement(DisplayLine line)
{
var pieces = new List<string>();
ElementMarkup? last = null;
foreach (var run in line.Content.Runs)
{
var element = run.Markups.OfType<ElementMarkup>().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<!ELEMENT Exit FLAG=RoomExit>\n\e[1z<Exit>north</Exit><Exit>south</Exit>\n")]
[Arguments("\e[1z<SEND href=go>north</SEND><SEND href=go>south</SEND>\n")]
[Arguments("\e[1z<SEND \"n|s\">north</SEND><SEND \"n|s\">south</SEND>\n")]
[Arguments("\e[1z<A href=\"https://x.org\">north</A><A href=\"https://x.org\">south</A>\n")]
[Arguments("\e[1z<VAR hp>north</VAR><VAR hp>south</VAR>\n")]
[Arguments("\e[1z<IMAGE north><IMAGE south>\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<IMAGE m.png><IMAGE m.png>\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[1z<SEND href=go>a<B>b</B>c</SEND>\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()
{
Expand Down
Loading
Loading