「コンソールのカラー出力」の版間の差分

提供: ArchWiki
ナビゲーションに移動 検索に移動
(Pkg/AUR テンプレートの更新)
(→‎アプリケーション: inset == Background ==)
8行目: 8行目:
 
{{Related articles end}}
 
{{Related articles end}}
 
このページでは CLI 出力のカラー化をまとめています。
 
このページでは CLI 出力のカラー化をまとめています。
  +
  +
== Background ==
  +
  +
{{Expansion|Probably a good idea to move the list-color scripts here now.}}
  +
  +
=== Escape sequences ===
  +
  +
The [[Wikipedia:ANSI escape sequence|ANSI escape sequences]] define a way to put additional information into terminal output, and color is part of this "additional information". Throughout the years the range of terminal colors has been vastly expanded, from the initial eight colors to a full 24-bit truecolor.
  +
  +
The basic color encoding provides 8 normal-brightness colors and 8 brighter versions of these colors. Modern terminal emulators, including the Linux console itself, allows you to specify the precise RGB values that the colors translate to. This mode is supported by almost all terminal emulators.
  +
  +
With the advent of 256-color displays came the 256-color escape. The 256 colors are the 16 basic colors, the 216 RGB colors (laid out in a 6x6x6 cube), and 24 levels of greyscale. Except for the first 16 colors, the scheme is usually not customizable as it has a well-defined mapping to RGB. This mode is supported by most terminal emulators. (A minority of emulators use a similar but incompatible encoding with only 88 colors. You are very unlikely to use them in practise, but they will appear in the terminfo database.)
  +
  +
Less commonly supported is the truecolor mode, allowing one to use 16.7 million (2<sup>24</sup>) colors in RGB (each value ranging from 0 to 255).
  +
  +
=== Termcap and terminfo ===
  +
  +
Termcap and terminfo, part of {{Pkg|ncurses}}, are databases that provide information on what escapes a terminal (usually specified by the {{ic|TERM}} env-var) understands. The {{man|1|tput}} and {{man|1|infocmp}} commands can be used to access them from command-line.
   
 
== アプリケーション ==
 
== アプリケーション ==

2021年3月25日 (木) 21:08時点における版

関連記事

このページでは CLI 出力のカラー化をまとめています。

Background

