Search code examples
bashcolorszshansi-escape

ANSI color code of solarized theme to customize my prompt


I am using ANSI colors To beautify my prompt.

I am using solarized color pallet.

enter image description here

To get the colors what I am currently doing is using the following function to generate ANSI color codes alongside the colors.

function colors() {
  for color in {000..255}; do
    print -P "$color: %F{$color} Foreground %f%K{$color} Background %k"
    # Use `print -P` instead of `echo` if you want to use color.
  done
}

Then I am manually comparing them with the solarized color pallet. Then I am taking the ANSI code of that and using in my prompt. For example:

prompt='%F{002}[%2~]%f$(git_super_status)%(?.%F{033}√.%F{124}✕%?)%F{033}$ %f'

In there any way I can get the ANSI color code of the solarized color pallet more accurately?


Solution

  • Since you already defined the color palette inside your terminal emulator, you could use ANSI 3/4-bit color codes \033\[...m instead of zsh's promt expansion print -P '%F{...}'. That way, you will always use the colors from the palette, even when you change the palette. Furthermore, the colors will also work in any other shell and not just zsh.

    Example

    PS1=$'\033[31mThis is the same red as in your solarized palette\033[0m'
    

    Print palette with color codes

    echo 'use \033[CODEm Text \033[0m to set text color'
    for i in {0..7}; do
      for j in "3$i" "9$i"; do
        printf '\033[%sm Code %s ' "$j" "$j"
      done
      printf '\033[0m\n'
    done
    

    If you don't care about portability and want to use zsh's %F syntax, then you can use the codes %F{1} to %F{15} (which were already printed by your own script but overlooked because there were many more colors than just these).

    Hard-Coded Colors

    As said, above color codes use the palette from you terminal emulator. If you always want the same color regardless of the terminal emulator settings, then you can use 6-digit hex color codes in zsh:

    print -P '%F{#dc322f} This is always the red from the solarized palette'

    Wikipedia lists the hex color codes of the solarized palette.