From 11c5bd98c3285dd02c55c9369b9ee590c5fbe2e5 Mon Sep 17 00:00:00 2001 From: TEC Date: Sat, 9 Mar 2024 14:06:07 +0800 Subject: [PATCH] Introduce specialised write for AnnotatedIOBuffer In https://github.com/JuliaLang/julia/commit/f117a500ca93, the AnnotatedIOBuffer type was introduced. If you write from an AnnotatedIOBuffer to another kind of IO, currently all styling information is lost. This seems undesirable, and we can make it work more like writing an AnnotatedString to IO ... by converting this to an AnnotatedString write within a specialised write method. The conversion surely adds overhead, but it's a very staightforward way to make this work. If this ends up being a legitimate performance concern, we can always revisit this and either: - Add a specialised code path for AnnotatedIOBuffer - Try to make the current AnnotatedString-oriented methods more generic (somehow) --- src/io.jl | 14 ++++++++++++++ test/runtests.jl | 11 +++++++++++ 2 files changed, 25 insertions(+) diff --git a/src/io.jl b/src/io.jl index c15cce3c..73228332 100644 --- a/src/io.jl +++ b/src/io.jl @@ -274,6 +274,20 @@ function show(io::IO, c::AnnotatedChar) end end +function write(io::IO, aio::Base.AnnotatedIOBuffer) + if get(io, :color, false) == true + # This does introduce an overhead that technically + # could be avoided, but I'm not sure that it's currently + # worth the effort to implement an efficient version of + # writing from a AnnotatedIOBuffer with style. + # In the meantime, by converting to an `AnnotatedString` we can just + # reuse all the work done to make that work. + write(io, read(aio, AnnotatedString)) + else + write(io, aio.io) + end +end + """ A mapping between ANSI named colors and 8-bit colors for use in HTML representations. diff --git a/test/runtests.jl b/test/runtests.jl index f5a7a4d9..205bbe5c 100644 --- a/test/runtests.jl +++ b/test/runtests.jl @@ -235,6 +235,17 @@ end @test normal == styled == "abcdef" end +@testset "AnnotatedIOBuffer" begin + aio = Base.AnnotatedIOBuffer() + @test write(aio, styled"{red:hey} {blue:there}") == 9 + buf = IOBuffer() + @test write(buf, seekstart(aio)) == 9 + @test String(take!(buf)) == "hey there" + cbuf = IOContext(buf, :color => true) + @test write(cbuf, seekstart(aio)) == 29 + @test String(take!(buf)) == "\e[31mhey\e[39m \e[34mthere\e[39m" +end + @testset "Legacy" begin @test StyledStrings.Legacy.legacy_color(:blue) == SimpleColor(:blue) @test StyledStrings.Legacy.legacy_color(:light_blue) == SimpleColor(:bright_blue)