I am using NeoVim, and I automatically define an abbreviation for the string W every time the commandline mode starts.

However, it seems that commandline mode includes the search modes as well.

I do not want the abbreviation to exist in the search modes, so I want to delete it if it exists.

I tried maparg('W','c',v:true) and mapcheck('W','c',v:true) to check if W is defined as an abbreviation in command mode, but they do not seem to work. (here 'W' is the abbreviation I want to check for, 'c' stands for commandline mode, and true is for abbreviation -- I think)

What am I doing wrong? Thanks

EDIT: adding my code for defining the abbreviation for W:

autocmd CmdlineEnter,CmdwinEnter :,q: cnoreabbrev W w !git add %

(this allows me to add the file to the local git repo by typing :W<CR>

  • 1
    Can you include the definition of the W abbreviation? mapcheck('W', 'c', v:true) works for me and returns whatever if I define it as cabbrev W whatever, not sure what's the case with your particular setting...
    – filbranden
    Aug 24 at 23:53
  • Don't use auto-command here. It's pointless.
    – Matt
    Aug 25 at 6:12

If you use a mapping instead of an abbreviation then this'll do...

:cnoremap <expr> W (getcmdtype() == ':') ? "foobar" : "W"

From command-line you get W resolving to whatever you specify where I have "foobar". OTOH, if you enter W during a search then getcmdtype() returns / or ? and the ternary expression evaluates to false and inserts "W".

And, per @filbranden, the same thing works with cabbrev...

:cabbrev <expr> W (getcmdtype() == ':') ? "foobar" : "W"

You may know this already but, FYI, there's a difference between these: the cmap version will insert the mapped string immediately after you enter the W while cabbrev requires entering an additional, non-keyword character immediately afterward (per normal abbreviation mechanics).

  • 2
    Using <expr> also works with a cabbrev...
    – filbranden
    Aug 24 at 23:57
  • @filbranden Thanks. Updated.
    – B Layer
    Aug 25 at 0:07
  • Wow -- Thanks guys! What does <expr> do?
    – Benben
    Aug 25 at 0:09
  • 2
    Treats the right-hand side as a Vim expression to be evaluated rather than a literal string.
    – B Layer
    Aug 25 at 0:09
  • 2
    Thanks all! This answer made it unnecessary to remove the definition everytime I enter search mode.
    – Benben
    Aug 25 at 0:14

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.