Reloading terminal settings on the fly

One of the most useful programs from the UNIX user’s toolbox is the terminal emulator. Because it’s one of the most used tools and contains a lot of text, many users prefer to customize their terminal with custom fonts and color schemes, to make it more readable, or to make it look good. Often, the user wants to reload the configuration file. Some sophisticated emulators reload themselves automatically on file change, others need restarting.

However, many of them support escape codes for changing color values and some support specific codes for setting the background/foreground colors and even font.

This article is meant to be a guide, or cheat sheet, for such codes. My terminal emulator of choice is rxvt-unicode (aka urxvt), because it’s lightweight (it doesn’t have heavy dependencies like gtk or libvte), fast, and is configured easily through the X resource database (xrdb).

List of codes

Wrap-up

Using these codes you can make make a theme switcher, or a basic color switcher, anything you like!

Here is an example color switcher:

#!/bin/sh

usage() {
	echo "Usage: $(basename "$0") <color scheme>" >&2
	exit 1
}

test -f "$1" || usage

sequences=""

set_color() {
	sequences+="\033]4;${1};${2}\007"
}

set_special() {
	sequences+="\033]${1};${2}\007"
}

# colorcolumns is a script that takes colors from an X resources file
# and prints them by key and by color
IFS=$'\n'
for line in $(colorcolumns "$1"); do
	key="$(echo $line | awk '{print $1}' | tr -d ':')"
	color="$(echo $line | awk '{print $2}')"

	case "$key" in
		color*)
			colorcode="$(echo "$key" | grep -o '[0-9]\+')"
			set_color "$colorcode" "$color"
			;;
		foreground)
			set_special 10 "$color"
			set_special 12 "$color"
			set_special 13 "$color"
			;;
		background)
			set_special 11 "$color"
			set_special 14 "$color"
			set_special 708 "$color"
			;;
	esac
done

# send codes to all terminals
for term in /dev/pts/[0-9]*; do
	printf "%b" "$sequences" > "$term"
done

# save changes for future instances
xrdb -merge "$1"

To change the font, I do

for term in /dev/pts/[0-9]*; do
	printf '\33]50;%s\007' "$TERM_FONT" > "$term"
done

Have fun switching colors!

Oh, here’s a video of the color switcher in action: ka-chow.