Question

1) I have in my .vimrc a fold expr (cf. the third example under the :help fold-expr section) which makes a fold out of paragraphs separated by blank lines :

set foldmethod=expr
set foldexpr=getline(v:lnum)=~'^\\s*$'&&getline(v:lnum+1)=~'\\S'?'<1':1

Most of my files are files with paragraphs (to begin with my .vimrc)

2) But I have two or three text files which are simply lists with no paragraphs and I would like to be able to fold everything except for matches to my search. I found in Vim Wikia (Tip 282) the following "Simple Folding" (at the bottom of the Tip's page) which I would like to implement :

:set foldexpr=getline(v:lnum)!~@/
:nnoremap <F8> :set foldmethod=expr<CR><Bar>zM

How can I have both of them peacefully coexist in my .vimrc ?

  • Is setlocal (for the second foldexpr) the solution ? Tried, failed…
  • Is it possible to have a fold expression (the second one) apply only to two files (file1.txt, file2.txt) ?
  • Is it possible to merge the 2 foldexpr in one ?

Thanks for your help

Was it helpful?

Solution

Option foldexpr is local to window, so:

  • :set will establish both global and local values. Global value will be used as a default for subsequent windows where local value is not specified.
  • :setlocal will determine local value only.

It's not clear to me what merging the two expressions would mean, but of course you can create a fold function containing all the complicated logic you want.

What is definitely easy is to set different values for foldexpr depending on the file (or file type). Use an autocommand for that.

So, the whole thing could be, in your .vimrc:

" Default: for all files
set foldmethod=expr
set foldexpr=getline(v:lnum)=~'^\\s*$'&&getline(v:lnum+1)=~'\\S'?'<1':1
nnoremap <F8> :setlocal foldmethod=expr<CR><Bar>zM

" Only for specific files
augroup NonDefaultFoldMethod
    autocmd!
    autocmd BufNewFile,BufRead file1.txt,file2.txt setlocal foldexpr=getline(v:lnum)!~@/
augroup end

The augroup/autocmd! idiom is there just to avoid duplicating autocommands if you source .vimrc repeatedly. It's best practice when establishing autocommands.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top