Skip to content

Commit

Permalink
Improve String#pretty_print output by splitting newline (#5750)
Browse files Browse the repository at this point in the history
Like Ruby's `pp`, String#pretty_print splits its content by newline and
shows each lines with joining `+` operator.

I believe this improves readability against large multiline string on `p`.
  • Loading branch information
makenowjust authored and RX14 committed Mar 9, 2018
1 parent 5a189cb commit 4ef9167
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 1 deletion.
7 changes: 7 additions & 0 deletions spec/std/string_spec.cr
Expand Up @@ -1494,6 +1494,13 @@ describe "String" do
"\u{1f48e}".inspect_unquoted.should eq %(\u{1F48E})
end

it "does pretty_inspect" do
"a".pretty_inspect.should eq(%("a"))
"hello\nworld".pretty_inspect.should eq(%("hello\\n" + "world"))
"hello\nworld".pretty_inspect(width: 9).should eq(%("hello\\n" +\n"world"))
"hello\nworld\n".pretty_inspect(width: 9).should eq(%("hello\\n" +\n"world\\n"))
end

it "does *" do
str = "foo" * 10
str.bytesize.should eq(30)
Expand Down
18 changes: 17 additions & 1 deletion src/string.cr
Expand Up @@ -3831,7 +3831,23 @@ class String

# Pretty prints `self` into the given printer.
def pretty_print(pp : PrettyPrint) : Nil
pp.text(inspect)
printed_bytesize = 0
pp.group do
split('\n') do |part|
printed_bytesize += part.bytesize
if printed_bytesize != bytesize
printed_bytesize += 1 # == "\n".bytesize
pp.text("\"")
pp.text(part.inspect_unquoted)
pp.text("\\n\"")
break if printed_bytesize == bytesize
pp.text(" +")
pp.breakable
else
pp.text(part.inspect)
end
end
end
end

# Returns a representation of `self` using character escapes for special characters and wrapped in quotes.
Expand Down

0 comments on commit 4ef9167

Please sign in to comment.