How to open a file in VIM in readonly mode if it already has a swapfile

filesswapvim

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).

Best Answer

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.

Related Question