この記事またはセクションは加筆を必要としています。
理由: Probably a good idea to move the list-color scripts here now. (議論: トーク:コンソールのカラー出力#)

Escape sequences

The ANSI escape sequences define a way to put additional information into terminal output, and color is part of this "additional information". Throughout the years the range of terminal colors has been vastly expanded, from the initial eight colors to a full 24-bit truecolor.

The basic color encoding provides 8 normal-brightness colors and 8 brighter versions of these colors. Modern terminal emulators, including the Linux console itself, allows you to specify the precise RGB values that the colors translate to. This mode is supported by almost all terminal emulators.

With the advent of 256-color displays came the 256-color escape. The 256 colors are the 16 basic colors, the 216 RGB colors (laid out in a 6x6x6 cube), and 24 levels of greyscale. Except for the first 16 colors, the scheme is usually not customizable as it has a well-defined mapping to RGB. This mode is supported by most terminal emulators. (A minority of emulators use a similar but incompatible encoding with only 88 colors. You are very unlikely to use them in practise, but they will appear in the terminfo database.)

Less commonly supported is the truecolor mode, allowing one to use 16.7 million (224) colors in RGB (each value ranging from 0 to 255).

Termcap and terminfo

Termcap and terminfo, part of ncurses, are databases that provide information on what escapes a terminal (usually specified by the TERM env-var) understands. The tput(1) and infocmp(1) commands can be used to access them from command-line.

アプリケーション

diff

diffutils にはバージョン 3.4 から --color オプションが存在します (GNU メーリングリスト):

$ alias diff='diff --color=auto'

grep

--color=auto オプションでカラーハイライトが有効になります。カラーコードは標準出力でのみ使われ、パイプやリダイレクトには出力されません。

grep のカラー出力は regexp でも利用できます。

エイリアスを作成することでオプションをずっと有効にできます:

alias grep='grep --color=auto'

GREP_COLORS 変数を使うことで色を定義したり、ハイライトの様々な部分を設定できます。

詳しくは grep(1) を見てください。

GREP_COLOR 環境変数を使うことでデフォルトのハイライト色を定義できます (デフォルトは赤です)。色を変更するときは、色の ANSI エスケープシーケンス を確認して以下のコマンドを使ってください:

export GREP_COLOR="1;32"

-n オプションを使うことでファイルの行番号も出力されます。

ip

ip(8) コマンドの -color オプションが使えます。auto 引数を指定すると、出力先が標準出力のときのみカラー出力が行なわれます。

alias ip='ip --color=auto'

less

環境変数

以下の行をシェルの設定ファイルに追加してください:

~/.bashrc
export LESS=-R
export LESS_TERMCAP_mb=$'\E[1;31m'     # begin blink
export LESS_TERMCAP_md=$'\E[1;36m'     # begin bold
export LESS_TERMCAP_me=$'\E[0m'        # reset bold/blink
export LESS_TERMCAP_so=$'\E[01;44;33m' # begin reverse video
export LESS_TERMCAP_se=$'\E[0m'        # reset reverse video
export LESS_TERMCAP_us=$'\E[1;32m'     # begin underline
export LESS_TERMCAP_ue=$'\E[0m'        # reset underline
# and so on

値はお好きに変更してください (ANSI エスケープコード)。このブログ記事Bash/プロンプトのカスタマイズも見てください。

ノート: LESS_TERMCAP_xx 変数は less(1) の man ページに載っていません。詳しい説明は [1] を見てください。

標準入力からの読み込み

ノート: 以下は export LESS=R に基づいているので、~/.bashrc~/.zshrc環境変数を追加することを推奨します。

コマンドを実行してページ表示するために標準出力 (stdout) を less にパイプする場合 (例: pacman -Qe | less)、出力がカラー化されないことに気づくかもしれません。stdout がインタラクティブターミナルであるかどうかを判別して、その場合はカラーのテキストを出力して、そうでない場合はカラーでないテキストを出力するようになっているのが原因です。stdout をファイルにリダイレクトしたいようなときはこれで構わないでしょうが (例: pacman -Qe > pkglst-backup.txt)、less で出力を表示したいような時はあまり望ましくありません。

インタラクティブ tty の検出を無効化するオプションがプログラムに存在することがあります:

# dmesg --color=always | less

プログラムに無効化オプションが存在しない場合、以下のユーティリティを使うことで stdout がインタラクティブターミナルであるかのように信じこませることができます:

  • stdoutisattyisatty 関数のコールをキャッチする小さなプログラム。
https://github.com/lilydjwg/stdoutisatty. || stdoutisatty-gitAUR
例: stdoutisatty program | less
  • unbuffershTcl ベースのスクリプト。
http://expect.sourceforge.net/example/unbuffer.man.html || expect
例: unbuffer program | less

もしくは、zshzpty モジュールを使って下さい [2]:

~/.zshrc
zmodload zsh/zpty

pty() {
	zpty pty-${UID} ${1+$@}
	if [[ ! -t 1 ]];then
		setopt local_traps
		trap '' INT
	fi
	zpty -r pty-${UID}
	zpty -d pty-${UID}
}

ptyless() {
	pty $@ | less
}

使用方法:

$ ptyless program

他のページャにパイプするには (例: less):

$ pty program | less

ls

--color=auto オプションでカラーハイライトが有効になります。カラーコードは標準出力でのみ使われ、パイプやリダイレクトでは使われません。

エイリアスを使うことでオプションを永続的に有効化できます:

alias ls='ls --color=auto'

LS_COLORS 変数を使って色を定義します。様々なハイライトを設定できます。設定するときは dircolors(1) コマンドを使ってください。

ノート: --color オプションを使用すると大量のファイルが存在するディレクトリで ls を実行したときにパフォーマンスに深刻な影響を与えることがあります。デフォルト設定では ls は表示する全てのファイルに stat(1) する必要があります。しかしながら、他のカラーオプション (executable, orphan, sticky, other-writable, capability) を使用しないでほとんどのファイルタイプのカラー化をしたい場合、dircolors を使って LS_COLORS 環境変数を以下のように設定してください:
eval $(dircolors -p | perl -pe 's/^((CAP|S[ET]|O[TR]|M|E)\w+).*/$1 00/' | dircolors -)

詳しくは ls(1) を見てください。

man

man ページのカラー出力を行う方法は2つ存在します: less を使用する方法、または most を使用する方法。

less を使う

詳しくは #less を見てください。

manless ラッパーは以下のようになります:

~/.bashrc
man() {
    LESS_TERMCAP_md=$'\e[01;31m' \
    LESS_TERMCAP_me=$'\e[0m' \
    LESS_TERMCAP_se=$'\e[0m' \
    LESS_TERMCAP_so=$'\e[01;44;33m' \
    LESS_TERMCAP_ue=$'\e[0m' \
    LESS_TERMCAP_us=$'\e[01;32m' \
    command man "$@"
}

Fish の場合、以下のようにします:

~/.config/fish/config.fish
set -xU LESS_TERMCAP_md (printf "\e[01;31m")
set -xU LESS_TERMCAP_me (printf "\e[0m")
set -xU LESS_TERMCAP_se (printf "\e[0m")
set -xU LESS_TERMCAP_so (printf "\e[01;44;33m")
set -xU LESS_TERMCAP_ue (printf "\e[0m")
set -xU LESS_TERMCAP_us (printf "\e[01;32m")

設定を source するかシェルを再起動すると変更が適用されます。

most を使う

'most' の基本的な機能は lessmore と似ていますが、備えている機能の数はやや少なくなっています。most でカラー出力を使うように設定するのは less よりも簡単ですが、less のように most を使うには別の設定が必要になります。

most パッケージをインストールしてください。

/etc/man_db.conf を編集して、ページャの定義をアンコメントして次のように変更:

DEFINE     pager     most -s

新しい設定は以下を入力することでテストできます:

$ man whatever_man_page

カラーの値を変更するには ~/.mostrc または /etc/most.conf (システム全体に変更が適用されます) を編集する必要があります (ファイルが存在しない場合は作成してください)。~/.mostrc の例:

% Color settings
color normal lightgray black
color status yellow blue
color underline yellow black
color overstrike brightblue black

less と同じようなキーバインドを使う例 (行ジャンプを 'J' に設定):

% less-like keybindings
unsetkey "^K"
unsetkey "g"
unsetkey "G"
unsetkey ":"

setkey next_file ":n"
setkey find_file ":e"
setkey next_file ":p"
setkey toggle_options ":o"
setkey toggle_case ":c"
setkey delete_file ":d"
setkey exit ":q"

setkey bob "g"
setkey eob "G"
setkey down "e"
setkey down "E"
setkey down "j"
setkey down "^N"
setkey up "y"
setkey up "^Y"
setkey up "k"
setkey up "^P"
setkey up "^K"
setkey page_down "f"
setkey page_down "^F"
setkey page_up "b"
setkey page_up "^B"
setkey other_window "z"
setkey other_window "w"
setkey search_backward "?"
setkey bob "p"
setkey goto_mark "'"
setkey find_file "E"
setkey edit "v"

X resources を使う

xterm/uxtermrxvt-unicode でマニュアルページを表示するときにカラーを追加したいときは ~/.Xresources を編集するのが簡単です。

xterm

修飾をカラーで置き換える:

*VT100.colorBDMode:     true
*VT100.colorBD:         red
*VT100.colorULMode:     true
*VT100.colorUL:         cyan

カラーと修飾 (太字や下線) を同時に使いたい場合:

*VT100.veryBoldColors: 6

veryBoldColors の説明は xterm(1) を見てください。

rxvt-unicode
URxvt.colorIT:      #87af5f
URxvt.colorBD:      #d7d7d7
URxvt.colorUL:      #87afd7

次を実行:

$ xrdb -load ~/.Xresources

xterm/uxtermrxvt-unicode を新しく起動すると man ページがカラフルになっているはずです。

上記の組み合わせは xterm/uxterm太字下線がある単語や、rxvt-unicode太字下線斜体のテキストに色を追加します。組み合わせを変えることで色々試せます。

pacman

Pacman にはカラーオプションがあります。/etc/pacman.confColor 行をアンコメントしてください。

ラッパー

ユニバーサルラッパー

以下のラッパーには複数のプリセットが含まれており、変更したり新しいプリセットを作成することができます。

  • rainbow — パターンを使ってコマンドの出力や標準入力をカラー化します。
    プリセット: df, diff, env, host, ifconfig, java-stack-trace, jboss, jonas, md5sum, mvn2, mvn3, ping, tomcat, top, traceroute。
https://github.com/nicoulaj/rainbow || rainbowAUR
  • grc — ログファイルやコマンドの出力を美しくするカラーライザー。
    プリセット: cat, cvs, df, digg, gcc, g++, ls, ifconfig, make, mount, mtr, netstat, ping, ps, tail, traceroute, wdiff, blkid, du, dnf, docker, docker-machine, env, id, ip, iostat, last, lsattr, lsblk, lspci, lsmod, lsof, getfacl, getsebool, ulimit, uptime, nmap, fdisk, findmnt, free, semanage, sar, ss, sysctl, systemctl, stat, showmount, tune2fs, tcpdump。
https://github.com/pengwynn/grc || grc
  • colorlogs — パターンを使ってコマンド出力や標準入力をカラー化。
    プリセット: logs, git status, ant, maven。
https://github.com/memorius/colorlogs || パッケージが存在しないか AUR で検索
  • cope — ターミナルプログラムのカラフルラッパー。
    プリセット: acpi, arp, cc, df, dprofpp, fdisk, free, g++, gcc, id, ifconfig, ls, lspci, lsusb, make, md5sum, mpc, netstat, nm, nmap, nocope, ping, pmap, ps, readelf, route, screen, sha1sum, sha224sum, sha256sum, sha384sum, sha512sum, shasum, socklist, stat, strace, tcpdump, tracepath, traceroute, w, wget, who, xrandr。
https://github.com/yogan/cope || cope-gitAUR
  • cw — 一般的な UNIX ベースコマンドのお手軽リアルタイム ANSI カラーラッパー。
    プリセット: arp, arping, auth.log@, blockdev, cal, cksum, clock, configure, cpuinfo@, crontab@, cw-pipe, cw-test.cgi, date, df, diff, dig, dmesg, du, env, figlet, file, find, finger, free, fstab@, fuser, g++, gcc, group@, groups, hdparm, hexdump, host, hosts@, id, ifconfig, inittab@, iptables, last, lastlog, lsattr, lsmod, lsof, ltrace-color, make, md5sum, meminfo@, messages@, mount, mpg123, netstat, nfsstat, nmap, nslookup, objdump, passwd@, ping, pmap, pmap_dump, praliases, profile@, protocols@, ps, pstree, quota, quotastats, resolv.conf@, route, routel, sdiff, services@, showmount, smbstatus, stat, strace-color, sysctl, syslog, tar, tcpdump, tracepath, traceroute, umount, uname, uptime, users, vmstat, w, wc, whereis, who, xferlog。
http://cwrapper.sourceforge.net/ || cwAUR
  • ccze — C で書かれた高速なログカラー化ツール。colorize を置き換えます。
https://github.com/cornet/ccze/ || ccze

出力をカラー化するためのライブラリ

  • ruby-rainbow — ruby の String クラスを拡張して ANSI ターミナルにおけるテキストのカラー化をサポート。
https://rubygems.org/gems/rainbow/ || ruby-rainbow
  • python-blessings — ターミナルのカラー化・スタイル・ポジションの実用的なラッパー。
https://github.com/erikrose/blessings || python-blessings, python2-blessings[リンク切れ: アーカイブ: aur-mirror]

特定のアプリケーションのラッパー

コンパイラ

  • colorgcc — gcc の出力形式に一致する警告・エラーメッセジなどのコンパイラの出力をカラーにする Perl ラッパー。
https://schlueters.de/colorgcc.html || colorgcc

diff

diff にはカラー出力機能が備わっていますが、以下のラッパーを使うこともできます:

  • colordiff — Perl script for diff highlighting.
http://www.colordiff.org/ || colordiff
  • cwdiff(w)diff wrapper with directories support and highlighting.
https://github.com/junghans/cwdiff || cwdiffAUR, cwdiff-gitAUR

less

source-highlight

less でシンタックスハイライトを有効にすることができます。まず、source-highlight をインストールし、次に以下の行をシェルの設定ファイルに追加してください:

~/.bashrc
export LESSOPEN="| /usr/bin/source-highlight-esc.sh %s"
export LESS='-R '
lesspipe

コマンドラインインターフェイスを頻繁に使う場合 lesspipe をインストールすると良いかもしれません。

ページャを使ってアーカイブの中の圧縮されたファイルを表示することができるようになります:

$ less compressed_file.tar.gz
==> use tar_file:contained_file to view a file in the archive
-rw------- username/group  695 2008-01-04 19:24 compressed_file/content1
-rw------- username/group   43 2007-11-07 11:17 compressed_file/content2
compressed_file.tar.gz (END)

lesspipe はファイルタイプに関連付けられたコマンドの代替として (例えば python-html2text で HTML を閲覧する)、アーカイブ以外のファイルも less のインターフェイスに接続します。

lesspipe を有効にするにはログインしなおすか、/etc/profile.d/lesspipe.sh を実行してください。

Make

  • colormake — 出力を読みやすくするシンプルな make のラッパー。
http://bre.klaki.net/programs/colormake/ || colormakeAUR, colormake-gitAUR

Ping

  • prettyping — ping の監視に素晴らしい機能を追加するラッパー。標準の ping ツールの出力を美麗・コンパクト・読みやすく改造。
http://denilson.sa.nom.br/prettyping/ || prettyping

シェル

bash

Bash/プロンプトのカスタマイズ#カラーを見てください。

zsh

Zsh#プロンプトのカスタマイズを見てください。

Fish

Fish#ウェブインターフェイスを見てください。

ターミナルエミュレータ

仮想端末

フレームバッファで実行される Linux 仮想端末の色は変更することができます。エスケープコードe \\e]PXRRGGBB を書き込むことで変更できます。X は 0-F からなる色の16進数インデックス、RRGGBB は伝統的な16進数の RGB コードに置き換えてください。

