3

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)

2 Answers 2

11

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'
3
  • 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.
    – DrBeco
    Jul 9, 2017 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.
    – DrBeco
    Jul 9, 2017 at 23:58
  • @DrBeco Yes, that should do it. Jul 10, 2017 at 9:51
0

I wrote a similar function in Lua for those using Neovim:

local key = vim.keymap.set
local silent = { noremap = true, silent = true }

-- Toggle all folds
key('n', "<Leader><Tab>",
    function()
        local get_opt = vim.api.nvim_win_get_option
        local set_opt = vim.api.nvim_win_set_option

        if get_opt(0, "foldlevel") >= 20 then
            set_opt(0, "foldlevel", 0)
        else
            set_opt(0, "foldlevel", 20)
        end
    end,
silent)
1
  • Thanks. May be useful to let it here for reference
    – DrBeco
    Oct 27, 2022 at 0:47

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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