Skip to content

Instantly share code, notes, and snippets.

@oppara
Forked from kawarimidoll/README.md
Created January 17, 2022 01:12
Show Gist options
  • Save oppara/b445bd10c557fa8679f5da1bdbf22328 to your computer and use it in GitHub Desktop.
Save oppara/b445bd10c557fa8679f5da1bdbf22328 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

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

" call 'map' instead of 'noremap' when '<Plug>' is detected
Keymap nx s <Plug>(do-something)
" same as ↓
" nmap s <Plug>(do-something)
" xmap s <Plug>(do-something)

" 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(modes, ...) abort
let arg = join(a:000, ' ')
let cmd = arg !~? '<Plug>' ? 'noremap' : 'map'
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=+ Keymap call <SID>keymap(<f-args>)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment