Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setting a keyboard shortcut for a vim command

Tags:

vim

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?

like image 958
Amal Antony Avatar asked Sep 20 '13 12:09

Amal Antony


2 Answers

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>
like image 70
Ingo Karkat Avatar answered Nov 16 '22 14:11

Ingo Karkat


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()
like image 29
Manne Tallmarken Avatar answered Nov 16 '22 15:11

Manne Tallmarken