aboutsummaryrefslogtreecommitdiff
path: root/optionals/.zshrc
blob: 9a65c33dbb6e53ff45b44ba5c18f6fbc57a34658 (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
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
# Interactive Zsh configuration.
[[ -o interactive ]] || return

# Standard environment
export XDG_CONFIG_HOME="${XDG_CONFIG_HOME:-$HOME/.config}"
export XDG_CACHE_HOME="${XDG_CACHE_HOME:-$HOME/.cache}"
export XDG_DATA_HOME="${XDG_DATA_HOME:-$HOME/.local/share}"
export XDG_STATE_HOME="${XDG_STATE_HOME:-$HOME/.local/state}"

export EDITOR="${EDITOR:-vim}"
export VISUAL="${VISUAL:-$EDITOR}"
export PAGER="${PAGER:-less}"
export LESS="${LESS:--R -F -X}"

# Keep PATH unique. In Zsh, $path is an array tied to $PATH.
typeset -gU path PATH

path_prepend() {
    [[ -n $1 ]] || return 2
    path=("$1" "${path[@]}")
}

path_append() {
    [[ -n $1 ]] || return 2
    path+=("$1")
}

path_append "$HOME/.local/bin"

# Defaults that may be overridden by this machine's local configuration.
PROMPT_SYMBOL="${PROMPT_SYMBOL:-λ}"

if [[ -r "$HOME/.zshrc.local" ]]; then
    source "$HOME/.zshrc.local"
fi

# Prompt ---------------------------------------------------------------------
autoload -Uz add-zsh-hook

__git_status_prompt() {
    emulate -L zsh

    local output='' line='' branch='' oid=''
    local -i dirty=0

    # One Git invocation provides the branch (or detached HEAD) and status.
    if ! output=$(command git status --porcelain=v2 --branch 2>/dev/null); then
        return
    fi

    while IFS= read -r line; do
        case "$line" in
            '# branch.head '*) branch=${line#\# branch.head } ;;
            '# branch.oid '*)  oid=${line#\# branch.oid } ;;
            '# '*) ;;
            *) dirty=1 ;;
        esac
    done <<< "$output"

    if [[ $branch == '(detached)' ]]; then
        branch="@${oid[1,7]}"
    fi

    # A literal percent must be doubled inside a Zsh prompt.
    branch=${branch//\%/%%}

    if (( dirty )); then
        print -r -- "%F{yellow}( %F{blue}${branch} %F{red}✗%F{yellow} )"
    else
        print -r -- "%F{yellow}( %F{blue}${branch} %F{green}✓%F{yellow} )"
    fi
}

__set_prompt() {
    local exit_status=$?
    local symbol=${PROMPT_SYMBOL//\%/%%}
    local git_prompt=$(__git_status_prompt)
    local marker

    if (( exit_status != 0 )); then
        marker="%F{red}${symbol}[${exit_status}] %f"
    else
        marker="%F{green}${symbol} %f"
    fi

    PROMPT="${marker}%F{magenta}%1~%F{yellow}${git_prompt} $ %f"
}

add-zsh-hook precmd __set_prompt
PROMPT="${PROMPT_SYMBOL} "

# Aliases --------------------------------------------------------------------
# Git
alias gc='git commit -m'
alias gaa='git add .'
alias gp='git push'
alias gl="git log --graph --abbrev-commit --decorate --format=format:'%C(bold blue)%h%C(reset) - %C(bold green)(%ar)%C(reset) %C(white)%s%C(reset) %C(dim white)- %an%C(reset)%C(bold yellow)%d%C(reset)' --all"
alias gchk='git checkout'
alias grefresh='git fetch --all && git pull'
alias gs='git status'

# Files and directories
alias ll='ls -lah'
alias lc='ls --color=never'
alias ls='ls --color=auto'
alias lt='ls -lAht'
alias ..='cd ..'
alias ...='cd ../..'
alias ....='cd ../../..'
alias mv='mv -i'
alias rm='rm -i'
alias cp='cp -i'

# Utilities
alias e='yazi'
alias ytd='yt-dlp'
alias grep='grep --color=auto'
alias lsblk='lsblk -fl'
alias genkey='ssh-keygen -t ed25519 -C "$(git config --get user.email)"'
alias ports='ss -tulnp'
alias myip='ip route get 1 | awk "{print \$7}" | head -1'
alias reload='source ~/.zshrc'

# Functions ------------------------------------------------------------------
mkcd() {
    mkdir -p -- "$1" && cd -- "$1"
}

croot() {
    local root

    if ! root=$(command git rev-parse --show-toplevel 2>/dev/null); then
        print -u2 'croot: not inside a Git repository'
        return 1
    fi

    cd -- "$root" || return
}

showpath() {
    print -l -- "${path[@]}"
}

serve() {
    local port=${1:-8000}
    python -m http.server "$port"
}

extract() {
    if (( $# != 1 )); then
        print -u2 'Usage: extract ARCHIVE'
        return 2
    fi

    local archive=$1
    [[ $archive == -* ]] && archive="./$archive"

    if [[ ! -f $archive ]]; then
        print -u2 -- "extract: $1 is not a regular file"
        return 1
    fi

    case "$archive" in
        *.tar.gz|*.tgz)  tar xzf "$archive" ;;
        *.tar.bz2|*.tbz) tar xjf "$archive" ;;
        *.tar.xz)        tar xJf "$archive" ;;
        *.tar)           tar xf "$archive" ;;
        *.zip)           unzip "$archive" ;;
        *.gz)            gunzip "$archive" ;;
        *.bz2)           bunzip2 "$archive" ;;
        *.xz)            unxz "$archive" ;;
        *.rar)           unrar x "$archive" ;;
        *) print -u2 -- "extract: unknown archive format: $1"; return 1 ;;
    esac
}

