Skip to content

Commit

Permalink
show(::String): elide long strings (close #40724)
Browse files Browse the repository at this point in the history
  • Loading branch information
StefanKarpinski committed May 6, 2021
1 parent f806df6 commit 8dd4e1b
Showing 1 changed file with 35 additions and 1 deletion.
36 changes: 35 additions & 1 deletion base/strings/io.jl
Original file line number Diff line number Diff line change
Expand Up @@ -188,7 +188,41 @@ string(a::Symbol) = String(a)
# write uses an encoding determined by `s` (UTF-8 for `String`)
print(io::IO, s::AbstractString) = for c in s; print(io, c); end
write(io::IO, s::AbstractString) = (len = 0; for c in s; len += Int(write(io, c))::Int; end; len)
show(io::IO, s::AbstractString) = print_quoted(io, s)

# show string elided if more than `limit` characters
function show(
io :: IO,
str :: AbstractString;
limit :: Integer = 5 * max(20, displaysize(io)[2]), # five lines
)
# early out for short strings
len = ncodeunits(str)
len  limit - 2 && # quotes
return print_quoted(io, str)

# these don't depend on string data
units = codeunit(str) == UInt8 ? "bytes" : "code units"
skip_text(skip) = "$skip $units"
chars = limit - length(skip_text("")) - 4 # quotes

# figure out how many characters to print in elided case
chars -= d = ndigits(len - chars) # first adjustment
chars += d - ndigits(len - chars) # second if needed

# find head & tail, avoiding O(length(str)) computation
head = nextind(str, 0, (chars + 1) ÷ 2)
tail = prevind(str, len + 1, chars ÷ 2)

# decide whether to elide or not
if limit - chars  tail - head
skip = skip_text(tail - head - 1)
print_quoted(io, SubString(str, 1, head))
print(io, skip) # TODO: bold styled
print_quoted(io, SubString(str, tail))
else
print_quoted(io, str)
end
end

# optimized methods to avoid iterating over chars
write(io::IO, s::Union{String,SubString{String}}) =
Expand Down

0 comments on commit 8dd4e1b

Please sign in to comment.