2

I often write the active Vim buffer with :w, then reload the buffer with :e to reset the undo/redo history. I do this so often, I've updated my .vimrc file with a command mapping for :we, to do both in one step:

" Reset undo/redo buffer on reload
set undoreload=0

" Write and clear undo/redo buffer
cnoremap we w\|e

However, this mapping is still executed if I enter we in the middle of the command line; for example, :s/answer/42/ is expanded to :s/answ|er/42/. Is it possible to map we only if it appears at the start of the command?

1 Answers1

2

Here is a good place to use abbreviations. From :h abbreviations

2. Abbreviations            *abbreviations* *Abbreviations*

Abbreviations are used in Insert mode, Replace mode and Command-line mode.
If you enter a word that is an abbreviation, it is replaced with the word it
stands for.  This can be used to save typing for often used long words.  And
you can use it to automatically correct obvious spelling errors.
Examples:

    :iab ms Microsoft
    :iab tihs this

The convenient thing about abbreviations instead of mappings is that they will only be triggered if the entire word is your abbreviation.

I would recommend running:

:cnoreabbrev we w\|e

I have tested this, and I can confirm that the substitution:

:s/answer/42

is still typable without being expanded to :s/answ|er/42. Be warned though, this approach isn't entirely foolproof! You can still run into issues sometimes. For example, typing

:let foo = "we"

is expanded to

:let foo = "w|e"
DJMcMayhem
  • 221
  • 1
  • 3
  • 16