What is the best way to add a custom key mapping i

2019-05-11 23:58发布

I know you can add custom keymappings to vim with imap in the .vimrc file. My question is, if one is to create additional custom operators, motions, commands and map them to keys, what is the best way to add them in so they don't conflict with existing bindings?

An analogy, in emacs, a lot of custom key commands are added via the C-c sequence. To be more technical, are there unbound keys in vim that allow for user customization? In other words, is there a free keyspace available to users?

标签: vim vi hotkeys
1条回答
女痞
2楼-- · 2019-05-12 00:52

:imapEnter will show a list of your insert mode mappings.

My question is, if one is to create additional custom operators, motions, commands and map them to keys, what is the best way to add them in so they don't conflict with existing bindings?

In my opinion the best way is creating custom command, they start with uppercase, native ones with lowercase.


Additionally, you can use a <leader> I use , some use \.

e.g. :let mapleader = ","

then, you can use the leader to combine it with other keys, like ,p to call a command, native or custom, see below:

:map <leader>p :MyCustomCommand<CR>

A custom motion example. Delete the third word after the cursor.

nnoremap <leader>x :normal 2wdw<CR>


Several commands can be used to create new, remove and list the mappings, here is a list of working modes, from :help map-overview

                                        Normal  Visual+Select  Operator-pending ~
:map   :noremap   :unmap   :mapclear     yes      yes                yes
:nmap  :nnoremap  :nunmap  :nmapclear    yes       -                  -
:vmap  :vnoremap  :vunmap  :vmapclear     -       yes                 -
:omap  :onoremap  :ounmap  :omapclear     -        -                 yes

further info :help map


Here's an example function, converted to a custom command

function! MoveLastLines(f)
  exe '$-9,$w ' . a:f    "write last ten lines to the passed filename
  $-9,$d                 "delete last ten lines
endfunction

command! -nargs=1 -range MoveTo :call MoveLastLines(<f-args>)

Now, both lines below are equivalent

  • :call MoveLastLines('newFile.txt')
  • :MoveTo newFile.txt
查看更多
登录 后发表回答