8000 Fix newline depth with multiple braces · ruby/irb@7dc8af0 · GitHub
[go: up one dir, main page]

Skip to content

Commit 7dc8af0

Browse files
committed
Fix newline depth with multiple braces
This commit fixes the check_newline_depth_difference method to multiple open braces on one line into account. Before this change we were subtracting from the depth in check_newline_depth_difference on every open brace. This is the right thing to do if the opening and closing brace are on the same line. For example in a method definition we have an opening and closing parentheses we want to add 1 to our depth, and then remove it. ``` def foo() end ``` However this isn't the correct behavior when the brace spans multiple lines. If a brace spans multiple lines we don't want to subtract from check_newline_depth_difference and we want to treat the braces the same way as we do `end` and allow check_corresponding_token_depth to pop the correct depth. Example of bad behavior: ``` def foo() [ ] puts 'bar' end ``` Example of desired behavior: ``` def foo() [ ] puts 'bar' end ```
1 parent 304145a commit 7dc8af0

File tree

2 files changed

+19
-1
lines changed

2 files changed

+19
-1
lines changed

lib/irb/ruby-lex.rb

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -317,11 +317,13 @@ def process_nesting_level
317317

318318
def check_newline_depth_difference
319319
depth_difference = 0
320+
open_brace_on_line = 0
320321
@tokens.each_with_index do |t, index|
321322
case t[1]
322323
when :on_ignored_nl, :on_nl, :on_comment
323324
if index != (@tokens.size - 1)
324325
depth_difference = 0
326+
open_brace_on_line = 0
325327
end
326328
next
327329
when :on_sp
@@ -330,8 +332,9 @@ def check_newline_depth_difference
330332
case t[1]
331333
when :on_lbracket, :on_lbrace, :on_lparen
332334
depth_difference += 1
335+
open_brace_on_line += 1
333336
when :on_rbracket, :on_rbrace, :on_rparen
334-
depth_difference -= 1
337+
depth_difference -= 1 if open_brace_on_line > 0
335338
when :on_kw
336339
next if index > 0 and @tokens[index - 1][3].allbits?(Ripper::EXPR_FNAME)
337340
case t[2]

test/irb/test_ruby_lex.rb

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -70,7 +70,22 @@ def test_auto_indent
7070
lines = []
7171
input_with_correct_indents.each do |row|
7272
lines << row.content
73+
assert_indenting(lines, row.current_line_spaces, false)
74+
assert_indenting(lines, row.new_line_spaces, true)
75+
end
76+
end
7377

78+
def test_braces_on_thier_own_line
79+
input_with_correct_indents = [
80+
Row.new(%q(if true), nil, 2),
81+
Row.new(%q( [), nil, 4),
82+
Row.new(%q( ]), 2, 2),
83+
Row.new(%q(end), 0, 0),
84+
]
85+
86+
lines = []
87+
input_with_correct_indents.each do |row|
88+
lines << row.content
7489
assert_indenting(lines, row.current_line_spaces, false)
7590
assert_indenting(lines, row.new_line_spaces, true)
7691
end

0 commit comments

Comments
 (0)
0