VIM: Save a file as a different filename, but keep :w as the current filename

17,958

Solution 1

Yes. If you use :w someOtherFile.c it will write to that file, but stay editing someFile.c.

My answer also used to link to a Stack Overflow answer that provided link to useful VIM command cheat sheets. That answer has since been deleted as being off-topic for that site.

Here is the original contents of that answer, written by user David


Here are some that I have bookmarked from back in the day:

The Linux commands cheatsheets:

Solution 2

You could put an autocommand like this one in your ~/.vimrc:

:au! BufWrite * execute "w" expand("%") . strftime(".%y%m%d.%H%M%S")

That will save a copy of the current file in a file of the same name but with the current date and time appended every time you save the original file. That's probably more than you want, but you could modify it to work with only certain file types, or put your copies in a special directory, etc.

I used to use something similar to make backups of certain often-changed configuration files.

Share:
17,958

Related videos on Youtube

dotancohen
Author by

dotancohen

Updated on September 18, 2022

Comments

  • dotancohen
    dotancohen over 1 year

    As a sort of poor-mans version control, I need to save a file someFile.c as someOtherFile.c, but I want :w to continue saving as someFile.c. Is this possible?

    The environment is Windows XP SP3, but I do have a Cygwin install here so I could do it in the Cygwin instance if that helps.

    Thanks.

  • dotancohen
    dotancohen about 12 years
    I cannot believe that this was the default behaviour! Thank you!
  • paddy
    paddy about 12 years
    No worries... Neither did I, actually. I just did vim test, entered 'hello', then :w test2, appended 'world' and :w again. The file 'test' contained "hello world", and 'test2' contained "hello".
  • dotancohen
    dotancohen about 12 years
    I am trying to map this to <F2> but it is not saving. Might you see the issue? noremap <F2> execute "w" expand("%") . strftime(".%y%m%d.%H%M%S") Thanks for this wonderful tip.
  • garyjohn
    garyjohn about 12 years
    I didn't try your mapping, but my first thought is that you're missing a : in front of execute. The command argument to an autocommand is an ex command so no : is necessary, but the rhs of a mapping is just a sequence of keys, so a : is necessary to begin ex mode from normal mode. Also, you'll probably want to end your mapping with <CR> so that you don't have to press Enter each time you use it. You're welcome.