timer.plugin.zsh 1.1 KB

1234567891011121314151617181920212223242526272829303132333435363738
  1. zmodload zsh/datetime
  2. __timer_current_time() {
  3. zmodload zsh/datetime
  4. echo $EPOCHREALTIME
  5. }
  6. __timer_format_duration() {
  7. local mins=$(printf '%.0f' $(($1 / 60)))
  8. local secs=$(printf "%.${TIMER_PRECISION:-1}f" $(($1 - 60 * mins)))
  9. local duration_str=$(echo "${mins}m${secs}s")
  10. local format="${TIMER_FORMAT:-/%d}"
  11. echo "${format//\%d/${duration_str#0m}}"
  12. }
  13. __timer_save_time_preexec() {
  14. __timer_cmd_start_time=$(__timer_current_time)
  15. }
  16. __timer_display_timer_precmd() {
  17. if [ -n "${__timer_cmd_start_time}" ]; then
  18. local cmd_end_time=$(__timer_current_time)
  19. local tdiff=$((cmd_end_time - __timer_cmd_start_time))
  20. unset __timer_cmd_start_time
  21. if [[ -z "${TIMER_THRESHOLD}" || ${tdiff} -ge "${TIMER_THRESHOLD}" ]]; then
  22. local last_cmd="${history[$((HISTCMD - 1))]%% *}"
  23. if [[ "$last_cmd" != clear ]]; then
  24. local tdiffstr=$(__timer_format_duration ${tdiff})
  25. local cols=$((COLUMNS - ${#tdiffstr} - 1))
  26. echo -e "\033[1A\033[${cols}C ${tdiffstr}"
  27. fi
  28. fi
  29. fi
  30. }
  31. autoload -U add-zsh-hook
  32. add-zsh-hook preexec __timer_save_time_preexec
  33. add-zsh-hook precmd __timer_display_timer_precmd