0

I know how to create normal and command mappings, but I am trying to make a command that toggles between two states, (a) create 3 mappings and (b) reset them using unmap. How can I do this in my vimrc config?

1

You can use this:

let s:mappingsState=1

command! TM call ToggleMappings()

function! ToggleMappings()
    if s:mappingsState
        nnoremap <F1> :echo "mapping 1"<CR>
        " Or any mapping you want to create
    else
        unmap <F1>
        " Or any key you want to unmap
    endif

    let s:mappingsState = !s:mappingsState
endfunction

This create a variable which will keep track of the state of the mappings, a function which maps or unmaps the keys depending on this state and a command :TM which calls the function.

  • 1
    Would also recommend using map expressions, e.g. nnoremap <expr> <f1> s:state ? "keys" : "original". See :h :map-expression – Peter Rincker Mar 15 '18 at 14:30
0

A long, long, time ago, I've published a plugin aimed at toggling the state of various things (vim settings, mappings, abbreviations...).

AFAIK it still works, but the code is old and quite cumbersome by vim7 standards -- yeah, vim 8 is out, and vim 8.1 not that far away.

To use the (badly named) Trigger.vim plugin,

  1. install first my vim library plugin it depends upon, then drop Trigger.vim into your ~/.vim/plugin/ directory.
  2. then, the easier way consist in putting all your mappings in a function in a dedicated file ~/.vim/plugin/after/mymappings.vim for instance, and register the toggling with something like:

    " to put in plugin/mymappings.vim, 
    " expecting the mappings are defined in the function FRabbrInit()
    call Trigger_Function('<Plug>(do-toggle-fr-abbreviations)', 'FRabbrInit', expand('<sfile>:p'), 0, 0 )
    
    nmap <Plug>(toggle-fr-abbreviations) <Plug>(do-toggle-fr-abbreviations)
    if !hasmapto('<Plug>(toggle-fr-abbreviations)', 'n')
        nmap <silent> <unique> <leader>tfa <Plug>(toggle-fr-abbreviations)
    endif
    

See my plugin/fr-abbr.vim plugin for a complete (and very old-school) example.

Someday I should move these functions into an autoload plugin and simplify a few things.

  • 1
    Hey thanks for your response. I'll keep that in mind, but for now I will use the above answer due to its simplicity. – jihupona Mar 16 '18 at 13:47
  • The first answer is indeed simple and it should be preferred at first. My answer becomes interesting the day we're tired to keep in sync dozens of mappings and abbreviation to define and undefine. – Luc Hermitte Mar 16 '18 at 14:00

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.