Skip to content
This repository has been archived by the owner on Apr 24, 2020. It is now read-only.

User Segments

MatthewAlner edited this page Jun 1, 2019 · 14 revisions

Did you come up with a cool segment that isn't yet ready to contribute to the powerlevel9k codebase, but that you still want to share? Put them here!

Battery Status (MacOS only)

I felt that the built-in battery status in powerlevel9k was a bit too large and had too much extra info, so I created my own.

Keep in mind, this requires a font patched with Font Awesome (for one of the versions) or Material Icons (for the other).

To install, paste the one that is compatible with your icon set into your zshrc. Then, add POWERLEVEL9K_CUSTOM_BATTERY_STATUS="prompt_zsh_battery_level" to your zshrc. After that, simply add custom_battery_status to one of your prompts.

Demo

(Image shows Material Icons Version)

Material Icons Version

prompt_zsh_battery_level() {
    local percentage1=`pmset -g ps  |  sed -n 's/.*[[:blank:]]+*\(.*%\).*/\1/p'`
  local percentage=`echo "${percentage1//\%}"`
  local color='%F{red}'
  local symbol="\uf00d"
  pmset -g ps | grep "discharging" > /dev/null
  if [ $? -eq 0 ]; then
    charging="false";
  else
    charging="true";
  fi
  if [ $percentage -le 20 ]
  then symbol='\uf579' ; color='%F{red}' ;
    #10%
  elif [ $percentage -gt 19 ] && [ $percentage -le 30 ]
  then symbol="\uf57a" ; color='%F{red}' ;
    #20%
  elif [ $percentage -gt 29 ] && [ $percentage -le 40 ]
  then symbol="\uf57b" ; color='%F{yellow}' ;
    #35%
  elif [ $percentage -gt 39 ] && [ $percentage -le 50 ]
  then symbol="\uf57c" ; color='%F{yellow}' ;
    #45%
  elif [ $percentage -gt 49 ] && [ $percentage -le 60 ]
  then symbol="\uf57d" ; color='%F{blue}' ;
    #55%
  elif [ $percentage -gt 59 ] && [ $percentage -le 70 ]
  then symbol="\uf57e" ; color='%F{blue}' ;
    #65%
  elif [ $percentage -gt 69 ] && [ $percentage -le 80 ]
  then symbol="\uf57f" ; color='%F{blue}' ;
    #75%
  elif [ $percentage -gt 79 ] && [ $percentage -le 90 ]
  then symbol="\uf580" ; color='%F{blue}' ;
    #85%
  elif [ $percentage -gt 89 ] && [ $percentage -le 100 ]
  then symbol="\uf581" ; color='%F{blue}' ;
    #85%
  elif [ $percentage = 100 ]
  then symbol="\uf578" ; color='%F{green}' ;
    #100%
  fi
  if [ $charging = "true" ];
  then color='%F{green}'; if [ $percentage = 100 ]; then symbol='\uf584'; fi
  fi
  echo -n "%{$color%}$symbol" ;
}

Font Awesome Version

prompt_zsh_battery_level() {
    local percentage=`pmset -g ps  |  sed -n 's/.*[[:blank:]]+*\(.*%\).*/\1/p'`
    local percentage=`echo "${percentage//\%}"`
    local color='%F{red}'
    local symbol="\uf00d"
if [ $(bc <<< "scale=2 ; $percentage<25") = '1' ]
    then symbol="\uf244" ; color='%F{red}' ;
        #Less than 25
        fi
        
if [ $(bc <<< "scale=2 ; $percentage>=25") = '1' ] && [ $(bc <<< "scale=2 ; $percentage<50") = '1' ]
    then symbol='\uf243' ; color='%F{red}' ;
    #25%
    fi
if [ $(bc <<< "scale=2 ; $percentage>=50") = '1' ] && [ $(bc <<< "scale=2 ; $percentage<75") = '1' ]  
     then symbol="\uf242" ; color='%F{yellow}' ;
     #50%
     fi
if [ $(bc <<< "scale=2 ; $percentage>=75") = '1' ] && [ $(bc <<< "scale=2 ; $percentage<100") = '1' ]
        then symbol="\uf241" ; color='%F{blue}' ;
        #75%
        fi  
 
if [ $(bc <<< "scale=2 ; $percentage>99") = '1' ]
        then symbol="\uf240" ; color='%F{green}' ;
        #100%
        fi
pmset -g ps | grep "discharging" >& /dev/null
if [ $? -eq 0 ]; then
    true;
else ;
   color='%F{green}' ;
fi
echo -n "%{$color%}$symbol" ;
}

