fix print_child_key with color
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.
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
This seems like it probably belongs in Base.
perhaps @nhz2 could submit this as a PR to Base then? Or I could do it if you are busy.
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.
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.
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?