rombez
rombez

Reputation: 2208

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

My setup:

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\]~

Upvotes: 2

Views: 3549

Answers (1)

chepner
chepner

Reputation: 532303

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}%~ %# '

Upvotes: 8

Related Questions