Sets the terminal title dynamically using ANSI escape codes. By default the current directory is shown, and the name of the current command while one is executing.
This file is written in literate programming style, to make it easy to explain. See terminal-title.elv for the generated file.
Install the elvish-modules
package using epm:
use epm
epm:install github.com/zzamboni/elvish-modules
In your rc.elv
, load this module:
use github.com/zzamboni/elvish-modules/terminal-title
By default the terminal title will show the name of the command being executed or the word elvish
, followed by the current path. You can customize the titles by setting the $terminal-title:title-during-prompt
and $terminal-title:title-during-command
variables to lambdas that determine the title to set while the prompt is displayed (i.e. while you are typing a command) and while a command is being executed, respectively. These are their default values:
var title-during-prompt = {
put "elvish "(tilde-abbr $pwd)
}
var title-during-command = {|cmd|
put (edit:wordify $cmd | take 1)" "(tilde-abbr $pwd)
}
We load the prompt-hooks and re libraries.
use ./prompt-hooks
use re
use str
The ANSI escape sequences to start/end the title setting can be configured in the $terminal-title:start
and $terminal-title:end
variables. The default values work with xterm terminal types (including Terminal.app on macOS with the xterm-256color
terminal type, which I use), but you can change them if needed.
var start = "\e]0;"
var end = "\007"
The set-title
function takes a string and sets it as the current terminal title.
fn set-title {|@title|
var title-str = (str:join ' ' $title)
print $start$title-str$end
}
The $terminal-title:title-during-prompt
and $terminal-title:title-during-command
variables contain lambdas that determine the title to set while the prompt is displayed (i.e. while you are typing a command) and while a command is being executed, respectively.
title-during-prompt
takes no parameters, and by default shows the word “elvish” followed by the current directory.
<<title-during-prompt-default>>
title-during-command
received one parameter containing the command that will be executed. By default shows the command name followed by the current directory.
<<title-during-command-default>>
The init
function sets up the corresponding prompt hooks and after-chdir hook. The after-chdir hook is needed for cases such as navigating with the built-in Elvish location and navigation modes.
fn init {
prompt-hooks:add-before-readline {
set-title ($title-during-prompt)
}
prompt-hooks:add-after-readline {|cmd|
set-title ($title-during-command $cmd)
}
set after-chdir = [ $@after-chdir {|dir|
set-title ($title-during-prompt)
} ]
}
We call init
automatically upon module load.
init