2012/12/07

Vimの背景色を環境変数で設定する

本記事は Vim Advent Calendar 2012 の7日目です。6日目は いつでもどこでも同じ.vimrcを使う - くりにっき でした。ここでは端末の色設定についての小技を紹介したいと思います。

端末使いは明るい背景色が好み!?

私は ssh 先での作業が多いため、ターミナルエミュレータの設定で接続先ごとに黒背景と白背景を使い分けています。当然 CUI の vim を使うことになるのですが、デフォルトでは明るい背景に合う色(background=light)となっているため、黒背景の端末を使っているときは毎回 :se bg=dark と打ち込んでいます。これがけっこう面倒です。そういえば Linux における ls コマンドのカラー出力のデフォルトも黒背景に優しくないですね。

はじめから設定ファイルに書いておけばよいのですが、共通の .vimrc を使っている場合でホスト名をハードコードして分岐したくないときがあります。え?私だけ?

COLORFGBG環境変数

そのような時は Vim 7 で参照されるようになった COLORFGBG 環境変数を使う事で解決できます。

  • :help version7
    When using an rxvt terminal emulator guess the value of 'background' using the COLORFGBG environment variable. (Ciaran McCreesh)
  • :help 'background'
    For MS-DOS, Windows and OS/2 the default is "dark". For other systems "dark" is used when 'term' is "linux", "screen.linux", "cygwin" or "putty", or $COLORFGBG suggests a dark background. Otherwise the default is "light".
具体的にどのような値を設定すべきかは、ソースコードのコメントに記されています。
  • vim73/src/option.c
    /*
    * Return "dark" or "light" depending on the kind of terminal.
    * This is just guessing! Recognized are:
    * "linux" Linux console
    * "screen.linux" Linux console with screen
    * "cygwin" Cygwin shell
    * "putty" Putty program
    * We also check the COLORFGBG environment variable, which is set by
    * rxvt and derivatives. This variable contains either two or three
    * values separated by semicolons; we want the last value in either
    * case. If this value is 0-6 or 8, our background is dark.
    */
    static char_u *
    term_bg_default()
    {
    #if defined(MSDOS) || defined(OS2) || defined(WIN3264)
    /* DOS console nearly always black */
    return (char_u *)"dark";
    #else
    char_u *p;
    if (STRCMP(T_NAME, "linux") == 0
    || STRCMP(T_NAME, "screen.linux") == 0
    || STRCMP(T_NAME, "cygwin") == 0
    || STRCMP(T_NAME, "putty") == 0
    || ((p = mch_getenv((char_u *)"COLORFGBG")) != NULL
    && (p = vim_strrchr(p, ';')) != NULL
    && ((p[1] >= '0' && p[1] <= '6') || p[1] == '8')
    && p[2] == NUL))
    return (char_u *)"dark";
    return (char_u *)"light";
    #endif
    }
    view raw option.c hosted with ❤ by GitHub

私は黒背景をメインに使っていますのでシェルの設定で COLORFGBG 環境変数の値を 15;0 としています。白背景の端末を使って接続するホストの場合はこの値を 0;15 としています。ローカル端末の場合はターミナルエミュレータによってはプロファイルなどの値が変数で参照できますので、それらが白背景の時に変更しています。

# I like dark background.
export COLORFGBG='15;0'
# But, follow with some predefined light background.
if [[ -n "${(M)ITERM_PROFILE#light}" ]] then
export COLORFGBG='0;15'
elif [[ -n "${(M)COLORTERM#gnome-terminal}" ]] then
export COLORFGBG='0;15'
fi
view raw zshrc hosted with ❤ by GitHub

.vimrc か .zshrc のどちらに設定を書くかというだけですが、環境変数でも背景色を設定できる vim って柔軟でいいなーと思いました。

明日は @kefir_ さんです。楽しみですね。

0 件のコメント:

コメントを投稿