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)