Here is another interesting and useful feature of vim. We can start vim as a server which will send and receive commands and execute them.
The first use-case of the above feature is to give vim a one-instance functionality, just like Firefox. We click on a link anywhere in the system, it doesn’t open a new Firefox window. Just creates a new tab in the existing Firefox instance. To achieve similar functionality in vim, we need to start vim as a server -
[command_promot]$ vim –servername SAMPLESERVER file1.txt
Done. Now you can go to any shell in the system, and to open a file in the existing vim instance, just do -
[command_prompt]$ vim –servername SAMPLESERVER –remote-tab file2.txt file3.txt
The above command will open file2.txt and file3.txt as new tabs in the existing vim instance running :).
If the above typing is very long and cumbersome, you can just set a couple of aliases [one for command to start the server and another for opening the file in existing server]. You can also choose any server-name and you can also run multiple servers in your system [A possible use-case when you're working on multiple projects and run one vim instance for every project and while opening the file you decide which vim instance to use for opening this file]. The servers are recognized by the –servername option which you give while starting the server.
The server has additional functionality in which it can receive a command and execute it. This can be quite handy when you use multiple computers and login to a server machine for working. Example – You were using machine A and had a vim instance running. You left this machine and started using machine B and would like to continue editing where you left on machine A. If your vim instance was started as a server (assuming server name to be SAMPLESERVER), then from machine B you can just login to machine A and execute the following command -
[command_prompt_on_machine_A]$ vim –servername SAMPLESERVER –remote-send ‘<Esc>:mksession ~/sessionFile.vim<CR>:wqa<CR>’
Essentially this command will send the existing server running by name SAMPLESERVER, to store all the progress in ~/sessionFile.vim, save all files and exit :). [If you dont know what mksession does, please read my earlier post about sessions in vim]. Now to continue with the same settings, you start your vim instance by picking up the settings from the session file -
[command_prompt_on_machine_A]$ vim –servername SAMPLESERVER -S ~/sessionFile.vim
Done. This will allow you to edit files in one single environment, even if you work on different machines :). Happy Vimming.
PS: vim needs to be compiled with +clientserver in order for you to be able to use this feature.