Skip to content
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.

Commit a9a47b9

Browse files
committedMay 6, 2021
show(::String): elide long strings (close #40724)
1 parent f806df6 commit a9a47b9

File tree

1 file changed

+32
-1
lines changed

1 file changed

+32
-1
lines changed
 

‎base/strings/io.jl

+32-1
Original file line numberDiff line numberDiff line change
@@ -188,7 +188,38 @@ string(a::Symbol) = String(a)
188188
# write uses an encoding determined by `s` (UTF-8 for `String`)
189189
print(io::IO, s::AbstractString) = for c in s; print(io, c); end
190190
write(io::IO, s::AbstractString) = (len = 0; for c in s; len += Int(write(io, c))::Int; end; len)
191-
show(io::IO, s::AbstractString) = print_quoted(io, s)
191+
192+
# show string elided if more than `lines` lines long
193+
function show(
194+
io :: IO,
195+
str :: AbstractString;
196+
lines :: Integer = 5,
197+
width :: Integer = displaysize(io)[2],
198+
)
199+
# these don't depend on string data
200+
skip_text(skip) = "$skip $units"
201+
units = codeunit(str) == UInt8 ? "bytes" : "code units"
202+
chars = lines*width - length(skip_text("")) - 4
203+
204+
# figure out how many characters to print in elided case
205+
len = ncodeunits(str)
206+
chars -= digs = ndigits(len - chars) # first adjustment
207+
chars += digs -= ndigits(len - chars) # second if needed
208+
209+
# find head & tail, avoiding O(length(str)) computation
210+
head = nextind(str, 0, (chars + 1) ÷ 2)
211+
tail = prevind(str, len + 1, chars ÷ 2)
212+
213+
# decide whether to elide or not
214+
if lines*width - chars  tail - head
215+
skip = skip_text(tail - head - 1)
216+
print_quoted(io, SubString(str, 1, head))
217+
print(io, skip) # TODO: bold styled
218+
print_quoted(io, SubString(str, tail))
219+
else
220+
print_quoted(io, str)
221+
end
222+
end
192223

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

0 commit comments

Comments
 (0)
Please sign in to comment.