3

I use git to share my vimrc across multiple machines. But now I have some commands which I only want on one machine. Namely, this line: au! redhat BufReadPost (derived from this very helpful answer! https://unix.stackexchange.com/questions/59486/disable-vi-from-going-to-the-last-visited-line-upon-file-opening)

Is there a way to load this line only for my linux machine? Or maybe put into a second vimrc file which only exists/loads on linux? Or maybe another solution, so that I can keep using version control for the rest of my files but let this one command apply just for this one machine?

1 Answer 1

5

You can surround the config/code in question with a conditional based on an environment variable.

If you're using Bash environments a good candidate is envvar HOSTNAME which will probably be unique (in a personal context, at least). In other environments there is usually a way to get this same information (e.g. output of the *nix command hostname or envvar COMPUTERNAME on Windows). If you have a heterogeneous mix of machines then the best approach is probably to use the Vim function hostname() which provides a platform agnostic means of getting the information.1

For simplicity, we'll pretend we're all in on Bash. :) For the example you mentioned we'd just need to add something like...

 if $HOSTNAME == "foo"
     au! redhat BufReadPost ...
 endif

Of course, we can also extend this to multiple hosts and/or have default settings...

 if $HOSTNAME == "foo"
     " this config
 elseif $HOSTNAME == "bar"
     " that config
 else
     " default config
 endif

Before you set it up check availability with :echo $HOSTNAME.

If you want to look for alternatives you could run :!printenv or :!env or whatever your system's equivalent command is. In the unlikely event that you can't find an existing envvar that will work then make something up! Choose a variable name not currently in use and on the machine(s) you want to isolate put (assuming Bash, again) export MYSPECIALVAR=uniquevalue in your .profile, .bash_profile, .bashrc or whatever makes the most sense for your environment.

1Thanks to @Achilleas for spurring me to expand/improve this section.

3
  • 2
    Works perfectly, thank you so much! Jul 3, 2019 at 19:47
  • 2
    The availability of $HOSTNAME in the environment depends on the system or shell and maybe even other factors. It looks like vim has a hostname() function for this, which should be more universally available.
    – Achilleas
    May 17, 2020 at 16:03
  • @Achilleas A good point. Note updated answer. Cheers.
    – B Layer
    May 17, 2020 at 17:45

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.