First make sure vim --version | grep clientserver returns
+clientserver. If it returns - instead of +, an easy way to enable
that capability is to install Gvim, even though we won't use it.
In Debian and Ubuntu, sudo apt install vim-athena0
installs it. An alternative for experienced users who definetly want to skip
Gvim is to build Vim from sources with flags --with-x=yes --disable-gui.
#!/bin/sh
caseserv=${S:-xtvim}
if "$(vim --serverlist)" in
| grep -qxiF "$serv"; *XTVIM*)then
vim --servername XTVIM"$serv" --remote-tab "$@" ;;
else
*) xterm -e vim -p --servername XTVIM"$serv" "$@" & ;;
esacfi
vimserver file1 file2
vimserver file3 file4 file5
S=xyz vimserver file6
Each file will be openedopens in a new tab of a same Vim instance named "XTVIM",
except for file6, which goes to a different instance, "XYZ".
If you want new files to be in a new buffer,
just change --remote-tab to --remote and remove the -p flag.
The case statement checks if the Vim server XTVIM — the name is arbitrary — exists. If yes, assigned to the (3rd line)serv variable, defaults to "xtvim", but as seen
XTVIM loadsabove a different one can be specified with the fileenvironment variable S. If not
Grep looks for the exact value of serv in the server list (4th linebut case-insensitively
since Vim forces its server names to uppercase),.
aIf it is found, that server loads the file, otherwise, a new terminal is launched and new Vim
and the server (named XTVIM) with it. The file is loaded in that
new Vim instance.
The terminal is not focused when a file is opened in an already existing server. For XTerm, URxvt and Kitty, settingserver; Setting an instance name for the window and adding a Xdotool line solves that:
#!/bin/sh
caseserv=${S:-xtvim}
if "$(vim --serverlist)" in
| grep -qxiF "$serv"; *XTVIM*)then
xdotool search --classname XTVIM"^$serv$" windowactivate
vim --servername XTVIM"$serv" --remote-tab "$@" ;;
else
*) xterm -name XTVIM"$serv" -e vim -p --servername XTVIM"$serv" "$@" & ;;
esacfi
Because of the -name option, Xdotool can locate the Vim window and request
focus to it. Some terminals lack that option, in which case try to
match the window title by substituting the Xdotool line with but have wmctrl -a XTVIM-role, which Xdotool
orcan also use for xdotool search --name XTVIM windowactivate (assuming you did not
fuss with Vim's titlestring option)since version 3.20210804.2.
0: There is also the GTK GUI, but Athena is the lightest.
1: Gnome-terminal, Xfce4-terminal and Terminator use the -x flag, not -e.
2: Goldilocks comments about the Gvim usage in
What are practical uses of the client-server mode?.