Skip to content

Improve String#pretty_print output by splitting newline #5750

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

Merged
merged 1 commit into from
Mar 9, 2018
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
7 changes: 7 additions & 0 deletions spec/std/string_spec.cr
Original file line number Diff line number Diff line change
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
Original file line number Diff line number Diff line change
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