Improve Python folding behaviour

This commit is contained in:
Kenneth Benzie 2016-09-08 22:10:31 +01:00
parent 3e36a88cef
commit 051edae965
2 changed files with 43 additions and 3 deletions

View File

@ -28,3 +28,46 @@ let python_highlight_all=1
" Mappings " Mappings
nnoremap K :YcmCompleter GetDoc<CR> nnoremap K :YcmCompleter GetDoc<CR>
" Set custom fold expression
setlocal foldmethod=expr
setlocal foldexpr=PythonFold(v:lnum)
" Custom fold function greedyily matches following blank lines
function! PythonFold(lnum)
let l:line = getline(a:lnum)
" Blank lines, comments, and docstrings use previous fold level
if l:line =~ '^\(\s*\|#.*\|"\(""\)\=.*\)$'
return '='
" Keywords beginning indented blocks start a fold
elseif l:line =~ '^\s*class\s\+\w*(\w*)\s*:\s*$'
\ || l:line =~ '^\s*def\s\+\w\+\s*(.*)\s*:\s*$'
\ || l:line =~ '^\s*if\s\+.*:\s*$'
\ || l:line =~ '^\s*elif\s\+.*:\s*$'
\ || l:line =~ '^\s*else\s*:\s*$'
\ || l:line =~ '^\s*for\s\+.*:\s*$'
\ || l:line =~ '^\s*while\s\+.*:\s*$'
\ || l:line =~ '^\s*try\s*:\s*$'
\ || l:line =~ '^\s*except\s*.*:\s*$'
return '>'.string((indent(a:lnum) / &shiftwidth) + 1)
" Opening curly braces, not in a string, add a fold level
elseif l:line =~ '{' && l:line !~ '}' && l:line !~ "'.*{.*'" && l:line !~ '".*{.*"'
return 'a1'
" Closing curly braces, not in a string, substract a fold level
elseif l:line =~ '}' && l:line !~ '{' && l:line !~ "'.*}.*'" && l:line !~ '".*}.*"'
return 's1'
" Opening square braces, not in a string, add a fold level
elseif l:line =~ '[' && l:line !~ ']' && l:line !~ "'.*[.*'" && l:line !~ '".*].*"'
return 'a1'
" Closing square braces, not in a string, substract a fold level
elseif l:line =~ ']' && l:line !~ '[' && l:line !~ "'.*].*'" && l:line !~ '".*[.*"'
return 's1'
" Calculate lines with a lower indent than the previous line
elseif indent(a:lnum) < indent(a:lnum - 1)
return string((indent(a:lnum) / &shiftwidth))
endif
" Finally all unmatched lines use fold level from previous line
return '='
endfunction

3
vimrc
View File

@ -159,9 +159,6 @@ let g:DoxygenToolkit_commentType="C++"
Plug 'suan/vim-instant-markdown' Plug 'suan/vim-instant-markdown'
let g:markdown_fenced_languages=['cpp', 'c', 'cmake', 'sh', 'vim', 'python'] let g:markdown_fenced_languages=['cpp', 'c', 'cmake', 'sh', 'vim', 'python']
" SimplyFold - python folding
Plug 'tmhedberg/SimpylFold'
" syntastic - syntax checker " syntastic - syntax checker
Plug 'scrooloose/syntastic' Plug 'scrooloose/syntastic'
let g:syntastic_always_populate_loc_list = 1 let g:syntastic_always_populate_loc_list = 1