Setting a keyboard shortcut for a vim command

亡梦爱人 提交于 2020-01-01 05:25:08

问题


Say I want <C-*> to provide me the functionality of the:set nohlsearch command. How do I accomplish this? The map command only seems to be able to map a set of keystrokes with another set. How can a key combination be mapped to a command?


回答1:


You'd do it like this:

:nnoremap <C-*> :set nohlsearch<CR>

<C-*> means pressing Ctrl and Shift and 8 (on an English keyboard layout, at least) simultaneously. Unfortunately, that particular combination won't work. Due to the way that the keyboard input is handled internally, this unfortunately isn't generally possible today, even in GVIM. Some key combinations, like Ctrl + non-alphabetic cannot be mapped, and Ctrl + letter vs. Ctrl + Shift + letter cannot be distinguished. (Unless your terminal sends a distinct termcap code for it, which most don't.) In insert or command-line mode, try typing the key combination. If nothing happens / is inserted, you cannot use that key combination. This also applies to <Tab> / <C-I>, <CR> / <C-M> / <Esc> / <C-[> etc. (Only exception is <BS> / <C-H>.) This is a known pain point, and the subject of various discussions on vim_dev and the #vim IRC channel.

Some people (foremost Paul LeoNerd Evans) want to fix that (even for console Vim in terminals that support this), and have floated various proposals.

But as of today, no patches or volunteers have yet come forward, though many have expressed a desire to have this in a future Vim 8 major release.

What you can do is choose another key combination, e.g. one of the function keys:

:nnoremap <F5> :set nohlsearch<CR>



回答2:


As others have already pointed out, all types of keybindings are not possible due to the way the strokes are sent to the terminal. However, to accomplish what you are asking for (:nohlsearch) this code below allows you to toggle the highlighting by pressing space.

set nocompatible

let g:highlighting = 0
function! Highlighting()
  if g:highlighting == 1 && @/ =~ '^\\<'.expand('<cword>').'\\>$'
    let g:highlighting = 0
    return ":silent nohlsearch\<CR>"
  endif
  let @/ = '\<'.expand('<cword>').'\>'
  let g:highlighting = 1
  return ":silent set hlsearch\<CR>"
endfunction
nnoremap <silent> <expr> <Space> Highlighting()



回答3:


You should be able to do so in your .vimrc :

nnoremap <C-*> :set nohlsearch<CR>

though I am not sure is always a supported shortcut.

See another exemple here



来源:https://stackoverflow.com/questions/18916929/setting-a-keyboard-shortcut-for-a-vim-command

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!