user3056541
user3056541

Reputation: 77

Trying to conditionally insert a newline in my ZSH prompt. Having trouble figuring it out

I have the following in my .zshrc:

PROMPT=$'$(ps1_head)[%F{32}%n@%m%f %~]%(!.#.$) '

function ps1_head ()
{
  var=${vcs_info_msg_0_}
  [ ! -z "$var" ] && printf '%b\n' $var
}

It works in that I get my git prompt. But the newline is never inserted. How do I fix this?

Upvotes: 1

Views: 660

Answers (1)

Gairfowl
Gairfowl

Reputation: 2980

With a command substitution like $(...), trailing newlines are trimmed from the replacement text, so the \n isn't included in the resulting prompt string.

Note that it's only the last newlines that are removed; newlines in the middle are retained. So a simple fix would be to add some text (e.g. a space) after the newline:

autoload -Uz vcs_info
setopt PROMPT_SUBST

PROMPT=$'$(ps1_head)[%F{32}%n@%m%f %~]%(!.#.$) '

function ps1_head() {
  vcs_info
  var=${vcs_info_msg_0_}
  [ -n "$var" ] && printf '%s\n ' "$var"
}

For more formatting flexibility, it's often easier to use a zsh precmd:

my_precmd() {
  vcs_info
  [[ -n $vcs_info_msg_0_ ]] && print $vcs_info_msg_0_
}

autoload -Uz vcs_info
zstyle ':vcs_info:git:*' formats '(%s)-[%b]'
autoload -Uz add-zsh-hook
add-zsh-hook precmd my_precmd
PROMPT='[%F{32}%n@%m%f %~]%(!.#.$) '

The precmd will be executed prior to every prompt being displayed, and can print information and set variables. It's frequently used to fill in the psvar array, which is easy to use in a zsh prompt. The zstyle command can be used to format the output from vcs_info.

Upvotes: 1

Related Questions