# zterm-title
#
# Fancy setting of the xterm title
#
# Copyright © 1994–2008 martin f. krafft <madduck@madduck.net>
# Released under the terms of the Artistic Licence 2.0
#
# Source repository: http://git.madduck.net/v/etc/zsh.git
#
# Based on http://www.zshwiki.org/cgi-bin/wiki.pl?ZshHardStatus
#

__set_xterm_title() {
  case $TERM in
    screen)
      print -nR $'\033k'$1$'\033'\\ 
      print -nR $'\033]0;'$2$'\a'
      ;;
    xterm|rxvt*)
      print -nR $'\033]0;'$*$'\a'
      ;;
  esac
}

__get_session_flags() {
  [ -n "$SSH_CONNECTION" ] || return
  local flags; flags=
  [ -n "$DISPLAY" ] && flags="${flags}x"
  [ -n "$SSH_AUTH_SOCK" ] && flags="${flags}a"
  [ -n "$flags" ] && echo "[${flags}]"
}

__get_standard_prompt() {
  print -P "%m%#%25\<..\<%~ $(__get_session_flags)"
}

_set_plain_xterm_title() {
  __set_xterm_title "$(__get_standard_prompt)"
}
precmd_functions+=_set_plain_xterm_title

_set_cmd_xterm_title () {
    local -a cmd; cmd=(${(z)1})             # Re-parse the command line

    # Construct a command that will output the desired job number.
    case $cmd[1] in
        fg) if (( $#cmd == 1 )); then
                # No arguments, must find the current job
                cmd=(builtin jobs -l %+)
            else
                # Replace the command name, ignore extra args.
                cmd=(builtin jobs -l ${(Q)cmd[2]})
            fi;;
        %*) cmd=(builtin jobs -l ${(Q)cmd[1]});; # Same as "else" above
        *) # Not resuming a job,
            __set_xterm_title $cmd[1]:t${cmd[2]:+ }$cmd[2,-1] "| $(__get_standard_prompt)"
            return;;                        # so we're all done
    esac

    local -A jt; jt=(${(kv)jobtexts})       # Copy jobtexts for subshell

    # Run the command, read its output, and look up the jobtext.
    # Could parse $rest here, but $jobtexts (via $jt) is easier.
    $cmd >>(
              read num rest
              cmd=(${(z)${(e):-\$jt$num}})
              __set_xterm_title $leader$cmd[1]:t${cmd[2]:+ }$cmd[2,-1] "| $(__get_standard_prompt)"
           )
}
preexec_functions+=_set_cmd_xterm_title

# vim:ft=zsh