gvim "swap file .blah.swp already exists" and xdotool

Powered by Drupal
Submitted by raf on Sat, 03/06/2010 - 19:51

When editing multiple files I regular get the error Swap file ".blah.swp" already exists when I try to run gvim on an already opened file. Instead of starting a new instance of gvim, I would prefer if the existing gvim was activated.

xdotool to the rescue!

xdotool is a command I had never heard of until I researched this problem. It seems to be very powerful. For example, you can use it to search all the open windows by name and it will return the windowid. And then you can activate that window:

$ xdotool search --title xterm
$ xdotool windowactivate 102348456

Putting it all together, it is easy to write a script that search for the gvim window that has the file open, and activate it:

test $# -ne 1 && exec gvim "$@"
file=`readlink -f "$1" | sed -e "s+$HOME+~+"`
dir=`dirname "$file"`
file=`basename "$file"`
wid=`xdotool search --title "$file.*\($dir\) - GVIM"`
test -z "$wid" && exec gvim "$@"
xdotool windowactivate $wid

And then I made an alias from gvim to that script.