romkatv / powerlevel10k

A Zsh theme
MIT License
46.59k stars 2.19k forks source link

How to return default segment inside custom function? #1367

Closed sahinakkaya closed 3 years ago

sahinakkaya commented 3 years ago

I want to show battery segment based on a condition. I know I can hide if it is above a threshold value by setting POWERLEVEL9K_BATTERY_HIDE_ABOVE_THRESHOLD and I know I can write a custom segment which displays battery information. But I want to use the default battery segment. Consider the following pseudocode:

func prompt_example()
    if ...
         return default_battery_segment_so_I_dont_need_to_do_anything
    else
         do_nothing

How can I achieve this? Sorry if this is something basic but I couldn't find any example about this.

romkatv commented 3 years ago

Instead of a custom prompt segment, write a precmd hook that hides/shows the regular battery segment. See p10k help display.

sahinakkaya commented 3 years ago

I ended up putting the below code to my .zshrc and it worked:

# https://github.com/rothgar/mastering-zsh/blob/master/docs/config/hooks.md
function hide_battery_inside_tmux() {
  if ! [ -n "$TMUX" ]; then
    p10k display '*/battery'=show
  else
    p10k display '*/battery'=hide
  fi
}

typeset -a precmd_functions
precmd_functions+=(hide_battery_inside_tmux)

Thanks!

romkatv commented 3 years ago

Oh, that condition is static, so it's much easier (and faster) to change your ~/.p10k.zsh like this:

  1. Remove battery from POWERLEVEL9K_RIGHT_PROMPT_ELEMENTS.
  2. Add this line:
    [[ -n $TMUX ]] || POWERLEVEL9K_RIGHT_PROMPT_ELEMENTS+=(battery)
sahinakkaya commented 3 years ago

Yeah, this is much better! I know very little (nothing?) about bash/zsh scripting so I couldn't think of this one :D Thanks again!