I often come across the situation where I have lots of lines folded and I am writing, say a new block of code, above these folds. As soon as I type a '{', all the folds below open up. Even though it is legitimate that vim does this, it is irritating to close all the folds again. Is there a way around this situation?
Vim uses the same movement commands to define folds. Folding also works in visual mode. If you enter visual mode using v or V , then select a few lines of text using the movement keys, and type zf , Vim will create a fold comprising those lines. Another option is to specify a range in command mode.
With the following in your vimrc, you can toggle folds open/closed by pressing F9. In addition, if you have :set foldmethod=manual , you can visually select some lines, then press F9 to create a fold. Here is an alternative procedure: In normal mode, press Space to toggle the current fold open/closed.
You can press V to go into Visual Line mode, select the lines to be folded, then z f to make a manual fold. You'll need to :set foldmethod=manual if it isn't already set. You can open the fold with z o , or delete the fold with z d .
The problem is that when you close Vim, your artfully folded code returns to its unfolded state. The solution is quite simple - when you are ready to save your folds run the :mkview command. This will save your folds in the current buffer to your viewdir ( :h viewdir ) depending on your environment.
I had the same problem and could solve it using this vimtip.
Little excerpt of the tip description:
If you are using any sort of automatic folding method, be it marker, syntax, or expression folding, inserting text that starts a fold will automatically open all folds beneath the insertion point. This can be very annoying. To get around this, you can temporarily switch to a manual fold method when entering insert mode, and switch back when leaving it.
The trick is to set the foldmethod
to manual
when editing starts:
autocmd InsertEnter * if !exists('w:last_fdm') | let w:last_fdm=&foldmethod | setlocal foldmethod=manual | endif
When you're done with editing, reset foldmethod
to it's original value:
autocmd InsertLeave,WinLeave * if exists('w:last_fdm') | let &l:foldmethod=w:last_fdm | unlet w:last_fdm | endif
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With