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 a9a47b9
Showing 1 changed file with 32 additions and 1 deletion.
33 changes: 32 additions & 1 deletion base/strings/io.jl
Original file line number Diff line number Diff line change
Expand Up @@ -188,7 +188,38 @@ 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 `lines` lines long
function show(
io :: IO,
str :: AbstractString;
lines :: Integer = 5,
width :: Integer = displaysize(io)[2],
)
# these don't depend on string data
skip_text(skip) = "$skip $units"
units = codeunit(str) == UInt8 ? "bytes" : "code units"
chars = lines*width - length(skip_text("")) - 4

# figure out how many characters to print in elided case
len = ncodeunits(str)
chars -= digs = ndigits(len - chars) # first adjustment
chars += digs -= 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 lines*width - 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 a9a47b9

Please sign in to comment.