[Home] Zsh logo

two_line_prompt

Zsh Wizard

Download two_line_prompt Return to Examples
  1. # The following function generates a two-line PS1 prompt. It uses two new
  2. # array variables, abovePS1 and aboveRPS1, either of which may be empty or
  3. # unset. Each of these is a series of prompt segments that should appear,
  4. # obviously, above the regular PS1 and RPS1 prompts. (I generally prefer to
  5. # put the extra info in the xterm title bar, but when not using an xterm
  6. # this can be handy.)
  7. #
  8. # To use the two-line prompt:
  9. #
  10. # function precmd() {
  11. # two_line_prompt
  12. # }
  13. abovePS1=(%m %n %~)
  14. aboveRPS1=(%W %@ tty%l) # Remember, display is reversed to tty%l %@ %W.
  15. realPS1=$PS1 # Save the original PS1 for later use
  16. two_line_prompt() {
  17. local fakePS1="" fakeRPS1="" p P
  18. for p in $abovePS1
  19. do
  20. # Compute the width of each abovePS1 segment. If the total
  21. # width so far is wider than the screen, omit the segment.
  22. P=$(print -nP $p)
  23. if [[ $[$#fakePS1+$#P] -lt $[$COLUMNS-1] ]]
  24. then fakePS1="${fakePS1:+$fakePS1 }$P"
  25. fi
  26. done
  27. for p in $aboveRPS1
  28. do
  29. # Add in the width of each aboveRPS1 segment. If the total
  30. # width so far is wider than the screen, omit the segment.
  31. P=$(print -nP $p)
  32. if [[ $[$#fakePS1+$#fakeRPS1+$#P] -lt $COLUMNS-1 ]]
  33. then fakeRPS1="$P${fakeRPS1:+ $fakeRPS1}"
  34. fi
  35. done
  36. if [[ $[$#fakePS1+$#fakeRPS1] -gt 0 ]]
  37. then
  38. # Reset fakeRPS1 to use right-justified display (typeset -R) at
  39. # the correct width to push it to the right edge of the screen.
  40. local -R $[$COLUMNS-$#fakePS1-1] fakeRPS1="$fakeRPS1"
  41. # Prefix PS1 with the first line of the two-line prompt.
  42. PS1="$fakePS1$fakeRPS1
  43. $realPS1"
  44. else PS1=$realPS1
  45. fi
  46. }