How to match a key in command line mode, but not in search mode

I want to display the key in VIM in command line mode, but not in search mode (with a leader /), as shown below:

  • Q map on q
  • Map W to w

Sometimes I entered the wrong command in VIM, for example, :Qand :W, and I want these incorrect commands to be correct.

If I can match Qwith Qand Wwith W, I can make the wrong commands correct.

I tried cmap Q qand cmap W w, but it will also affect the search mode, i.e. /Queryon /Query(in fact you cannot enter the top Q).

And I also tried cabbrev Q q, and this will also affect the search mode.

So, is there any other team that can meet my requirements?

Thank.

+4
source share
2 answers

There are several ways to do this, and it is not so simple.

With commandyou need to take care of the attributes:

command! -nargs=* -complete=file -range=% -bang -bar W w
command! -bang -bar Q q

C cabbrevtraps are described in the wiki , so you need to do this as follows:

cnoreabbrev W <C-r>=(getcmdtype()==':' && getcmdpos()==1 ? 'w' : 'W')<CR>

I have a function for this purpose:

function! s:CAbbrev(from, to)
    execute 'cnoreabbrev ' . a:from . ' <C-r>=(getcmdtype()==#'':'' && getcmdpos()==1 ? ' . string(a:to) . ' : ' . string(a:from) . ')<CR>'
endfunction

cmapYou need a qualifier with you <expr>, and you need more or less the same precautions as for cabbrev:

cnoremap <nowait> <expr> W getcmdtype() ==# ':' && getcmdpos() == 1 ? 'w' : 'W'

The safest way is probably cabbrev.

+3
source

In this case, you can define a user command because it starts in uppercase.

:command! Q q
:command! W w
0
source

All Articles