--- /dev/null
+#
+# Fancy setting of the xterm title
+#
+# Copyright © 1994–2017 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
+#
+
+autoload -U add-zsh-hook
+
+__set_xterm_title() {
+ emulate -L zsh
+ 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() {
+ emulate -L zsh
+ [ -n "$SSH_CONNECTION" ] || return
+ local flags
+ [ -n "$DISPLAY" ] && flags+=x
+ [ -n "$SSH_AUTH_SOCK" ] && flags+=a
+ [[ $SSH_CLIENT = *:* ]] && flags+=6
+ [ -n "$flags" ] && echo "[${flags}]"
+}
+
+__get_standard_prompt() {
+ emulate -L zsh
+ [[ -z $SSH_CLIENT ]] || print -nP "%m"
+ print -P "%#%25\<..\<%~ $(__get_session_flags)"
+}
+
+_set_plain_xterm_title() {
+ emulate -L zsh
+ __set_xterm_title "$(__get_standard_prompt)"
+}
+add-zsh-hook precmd _set_plain_xterm_title
+
+_set_cmd_xterm_title () {
+ emulate -L zsh
+ 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 2>/dev/null >>(read num rest; cmd=(${(z)${(e):-\$jt$num}};)
+ __set_xterm_title $leader$cmd[1]:t${cmd[2]:+ }$cmd[2,-1] "| $(__get_standard_prompt)"
+)
+}
+add-zsh-hook preexec _set_cmd_xterm_title
+
+# vim:ft=zsh