Handle a short ANSI reset ("\e[m") (#220)

It's legal to omit the 0 in the "\e[0m" sequence to reduce the number of
bytes needed to reset the terminal. See
https://en.wikipedia.org/wiki/ANSI_escape_code#CSI_(Control_Sequence_Introducer)_sequences
and a simple explanation and the cited reference for a more involved
one.
This commit is contained in:
Frank Hunleth 2021-04-20 08:16:21 -04:00 committed by GitHub
parent 0ea781cccb
commit 0f49351c3b
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
2 changed files with 8 additions and 0 deletions

View file

@ -79,6 +79,9 @@ defmodule LivebookWeb.ANSI do
defmodifier(:reset, 0)
# When the code is missing (i.e., "\e[m"), it is 0 for reset.
defmodifier(:reset, "")
@colors [:black, :red, :green, :yellow, :blue, :magenta, :cyan, :white]
for {color, index} <- Enum.with_index(@colors) do

View file

@ -18,6 +18,11 @@ defmodule LivebookWeb.ANSITest do
ANSI.ansi_string_to_html("\e[4mcat\e[0m") |> Phoenix.HTML.safe_to_string()
end
test "supports short reset sequence" do
assert ~s{<span style="color: var(--ansi-color-blue);">cat</span>} ==
ANSI.ansi_string_to_html("\e[34mcat\e[m") |> Phoenix.HTML.safe_to_string()
end
test "supports multiple escape codes at the same time" do
assert ~s{<span style="background-color: var(--ansi-color-red);color: var(--ansi-color-blue);">cat</span>} ==
ANSI.ansi_string_to_html("\e[34m\e[41mcat\e[0m") |> Phoenix.HTML.safe_to_string()