-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathdeclzsh
executable file
·1537 lines (1371 loc) · 56.5 KB
/
declzsh
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 zsh
# -*- mode: shell-script -*-
# vim:ft=zsh:sw=4:sts=4:et
# Started from Zle or from command line
#
# Copyright (c) 2017 Sebastian Gniazdowski
emulate -LR zsh -o extendedglob -o typesetsilent -o warncreateglobal
local IFS=$' \n'
local -F2 SECONDS=0
# Run as script?
if [[ "$0" != declzsh || -n "$ZSH_SCRIPT" ]]; then
# Handle $0 according to the Zsh Plugin Standard:
# https://zdharma-continuum.github.io/Zsh-100-Commits-Club/Zsh-Plugin-Standard.html
0="${${ZERO:-${0:#$ZSH_ARGZERO}}:-${(%):-%N}}"
0="${${(M)0##/*}:-$PWD/$0}"
fpath+=( "$0:h" )
else
# Don't leak any functions
typeset -g declzsh_ef
declzsh_ef=( ${(k)functions} )
trap "unset -f -- \"\${(k)functions[@]:|declzsh_ef}\" &>/dev/null; unset declzsh_ef" EXIT
trap "unset -f -- \"\${(k)functions[@]:|declzsh_ef}\" &>/dev/null; unset declzsh_ef; return 1" INT
fi
# Already autoloaded in *.plugin.zsh, here it's for Zshelldoc
autoload -Uz -- @declzsh-process-buffer colors
colors
# Debug array, initially for the debug view in the ZUI app
local -a DECLZSH_DEBUG_MSGS
# Append message to the debug view
/declzsh-dbg() { DECLZSH_DEBUG_MSGS+=( "$*" ); }
# Append multiple messages to the debug view
/declzsh-dbg-array() { DECLZSH_DEBUG_MSGS+=( "$@" ); }
# Print-out the debug messages
/declzsh-dbg-print-out() {
DECLZSH_DEBUG_MSGS=( "${DECLZSH_DEBUG_MSGS[@]/<ZSHRCSIZE>/$(( ${#zshrc} - 5 ))}" )
local -a lines
lines=( "${(f@)zshrc}" )
DECLZSH_DEBUG_MSGS=( "${DECLZSH_DEBUG_MSGS[@]/<ZSHRCLINES>/${#lines}}" )
{ local ver="$(<${ZPLGM[BIN_DIR]}/.git/refs/heads/master)" } 2>/dev/null
[[ -z "$ver" ]] && ver="unknown (no .git/refs/heads/master)" || ver="${ver[1,7]}"
DECLZSH_DEBUG_MSGS=( "${DECLZSH_DEBUG_MSGS[@]/<ZPLGVERSION>/$ver}" )
{ local ver="$(<$DECLZSH_REPO_DIR/.git/refs/heads/master)" } 2>/dev/null
[[ -z "$ver" ]] && ver="unknown (no .git/refs/heads/master)" || ver="${ver[1,7]}"
DECLZSH_DEBUG_MSGS=( "${DECLZSH_DEBUG_MSGS[@]/<DECLZSHVERSION>/$ver}" )
print -rl -- "${DECLZSH_DEBUG_MSGS[@]}";
}
local -a ice_order nval_ices
ice_order=(
wait lucid silent service svn proto from teleid as id-as depth cloneopts
ver has if load unload blockf pick bpick src notify mv cp atinit atclone
atload atpull make run-atpull nocd cloneonly trackbinds bindmap multisrc
compile nocompile nocompletions reset-prompt
# Include all additional ices – after
# stripping them from the possible: ''
${(@s.|.)${ZPLG_EXTS[ice-mods]//\'\'/}}
)
nval_ices=(
blockf silent lucid trackbinds cloneonly nocd run-atpull
nocompletions svn
# Include only those additional ices,
# don't have the '' in their name, i.e.
# aren't designed to hold value
${(@)${(@s.|.)ZPLG_EXTS[ice-mods]}:#*\'\'*}
)
# Initial debug message
/declzsh-dbg "ZSH version: $ZSH_VERSION ($ZSH_PATCHLEVEL), machine: $CPUTYPE $VENDOR $OSTYPE, LANG: $LANG"
if [[ ${+ZPLGM} = 1 ]]; then
/declzsh-dbg "Zinit version: <ZPLGVERSION>, declare-zshrc version: <DECLZSHVERSION>"
/declzsh-dbg "Zinit BIN_DIR: ${ZPLGM[BIN_DIR]/$HOME/~}, HOME_DIR: ${ZPLGM[HOME_DIR]/$HOME/~}, PLUGINS_DIR: ${ZPLGM[PLUGINS_DIR]/$HOME/~}, COMPLETIONS_DIR: ${ZPLGM[COMPLETIONS_DIR]/$HOME/~}"
else
/declzsh-dbg "${ZUI[RED]}Zinit not loaded${ZUI[FMT_END]}"
fi
/declzsh-dbg ""
/declzsh-dbg-array "Active plugins:" "${ZPLG_REGISTERED_PLUGINS[@]/(#s)/ }"
/declzsh-dbg ""
+declzsh-error() {
[[ -n "$OPT_QUIET" && "$1" != \!* ]] && return 0
local opt="${(M)1:#(-r|-rl|-l|-rnl|-rln|-n|-nl|-rn|-nr)}"
[[ -n "$opt" ]] && shift
print -r $opt -- "$fg[red]ERROR$reset_color:" "$@"
}
+declzsh-warn() {
[[ -n "$OPT_QUIET" && "$1" != \!* ]] && return 0
local opt="${(M)1:#(-r|-rl|-l|-rnl|-rln|-n|-nl|-rn|-nr)}"
[[ -n "$opt" ]] && shift
print -r $opt -- "$fg[red]WARNING$reset_color:" "$@"
}
+declzsh-info() {
[[ -n "$OPT_QUIET" && "$1" != \!* ]] && return 0
local opt="${(M)1:#(-r|-rl|-l|-rnl|-rln|-n|-nl|-rn|-nr)}"
[[ -n "$opt" ]] && shift
print -r $opt -- ${fg[yellow]}${${(M)1#-}:+INFO: }"${1#-}" "${@[2,-1]}"$reset_color
}
+declzsh-msg() {
[[ -n "$OPT_QUIET" && "$1" != \!* ]] && return 0
local opt="${(M)1:#(-r|-rl|-l|-rnl|-rln|-n|-nl|-rn|-nr)}"
[[ -n "$opt" ]] && shift
local -A map
map=(
RE "${fg[red]:-x}" GR "${fg[green]:-x}"
YE "${fg[yellow]:-x}" BL "${fg[blue]:-x}"
CY "${fg[cyan]:-x}" MA "${fg[magenta]:-x}"
RS "${reset_color:-x}"
)
print -r $opt -- "${@//(#m)[A-Z][A-Z]/${${map[$MATCH]:-$MATCH}:#x}}"$reset_color
}
#
# CONSTANTS
#
local -A TOKEN_TYPES
TOKEN_TYPES=(
# Precommand
'builtin' 1
'command' 1
'exec' 1
'nocorrect' 1
'noglob' 1
'pkexec' 1
# Control flow
# Tokens that at "command position" are followed by a command
$'\x7b' 2 # {
$'\x28' 2 # (
'()' 2
'while' 2
'until' 2
'if' 2
'then' 2
'elif' 2
'else' 2
'do' 2
'time' 2
'coproc' 2
'!' 2
# Command separators
'|' 3
'||' 3
'&&' 3
'|&' 4
'&!' 4
'&|' 4
'&' 4
';' 4
)
#
# Parse options
#
local -a OPT_HELP OPT_VERBOSE OPT_QUIET OPT_NOANSI \
OPT_DISABLE OPT_ENABLE OPT_TOGGLE OPT_ADD \
OPT_ADD_FLAG OPT_PURGE OPT_OUT
local -A opthash
zparseopts -E -D -A opthash h=OPT_HELP -help=OPT_HELP \
v=OPT_VERBOSE -verbose=OPT_VERBOSE \
q=OPT_QUIET -quiet=OPT_QUIET \
n=OPT_NOANSI -noansi=OPT_NOANSI \
o:=OPT_OUT -out:=OPT_OUT \
DD+:=OPT_DISABLE -zp-disable+:=OPT_DISABLE \
EE+:=OPT_ENABLE -zp-enable+:=OPT_ENABLE \
TT+:=OPT_TOGGLE -zp-toggle+:=OPT_TOGGLE \
AA+:=OPT_ADD -zp-add+=OPT_ADD_FLAG \
PP+:=OPT_PURGE -zp-purge+:=OPT_PURGE || \
{ echo "Improper options given, see help (-h/--help)"; return 1; }
integer i l
local -a mbegin mend match
local MATCH; integer MBEGIN MEND
# Filter-out odd indices
i=0; l=$#OPT_DISABLE+1; OPT_DISABLE=( ${OPT_DISABLE[@]/(#m)*/$OPT_DISABLE[++i%2 ? l:i]} )
i=0; l=$#OPT_ENABLE+1; OPT_ENABLE=( ${OPT_ENABLE[@]/(#m)*/$OPT_ENABLE[++i%2 ? l:i]} )
i=0; l=$#OPT_TOGGLE+1; OPT_TOGGLE=( ${OPT_TOGGLE[@]/(#m)*/$OPT_TOGGLE[++i%2 ? l:i]} )
i=0; l=$#OPT_ADD+1; OPT_ADD=( ${OPT_ADD[@]/(#m)*/$OPT_ADD[++i%2 ? l:i]} )
i=0; l=$#OPT_PURGE+1; OPT_PURGE=( ${OPT_PURGE[@]/(#m)*/$OPT_PURGE[++i%2 ? l:i]} )
i=0; l=$#OPT_OUT+1; OPT_OUT=( ${OPT_OUT[@]/(#m)*/$OPT_OUT[++i%2 ? l:i]} )
# PARAMETERS
#
# Document to process
local zshrc_in_path="${1:-${ZDOTDIR:-~}/.zshrc}" zshrc_path zshrc
zshrc_path=${~zshrc_in_path}
[[ -n "$OPT_ADD_FLAG" ]] && shift
#
# Parsing state-machine parameters
#
# The bits returned by -zini-process-buffer
local token prev_token spaces prev_spaces next_token next_spaces
# Command detection
integer at_command=1 in_zinit=0
# Functions
local fun_name
integer next_fun=0 cur_fun=0 prev_fun=0
# Depths in functions, i.e. -1 not in function, 0 in one function, etc.
integer depth=0 prev_depth=0 fun_depth=-1 anon_depth=-1 descentff=0 descentfa=0
# Nested functions tracking
integer nested_fun=0 next_nested_fun=0 prev_nested_fun=0
local -a fun_stack_depths
# Feature detection, call tree, reversed call tree
local -A features call_tree rev_call_tree funs
local -a known_functions sourced_files
# Text and commands data
integer was_zinit=0 pre_block_end=0 post_block_begin=0
local -A cmd3
local -a cmdlist
integer coidx=1
#
# Other, general parameters
#
# Common
integer j own_order=0 own_quoting=0
local input tmp
local REPLY
local -a reply
# @declzsh-process-buffer output parameters, declare
# them to prevent globals from being created
local -a DECLZSH_PB_WORDS DECLZSH_PB_SPACES \
DECLZSH_PB_WORDS_BEGINNINGS DECLZSH_PB_ALL
#
# Examine zshrc
#
[[ ! -e "$zshrc_path" ]] && { +declzsh-error "No such file \`$zshrc_path'${ZDOTDIR:+ (using \$ZDOTDIR)}"; return 1; }
[[ ! -f "$zshrc_path" ]] && { +declzsh-error "\`$zshrc_path' isn't a plain, regular file${ZDOTDIR:+ (using \$ZDOTDIR)}"; return 1; }
[[ ! -r "$zshrc_path" ]] && { +declzsh-error "No read permissions to \`$zshrc_path'${ZDOTDIR:+ (using \$ZDOTDIR)}"; return 1; }
[[ ! -w "$zshrc_path" ]] && { +declzsh-error "No write permissions to \`$zshrc_path'${ZDOTDIR:+ (using \$ZDOTDIR)}"; return 1; }
[[ ! -s "$zshrc_path" ]] && { +declzsh-error "File \`$zshrc_path' is empty, aborting"; return 1; }
local -A theme
#
# Parsing-related functions
#
# FUNCTION: .declzsh-tokenize-zsh-rc {{{
# Runs @declzsh-process-buffer() on $zshrc (containing the loaded
# .zshrc file). The *-process-buffer() is a general function that
# exists in other projects, is an autoload function, and is kept
# in separate file "@declzsh-process-buffer".
.declzsh-tokenize-zsh-rc() {
@declzsh-process-buffer "$zshrc" 1
}
# }}}
# FUNCTION: .declzsh_verify_tokenization {{{
# To large extent verifies if tokenization was correct.
# Also removes the test-tokens added to input zshrc (this
# is how the verification is implemented - it is being
# checked if in the output data structures there's the
# `test' token - it's the last one to be parsed, so its
# existence in the structures confirms correct parsing
# of the preceding text, i.e. the whole zshrc).
.declzsh_verify_tokenization() {
local lasta="${DECLZSH_PB_WORDS[-1]}" lastb="${DECLZSH_PB_ALL[-2]}"
if [[ "$lasta" != "test" || "$lastb" != "test" ]]; then
return 1
fi
DECLZSH_PB_WORDS[-1]=()
DECLZSH_PB_SPACES[-1]=()
DECLZSH_PB_SPACES[-1]="${DECLZSH_PB_SPACES[-1]%$'\n'}"
DECLZSH_PB_ALL[-2,-1]=()
DECLZSH_PB_ALL[-1]="${DECLZSH_PB_ALL[-1]%$'\n'}"
return 0
}
# }}}
# FUNCTION: .declzsh_tokenization_failed {{{
# Outputs a message that zshrc didn't parse, and
# includes information what can be a possible cause.
.declzsh_tokenization_failed() {
+declzsh-error "Failed to parse zshrc. Possible causes:"
+declzsh-info ""
+declzsh-info "1. Zsh <= 5.4.2 doesn't parse closing parenthesis ')' for '\$('"
+declzsh-info " if it is at other line, not at the same line as '\$('. So:"
+declzsh-info ""
+declzsh-info " \$(ls -1 | perl -alne 'echo foo')"
+declzsh-info ""
+declzsh-info " will parse correctly, while:"
+declzsh-info ""
+declzsh-info " \$(ls -1 | perl -alne 'echo foo'"
+declzsh-info " )"
+declzsh-info ""
+declzsh-info " will not. A more sophisticated not-parsing example:"
+declzsh-info ""
+declzsh-info " asmcmds+=(\${(o)\$(ls -1 | perl -alne 'echo foo'"
+declzsh-info " )})"
+declzsh-info ""
+declzsh-info "2. A regular syntax error may exist, try: zcompile .zshrc, or"
+declzsh-info " start a zsh session and see if there are error messages."
+declzsh-info ""
}
# }}}
# FUNCTION: .declzsh-process-zsh-rc {{{
# Parses tokens of the loaded zshrc and detects:
# - functions
# - block preceding zinit commands
# - block with those commands
# - block following them
#
# Uses parameters filled by @declzsh-process-buffer:
# - $DECLZSH_PB_WORDS - tokens
# - $DECLZSH_PB_SPACES - spaces in front of each token, +1 at the end
.declzsh-process-zsh-rc() {
integer i j size="${#DECLZSH_PB_WORDS}"
for (( i=1; i<=size; ++ i )); do
token="${DECLZSH_PB_WORDS[i]}"
spaces="${DECLZSH_PB_SPACES[i]}"
next_token="${DECLZSH_PB_WORDS[i+1]}"
next_spaces="${DECLZSH_PB_SPACES[i+1]}"
cur_fun=0 prev_fun=0 descentff=0 descentfa=0
nested_fun=0 prev_nested_fun=0
(( next_fun )) && { next_fun=0 cur_fun=1 prev_fun=0 anon_depth=-1; }
(( next_nested_fun )) && { next_nested_fun=0 nested_fun=1 prev_nested_fun=0; }
# Explicit future-function
if [[ "$token" = "function"(|$'\r') && ( "$fun_depth" -lt 0 ) && ( $anon_depth -lt 0 ) ]]; then
next_fun=1 cur_fun=0 prev_fun=0 anon_depth=-1
# Detect top-level prev-function differentiating from anonymous function
elif [[ "$token" = "()"(|$'\r') && ( "$fun_depth" -lt 0 ) && ( $anon_depth -lt 0 ) ]]; then
if [[ "$spaces" = *$'\n'* || -z "$prev_token" || "${TOKEN_TYPES[$prev_token]}" = [1234] ]]; then
next_fun=0 cur_fun=0 prev_fun=0 anon_depth=$depth
else
next_fun=0 cur_fun=0 prev_fun=1 anon_depth=-1
fi
# Must be a nested future-function
elif [[ "$token" = "function"(|$'\r') ]]; then
next_nested_fun=1 nested_fun=0 prev_nested_fun=0
# Is it a nested prev-function?
elif [[ "$token" = "()"(|$'\r') && "$nested_fun" -eq 0 && "$depth" -gt "$fun_stack_depths[-1]" ]]; then
if [[ "$spaces" != *$'\n'* && -n "$prev_token" && "${TOKEN_TYPES[$prev_token]}" != [1234] ]]; then
next_nested_fun=0 nested_fun=0 prev_nested_fun=1
fi
elif [[ "$token" = "{"(|$'\r') ]]; then
(( ++ depth ))
elif [[ "$token" = "}"(|$'\r') ]]; then
(( -- depth ))
fi
# Check if any final function-flag is raised
if (( cur_fun )); then
fun_name="${token%$'\r'}"
fun_depth="$depth"
fun_stack_depths+=( "$depth" )
elif (( prev_fun )); then
fun_name="${prev_token%$'\r'}"
fun_depth="$depth"
fun_stack_depths+=( "$depth" )
fi
# Track nested functions
if (( nested_fun + prev_nested_fun )); then
fun_stack_depths+=( "$depth" )
fi
# Ascent to function - skip '{'
if (( fun_depth >= 0 && depth == (fun_depth + 1) )) && [[ "$token" = "{"(|$'\r') ]]; then
:
# In function
elif (( fun_depth >= 0 && depth > fun_depth )); then
if [[ "$token" != [[:blank:]]#\#* ]]; then
# : # do something with a non-comment function token
funs[$fun_name]+="${spaces}${token}"
fi
# Handle descent from nested function
if (( ${#fun_stack_depths} > 0 && depth == fun_stack_depths[-1] && prev_depth == fun_stack_depths[-1] + 1 )); then
fun_stack_depths[-1]=()
fi
# In anonymous-function
elif (( anon_depth >= 0 && depth > anon_depth )); then
if (( ${#fun_stack_depths} > 0 && depth == fun_stack_depths[-1] && prev_depth == fun_stack_depths[-1] + 1 )); then
fun_stack_depths[-1]=()
fi
# Descent from function - skip '}'
elif (( fun_depth >= 0 && depth == fun_depth && prev_depth == fun_depth + 1 )); then
descentff=1
# Descent from anon
elif (( anon_depth >= 0 && depth == anon_depth && prev_depth == anon_depth + 1 )); then
descentfa=1
fi
# Anon function in top-level
if (( anon_depth >= 0 && fun_depth < 0 )); then
[[ "$token" != [[:blank:]]#\#* ]] && preamble+="${spaces}${token}"
fi
### Detect function call
# Check for introduction of Zinit call
if [[ "$spaces" = *$'\n'* || -z "$prev_token" || "${TOKEN_TYPES[$prev_token]}" = [1234] ]]; then
if [[ $spaces != [[:blank:]]#"\\"(|$'\r')$'\n'[[:blank:]]# || ${TOKEN_TYPES[$prev_token]} = [1234] ]]; then
at_command=1
[[ "$token" != [[:blank:]]#\#* ]] && in_zinit=0 || { (( in_zinit )) && in_zinit=1; }
fi
(( in_zinit )) && {
(( 2*i - 1 - post_block_begin > 7*4 )) && { /declzsh-dbg "WARNING: many non-Zinit commands in Zinit block"; }
# A new command (i.e. $spaces has a new line, etc.) - move the post-block pointer
post_block_begin=2*i-1
}
fi
# Command token
if (( at_command )); then
at_command=0
# Zinit call not in function
if [[ "$cur_fun" -eq 0 && "$next_token" != "()"(|$'\r') && "$fun_stack_depths[-1]" -le "0" ]]; then
if [[ "$token" = (zinit|zini|zi) || ( "$token" = ":" && "$next_token" = (zinit|zini|zpl) ) ]]; then
in_zinit=1
(( was_zinit == 0 )) && {
# Initially point the pre-block at the previous token
# (the result will be zero if zinit command is first)
pre_block_end=2*(i-1)
for (( j=i-1; j >= 1; j -- )); do
# Include also some preceding comments
[[ "${DECLZSH_PB_WORDS[j]}" != [[:blank:]]#\#* || "${DECLZSH_PB_SPACES[j+1]}" = *$'\n'*$'\n'* ]] && { pre_block_end=2*j; break; }
done
}
was_zinit=1
# Revive at_command mode if disabled zinit command
[[ "$token" = ":" ]] && at_command=1
fi
fi
# Prepare call-tree extraction
# Search for this possible function ($token) in current script
local tokenEx="${(q)name}/${(q)token}"
local found="${known_functions[(r)$tokenEx]}" candidate="" last_candidate=""
integer nth=1
if [[ -z "$found" ]]; then
# Search for other scripts having this possible function
tokenEx="*/${(q)token}"
while (( 1 )); do
candidate="${known_functions[(rn:nth:)$tokenEx]}"
if [[ -n "$candidate" ]]; then
last_candidate="$candidate"
found="${sourced_files[(r)*${candidate:h}*]}"
[[ -n "$found" ]] && break
else
break
fi
(( ++ nth ))
done
found="$last_candidate"
fi
if [[ -z "$fun_name" ]]; then
local needle="${(q)name}/zsd_script_body"
else
local needle="${(q)name}/${(q)fun_name}"
fi
# Extract call-tree and reversed call-tree, and also features
if [[ "$cur_fun" -eq 0 && "$next_token" != "()" && -n "$found" && "$fun_stack_depths[-1]" -le "0" ]]; then
if [[ -z "$fun_name" ]]; then
[[ "${call_tree[${(q)name}/zsd_script_body]}" != *[[:blank:]]"${(q)found}"[[:blank:]]* ]] && {
call_tree[${(q)name}/zsd_script_body]+=" ${(q)found} "
}
[[ "${rev_call_tree[${(q)found}]}" != *[[:blank:]]"$needle"[[:blank:]]* ]] && {
rev_call_tree[${(q)found}]+=" ${(q)name}/zsd_script_body "
}
else
[[ "${call_tree[${(q)name}/${(q)fun_name}]}" != *[[:blank:]]"${(q)found}"[[:blank:]]* ]] && {
call_tree[${(q)name}/${(q)fun_name}]+=" ${(q)found} "
}
[[ ${rev_call_tree[${(q)found}]} != *[[:blank:]]"$needle"[[:blank:]]* ]] && {
rev_call_tree[${(q)found}]+=" ${(q)name}/${(q)fun_name} "
}
fi
fi
if [[ "$cur_fun" -eq 0 && "$next_token" != "()" && "$fun_stack_depths[-1]" -le "0" ]]; then
# Features
if [[ "$token" = ${(~j:|:)feature_list} ]]; then
[[ -z "$fun_name" ]] && local fkey="zsd_script_body" || local fkey="$fun_name"
[[ "${features[$fkey]}" != *[[:blank:]]"$token"[[:blank:]]* ]] && features[$fkey]+=" $token "
[[ "$token" = "source" ]] && sourced_files+=( "$next_token" )
fi
fi
fi
# Late disable of anonymous function
if (( descentfa )); then
anon_depth=-1
# Late disable of normal function
elif (( descentff )); then
fun_name=""
fun_depth=-1
fun_stack_depths[-1]=()
# No-function text gathering
elif (( next_fun == 0 && cur_fun == 0 && prev_fun == 0 && anon_depth < 0 && fun_depth < 0 )); then
if [[ "$next_token" != "()"(|$'\r') || "$next_spaces" = *$'\n'* || "${TOKEN_TYPES[$token]}" = [34] ]]; then
[[ "$token" != [[:blank:]]#\#* ]] && : # do something with script-body token
fi
fi
# History of state
prev_depth="$depth"
prev_token="$token"
prev_spaces="$spaces"
done
# If zinit command ended the zshrc, detect it here
(( in_zinit )) && post_block_begin=2*i-1
if (( pre_block_end == 0 )); then
# No zinit commands -> pre-block ends at
# the last token in the file
(( post_block_begin == 0 )) && pre_block_end=2*(i-1)
else
j=0+(pre_block_end/2)
# Soft command-separator?
if [[ "${TOKEN_TYPES[${DECLZSH_PB_WORDS[j]}]}" = "3" ]]; then
integer found=0
for (( j=(pre_block_end/2)-1; j>=1; -- j )); do
token="${DECLZSH_PB_WORDS[j]}"
spaces="${DECLZSH_PB_SPACES[j]}"
next_token="${DECLZSH_PB_WORDS[j+1]}"
next_spaces="${DECLZSH_PB_SPACES[j+1]}"
(( j >= 2 )) && prev_token="${DECLZSH_PB_WORDS[j-1]}" || prev_token=""
if [[ "${TOKEN_TYPES[$token]}" = "4" ]]; then
found=1
pre_block_end=2*j
break
# Soft command separator can have spaces after it
elif [[ "$spaces" = *$'\n'* && "${TOKEN_TYPES[$prev_token]}" != "3" ]]; then
pre_block_end=2*(j-1)
found=1
break
fi
done
# Didn't found, and therefore reached beginning of file
(( found == 0 )) && pre_block_end=0
fi
fi
if (( post_block_begin == 0 )); then
post_block_begin=2*i-1
else
# Detect not related trailing comments
for (( j=(post_block_begin+1)/2-1; j >= 1; -- j )); do
[[ "${DECLZSH_PB_WORDS[j]}" = [[:blank:]]#\#* && "${DECLZSH_PB_WORDS[j]}" != [[:blank:]]#\#[[:blank:]]#zinit* ]] && {
post_block_begin=2*j-1
} || break
done
# Detect if compinit follows
integer count=$(( size-(post_block_begin+1)/2 ))
local next_token_2
(( count = (count > 15) ? 15 : count ))
for (( j=(post_block_begin+1)/2; count > 0; ++ j, -- count )); do
token="${DECLZSH_PB_WORDS[j]}"
next_token="${DECLZSH_PB_WORDS[j+1]}"
next_token_2="${DECLZSH_PB_WORDS[j+2]}"
next_spaces="${DECLZSH_PB_SPACES[j+1]}"
if [[ "$token" = "autoload" && ( "$next_token" = "compinit" || "$next_token_2" = "compinit" ) ]]; then
[[ "$next_token" = "compinit" ]] && { post_block_begin=2*(j+2)-1; j+=1; count=count-1; }
[[ "$next_token_2" = "compinit" ]] && { post_block_begin=2*(j+3)-1; j+=2; count=count-2; }
elif [[ "$token" = "compinit" && ( "$next_spaces" = *$'\n'* || "${TOKEN_TYPES[$next_token]}" = 4 ) ]]; then
# TODO: soft-connected following tokens can be also included
post_block_begin=2*(j+1)-1
break
fi
done
fi
}
# }}}
# FUNCTION: .declzsh-process-zinit-commands {{{
# Processes block with zinit commands established earlier
# in .declzsh-process-zsh-rc() and generates $cmdlist array
# which holds serialized hashes of every zinit invocation,
# mixed-in additional (external) commands, comments.
#
# Uses parameters filled by @declzsh-process-buffer:
# - $DECLZSH_PB_WORDS - tokens
# - $DECLZSH_PB_SPACES - spaces in front of each token, +1 at the end
.declzsh-process-zinit-commands() {
integer i
cmd3=()
# Reset parameters used in .declzsh-process-zsh-rc
prev_depth=0 prev_token="" prev_spaces=""
# From start to end of zinit block
# (pre_block_end/2)+1 - from the one space-token element after the pre-block
# (post_block_begin+1)/2-1 - to one space-token element before the post-block
# (post_block_begin+1)/2 - to the next, first element after last zinit command
for (( i=(pre_block_end/2)+1; i<=(post_block_begin+1)/2-1; ++ i )); do
token="${DECLZSH_PB_WORDS[i]}"
spaces="${DECLZSH_PB_SPACES[i]}"
next_token="${DECLZSH_PB_WORDS[i+1]}"
next_spaces="${DECLZSH_PB_SPACES[i+1]}"
# New command?
if [[ "$spaces" = *$'\n'* || -z "$prev_token" || "${TOKEN_TYPES[$prev_token]}" = [1234] ]]; then
# Remember trailing spaces even though they might
# get overwritten later, if the single command is
# multi-line, i.e. if it uses \-line endings. The
# last stored spaces are the command's spaces.
if [[ "${TOKEN_TYPES[$prev_token]}" = [34] ]]; then
# When command ends with explicit command separator,
# then remember white spaces after that separator
cmd3[aspaces]="$spaces"
elif [[ "$spaces" != (|$'\r')$'\n' ]]; then
# Remember spaces if they're not single newline, and
# if what follows isn't a comment. So basically spaces
# between commands are remembered. Spaces before comments
# are not (but comment-remembering handles this)
if [[ "$token" != [[:blank:]]#\#* ]]; then
cmd3[aspaces]="$spaces"
else
unset 'cmd3[aspaces]'
fi
else
unset 'cmd3[aspaces]'
fi
if [[ "$spaces" = [[:blank:]]#"\\"(|$'\r')$'\n'[[:blank:]]# ]]; then
cmd3[\\-break_$in_zinit]="$spaces"
else
in_zinit=1
if [[ "${cmd3[c]}" = "zinit" && "${cmd3[sub]}" = "ice" ]]; then
cmdlist[coidx+1]="${(j: :)${(qkv)cmd3[@]}}"
/declzsh-dbg "Stored <ice>/$coidx-cmd: ${cmdlist[coidx+1]}"
elif [[ "${cmd3[c]}" = "zinit" && "${cmd3[sub]}" != "ice" ]]; then
cmdlist[coidx+2]="${(j: :)${(qkv)cmd3[@]}}"
/declzsh-dbg "Stored <non-ice>/$coidx-cmd: ${cmdlist[coidx+2]}"
coidx+=3
else
# Don't increase coidx untill we get some command.
# This causes preceding comments to accumulate.
if [[ -n "${cmd3[c]}" ]]; then
# Custom command
cmdlist[coidx+2]="${(j: :)${(qkv)cmd3[@]}}"
/declzsh-dbg "Stored <custom>/$coidx-cmd: ${cmdlist[coidx+2]}"
coidx+=3
fi
fi
cmd3=()
fi
fi
# Command token
if [[ "$token" = [[:blank:]]#\#* ]]; then
if (( in_zinit == 1 )); then
cmdlist[coidx]="${cmdlist[coidx]%%[[:space:]]##}"
cmdlist[coidx]+="$spaces$token$next_spaces"
else
cmd3[comment]="$spaces$token"
fi
elif (( in_zinit == 1 )); then
[[ "$token" = (zinit|zini|zi) ]] && cmd3[c]="zinit" || cmd3[c]="$token"
# Postpone current state to next token
[[ "$token" = ":" ]] && { cmd3[disabled]=1; (( in_zinit -- )); }
elif (( in_zinit == 2 )); then
if [[ "${cmd3[c]}" = "zinit" ]]; then
[[ "$token" = (ice|load|light|snippet|cdclear|\
cdreplay|env-whitelist|create)
]] && {
cmd3[sub]="$token"
# We get another ice-command while a previous ice-command
# is still being pointed to by coidx? -> progress coidx
[[ "$token" = ice && -n "${cmdlist[coidx+1]}" ]] && \
coidx+=3
((1))
} || \
{ cmd3[sub]="unkn"; cmd3[unkn]="$token"; }
else
cmd3[arg_1]="$token"
cmd3[spaces_1]="$spaces"
fi
else
if [[ "${cmd3[sub]}" = "ice" ]]; then
# Also dequote the ice modifier
[[ "$token" = (#b)(${(~j:|:)ice_order})(?)(?)(*)(?) || \
"$token" = (#b)(${(~j:|:)ice_order})(*)
]] && {
local key="${match[1]}" string="${match[2]#[:=]}${match[3]}${match[4]}${match[5]}"
local second="${match[2]}" third="${match[3]}" last="${match[5]}"
cmd3[${${(M)own_order#0}:+${in_zinit}_}$key]="${string//(#b)(:|=|)([\"\']|\$\'|)(*)[\"\']/${match[3]}}"
# Remember also the quoting style, if the quoting
# is a recognized one
[[ ( -n "$second" && "$second" = "$last" ) || \
"$second" = (:|=)* # Via the star this handles both matchings
]] && \
cmd3[${${(M)own_order#0}:+${in_zinit}_}${key}_style]="${second[1]}" || {
[[ "$second" = '$' && "$third" = "'" ]] && \
cmd3[${${(M)own_order#0}:+${in_zinit}_}${key}_style]="\$'"
}
((1))
} || {
cmd3[custom_$(( in_zinit - 2 ))]="$token"
cmd3[spaces_$(( in_zinit - 2 ))]="$spaces"
}
elif [[ "${cmd3[sub]}" = (load|light) ]]; then
if (( in_zinit == 4 )); then
cmd3[url]+="/$token"
elif (( ${+cmd3[url]} == 0 )); then
cmd3[url]="$token"
else
cmd3[custom_$(( in_zinit - 2 ))]="$token"
cmd3[spaces_$(( in_zinit - 2 ))]="$spaces"
fi
elif [[ "${cmd3[sub]}" = "snippet" ]]; then
if [[ "$token" = "-f" ]]; then
cmd3[-f]="1"
elif [[ "$token" = "--command" ]]; then
cmd3[--command]="1"
elif [[ ${+cmd3[url]} != 1 && "${TOKEN_TYPES[$token]}" != [34] ]]; then
cmd3[url]="$token"
else
cmd3[custom_$(( in_zinit - 2 ))]="$token"
cmd3[spaces_$(( in_zinit - 2 ))]="$spaces"
fi
elif [[ "${cmd3[sub]}" = "cdclear" ]]; then
[[ "$token" = "-q" ]] && cmd3[-q]="1" || {
cmd3[custom_$(( in_zinit - 2 ))]="$token"
cmd3[spaces_$(( in_zinit - 2 ))]="$spaces"
}
elif [[ "${cmd3[sub]}" = "cdreplay" ]]; then
[[ "$token" = "-q" ]] && cmd3[-q]="1" || {
cmd3[custom_$(( in_zinit - 2 ))]="$token"
cmd3[spaces_$(( in_zinit - 2 ))]="$spaces"
}
elif [[ "${cmd3[sub]}" = "unkn" ]]; then
# Argument following "zinit <unknown> ..."
cmd3[arg_$(( in_zinit - 2 ))]="$token"
else
# Argument following "<unknown> <arg_1> ..."
cmd3[arg_$(( in_zinit - 1 ))]="$token"
cmd3[spaces_$(( in_zinit - 1 ))]="$spaces"
fi
fi
# Advance deeper into "zinit ..." if it wasn't comment
#[[ "$token" != [[:blank:]]#\#* ]] && in_zinit+=1
in_zinit+=1
# History of state
prev_depth="$depth"
prev_token="$token"
prev_spaces="$spaces"
done
if [[ -n "${cmd3[c]}" ]];then
if [[ "${cmd3[c]}" = "zinit" && "${cmd3[sub]}" = "ice" ]]; then
cmdlist[coidx+1]="${(j: :)${(qkv)cmd3[@]}}"
/declzsh-dbg "Stored <ice>/$coidx-cmd: ${cmdlist[coidx+1]}"
elif [[ "${cmd3[c]}" = "zinit" && "${cmd3[sub]}" != "ice" ]]; then
cmdlist[coidx+2]="${(j: :)${(qkv)cmd3[@]}}"
/declzsh-dbg "Stored <non-ice>/$coidx-cmd: ${cmdlist[coidx+2]}"
elif [[ "${cmd3[c]}" != "zinit" ]]; then
cmdlist[coidx+2]="${(j: :)${(qkv)cmd3[@]}}"
/declzsh-dbg "Stored <custom>/$coidx-cmd: ${cmdlist[coidx+2]}"
fi
/declzsh-dbg "Zinit block in zshrc has $(( (coidx + 2) / 3 )) commands (not counting \`zinit ice ...')"
else
/declzsh-dbg "Zinit block in zshrc has $(( (coidx-1) / 3 )) commands (not counting \`zinit ice ...')"
fi
/declzsh-dbg ""
}
# }}}
# FUNCTION: .declzsh_compose {{{
# Constructs text with zinit commands, optionally
# including original Zshrc blocks (in order to create
# full .zshrc). Can skip comments (via $1).
#
# $1 - 0 or 1 - whether to include comments
# $2 - 0 or 1 - whether to generate complete zshrc
#
# $reply - lines of created code
.declzsh_compose() {
local with_comments="$1" whole="$2" own_quoting="$3"
local buf="" tmp comment key
integer i size=$(( ${#cmdlist} / 3 ))
local -a cmd keys
local -A ice_cmd main_cmd
[[ "$whole" = "1" ]] && {
if (( pre_block_end > 0 )); then
buf="${(j::)DECLZSH_PB_ALL[1,pre_block_end+1]}"
else
buf=""
fi
}
for (( i=1; i<=size; ++ i )); do
cmd=( "${(@)cmdlist[(i-1)*3+1,i*3]}" )
comment="${cmd[1]}"
ice_cmd=() main_cmd=()
[[ -n "${cmd[2]}" ]] && ice_cmd=( "${(z@)cmd[2]}" )
[[ -n "${cmd[3]}" ]] && main_cmd=( "${(z@)cmd[3]}" )
ice_cmd=( "${(Qkv)ice_cmd[@]}" )
main_cmd=( "${(Qkv)main_cmd[@]}" )
# A horrible thing with $(<...) omitting trailing newlines
[[ ${#buf} -gt 0 && ${buf[-1]} != $'\n' && $i -eq 1 ]] && buf+=$'\n'
# Protection against previous command having trailing spaces before $'\n'
local nl=$'\n'
comment="${comment/[[:blank:]]##$nl/$nl}"
# Comment
[[ "$with_comments" = "1" && -n "$comment" ]] && {
(( i == 1 )) && buf+="${comment##[[:space:]]##}" || buf+="${comment#$nl}"
}
# ICE
# Something more than [c]=zinit [sub]=ice [comment]=comment
if (( ${#ice_cmd} > 2 && ${+ice_cmd[comment]} == 0 || ${#ice_cmd} > 3 && ${+ice_cmd[comment]} == 1 )); then
(( ice_cmd[disabled] || main_cmd[disabled] )) && buf+=": "
buf+="zinit${ice_cmd[\\-break_2]:- }ice"
if (( own_order )); then
for tmp in "${ice_order[@]}"; do
.declzsh_the_ice_case "$tmp" "$tmp"
done
else
keys=( "${(kon)ice_cmd[@]}" )
for key in "${keys[@]}"; do
[[ "$key" != <->_* ]] && continue
.declzsh_the_ice_case "${key#<->_}" "$key"
done
fi
# Put tokens other than ice-mod at the
# end, in order, with spaces
keys=( "${(kon)ice_cmd[@]}" )
for key in "${keys[@]}"; do
[[ "$key" != custom_* ]] && continue
buf+="${ice_cmd[spaces_${key#custom_}]}${ice_cmd[$key]}"
done
[[ "$with_comments" = "1" && -n "${ice_cmd[comment]}" ]] && buf+="${ice_cmd[comment]}"
if [[ ${#ice_cmd} -gt 0 || "$i" -lt "$size" ]]; then
(( ${+ice_cmd[aspaces]} )) && buf+="${ice_cmd[aspaces]}" || buf+=$'\n'
fi
fi
# COMMAND
if [[ "${#main_cmd}" -ge 1 ]]; then
if [[ "${main_cmd[c]}" = (zinit|zini|zi) ]]; then
(( ice_cmd[disabled] || main_cmd[disabled] )) && buf+=": "
if [[ "${main_cmd[sub]}" = (load|light|snippet|cdclear|\
cdreplay|env-whitelist|create) ]]; then
buf+="zinit${main_cmd[\\-break_2]:- }${main_cmd[sub]}"
[[ "${main_cmd[--command]}" = "1" ]] && buf+=" --command"
[[ "${main_cmd[-f]}" = "1" ]] && buf+=" -f"
[[ "${main_cmd[-q]}" = "1" ]] && buf+=" -q"
[[ -n "${main_cmd[url]}" ]] && buf+=" ${main_cmd[url]}"
[[ "$with_comments" = "1" && -n "${main_cmd[comment]}" ]] && buf+="${main_cmd[comment]}"
keys=( "${(kon)main_cmd[@]}" )
for key in "${keys[@]}"; do
[[ "$key" != arg_* ]] && continue
buf+="${main_cmd[\\-break_$(( ${key#arg_} + 1 ))]:- }${main_cmd[$key]}"
done
if [[ "$i" -lt "$size" ]]; then
(( ${+main_cmd[aspaces]} )) && buf+="${main_cmd[aspaces]}" || buf+=$'\n'
fi
else
# Unknown subcommand
local text="${main_cmd[c]}"
[[ -n "${main_cmd[unkn]}" ]] && text+=" ${main_cmd[unkn]}"
keys=( "${(kon)main_cmd[@]}" )
for key in "${keys[@]}"; do
[[ "$key" != arg_* ]] && continue
text+=" ${main_cmd[$key]}"
done
buf+="$text"
if [[ "$i" -lt "$size" ]]; then
(( ${+main_cmd[aspaces]} )) && buf+="${main_cmd[aspaces]}" || buf+=$'\n'
fi
fi
else
local text="${main_cmd[c]}"
keys=( "${(kon)main_cmd[@]}" )
for key in "${keys[@]}"; do
[[ "$key" != arg_* ]] && continue
text+="${main_cmd[spaces_${key#arg_}]}${main_cmd[$key]}"
done
buf+="$text"
if [[ "$i" -lt "$size" ]]; then
(( ${+main_cmd[aspaces]} )) && buf+="${main_cmd[aspaces]}" || buf+=$'\n'
fi
fi
fi
done
if (( pre_block_end+1 != post_block_begin )); then
[[ "$whole" = "1" ]] && buf+="${(j::)DECLZSH_PB_ALL[post_block_begin,-1]}"
fi
reply=( "${(@f)buf}" )
}
# }}}
# FUNCTION: .declzsh_save {{{
# Called when [Save] pressed. Composes full .zshrc,
# performs the save, outputs status message.
# $1 - destination path
.declzsh_save() {
local dest="$1"
integer ret
.declzsh_compose 1 1 "$own_quoting"
builtin print -rl -- "${reply[@]}" >| "$dest"
ret=$?
(( !ret )) && \
/declzsh-dbg "Saved to: \`$dest'" || \
/declzsh-dbg "Couldn't save to: \`$dest'"
return $ret
}
# }}}
#
# Backend functions
#
# FUNCTION: .declzsh_update_main_cmd {{{
# Updates main entry in given ($3) command packet. There
# is single command packet per zinit invocation and it
# contains main command, optionally ICE command, and also
# optionally a preceding comment.
#
# $1 - key to update in the main command
# $2 - data to store under the key
# $3 - index of command pack to alter
.declzsh_update_main_cmd() {
local key="$1" data="$2" idx="$3"
local -a cmd
local -A main_cmd
cmd=( "${(@)cmdlist[(idx-1)*3+1,idx*3]}" )
if [[ -n "${cmd[3]}" ]]; then
main_cmd=( "${(z@)cmd[3]}" )
main_cmd=( "${(Qkv)main_cmd[@]}" )
fi
if [[ "$data" = "