" Mapping for Vim help of the word under cursor.
nnoremap K :help <C-r><C-w><CR>

" Set custom fold expression
setlocal foldmethod=expr
setlocal foldexpr=VimFold(v:lnum)

" Custom fold expresson folds control flow keywords and fold markers
function! VimFold(lnum)
  let l:line = getline(a:lnum)

  if l:line =~ '^python\s\+<<\s\+\w\+\s*$'
    let b:vim_python_end = substitute(l:line, '^python\s\+<<\s\+\(\w\+\)\s*$', '\1', '')
    return 'a1'
  endif

  if exists('b:vim_python_end')
    if l:line =~ '^'.b:vim_python_end.'\s*$'
      unlet b:vim_python_end
      return 's1'
    endif
  else
    if l:line =~ '^\s*fun\(c\(tion\)\=\)\=!\=\s\+.*#\=\w*(.*).*$'
        \ || l:line =~ '^\s*if\s*.*$'
        \ || l:line =~ '^\s*el\(se\)\=\s*.*$'
        \ || l:line =~ '^\s*elseif\=\s*.*$'
        \ || l:line =~ '^\s*wh\(ile\)\=\s*.*$'
        \ || l:line =~ '^\s*for\s*.*$'
        \ || l:line =~ '^\s*try\s*$'
        \ || l:line =~ '^\s*cat\(ch\)\=\s*.*$'
        \ || l:line =~ '^\s*fina\(lly\)\=\s*$'
      return '>'.string((indent(a:lnum) / &shiftwidth) + 1)
    elseif l:line =~ '^\s*endfun\(c\(tion\)\=\)\=\s*$'
        \ || l:line =~ '^\s*en\(dif\)\=\s*$'
        \ || l:line =~ '^\s*endw\(hile\)\=\s*$'
        \ || l:line =~ '^\s*endfor\=\s*$'
        \ || l:line =~ '^\s*endt\(ry\)\=\s*$'
      return '<'.string((indent(a:lnum) / &shiftwidth) + 1)
    endif
  endif

  return '='
endfunction