diff --git a/autoload/ale/fix/registry.vim b/autoload/ale/fix/registry.vim index b85c5d76..59b8997a 100644 --- a/autoload/ale/fix/registry.vim +++ b/autoload/ale/fix/registry.vim @@ -2,6 +2,11 @@ " Description: A registry of functions for fixing things. let s:default_registry = { +\ 'add_blank_lines_for_python_control_statements': { +\ 'function': 'ale#handlers#python#AddLinesBeforeControlStatements', +\ 'suggested_filetypes': ['python'], +\ 'description': 'Add blank lines before control statements.', +\ }, \ 'autopep8': { \ 'function': 'ale#handlers#python#AutoPEP8', \ 'suggested_filetypes': ['python'], diff --git a/autoload/ale/handlers/python.vim b/autoload/ale/handlers/python.vim index 5e9ddecd..952df8f4 100644 --- a/autoload/ale/handlers/python.vim +++ b/autoload/ale/handlers/python.vim @@ -36,6 +36,26 @@ function! ale#handlers#python#HandlePEP8Format(buffer, lines) abort return l:output endfunction +" Add blank lines before control statements. +function! ale#handlers#python#AddLinesBeforeControlStatements(buffer, lines) abort + let l:new_lines = [] + let l:last_indent_size = 0 + + for l:line in a:lines + let l:indent_size = len(matchstr(l:line, '^ *')) + + if l:indent_size <= l:last_indent_size + \&& match(l:line, '\v^ *(return|if|for|while|break|continue)') >= 0 + call add(l:new_lines, '') + endif + + call add(l:new_lines, l:line) + let l:last_indent_size = l:indent_size + endfor + + return l:new_lines +endfunction + function! ale#handlers#python#AutoPEP8(buffer, lines) abort return { \ 'command': 'autopep8 -' diff --git a/test/fixers/test_python_add_blank_lines_fixer.vader b/test/fixers/test_python_add_blank_lines_fixer.vader new file mode 100644 index 00000000..6a3c58da --- /dev/null +++ b/test/fixers/test_python_add_blank_lines_fixer.vader @@ -0,0 +1,85 @@ +Before: + Save g:ale_fixers + +After: + Restore + +Given python(Some Python without blank lines): + def foo(): + return 1 + + + def bar(): + return 1 + return 4 + + + def bar(): + if x: + pass + for l in x: + pass + for l in x: + pass + break + continue + elif x: + pass + while x: + pass + while x: + pass + else: + pass + if x: + pass + elif x: + pass + else: + pass + +Execute(Blank lines should be added appropriately): + let g:ale_fixers = {'python': ['ale#handlers#python#AddLinesBeforeControlStatements']} + ALEFix + +Expect python(Newlines should be added): + def foo(): + return 1 + + + def bar(): + return 1 + + return 4 + + + def bar(): + if x: + pass + + for l in x: + pass + + for l in x: + pass + + break + + continue + elif x: + pass + + while x: + pass + + while x: + pass + else: + pass + + if x: + pass + elif x: + pass + else: + pass