19

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.

WestCoastProjects
  • 58,982
  • 91
  • 316
  • 560

2 Answers2

29

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.

mkrieger1
  • 19,194
  • 5
  • 54
  • 65
6

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.

user295691
  • 7,108
  • 1
  • 26
  • 35