Less intrusive swap file warning

2 Points

Lifepillar Lifepillar

6 years ago

Annoyed by the long E325: ATTENTION warning message that pops up every time Vim finds a swap file? To the point that you have turned off swap files and risk losing data on crash? Tsk tsk. Vim allows you to override the prompt very easily—see below.


The file parameter is not used in the snippet below, but it is there for the sake of completeness, in case you want to modify the snippet.

The function prints the number of swap files associated to the file you are trying to open. Keep in mind that glob() honors 'wildignore': if you have a *.swp pattern in 'wildignore', you should adjust the count accordingly.

If you press Enter at the prompt, the original Vim warning appears.

The prompt uses two lines. To avoid the Press ENTER or type command to continue message, set cmdheight to 2 or greater, or modify the prompt message to fit in one line.

fun! SwapPrompt(file)
  let l:n = len(split(glob(fnamemodify(v:swapname, ":r").".*"), "\n"))
  echohl WarningMsg
  echon 'A swap file exists: ' . fnamemodify(v:swapname, ":t")
    \ . ' (' . l:n . ' swap file(s) found)'
  echohl None
  echon "\n". 'read-(o)nly (e)dit (r)ecover (d)elete (q)uit (a)bort (ENTER for details) '
  let v:swapchoice = nr2char(getchar())
  echo "\r"

autocmd SwapExists * call SwapPrompt(expand("<afile>"))