-
Notifications
You must be signed in to change notification settings - Fork 1
/
functions
624 lines (544 loc) · 18.1 KB
/
functions
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
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
#!/usr/bin/env zsh
# __ _ _
# / _| _ _ _ __ ___ | |_ (_) ___ _ __ ___
# | |_ | | | || '_ \ / __|| __|| | / _ \ | '_ \ / __|
# | _|| |_| || | | || (__ | |_ | || (_) || | | |\__ \
# |_| \__,_||_| |_| \___| \__||_| \___/ |_| |_||___/
#
# =================================================================
# Utilities
# =================================================================
yes_or_no() {
while true; do
read yn"?$* [y/n]: "
case $yn in
[Yy]*) return 0 ;;
[Nn]*) echo "Aborted" ; return 1 ;;
esac
done
}
# =================================================================
# Applications
# =================================================================
# Try to find word in dictionary, remove clutter from output
aj() {
dict -d fd-eng-ces "$1" | grep -v '^From ' | grep -v '^\s*$' | grep -v "Entry edited" | grep -v '[0-9] def' | grep -v "$1" | sed 's/()//'
}
cs() {
dict -d fd-ces-eng "$1" | grep -v '^From ' | grep -v '^\s*$' | grep -v "Entry edited" | sed 's/()//'
}
eng() {
dict -d gcide "$1" | grep -v '^From ' | grep -v '^$' | sed 's/()//'
}
# Change current directory according to Ranger
ra() {
tempfile="$(mktemp)"
/usr/bin/ranger --choosedir="$tempfile" "${@:-$(pwd)}"
test -f "$tempfile" &&
if [ "$(cat -- "$tempfile")" != "$(echo -n `pwd`)" ]; then
cd -- "$(cat "$tempfile")"
fi
rm -f -- "$tempfile"
}
# Browse images
images() {
feh \
--image-bg black \
--geometry 1600x1000 \
--auto-zoom \
--title "%u/%l | %n | %wx%h | %S" \
--info ";indentify %F" \
--hide-pointer \
--action ";i3-msg 'workspace 6: ' && gthumb %F >/dev/null 2>&1"
}
# Browser history
bhistory() {
local cols sep google_history open
cols=$(( COLUMNS / 3 ))
sep='{::}'
google_history="$HOME/.config/google-chrome/Default/History"
open=xdg-open
cp -f "$google_history" /tmp/h
sqlite3 -separator $sep /tmp/h \
"select substr(title, 1, $cols), url
from urls order by last_visit_time desc" | \
awk -F $sep '{printf "%-'$cols's \x1b[36m%s\x1b[m\n", $1, $2}' | \
fzf --ansi --multi | sed 's#.*\(https*://\)#\1#' | xargs $open 2&>1 >/dev/null
}
s() {
local search
search="$1"
[ -z "$1" ] && read "search?Search: "
( node -pe "encodeURIComponent(\"$search\")" | xargs -I{} xdg-open "https://duckduckgo.com/?q={}" &>/dev/null & )
}
# =================================================================
# Files
# =================================================================
# Just open the file as you can
open() {
( xdg-open "$1" &>/dev/null & )
}
# Open text files in current terminal, other files separately
open_smart() {
if [[ -f "$1" ]]; then
name="$1"
# make sure the access time of the file is updated
touch -a -t $(date +%Y%m%d%H%M.%S) $name
if [[ $WSL = true ]]; then # on WSL
WINDOWS_PATH="$(wslpath -s -w "$name")"
if [[ ! $(file --brief --mime-type "$name") =~ "text.*" ]]; then
cmd.exe /c "start "" "$WINDOWS_PATH""
else
gvim.exe "$WINDOWS_PATH" 2>/dev/null
fi
else # on Unix
if file -L "$name" | grep -q text ; then
# open text files in editor
${EDITOR:-vim} $name
else
# open separately, suppress output and don't exit when
# parent terminal exits
( xdg-open "$name" &>/dev/null & )
fi
fi
elif [[ -d "$1" ]]; then
( xdg-open "$1" &>/dev/null & )
else
echo "No file called '$name' found."
fi
}
o() { open_smart "$1" }
# Locate documents (pdfs, ms office, open doc)
locate_documents() {
# only from /home/user folder, exclude hidden files in home folder
# based on extension, with last character optional (like .docx)
local RE="\/home\/$USER\/[^\.].*\.\(pdf\|doc\|xls\|ppt\|odt\|ods\|odp\).\?$"
locate --ignore-case --regexp $RE
}
# Locate text files and scripts
locate_text_files() {
# only from /home/user folder, exclude hidden files in home folder
# based on extension
local RE="\/home\/$USER\/[^\.].*\.\(txt\|md\|sh\|bash\|zsh\|conf\)$"
locate --ignore-case --regexp $RE
}
# Open a document found in home and selected by fzf
open_doc() {
open_smart "$(locate_documents | fzf)"
}
# Open a text file found in home and selected by fzf
open_file() {
open_smart "$(locate_text_files | fzf)"
}
# Extract any archive file
# Source https://github.com/xvoland/Extract
extract() {
if [ -z "$1" ]; then
# display usage if no parameters given
echo "Usage: extract <path/file_name>.<zip|rar|bz2|gz|tar|tbz2|tgz|Z|7z|xz|ex|tar.bz2|tar.gz|tar.xz>"
else
if [ -f "$1" ] ; then
local nameInLowerCase=`echo "$1" | awk '{print tolower($0)}'`
case "$nameInLowerCase" in
*.tar.bz2) tar xvjf ./"$1" ;;
*.tar.gz) tar xvzf ./"$1" ;;
*.tar.xz) tar xvJf ./"$1" ;;
*.lzma) unlzma ./"$1" ;;
*.bz2) bunzip2 ./"$1" ;;
*.rar) unrar x -ad ./"$1" ;;
*.gz) gunzip ./"$1" ;;
*.tar) tar xvf ./"$1" ;;
*.tbz2) tar xvjf ./"$1" ;;
*.tgz) tar xvzf ./"$1" ;;
*.zip) unzip ./"$1" ;;
*.Z) uncompress ./"$1" ;;
*.7z) 7zr e ./"$1" ;;
*.xz) unxz ./"$1" ;;
*.exe) cabextract ./"$1" ;;
*) echo "extract: '$1' - unknown archive method" ;;
esac
else
echo "'$1' - file does not exist"
fi
fi
}
x() { extract "$1" }
# Edit file recently opened in neovim # file recent
file-recent() {
local list file
list=$(nvim --headless -u NONE -c 'echo v:oldfiles | q' 2>&1 | tr -d \' | tr -d '[]' | tr ',' '\n' | tr -d ' ' | grep -v '://' | grep -v '/\.local/' | grep -v '/tmp/' | sed "s:$HOME:~:" )
file=$(echo $list | fzf --query="$1")
file=$(echo $file | sed "s:~:$HOME:")
if [ -n "$file" ]; then
${EDITOR:-vim} "$file" < /dev/tty
fi
}
fe() { file-recent "$1" }
# Edit file in current (sub)dir with default editor (press Enter)
# or GUI application (press Ctrl+o)
file-edit() {
local out file key
IFS=$'\n' out=($(fd "$1" | fzf --expect=ctrl-o))
key=$(head -1 <<< "$out")
file=$(head -2 <<< "$out" | tail -1)
if [ -n "$file" ]; then
[ "$key" = ctrl-o ] && open "$file" || ${EDITOR:-vim} "$file" < /dev/tty
fi
}
# Interactive search in files, open in vim on selected line
# Ignores lines not matching "\w"
file-search() {
local out tokens file line
out=$(rg --follow --no-heading "$1" | fzf)
IFS=':' tokens=( $out )
file=${tokens[1]}
line=${tokens[2]}
if [ -n "$out" ]; then
${EDITOR:-vim} "$file" +${line} +"setlocal cursorline" < /dev/tty
fi
}
# Open a globally found file (via locate command)
file-locate() {
local files
file=$(locate -Ai -0 $@ | grep -z -vE '~$' | fzf --read0)
if [[ -n $file ]]; then
open_smart "$file"
fi
}
# Trash restore
restore() {
echo '' | trash-restore 2>/dev/null \
| sed '$d' \
| sort -k2,3 -k1,1n \
| fzf \
| awk 'END {print $1}' \
| trash-restore >/dev/null 2>&1
}
# =================================================================
# Directories
# =================================================================
# Directories jumping
# Source http://seanbowman.me/blog/fzf-fasd-and-bash-aliases/
# Change to recent directory, select with fzf
dir-recent() {
local dir
dir=$(zoxide query --list |\
sed "s:$HOME:~:" |\
fzf --no-sort --query "$*" |\
sed "s:~:$HOME:") \
&& cd "$dir"
if [[ $WSL != true ]]; then # on WSL
xdotool key KP_Enter
fi
}
dr() { dir-recent "$1" }
# Change to a subdirectory, select with fzf
dir-open() {
local dir
# dir=$(find -L ${1:-*} -path '*/\.*'\
# -prune -o -type d\
# -print 2> /dev/null | fzf)
dir=$(fd --type=d | fzf)
[ -d "$dir" ] && cd "$dir"
if [[ $WSL != true ]]; then # on WSL
xdotool key KP_Enter
fi
}
de() { dir-open "$1" }
# Change to a subdirectory which contains a given file, select with fzf
dir-with-file() {
local file
local dir
file=$(fzf --query "$1")\
&& dir=$(dirname "$file")
[ -d "$dir" ] && cd "$dir"
}
# Change to any directory or directory with file in it found by locate command
dir-locate() {
local file
file="$(locate -Ai -0 $@ | grep -z -vE '~$' | fzf --read0)"
if [[ -n $file ]]; then
if [[ -d $file ]]; then
cd -- $file
else
cd -- ${file:h}
fi
fi
}
# =================================================================
# Git
# =================================================================
# Easy git commit
c() {
IFS=' '
git commit -m "${*}"
}
gac() { # git add and commit
IFS=' '
git add --all
git commit -m "${*}"
}
ca() {
IFS=' '
git commit --amend -m "${*}"
}
ce() {
IFS=' '
git commit --allow-empty -m "${*}"
}
# Easy github issue
issue() {
IFS=' '
gh issue create --title "${*}"
}
# Searchable git log
fzf-log() {
git log --graph --color=always \
--format="%C(auto)%h%d %s %C(black)%C(bold)%cr" "$@" |
fzf --ansi --no-sort --reverse --tiebreak=index --bind=ctrl-s:toggle-sort \
--bind "ctrl-m:execute:
(grep -o '[a-f0-9]\{7\}' | head -1 |
xargs -I % sh -c 'git show --color=always % | less -R') << 'FZF-EOF'
{}
FZF-EOF"
}
# Checkout merge request from gitlab
mrco() {
local out id
out=$(glab mr list | grep '^!' | fzf --query "$1")
if [ -n "$out" ]; then
# id=$(echo $out | awk '{ print $1 }' | tr -d '!')
branch=$(echo $out | awk -F '(' '{ print $3 }' | tr -d ')')
glab mr checkout $branch
yes_or_no "Unable to checkout $branch - force it?" &&
git fetch --all &&
git reset --hard origin/$branch &&
git checkout $branch &&
git pull
fi
}
mrme() {
local out id
out=$(glab mr list | grep '^!' | fzf --query "$1")
if [ -n "$out" ]; then
id=$(echo $out | awk '{ print $1 }' | tr -d '!')
glab mr merge --remove-source-branch --auto-merge --yes $id
fi
}
mrmerge() {
glab mr merge --remove-source-branch --auto-merge --yes
}
# List gitlab merge requests
mrs() {
glab mr list
}
# =================================================================
# Code
# =================================================================
draft() {
IFS=" "
MY_SITE_DIR="${HOME}/code/lukastrumm"
BLOG_DIR="src/_drafts"
FILE_TITLE="${*}"
FILE_SLUG=$(echo $FILE_TITLE | tr "[:upper:]" "[:lower:]" | sed "s/[[:space:]]\+/-/g")
FILE_PATH="${MY_SITE_DIR}/${BLOG_DIR}/${FILE_SLUG}.md"
echo "---" >> $FILE_PATH
echo "title: ${FILE_TITLE}" >> $FILE_PATH
echo "date: $(date +'%Y-%m-%d')" >> $FILE_PATH
echo "tags: " >> $FILE_PATH
echo "---" >> $FILE_PATH
echo "" >> $FILE_PATH
nvim "${FILE_PATH}" +"cd ${MY_SITE_DIR}"
}
blog() {
IFS=" "
MY_SITE_DIR="${HOME}/code/lukastrumm"
BLOG_DIR="src/blog"
FILE_TITLE="${*}"
FILE_SLUG=$(echo $FILE_TITLE | tr "[:upper:]" "[:lower:]" | sed "s/[[:space:]]\+/-/g")
FILE_PATH="${MY_SITE_DIR}/${BLOG_DIR}/${FILE_SLUG}.md"
echo "---" >> $FILE_PATH
echo "title: ${FILE_TITLE}" >> $FILE_PATH
echo "date: $(date +'%Y-%m-%d')" >> $FILE_PATH
echo "tags: " >> $FILE_PATH
echo "---" >> $FILE_PATH
echo "" >> $FILE_PATH
nvim "${FILE_PATH}" +"cd ${MY_SITE_DIR}"
}
note() {
IFS=" "
MY_SITE_DIR="${HOME}/code/lukastrumm"
NOTES_DIR="src/notes"
FILE_TITLE="${*}"
FILE_SLUG=$(echo $FILE_TITLE | tr "[:upper:]" "[:lower:]" | tr -d "!" | sed "s/[[:space:]]\+/-/g")
FILE_PATH="${MY_SITE_DIR}/${NOTES_DIR}/${FILE_SLUG}.md"
echo "---" >> $FILE_PATH
echo "title: ${FILE_TITLE}" >> $FILE_PATH
echo "date: $(date +'%Y-%m-%d')" >> $FILE_PATH
echo "tags: " >> $FILE_PATH
echo "---" >> $FILE_PATH
echo "" >> $FILE_PATH
nvim "${FILE_PATH}" +"cd ${MY_SITE_DIR}"
}
notes() {
local out key relativePath webPath localPath url
if [ -n "$1" ]; then
IFS=$'\n' out=($(cd ~/code/lukastrumm/src; rg -t md "$1" | fzf --query "$1" --expect=ctrl-o))
else
IFS=$'\n' out=($(cd ~/code/lukastrumm/src; rg -t md -l "" | fzf --expect=ctrl-o))
fi
key=$(head -1 <<< "$out")
relativePath=$(head -2 <<< "$out" | tail -1 | cut -f1 -d':')
webPath=$(echo $relativePath | sed 's/\.md//')
localPath="/home/lukas/code/lukastrumm/src/${relativePath}"
url="https://lukastrumm.com/${webPath}"
if [ -n "$relativePath" ]; then
[ "$key" = ctrl-o ] && xdg-open "$url" &>/dev/null || ${EDITOR:-vim} "$localPath" < /dev/tty
fi
}
# =================================================================
# Shell
# =================================================================
# Make directory, inform about the result and change current directory into it.
# Use only the first argument.
mkcd() {
if [ ! -n "$1" ]; then
echo "Enter a directory name"
elif [ -d "$1" ]; then
echo "'$1' already exists"
else
mkdir -pv "$1" && cd "$1" && echo "cd into: $1"
fi
}
# Copy last command executed on command line into clipboard
last-command() {
fc -l -1 | cut -d' ' -f4- | xsel --clipboard
}
# Print all executable files on path
executables() {
echo -n "$PATH" \
| xargs -d: -I{} -r -- \
find -L {} -maxdepth 1 -mindepth 1 -type f -executable -printf '%P\n' \
| sort -u
}
# Lists all functions available in shell
# Hack: using zsh array of functions, actually its keys (k),
# sorted (o). Filtering out internal functions (starting with _)
list-functions() {
print -l ${(ok)functions} | grep -v '^_'
}
# Insert sequence `!!` which is expanded into output of last
# command by double Tab
insert-last-output() {
xdotool type --clearmodifiers '`!!`' \
&& xdotool key --clearmodifiers Tab \
&& xdotool key --clearmodifiers Tab
}
# kill processes blocking ports
portkill() {
local pid
# get processes listening on local numbered ports and output process id, port number and process name
pid=$( \
netstat -tnlp 2>/dev/null \
| awk 'BEGIN { OFS = "\t"; print "PID","PORT","NAME" } $4 ~ "(127.0.0.1\|\[::\]\|0.0.0.0):[0-9]" && $7!="-" { gsub(/:::/,":"); split($7,a,"/"); split($4,b,":"); print a[1],b[2],a[2] }' 2>/dev/null \
| sort -n -k2 \
| fzf \
| awk '{ print $1 }' \
)
if [ "x$pid" != "x" ]; then
echo $pid | xargs kill -${1:-9}
echo "Process $pid was killed"
else
echo "No process was killed"
fi
}
# zkill - kill processes - list only the ones you can kill.
zkill() {
local pid
if [ "$UID" != "0" ]; then
pid=$(ps -f -u $UID | sed 1d | fzf -m | awk '{print $2}')
else
pid=$(ps -ef | sed 1d | fzf -m | awk '{print $2}')
fi
if [ "x$pid" != "x" ]; then
echo $pid | xargs kill -${1:-9}
fi
}
close_applications() {
xdotool search --class ".*" | xargs -inum xdotool getwindowpid num 2> /dev/null | grep "^[0-9]" | uniq -u | xargs kill
}
# =================================================================
# Graphics
# =================================================================
vectorize() {
local name
name="$1"
# https://linux.die.net/man/1/pdftoppm
# http://potrace.sourceforge.net/potrace.1.html
pdftoppm ${name}.pdf | potrace --output ${name}.svg --blacklevel 0.71 --color '#222020' --svg
}
# =================================================================
# i3wm
# =================================================================
get-current-workspace-name() {
i3-msg -t get_workspaces | jq -r '.[] | select(.focused==true).name'
}
# =================================================================
# Work
# =================================================================
# Interactively select a sql file with database connection
# Last edited files will be closer
# Using dbext in vim
dbext() {
${EDITOR:-vim} "$( ls --color=never --sort=time ~/work/db/*.sql | fzf )"
}
# Simple calculator
calc() {
awk "BEGIN { print "$*" }"
}
emod() {
git status --porcelain | grep '^\(??\)\|\(M\)' | awk '{print $2}' | xargs ${EDITOR:-vim}
}
# =================================================================
# Tmux
# =================================================================
# complete words from tmux pane(s) {{{1
# Source: http://blog.plenz.com/2012-01/zsh-complete-words-from-tmux-pane.html
_tmux_pane_words() {
local expl
local -a w
if [[ -z "$TMUX_PANE" ]]; then
_message "not running inside tmux!"
return 1
fi
# capture current pane first
w=( ${(u)=$(tmux capture-pane -J -p)} )
for i in $(tmux list-panes -F '#P'); do
# skip current pane (handled above)
[[ "$TMUX_PANE" = "$i" ]] && continue
w+=( ${(u)=$(tmux capture-pane -J -p -t $i)} )
done
_wanted values expl 'words from current tmux pane' compadd -a w
}
zle -C tmux-pane-words-prefix complete-word _generic
zle -C tmux-pane-words-anywhere complete-word _generic
bindkey '^X^Tt' tmux-pane-words-prefix
bindkey '^X^TT' tmux-pane-words-anywhere
zstyle ':completion:tmux-pane-words-(prefix|anywhere):*' completer _tmux_pane_words
zstyle ':completion:tmux-pane-words-(prefix|anywhere):*' ignore-line current
# display the (interactive) menu on first execution of the hotkey
zstyle ':completion:tmux-pane-words-(prefix|anywhere):*' menu yes select interactive
zstyle ':completion:tmux-pane-words-anywhere:*' matcher-list 'b:=* m:{A-Za-z}={a-zA-Z}'
# =================================================================
# Experimantal
# =================================================================
# Translation tool
# https://github.com/soimort/translate-shell
t() {
trans :cs -brief "${*}"
}
# English dictionary tool
# https://github.com/soimort/translate-shell
dic() {
trans -d :en "${*}"
}