JORDAN.YELLOZ.me

Problem: I always had trouble maintaining coherence when editing things with vim, especially when I have the urge to look at a new file instantly. Over the months and years, I learned to use the buffer- (and tab-) switching commands to get back to my old work after I’m done looking at an unrelated file. When I’m trying to work on an actual project, I would often like to type stuff in one terminal and have it open the designated files in an existing vim in some other terminal window (whether screen, tmux, or terminator).

Solution: While vim has a server functionality, its command-line options are inconvenient and don’t behave the way I want. Luckily, I decided to make my own wrapper script to get it going the way I want.

This is what I had in mind:

  • If there’s a running server, use it for all the mentioned files.

  • If there are no running servers, start one in the current terminal.

  • If there are no specified files, always edit a new blank file in whatever vim is supposed to run.

A corollary to those three statements should be:

  • Always edit the specified file(s) in a shared vim.

I put some thought into those concepts and learned how to use vim’s server options in order to achieve the desired behavior. Here’s what came out:

#!/bin/bash

# You can put a custom name in here per project.
servername=VIM

switches=( )
files=( )
servers=( )

for arg in "${@}"; do
    if [[ $arg == "-R" ]] ; then
        switches+=( "$arg" )
    else
        files+=( "$arg" )
    fi
done

servers=( $(vim --serverlist | grep -i "$servername" ) )

command="vim ${switches[@]} --servername $servername"

if [[ ${#files[@]} -gt 0 ]]; then
    command="${command} --remote-silent ${files[@]}"
else
    if [[ ${#servers[@]} -gt 0 ]]; then
        command="${command} --remote-send '<C-\><C-N>:enew<CR>'"
    fi
fi

eval "exec $command"

Basically, it re-arranges the command-line options so that common options are placed correctly and there’s a special case when there are no existing servers and another when no files are specified. All you have to do is alias vim="the name of the script file" or make a function. I don’t think the -R switch even works in cases where you re-use an existing server, though, which is unfortunate because it’s one of my favorite ways of opening vim. Either way, I think it might make things easier for me.

Posted on

Revisions: