Search code examples
regexzshzshrc

Is it possible to format the colour of parts of my git branch name inside the prompt?


In my .zshrc file I have the following lines that parse my current git branch and display it in the terminal, the .zshrc file looks like this:

# Load version control information
autoload -Uz vcs_info
precmd() { vcs_info }

# Set up the prompt (with git branch name)
setopt PROMPT_SUBST
PROMPT='%n in ${PWD/#$HOME/~} ${vcs_info_msg_0_} > '


# Format the vcs_info_msg_0_ variable
zstyle ':vcs_info:git:*' formats '(%b)'

So my terminal ends up looking like this:

me in ~/repos/myrepo (feat/MYISSUE-123/fix-the-broken-stuff) >

I would like to modify the script above so MYISSUE-123 has a different colour to the rest of the branch name.
How can I do that?


Solution

  • Try this ... change precmd to:

    precmd() {
      vcs_info
      psvar=(${(s:/:)vcs_info_msg_0_})
      # in case there are more than three components:
      psvar[3]=${(j:/:)psvar[3,-1]}  
    }
    

    Make sure precmd() is being called prior to each prompt display by adding it to the hook:

    autoload -Uz add-zsh-hook
    add-zsh-hook precmd precmd
    
    

    And change PROMPT to:

    PROMPT='%n in ${PWD/#$HOME/~} %1v/%F{red}%2v%f/%3v > '
    

    There are some notes about psvar in this answer: https://stackoverflow.com/a/64094551/9307265.
    The (s) and (j) parameter expansion flags are documented in the zshexpn man page.

    Please let me know if there are any issues.