TaskWarrior Segment

This segment came from #455, and has the neat functionality of updating a multi-line segment based on the TaskWarrior status.

pltask demo

TaskWarrior Download/Build/Install Docs

link to pltask github gist (Star it if you end up using it! 😄)

#pltask functions
## pltask is a lightweight facade to taskwarrior for use with Powerlevel9k's Last Prompt Prefix (by dmidlo @querentCode)
## Be sure to set search.case.sensitive=no within .taskrc
POWERLEVEL9K_PROMPT_ON_NEWLINE=true
POWERLEVEL9K_PROMPT_ADD_NEWLINE=true
POWERLEVEL9K_MULTILINE_FIRST_PROMPT_PREFIX="\n"

pltask () {
    setNewlinePrompt () {
        POWERLEVEL9K_MULTILINE_LAST_PROMPT_PREFIX="%K{white}%F{black}\n $1 %f%k%F{white}%f $ "
    }

    if [ -n "$3" ]; then
        echo "pltask only supports two args. did\nyou remember to use quotes when\ncreating a task?"
        return 1
    elif [ -z "$1" ]; then
        export PLTASK=`task _get 1.description`
        if [ -z "$PLTASK" ]; then
            echo "no tasks in queue, go do something else"
            echo "Setting pltask to '.' "
            setNewlinePrompt "."
        else
            echo "Setting pltask to first task from taskwarrior:" $PLTASK
            setNewlinePrompt $PLTASK
        fi
    elif [[ $1 = "_print" || $1 = "_p" ]]; then
         echo $PLTASK
    elif [[ $1 = "help" || $1 = "h" ]]; then
        echo "\n pltask is a lightweight facade to taskwarrior for use with Powerlevel9k's Last Prompt Prefix\n"
        echo   Options:
        echo -----------------------------------------------------------------------------
        echo   "  No args           ---   Calls first available task from taskwarrior."
        echo   "  help              ---   h - This help dialog."
        echo   "  list              ---   ls - A Wrapper for \'task next\'."
        echo   "  set  <taskID>     ---   s - Sets the pltask prompt to description of specified task id."
        echo   "  done              ---   d - Completes the current task and sets pltask to next task."
        echo   "  \"string\"          ---       \"string\" with no additional arguments, sets the pltask prompt but no new task."
        echo   "  \"string\" add      ---   a - \"string\" followed by 'add' will set the pltask and add a new task to taskwarrior.\n\n"
        echo   Examples:
        echo "-----------------------------------------------------------------------------\n"
        echo "   Create a task:"
        echo "      $ pltask \"Edit Super Cool Project\" add"
        echo "      $ pltask \"Write Blog Post\" a"
    elif [[ $1 = "list" || $1 = "ls" ]]; then
        task next
    elif [[ $1 = "set" || $1 = "s" ]]; then
        export PLTASK=`task _get $2.description`
        if [ -z "$PLTASK" ]; then
            export PLTASK=`task _get 1.description`
            if [ -z "$PLTASK" ]; then
                pltask
            else
                echo "no task with id $2 in queue"
                echo "Setting pltask to first available task: " $PLTASK
                setNewlinePrompt $PLTASK
            fi
        else
            echo "Setting pltask to task id $2:" $PLTASK
            setNewlinePrompt $PLTASK
        fi
    elif [[ $1 = "done" || $1 = "d" ]]; then
        task /$PLTASK/ done
        task
        export PLTASK=`task _get 1.description`
        if [ -z "$PLTASK" ]; then
                pltask
        else
            echo "Setting pltask to next task: "$PLTASK
            setNewlinePrompt $PLTASK
        fi
    elif [ -z "$2" ]; then
        setNewlinePrompt $1
        echo "terminal pltask set to " $1 "But no task has been created"
    elif [[ $2 = "add" || $2 = "a" ]]; then
        export PLTASK="$1"
        task "$1" add
        task
        setNewlinePrompt $1
    fi
}
# Initial state
pltask "."

