9

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?

ib.
  • 27,830
  • 11
  • 80
  • 100

2 Answers2

13

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.

ib.
  • 27,830
  • 11
  • 80
  • 100
  • 16
    -1. Please, don't use `cnoremap` for that! This will expand q in any command. For example `:set cscopequickfix` will expand to `:set cscopebduickfix`. Use `:cnoreabbrev` instead! See the help for that. – Benoit Nov 07 '10 at 08:49
  • Your first cnoremap won't work. The line tells Vim to remap command mode wq to w, and then close the current buffer - not rebind wq to w|bd. Benoits complaints are also valid, however, you can do :cnoremap wq wbd - this will work as expected. – Sarah Nov 07 '10 at 15:16
  • 4
    Sarah, no. Still `cnoreabbrev` is better because if you want to write your file as `anything ending with wq` the abbreviation will not trigger unless the filename is exactly wq. – Benoit Nov 08 '10 at 12:29
  • 2
    I agree completely, though it still has to be wbd. – Sarah Nov 08 '10 at 16:25
  • 1
    Also, you can emulate `:x` for buffers with `:cnoreabbrev bx upbd `, which will write the buffer only if it's changed, and then close the buffer. – naught101 Mar 02 '12 at 05:23
  • 1
    Problem with `wq` mapping is that it doesnt actually quit, but this is really an issue with concept of the question. – D. Ben Knoble Aug 09 '19 at 21:20
1

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
Andrew Keeton
  • 22,195
  • 6
  • 45
  • 72