Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems.. It's 100% free, no registration required.

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

share|improve this question

3 Answers 3

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()
  swapname
  if v:statusmsg =~ '\.sw[^p]$'
    set ro
  endif
endfunc

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

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

share|improve this answer

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

share|improve this answer
    
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

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.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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