I've got a simple but custom .zshrc that I'd like to populate the prompt with the git branch I'm currently on (when in a git repo). The code below seems to work, but one prompt behind where I'm actually at.
.zshrc:
#Prompt messing
# Load colors for prompt
autoload -U colors && colors
# Load version control information
autoload -Uz vcs_info
precmd() {
vcs_info
if [[ -n ${vcs_info_msg_0_} ]]; then
# allow check for changes
zstyle ':vcs_info:*' check-for-changes true
#sets unstaged string to this
zstyle ':vcs_info:git:*' unstagedstr "!"
#sets staged string to this
zstyle ':vcs_info:git:*' stagedstr " "
zstyle ':vcs_info:git:*' formats '%K{green}%u%k%K{cyan}%c%k'
BRANCH=$(command git rev-parse --abbrev-ref HEAD)
PS1='%F{magenta}%7>>${BRANCH}%<<%f'
PS1 ='${vcs_info_msg_0_} %~; '
else
PS1='%~; '
fi
}
For example:
master ~/code/external-api; cd ..
master ~/code;
~/code;
I would expect the second line there to not have the master
in the prompt.
Any help is greatly appreciated!
CodePudding user response:
After going to the trouble to enabling vcs_info, you've then got your own git branch implementation with the two lines assigning $BRANCH
. Setting zstyles for vcs_info
really doesn't need to be repeated every time precmd()
runs. It is better to use psvar
and %v
instead of relying on the PROMPT_SUBST
option. For example:
PS1='%(V.%v .)%~; '
autoload -U vcs_info
zstyle … # all the zstyle commands from before
precmd() {
vcs_info
psvar[1]="${vcs_info_msg_0_}"
}
I also wouldn't bother with the colors
function. Just using %F{majenta}
works better. It is a holdover from many years ago before zsh had direct support and just sets variables with literal escape sequences.
CodePudding user response:
According to this page you can do this with vcs_info.
# in your ~/.zshrc
autoload -Uz vcs_info
zstyle ':vcs_info:*' enable git
precmd() {
vcs_info
}
Prompt setup:
setopt prompt_subst
PROMPT='${vcs_info_msg_0_}%# '
And then you need to format the message:
zstyle ':vcs_info:git*' formats "%{$fg[grey]%}%s %{$reset_color%}%r/%S%{$fg[grey]%} %{$fg[blue]%}%b%{$reset_color%}%m%u%c%{$reset_color%} "
CodePudding user response:
To fix the 'one prompt behind' problem, try adding this to ~/.zshrc
, after declaring the function:
autoload -Uz add-zsh-hook
add-zsh-hook precmd precmd
The precmd
function isn't a precmd
function until you make it a precmd
function :). A lot of folks have oh-my-zsh
installed, and get the precmd
hook set that way, so this part isn't always documented.
To avoid confusion, it's often preferable to use a different name for the function:
function my_precmd {
vcs_info
...
}
autoload -Uz add-zsh-hook
add-zsh-hook precmd my_precmd