Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to save a file with a new name in VIM while switching to that new buffer (and closing the original)

Tags:

vim

The title about covers it: I know that

w! newFileName

will write to newFileName while continuing to edit the original file.

But I want to

  1. write to the newFileName
  2. Open that new newFileName in the current buffer
  3. (Therefore meaning: close the original file without making updates to it)

Thanks.

like image 979
WestCoastProjects Avatar asked Jun 27 '15 19:06

WestCoastProjects


2 Answers

The sav command should do what you want.

Reference:

:sav[eas][!] [++opt] {file}

Save the current buffer under the name {file} and set the filename of the current buffer to {file}.

The previous name is used for the alternate file name. The [!] is needed to overwrite an existing file. When 'filetype' is empty filetype detection is done with the new name, before the file is written. When the write was successful 'readonly' is reset.

like image 128
mkrieger1 Avatar answered Sep 21 '22 14:09

mkrieger1


Another way of accomplishing this is to :w newName and then CTRL-^ (which is the same as CTRL-6) to switch to the new name.

When you :w to a new name, it sets that as the "alternate" file name, and CTRL-^ switches that to primary. See :help alternate for more information on this. Also useful is the :f newName which just renames the buffer (saving the old name as the alternate) without saving anything.

I like this a little better than the :saveas command because it doesn't introduce a new command, only a new shortcut, which is occasionally useful in other contexts as well. It's always surprising to me that switching to the new name is not the default behavior of :w newName whenever I encounter it; it's hard for me to think of a use case where the existing behavior would be preferable.

like image 44
user295691 Avatar answered Sep 18 '22 14:09

user295691