Tip 1568 Printable Monobook Previous Next

created 2008 · complexity basic · author Ewfalor · version 7.0

By default, when Vim notices the file for a buffer being edited has been deleted (e.g. after running a shell command), it raises error E221 to warn the user. An additional behaviour desired by some is to also mark the buffer as 'modified' so that it can't be abandoned without providing a bang (!). This isn't foolproof, as the file could still be deleted without Vim noticing, so your best defense is to make sure files you want are not deleted; however this can provide a second line of defense.

To use it, add the following to your vimrc, or create file ~/.vim/plugin/filechanged.vim (Unix) or $HOME/vimfiles/plugin/filechanged.vim (Windows) containing the script below, then restart Vim.

au FileChangedShell * call FCSHandler(expand("<afile>:p"))
function FCSHandler(name)
  let msg = 'File "'.a:name.'"'
  let v:fcs_choice = ''
  if v:fcs_reason == "deleted"
    let msg .= " no longer available - 'modified' set"
    call setbufvar(expand(a:name), '&modified', '1')
    echohl WarningMsg
  elseif v:fcs_reason == "time"
    let msg .= " timestamp changed"
  elseif v:fcs_reason == "mode"
    let msg .= " permissions changed"
  elseif v:fcs_reason == "changed"
    let msg .= " contents changed"
    let v:fcs_choice = "ask"
  elseif v:fcs_reason == "conflict"
    let msg .= " CONFLICT --"
    let msg .= " is modified, but"
    let msg .= " was changed outside Vim"
    let v:fcs_choice = "ask"
    echohl ErrorMsg
  else  " unknown values (future Vim versions?)
    let msg .= " FileChangedShell reason="
    let msg .= v:fcs_reason
    let v:fcs_choice = "ask"
    echohl ErrorMsg
  echomsg msg
  echohl None

You can easily customize this code to take whatever action you desire for the various values of v:fcs_reason, by setting v:fcs_choice (for example, you could reload the buffer if the mode has changed).

Based on discussion on the vim_use mailing list.

References[edit | edit source]

Basis of this tip:

Used in this tip:

See also[edit | edit source]

Comments[edit | edit source]

Community content is available under CC-BY-SA unless otherwise noted.