Skip to content

Instantly share code, notes, and snippets.

@kawarimidoll
Last active December 3, 2022 11:13
Show Gist options
  • Save kawarimidoll/496cb16b40af33e8d84daff6dde8a16f to your computer and use it in GitHub Desktop.
Save kawarimidoll/496cb16b40af33e8d84daff6dde8a16f to your computer and use it in GitHub Desktop.
Define keymappings for multiple modes at once in Vim or Neovim

multiple_keymap.vim

Define keymappings for multiple modes at once in Vim or Neovim.

Installation

Put codes in your configuration file, such as .vimrc or init.vim.

Usage

:Keymap {modes} {arguments-of-map-commands}

" define mappings at once
Keymap nx s <Cmd>DoSomething<CR>
" same as ↓
" nnoremap s <Cmd>DoSomething<CR>
" xnoremap s <Cmd>DoSomething<CR>

" all options like '<expr>' are available
Keymap no <script> <expr> s SomeCondition() ? '<Plug>(do-something)' : 's'
" same as ↓
" nnoremap <script> <expr> s SomeCondition() ? '<Plug>(do-something)' : 's'
" onoremap <script> <expr> s SomeCondition() ? '<Plug>(do-something)' : 's'

" show existing mappings
Keymap nx
" same as ↓
" nmap
" xmap

" show existing mappings about specific key
Keymap nx s
" same as ↓
" nmap s
" xmap s

Motivation

Neovim already has nvim_set_keymap() and vim.keymap.set(), but I wanted more simple command.

function! s:keymap(force_map, modes, ...) abort
let arg = join(a:000, ' ')
let cmd = a:force_map ? 'map' : 'noremap'
for mode in split(a:modes, '.\zs')
if index(split('nvsxoilct', '.\zs'), mode) < 0
echoerr 'Invalid mode is detected: ' .. mode
continue
endif
execute mode .. cmd arg
endfor
endfunction
command! -nargs=+ -bang Keymap call s:keymap(<bang>0, <f-args>)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment