-
Notifications
You must be signed in to change notification settings - Fork 0
/
.bash_functions
1024 lines (872 loc) · 28.3 KB
/
.bash_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
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env bash
# EMACS_VERSION="25.1.91"
EMACS_VERSION="27.2"
function __debug() {
if [[ ! -z ${DEBUG} ]]; then
echo "$@"
fi
}
# Gets a random decimal number made up of 0-N bytes specified by the user.
# So, for example, random 1 produces a decimal between 0-255
function random() {
local num_bytes=$1
[[ ${num_bytes} == "" ]] && local num_bytes=1
od -A n -t d -N ${num_bytes} /dev/urandom | tr -d ' '
}
# alert function for long running commands. Use like so:
# sleep 10; alert
function alert() {
msg="Terminal"
[ $? -eq 0 ] && msg="Error"
prevous_cmd="$(history | tail -n2 | head -n1 | sed -e 's/ */ /g' | cut -d' ' -f3-)"
notify-send --urgency=low\
-i "${msg}"\
"${previous_cmd}"
}
function now() {
date "+%H:%M:%S"
}
function diff-lines() {
local path=
local line=
while read; do
esc=$'\033'
if [[ "${REPLY}" =~ ---\ (a/)?.* ]]; then
continue
elif [[ "${REPLY}" =~ \+\+\+\ (b/)?([^[:blank:]$esc]+).* ]]; then
path="${BASH_REMATCH[2]}"
elif [[ "${REPLY}" =~ @@\ -[0-9]+(,[0-9]+)?\ \+([0-9]+)(,[0-9]+)?\ @@.* ]]; then
line="${BASH_REMATCH[2]}"
elif [[ "${REPLY}" =~ ^(${esc}\[[0-9;]+m)*([\ +-]) ]]; then
echo "${path}:${line}:${REPLY}"
if [[ "${BASH_REMATCH[2]}" != - ]]; then
((line++))
fi
fi
done
}
function open-bg() {
filename=$(basename $1)
logfile="/tmp/$USER-$filename.log"
$1 >&${logfile} &
}
function compress-pdf() {
if [ "$1" == "--help" ]; then
echo "This command compresses a pdf to enough quality for documents with images (like passports)"
echo "Usage:"
echo "compress-pdf <input-file> [output-file]"
echo "input-file: The PDF file to compress"
echo "output-file: The name of the output file to compress, if no output-file is given"
echo " then a file called compressed-<input-file> is created."
fi
input_file=$1
output_file=$2
if [ "$output_file" == "" ]; then
output_file="compressed-$(basename $input_file)"
fi
compression_level="/ebook"
# /screen selects low-resolution output similar to the Acrobat Distiller "Screen Optimized" setting.
# /ebook selects medium-resolution output similar to the Acrobat Distiller "eBook" setting.
# /printer selects output similar to the Acrobat Distiller "Print Optimized" setting.
# /prepress selects output similar to Acrobat Distiller "Prepress Optimized" setting.
# /default selects output intended to be useful across a wide variety of uses, possibly at the expense of a larger output file.
gs -dNOPAUSE -dQUIET -dBATCH \
-sDEVICE=pdfwrite \
-dCompatibilityLevel=1.4 \
-dPDFSETTINGS=$compression_level \
-sOutputFile=$output_file $input_file
# other compression options for pdfwrite
# -dr[resolution] -> default setting is 720dpi
# -dDetectDuplicateImages -> defaults to true, will reuse a image used more than once
# -dCompressPages -> defaults to true
# -dOptimize -> defaults to false, set to true on /screen, /ebook, /printer, /prepress
# -dCompressFonts -> defaults to true, never set to false.
}
# executes a command without any output
function succeeds() {
$@ >&/dev/null
}
# executes a command with output
function fails() {
$@ >&/dev/null
}
mlocate-here() {
directory=$2
if [ -z "${directory}" ]; then
directory="$(pwd)/"
fi
mlocate -b "$1" | grep --color=never "^${directory}"
}
run-step() {
eval "$1"
__result=$?
time=$(date +%H:%M)
if [ "${__result}" == "0" ]; then
lemonbar-show --fg "#99FF99" "(${time}) <$1> done ($2)"
else
lemonbar-show --fg "#C45454" "(${time}) <$1> failed ($2)"
fi
}
function top-n() {
history \
| sed 's/^ \+//;s/ / /' \
| cut -d']' -f2- \
| awk '{ count[$0]++ } END { for (i in count) print count[i], i }' \
| sort -rn \
| head -$1
}
function top-ten() {
top-n 10
}
function java-package-to-path() {
get-arg-or-stdin "$@" | sed 's/\./\//g'
}
function copy-to-clip() {
get-arg-or-stdin "$@" | perl -pe 'chomp if eof' | xclip -sel clip
}
function paste-clip() {
xclip -o
}
function get-arg-or-stdin() {
# if there are no arguments, then echo from stdin, otherwise echo arguments
([ $# -eq 0 ] && cat) || echo "$@"
}
function tmux-to-clip() {
tmux show-buffer | copy-to-clip
}
function copy-to-tmux() {
tmux set-buffer "$(get-arg-or-stdin $@)"
}
function history-cmd-only() {
history | sed 's/^[^]]*\]//'
}
function cmd-exists() {
( type "$1" >/dev/null 2>&1 && echo "true" ) || echo "false"
}
function tmux-session-name() {
tmux display-message -p '#S'
}
function tmux-window-set-name() {
if [[ "$2" == "-n" ]]; then
local short_name="$1"
else
local short_name=$(echo "$1" | cut -c 1-30)
fi
tmux rename-window "${short_name}"
}
function tmux-window-name() {
tmux display-message -p '#W'
}
function tmux-window-bell-on-activity() {
local setting=$1
[[ -z "${setting}" ]] && setting="on"
tmux set-window-option monitor-activity "${setting}"
}
function is-ssh-session() {
([ -n "${SSH_CLIENT}" ] || [ -n "${SSH_TTY}" ] || [ -n "${SSH_CONNECTION}" ]) && echo "true"
}
function get-ssh-relay-ip() {
connection_string=$(([ -n "${SSH_CLIENT}" ] && echo "${SSH_CLIENT}")|| echo "${SSH_CONNECTION}")
echo "${connection_string}" | cut -d' ' -f1
}
function get-ssh-relay-hostname() {
relay_ip=$(get-ssh-relay-ip)
if [ -n "${relay_ip}" ]; then
nslookup "${relay_ip}" | grep -o 'name =.*' | cut -d'=' -f2 | sed 's/ //g' | sed 's/\.$//'
fi
}
function __process-ps-lines() {
lines="$(cat)"
byte_limit="$(numfmt --to=none --from=si $1 2>/dev/null)"
__debug "__process-ps-lines: byte_limit=${byte_limit}"
readarray -t lines_array <<<"${lines}"
for line in "${lines_array[@]}"
do
elements=(${line//:/ })
kb_size="${elements[0]}"
if [[ "${kb_size}" == "SIZE" ]]; then
echo "${line}"
else
byte_size=$(echo "${kb_size} * 1024" | bc)
elements=("${elements[@]/$kb_size}")
human_size="$(numfmt --to=si ${byte_size})"
if [[ "${byte_size}" -gt "${byte_limit}" ]] || [[ -z "${byte_limit}" ]]; then
echo "${human_size} ${elements[@]}"
fi
fi
done
}
function ps-show-memory-hogs() {
procs=25
command_format=comm
while [[ $# -gt 0 ]]; do
case $1 in
-n|--number)
procs=$2
shift
;;
-f|--full-command)
command_format="args"
shift
;;
-s|--short-command)
# this is the default
;;
-l|--limit-size)
limit=$2
shift
;;
*)
echo "Ignoring unkown parameter: $1" >&2
;;
esac
shift
done
__debug "procs=${procs}"
__debug "limit=${limit}"
ps -A -o size -o pid -o "${command_format}" --sort=-size \
| __process-ps-lines "${limit}" | head "-${procs}"
}
function ps-nice() {
# TODO: move to its own script file
format="-o pid -o tty -o start -o args"
sort="--sort=-comm"
config="axw"
# default configuration
use_headers="false"
full_command="false"
while [[ $# -gt 0 ]]; do
case $1 in
--use-headers)
use_headers="true"
;;
--full-command)
full_command="true"
;;
--show-size)
size="true"
;;
*)
break
;;
esac
shift
done
if [ "${use_headers}" == "false" ]; then
config="${config}h"
fi
if [ "${full_command}" == "true" ]; then
config="${config}w"
fi
if [ ! -z "${size}" ]; then
format="-o pid -o size -o tty -o start -o args"
fi
ps ${format}\
${sort}\
${config}\
"$@"
}
function emacs() {
local emacs_bin="$(which emacs)"
# prioritize the snap installation of emacs
if [[ -x "/snap/bin/emacs" ]]; then
emacs_bin="/snap/bin/emacs"
fi
# prioritize user-local install of emacs
if [[ -x "${HOME}/.local/bin/emacs" ]]; then
emacs_bin="${HOME}/.local/bin/emacs"
fi
if [[ "${EMACS_VERSION}" != "" ]]; then
if [[ -x "/usr/local/bin/emacs-${EMACS_VERSION}" ]]; then
emacs_bin="/usr/local/bin/emacs-${EMACS_VERSION}"
elif [[ -x "/usr/snap/bin/emacs-${EMACS_VERSION}" ]]; then
emacs_bin="/snap/bin/emacs-${EMACS_VERSION}"
else
echo "Emacs binary for version ${EMACS_VERSION} not found. Using ${emacs_bin} instead." >&2
fi
fi
"${emacs_bin}" -nw "$@"
}
function emacs-client() {
local editor_cmd=(/usr/bin/emacsclient --create-frame --tty --socket-name=${EMACS_TTY_SERVER})
if ! EDITOR="'""${editor_cmd[@]}""'" "${editor_cmd[@]}" "$@"; then
if type at &>/dev/null; then
echo "emacs --daemon=${EMACS_TTY_SERVER}" | at NOW
else
(emacs --bg-daemon=${EMACS_TTY_SERVER} &)
fi
# Give the server 125ms to start listening for connections.
sleep 0.125
EDITOR="'""${editor_cmd[@]}""'" "${editor_cmd[@]}" "$@"
fi
}
# force myself to use emacs, not nano
function nano() {
[ "$1" == "-F" ] && shift
emacs-client "$@"
}
# shows the shell's keyboard shortcuts
function bind-show-shortcuts() {
bind -p | tail -n +1 | grep -v "not bound" | grep -v "self-insert"
}
# shows the shell's settings
function bind-show-settings() {
bind -v
}
# show the shell's interactive capabilities
function bind-show-capabilities() {
bind -l
}
function show-shell-shortcuts() {
bind-show-shortcuts
}
function show-shell-settings() {
bind-show-settings
}
function show-shell-capabilities() {
bind-show-capabilities
}
function wait-for-process() {
for pid in "$@"
do
# skip pid if process does not exist
[ -z "$(pgrep "${pid}")" ] && continue
wait ${pid} &>/dev/null ||\
tail --pid=${pid} -f &>/dev/null ||\
echo "Failed to wait for process ${pid}" 1>&2
done
}
# This function reduces the horrible lag spikes caused by the NetworkManager
# scanning the wifi network in the background when using a 802.11AC enabled
# wireless network interface.
# NOTE: if this solution does not work well enough, you can alternatively
# switch from NetworkManager to wicd (manual configuration).
function wifi-pause-background-scan() {
sudo killall -STOP NetworkManager &>/dev/null ||\
sudo killall -STOP wicd &>/dev/null
if [[ "$?" != "0" ]]; then
echo "Neither a NetworkManager nor a wicd process found to STOP." >&2
fi
echo "Disabled background wi-fi network scan by pausing the NetworkManager/wicd process"
}
function wifi-enable-background-scan() {
sudo killall -CONT NetworkManager &>/dev/null ||\
sudo killall -CONT wicd &>/dev/null
if [[ "$?" != "0" ]]; then
echo "Neither a NetworkManager nor a wicd process found to CONTinue." >&2
fi
echo "Enabled background wi-fi network scan by signaling the NetworkManager/wicd process"
}
# start npm functions
function node-lts-version() {
local node_version_file="/tmp/${USER}_NODE_VERSION"
local lts_node_version=
if [[ -e "${node_version_file}" ]]; then
lts_node_version=$(cat "${node_version_file}")
fi
if [[ -z "${lts_node_version}" ]]; then
lts_node_version=$(nvm ls-remote --lts | tail -1 | grep -oP "(?<=v)[0-9a-b\.]+")
echo "${lts_node_version}" > "${node_version_file}"
fi
echo "${lts_node_version}"
}
function node-check-use() {
local node_version=$(node --version 2>/dev/null)
if [[ "${NODE_VERSION}" == "lts" ]] || [[ "${NODE_VERSION}" == "LTS" ]]; then
NODE_VERSION="$(node-lts-version)"
export NODE_VERSION
fi
if [ "${node_version}" != "v${NODE_VERSION}" ]; then
local node_version_installed=$(nvm ls 2>/dev/null | grep "${NODE_VERSION}")
if [ "${node_version_installed}" == "" ]; then
echo Node v$NODE_VERSION is not installed, installing now.
nvm install "v${NODE_VERSION}"
fi
if [ "$1" == "--silent" ]; then
nvm use "${NODE_VERSION}" >/dev/null 2>&1
else
nvm use "${NODE_VERSION}"
fi
fi
}
function npm-tdd() {
node-check-use
npm run test:watch
}
function npm-install() {
node-check-use
npm install
}
function npm-test() {
node-check-use
npm run test
}
function npm-start() {
node-check-use
npm start
}
function npm-lint() {
node-check-use
npm run lint
}
# start git functions
function diff-lines() {
local path=
local line=
while read; do
esc=$'\033'
if [[ $REPLY =~ ---\ (a/)?.* ]]; then
continue
elif [[ $REPLY =~ \+\+\+\ (b/)?([^[:blank:]$esc]+).* ]]; then
path=${BASH_REMATCH[2]}
elif [[ $REPLY =~ @@\ -[0-9]+(,[0-9]+)?\ \+([0-9]+)(,[0-9]+)?\ @@.* ]]; then
line=${BASH_REMATCH[2]}
elif [[ $REPLY =~ ^($esc\[[0-9;]+m)*([\ +-]) ]]; then
echo "$path:$line:$REPLY"
if [[ ${BASH_REMATCH[2]} != - ]]; then
((line++))
fi
fi
done
}
function git-diff-lines() {
git diff $1 $2 $3 $4 | diff-lines
}
function g-diff-lines() {
git-diff-lines $1 $2 $3 $4
}
function git-branch-out() {
new_branch_name=$1
treeish=$2
git checkout -b $1 $2
}
function g-branch-out() {
git-branch-out $1 $2
}
function git-rm-forever() {
if [ "$1" == "--help" ]; then
echo Removes a file completely from the repository history
exit 1
fi
file="$1"
git filter-branch --force --index-filter \
"git rm --cached --ignore-unmatch ${file}" \
--prune-empty --tag-name-filter cat -- --all
}
function g-rm-forever() {
git-rm-forever $1
}
function git-push-marcel() {
git push marcel $(git-current-branch):$(git-current-branch)
}
function git-push-f-marcel() {
git push -f marcel $(git-current-branch):$(git-current-branch)
}
# end git functions
# java management functions
function set-env-java9() {
export JAVA_HOME='/usr/lib/jvm/java-9-openjdk-amd64'
}
function set-env-java8() {
export JAVA_HOME='/usr/lib/jvm/java-8-openjdk-amd64'
}
function java() {
if [[ ! -z ${JAVA_HOME} ]]; then
${JAVA_HOME}/bin/java $@
else
/usr/bin/java $@
fi
}
function javac() {
if [[ ! -z ${JAVA_HOME} ]]; then
"${JAVA_HOME}/bin/java" $@
else
/usr/bin/javac $@
fi
}
function fixup_ssh_auth_sock() {
if [[ -n ${SSH_AUTH_SOCK} && ! -e ${SSH_AUTH_SOCK} ]]; then
local new_sock=
new_sock=$(echo /tmp/ssh-*/agent*)
if [[ -n ${new_sock} ]]; then
export SSH_AUTH_SOCK=${new_sock}
fi
fi
}
function less-color() {
less -R "$@"
}
function generate-dotfiles-tags() {
type etags &>/dev/null && etags ~/.bashrc ~/.bash_functions ~/.bash_aliases\
~/.bash_ssh ~/.bash_profile ~/.bash_logout\
~/.profile ~/.xinitrc ~/.xinputrc ~/.xsession
}
function set-window-title {
local new_title="$@"
echo -e "\x1b]2;${new_title}\x1b\\"
}
function imgcat-url {
local url="$1"
if [[ -z "${url}" ]]; then
url=$(cat)
fi
if [[ -z "${url}" ]]; then
echo "No URL provided, stopping" >&2
return 1
fi
local clean_url=$(echo "${url}" | sed 's|[\r\n\t]||g')
if [[ "${TMUX}" ]] || ! type wezterm &>/dev/null; then
if type imgcat &>/dev/null; then
echo "We're within a TMUX session, using normal imgcat" >&2
wget -O /dev/stdout "${clean_url}" | imgcat
else
echo "You need to install imgcat" >&2
return 1
fi
elif type wezterm &>/dev/null; then
wget -O /dev/stdout "${clean_url}" | wezterm imgcat
fi
}
function cpu-get-perf-modes {
cat /sys/devices/system/cpu/cpu*/cpufreq/scaling_available_governors
}
function cpu-get-perf-mode {
cat /sys/devices/system/cpu/cpu*/cpufreq/scaling_governor
}
function cpu-set-high-perf-mode {
for _cpu in {0..7}; do
sudo cpufreq-set --governor "performance" --cpu "${_cpu}"
done
# echo "performance" | sudo tee /sys/devices/system/cpu/cpu*/cpufreq/scaling_governor
}
function cpu-set-save-perf-mode {
for _cpu in {0..7}; do
sudo cpufreq-set --governor "powersave" --cpu "${_cpu}"
done
#echo "powersave" | sudo tee /sys/devices/system/cpu/cpu*/cpufreq/scaling_governor
}
function gnome-terminal-dump-conf {
dconf dump /org/gnome/terminal/
}
function gnome-terminal-load-conf {
local conf_file="$1"
if [[ -z "${conf_file}" ]]; then
conf_file="${HOME}/.gterminal.conf"
fi
cat "${conf_file}" | dconf load /org/gnome/terminal/legacy/profiles:/
}
function timestamp {
date "+%s"
}
function chrono-start {
__CHRONO_START=$(timestamp)
echo "${__CHRONO_START}"
}
function chrono-end {
local chrono_end=
chrono_end=$(timestamp)
local chrono_duration_sec=$((chrono_end-__CHRONO_START))
echo "${chrono_duration_sec}"
}
function fzf-context {
local file="$1"
local context_lines="$2"
if [[ -z "${context_lines}" ]]; then
context_lines=10
fi
local tmpfile=
tmpfile="$(mktemp).sh"
local terminal_width=
terminal_width=$(stty -a | grep -Po '(?<=columns )\d+')
local preview_width=
preview_width=$((terminal_width / 2))
(cat<<EOF
hilite=\$1;
context=\$2;
start=\$((hilite - context));
if [[ \$start -lt 0 ]]; then start=0; fi;
end=\$((hilite + context));
batcat ${file} --highlight-line=\${hilite} --line-range=\${start}:\${end} --color=always --style=numbers --wrap=character --terminal-width=${preview_width} --paging=always
EOF
)>"${tmpfile}"
cat -n "${file}" | fzf --preview "bash ${tmpfile} {1} ${context_lines}" --bind 'ctrl-/:toggle-preview'
}
function fzf-cmd {
if ! type -p fzf &>/dev/null; then
echo "fzf-find: fzf not available, can't proceed." >&2
echo 'sudo apt install fzf' >&2
fi
local fzf_cmd=('fzf')
if [[ "${TMUX}" ]]; then
fzf_cmd=('fzf-tmux' '-p' '-h' '90%' '-w' '90%')
fi
"${fzf_cmd[@]}" "$@"
}
function fzf-find {
if ! type -p rg &>/dev/null; then
echo "fzf-find: rg not available, can't proceed." >&2
echo 'sudo apt install ripgrep' >&2
fi
# 1. Search for text in files using Ripgrep
# 2. Interactively restart Ripgrep with reload action
local options=("$@")
if [[ "$#" -eq 0 ]]; then
options=('.*')
fi
rg --color=always --line-number --no-heading --smart-case "${options[@]}" |
fzf-cmd --ansi \
--color "hl:-1:underline,hl+:-1:underline:reverse" \
--delimiter : \
--preview 'batcat --color=always {1} --highlight-line {2}' \
--preview-window 'up,60%,border-bottom,+{2}+3/3,~3' \
--bind 'enter:become(echo {1})'
}
function fzf-edit {
rg --color=always --line-number --no-heading --smart-case "${*:-}" |
fzf --ansi \
--color "hl:-1:underline,hl+:-1:underline:reverse" \
--delimiter : \
--preview 'batcat --color=always {1} --highlight-line {2} --line-range {2}:-5 --line-range {2}:+5' \
--preview-window 'up,60%,border-bottom,+{2}+3/3,~3' \
--bind 'enter:become(emacsclient --socket-name='"${EMACS_TTY_SERVER}"' --tty --create-frame {1} +{2})'
}
function fzf-edit-deep {
if ! type -p rg &>/dev/null; then
echo "fzf-edit-deep: rg not available, can't proceed." >&2
echo 'sudo apt install ripgrep' >&2
fi
if ! type -p batcat &>/dev/null; then
echo "fzf-edit-deep: batcat not available, can't proceed." >&2
echo 'sudo apt install bat' >&2
fi
RG_PREFIX="rg --column --line-number --no-heading --color=always --smart-case "
FILESET=("$@")
if [[ "$#" -eq 0 ]]; then
FILESET=(".")
fi
: | fzf --ansi --disabled --query "" \
--bind "start:reload:$RG_PREFIX {q} ${FILESET[*]}" \
--bind "change:reload:sleep 0.1; $RG_PREFIX {q} ${FILESET[*]} || true" \
--header=$'ctrl-f:fzf-mode, ctrl-space:select-all'\
--bind "ctrl-f:rebind(ctrl-r)+unbind(change,ctrl-f)+change-prompt(2. fzf> )+change-header(ctrl-r:ripgrep-mode, ctrl-space:select-all)+enable-search+clear-query" \
--bind "ctrl-r:rebind(change,ctrl-f)+unbind(ctrl-r)+change-prompt(1. ripgrep> )+change-header(ctrl-f:fzf-mode, ctrl-space:select-all)+disable-search+clear-query" \
--bind "ctrl-space:select-all" \
--color "hl:-1:underline,hl+:-1:underline:reverse" \
--prompt '1. ripgrep> ' \
--delimiter : \
--preview 'batcat --color=always {1} --highlight-line {2}' \
--preview-window 'up,60%,border-bottom,+{2}+3/3,~3' \
--bind 'enter:become(/usr/bin/emacsclient --socket-name='"${EMACS_TTY_SERVER}"' --create-frame --tty {1} +{2})'
}
function fzf-preview {
fzf-cmd --ansi --query '' \
--color "hl:-1:underline,hl+:-1:underline:reverse" \
--delimiter : \
--preview 'batcat --color=always {1} --highlight-line {2}' \
--preview-window 'up,66%,border-bottom,+{2}+3/3,~3'
}
function fzf-kill {
# pipes ps -ef output to fzf and kills the process with with signal -9
local kill_args=("$@")
if [[ $# -eq 0 ]]; then
kill_args=('-9')
fi
(date; ps -ef) |
fzf-cmd --bind='ctrl-r:reload(date; ps -ef)' \
--header=$'Press CTRL-R to reload\n\n' --header-lines=2 \
--preview='echo {}' --preview-window=down,3,wrap \
--height=80% | awk '{print $2}' | xargs kill "${kill_args[@]}"
}
function f {
# if no arguments passed, just lauch fzf
if [ $# -eq 0 ]
then
fzf-cmd | sort
return 0
fi
# Store the program
program="$1"
# Remove first argument off the list
shift
# Store any option flags
options=("$@")
# Store the arguments from fzf
arguments=($(IFS='
' fzf-cmd --multi))
# If no arguments passed (e.g. if Esc pressed), return to terminal
if [ "${#arguments[@]}" -eq 0 ]; then
return 1
fi
# Sanitise the command by putting single quotes around each argument, also
# first put an extra single quote next to any pre-existing single quotes in
# the raw argument. Put them all on one line.
clean_arguments=()
for arg in "${arguments[@]}"; do
clean_arguments+=($(echo "$arg" | IFS='' sed "s/'/''/g; s/.*/'&'/g; s/\n//g"))
done
# space is the default
IFS=" "
# If the program is on the GUI list, add a '&'
if [[ "${program}" =~ ^(nautilus|zathura|evince|vlc|eog|kolourpaint)$ ]]; then
clean_arguments+=("&")
fi
# Write the shell's active history to ~/.bash_history.
history -w
# Add the command with the sanitised arguments to .bash_history
echo "${program}" "${options[@]}" "${clean_arguments[@]}" >> ~/.bash_history
# Reload the ~/.bash_history into the shell's active history
history -r
# execute the last command in history
"${program}" "${options[@]}" "${clean_arguments[@]}"
}
function fif {
__debug "fif: Checks."
if ! type rg &>/dev/null; then
echo "Ripgrep required. sudo apt install ripgrep" >&2
return 1
fi
if ! type fzf &>/dev/null; then
echo "Fzf required. sudo apt install fzf" >&2
return 1
fi
if ! type sponge &>/dev/null; then
echo "Sponge required. sudo apt install moreutils" >&2
return 1
fi
__debug "fif: Start."
local results_file=
local results_file_history=
local prompt_file=
local prompt_file_history=
local initial_query=()
local _pwd=
local prompt_ln="/tmp/fif-prompt.${RANDOM}"
local results_ln="/tmp/fif-files.${RANDOM}"
local rg_query_file="/tmp/rg-fzf-r.${RANDOM}"
local fzf_query_file="/tmp/rg-fzf-f.${RANDOM}"
local ctrl_space_execute=
local ctrl_delete_execute=
local term_width=$(tput cols)
local half_term_width=$((term_width / 2))
local preview_title_width=$((half_term_width - 10))
prompt_file=$(mktemp)
prompt_file_history=$(mktemp)
results_file=$(mktemp)
results_file_history=$(mktemp)
echo "${prompt_file}" > "${prompt_file_history}"
ln -sf "${prompt_file}" "${prompt_ln}"
echo "${results_file}" > "${results_file_history}"
ln -sf "${results_file}" "${results_ln}"
while read -r filename; do
if [[ -d "${filename}" ]]; then
find "${filename}" -type f >> "${results_ln}"
else
echo "${filename}" >> "${results_ln}"
fi
done
__debug "fif: Step 1."
sort < "${results_ln}" | uniq | sponge "${results_ln}"
if [[ "$1" ]]; then
initial_query+=("-e" "$1")
echo -n "$1> " > "${prompt_ln}"
else
initial_query+=("-e" '')
echo -n '> ' > "${prompt_ln}"
fi
local rg_prefix="rg-file --files-with-matches --line-buffered --file-list-path ${results_ln}"
local rg_header="[RG MODE] ctrl-space:filter / ctrl-delete:undo-filter
ctrl+o:open / ctrl+/: popup batcat / ctrl-f:fzf mode"
local fzf_header="[FZF MODE] ctrl-space:filter / ctrl-delete:undo-filter
ctrl+o:open / ctrl+/: popup batcat / ctrl-r:rg mode"
_pwd="$(pwd)"
ctrl_space_execute=$(cat<<EOF
mktemp >> ${results_file_history};
mktemp >> ${prompt_file_history};
bash -c 'cp ${prompt_ln} \$(tail -1 ${prompt_file_history})';
bash -c 'ln -sf \$(tail -1 ${results_file_history}) ${results_ln}';
bash -c 'ln -sf \$(tail -1 ${prompt_file_history}) ${prompt_ln}';
echo {+} | sed -E 's|[ ]+|\n|g' > ${results_ln};
echo -n "{q} > " >> ${prompt_ln}
EOF
)
ctrl_delete_execute=$(cat<<EOF
head -n -1 ${results_file_history} | sponge ${results_file_history};
head -n -1 ${prompt_file_history} | sponge ${prompt_file_history};
bash -c 'ln -sf \$(tail -1 ${results_file_history}) ${results_ln}';
bash -c 'ln -sf \$(tail -1 ${prompt_file_history}) ${prompt_ln}';
EOF
)
__debug "fif: Step 2."
FZF_DEFAULT_COMMAND="${rg_prefix} ${initial_query[@]}" \
fzf \
--sort \
--multi \
--preview '[[ ! -z {} ]] && rg --pretty --context 5 {q} {}' \
--ansi --phony --query "${initial_query[1]}" \
--bind "start:reload(cat ${results_ln})" \
--bind "focus:transform-preview-label(echo {} | tail -c ${preview_title_width})" \
--bind "result:transform-preview-label(echo {} | tail -c ${preview_title_width})" \
--bind "change:reload(sleep 0.25 && ${rg_prefix} -e {q} | sort || true)" \
--bind "ctrl-space:select-all+execute(${ctrl_space_execute})+transform-prompt(cat ${prompt_ln})+clear-query+reload(cat ${results_ln})" \
--bind "ctrl-delete:deselect-all+execute(${ctrl_delete_execute})+transform-prompt(cat ${prompt_ln})+clear-query+reload(cat ${results_ln})" \
--bind "ctrl-f:unbind(change,ctrl-f)+change-header(${fzf_header})+enable-search+rebind(ctrl-r)+transform-query(echo {q} > ${rg_query_file}; cat ${fzf_query_file})+change-preview(batcat --paging=never --style='numbers,changes' --color=always {})" \
--bind "ctrl-r:unbind(ctrl-r)+change-header(${rg_header})+disable-search+reload(${rg_prefix} -e {q} || true)+rebind(change,ctrl-f)+transform-query(echo {q} > ${fzf_query_file}; cat ${rg_query_file})+change-preview([[ ! -z {} ]] && rg --pretty --context 5 {q} {})" \
--bind 'ctrl-o:become(bash -i -c "emacs-client {+}")' \
--prompt "$(cat "${prompt_ln}")" \
--bind "ctrl-/:execute:tmux display-popup -w '80%' -h '80%' -d '${_pwd}' -T '{}' -E batcat --paging=always --style='numbers,changes' --color=always {}" \
--header "${rg_header}"
}
function fzf-cs-cd {
local cd_file=
cd_file="$(fzf-cs | cut -d':' -f1)"
local directory=
directory="$(dirname "${cd_file}")"
cd "${directory}" || return 1
}
function hg_lines_changed {
local diffstats_local=
local diffstats_commit=
local added_local=
local added_commit=0
local deleted_local=
local deleted_commit=0
# The head commit is authored by this user
if [[ "${USER}@google.com" == "$(hg log -r . -T '{user}')" ]]; then
# The head commit is not submitted
if [[ -z "$(hg log -r . -T '{submittedcls}')" ]]; then
diffstats_commit="$(hg log -r . -T '{diffstat}')"
added_commit=$(echo "${diffstats_commit}" | cut -d'+' -f2 | cut -d'/' -f1)
deleted_commit=$(echo "${diffstats_commit}" | cut -d'-' -f2)
fi
fi
# Format:
# files_modified: +lines_added/-lines_deleted
diffstats_local="$(hg status -T '{diffstat}')"
added_local=$(echo "${diffstats_local}" | cut -d'+' -f2 | cut -d'/' -f1)
deleted_local=$(echo "${diffstats_local}" | cut -d'-' -f2)
modified_total=$((added_local+added_commit+deleted_local+deleted_commit))
if [[ ${modified_total} -lt 49 ]]; then
printf "\033[0;32m${modified_total}\033[0m"
elif [[ ${modified_total} -lt 250 ]]; then