4

To make my command line prompt look prettier on zsh, I added this line to .zshrc:

PROMPT='%F{green}%n%f %B%F{blue}%1~%f%b $ '

However, when I activate an anaconda virtual environment (i.e. conda activate base), I see the name of the virtual environment on the left like this:

(base) myusername ~ $

I wonder how I can modify the virtual environment part of the prompt (say we want to color it to cyan for example)

3 Answers3

7

The first step is to disable the default conda prompt modifier by running conda config --set changeps1 false as they already mentioned.

Next, add the following to your .zshrc:

# Determines prompt modifier if and when a conda environment is active
precmd_conda_info() {
  if [[ -n $CONDA_DEFAULT_ENV ]]; then
    CONDA_ENV="($CONDA_DEFAULT_ENV) "
  # When no conda environment is active, don't show anything
  else
    CONDA_ENV=""
  fi
}

# Run the previously defined function before each prompt
precmd_functions+=( precmd_conda_info )

# Allow substitutions and expansions in the prompt
setopt prompt_subst

PROMPT='%F{cyan}$CONDA_ENV%f%F{green}%n%f %B%F{blue}%1~%f%b $ '

With this, the conda environment is shown before the rest of the prompt, inside parentheses, and in cyan.

If you want it to appear bold, enclose that portion in %B and %b:

PROMPT='%B%F{cyan}$CONDA_ENV%b%f%F{green}%n%f %B%F{blue}%1~%f%b $ '

If you want to use more colours, check whether your terminal supports it by running echo $TERM. If it returns xterm-256color, you can replace the colours in curly brackets by values from 0 to 255. You can check out the colours here.

allerpi
  • 71
  • 1
  • 3
0

Run:

conda config --set changeps1 False

or add changeps1: False to your .condarc.

GAD3R
  • 63,407
  • 31
  • 131
  • 192
  • Thank you for the suggestion, it helps me with removing the virtual environment name. Do you also know how to modify the prompt? (i.e change the color, or make it bold) – Firat Cem Gurbey Jun 27 '21 at 18:54
0

It seems that allerpi's answer fails when switching conda environments.

This could be solved with a minor change:

  1. Still, conda config --set changeps1 false
  2. Append this snippet to your ~/.zshrc
    # ~/.zshrc
    precmd_get_conda_env_name() {
    if [[ -n $CONDA_PREFIX ]]; then
        if [[ $(basename $CONDA_PREFIX) == "miniconda3" ]]; then
            CONDA_ENV="base"
        else
            CONDA_ENV="$(basename $CONDA_PREFIX)"
        fi
    else
        CONDA_ENV=""
    fi
    }
    precmd_functions+=( precmd_get_conda_env_name )
    precmd_update_prompt() {
        PROMPT=$'\n'"%B%F{black}[%F{green}%D{%m/%d %H:%M}%F{black}] %F{red}%n%F{black}@%F{yellow}%m%F{black}:%F{cyan}%~"$'\n'"%F{magenta}($CONDA_ENV)%F{blue} ➜ %f%b"
    }
    precmd_functions+=( precmd_update_prompt )
    

It would eventually look like:

  • iTerm2

    MacOS, iTerm2

  • VSCode Integrated Terminal

    VSCode Integrated Terminal