18

Say I'm editing file foo. I want to copy/write what I have in the buffer to bar and change the buffer to be editing bar instead of foo. I can achieve this with:

:w bar
:e bar

But that has a few problems

  1. If bar is actually /usr/local/share/long/path/to/bar, I really don't want to type that in twice, even with tab completion.
  2. It reloads the file, potentially messing with the settings/folds/etc. I had for that buffer.
  3. The working directory is left the same.

1 is the biggest problem I'd like a solution to address; 2 would be really helpful, 3 is more of a "nice to have."

Is there a cleaner way to do this?

Martin Tournoij
  • 62,054
  • 25
  • 192
  • 271
Kevin
  • 621
  • 6
  • 11

3 Answers3

14

Here's a relatively simple solution:

:saveas bar

This solves problems #1 and #2. It doesn't address problem #3, however.

Note that this still leaves the old file open in another buffer. For example, :w foo<cr>:saveas bar<cr>:ls<cr> will list two buffers, foo and bar.

Doorknob
  • 15,237
  • 3
  • 48
  • 70
  • Beat me by twelve seconds! – wchargin Feb 21 '15 at 00:22
  • Indeed, saveas is what I was looking for. I don't suppose there's an option to have it open in a new window, is there? – Kevin Feb 21 '15 at 00:31
  • @Kevin By "window," do you mean split or tab? – Doorknob Feb 21 '15 at 00:32
  • Split, preferably vertical (or an option for both) – Kevin Feb 21 '15 at 00:33
  • @Kevin Not that I'm aware of, but you could always use, for example, <C-w><C-s>:saveas bar<cr>. (This could be all in one ex command if you want to make a mapping or something: :wincmd s|saveas bar.) – Doorknob Feb 21 '15 at 00:36
  • 1
    @Kevin :vs (with no argument) will split the window, having the same file in both buffers. You can then choose one of the buffers and use :saveas bar.txt, it will leave the 2nd buffer intact. – yo' Feb 21 '15 at 01:00
4

If you are working on a file that is not in the current working directory, and you want to save it under a new name in that directory, you can use the following:

execute 'saveas' expand('%:h') . "/new-file-name"

The execute command allows you to use an argument to saveas that is not a literal string. expand('%:h') gets the relative path of the current file. The rest of the statement concatenates the new file name.

Swoogan
  • 141
  • 3
2

Write the file as usual: :w bar and press Ctrl+^ (or Ctrl+6) to alternate the file.

For splits (:ba/:vert ba), check: How to convert all windows into horizontal, vertical or tab splits?

See: :help ctrl-6.

kenorb
  • 18,433
  • 18
  • 72
  • 134