Showing git branch in zsh

Lately, I’ve been working a lot with several git and mercurial repositories. Keeping track of the current state of the repo (branch + staging changes) gets boring quickly, so I decided to use zsh facilities to include that information in the prompt. The preferred way of doing it is with vcs_info, available since zsh beta, version 4.3.6-dev-0+20080929-1 (ref); older guides will use custom functions, which is unnecessary, unless you want to go beyond the basic support provided by this module.

My configuration includes information about staged(stagedstr) and unstaged(unstaged), displayed as “:S” and “:U” respectively:

autoload -Uz vcs_info
setopt promptsubst

zstyle ':vcs_info:*' check-for-changes true
zstyle ':vcs_info:*' stagedstr ':S'
zstyle ':vcs_info:*' unstagedstr ':U'
zstyle ':vcs_info:*' enable git hg
zstyle ':vcs_info:*' actionformats \
  '%F{5}(%f%s%F{5})%F{3}-%F{5}[%F{2}%b%F{3}%c%u|%F{1}%a%F{5}]%f '
zstyle ':vcs_info:*' formats       \
  '%F{5}(%f%s%F{5})%F{3}-%F{5}[%F{2}%b%F{5}%c%u]%f '

precmd() {

RPROMPT='${vcs_info_msg_0_}[%T on %D]'

And here is how it looks (original):

A few things I struggled with, basically because I didn’t read the docs:

  • You must set setopt promptsubst otherwise, ${vcs_info_msg_0_} is not going to be recognized.
  • If you use %c or %u for change tracking, you should set to true check-for-changes (see code).
  • Don’t forget about precmd()

Here are other examples: 1, 2