### Xterm title:

# The title is set in 2 occasions:
# 1 preexec -- during the run of a command
# 2 part of PROMPT -- during the CLI edit.

# In this file only 1 is implemented:

if false;
    then
# preexec hook shows command in title as it's running,
# and precmd sets it to something else when it's done.
    case $TERM in
        xterm*|screen*)
            preexec () {
                export CURRENTCMD="$1"
                print -Pn "\e]0;$1\a"
            }
            precmd () {
                if [[ ! -z $CURRENTCMD ]]; then
                    print -Pn "\e]0;($CURRENTCMD)\a"
                fi
            }
            ;;
    esac
fi



mytitle() {
# Use these two for GNU Screen:
#       dir=${pwd}
#    print -nR $'\033k'$1$'\033'\\
#	print -nR $'\033]0;'$2$'\a'

       # Use this one instead for XTerms:
    print -nR $'\033]0;'$LOGNAME"@"$HOST":"${TTY##*/}" "$PWD" "$*$'\a'
    #  $TTY!
}

# function precmd {
#     title zsh "$PWD"
# }

# function preexec {
#     emulate -L zsh
#     local -a cmd; cmd=(${(z)1})
#     title $cmd[1]:t "$cmd[2,-1]"
# }


if under_xterm;
    then
preexec() {
    emulate -L zsh

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

    # 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 $cmd[2])
            fi;;
        %*) cmd=(builtin jobs -l $cmd[1]);; # Same as "else" above
        *)  mytitle $cmd[1]:t "$cmd[2,-1]"    # Not resuming a job,
            return;;                        # so we're all done
    esac

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

    # 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}})
        mytitle $cmd[1]:t "$cmd[2,-1]") 2>/dev/null
}
fi
