Tuesday, January 17, 2012

Automatic Screen Window Titles in Bash and Vim

I finally configured screen to display the list of windows open with useful titles. Here are the few bits I needed

First, if you don't know what I'm talking about:
I occasionally SSH into work, and when I do I use a program called screen that can host multiple terminal shells. It can persist those shells and allow me to reconnect if I get disconnected or want to change computers I'm working on.

BTW, I always start screen with screen -RaAd -S x

  • -a   include all capabilities ...
  • -A   Adapt  the sizes of all windows ...
  • -d -R   Reattach a session and if necessary detach or even create it first.
  • -S Name of the session

The default configuration makes it hard to keep track of how many terminals you have running, and what they are doing. I made three changes that help my personal workflow:

Add a persistent display at the bottom of screen
In .screenrc I appended this line:
hardstatus alwayslastline "%{=b}%{G} Screen(s): %{b}%w %=%{kG}%C%A  %D, %M/%d/%Y "

Source: Julien Chaffraix, a coworker.

Set the current directory name as the window title from bash
In .bashrc I appended these lines:

if [ "$TERM" = "screen" ]; then
  screen_set_window_title () {
    local HPWD="$PWD"
    case $HPWD in
      $HOME) HPWD="~";;

      ## long name option:
      # $HOME/*) HPWD="~${HPWD#$HOME}";;

      ## short name option:
      *) HPWD=`basename "$HPWD"`;;

    printf '\ek%s\e\\' "$HPWD"
  PROMPT_COMMAND="screen_set_window_title; $PROMPT_COMMAND"

You can see that I'm using a short name for each directory, e.g. "chromium" instead of the full path or suffix path after my home directory, e.g. "~/projects/chromium". You can toggle the commented lines to try alternates.

Source: http://unix.stackexchange.com/questions/6065/gnu-screen-new-window-name-change.

Set the name of the buffer I'm editing in vim
In .vimrc I appended these lines ("To create ^[, which is escape, you need to enter CTRL+V < Esc"):

if &term == "screen"
  let &titlestring=expand("%:t")
  set t_ts=^[k
  set t_fs=^[\
  set title

Source: http://vim.wikia.com/wiki/Automatically_set_screen_title.


  1. Awesome post, exactly what I was looking for. You forgot the part in the .vimrc tutorial where you have to create the ^[ character using a keyboard shortcut in vim.

    "To create ^[, which is escape, you need to enter CTRL+V <Esc"

    After you do this it works fine, but if you don't do this the first time you have to remove those lines from your vimrc or you can't edit in vim properly, it's a bit of a pain.