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?
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.
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,
- install first my vim library plugin it depends upon, then drop
then, the easier way consist in putting all your mappings in a function in a dedicated file
~/.vim/plugin/after/mymappings.vimfor 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.