0

I'm trying to optimize this solution I came up with.


The code bellow do works fine. So feel free to use it as a valid solution to this question.

nnoremap <F2> :call ToogleFold()<CR>

function! ToogleFold()
     if &foldlevel >= 20
         "normal! zM<CR> (folds all)
         set foldlevel=0
     else
         "normal! zR<CR> (unfolds everything)
         set foldlevel=20
     endif
 endfunction

But I believe we can do it all in a single line without the use of functions.

I've tried some strange combinations here, attempting to get it right. So, to inspire your creativity, here the wrong codes:

nnoremap <F2> @=(foldlevel('.')?'zM':'zR')<CR>
nnoremap <F2> :exe 'if &foldlevel>=20' \ <ESC>zM \ else <ESC>zR'
nnoremap <F2> :exe &foldlevel>=20? <ESC>zM : <ESC>zR
nnoremap <F2> :exe '&foldlevel>=20?' <ESC>zM : <ESC>zR'

In the and, what I'm trying to achieve is the use of zM and zR in normal mode depending on the value of a setting variable foldlevel.

I believe this solution may be very useful to other similar cases (other variables)

6

So you want to toggle between all lines folded and no lines folded.

Does this mapping do what you want?

:nnoremap <expr> <f2> &foldlevel ? 'zM' :'zR'
  • It kind'a does! :) But I still need to test it better, because the foldlevel isn't toggling from 0 to 20 and back again. Let me see what happens in a set foldmethod=manual. I think that won't matter. – Dr Beco Jul 9 '17 at 22:54
  • Dandy! Work as a charm. Two somewhat unrelated questions that will help me in my script and don't deserve a full question: how can you negate the condition? Just !&foldlevel? will do? And how to compare with 20? Just &foldlevel >= 20?. Thanks! Accepted answer +1. – Dr Beco Jul 9 '17 at 23:58
  • @DrBeco Yes, that should do it. – Christian Brabandt Jul 10 '17 at 9:51

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.