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?

  • Could you use ^ before the w when specifying your command to specify via regex that only at the beginning of a line? 'cnoreman ^we w\|e' – Kyle H Dec 20 '16 at 14:42
  • @KyleH Thanks, but that was the first thing I tried! Unfortunately the LHS of the map command is interpreted literally, not as a regex, so ":^we" expands to "w|e", and ":we" produces "Not an editor command: we". – Huw Walters Dec 29 '16 at 8:00
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"
  • Not ideal, but given Vim's lack of a regex-based mapping command (hard to optimise, as it would have to check a list of regexes on every keystroke) it looks like the best I can do. Thanks for the suggestion. – Huw Walters Dec 29 '16 at 8:22

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.