1 " Vim Plugin: Edit the file with an existing Vim if possible
2 " Maintainer: Bram Moolenaar
3 " Last Change: 2006 Apr 30
5 " This is a plugin, drop it in your (Unix) ~/.vim/plugin or (Win32)
6 " $VIM/vimfiles/plugin directory. Or make a symbolic link, so that you
7 " automatically use the latest version.
9 " This plugin serves two purposes:
10 " 1. On startup, if we were invoked with one file name argument and the file
11 " is not modified then try to find another Vim instance that is editing
12 " this file. If there is one then bring it to the foreground and exit.
13 " 2. When a file is edited and a swap file exists for it, try finding that
14 " other Vim and bring it to the foreground. Requires Vim 7, because it
15 " uses the SwapExists autocommand event.
17 " Function that finds the Vim instance that is editing "filename" and brings
18 " it to the foreground.
19 func s:EditElsewhere(filename)
20 let fname_esc = substitute(a:filename, "'", "''", "g")
22 let servers = serverlist()
24 " Get next server name in "servername"; remove it from "servers".
25 let i = match(servers, "\n")
27 let servername = servers
30 let servername = strpart(servers, 0, i)
31 let servers = strpart(servers, i + 1)
35 if servername ==? v:servername
39 " Check if this server is editing our file.
40 if remote_expr(servername, "bufloaded('" . fname_esc . "')")
41 " Yes, bring it to the foreground.
43 call remote_foreground(servername)
45 call remote_expr(servername, "foreground()")
47 if remote_expr(servername, "exists('*EditExisting')")
48 " Make sure the file is visible in a window (not hidden).
49 " If v:swapcommand exists and is set, send it to the server.
50 if exists("v:swapcommand")
51 let c = substitute(v:swapcommand, "'", "''", "g")
52 call remote_expr(servername, "EditExisting('" . fname_esc . "', '" . c . "')")
54 call remote_expr(servername, "EditExisting('" . fname_esc . "', '')")
58 if !(has('vim_starting') && has('gui_running') && has('gui_win32'))
59 " Tell the user what is happening. Not when the GUI is starting
60 " though, it would result in a message box.
61 echomsg "File is being edited by " . servername
70 " When the plugin is loaded and there is one file name argument: Find another
71 " Vim server that is editing this file right now.
72 if argc() == 1 && !&modified
73 if s:EditElsewhere(expand("%:p")) == 'q'
78 " Setup for handling the situation that an existing swap file is found.
80 au! SwapExists * let v:swapchoice = s:EditElsewhere(expand("<afile>:p"))
82 " Without SwapExists we don't do anything for ":edit" commands
85 " Function used on the server to make the file visible and possibly execute a
87 func! EditExisting(fname, command)
88 let n = bufwinnr(a:fname)
92 exe "split " . escape(a:fname, ' #%"|')
96 exe "normal " . a:command