psf() {
    if (( $# != 1 )); then
        print -u2 'Usage: psf PATTERN'
        return 2
    fi

    pgrep -af -- "$1"
}

bak() {
    if (( $# != 1 )); then
        print -u2 'Usage: bak FILE'
        return 2
    fi

    if [[ ! -e $1 ]]; then
        print -u2 -- "bak: $1 does not exist"
        return 1
    fi

    command cp -- "$1" "$1.$(date +%Y%m%d_%H%M%S).bak"
}

rchmod() {
    if (( $# != 2 )) || [[ -z $2 ]]; then
        print -u2 'Usage: rchmod {f|d} MODE'
        return 2
    fi

    if [[ $1 != f && $1 != d ]]; then
        print -u2 'Usage: rchmod {f|d} MODE'
        return 2
    fi

    if [[ ! $2 =~ '^[0-7]{3,4}$' ]]; then
        print -u2 -- "Invalid mode: $2"
        return 2
    fi

    find . -type "$1" -exec chmod -- "$2" {} +
}

alias rchmodd='rchmod d 755'
alias rchmodf='rchmod f 644'
alias fixperm='rchmodd; rchmodf'

sshlk() {
    if (( $# != 1 )); then
        print -u2 'Usage: sshlk KEY_NAME'
        return 2
    fi

    local key="$HOME/.ssh/$1"
    if [[ ! -f $key ]]; then
        print -u2 -- "sshlk: key does not exist: $key"
        return 1
    fi

    local agent
    local -i agent_status

    if [[ -n ${SSH_AUTH_SOCK:-} ]]; then
        ssh-add -l >/dev/null 2>&1
        agent_status=$?
    else
        agent_status=2
    fi

    # ssh-add returns 1 when an agent exists but currently has no identities.
    if (( agent_status != 0 && agent_status != 1 )); then
        if ! agent=$(ssh-agent -s); then
            print -u2 'sshlk: could not start ssh-agent'
            return 1
        fi
        eval "$agent"
    fi

    ssh-add -- "$key"
}

smount() {
    if (( $# != 1 )); then
        print -u2 'Usage: smount DEVICE'
        return 2
    fi

    udisksctl mount -b "$1"
}

sumount() {
    if (( $# != 1 )); then
        print -u2 'Usage: sumount DEVICE'
        return 2
    fi

    udisksctl unmount -b "$1" && udisksctl power-off -b "$1"
}

# History --------------------------------------------------------------------
HISTFILE="${ZDOTDIR:-$HOME}/.zsh_history"
# Keep some in-memory headroom so duplicate expiry works before saving.
HISTSIZE=250000
SAVEHIST=200000

setopt EXTENDED_HISTORY
setopt SHARE_HISTORY
setopt HIST_EXPIRE_DUPS_FIRST
setopt HIST_FIND_NO_DUPS
setopt HIST_IGNORE_ALL_DUPS
setopt HIST_IGNORE_DUPS
setopt HIST_IGNORE_SPACE
setopt HIST_REDUCE_BLANKS
setopt HIST_SAVE_NO_DUPS
setopt HIST_VERIFY

# General interactive behavior
setopt INTERACTIVE_COMMENTS
setopt COMPLETE_IN_WORD
setopt NO_BEEP

# Completion and line editor --------------------------------------------------
autoload -Uz compinit
mkdir -p -- "$XDG_CACHE_HOME/zsh"
compinit -d "$XDG_CACHE_HOME/zsh/zcompdump-${ZSH_VERSION}"

zstyle ':completion:*' matcher-list 'm:{a-zA-Z}={A-Za-z}'
zstyle ':completion:*' menu select
zstyle ':completion:*' group-name ''
zstyle ':completion:*' use-cache true
zstyle ':completion:*' cache-path "$XDG_CACHE_HOME/zsh/completion-cache"
if [[ -n ${LS_COLORS:-} ]]; then
    zstyle ':completion:*' list-colors "${(s.:.)LS_COLORS}"
fi

bindkey -e
autoload -Uz up-line-or-beginning-search down-line-or-beginning-search
zle -N up-line-or-beginning-search
zle -N down-line-or-beginning-search
bindkey '^[[A' up-line-or-beginning-search
bindkey '^[[B' down-line-or-beginning-search

# Optional integrations ------------------------------------------------------
# fzf's widgets require a real terminal/ZLE session.
if (( $+commands[fzf] )) && [[ -t 0 ]]; then
    if (( $+commands[rg] )); then
        export FZF_DEFAULT_COMMAND='rg --files --hidden --follow --glob "!.git"'
        export FZF_CTRL_T_COMMAND="$FZF_DEFAULT_COMMAND"
    fi

    export FZF_DEFAULT_OPTS='
      --height 40%
      --layout=reverse
      --border
      --preview "if [ -d {} ]; then ls -la -- {}; elif command -v bat >/dev/null 2>&1; then bat --style=numbers --color=always --line-range :500 -- {}; else head -n 500 -- {}; fi"
      --preview-window=right:50%:wrap
    '

    source <(fzf --zsh)
fi

if (( $+commands[zoxide] )); then
    eval "$(zoxide init zsh)"
fi

# Random text art on shell startup.
if (( $+commands[rndtxtart] )); then
    rndtxtart
fi