-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathxpanes
executable file
·2157 lines (1987 loc) · 62.6 KB
/
xpanes
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
readonly XP_SHELL="/usr/bin/env bash"
# @Author Yamada, Yasuhiro
# @Filename xpanes
set -u
readonly XP_VERSION="4.1.3"
## trap might be updated in 'xpns_pre_execution' function
trap 'rm -f "${XP_CACHE_HOME}"/__xpns_*$$; xpns_clean_session' EXIT
## --------------------------------
# Error constants
## --------------------------------
# Invalid option/argument
readonly XP_EINVAL=4
# Could not open tty.
readonly XP_ETTY=5
# Invalid layout.
readonly XP_ELAYOUT=6
# Impossible layout: Small pane
readonly XP_ESMLPANE=7
# Log related exit status is 2x.
## Could not create a directory.
readonly XP_ELOGDIR=20
## Could not directory to store logs is not writable.
readonly XP_ELOGWRITE=21
# User's intentional exit is 3x
## User exit the process intentionally by following warning message.
readonly XP_EINTENT=30
## All the panes are closed before processing due to user's options/command.
readonly XP_ENOPANE=31
# Necessary commands are not found
readonly XP_ENOCMD=127
# ===============
# XP_THIS_FILE_NAME is supposed to be "xpanes".
readonly XP_THIS_FILE_NAME="${0##*/}"
readonly XP_THIS_DIR="$(cd "$(dirname "${BASH_SOURCE[0]:-$0}")" && pwd)"
readonly XP_ABS_THIS_FILE_NAME="${XP_THIS_DIR}/${XP_THIS_FILE_NAME}"
# Prevent cache directory being created under root / directory in any case.
# This is quite rare case (but it can be happened).
readonly XP_USER_HOME="${HOME:-/tmp}"
# Basically xpanes follows XDG Base Direcotry Specification.
# https://specifications.freedesktop.org/basedir-spec/basedir-spec-0.6.html
XDG_CACHE_HOME="${XDG_CACHE_HOME:-${XP_USER_HOME}/.cache}"
readonly XP_CACHE_HOME="${XDG_CACHE_HOME}/xpanes"
# This is supposed to be xpanes-12345(PID)
readonly XP_SESSION_NAME="${XP_THIS_FILE_NAME}-$$"
# Temporary window name is tmp-12345(PID)
readonly XP_TMP_WIN_NAME="tmp-$$"
readonly XP_EMPTY_STR="EMPTY"
readonly XP_SUPPORT_TMUX_VERSION_LOWER="1.8"
# Check dependencies just in case.
# Even POSIX compliant commands are only used in this program.
# `xargs`, `sleep`, `mkfifo` are omitted because minimum functions can work without them.
readonly XP_DEPENDENCIES="${XP_DEPENDENCIES:-tmux grep sed tr od echo touch printf cat sort pwd cd mkfifo}"
## --------------------------------
# User customizable shell variables
## --------------------------------
TMUX_XPANES_EXEC=${TMUX_XPANES_EXEC:-tmux}
TMUX_XPANES_PANE_BORDER_FORMAT="${TMUX_XPANES_PANE_BORDER_FORMAT:-#[bg=green,fg=black] #T #[default]}"
TMUX_XPANES_PANE_BORDER_STATUS="${TMUX_XPANES_PANE_BORDER_STATUS:-bottom}"
TMUX_XPANES_PANE_DEAD_MESSAGE=${TMUX_XPANES_PANE_DEAD_MESSAGE:-'\033[41m\033[4m\033[30m Pane is dead: Press [Enter] to exit... \033[0m\033[39m\033[49m'}
XP_DEFAULT_TMUX_XPANES_LOG_FORMAT="[:ARG:].log.%Y-%m-%d_%H-%M-%S"
TMUX_XPANES_LOG_FORMAT="${TMUX_XPANES_LOG_FORMAT:-${XP_DEFAULT_TMUX_XPANES_LOG_FORMAT}}"
XP_DEFAULT_TMUX_XPANES_LOG_DIRECTORY="${XP_CACHE_HOME}/logs"
TMUX_XPANES_LOG_DIRECTORY="${TMUX_XPANES_LOG_DIRECTORY:-${XP_DEFAULT_TMUX_XPANES_LOG_DIRECTORY}}"
## --------------------------------
# Initialize Options
## --------------------------------
# options which work individually.
# readonly XP_FLAG_OPTIONS="[hVdetxs]"
# options which need arguments.
readonly XP_ARG_OPTIONS="[ISclnCRB]"
readonly XP_DEFAULT_LAYOUT="tiled"
readonly XP_DEFAULT_REPSTR="{}"
readonly XP_DEFAULT_CMD_UTILITY="echo {} "
readonly XP_SSH_CMD_UTILITY="ssh -o StrictHostKeyChecking=no {} "
readonly XP_OFS="${XP_OFS:- }"
XP_OPTIONS=()
XP_ARGS=()
XP_STDIN=()
XP_BEGIN_ARGS=()
XP_IS_PIPE_MODE=0
XP_OPT_IS_SYNC=1
XP_OPT_DRY_RUN=0
XP_OPT_ATTACH=1
XP_OPT_LOG_STORE=0
XP_REPSTR=""
XP_DEFAULT_SOCKET_PATH_BASE="${XP_CACHE_HOME}/socket"
XP_DEFAULT_SOCKET_PATH="${XP_DEFAULT_SOCKET_PATH_BASE}.$$"
XP_SOCKET_PATH="${XP_SOCKET_PATH:-${XP_DEFAULT_SOCKET_PATH}}"
XP_NO_OPT=0
XP_OPT_CMD_UTILITY=0
XP_CMD_UTILITY=""
XP_LAYOUT="${XP_DEFAULT_LAYOUT}"
XP_MAX_PANE_ARGS=""
XP_OPT_SET_TITLE=0
XP_OPT_CHANGE_BORDER=0
XP_OPT_EXTRA=0
XP_OPT_SPEEDY=0
XP_OPT_SPEEDY_AWAIT=0
XP_OPT_USE_PRESET_LAYOUT=0
XP_OPT_CUSTOM_SIZE_COLS=
XP_OPT_CUSTOM_SIZE_ROWS=
XP_OPT_BULK_COLS=
XP_WINDOW_WIDTH=
XP_WINDOW_HEIGHT=
XP_COLS=
XP_COLS_OFFSETS=
XP_OPT_DEBUG=0
XP_OPT_IGNORE_SIZE_LIMIT=0
## --------------------------------
# Logger
# $1 -- Log level (i.e Warning, Error)
# $2 -- Message
# i.e
# xpanes:Error: invalid option.
#
# This log format is created with reference to openssl's one.
# $ echo | openssl -a
# openssl:Error: '-a' is an invalid command.
## --------------------------------
xpns_msg() {
local _loglevel="$1"
local _msgbody="$2"
local _msg="${XP_THIS_FILE_NAME}:${_loglevel}: ${_msgbody}"
printf "%s\\n" "${_msg}" >&2
}
xpns_msg_info() {
xpns_msg "Info" "$1"
}
xpns_msg_warning() {
xpns_msg "Warning" "$1"
}
xpns_msg_debug() {
if [[ $XP_OPT_DEBUG -eq 1 ]]; then
xpns_msg "Debug" "$(date "+[%F_%T]"):${FUNCNAME[1]}:$1"
fi
}
xpns_msg_error() {
xpns_msg "Error" "$1"
}
xpns_usage_warn() {
xpns_usage_short >&2
echo "Try '${XP_THIS_FILE_NAME} --help' for more information." >&2
}
xpns_usage_short() {
cat << _EOS_
Usage: ${XP_THIS_FILE_NAME} [OPTIONS] [argument ...]
Usage(Pipe mode): command ... | ${XP_THIS_FILE_NAME} [OPTIONS] [<command> ...]
_EOS_
}
xpns_usage() {
cat << USAGE
Usage:
${XP_THIS_FILE_NAME} [OPTIONS] [argument ...]
Usage(Pipe mode):
command ... | ${XP_THIS_FILE_NAME} [OPTIONS] [<command> ...]
OPTIONS:
-h,--help Display this help and exit.
-V,--version Output version information and exit.
-B <begin-command> Run <begin-command> before processing <command> in each pane. Multiple options are allowed.
-c <command> Set <command> to be executed in each pane. Default is \`echo {}\`.
-d,--desync Make synchronize-panes option off in new window.
-e Execute given arguments as is. Same as \`-c '{}'\`
-I <repstr> Replacing one or more occurrences of <repstr> in command provided by -c or -B. Default is \`{}\`.
-C NUM,--cols=NUM Number of columns of window layout.
-R NUM,--rows=NUM Number of rows of window layout.
-l <layout> Set the preset of window layout. Recognized layout arguments are:
t tiled
eh even-horizontal
ev even-vertical
mh main-horizontal
mv main-vertical
-n <number> Set the maximum number of <argument> taken for each pane.
-s Speedy mode: Run command without opening an interactive shell.
-ss Speedy mode AND close a pane automatically at the same time as process exiting.
-S <socket-path> Set a full alternative path to the server socket.
-t Display each argument on the each pane's border as their title.
-x Create extra panes in the current active window.
--log[=<directory>] Enable logging and store log files to ~/.cache/xpanes/logs or <directory>.
--log-format=<FORMAT> Make name of log files follow <FORMAT>. Default is \`${XP_DEFAULT_TMUX_XPANES_LOG_FORMAT}\`.
--ssh Same as \`-t -s -c 'ssh -o StrictHostKeyChecking=no {}'\`.
--stay Do not switch to new window.
--bulk-cols=NUM1[,NUM2 ...] Set number of columns on multiple rows (i.e, "2,2,2" represents 2 cols x 3 rows).
--debug Print debug message.
Copyright (c) 2021 Yamada, Yasuhiro
Released under the MIT License.
https://github.com/greymd/tmux-xpanes
USAGE
}
# Show version number
xpns_version() {
echo "${XP_THIS_FILE_NAME} ${XP_VERSION}"
}
# Get version number for tmux
xpns_get_tmux_version() {
local _tmux_version=""
if ! ${TMUX_XPANES_EXEC} -V &> /dev/null; then
# From tmux 0.9 to 1.3, there is no -V option.
_tmux_version="tmux 0.9-1.3"
else
_tmux_version="$( ${TMUX_XPANES_EXEC} -V)"
fi
read -r _ _ver <<< "${_tmux_version}"
# Strip the leading "next-" part that is present in tmux versions that are
# in development. Eg: next-3.3
echo "${_ver//next-/}"
}
# Check whether the prefered tmux version is greater than host's tmux version.
# $1 ... Prefered version.
# $2 ... Host tmux version(optional).
# In case of tmux version is 1.7, the result will be like this.
# 0 is true, 1 is false.
## arg -> result
# func 1.5 1.7 -> 0
# func 1.6 1.7 -> 0
# func 1.7 1.7 -> 0
# func 1.8 1.7 -> 1
# func 1.9 1.7 -> 1
# func 1.9a 1.7 -> 1
# func 2.0 1.7 -> 1
xpns_tmux_is_greater_equals() {
local _check_version="$1"
local _tmux_version="${2:-$(xpns_get_tmux_version)}"
# Simple numerical comparison does not work because there is the version like "1.9a".
if [[ "$( printf "%s\\n%s" "${_tmux_version}" "${_check_version}" | sort -n | head -n 1)" != "${_check_version}" ]]; then
return 1
else
return 0
fi
}
xpns_get_local_tmux_conf() {
local _conf_name="$1"
local _session="${2-}"
{
if [[ -z "${_session-}" ]]; then
${TMUX_XPANES_EXEC} show-window-options
else
${TMUX_XPANES_EXEC} -S "${_session}" show-window-options
fi
} | grep "^${_conf_name}" |
{
read -r _ _v
printf "%s\\n" "${_v}"
}
}
xpns_get_global_tmux_conf() {
local _conf_name="$1"
local _session="${2-}"
{
if [[ -z "${_session-}" ]]; then
${TMUX_XPANES_EXEC} show-window-options -g
else
${TMUX_XPANES_EXEC} -S "${_session}" show-window-options -g
fi
} | grep "^${_conf_name}" |
{
read -r _ _v
printf "%s\\n" "${_v}"
}
}
# Disable allow-rename because
# window separation does not work correctly
# if "allow-rename" option is on
xpns_suppress_allow_rename() {
local _default_allow_rename="$1"
local _session="${2-}"
if [[ "${_default_allow_rename-}" == "on" ]]; then
## Temporary, disable "allow-rename"
xpns_msg_debug "'allow-rename' option is 'off' temporarily."
if [[ -z "${_session-}" ]]; then
${TMUX_XPANES_EXEC} set-window-option -g allow-rename off
else
${TMUX_XPANES_EXEC} -S "${_session}" set-window-option -g allow-rename off
fi
fi
}
# Restore default "allow-rename"
# Do not write like 'xpns_restore_allow_rename "some value" "some value" > /dev/null'
# In tmux 1.6, 'tmux set-window-option' might be stopped in case of redirection.
xpns_restore_allow_rename() {
local _default_allow_rename="$1"
local _session="${2-}"
if [[ "${_default_allow_rename-}" == "on" ]]; then
xpns_msg_debug "Restore original value of 'allow-rename' option."
if [[ -z "${_session-}" ]]; then
${TMUX_XPANES_EXEC} set-window-option -g allow-rename on
else
${TMUX_XPANES_EXEC} -S "${_session}" set-window-option -g allow-rename on
fi
fi
}
# func "11" "2"
# => 6
# 11 / 2 = 5.5 => ceiling => 6
xpns_ceiling() {
local _divide="$1"
shift
local _by="$1"
printf "%s\\n" $(((_divide + _by - 1) / _by))
}
# func "10" "3"
# => 4 3 3
# Divide 10 into 3 parts as equally as possible.
xpns_divide_equally() {
local _number="$1"
shift
local _count="$1"
local _upper _lower _upper_count _lower_count
_upper="$(xpns_ceiling "$_number" "$_count")"
_lower=$((_upper - 1))
_lower_count=$((_upper * _count - _number))
_upper_count=$((_count - _lower_count))
eval "printf '${_upper} %.0s' {1..$_upper_count}"
((_lower_count > 0)) && eval "printf '${_lower} %.0s' {1..$_lower_count}"
}
# echo 3 3 3 3 | func
# => 3 6 9 12
xpns_nums_accumulate_sum() {
local s=0
while read -r n; do
((s = s + n))
printf "%s " "$s"
done < <( cat | tr ' ' '\n')
}
# func 3 2 2 2
# => 4 4 1
#
# For example, "3 2 2 2" represents following cell positions
# 1 2 3
# 1 [] [] [] => 3 rows
# 2 [] [] => 2 rows
# 3 [] [] => 2 rows
# 4 [] [] => 2 rows
#
# After the transposition, it must be "4 4 1" which represents below
# 1 2 3 4
# 1 [] [] [] [] => 4 rows
# 2 [] [] [] [] => 4 rows
# 3 [] => 1 rows
xpns_nums_transpose() {
local _colnum="$1"
local _spaces=
local _result=
xpns_msg_debug "column num = $_colnum, input = $*"
_spaces="$(for i in "$@"; do
printf "%${i}s\\n"
done)"
# 'for' statement does not work somehow
_result="$(while read -r i; do
## This part is depending on the following 'cut' behavior
## $ echo 1234 | cut -c 5
## => result is supposed to be empty
printf "%s\\n" "$_spaces" | cut -c "$i" | grep -c ' '
done < <(xpns_seq 1 "${_colnum}") | xpns_newline2space)"
xpns_msg_debug "result = $_result"
printf "%s\\n" "$_result"
}
# Adjust size of columns and rows in accordance with given N
# func <col> <row> <N>
# i.e:
# func "" "" 20
# => returns 4 5
# func "6" 0 20
# => returns 6 4
xpns_adjust_col_row() {
local col="${1:-0}"
shift
local row="${1:-0}"
shift
local N="$1"
shift
local fix_col_flg
local fix_row_flg
((col != 0)) && fix_col_flg=1 || fix_col_flg=0
((row != 0)) && fix_row_flg=1 || fix_row_flg=0
# This is just a author (@greymd)'s preference.
if ((fix_col_flg == 0)) && ((fix_row_flg == 0)) && ((N == 2)); then
col=2
row=1
printf "%d %d\\n" "${col}" "${row}"
return
fi
# If both values are provided, col is used.
if ((fix_col_flg == 1)) && ((fix_row_flg == 1)); then
row=0
fix_row_flg=0
fi
# This algorhythm is almost same as tmux default
# https://github.com/tmux/tmux/blob/2.8/layout-set.c#L436
while ((col * row < N)); do
((fix_row_flg != 1)) && ((row = row + 1))
if ((col * row < N)); then
((fix_col_flg != 1)) && ((col = col + 1))
fi
done
printf "%d %d\\n" "${col}" "${row}"
}
# Make each line unique by adding index number
# echo aaa bbb ccc aaa ccc ccc | xargs -n 1 | xpns_unique_line
# aaa-1
# bbb-1
# ccc-1
# aaa-2
# ccc-2
# ccc-3
#
# Eval is used because associative array is not supported before bash 4.2
xpns_unique_line() {
local _val_name
while read -r line; do
_val_name="__xpns_hash_$(printf "%s" "${line}" | xpns_value2key)"
# initialize variable
eval "${_val_name}=\${${_val_name}:-0}"
# increment variable
eval "${_val_name}=\$(( ++${_val_name} ))"
printf "%s\\n" "${line}-$(eval printf "%s" "\$${_val_name}")"
done
}
#
# Generate log file names from given arguments.
# Usage:
# echo <arg1> <arg2> ... | xpns_log_filenames <FORMAT>
# Return:
# File names.
# Example:
# $ echo aaa bbb ccc aaa ccc ccc | xargs -n 1 | xpns_log_filenames '[:ARG:]_[:PID:]_%Y%m%d.log'
# aaa-1_1234_20160101.log
# bbb-1_1234_20160101.log
# ccc-1_1234_20160101.log
# aaa-2_1234_20160101.log
# ccc-2_1234_20160101.log
# ccc-3_1234_20160101.log
#
xpns_log_filenames() {
local _arg_fmt="$1"
local _full_fmt=
_full_fmt="$(date "+${_arg_fmt}")"
cat |
# 1st argument + '-' + unique number (avoid same argument has same name)
xpns_unique_line |
while read -r _arg; do
cat <<< "${_full_fmt}" |
sed "s/\\[:ARG:\\]/${_arg}/g" |
sed "s/\\[:PID:\\]/$$/g"
done
}
## --------------------------------
# Normalize directory by making following conversion.
# * Tilde expansion.
# * Remove the slash '/' at the end of the dirname.
# Usage:
# xpns_normalize_directory <direname>
# Return:
# Normalized <dirname>
## --------------------------------
xpns_normalize_directory() {
local _dir="$1"
# Remove end of slash '/'
_dir="${_dir%/}"
# tilde expansion
_dir="${_dir/#~/${HOME}}"
printf "%s\\n" "${_dir}"
}
## --------------------------------
# Ensure existence of given directory
# Usage:
# xpns_is_valid_directory <direname>
# Return:
# Absolute path of the <dirname>
## --------------------------------
xpns_is_valid_directory() {
local _dir="$1"
local _checkfile="${XP_THIS_FILE_NAME}.$$"
# Check directory.
if [[ ! -d "${_dir}" ]]; then
# Create directory
if mkdir "${_dir}"; then
xpns_msg_info "${_dir} is created."
else
xpns_msg_error "Failed to create ${_dir}"
exit ${XP_ELOGDIR}
fi
fi
# Try to create file.
# Not only checking directory permission,
# but also i-node and other misc situations.
if ! touch "${_dir}/${_checkfile}"; then
xpns_msg_error "${_dir} is not writable."
rm -f "${_dir}/${_checkfile}"
exit ${XP_ELOGWRITE}
fi
rm -f "${_dir}/${_checkfile}"
}
# Convert array to string which is can be used as command line argument.
# Usage:
# xpns_arr2args <array object>
# Example:
# array=(aaa bbb "ccc ddd" eee "f'f")
# xpns_arr2args "${array[@]}"
# @returns "'aaa' 'bbb' 'ccc ddd' 'eee' 'f\'f'"
# Result:
xpns_arr2args() {
local _arg=""
# If there is no argument, usage will be shown.
if [[ $# -lt 1 ]]; then
return 0
fi
for i in "$@"; do
_arg="${i}"
# Use 'cat <<<"input"' command instead of 'echo',
# because such the command recognizes option like '-e'.
cat <<< "${_arg}" |
# Escaping single quotations.
sed "s/'/'\"'\"'/g" |
# Surround argument with single quotations.
sed "s/^/'/;s/$/' /" |
# Remove new lines
tr -d '\n'
done
}
# Extract first field to generate window name.
# ex, $2 = 'aaa bbb ccc'
# return = aaa-12345(PID)
xpns_generate_window_name() {
local _unprintable_str="${1-}"
shift
# Leave first 200 characters to prevent
# the name exceed the maximum length of tmux window name (2000 byte).
printf "%s\\n" "${1:-${_unprintable_str}}" |
( read -r _name _ && printf "%s\\n" "${_name:0:200}-$$" )
}
# Convert any string (including multi-byte chars) to another string
# which can be handled as tmux window name.
xpns_value2key() {
od -v -tx1 -An | tr -dc 'a-zA-Z0-9' | tr -d '\n'
}
# Restore string encoded by xpns_value2key function.
xpns_key2value() {
read -r _key
# shellcheck disable=SC2059
printf "$(printf "%s" "$_key" | sed 's/../\\x&/g')"
}
# Remove empty lines
# This function behaves like `awk NF`
xpns_rm_empty_line() {
{
cat
printf "\\n"
} | while IFS= read -r line; do
# shellcheck disable=SC2086
set -- ${line-}
if [[ $# != 0 ]]; then
printf "%s\\n" "${line}"
fi
done
}
# Enable logging feature to the all the panes in the target window.
xpns_enable_logging() {
local _window_name="$1"
shift
local _index_offset="$1"
shift
local _log_dir="$1"
shift
local _log_format="$1"
shift
local _unprintable_str="$1"
shift
local _args=("$@")
local _args_num=$(($# - 1))
# Generate log files from arguments.
local _idx=0
while read -r _logfile; do
# Start logging
xpns_msg_debug "Start logging pipe-pane(cat >> '${_log_dir}/${_logfile}')"
${TMUX_XPANES_EXEC} \
pipe-pane -t "${_window_name}.$((_idx + _index_offset))" \
"cat >> '${_log_dir}/${_logfile}'" # Tilde expansion does not work here.
_idx=$((_idx + 1))
done < <(
for i in $(xpns_seq 0 "${_args_num}"); do
# Replace empty string.
printf "%s\\n" "${_args[i]:-${_unprintable_str}}"
done | xpns_log_filenames "${_log_format}"
)
}
## Print "1" on the particular named pipe
xpns_notify() {
local _wait_id="$1"
shift
local _fifo=
_fifo="${XP_CACHE_HOME}/__xpns_${_wait_id}"
xpns_msg_debug "Notify to $_fifo"
printf "%s\\n" 1 > "$_fifo" &
}
xpns_notify_logging() {
local _window_name="$1"
shift
local _args_num=$(($# - 1))
for i in $(xpns_seq 0 "${_args_num}"); do
xpns_notify "log_${_window_name}-${i}-$$"
done
}
xpns_notify_sync() {
local _window_name="$1"
shift
local _args_num=$(($# - 1))
for i in $(xpns_seq 0 "${_args_num}"); do
xpns_notify "sync_${_window_name}-${i}-$$" &
done
}
xpns_is_window_alive() {
local _window_name="$1"
shift
local _speedy_await_flag="$1"
shift
local _def_allow_rename="$1"
shift
if ! ${TMUX_XPANES_EXEC} display-message -t "$_window_name" -p > /dev/null 2>&1; then
xpns_msg_info "All the panes are closed before displaying the result."
if [[ "${_speedy_await_flag}" -eq 0 ]]; then
xpns_msg_info "Use '-s' option instead of '-ss' option to avoid this behavior."
fi
xpns_restore_allow_rename "${_def_allow_rename-}"
exit ${XP_ENOPANE}
fi
}
xpns_inject_title() {
local _target_pane="$1"
shift
local _message="$1"
shift
local _pane_tty=
_pane_tty="$( ${TMUX_XPANES_EXEC} display-message -t "${_target_pane}" -p "#{pane_tty}")"
printf "\\033]2;%s\\033\\\\" "${_message}" > "${_pane_tty}"
xpns_msg_debug "target_pane=${_target_pane} pane_title=${_message} pane_tty=${_pane_tty}"
}
xpns_is_pane_title_required() {
local _title_flag="$1"
shift
local _extra_flag="$1"
shift
local _pane_border_status=
_pane_border_status=$(xpns_get_local_tmux_conf "pane-border-status")
if [[ $_title_flag -eq 1 ]]; then
return 0
elif [[ ${_extra_flag} -eq 1 ]] &&
[[ "${_pane_border_status}" != "off" ]] &&
[[ -n "${_pane_border_status}" ]]; then
## For -x option
# Even the -t option is not specified, it is required to inject pane title here.
# Because user expects the title is displayed on the pane if the original window is
# generated from tmux-xpanes with -t option.
return 0
fi
return 1
}
# Set pane titles for each pane for -t option
xpns_set_titles() {
local _window_name="$1"
shift
local _index_offset="$1"
shift
local _index=0
local _pane_index=
for arg in "$@"; do
_pane_index=$((_index + _index_offset))
xpns_inject_title "${_window_name}.${_pane_index}" "${arg}"
_index=$((_index + 1))
done
}
# Send command to the all the panes in the target window.
xpns_send_commands() {
local _window_name="$1"
shift
local _index_offset="$1"
shift
local _repstr="$1"
shift
local _cmd="$1"
shift
local _index=0
local _pane_index=
local _exec_cmd=
for arg in "$@"; do
_exec_cmd="${_cmd//${_repstr}/${arg}}"
_pane_index=$((_index + _index_offset))
${TMUX_XPANES_EXEC} send-keys -t "${_window_name}.${_pane_index}" "${_exec_cmd}" C-m
_index=$((_index + 1))
done
}
# Separate window vertically, when the number of panes is 1 or 2.
xpns_organize_panes() {
local _window_name="$1"
shift
local _args_num="$1"
## ----------------
# Default behavior
## ----------------
if [[ "${_args_num}" -eq 1 ]]; then
${TMUX_XPANES_EXEC} select-layout -t "${_window_name}" even-horizontal
elif [[ "${_args_num}" -gt 1 ]]; then
${TMUX_XPANES_EXEC} select-layout -t "${_window_name}" tiled
fi
## ----------------
# Update layout
## ----------------
if [[ "${XP_LAYOUT}" != "${XP_DEFAULT_LAYOUT}" ]]; then
${TMUX_XPANES_EXEC} select-layout -t "${_window_name}" "${XP_LAYOUT}"
fi
}
#
# Generate sequential number descending order.
# seq is not used because old version of
# seq does not generate descending order.
# $ xpns_seq 3 0
# 3
# 2
# 1
# 0
#
xpns_seq() {
local _num1="$1"
local _num2="$2"
eval "printf \"%d\\n\" {$_num1..$_num2}"
}
xpns_wait_func() {
local _wait_id="$1"
local _fifo="${XP_CACHE_HOME}/__xpns_${_wait_id}"
local _arr=("$_fifo")
local _fifo_arg=
_fifo_arg=$(xpns_arr2args "${_arr[@]}")
xpns_msg_debug "mkfifo $_fifo"
mkfifo "${_fifo}"
xpns_msg_debug "grep -q 1 ${_fifo_arg}"
printf "%s\\n" "grep -q 1 ${_fifo_arg}"
}
# Split a new window into multiple panes.
#
xpns_split_window() {
local _window_name="$1"
shift
local _log_flag="$1"
shift
local _title_flag="$1"
shift
local _speedy_flag="$1"
shift
local _await_flag="$1"
shift
local _pane_base_index="$1"
shift
local _repstr="$1"
shift
local _cmd_template="$1"
shift
local _exec_cmd=
local _sep_count=0
local args=("$@")
_last_idx=$((${#args[@]} - 1))
for i in $(xpns_seq $_last_idx 0); do
xpns_msg_debug "Index:${i} Argument:${args[i]}"
_sep_count=$((_sep_count + 1))
_exec_cmd="${_cmd_template//${_repstr}/${args[i]}}"
## Speedy mode
if [[ $_speedy_flag -eq 1 ]]; then
_exec_cmd=$(xpns_inject_wait_command "${_log_flag}" "${_title_flag}" "${_speedy_flag}" "${_await_flag}" "$i" "${_exec_cmd}")
# Execute command as a child process of default-shell.
${TMUX_XPANES_EXEC} split-window -t "${_window_name}" -h -d "${_exec_cmd}"
else
# Open login shell and execute command on the interactive screen.
${TMUX_XPANES_EXEC} split-window -t "${_window_name}" -h -d
fi
# Restraining that size of pane's width becomes
# less than the minimum size which is defined by tmux.
if [[ ${_sep_count} -gt 2 ]]; then
${TMUX_XPANES_EXEC} select-layout -t "${_window_name}" tiled
fi
done
}
#
# Create new panes on existing window.
# Usage:
# func <window name> <offset of index> <number of pane>
#
xpns_prepare_extra_panes() {
local _window_name="$1"
shift
local _pane_base_index="$1"
shift
local _log_flag="$1"
shift
local _title_flag="$1"
shift
local _speedy_flg="$1"
shift
local _await_flg="$1"
shift
# specify a pane which has the biggest index number.
# Because pane_id may not be immutable.
# If the small number of index is specified here, correspondance between pane_title and command can be slip off.
${TMUX_XPANES_EXEC} select-pane -t "${_window_name}.${_pane_base_index}"
# split window into multiple panes
xpns_split_window \
"${_window_name}" \
"${_log_flag}" \
"${_title_flag}" \
"${_speedy_flg}" \
"${_await_flg}" \
"${_pane_base_index}" \
"$@"
}
xpns_get_joined_begin_commands() {
local _commands="$1"
if [[ "${#XP_BEGIN_ARGS[*]}" -lt 1 ]]; then
printf "%s" "${_commands}"
return
fi
printf "%s\\n" "${XP_BEGIN_ARGS[@]}" "${_commands}"
}
xpns_inject_wait_command() {
local _log_flag="$1"
shift
local _title_flag="$1"
shift
local _speedy_flg="$1"
shift
local _await_flg="$1"
shift
local _idx="$1"
shift
local _exec_cmd="$1"
shift
## Speedy mode + logging
if [[ "${_log_flag}" -eq 1 ]] && [[ "${_speedy_flg}" -eq 1 ]]; then
# Wait for start of logging
# Without this part, logging thread may start after new process is finished.
# Execute function to wait for logging start.
_exec_cmd="$(xpns_wait_func "log_${_window_name}-${_idx}-$$")"$'\n'"${_exec_cmd}"
fi
## Speedy mode (Do not allow to close panes before the separation is finished).
if [[ "${_speedy_flg}" -eq 1 ]]; then
_exec_cmd="$(xpns_wait_func "sync_${_window_name}-${_idx}-$$")"$'\n'${_exec_cmd}
fi
## -s: Speedy mode (Not -ss: Speedy mode + nowait)
if [[ "${_await_flg}" -eq 1 ]]; then
local _msg
_msg="$(xpns_arr2args "${TMUX_XPANES_PANE_DEAD_MESSAGE}" | sed 's/"/\\"/g')"
_exec_cmd="${_exec_cmd}"$'\n'"${XP_SHELL} -c \"printf -- ${_msg} >&2 && read\""
fi
printf "%s" "${_exec_cmd}"
}
xpns_new_window() {
local _window_name="$1"
shift
local _attach_flg="$1"
shift
local _speedy_flg="$1"
shift
local _exec_cmd="$1"
shift
local _window_id=
# Create new window.
if [[ "${_attach_flg}" -eq 1 ]]; then
if [[ "${_speedy_flg}" -eq 1 ]]; then
_window_id=$(${TMUX_XPANES_EXEC} new-window -n "${_window_name}" -F '#{window_id}' -P "${_exec_cmd}")
else
_window_id=$(${TMUX_XPANES_EXEC} new-window -n "${_window_name}" -F '#{window_id}' -P)
fi
else
# Keep background
if [[ "${_speedy_flg}" -eq 1 ]]; then
_window_id=$(${TMUX_XPANES_EXEC} new-window -n "${_window_name}" -F '#{window_id}' -P -d "${_exec_cmd}")
else
_window_id=$(${TMUX_XPANES_EXEC} new-window -n "${_window_name}" -F '#{window_id}' -P -d)
fi
fi
printf "%s" "${_window_id}"
}
xpns_new_pane_vertical() {
local _window_id="$1"
shift
local _cell_height="$1"
shift
local _speedy_flg="$1"
shift
local _exec_cmd="$1"
shift
local _pane_id=
if [[ "${_speedy_flg}" -eq 1 ]]; then
_pane_id="$(${TMUX_XPANES_EXEC} split-window -t "$_window_id" -v -d -l "${_cell_height}" -F '#{pane_id}' -P "${_exec_cmd}")"
else
_pane_id="$(${TMUX_XPANES_EXEC} split-window -t "$_window_id" -v -d -l "${_cell_height}" -F '#{pane_id}' -P)"
fi
printf "%s\\n" "${_pane_id}"
}
xpns_split_pane_horizontal() {
local _target_pane_id="$1"
shift
local _cell_width="$1"
shift
local _speedy_flg="$1"
shift
local _exec_cmd="$1"
shift
if [[ "${_speedy_flg}" -eq 1 ]]; then
${TMUX_XPANES_EXEC} split-window -t "$_target_pane_id" -h -d -l "$_cell_width" "${_exec_cmd}"
else
${TMUX_XPANES_EXEC} split-window -t "$_target_pane_id" -h -d -l "$_cell_width"
fi
}
xpns_prepare_window() {
local _window_name="$1"
shift
local _log_flag="$1"
shift