shell prompt: enclose control sequence in brackets (#33079)

When setting `PS1` in Bash, it's required to enclose non-printable characters in square brackets, so that the width of the terminal is handled correctly.

See https://www.gnu.org/software/bash/manual/bash.html#Controlling-the-Prompt
This commit is contained in:
Brian Vanderwende 2022-10-10 07:29:58 -06:00 committed by GitHub
parent 7cb745b03a
commit 27cf8dddec
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 10 additions and 4 deletions

View File

@ -150,13 +150,17 @@ def color_when(value):
class match_to_ansi(object):
def __init__(self, color=True):
def __init__(self, color=True, enclose=False):
self.color = _color_when_value(color)
self.enclose = enclose
def escape(self, s):
"""Returns a TTY escape sequence for a color"""
if self.color:
return "\033[%sm" % s
if self.enclose:
return r"\[\033[%sm\]" % s
else:
return "\033[%sm" % s
else:
return ""
@ -201,9 +205,11 @@ def colorize(string, **kwargs):
Keyword Arguments:
color (bool): If False, output will be plain text without control
codes, for output to non-console devices.
enclose (bool): If True, enclose ansi color sequences with
square brackets to prevent misestimation of terminal width.
"""
color = _color_when_value(kwargs.get("color", get_color_when()))
string = re.sub(color_re, match_to_ansi(color), string)
string = re.sub(color_re, match_to_ansi(color, kwargs.get("enclose")), string)
string = string.replace("}}", "}")
return string

View File

@ -44,7 +44,7 @@ def activate_header(env, shell, prompt=None):
# TODO: prompt
else:
if "color" in os.getenv("TERM", "") and prompt:
prompt = colorize("@G{%s}" % prompt, color=True)
prompt = colorize("@G{%s}" % prompt, color=True, enclose=True)
cmds += "export SPACK_ENV=%s;\n" % env.path
cmds += "alias despacktivate='spack env deactivate';\n"