timer.plugin.zsh 1.02 KB
Newer Older
Marc Cornellà's avatar
Marc Cornellà committed
1
2
zmodload zsh/datetime

Robert Strack's avatar
Robert Strack committed
3
__timer_current_time() {
Marc Cornellà's avatar
Marc Cornellà committed
4
5
  zmodload zsh/datetime
  echo $EPOCHREALTIME
Robert Strack's avatar
Robert Strack committed
6
7
8
9
}

__timer_format_duration() {
  local mins=$(printf '%.0f' $(($1 / 60)))
10
  local secs=$(printf "%.${TIMER_PRECISION:-1}f" $(($1 - 60 * mins)))
Robert Strack's avatar
Robert Strack committed
11
  local duration_str=$(echo "${mins}m${secs}s")
Robert Strack's avatar
Robert Strack committed
12
13
  local format="${TIMER_FORMAT:-/%d}"
  echo "${format//\%d/${duration_str#0m}}"
Robert Strack's avatar
Robert Strack committed
14
15
}

Robert Strack's avatar
Robert Strack committed
16
__timer_save_time_preexec() {
Robert Strack's avatar
Robert Strack committed
17
  __timer_cmd_start_time=$(__timer_current_time)
18
19
}

Robert Strack's avatar
Robert Strack committed
20
__timer_display_timer_precmd() {
Robert Strack's avatar
Robert Strack committed
21
22
  if [ -n "${__timer_cmd_start_time}" ]; then
    local cmd_end_time=$(__timer_current_time)
Robert Strack's avatar
Robert Strack committed
23
    local tdiff=$((cmd_end_time - __timer_cmd_start_time))
24
    unset __timer_cmd_start_time
25
26
27
28
29
    if [[ -z "${TIMER_THRESHOLD}" || ${tdiff} -ge "${TIMER_THRESHOLD}" ]]; then
        local tdiffstr=$(__timer_format_duration ${tdiff})
        local cols=$((COLUMNS - ${#tdiffstr} - 1))
        echo -e "\033[1A\033[${cols}C ${tdiffstr}"
    fi
30
31
  fi
}
Robert Strack's avatar
Robert Strack committed
32

33
34
35
autoload -U add-zsh-hook
add-zsh-hook preexec __timer_save_time_preexec
add-zsh-hook precmd __timer_display_timer_precmd