sponsor Vim development Vim logo Vim Book Ad

intermediate Tip #108: Toggle a fold with a single keystroke

 tip karma   Rating 90/41, Viewed by 5286 

created:   September 6, 2001 2:51      complexity:   intermediate
author:   Max Ischenko      as of Vim:   6.0

When viewing/editing a folded file, it is often needed to inspect/close some fold.
To speed up these operation use the following (put in your $HOME/.vimrc):

" Toggle fold state between closed and opened.
"
" If there is no fold at current line, just moves forward.
" If it is present, reverse it's state.
fun! ToggleFold()
if foldlevel('.') == 0
normal! l
else
if foldclosed('.') < 0
. foldclose
else
. foldopen
endif
endif
" Clear status line
echo
endfun

" Map this function to Space key.
noremap <space> :call ToggleFold()<CR>


See :help folding for more information about folding.

 rate this tip  Life Changing Helpful Unfulfilling 

<< C/C++: convert enum to string table | jump between files >>

Additional Notes

[email protected], September 22, 2001 0:10
isn't this what 'za' does? would it be better to just map space to za?
[email protected], December 16, 2001 14:42
The problem with just maping space to za is that it wont function as space if it isnt on the folded line.
[email protected], May 21, 2002 13:18
This command breaks the behavior of <Space> outside folds: it moves the
cursor 3 columns instead of 1, at least for me. Fix: I use

normal! "

instead of

normal! l
Anonymous, July 7, 2002 9:16
Check and make sure you didn't paste in any extra spaces at the end of the "normal" line. It was moving too far for me, too, but now moves one space since I deleted the space after the "l" which I had pasted in there.
David Fishburn, May 31, 2003 18:25

This line:
noremap <space> :call ToggleFold()<CR>

Should be changed to:
nnoremap <space> :call ToggleFold()<CR>

Without doing that, you cannot use the <space> to represent characters, for example:
4c<space>

Would mean change the next 4 characters.
[email protected], June 2, 2003 23:09
There is more shorter way to do the same:

nnoremap  <silent>  <space> :exe 'silent! normal! za'.(foldlevel('.')?'':'l')<cr>

Explanation:
- 'normal! za' toggles folds.
- 'silent!' allows to avoid error message when current line doesn't
delong to fold.
- (foldlevel('.')?'':'l') adds forward moving only if current line
doesn't delong to fold.
[email protected], August 23, 2004 13:33
Fantastic,  ppa-nsu.
Works like a charm. Thanks!
If you have questions or remarks about this site, visit the vimonline development pages. Please use this site responsibly.
Questions about Vim should go to [email protected] after searching the archive. Help Bram help Uganda.
    stats
Sponsored by Web Concept Group Inc. SourceForge.net Logo