AbstractTrees.jl icon indicating copy to clipboard operation
AbstractTrees.jl copied to clipboard

fix print_child_key with color

Open Roger-luo opened this issue 2 years ago • 6 comments

textwidth does not escape ASCII escape chars, which as a result gives wrong estimation of the text width, this might need to be fixed upstream (or use a more accurate function), but this PR is a workaround to this.

Roger-luo avatar Feb 01 '23 06:02 Roger-luo

I think this function will work to correct the textwidth result in case there are colors.

function colored_textwidth(x::AbstractString)
    i = firstindex(x)
    width = textwidth(x)
    while true
        found = findnext(r"\x1b\[[0-9;]*m", x, i)
        isnothing(found) && break
        width -= (length(found) - 1)
        i = found[end] + 1
    end
    width
end

nhz2 avatar Feb 10 '23 21:02 nhz2

This seems like it probably belongs in Base.

oscardssmith avatar Feb 11 '23 00:02 oscardssmith

perhaps @nhz2 could submit this as a PR to Base then? Or I could do it if you are busy.

Roger-luo avatar Feb 11 '23 20:02 Roger-luo

Yes, feel free to submit the function as a PR to Base as I will be pretty busy for the next two weeks. Also, the changes in this PR look good to me, though ideally with a colored_textwidth function the print_child_key function would only need to be called once.

nhz2 avatar Feb 13 '23 03:02 nhz2

True, I think even with this fixed in Base, it will take a quite long time for AbstractTree get fixed, so maybe we should have this patch included in this package and add a @static if VERSION < v"1.9-" on it so it only triggers in lower Julia version.

Roger-luo avatar Feb 13 '23 04:02 Roger-luo

https://github.com/JuliaIO/WidthLimitedIO.jl Seems to have some ANSI escape code detection without regex. Maybe this function could be added to WidthLimitedIO.jl?

nhz2 avatar Mar 21 '23 16:03 nhz2