Saturday, July 24, 2010

Code folding with Vim

I've learned about code folding using Vim.
The command zfa} collapses (folds) a C block using the } symbol as guide.

The following code maps the Spacebar to a function that folds/unfolds the current block (add this to ~/.vimrc), based on this.

"Fold coloring 
hi Folded        ctermfg=white ctermbg=NONE

fun! ToggleFold()
if foldclosed('.') < 0
". foldclose
:execute "normal zfa}<cr>"
. foldopen
" Clear status line

" Map fold/unfold function to Space key.
"nmap <space> zfa}<cr>
"nmap <space> :call ToggleFold()<cr>
noremap <space> :call ToggleFold()<cr>

Here there is a more sophisticated function for folding.

vmap <space> zf

" inspired by Max Ischenko's
function ToggleFold()
   if foldlevel('.') == 0
      " No fold exists at the current line,
      " so create a fold based on braces
      let x = line('.')    " the current line number
      normal 0
      call search("{")
      normal %
      let y = line('.')    " the current line number
      " Create the fold from x to y
      execute x . "," . y . " fold"
      " Delete the fold on the current line
      normal zd

nmap <space> :call ToggleFold()<cr>

No comments:

Post a Comment