Bash Snippet: Universal Vim Function (unify Vim, NeoVim, SpaceVim, etc.)

Personally, I like to use SpaceVim+NeoVim for dev work, and vanilla Vim or NeoVim on non-dev machines I manage. This function allows me use all different Vim scenarios with a consistently simple vanilla syntax, while maintaining only a single Bash config across all the systems I use!

As another example, let’s say you have three systems: On system A you use SpaceVim with NeoVim, on system B you use vanilla Vim with a highly customized ~/.vimrc, and system C is a mostly stock machine with Vim freshly installed. As long you you have your this function sourced in (or by) your ~/.bashrc then all of these scenarios will ‘just work’ using just vanilla vim commands like ‘vim /some/file/to/edit’.

Configuration & Usage:

There’s no real ‘usage’ to speak of, just add this to ~/.bashrc (or another file that you will source in ~..bashrc; I like to use ~/.bash_functions). The you just run vim as you normally would!

This is optional, but if you do use SpaceVim, or some other custom config that isn’t in a standard location, then you will want to set VIMRC (line 6) to the appropriate file path, and that’s it as far as configuration!

The Bash Function:

## Handle different Vim binaries & configs in a consistent manner
function vim {
    # You can specify an alternate vimrc file here (e.g. SpaceVim). If this file 
    # doesn't exist then the Vim binary we end up using will just look for it's 
    # config like usual.
    VIMRC=~/src/SpaceVim/vimrc
    #VIMRC='DEFAULT' # this will explicitly disable the custom vimrc

    # Try vim bins in order of preference. The final 'command "$@"' is just so 
    # it will fail with the users original command, rather than some contrived 
    # error response - since there is presumably no 'vim' cmd by that point.
    vim_exec=$(command -v nvim || command -v vim || command "$@")

    # Look for an alternate cfg at $VIMRC
    vim_conf=$(test -r ${VIMRC} && echo -n "-u ${VIMRC}") || echo -n ''

    # Vim assemble!!!
    command ${vim_exec} ${vim_conf} "$@"
}

So yes, the explanation is more complicated than the code, but although its simple it does solve a real problem! I started trying to do something like this with a simple Bash alias, but it was just growing too confounded – I like to keep my ~/.bash_aliases file very simple, to the point that I could import them directly in the Fish shell (which I used to do when I briefly used Fish, and it does work if your Bash aliases are fairly simple). Anyways, I’m getting off track here… It’s just a simple function to solve an annoying problem that wasted my time. I hope someone else finds it useful! :)

I’m certainly not a Bash scripting guru… I’m not even sure I’m a good novice, ha. So if you have any tips / fixes / improvements / optimizations then please do comment and I’ll certainly give credit if I use the suggestions!

Leave a Reply