0x131
0x131

Reputation: 109

How to use escape sequences in a ZSH prompt for truecolor or bold?

I am in the middle of customizing my ZSH prompt but am seemingly unable to use escape sequences to tell Konsole to use bold text or a specific RGB color.

I know about the built in formatting options in ZSH, like %F{000} %f, but as far as I know, those options only allow access to the defaults(red, blue, etc) and the 256 color palette. While %B %b, the built-in option for bold, does work, it seems limited to just one color.

What I want to be able to do is color a specific section of the prompt using all RGB colors and/or make it bold. From what I could find, something like this should work:

PS1="%{\e[38;0;255;0;255m%}%M >:%{\e[0m%}"

That should give me a pink prompt like this:

HOSTNAME >:                  

But what I get is this:

\e[38;0;255;0;255mHOSTNAME >:\e[0m

I have tried different escape sequences like \033 \x1b, but nothing seems to work.

So, how do I properly use escape sequences in ZSH prompts?



Specifics:

OpenSUSE Tumbleweed KDE

Konsole --version 16.12.0 (Keyboard:XFree 4)

ZSH --version 5.3

Upvotes: 10

Views: 5215

Answers (3)

chepner
chepner

Reputation: 532518

You can specify arbitrary 24-bit colors with %F using an RGB triplet.

% print -P "%F{#009090}tealish"
tealish

result of above code

Upvotes: 5

V.G.
V.G.

Reputation: 71

I might be a little late for this, but on ZSH, your answer will be:

PS1="%F{green}%M >:%f"

Your original code used the ANSI escape sequences for colour formatting, which might not work correctly in all Zsh terminals. This updated code uses the Zsh-specific prompt escape sequences (%F{color_code} and %K{color_code}) to set the Foreground and bacKground colours, respectively.

To apply this you must set it in ~/.zshrc.

Run this to set it automatically (it will not override any existing settings there):

touch ~/.zshrc && echo '\nPS1="%F{green}%M >:%f"' >> ~/.zshrc && echo "Success";

Here is a StackOverflow question that answers how the colours work in zsh.

Upvotes: 1

sbdchd
sbdchd

Reputation: 676

You need to change your strings so that zsh evaluates them correctly.

Try changing:

PS1="%{\e[38;0;255;0;255m%}%M >:%{\e[0m%}"

To:

PS1=$'%{\e[38;0;255;0;255m%}%M >:%{\e[0m%}'

Notice the change from " to ' quotes along with the prepended $

See http://zsh.sourceforge.net/Guide/zshguide05.html for more info on substitutions.

Upvotes: 5

Related Questions