例えば、~/.Xresources に定義した既存の色定義を再利用するには、シェルの初期化ファイル (~/.bashrc など) に以下を追加してください:

if [ "$TERM" = "linux" ]; then
    _SEDCMD='s/.*\*color\([0-9]\{1,\}\).*#\([0-9a-fA-F]\{6\}\).*/\1 \2/p'
    for i in $(sed -n "$_SEDCMD" $HOME/.Xresources | awk '$1 < 16 {printf "\\e]P%X%s", $1, $2}'); do
        echo -en "$i"
    done
    clear
fi

ログイン画面

以下は /etc/issue の仮想端末のログイン画面のカラー出力例です。root で mv /etc/issue /etc/issue.bak を実行して元のファイルのバックアップを作成してから、新しい /etc/issue を作成してください:

\e[H\e[2J
                                                            \e[1;30m| \e[34m\\s \\r
       \e[36;1m/\\\\                      \e[37m||     \e[36m| |                   \e[30m|
      \e[36m/  \\\\                     \e[37m||     \e[36m|     _               \e[30m| \e[32m\\t
     \e[1;36m/ \e[0;36m.. \e[1m\\\\   \e[37m//==\\\\\\\\ ||/= /==\\\\ ||/=\\\\  \e[36m| | |/ \\\\ |  | \\\\ /     \e[30m| \e[32m\\d
    \e[0;36m/ .  . \\\\  \e[37m||  || ||   |    ||  || \e[36m| | |  | |  |  X      \e[1;30m|
   \e[0;36m/  .  .  \\\\ \e[37m\\\\\\\\==/| ||   \\\\==/ ||  || \e[36m| | |  | \\\\_/| / \\\\     \e[1;30m| \e[31m\\U
  \e[0;36m/ ..    .. \\\\   \e[0;37mA simple, lightweight linux distribution.  \e[1;30m|
 \e[0;36m/_\x27        `_\\\\                                             \e[1;30m| \e[35m\\l \e[0mon \e[1;33m\\n
 \e[0m

ファイルを保存したら chmod +x /etc/issue で実行可能属性を付与してください。

参照:

X window system

ほとんどの Xorg ターミナル (xtermurxvt を含む) は16色の基本色をサポートしています。0-7 の色は 'normal' カラーです。8-15 の色は 0-7 の色の 'bright' カラーです。ハイライトに使用します。X resources を使ったりターミナルの設定を使うことで色は変更することができます。例:

~/.Xresources
! Black + DarkGrey
*color0:  #000000
*color8:  #555753
! DarkRed + Red
*color1:  #ff6565
*color9:  #ff8d8d
! DarkGreen + Green
*color2:  #93d44f
*color10: #c8e7a8
! DarkYellow + Yellow
*color3:  #eab93d
*color11: #ffc123
! DarkBlue + Blue
*color4:  #204a87
*color12: #3465a4
! DarkMagenta + Magenta
*color5:  #ce5c00
*color13: #f57900
!DarkCyan + Cyan (both not tango)
*color6:  #89b6e2
*color14: #46a4ff
! LightGrey + White
*color7:  #cccccc
*color15: #ffffff
警告: foregroundbackground などのカラーリソースは他のアプリケーション (例: emacs) によって読み込まれる可能性があります。クラス名を指定することで読み込まれないようにすることができます。例: XTerm.foreground

参照:

256色全てを表示

画面上に256色を表示:

$ (x=`tput op` y=`printf %76s`;for i in {0..256};do o=00$i;echo -e ${o:${#o}-3:3} `tput setaf $i;tput setab $i`${y// /=}$x;done)

tput のエスケープコードを表示

tput op は確認したい色に置き換えてください。op はデフォルトの前景色と背景色です。

$ ( strace -s5000 -e write tput op 2>&2 2>&1 ) | tee -a /dev/stderr | grep -o '"[^"]*"'
033[\033[1;34m"\33[39;49m"\033[00m

サポートされている色を確認

以下のコマンドで使用しているターミナルがサポートしている色の数を確認できます。色の数は次のどれかになります: 8, 15, 16, 52, 64, 88, 256。

$ for T in `find /usr/share/terminfo -type f -printf '%f '`;do echo "$T `tput -T $T colors`";done|sort -nk2
Eterm-88color 88
rxvt-88color 88
xterm+88color 88
xterm-88color 88
Eterm-256color 256
gnome-256color 256
konsole-256color 256
putty-256color 256
rxvt-256color 256
screen-256color 256
screen-256color-bce 256
screen-256color-bce-s 256
screen-256color-s 256
xterm+256color 256
xterm-256color 256

ターミナルの機能を確認

以下のコマンドを使うことでターミナルによってサポートされている機能を確認できます:

$ infocmp -1 | sed -nu 's/^[ \000\t]*//;s/[ \000\t]*$//;/[^ \t\000]\{1,\}/!d;/acsc/d;s/=.*,//p'|column -c80
bel	cuu	ich	kb2	kf15	kf3	kf44	kf59	mc0	rmso	smul
blink	cuu1	il	kbs	kf16	kf30	kf45	kf6	mc4	rmul	tbc
bold	cvvis	il1	kcbt	kf17	kf31	kf46	kf60	mc5	rs1	u6
cbt	dch	ind	kcub1	kf18	kf32	kf47	kf61	meml	rs2	u7
civis	dch1	indn	kcud1	kf19	kf33	kf48	kf62	memu	sc	u8
clear	dl	initc	kcuf1	kf2	kf34	kf49	kf63	op	setab	u9
cnorm	dl1	invis	kcuu1	kf20	kf35	kf5	kf7	rc	setaf	vpa

カラースキームスクリプト

現在のターミナルスキームのチャートを表示するスクリプトが [3] に存在します。

参照