What’s the right value of $TERM for emacs’ ansi-term, especially if ‘eterm-color’ isn’t available after SSH

ansi-termemacsterminalxterm

I'm currently setting $TERM to xterm-256color:

if [[ -n "$EMACS" ]]; then
    export TERM=xterm-256color
    alias emacs="emacsclient --no-wait"
    export EDITOR="emacsclient --no-wait"
    export VISUAL="emacsclient"
fi

I used to have it set to eterm-color, but the problem is that this terminal type is not available on most of the machines I log into via SSH.

The default .bashrc in Ubuntu checks if the TERM variable starts with xterm-, in which case it tries to set the window title:

PS1="\[\e]0;${debian_chroot:+($debian_chroot)}\u@\h: \w\a\]$PS1"

The problem is the \[\e]0; bit. It should be parsed by xterm-compatible terminal emulators, but emacs (ansi-term) doesn't do that. The result of which is a terminal like this:

0;user@host: ~user@host:~$ 

It also breaks some applications using readline, when the typed text is larger than the width of the terminal.

Because eterm-color isn't available on some remote hosts (and I can't install it either), setting it to that value messes up things like less.

Is there any trick I can use, such as another terminal type that ships with most distributions or a hack that makes ansi-term recognize the relevant escape codes and set the title, or just discard them?

Best Answer

I worked out an approach that lets you find out specifically what terminals are available on the remote host and then set it. Usually, there is at least one ansi compatible terminal, so a 'hack' to fake it should be unnecessary.

Done in one long'ish ssh command, it will look something like this:

ssh -i ~/.ssh/some_key.pub -tty some_remote_server "export TERM=`ls -1R /usr/share/terminfo | grep ^eterm-color$ || ls -1R /usr/share/terminfo | grep ^aterm$ || ls -1R /usr/share/terminfo | grep ^ansi$ || ls -1R /usr/share/terminfo | grep ^xterm-256color$ || export TERM=xterm && emacs -nw"

This finds different ansi compatible (and non-compatible) terminal types in an order of preference on the remote host and sets the first one found before launching EMACS. It sets TERM to use 'xterm' type if none of our preferred types are found, ensuring EMACS does actually launch.

In this example, I am looking for eterm-color, aterm, ansi, and xterm-256color in that order. I am not a heavy EMACS user, so not sure those are actually the best. I tested this launch on CentOS and worked well (it found eterm-color in my testing).

I believe the terminfo is in the same place on most/all Linux variants, but you can add more paths to search the same way you would add more terminals, by adding more

 || ls -1R /a/different/path | grep ^someotherterminal$ 
conditional test and pipes.

Related Question