2 of 5
Simplified the solution function

(I actually figured it out by myself but as I didn't find an answer on this site I thought that could be usefull to create a self-answered question)

To do so it is possible to create the following function and put it in the .vimrc:

function! ToggleTestAutoGroup()
    " Switch the toggle variable
    let g:TestAutoGroupToggle = !get(g:, 'TestAutoGroupToggle', 1)

    " Reset group
    augroup TestAutoGroup
        autocmd!
    augroup END

    " Enable if toggled on
    if g:TestAutoGroupToggle
        augroup TestAutoGroup
            autocmd! BufEnter   * echom "BufEnter " . bufnr("%")
            autocmd! BufLeave   * echom "BufLeave " . bufnr("%")
            autocmd! TabEnter   * echom "TabEnter " . tabpagenr()
            autocmd! TabLeave   * echom "TabLeave " . tabpagenr()
        augroup END
    endif
endfunction

The function creates a variable used to determine if the group was previously enabled or not.

The group is always reset, and if it wasn't enabled, it is populated with the wanted autocommands.

A relevant documentation is here

Finally it is possible to create the folowing mapping:

nnoremap <F4> :call ToggleTestAutoGroup()<CR>

to use F4 to call the function.

statox
  • 44.1k
  • 15
  • 117
  • 198