Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

vim folds open up when giving an unmatched opening brace/parenthesis

Tags:

vim

folding

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?

like image 699
r.v Avatar asked Jan 07 '11 22:01

r.v


People also ask

How does folding work in Vim?

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.

How do you toggle fold in Vim?

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.

How do I collapse a line in Vim?

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 .

How do I save a fold in Vim?

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.


1 Answers

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
like image 52
eckes Avatar answered Nov 02 '22 04:11

eckes