KathleenL
KathleenL

Reputation: 11

Possible to make a backup of original file in vim?

Is it is possible to make a copy of original file before writing the new buffer to the file without having to leave vim and copy it manually?

Upvotes: 1

Views: 1435

Answers (4)

Dev Null
Dev Null

Reputation: 4997

As @Sato Katsura pointed out, it is patchmode:

:set patchmode=.orig

Upvotes: 1

Pylinux
Pylinux

Reputation: 11816

I just simply use:

:!cp % %.backup

Which will create a new file in the same location with .backup appended to it.

Upvotes: 0

Vinícius Souza
Vinícius Souza

Reputation: 41

UPDATE I realized that my solution might be a little complicated for beginners and unnecessary for single files backups, so if you want a simple solution just use:

:!cp % ~/ 

The % register keeps the name of the file and with this extern command you can copy the current file to your home folder or you can change it to any folder you want.

In Windows you can use this to send to a backup folder on C::

:!copy % \backups\ 

You can turn in a shortcut on your .vimrc with something like:

 nnoremap .b  :!cp % ~/

Old Answer:

I had the same need to backup before save the modifications, so I created a Bash and a Batch(for Windows) file that backups all the files that I want and used this conditional statement on .vimrc to choose automatically between the two systems:

if has("win32")
    nnoremap <leader>bc :! C:\C\SCRIPTS\backupWIN.bat<cr>
else
    nnoremap <leader>bc :!bash /home/vini/C/SCRIPTS/backup.sh<cr>
endif

Here the code for the Bash version:

#!/bin/bash

#adds the date to folder(you can change the date format)
now=$(date +"%d_%m_%Y_%H;%M;%S")

mkdir /home/vini/backups/C_BKP/pre_alpha/$now

cp -r /home/vini/C   /home/vini/backups/C_BKP/pre_alpha/$now

echo "saved in: /home/vini/backups/C_BKP/pre_alpha/"$now

Here the code for the Batch file:

set start=%time%

::I didn't managed to make it print the seconds, so I choose to 
::override the same files if I save twice in the same minute  
@echo off
For /f "tokens=1-4 delims=/ " %%a in ('date /t') do (set mydate=%%a-%%b-%%c)
For /f "tokens=1-4 delims=/:" %%a in ('time /t') do (set mytime=%%ah%%bm%%c)


mkdir C:\Users\vini\Desktop\C\C-%mydate%-%mytime%
::careful with xcopy , read the documentation before modify it 
xcopy /E /Y C:\C C:\Users\vini\Desktop\C\C-%mydate%-%mytime%\

You just need to change the name of the directories for match your folders and you are good to go.

Upvotes: 1

Peaceful
Peaceful

Reputation: 5450

How about this? After editing the file, before :wq, you can do:

:!cat myfile.txt > backup.txt

and then save using :wq. The previous content would be stored in backup.txt

Upvotes: 1

Related Questions