Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using custom colors in zsh PS1 (prompt) env var causes problems with whitespace

My setup:

  • zsh 5.7.1 (x86_64-apple-darwin19.0)
  • macOS Catalina 10.15.5

Here's the standard PS1 var: PS1="%n@%m %~ %# "

Problems arise when I try adding text coloring using either ANSI colors or tput. Example (without terminating the color, it behaves oddly regardless of that):

PS1="%n@%m \e[38;5;197m%~ %# "

Here's what happens when I use Ctrl+R (reverse search): weird indents

What could be the reason for this indent?

Second problem happens when a long string in the prompt goes to the newline - new character after newline overlaps the first line and I can't see the latter. This happens only with the first newline, third one appears normally (but in second place).

I tried using this answer but the solution can't get parsed by the shell: rombez@MacBook-Pro \[\e[38;5;197m\]~

like image 682
rombez Avatar asked Jan 30 '26 10:01

rombez


1 Answers

ANSI escape sequences don't take up any space on the terminal, so you have to tell zsh that they don't contribute to the length of the prompt. You do this by wrapping them in %{...%}.

PS1="%n@%m %{\e[38;5;197m%}%~ %# "

However, you don't need raw ANSI escape sequences in zsh nearly as often as you do in bash. You can specify a color directly using the %F sequence, which zsh knows how to handle when calculating the size of your prompt.

PS1='%n@%m %F{197}%~ %# '
like image 68
chepner Avatar answered Feb 01 '26 09:02

chepner



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!