When I use the command :e filename to open a file and this file is already opened by another vim instance, I get a prompt asking me if I want to open the file in read-only mode, edit anyway, recover, exit or abort.

When I try :silent! e filename what happens is that vim seems to have hanged. But it is indeed asking me what to do with the swapfile, just I can't see it because I told it to be silent.

Is there any command where I can tell it to open the file in read-only mode if the file can't be opened in write mode and without requiring user interaction? (I want to integrate this into a macro to jump/open files).


If you have vim >= 7 (I think) you can use autocmd with an event SwapExists. There you can do all from very simple things to very complicated.
Here is a simple example to put in your ~/.vimrc:

autocmd SwapExists * let v:swapchoice = "o"

If a swap file exists, this event will be triggered. The autocmd above will simply open the file in read only mode.
If v:swapchoice gets a value in an autocmd it will not prompt you what you want to do. The values you can use is listed here v:swapchoice.
For a very advanced autocmd see here: editexisting.vim
The script there can already be on your server from the installation of vim, search for editexisting.vim.


I have a script in my .vimrc which does exactly this. However it does so for all files opened which has a swp file. Not sure if you always want this behavior. Maybe you can tweak it to fit your needs in the macro you are writing.

To open ro if a swp file is present, put this in your .vimrc:

func CheckSwap()
  if v:statusmsg =~ '\.sw[^p]$'
    set ro

if &swf
  set shm+=A
  au BufReadPre * call CheckSwap()

I got this script from here, there is a more advanced example there as well which might be of interest.


The command view in RHEL and ubuntu opens vim in readonly mode, though you can override the readonly mode by using :w!.

  • Yes, I would like to preserve the writeability if possible, though. Unfortunately reading through the swap-file help it seems that detecting if a swap file exists is not reliable either. – Grzegorz Adam Hankiewicz Jan 22 '13 at 18:06

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.