The purpose of this blog is to happily share my learning and ideas to help people, who actively seek solutions for the day-to-day problems faced.

Recent Posts

Tips - vim '.swp' file automatic swap recovery and delete

vim editor is the most widely used editor among linux users and it really helps to read and write into a file. 

Though vim is powerful and useful, I often get annoyed by the '.swp' file recovery and delete messages due to any network glitch or if the previous session got crashed.

During such scenarios, vim provides a nice feature to make note of the unsaved data into a swap file and keep it hidden and share it to us when we edit the actual file. Here we are provided with two options either to recover the unsaved content or ignore it (delete the .swp file) and continue to write our very own data.

Swap file "~/rc/.sample.py.swp" already exists!
[O]pen Read-Only, (E)dit anyway, (R)ecover, (Q)uit, (A)bort:
In most cases I used to recover the file but its irritating to press r every time. Though the file as been recovered the swap file still exists there and that same prompt appears again.

Tips - vim
So each time in such situation, Instead of we manually selecting the recovery options and saving the unsaved data, I found a workaround to automate the same using vim command (added to .vimrc file)
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

After adding the AutomaticSwapRecoveryAndDelete command next time when '.swp' file is created and when we open the actual file we can type,

:w - to recover the file and save it
:q! - to ignore the swap content and keep writing the older one

Hope this saves your valuable time, will see you next in other useful tips post. 

Reference:

No comments