Here is a snippet to add in .vimrc
. It deletes all the swap files that are
associated to the current file buffer and reset swap extension.
function! DeleteFileSwaps()
write
let l:output = ''
redir => l:output
silent exec ':sw'
redir END
let l:current_swap_file = substitute(l:output, '\n', '', '')
let l:base = substitute(l:current_swap_file, '\v\.\w+$', '', '')
let l:swap_files = split(glob(l:base.'\.s*'))
" delete all except the current swap file
for l:swap_file in l:swap_files
if !empty(glob(l:swap_file)) && l:swap_file != l:current_swap_file
call delete(l:swap_file)
echo "swap file removed: ".l:swap_file
endif
endfor
" Reset swap file extension to `.swp`.
set swf! | set swf!
echo "Reset swap file extension for file: ".expand('%')
endfunction
command! DeleteFileSwaps :call DeleteFileSwaps()
Once encounter with the predicament, one can execute :DeleteFileSwaps
This is great if combine with :windo
or :tabdo
commands.
:tabdo DeleteFileSwaps
Further details: A file can have more than 1 swap file. The reason because
the swap file, with extension of .swp
, still exist and vim
will keep creating
new ones because of it. To find out if .swp
exist:
- With the target file open in vim, execute
:sw
to get current swap file.
- Check the directory that the current swap file is contained in.
- Then check if directory contains a swap file with the name of the open file
and has an extension of
.swp
.
The snippet above follows the same process, but remove all swap files.
Hope this helps.
See here https://vi.stackexchange.com/questions/13518/force-prompt-for-whether-to-delete-a-swap-file?newreg=20989544783642b4b37f610b9b0656cf "The "Delete it" option isn't displayed if the Vim process is still running" and note the comment re TMUX sessions i.e. be sure you don't have Vim still running (also, GNU screen) in the background somewhere, see here https://vi.stackexchange.com/questions/13518/force-prompt-for-whether-to-delete-a-swap-file?newreg=20989544783642b4b37f610b9b0656cf#comment38464_13524
– zenaan – 2019-10-01T00:50:38.343