Vim - save and close buffer in one command

26

1

I have a bunch of text files in a directory and I know I'll need to edit each one indiviudaly.

I start at the commend line with

vim *.txt

which opens the files as seperate buffers in vim and leaves me looking with at the first one. I edit it - then I use ':w' to save it and ':bd' to close the buffer and move on to the next one.

This ':w:bd' to save and close the buffer feels long to me, and I suspect there's a more vim ninja way of doing it - what's the recommend way to save and close the buffer you are working on in one felt swoop?

Joe

Posted 2013-01-26T12:15:45.813

Reputation: 2 942

My recomended way would be to just move to the :next buffer and write/close everything once your task is finished with :wqa. This supposes that you have :set hidden in your ~/.vimrc. – romainl – 2013-01-26T13:14:45.840

Answers

22

When passing the files to Vim on the command-line, they are not only opened in buffers, but also populate the argument list. Therefore, you can use commands like :next and :first to navigate through them (and :argdo for batch processing, which can be a nifty trick). The command I recommend for your question is :wnext (short form :wn), which :writes the current buffer and then goes to the :next one.

You don't need to explicitly :bdelete a buffer, especially not when you're launching Vim from the command-line with a set of files and then quit it when you're done. (The only exceptions I can think of is unloading a huge file to save system memory, or re-using a single GVIM instance for many different edits.)

However, if you really want this, just define a custom command, e.g.

:command Wd write|bdelete

Ingo Karkat

Posted 2013-01-26T12:15:45.813

Reputation: 19 513

5You've mentioned two methods of achieving what the OP requested, but the second one isn't obvious: :w|bd. – Jonno – 2016-08-15T05:50:54.143

--> This has the advantage of fitting the approach the OP uses, although I'd agree :next makes more sense in some cases. – Jonno – 2016-08-15T05:51:29.020

4

While I agree that you don't have to delete open buffers you aren't currently using, I like to delete them because I have vim-airline's tab line enabled, which shows all open buffers all the time at the top of the window. I have the following in my .vimrc:

nnoremap qq :w\|bd<cr>

qq saves and closes the current buffer, but also messes with the "record macro" functionality of vim (which I'm okay with).

apostl3pol

Posted 2013-01-26T12:15:45.813

Reputation: 141

2The built-in ZZ comes to mind, but that ends up saving and quitting Vim entirely, rather than just deleting the buffer. Lowercase zz might be an interesting alternative mapping, for anyone who finds macros more valuable than centering the view on the current cursor line. – 8bittree – 2016-10-17T20:00:10.310

1I recently changed it to Q, after realizing just how valuable recording in Vim can be. – apostl3pol – 2017-04-13T03:06:47.410