FrVentura
FrVentura

Reputation: 123

Different zsh terminal prompt when outside git directory

Does anyone know how to do this? I need/want my right prompt to display time when I'm outside a git directory, and I want it to show the branch when I'm inside a git dir.

This is the config I use, extracted from git doc:

autoload -Uz vcs_info
precmd_vcs_info() { vcs_info }
precmd_functions+=( precmd_vcs_info )
setopt prompt_subst
RPROMPT=\$vcs_info_msg_0_
zstyle ':vcs_info:git:*' formats '%b'

But want to use RPROMPT="%*" when outside git dir.

Upvotes: 0

Views: 706

Answers (1)

Gairfowl
Gairfowl

Reputation: 2981

One way is to put everything into your own precmd function. Here's an example (add this to ~/.zshrc):

my_precmd() {
  vcs_info
  psvar[1]=$vcs_info_msg_0_
  if [[ -z ${psvar[1]} ]]; then
    psvar[1]=${(%):-%*}
  fi
}

autoload -Uz vcs_info
zstyle ':vcs_info:git:*' formats '%b'
autoload -Uz add-zsh-hook
add-zsh-hook precmd my_precmd
RPROMPT=%1v

Some notes:

  • vcs_info Calls the zsh builtin to set $vcs_info_msg_0_.
  • zstyle ... Configures the result from vcs_info.
  • psvar[1] The psvar array is a set of special variables that can be referenced easily in a prompt (%1v).
  • if [[ -z ${psvar[1]} ]] Tests to see if anything was set by vcs_info; if the result is zero-length, use the time instead.
  • ${(%):-%*} Gets the time. There are a few pieces: (%) says to substitute percent escapes like in a prompt, :- is used to create an anonymous variable for the substitution, and %* is the prompt escape that sets the time.
  • add-zsh-hook ... Adds my_precmd to the precmd hook, so it'll be called prior to each prompt. This is preferable to setting precmd_functions directly.
  • RPROMPT=%1v Sets the right-side prompt to always display the value of psvar[1].

Upvotes: 1

Related Questions