colorfulgrayscale
colorfulgrayscale

Reputation: 353

Is it possible to remap ‘wq’ to save and close the current buffer instead of saving and quitting in Vim?

Vim newbie here.

When I issue the :wq Ex command, I would like to make it save and close just the active buffer, instead of saving it and then quitting from Vim.

Similarly, I would like to make the :q command to be identical to :bd in its effect.

Any suggestions how to implement this behavior?

Upvotes: 9

Views: 4456

Answers (2)

ib.
ib.

Reputation: 29004

Vim allows the user to add key mappings for commands in all modes, including the Command-line mode, so one can define the following mappings (in one’s .vimrc file):

:cnoreabbrev wq w<bar>bd
:cnoreabbrev q bd

These commands instruct Vim to expand the WQ key presses in the command line into w|bd and, similarly, expand Q into bd. See :help key-mapping for more details.

Upvotes: 13

Andrew Keeton
Andrew Keeton

Reputation: 23331

Check out the Sayonara plugin.

I tried the other answer but it was missing a use case. When I close the last buffer, I want it to close Vim, like a regular :q command. :bd will just leave you with a blank window and no buffer.

Here's the mapping, adapted from the other answer:

" Prevent accidental closing of all buffers when doing :wq or :q
cnoreabbrev wq w<bar>Sayonara
cnoreabbrev  q       Sayonara

Upvotes: 1

Related Questions