From 27cf8dddec398dcc779067f38a7bbc62b32c3d17 Mon Sep 17 00:00:00 2001 From: Brian Vanderwende Date: Mon, 10 Oct 2022 07:29:58 -0600 Subject: 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 --- lib/spack/llnl/util/tty/color.py | 12 +++++++++--- lib/spack/spack/environment/shell.py | 2 +- 2 files changed, 10 insertions(+), 4 deletions(-) (limited to 'lib') diff --git a/lib/spack/llnl/util/tty/color.py b/lib/spack/llnl/util/tty/color.py index 1bc80331d4..ad6862fc28 100644 --- a/lib/spack/llnl/util/tty/color.py +++ b/lib/spack/llnl/util/tty/color.py @@ -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 diff --git a/lib/spack/spack/environment/shell.py b/lib/spack/spack/environment/shell.py index 50a4bcf657..4150c8d52e 100644 --- a/lib/spack/spack/environment/shell.py +++ b/lib/spack/spack/environment/shell.py @@ -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" -- cgit v1.2.3-70-g09d2