Search code examples
pythonthemesvirtualenvzshoh-my-zsh

How can I add conditions to the display of certain elements of a ZSH prompt?


I'm customizing my ZSH theme and I'm having some problems. To start with, I want some elements of my prompt to be displayed only when git and/or (my virtual environment) are used.

example: Here I have my neutral prompt.

╭─[Swidenn ⏾ Hades] ▶ ~/Documents/
╰─[2003]-$                                                            [10:00:00]

And here you can see that the git information has appeared between 2 square brackets.

╭─[Swidenn ⏾ Hades] ⟜[git:master]⊸ ▶ ~/Documents/
╰─[2003]-$                                                            [10:00:00]

Now I've activated a virtual environment.

╭─[Swidenn ⏾ Hades] ⟜[git:master]⊸ [venv] ▶ ~/Documents/
╰─[2003]-$                                                            [10:00:00]

My problem is this: I'd like to display my virtual environment in the square brackets next to my git, like this:

╭─[Swidenn ⏾ Hades] ⟜[git:master env:venv]⊸ ▶ ~/Documents/
╰─[2003]-$                                                            [10:00:00]

All without impacting my neutral prompt.

My prompts are as follows:

PROMPT='%{$fg_bold[green]%}╭─[%{$reset_color%}%{$fg_bold[white]%}Swidenn %{$reset_color%}%{$fg_bold[green]%}⚡%{$reset_color%}%{$fg_bold[white]%}%M%{$reset_color%}%{$fg_bold[green]%}]$(git_prompt_info) $(virtualenv_prompt_info)%{$reset_color%}%{$fg_bold[green]%}▷ %{$reset_color%}%{$fg[white]%}%~
%{$reset_color%}%{$fg_bold[green]%}╰─[%{$reset_color%}%{$fg[white]%}%!%{$reset_color%}%{$fg_bold[green]%}]-> '

RPROMPT='%{$reset_color%}%{$fg[white]%}%D{[%H:%M:%S]}'

I've tried using these variables

ZSH_THEME_GIT_PROMPT_PREFIX=" ⟜[%{$reset_color%}%{$fg[white]%}git:%{$fg_bold[white]%}"
ZSH_THEME_GIT_PROMPT_SUFFIX="%{$reset_color%}%{$fg[green]%}]⊸"

but I don't know what they're called, so it's difficult for me to find solutions.


Solution

  • So I solved my problem by using simple conditions directly in my theme file. Here is my code:

    function neutral_prompt {
      echo "╭─[Swidenn ⚡ %M] ▷ %~
    ╰─[%!]-> "
    }
    
    function bracket_prompt {
      echo "╭─[Swidenn ⚡ %M] ⟜[$(git_prompt_info) $(virtualenv_prompt_info)]⊸ ▷ %~
    ╰─[%!]-> "
    }
    
    function final_prompt {
      if [[ $(git_prompt_info) == "" && $(virtualenv_prompt_info) == "" ]] ; then 
        prompt="$(neutral_prompt)"
      else
        prompt="$(bracket_prompt)"
      fi
    
    PROMPT='$(final_prompt)'