summaryrefslogtreecommitdiff
path: root/conf.d/60-prompt.zsh
blob: c21aafc2d95f4941101ecf7f0f0bf058e5c9f44d (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
bindkey -e # emacs-style keybindings

setopt autocd

autoload -U zmv

setopt prompt_subst prompt_percent
autoload colors && colors

# wrap in %{%} to prevent zsh from counting the content towards
# the text length, leading to over-compensation for zero-width characters
zcol() {
  echo -n "%{$@%}"
}

timestamp() {
  echo $((`date "+%s + %N / 1e9"`))
}

elapsed() {
  echo $(($(timestamp) - $command_start_time))
}

duration=0
command_start_time=$(timestamp)
# called just before line is evaluated
preexec() {
  command_start_time=$(timestamp)
}

# called just before prompt is updated which
# is usually after the program ran, but also
# on ^C or Enter on an empty line
precmd() {
  duration=$(elapsed)
  command_start_time=$(timestamp)
}

git_prompt() {
  local git_branch=$(git branch 2>/dev/null | grep \* | sed 's/* //')
  # is in git repository if branch != ""
  if [[ -n "$git_branch" ]]; then
    # if no uncommitted changes
    if git diff-index --quiet HEAD --; then
      zcol "$fg[green]"
    else
      zcol "$fg[red]"
    fi
    echo -n "$git_branch "
  fi
}

left_prompt() {
  local last_status=$?

  case $USER in
    "$PRIMARY_USER" | "root") ;;
    *) echo -n $USER
  esac

  if test -n "$SSH_TTY" \
  || [ -f /.dockerenv ]; then
    zcol "$fg[cyan]"
    echo -n "@$(hostname | tr -d '\n') "
  fi

  zcol "$fg[green]"
  { pwd; echo -n " " } | tr -d '\n' | sed -e "s:^$HOME:~:"

  git_prompt

  case $USER in
    root) zcol "$fg[red]"; echo -n "# " ;;
    *)    zcol "$fg[blue]"; echo -n "> " ;;
  esac

  if [ "$last_status" -ne 0 ]; then
    zcol "$fg_bold[red]"
    echo -n "$last_status "
  fi

  zcol "$reset_color"
}

right_prompt() {
  command_start_time=$(timestamp)
  if (($duration > 0.99)); then
    zcol "$fg_bold[cyan]"
    printf "%.1fs" "$duration"
  fi

  zcol "$reset_color"
}

PROMPT='$(left_prompt)'
RPROMPT='$(right_prompt)'

bindkey "${terminfo[khome]}" beginning-of-line
bindkey "${terminfo[kend]}" end-of-line

bindkey '\eOA' history-substring-search-up # or ^[OA
bindkey '\eOB' history-substring-search-down # or ^[OB

export ZSH_AUTOSUGGEST_HIGHLIGHT_STYLE=fg=cyan