diff --git a/base/show.jl b/base/show.jl index 39706805f9ec55..eb59ccc3690fff 100644 --- a/base/show.jl +++ b/base/show.jl @@ -273,11 +273,12 @@ print(io::IO, n::Unsigned) = print(io, dec(n)) show(io::IO, p::Ptr) = print(io, typeof(p), " @0x$(hex(UInt(p), Sys.WORD_SIZE>>2))") +show_pair_with_arrow(p::Pair) = + typeof(p.first) == typeof(p).parameters[1] && + typeof(p.second) == typeof(p).parameters[2] + function show(io::IO, p::Pair) - if typeof(p.first) != typeof(p).parameters[1] || - typeof(p.second) != typeof(p).parameters[2] - return show_default(io, p) - end + show_pair_with_arrow(p) || return show_default(io, p) isa(p.first,Pair) && print(io, "(") show(io, p.first) @@ -1373,9 +1374,13 @@ function alignment(io::IO, x::Rational) end function alignment(io::IO, x::Pair) - m = match(r"^(.*?=)(>.*)$", sprint(0, show, x, env=io)) - m === nothing ? (length(sprint(0, show, x, env=io)), 0) : - (length(m.captures[1]), length(m.captures[2])) + s = sprint(0, show, x, env=io) + if show_pair_with_arrow(x) + left = length(sprint(0, show, x.first, env=io)) + 2isa(x.first, Pair) # 2 for parens + (left+1, length(s)-left-1) # +1 for the "=" part of "=>" + else + (0, length(s)) # as for x::Any + end end const undef_ref_str = "#undef" diff --git a/test/show.jl b/test/show.jl index 72a8cd8e4436c5..c8a75950b7a6e8 100644 --- a/test/show.jl +++ b/test/show.jl @@ -818,3 +818,15 @@ end @test sprint(show, Val(:Float64)) == "Val{:Float64}()" # Val of a symbol @test sprint(show, Val(true)) == "Val{true}()" # Val of a value end + +@testset "alignment for pairs" begin # (#22899) + @test replstr([1=>22,33=>4]) == "2-element Array{Pair{Int64,Int64},1}:\n 1=>22\n 33=>4 " + # first field may have "=>" in its representation + @test replstr(Pair[(1=>2)=>3, 4=>5]) == + "2-element Array{Pair,1}:\n (1=>2)=>3\n 4=>5" + @test replstr(Any[Dict(1=>2)=> (3=>4), 1=>2]) == + "2-element Array{Any,1}:\n Dict(1=>2)=>(3=>4)\n 1=>2 " + # left-alignment when not using the "=>" symbol + @test replstr(Pair{Integer,Int}[1=>2, 33=>4]) == + "2-element Array{Pair{Integer,Int64},1}:\n Pair{Integer,Int64}(1, 2) \n Pair{Integer,Int64}(33, 4)" +end