Skip to content

Commit 2a7f8fd

Browse files
authored
Fix indentation of "else" in nested "if" (#59)
Fixes #56.
1 parent 404201e commit 2a7f8fd

2 files changed

Lines changed: 28 additions & 13 deletions

File tree

indent/python.vim

Lines changed: 20 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -145,20 +145,26 @@ endfunction
145145
" Find possible indent(s) of the block starter that matches the current line.
146146
function! s:find_start_of_block(lnum, types, multiple)
147147
let r = []
148+
let types = copy(a:types)
148149
let re = '\V\^\s\*\('.join(a:types, '\|').'\)\>'
149150
let lnum = a:lnum
150151
let last_indent = indent(lnum) + 1
151152
while lnum > 0 && last_indent > 0
152153
let indent = indent(lnum)
153154
if indent < last_indent
154-
if getline(lnum) =~# re
155-
if !a:multiple
156-
return [indent]
155+
for type in types
156+
let re = '\v^\s*'.type.'>'
157+
if getline(lnum) =~# re
158+
if !a:multiple
159+
return [indent]
160+
endif
161+
if index(r, indent) == -1
162+
let r += [indent]
163+
endif
164+
" Remove any handled type, e.g. 'if'.
165+
call remove(types, index(types, type))
157166
endif
158-
if !len(r) || index(r, indent) == -1
159-
let r += [indent]
160-
endif
161-
endif
167+
endfor
162168
let last_indent = indent(lnum)
163169
endif
164170
let lnum = prevnonblank(lnum - 1)
@@ -239,14 +245,15 @@ function! s:indent_like_block(lnum)
239245
if len(indents) == 1
240246
return indents[0]
241247
endif
248+
242249
" Multiple valid indents, e.g. for 'else' with both try and if.
243250
let indent = indent(a:lnum)
244-
for possible_indent in indents
245-
if indent == possible_indent
246-
return indent
247-
endif
248-
endfor
249-
return -2
251+
if index(indents, indent) != -1
252+
" The indent is valid, keep it.
253+
return indent
254+
endif
255+
" Fallback to the first/nearest one.
256+
return indents[0]
250257
endfor
251258
endfor
252259
return -2

spec/indent/indent_spec.rb

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -361,6 +361,14 @@
361361
end
362362
end
363363

364+
describe "when an else is used inside of a nested if" do
365+
before { vim.feedkeys 'iif foo:\<CR>\<TAB>if bar:\<CR>\<TAB>\<TAB>pass\<CR>' }
366+
it "indents an else to the inner if" do
367+
vim.feedkeys 'else:'
368+
indent.should == shiftwidth * 2
369+
end
370+
end
371+
364372
describe "when jedi-vim call signatures are used" do
365373
before { vim.command 'syn match jediFunction "JEDI_CALL_SIGNATURE" keepend extend' }
366374

0 commit comments

Comments
 (0)