-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathnsh.sh
executable file
·4983 lines (4856 loc) · 195 KB
/
nsh.sh
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
##############################################################################
# Preferences
NSH_DEFAULT_CONFIG="# preferences
NSH_PROMPT_SEPARATOR='\xee\x82\xb0'
NSH_PROMPT_SHOW_TIME=1
NSH_PROMPT_PREFIX= # this could be a string, a variable, or even a function, e.g. date
NSH_BOTTOM_MARGIN=20%
NSH_DEFAULT_EDITOR=vim
NSH_ITEMS_TO_HIDE=.*,*.pyc
NSH_DO_NOT_SHOW_ELAPSED_TIME=vi,vim,htop,config,grep,git
NSH_TEXT_PREVIEW='bat --color=always --number'
NSH_IMAGE_PREVIEW=
NSH_REMEMBER_LOCATION=1
HISTSIZE=1000
# colors
NSH_COLOR_TOP=$'\e[30;48;5;248m'
NSH_COLOR_CUR=$'\e[7m'
NSH_COLOR_TXT=$'\e[37m'
NSH_COLOR_CMD=$'\e[32m'
NSH_COLOR_VAR=$'\e[36m'
NSH_COLOR_VAL=$'\e[33m'
NSH_COLOR_ERR=$'\e[31m'
NSH_COLOR_DIR=$'\e[94m'
NSH_COLOR_EXE=$'\e[32m'
NSH_COLOR_IMG=$'\e[95m'
NSH_COLOR_LNK=$'\e[96m'
NSH_COLOR_SC1=$'\e[37;47m' # scrollbar foreground
NSH_COLOR_SC2=$'\e[48;5;240m' # scrollbar background
NSH_COLOR_SH1=$'\e[30;47m' # shortcut color1
NSH_COLOR_SH2=$'\e[37;100m' # shortcut color2
NSH_COLOR_DLG=$'\e[48;5;250;30m'
NSH_COLOR_BKG='48;5;239'
# menu
NSH_MENU_DEFAULT_CURSOR=$'\e[31;40m>'
NSH_MENU_DEFAULT_SEL_COLOR='32;40'
# aliases
alias ls='command ls --color=auto'
alias ll='ls -Al'
alias diff='command diff --color=always {} | less -RF'
"
eval "$NSH_DEFAULT_CONFIG"
# since alias doesn't work in the script, define a function with the same name
(return 0 2>/dev/null) || alias() {
local l="$@"
local n="${l%%=*}"
local c="${l#*=}"
[[ $c != *\{\}* ]] && c="$c {}"
if [[ $c == \'* || $c == \" ]]; then
[[ $c != *"${c:0:1}" ]] && echo "unmatched quote" >&2 && return 1
c="${c:1:$((${#c}-2))}"
fi
#eval "$n() { $c \"\$@\"; }"
eval "$n() { ${c/\{\}/\"\$@\"}; }"
}
GIT_COMMANDS=(clone init add mv restore rm checkout bisect diff grep log blame show status branch commit merge rebase reset switch tag fetch pull push)
# check compatibility
LS_COLOR_PARAM='--color'
ls $LS_COLOR_PARAM &>/dev/null || LS_COLOR_PARAM='-G'
LS_TIME_STYLE=
ls -l --time-style=long-iso &>/dev/null && LS_TIME_STYLE="--time-style=long-iso"
STAT_FSIZE_PARAM='--printf=%s'
stat "$STAT_FSIZE_PARAM" . &>/dev/null || STAT_FSIZE_PARAM='-f%z'
NSH_PROMPT=$'\e[31m>\e[33m>\e[32m>\e[0m'
##############################################################################
# utility functions
hide_cursor() {
printf '\e[?25l'
}
show_cursor() {
printf '\e[?25h'
}
get_terminal_size() {
read -r LINES COLUMNS < <(stty size)
max_lines=$((LINES-2))
}
# CAUTION: index starts at 1 not 0
move_cursor() {
[[ $1 == -* ]] && printf '\e[%sH' "$(($(get_cursor_row)+$1))" || printf '\e[%sH' "$1"
}
save_cursor_pos() {
printf '\e[7'
}
restore_cursor_pos() {
printf '\e[8'
}
get_cursor_pos() {
while true; do
IFS=';' read -sdR -p $'\E[6n' ROW COL </dev/tty; ROW=${ROW#*[};
[[ $ROW =~ ^[0-9]*$ ]] && return # sometimes ROW has weird values
done
}
get_cursor_row() {
IFS=';' read -sdR -p $'\E[6n' ROW COL </dev/tty; echo ${ROW#*[};
}
get_cursor_col() {
IFS=';' read -sdR -p $'\E[6n' ROW COL </dev/tty; echo $COL;
}
get_timestamp() {
if [[ "$OSTYPE" == darwin* ]]; then
echo $(($(date -u +%s) * 1000))
else
echo $(($(date +%s%N) / 1000000))
fi
}
enable_echo() {
stty echo
}
disable_echo() {
stty -echo
}
enable_line_wrapping() {
printf '\e[?7h'
}
disable_line_wrapping() {
printf '\e[?7l'
}
open_screen() {
printf '\e[?1049h' # alternative screen buffer
printf '\e[2J' # clear screen
# set the scrolling area and move to (0, 0)
printf '\e[%sr' "${1:-1;$LINES}"
}
close_screen() {
printf '\e[2J' # clear the terminal
printf '\e[;r' # reset the scroll region
printf '\e[?1049l' # restore main screen buffer
}
strlen() {
local nbyte nchar str oLang=$LANG oLcAll=$LC_ALL
LANG=C LC_ALL=C
nbyte=${#1}
LANG=$oLang LC_ALL=$oLcAll
nchar=${#1}
echo $(((nbyte-nchar)/2+nchar))
}
strip_escape() {
if [[ $# -eq 0 ]]; then
while read line; do
strip_escape "$line"
done
else
sed 's/\x1b\[[0-9;]*[mK]//g' <<< "$@"
fi
}
get_num_cpu() {
(grep 'physical id' /proc/cpuinfo 2>/dev/null | wc -l 2>/dev/null) || echo 1
}
print_filename() {
local n="$1"
local d=
if [[ $n == */* ]]; then
d="${n%/*}/"
d="${d/#$PWD\//}" && d="${d/#$HOME\//$tilde/}"
d="$NSH_COLOR_DIR$d"
n="${n##*/}"
fi
[[ -e "$1" ]] && d=$'\e[4m'"$d"
echo -ne "$d$(put_file_color "$n")$n\e[0m"
}
nshcp() {
local op='command cp' && [[ $1 == --mv ]] && shift && op='command mv'
local dst= && for dst in "$@"; do :; done
local overwrite_all=no
local skip_all=no
local cancel=no
local idx=0
local num_thread=$(($(get_num_cpu)*2))
local pids=()
set +m
__worker() {
local s="$1"
local d="$2" && [[ -d "$d" ]] && d="$d/${s##*/}"
if [[ -e "$d" ]]; then
[[ -d "$d" ]] && return
[[ $skip_all == yes ]] && return
if [[ $overwrite_all == no ]]; then
#$(command diff --brief "$s" "$d" &>/dev/null) && return
local ssize=$(stat "$STAT_FSIZE_PARAM" "$s" 2>/dev/null)
local dsize=$(stat "$STAT_FSIZE_PARAM" "$d" 2>/dev/null)
local cmp= && $(command diff --brief "$s" "$d" &>/dev/null) && cmp=', same file'
while true; do
dialog "$(print_filename "$d") already exists\n($(get_hsize $ssize) --> $(get_hsize $dsize)$cmp)" Overwrite Overwrite\ all Skip Skip\ all Rename Cancel
local ans=$?
case "$ans" in
0) ;;
1) overwrite_all=yes;;
#2) return;;
3) skip_all=yes && return;;
4)
dialog --input "New name: " "${d##*/}"
[[ -n $STRING ]] && d="${d%/*}/$STRING" || continue
;;
5) cancel=yes; return;;
*)
dialog --notice "Skipped: $(print_filename "$d")"
[[ $opened == yes ]] && sleep 1
return
;;
esac
[[ $ans != 4 || ! -e "$d" ]] && break
dialog "Sorry, $(print_filename "$d") also exists."
done
fi
fi
[[ -n "${pids[$idx]}" ]] && wait "${pids[$idx]}"
$op "$s" "$d" &
pids[$idx]="$!"
((idx++)) && [[ $idx -ge $num_thread ]] && idx=0
}
while [ $# -gt 1 ]; do
[[ -z "$1" ]] && shift && continue
[[ $opened == yes ]] && dialog --notice "${op#* }: $(print_filename "$1")" # --> $(print_filename "$dst")"
if [[ -e "$1" ]]; then
if [[ -d "$1" ]]; then
local src="$(command cd "$1"; pwd -P)"
local b="${src##*/}"
local tmp="$dst/${1##*/}"
if [[ -d "$tmp" && $op == *cp ]]; then
local i= && for i in {1..99999}; do
if [[ ! -d "${tmp}_($i)" ]]; then
tmp="$(strip_escape "$(print_filename "$tmp")")"
dialog "$tmp already exists.\nchanged name --> $tmp($i)"
[[ $opened == yes ]] && dialog --notice "${op#* }: $tmp"
eval "$op -r \"$1\" \"${tmp}($i)\""
break
fi
done
elif [[ $op == *mv && ! -d "$dst/$b" ]]; then
eval "$op \"$1\" \"$dst\""
else
if [[ -d "$dst" ]]; then
dst="$(command cd "$dst" &>/dev/null; pwd -P)"
else
mkdir -p "$dst"
b=
fi
mkdir -p "$dst/$b"
while read line; do
[[ $line == $src ]] && continue
local n="${line#$src/}"
if [[ -d "$line" ]]; then
mkdir -p "$dst/$b/$n"
else
__worker "$line" "$dst/$b/${n%/*}"
[[ $cancel == yes ]] && break
fi
done < <(find "$src" 2>/dev/null)
[[ $op == command\ mv && -e "$src" ]] && rm -rf "$src" &>/dev/null
fi
else
__worker "$1" "$dst"
fi
else
dialog "$1: No such file or directory"
fi
[[ $cancel == yes ]] && break
shift
done
unset __worker
wait "${pids[@]}"
[[ $cancel == yes ]] && cancel=Cancelled. || cancel=Done.
if [[ "$PWD" != "$(command cd "$dst"; echo "$PWD")" ]]; then
dialog "$cancel\nJump to the destination ($(print_filename "$dst"))?" Yes No
[[ $? == 0 ]] && command cd "$dst"
else
dialog "$cancel"
fi
set -m
}
nshmv() {
nshcp --mv "$@"
}
get_key() {
_key=
local k
local param=''
while [ $# -gt 1 ]; do
param="$param $1"
shift
done
[[ "$get_key_eps" == 1 && "$param" == *-t\ 0\.* ]] && printf -v "${1:-_key}" "%s" "$_key" && return
IFS= read -srn 1 $param _key 2>/dev/null
__ret=$?
if [[ $__ret -eq 0 && "$_key" == '' ]]; then
_key=$'\n'
elif [[ "$_key" == $'\e' ]]; then
while IFS= read -sn 1 -t $get_key_eps k; do
_key=$_key$k
case $k in
$'\e')
_key=$'\e'
break
;;
[a-zA-NP-Z~])
break
;;
esac
done
fi
printf -v "${1:-_key}" "%s" "$_key"
return $__ret
}
get_key_debug() {
_key=
local k
local param=''
while [ $# -gt 1 ]; do
param="$param $1"
shift
done
[[ "$get_key_eps" == 1 && "$param" == *-t\ 0\.* ]] && return
IFS= read -srn 1 $param _key
__ret=$?
if [[ $__ret == 0 && "$_key" == '' ]]; then
_key='\n'
elif [[ "$_key" == $'\e' ]]; then
_key='\e'
while IFS= read -sn 1 -t $get_key_eps k; do
_key="$_key$k"
case $k in
$'\e')
_key='\e'
break
;;
[a-zA-NP-Z~])
break
;;
esac
done
else
echo -e $_key | hexdump | head -n 1 | awk '{print $2}' | sed 's/^0a/\\/'
return
fi
echo "$_key"
return $__ret
}
STRING=
read_string() {
local highlight=0 && [[ $1 == --highlight ]] && highlight=1 && shift
local filename=0 && [[ $1 == --filename ]] && filename=1 && shift
STRING="$1"
local default="$STRING"
local cursor=${#STRING}
[[ $filename -ne 0 && "$STRING" == *\.* ]] && filename=".${STRING##*.}" && cursor=$((cursor-${#filename}))
get_cursor_pos
show_cursor
while true; do
local cx=$((cursor%COLUMNS))
local cy=$((cursor/COLUMNS))
hide_cursor
move_cursor "$((ROW+cy));$COL"
if [[ $cursor -lt ${#STRING} ]]; then
echo "$STRING"
move_cursor "$((ROW+cy));$COL"
fi
[[ $highlight -eq 0 ]] && echo -n "${STRING:0:$cursor}" || print_command "${STRING:0:$cursor}"
show_cursor
get_key KEY </dev/tty
case $KEY in
$'\e'|$'\04')
STRING=
break
;;
$'\t')
local pre="${STRING:0:$cursor}"
local post="${STRING:$cursor}"
STRING="$pre $post"
cursor=$((cursor+4))
;;
$'\177'|$'\b') # backspace
if [ $cursor -gt 0 ]; then
local pre="${STRING:0:$cursor}"
local post="${STRING:$cursor}"
STRING="${pre%?}$post"
move_cursor "$((ROW+cy));$COL"
echo -n "$STRING "
((cursor--))
fi
;;
$'\e[3~') # del
local pre="${STRING:0:$cursor}"
local post="${STRING:$cursor}"
STRING="$pre${post:1}"
echo -n "$STRING "
;;
$'\e[D')
[[ $cursor -gt 0 ]] && ((cursor--))
;;
$'\e[C')
[[ $cursor -lt ${#STRING} ]] && ((cursor++))
;;
$'\e[1~'|$'\e[H')
cursor=0
;;
$'\e[4~'|$'\e[F')
cursor=${#STRING}
;;
$'\n')
cursor=-1
[[ $highlight -ne 0 ]] && move_cursor "$((ROW+cy));$COL" && print_command "$STRING"
break
;;
[[:print:]])
local pre="${STRING:0:$cursor}"
local post="${STRING:$cursor}"
STRING="$pre$KEY$post"
((cursor++))
;;
esac
done
}
get_common_string() {
if [[ "$OSTYPE" == darwin* ]]; then
local item0="$1"
local len=${#item0}
shift
while [ $# -gt 0 ]; do
local item1="$1"
local n= && for ((n=0; n<$len; n++)); do
if [[ ${item0:n:1} != ${item1:n:1} ]]; then
len=$n
break
fi
done
shift
done
echo "${item0:0:$len}"
else
# this doesn't work on mac
echo "$(printf "%s\n" "$@" | sed -e '$!{N;s/^\(.*\).*\n\1.*$/\1\n\1/;D;}')"
fi
}
fuzzy_word() {
local p= && [[ $1 == -n ]] && p='-n' && shift
if [[ $1 == *\"* ]]; then
local word="$1"
local cur="${word%%\"*}"
fuzzy_word -n "$cur"
word="${word:$((${#cur}+1))}"
cur="${word%%\"*}"
echo -n "$cur"
word="${word:$((${#cur}+1))}"
fuzzy_word "$word"
else
if [[ $1 == *$ ]]; then
echo $p "${1:-*}" | sed -e 's/[^.^~^/^*]/*&*/g' -e 's/\*\*/\*/g' -e 's/[\*]*\$[\*]*$//'
else
echo $p "${1:-*}" | sed -e 's/[^.^~^/^*]/*&*/g' -e 's/\*\*/\*/g'
fi
fi
}
put_file_color() {
if [ -h "$1" ]; then
printf "$NSH_COLOR_LNK"
elif [ -d "$1" ]; then
printf "$NSH_COLOR_DIR"
elif [ -x "$1" ]; then
printf "$NSH_COLOR_EXE"
elif [[ $(is_image "$1") == YES ]]; then
printf "$NSH_COLOR_IMG"
else
printf "$NSH_COLOR_TXT"
fi
}
get_hsize() {
if [ $1 -ge 1073741824 ]; then
local t=$(($1*10/1073741824))
echo "$((t/10)).$((t%10)) G"
elif [ $1 -ge 1048576 ]; then
local t=$(($1*10/1048576))
echo "$((t/10)).$((t%10)) M"
elif [ $1 -ge 1024 ]; then
local t=$(($1*10/1024))
echo "$((t/10)).$((t%10)) K"
elif [ $1 -ge 0 ]; then
echo "$1 b"
fi
}
print_number() {
local str="$(echo "${1%%\.*}" | sed ':a;s/\B[0-9]\{3\}\>/,&/;ta' 2>/dev/null)"
[[ $1 == *\.* ]] && str+=".${1#*\.}"
echo "$str"
}
is_image() {
local n="$(echo "$1" | tr '[:upper:]' '[:lower:]')"
[[ "${n%\"}" == *.jpg || "$n" == *.jpeg || "$n" == *.png || "$n" == *.gif || "$n" == *.bmp ]] && echo YES || echo NO
}
is_binary() {
LC_MESSAGES=C grep -Hm1 '^' < "${1-$REPLY}" | grep -q '^Binary'
}
pipe_context() {
local c='>>'
[[ -t 0 ]] && c='->'
[[ -t 1 ]] && c="${c%?}-"
echo "$c"
}
menu() {
disable_line_wrapping >&2
hide_cursor >&2
get_terminal_size </dev/tty
local max_height=$((LINES-1))
local min_height=${NSH_BOTTOM_MARGIN:-20%}
local toprow=
local cursor0="$NSH_MENU_DEFAULT_CURSOR"
local items=()
local cur=-1 cur_bak=0
local popup=0
local hscroll=-1
local return_idx=0
local sel_color="$NSH_MENU_DEFAULT_SEL_COLOR"
local readparam=
local header=
local footer=
local preview=
local return_key=()
local return_fn=()
local search=off
local items_bak=()
local accent_header=
local accent_color0=
local accent_color1=
while [ $# -gt 0 ]; do
case "$1" in
-i|--initial)
shift
cur=$1
;;
-p|--popup)
popup=1
;;
--return-idx)
return_idx=1
;;
--sel-color)
shift
sel_color="$1"
;;
--cursor)
shift
cursor0="$1"
;;
--header)
shift
header="$1"
;;
--footer)
shift
footer="$1"
;;
-r)
readparam='-r'
;;
--preview)
shift
preview="$1"
;;
-h|--height)
shift
max_height=$1 && [[ $max_height -gt $LINES ]] && max_height=$LINES
;;
--hscroll)
hscroll=0
;;
--searchable)
search=on
;;
--key)
shift && return_key+=("$1")
shift && return_fn+=("$1")
;;
--accent)
shift; accent_header="$1"
shift; accent_color0="$1"
shift; accent_color1="$1"
;;
*)
items+=("$1")
;;
esac
shift
done <&1
[[ -z $footer && $search == on ]] && footer=+
if [[ $(pipe_context) == \>* ]]; then
local i=0
local ahlen="${#accent_header}"
local t=$(get_timestamp)
while IFS= read $readparam line; do
if [[ $ahlen -gt 0 ]]; then
if [[ $line == "$accent_header"* ]]; then
line=$'\e'"[${accent_color0}m${line:$ahlen}"
[[ $cur -lt 0 ]] && cur=$i
else
line=$'\e'"[${accent_color1}m$line"
fi
fi
[[ -n "$line" ]] && items+=("$line")
((i++))
[[ $i -eq 100 && $(($(get_timestamp)-t)) -gt 300 ]] && echo -en "\rLoading..." >&2
done
fi
[[ $cur -lt 0 ]] && cur=0
local cursor1="$(strip_escape "$cursor0" | sed 's/./ /g')"
[[ $header == - ]] && header="$cursor1 ${items[0]}" && items=("${items[@]:1}")
local ret=
local beg=0
local cnt=${#items[@]}
local lines=0
[[ $cnt == 0 ]] && return 0
[[ $cur -ge $cnt ]] && cur=$((cnt-1))
display_menu() {
[[ -n $toprow ]] && move_cursor $toprow >&2
lines=${#items[@]}
[[ $search == /* ]] && lines=$max_height
[[ $1 == clear ]] && cur=-1 && header="${header//?/ }" && items=()
local height=$((LINES-$(get_cursor_row < /dev/tty)+1))
[[ $min_height == *% ]] && min_height=$((LINES*${min_height%?}/100))
[[ $height -le $min_height ]] && height=$((min_height))
[[ $height -gt $max_height ]] && height=$((max_height))
[[ $height -gt 1 ]] && ((height--))
[[ -z $footer ]] && ((height++))
[[ -n "$header" ]] && printf "\r\e[0m\e[K$header\n" >&2 && ((height--))
[[ $lines -gt $height ]] && lines=$height
[[ $cur -lt 0 && $1 != show ]] && cur=0
[[ $cur -ge ${#items[@]} ]] && cur=$((${#items[@]}-1))
[[ $cur -ge 0 && $cur -lt $beg ]] && beg=$cur
[[ $cur -ge $((beg+lines)) ]] && beg=$((cur-lines+1))
#[[ $1 == show ]] && beg=0 && lines=${#items[@]}
local i= && for ((i=$beg; i<$((beg+lines)); i++)); do
local m="$cursor1" && [[ $i == $cur ]] && m="$cursor0"
local c=0
local line="${items[$i]}" && [[ $hscroll -gt 0 ]] && line="${line:$hscroll}"
if [[ $i == $cur ]]; then
c="$sel_color"
[[ -n $sel_color && $sel_color != 7 ]] && line="$(strip_escape "$line")"
fi
local cr=$'\n' && [[ -z $footer && $i == $((beg+lines-1)) ]] && cr=
printf "\r%s %b%s\e[0m \e[K$cr" "$m" "\e[0;${c}m" "$line" >&2
done
[[ $1 == show && -z $footer ]] && echo >&2
[[ $1 == show ]] && return
if [[ -n $footer ]]; then
[[ -z $footer || $footer == +* ]] && printf '\r\e[0;7m(%*s/%s)\e[0m\e[K' ${#cnt} $((cur+1)) $cnt >&2
[[ -n $footer && $search != /* ]] && printf "\e[0m\e[K${footer/#+/}\e[0m" >&2
fi
[[ $search == /* ]] && printf "\e[37;41m\e[K$search\e[0m" >&2
[[ $1 == clear ]] && printf '\r\e[K' >&2 && toprow=
if [[ -z $toprow ]]; then
get_cursor_pos < /dev/tty
[[ -n $header ]] && ((lines++))
toprow=$((ROW-lines))
[[ -z $footer ]] && ((toprow++))
move_cursor $toprow >&2
fi
}
local keys="${return_key[@]}"
while true; do
display_menu
get_key KEY < /dev/tty
if [[ $KEY != $'\e' && "$keys" == *$KEY* ]]; then # cannot override ESC
ret="$cur" && [[ $return_idx -eq 0 ]] && ret="$(strip_escape "${items[$ret]}")"
local i= && for ((i=0; i<${#return_key[@]}; i++)); do
if [[ "${return_key[$i]}" == *"$KEY"* ]]; then
if [[ $(type -t "${return_fn[$i]}") == function ]]; then
"${return_fn[$i]}" "$ret"
else
eval "TEMPFUNC() { ${return_fn[$i]}; }"
TEMPFUNC "$ret" "$cur"
fi
break
fi
done
ret=
break
fi
case $KEY in
$'\e'|q)
if [[ ${#items_bak[@]} -gt 0 ]]; then
items=("${items_bak[@]}")
items_bak=()
[[ $cur -lt 0 ]] && cur=0
cnt=${#items[@]}
cur=$cur_bak
search=on
else
break
fi
;;
j|$'\e[B')
[[ $cur -lt $((cnt-1)) ]] && cur=$((cur+1))
;;
k|$'\e[A')
[[ $cur -gt 0 ]] && cur=$((cur-1))
;;
h)
if [[ $hscroll -ge 0 ]]; then ((hscroll--)); [[ $hscroll -lt 0 ]] && hscroll=0; fi
;;
0)
[[ $hscroll -ge 0 ]] && hscroll=0
;;
g)
cur=0
;;
G)
cur=$((${#items[@]}-1))
;;
$'\04')
cur=$((cur+(lines-1)/2))
;;
$'\25')
cur=$((cur-(lines-1)/2))
;;
$'\t')
if [ -n "$preview" ]; then
"$preview" "$(strip_escape "${items[$cur]}")" >&2 < /dev/tty
hide_cursor >&2
fi
;;
$'\n'|' '|l|$'\e[C')
if [[ $KEY == l && $hscroll -ge 0 ]]; then
((hscroll++))
else
ret=$cur
[[ $return_idx -eq 0 ]] && ret="${items[$ret]}"
break
fi
;;
'/')
if [[ $search == on || $search == /* ]]; then
cur_bak=$cur
[[ $search != /* ]] && search=/
[[ $hscroll -ge 0 ]] && hscroll=0
items_bak=("${items[@]}")
show_cursor >&2
display_menu
NEXT_KEY=
while true; do
KEY="$NEXT_KEY" && NEXT_KEY=
[[ -z "$KEY" ]] && get_key KEY </dev/tty
case $KEY in
$'\e'|$'\t'|$'\n')
[[ ${#items[@]} -gt 0 ]] && cur=0
break
;;
$'\177'|$'\b')
search="${search%?}"
;;
$'\e'*)
;;
*)
search="$search$KEY"
;;
esac
[[ $search == /?* ]] && IFS=$'\n' read -d "" -ra items < <(printf '%s\n' "${items_bak[@]}" | grep -i "${search#/}")
beg=0 && cur=-1 && cnt=${#items[@]}
get_key -t $get_key_eps NEXT_KEY </dev/tty
[[ -z $NEXT_KEY ]] && display_menu
done
hide_cursor >&2
fi
;;
z)
local newrow=$((toprow*80/100))
[[ $newrow -le 2 ]] && newrow=2
local i= && for ((i=0; i<$((toprow-newrow)); i++)); do
move_cursor "$LINES;9999" >&2
echo >&2
done
toprow=$newrow
;;
esac
done
[[ -z $ret ]] && cur=-1
[[ $popup -eq 0 ]] && display_menu show || display_menu clear
unset -f display_menu
if [[ $opened != yes ]]; then
enable_line_wrapping >&2
show_cursor >&2
fi
[[ -n "$ret" ]] && strip_escape "$ret"
}
nshls() {
__d=() && __f=()
local l="${1:-.}"
if [[ -z $lssort ]]; then
while read ff; do
f="$l/$ff"
if [ -d "$f" ]; then
__d+=("${f##*/}/")
elif [ -e "$f" ]; then
__f+=("${f##*/}")
fi
done < <(echo "$lsparam \"$l\"" | xargs ls 2>/dev/null | sort --ignore-case)
[[ ${#__d[@]} -gt 0 ]] && printf '%s\n' "${__d[@]}"
[[ ${#__f[@]} -gt 0 ]] && printf '%s\n' "${__f[@]}"
else
while read ff; do
f="$l/$ff"
if [ -d "$f" ]; then
echo "${f##*/}/"
elif [ -e "$f" ]; then
echo "${f##*/}"
fi
done < <(echo "$lsparam $lssort \"$l\"" | xargs ls 2>/dev/null)
fi
return 0
}
cpu() {
disable_line_wrapping
(ps -ax -o %cpu,user,pid,cmd --sort=-%cpu 2>/dev/null || ps -ax -r) | head
enable_line_wrapping
}
mem() {
disable_line_wrapping
(ps -ax -o %mem,user,pid,cmd --sort=-%mem 2>/dev/null || ps -ax -m) | head
enable_line_wrapping
}
gpu() {
disable_line_wrapping
__skip_header() {
while IFS= read line; do
[[ "$line" == '|===='* ]] && break
done
}
local res=()
while true; do
__skip_header
local ll=
while IFS= read line; do
ll="$ll$line "
if [[ $line == +----* ]]; then
ll=($ll)
local w= && for w in "${ll[@]}"; do
[[ $w == *% ]] && res[${ll[1]}]="$(printf '%2d %4s' "${ll[1]}" "$w")" && break
done
ll=
elif [[ $line != \|* ]]; then
break
fi
done
while IFS= read line; do
if [[ $line == *\ PID\ * ]]; then
ll="${line%% PID *} PID" && ll=${#ll}
__skip_header
while IFS= read line; do
[[ $line != \|* ]] && break
line="${line:0:$ll}"
local pid="${line##* }"
line=($line)
res[${line[1]}]+=" $(ps -p $pid -o user= -o pid= -o command= 2>/dev/null)"
done
fi
done
break
done < <(nvidia-smi 2>/dev/null)
[[ ${#res[@]} -gt 0 ]] && echo ' # UTIL USER PID' && printf '%s\n' "${res[@]}"
enable_line_wrapping
}
disk() {
disable_line_wrapping
local cur="$PWD"
get_terminal_size
local max_h=$((LINES-3))
while IFS= read line; do
echo "$line" && ((max_h--))
done < <(df -h .)
local bars=(" " "| " "|| " "||| " "|||| " "||||| " "|||||| " "||||||| " "|||||||| " "||||||||| " "||||||||||")
while true; do
local l0=() && local l1=()
local s0=() && local s1=()
local total=0
while read f; do
if [[ -d "$f" ]]; then
if [[ "$f" == \.\. ]]; then
l0=("../" "${l0[@]}")
s0=("-1" "${s0[@]}")
elif [[ "$f" != \. && "$f" != \.\. ]]; then
l0+=("$f/")
size=$(du -sk "$f" 2>/dev/null | cut -f 1)
size=$((size*1024))
total=$((total+size))
s0+=("$size")
fi
elif [[ -e "$f" ]]; then
l1+=("$f")
size=$(stat "$STAT_FSIZE_PARAM" "$f" 2>/dev/null)
[ -z $size ] && size=0
total=$((total+size))
s1+=("$(stat "$STAT_FSIZE_PARAM" "$f" 2>/dev/null)")
fi
done < <(ls -a | sort --ignore-case)
local files=("${l0[@]}" "${l1[@]}")
local sideinfo=("${s0[@]}" "${s1[@]}")
# sort by size
local i= && for ((i=0; i<$((${#files[@]}-1)); i++)); do
[[ ${files[$i]} == ../ ]] && continue
local idx=$i
local j= && for ((j=$((i+1)); j<${#files[@]}; j++)); do
[[ ${sideinfo[$j]} -gt ${sideinfo[$idx]} ]] && idx=$j
done
local t=${sideinfo[$i]}
sideinfo[$i]=${sideinfo[$idx]}
sideinfo[$idx]=$t
t="${files[$i]}"
files[$i]="${files[$idx]}"
files[$idx]="$t"
done
echo -e "\r\033[4m$NSH_COLOR_DIR$PWD\033[0m ($(get_hsize $total))"
local ret="$(for ((i=0; i<${#files[@]}; i++)); do
local p=' ' && [[ ${sideinfo[$i]} -ge 0 ]] && p="[${bars[$(((${sideinfo[$i]}*100/$total+5)/10))]}]"
printf "%8s %s\n" "$(get_hsize ${sideinfo[$i]})" "$p $(put_file_color "${files[$i]}")${files[$i]}"
done | menu --popup --return-idx --cursor '' --sel-color 7 --key 'h' '[[ $(pwd) != / ]] && echo 0' --key 'o' 'echo cd \"${files[$1]}\"' --key 'x' 'echo quit here' --footer "+ $(draw_shortcut o Open z Zoom x QuitHere q Quit)")"
move_cursor $(($(get_cursor_row)-1)) && printf '\e[K'
[[ -z "$ret" ]] && break
[[ $ret == cd\ * ]] && eval "$ret" && cur="$(pwd)" && break
[[ $ret == quit\ here ]] && cur="$(pwd)" && break
cd "${files[$ret]}" &>/dev/null
done
cd "$cur"
enable_line_wrapping
}
__grep_match_case=OFF
__grep_whole_word=OFF
__grep_results=ALL
__grep_prev=
nshgrep() {
if [[ $# -eq 0 ]]; then
echo -en "$NSH_PROMPT search: "
read_string "$__grep_prev"
echo
[[ -z "$STRING" ]] && return
elif [[ $# -eq 1 ]]; then
STRING="$1"
else
echo 'Too many arguments' >&2
return 1
fi
__grep_prev="$STRING"