Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

vim

macvim

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?

like image 555
colorfulgrayscale Avatar asked Nov 07 '10 00:11

colorfulgrayscale


People also ask

How do I close a buffer in Vim?

Assuming the default backslash leader key, you can also press \bd to close (delete) the buffer in the current window (same as :Bclose ).

How do I close the current file in Vim?

To save a file in Vim and exit, press Esc > Shift + ZZ. To exit Vim without saving, press Esc > Shift + ZX.


2 Answers

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.

like image 188
ib. Avatar answered Oct 23 '22 10:10

ib.


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
like image 40
Andrew Keeton Avatar answered Oct 23 '22 12:10

Andrew Keeton