Zsh Prompt Hacking

10 June 2018 · 2 minute read

I’ve been doing some work porting my stuff from git to mercurial because it fits my workflow better. Which involved some tweaking to my prompt. Some of the key features include:

screenshot of terminal showing zsh prompt with separator, hostname, username, current directory, and version control information

Code under the fold. See my earlier post for more information about how I set up my .zshrc.

## ======================
## Prompt Configuration
## ======================

## autoload vcs and colors
autoload -Uz vcs_info
autoload -U colors && colors

# enable only git and mercurial 
zstyle ':vcs_info:*' enable git hg

# setup a hook that runs before every ptompt. 
precmd_vcs_info() { vcs_info }
precmd_functions+=( precmd_vcs_info )

# set an option so that I can pull variables
# in prompt strings.
setopt prompt_subst

# get revision info and check for local changes.
zstyle ':vcs_info:(hg*|git*):*' get-revision true
zstyle ':vcs_info:(hg*|git*):*' check-for-changes true

## style the prompt.
## %r repo name
## %b current branch info
## %m misc replacement bookmarks for hg
## %u unstaged changes
## %c stanged changes
zstyle ':vcs_info:git:*' formats " %r (%b) %m%u%c"
zstyle ':vcs_info:hg:*' formats " %r (%b) %m%u%c"

## set the unstaged string to "+"
zstyle ':vcs_info:(hg*|git*):*' unstagedstr "+"

## hgrevformat
## %r show local rev number as opposed to global patch id. 
zstyle ':vcs_info:hg*:*' hgrevformat "%r" 

## consider using hg_prompt for this 

## the actual prompt.
## ${(r:$COLUMNS::\u2500:)} a line separator.
## requires a unicode-aware terminal
##
## (%h%{$fg[red]%}%(?.. [%?])%{$reset_color%}) show history number and
## last exit code if it's not 0.
## %n username
## %m host name
## $vcs_info_msg_0_ vcs info set above.
##
## %(5~|%-1~/…/%3~|%4~) creatively truncated current path.
## %# identify if user has elevated privleges. 

PROMPT=$'${(r:$COLUMNS::\u2500:)}
(%h%{$fg[red]%}%(?.. [%?])%{$reset_color%}) %{$fg[green]%}%n@%m%{$reset_color%} $vcs_info_msg_0_ 
%{$fg[green]%}%(5~|%-1~/…/%3~|%4~)%{$reset_color%} %# '