Skip to content

Commit

Permalink
indent: handle consecutive linebreaks
Browse files Browse the repository at this point in the history
  • Loading branch information
bcgraham committed May 2, 2020
1 parent 9d9ae4a commit 4f2d067
Show file tree
Hide file tree
Showing 2 changed files with 42 additions and 0 deletions.
12 changes: 12 additions & 0 deletions lib/pry/indent.rb
Expand Up @@ -160,6 +160,10 @@ def indent(input)
before.times { prefix.sub! SPACES, '' }
new_prefix = prefix + SPACES * after

if !end_with_newline?(output) && already_indented?(output, prefix)
prefix = "\n" + prefix
end

line = prefix + line.lstrip unless previously_in_string

output += line
Expand Down Expand Up @@ -276,6 +280,14 @@ def in_string?
!open_delimiters.empty?
end

def already_indented?(output, prefix)
!output.lines.last.nil? && output.lines.last.to_s.start_with?(prefix)
end

def end_with_newline?(output)
output.lines.last.to_s.end_with?("\n")
end

# Given a string of Ruby code, use CodeRay to export the tokens.
#
# @param [String] string The Ruby to lex
Expand Down
30 changes: 30 additions & 0 deletions spec/indent_spec.rb
Expand Up @@ -102,6 +102,36 @@ def number
expect(@indent.indent(input)).to eq output
end

it 'should properly indent nested code with consecutive linebreaks' do
input = <<TXT.strip
class C
def foo
:foo
end
def bar
:bar
end
end
TXT

# rubocop:disable Layout/TrailingWhitespace
output = <<TXT.strip
class C
def foo
:foo
end
def bar
:bar
end
end
TXT
# rubocop:enable Layout/TrailingWhitespace

expect(@indent.indent(input).inspect).to eq output.inspect
end

it 'should indent statements such as if, else, etc' do
input = <<TXT.strip
if a == 10
Expand Down

0 comments on commit 4f2d067

Please sign in to comment.