Hyperlink escape codes

last updated: Sep 04, 2024

To print out a clickable hyperlink in a [terminal that supports] the OSC8 escape code, using bash:

printf '\e]8;;http://example.com\e\\This is a link\e]8;;\e\\\n'

The structure of that URL is (keep in mind that \e represents the same thing as \x1b):

OSC8 := \x1b]8;; ST := \x1b\x5C {OSC8}{url}{ST}{link text}{OSC8}{ST}

Found via trying to get the gh cli to output nicer code search results that I can get more context from

Here's a python function that returns an appropriately escaped hyperlink ready for display in the terminal:

def link(url, link):
    return f'\033]8;;{url}\033\\{link}\033]8;;\033\\'

note that this assumes your URL is properly URL-escaped.

Javascript code to output an OSC8 link:

function link(url, text) {
  const osc8 = '\x1B]8;;';
  const st = '\x1B\x5C';
  return `${osc8}${url}${st}${text}${osc8}${st}`;
}

Unfortunately the ansi-regex package has an issue where it doesn't support the standard ST (string termination) sequence of \x1b\x5C; I've submitted a pull request and we'll see if it gets in.

↑ up