MacOS – update_terminal_cwd dethestified please

bashitermmacostabsterminal

I am trying to find the documentation on what, exactly, the printf command is doing in update_terminal_cwd.

If you didn't know already, the update_terminal_cwd function is defined (at least on Mac OS X 10.7.4) in /etc/bashrc and in that same file the function is added to the $PROMPT_COMMAND so that it runs every time you hit enter in the Terminal.

The text of the update_terminal_cwd function itself is as follows:

update_terminal_cwd() {
    # Identify the directory using a "file:" scheme URL,
    # including the host name to disambiguate local vs.
    # remote connections. Percent-escape spaces.
local SEARCH=' '
local REPLACE='%20'
local PWD_URL="file://$HOSTNAME${PWD//$SEARCH/$REPLACE}"
printf '\e]7;%s\a' "$PWD_URL"
}

This is a few steps down the rabbit hole from trying to set my Terminal tab names from the command line, which can be done rather easily, but the tab name gets reset when sshing into a box.

This led me to How to stop automatic changing of iTerm titles? and the rather obscure list of control sequences on the Mac.

If you go to that last link and search for the string osc ps ; pt bel, you will find the section which defines the escape character that makes tab renaming work. However, while that explains printf '\e]1;%s\a' (note the "1"), it doesn't explain what the "7" does in the update_terminal_cwd function I quoted above.

Where is this documented?? (And why does PWD_URL include the prefix file://?)

Best Answer

from Terminal.app v2.6.1 (OS X 10.11), under Preferences/Profiles/Window, there is highlighted text "Escape sequence..." which says:

The working directory and location of the current document may be set using the Operating System Command (OSC) escape sequence:

ESC ] Ps ; Pt BEL

The parameter Ps is either 6 (document) or 7 (working directory) and Pt is a “file:” URL. The URL should include a hostname to disambiguate local and remote paths, and characters must be percent-encoded as appropriate.

When both the working directory and document are set only the document is displayed.

also, from Preferences/Profiles/Tab:

Window and tab titles may be set using the Operating System Command (OSC) escape sequence:

ESC ] Ps ; Pt BEL

The parameter Ps is either 1 (tab title—aka “icon title”) or 2 (window title) and Pt is the title text.

A custom window title will be displayed within the tab title (along with the other selected items) if there is no custom tab title.

The following example bash command sets the tab title to “My Tab”:

printf '\e]1;%s\a' 'My Tab'