Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

specify alignment for printing Pair in arrays #22899

Merged
merged 3 commits into from
Jul 27, 2017
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 10 additions & 0 deletions base/show.jl
Original file line number Diff line number Diff line change
Expand Up @@ -1383,6 +1383,16 @@ function alignment(io::IO, x::Rational)
(length(m.captures[1]), length(m.captures[2]))
end

function alignment(io::IO, x::Pair)
s = sprint(0, show, x, env=io)
if has_tight_type(x) # i.e. use "=>" for display
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"
const undef_ref_alignment = (3,3)

Expand Down
12 changes: 12 additions & 0 deletions test/show.jl
Original file line number Diff line number Diff line change
Expand Up @@ -828,3 +828,15 @@ end
show(IOContext(s, :compact => false), (1=>2) => Pair{Any,Any}(3,4))
@test String(take!(s)) == "(1 => 2) => Pair{Any,Any}(3, 4)"
end

@testset "alignment for pairs" begin # (#22899)
@test replstr([1=>22,33=>4]) == "2-element Array{Pair{$Int,$Int},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,Int64}[1=>2, 33=>4]) ==
"2-element Array{Pair{Integer,Int64},1}:\n Pair{Integer,Int64}(1, 2) \n Pair{Integer,Int64}(33, 4)"
end