VIM: Save a file as a different filename, but keep :w as the current filename
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.
Related videos on Youtube
dotancohen
Updated on September 18, 2022Comments
-
dotancohen over 1 year
As a sort of poor-mans version control, I need to save a file
someFile.c
assomeOtherFile.c
, but I want:w
to continue saving assomeFile.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.
-
Ciro Santilli Путлер Капут 六四事 almost 10 yearsPossible cross site duplicate of: stackoverflow.com/questions/4980168/…
-
-
dotancohen about 12 yearsI cannot believe that this was the default behaviour! Thank you!
-
paddy about 12 yearsNo 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 about 12 yearsI 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 about 12 yearsI didn't try your mapping, but my first thought is that you're missing a
:
in front ofexecute
. 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.