Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to recover and delete swap file automatically on E325?

Tags:

vim

Vim has a nice feature to recover files if previous session was crashed . Vim show something like this when it happened:

Swap file "~/Desktop/.file.txt.swp" already exists!
[O]pen Read-Only, (E)dit anyway, (R)ecover, (Q)uit, (A)bort:

In most cases I recover the file, and its irritating to press r every time vim crashes.

  1. I want recovery to be automatic.

The problem not ends here. Even if the file has been recovered the swap file still exists there, and that prompt appears again.

  1. I want swap file to be deleted if recovery occurs.

So each time in such situation, I want to recover silently and delete the swap file.

like image 853
Santosh Kumar Avatar asked Aug 25 '13 08:08

Santosh Kumar


People also ask

Can I delete SWP files?

If you are -certain- that the file on the disk is the correct one and you don't need the "autosaved" information in the swapfile, you can simply type "D" to delete the swapfile. The message will go away and you can continue working.

Where are swap files stored?

By default, the swap file is created in the same location as the virtual machine's configuration file, which may either be on a VMFS datastore, a vSAN datastore or a VMware vSphere® Virtual VolumesTM datastore. On a vSAN datastore or a vVols datastore, the swap file is created as a separate vSAN or vVols object.

What is SWP file in Vim?

An SWP file is a swap file created by the Vi text editor or one of its variants, such as Vim (Vi iMproved) and gVim. It stores the recovery version of a file being edited in the program. SWP files also serve as lock files, so no other Vi editing session can concurrently write to the currently-open file.


2 Answers

I haven't tried it, but I think you could use this:

augroup AutomaticSwapRecoveryAndDelete
    autocmd!
    autocmd SwapExists * :let v:swapchoice = 'r' | let b:swapname = v:swapname 
    autocmd BufWinEnter * :if exists("b:swapname") | call delete(b:swapname) | unlet b:swapname | endif
augroup end

See :h v:swapchoice, :h v:swapcommand, :h v:swapname and :h SwapExists

like image 93
elmart Avatar answered Nov 15 '22 09:11

elmart


Since the swap file should exist as long as your are editing the buffer, I woud rather replace the second autocommand of elmart's answer by

augroup AutomaticSwapRecoveryAndDelete
    autocmd!
    autocmd SwapExists * :let v:swapchoice = 'r' | let b:swapname = v:swapname 
    autocmd VimLeave * :if exists("b:swapname") | call delete(b:swapname) | endif
augroup end

Moreover, that would allow you to use :DiffOrig, when in doubt about the difference between swap and original.

like image 43
Hugo Raguet Avatar answered Nov 15 '22 09:11

Hugo Raguet