Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using ANSI escape sequences in zsh prompt

Tags:

zsh

zshrc

I'm trying to use ANSI escape sequences to set the color of my zsh prompt, but the escape character (\e) seems to be being escaped when displaying the prompt. Here's an example of what I'm running and the output I'm getting:

> autoload promptinit && promptinit
> autoload colors && colors
> echo "Not sure if those two lines are required" > /dev/null
> PROMPT="\e[32mhi> "
\e[32mhi> echo "Note that the escape character wasn't interpreted correctly" > /dev/null
\e[32mhi> print -P "$PROMPT"
hi>
\e[32mhi> echo "The hi> was printed in green, as I want" > /dev/null

The zsh print documentation seems to say the -P flag makes it print as if it was in the prompt, but it doesn't match the actual prompt behavior. Does anyone know why the escape character doesn't work?

I tried using $fg_no_bold, and things like $fg_no_bold[red] do work, but I'd like to use more than the 8 standard colors, but $fg_no_bold[32] doesn't work (for any number, not just 32). If getting 256 colors working with $fg_no_bold is easier, then I'd be ok doing that!

Thanks!

like image 425
robbiemc Avatar asked Jun 01 '15 07:06

robbiemc


1 Answers

You need to use dollar single quote in order to tell zsh to interpret ANSI escape sequences. So

PROMPT=$'\e[32mhi> '

will do what you want, however it is safer to additionally put all special codes inside %{...%} brackets to treat code literally and prevent unwanted moving of the cursor position. Moreover you should change back the colour to the default, unless you want to colourize all terminal text foreground to green.

After all your prompt setting should look like

PROMPT=$'%{\e[32m%}hi> %{\e[0m%}'
like image 153
jimmij Avatar answered Sep 26 '22 09:09

jimmij