WiFi on OSX

POWERLEVEL9K_CUSTOM_WIFI_SIGNAL="zsh_wifi_signal"
POWERLEVEL9K_CUSTOM_WIFI_SIGNAL_BACKGROUND="blue"
POWERLEVEL9K_CUSTOM_WIFI_SIGNAL_FOREGROUND="yellow"

zsh_wifi_signal(){
        local output=$(/System/Library/PrivateFrameworks/Apple80211.framework/Versions/A/Resources/airport -I) 
        local airport=$(echo $output | grep 'AirPort' | awk -F': ' '{print $2}')

        if [ "$airport" = "Off" ]; then
                local color='%F{yellow}'
                echo -n "%{$color%}Wifi Off"
        else
                local ssid=$(echo $output | grep ' SSID' | awk -F': ' '{print $2}')
                local speed=$(echo $output | grep 'lastTxRate' | awk -F': ' '{print $2}')
                local color='%F{yellow}'

                [[ $speed -gt 100 ]] && color='%F{green}'
                [[ $speed -lt 50 ]] && color='%F{red}'

                echo -n "%{$color%}$ssid $speed Mb/s%{%f%}" # removed char not in my PowerLine font 
        fi
}

Current iTunes(OSX) / Spotify(Ubuntu) Track

This segment reads the current Artist and Track from iTunes via osascript or fetches the data from Spotify using sp, a command line client by Wandernauta for Spotify on dbus

Screenshot

Create a .nowplaying file in your $HOME folder and make it executable with chmod +x

  • Ubuntu/Debian: If you are using Spotify on Ubuntu/Debian (or probably any other Linux distribution using dbus) download the sp script and make it executable
wget -O $HOME/sp https://gist.githubusercontent.com/wandernauta/6800547/raw/2c2ad0f3849b1b1cd1116b80718d986f1c1e7966/sp
chmod +x $HOME/sp
  • OSX: Create a new file (~/current-itunes-track in this example) and add this applescript
if application "iTunes" is running then
	tell application "iTunes"
		if player state is playing then
			return artist of current track & " - " & name of current track
		end if
	end tell
end if
  • Both: Add the following code to the .nowplaying file
#!/bin/bash
if [ `uname` = "Darwin" ]; then
  track="$(osascript ~/current-itunes-track)"
  if [ "$track" ]; then
    echo "\uF001 $track"
  fi
else
  track="$(~/.dotfiles/bin/sp current | sed '3q;d' | awk '{$1=""; print $0}' | sed 's/^ *//g' | sed 's/ *$//g') - $(~/.dotfiles/bin/sp current | sed '4q;d' | awk '{$1=""; print $0}' | sed 's/^ *//g' | sed 's/ *$//g')"
  if [ "$track" ]; then
    echo "\uF001 $track"
  fi
fi

In your .zshrc add the following code

POWERLEVEL9K_CUSTOM_NOW_PLAYING='~/.nowplaying'
POWERLEVEL9K_CUSTOM_NOW_PLAYING_BACKGROUND='blue'
POWERLEVEL9K_CUSTOM_NOW_PLAYING_FOREGROUND='black'

Now you can add this segment as custom_now_playing to your prompt

Github Issues for the current Project Directory

Screenshot

This segment will fetch open issues from your upstream repository on Github if:

  1. A .git folder is present in your current directory
  2. Upsteam/Origin is a legit Github Repository

Prerequisites

  1. autoenv from Tarrasch/zsh-autoenv (with antigen: antigen bundle Tarrasch/zsh-autoenv)
  2. jqa json parser for your shell: https://stedolan.github.io/jq/

Setup

Create an executable file (~/gh-issues.zsh for this example) and paste the following code into it:

#!/usr/bin/env zsh

git_url=$(git remote get-url origin)
repo=$(echo $( echo "$git_url" | perl -pne 's/^.*.com(?:\/|:)(.*)$/$1/g') | sed 's/.git//')
if [[ -d .git ]] && [[ "$git_url" = *'github.com'* ]]; then
    curl -s "https://api.github.com/repos/$repo/issues" | jq '. | length'
fi

In your Project, add the following .autoenv.zsh and .autoenv_leave.zsh (these two must be executable as well)

# .autoenv.zsh

if [[ -e ~/.dotfiles/bin/github_issues ]]; then
	git_url=$(git remote get-url origin)
	if [[ -d .git ]] && [[ "$git_url" = *'github.com'* ]]; then
		echo "Fetching Github Issues..."
		issues=$(~/gh_issues.zsh)
		if (( issues > 0 )); then
			echo "$(~/.dotfiles/bin/github_issues)" > .issues
		fi
	fi
fi
# .autoenv_leave.zsh

if [[ -e $OLDPWD/.issues ]]; then
  rm $OLDPWD/.issues
fi

If you enter or leave the directory for the first time you will be prompted if you want to execute the scripts, after that you do not have to confirm this again.

Segment Activation

Add the following snippet to your .zshrc

# Custom segment "github issues"
POWERLEVEL9K_CUSTOM_GITHUB_ISSUES='if [ -e ./.issues ]; then echo "\uF41B $(/bin/cat ./.issues)"; fi'
POWERLEVEL9K_CUSTOM_GITHUB_ISSUES_BACKGROUND='$POWERLEVEL9K_VCS_CLEAN_BACKGROUND'
POWERLEVEL9K_CUSTOM_GITHUB_ISSUES_FOREGROUND='$POWERLEVEL9K_VCS_CLEAN_FOREGROUND'

Now you can add this segment to your prompt with custom_github_issues

Notes

  1. This will run every time you enter a git-controlled directory with github remote
  2. You will have a new file in your directory .issues which saves the result from the last github-api call
  3. You probably might want to add /.autoenv* and /.issues to your .gitignore to avoid committing those files
  4. You can setup a simple function to symlink the .autoenv files into your current directory. With a symlink you do not need to confirm every new .autoenv file once you initialised your project:
function autoenv_init()
{
	ln -s ~/path/to/your/.autoenv.zsh .autoenv.zsh
	ln -s ~/path/to/your/.autoenv_leave.zsh .autoenv_leave.zsh
}

In link directory

For some tasks I found it useful to know whether the current directory was a symlink. I added a simple prompt flag that indicated the status with a single character icon.

POWERLEVEL9K_DIR_LINK_ICON="\uf838" #
POWERLEVEL9K_DIR_LINK_FOREGROUND=$POWERLEVEL9K_DIR_FOREGROUND
POWERLEVEL9K_DIR_LINK_BACKGROUND=$POWERLEVEL9K_DIR_BACKGROUND

prompt_dir_link() {
    if [ -h `pwd` ] ; then
	echo -n "$POWERLEVEL9K_DIR_LINK_ICON "
    else
	echo -n "";
    fi
}

A "built with" segment showing framework/language/library/build-tool icons.

powerlevel9k-built-with-segment example

powerlevel9k-built-with-segment shows icons and optionally version numbers for framework/language/library/build-tool your project is built with.

It's easily configurable via a json file so you can add your own rules, icons and whether to show a version number or not.

More info in the README