/
zsh-vi-mode.zsh
1324 lines (1168 loc) 路 33.9 KB
/
zsh-vi-mode.zsh
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
# zsh-vi-mode.zsh -- A better and friendly vi(vim) mode for Zsh
# Copyright 漏 2020 Jeffrey Tse
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
#
# All Settings
# Set these variables before sourcing this file.
#
# ZVM_VI_NORMAL_MODE_CURSOR:
# the prompt cursor in vi normal mode
#
# ZVM_VI_INSERT_MODE_CURSOR:
# the prompt cursor in vi insert mode
#
# ZVM_VI_INSERT_MODE_LEGACY_UNDO:
# using legacy undo behavior in vi insert mode
#
# ZVM_VI_HIGHLIGHT_BACKGROUND:
# the behavior of highlight (surrounds, visual-line, etc) in vi mode
#
# For example:
# ZVM_VI_HIGHLIGHT_BACKGROUND=red # Color name
# ZVM_VI_HIGHLIGHT_BACKGROUND=#ff0000 # Hex value
#
# ZVM_VI_SURROUND_BINDKEY
# the key binding mode for surround operating (default is 'classic')
#
# 1. 'classic' mode (verb->s->surround):
# S" Add " for visual selection
# ys" Add " for visual selection
# cs"' Change " to '
# ds" Delete "
#
# 2. 's-prefix' mode (s->verb->surround):
# sa" Add " for visual selection
# sd" Delete "
# sr"' Change " to '
#
# How to select surround text object?
# vi" Select the text object inside the quotes
# va( Select the text object including the brackets
#
# Then you can do any operation for the selection:
#
# 1. Add surrounds for text object
# vi" -> S[ or sa[ => "object" -> "[object]"
#
# 2. Delete/Yank/Change text object
# di( or vi( -> d
# ca( or va( -> c
# yi( or vi( -> y
#
# ZVM_KEYTIMEOUT:
# the key input timeout for waiting for next key (default is 0.3 seconds)
#
# ZVM_LAZY_KEYBINDINGS:
# the setting for lazy keybindings (default is true), and lazy keybindings
# will postpone the keybindings of vicmd and visual keymaps to the first
# time entering normal mode
#
# Plugin information
typeset -gr ZVM_NAME='zsh-vi-mode'
typeset -gr ZVM_DESCRIPTION='馃捇 A better and friendly vi(vim) mode plugin for ZSH.'
typeset -gr ZVM_REPOSITORY='https://github.com/jeffreytse/zsh-vi-mode'
typeset -gr ZVM_VERSION='0.5.0'
# Reduce ESC delay (zle)
# Set to 0.1 second delay between switching modes (default is 0.4 seconds)
KEYTIMEOUT=1
# Plugin initial status
ZVM_INIT_DONE=false
# Disable reset prompt (i.e. disable the widget `reset-prompt`)
ZVM_RESET_PROMPT_DISABLED=false
# Insert mode could be `i` (insert) or `a` (append)
ZVM_INSERT_MODE='i'
# The mode could be the below value:
# `n` (normal)
# `i` (insert)
# `v` (visual)
# `vl` (visual-line)
ZVM_MODE=''
# The keys typed to invoke this widget, as a literal string
ZVM_KEYS=''
# The region hilight information
ZVM_REGION_HIGHLIGHT=()
# Default alternative character for escape space character
ZVM_ESCAPE_SPACE='\s'
# Default vi modes
ZVM_MODE_NORMAL='n'
ZVM_MODE_INSERT='i'
ZVM_MODE_VISUAL='v'
ZVM_MODE_VISUAL_LINE='vl'
# Default cursor styles
ZVM_CURSOR_BLOCK='\e[2 q'
ZVM_CURSOR_BEAM='\e[6 q'
ZVM_CURSOR_BLINKING_BLOCK='\e[1 q'
ZVM_CURSOR_BLINKING_BEAM='\e[5 q'
ZVM_CURSOR_XTERM_BLOCK='\x1b[\x32 q'
ZVM_CURSOR_XTERM_BEAM='\x1b[\x36 q'
##########################################
# Initial all default settings
# Set key input timeout (default is 0.3 seconds)
ZVM_KEYTIMEOUT=${ZVM_KEYTIMEOUT:-0.3}
# Set keybindings mode (default is true)
# The lazy keybindings will post the keybindings of vicmd and visual
# keymaps to the first time entering the normal mode
ZVM_LAZY_KEYBINDINGS=${ZVM_LAZY_KEYBINDINGS:-true}
# All keybindings for lazy loading
if $ZVM_LAZY_KEYBINDINGS; then
ZVM_LAZY_KEYBINDINGS_LIST=()
fi
# Set the sursor stlye of defferent vi modes
if [[ ${TERM:0:5} == 'xterm' ]]; then
ZVM_VI_NORMAL_MODE_CURSOR=${ZVM_VI_NORMAL_MODE_CURSOR:-$ZVM_CURSOR_XTERM_BLOCK}
ZVM_VI_INSERT_MODE_CURSOR=${ZVM_VI_INSERT_MODE_CURSOR:-$ZVM_CURSOR_XTERM_BEAM}
else
ZVM_VI_NORMAL_MODE_CURSOR=${ZVM_VI_NORMAL_MODE_CURSOR:-$ZVM_CURSOR_BLOCK}
ZVM_VI_INSERT_MODE_CURSOR=${ZVM_VI_INSERT_MODE_CURSOR:-$ZVM_CURSOR_BEAM}
fi
ZVM_VI_INSERT_MODE_LEGACY_UNDO=${ZVM_VI_INSERT_MODE_LEGACY_UNDO:-false}
ZVM_VI_SURROUND_BINDKEY=${ZVM_VI_SURROUND_BINDKEY:-classic}
ZVM_VI_HIGHLIGHT_BACKGROUND=${ZVM_VI_HIGHLIGHT_BACKGROUND:-#cc0000}
# All the extra commands
zvm_before_init_commands=()
zvm_after_init_commands=()
zvm_before_select_vi_mode_commands=()
zvm_after_select_vi_mode_commands=()
zvm_before_lazy_keybindings_commands=()
zvm_after_lazy_keybindings_commands=()
# Display version information
function zvm_version() {
echo -e "$ZVM_NAME $ZVM_VERSION"
echo -e "\e[4m$ZVM_REPOSITORY\e[0m"
echo -e "$ZVM_DESCRIPTION"
}
# Define widget function
function zvm_define_widget() {
local widget=$1
local func=$2 || $1
local result=($(zle -l -L "${widget}"))
# Check if existing the same name
if [[ ${#result[@]} == 4 ]]; then
local rawfunc=${result[4]}
local wrapper="zvm_${widget}-wrapper"
eval "$wrapper() { $rawfunc; $func; }"
func=$wrapper
fi
zle -N $widget $func
}
# Default handler for unhandled key events
function zvm_default_handler() {
local keys=$(zvm_keys)
case "$KEYMAP" in
vicmd)
case "$keys" in
[cdy]*) zvm_range_handler "$keys";;
esac
;;
esac
}
# Get the keys typed to invoke this widget, as a literal string
function zvm_keys() {
local keys=${ZVM_KEYS:-$KEYS}
# Append `v` a the prefix of keys if it is visual mode
if [[ $ZVM_MODE == 'v' ]]; then
keys="v${keys}"
fi
echo ${keys// /$ZVM_ESCAPE_SPACE}
}
# Find the widget on a specified bindkey
function zvm_find_bindkey_widget() {
local keymap=$1
local keys=$2
local prefix_mode=$3
if [[ -z $prefix_mode ]]; then
local result=$(bindkey -M ${keymap} "$keys")
if [[ "${result: -14}" == ' undefined-key' ]]; then
return
fi
# Escape spaces in key bindings (space -> $ZVM_ESCAPE_SPACE)
for ((i=$#result;i>=0;i--)); do
# Backward find the first whitespace character
[[ "${result:$i:1}" == ' ' ]] || continue
# Retrieve the keys and widget
local k=${result:1:$i-2}
# Escape spaces in key bindings (space -> $ZVM_ESCAPE_SPACE)
k=${k// /$ZVM_ESCAPE_SPACE}
result="$k ${result:$i+1}"
break
done
echo $result
else
local widgets=()
local pos=0
local spos=3
local result=$(bindkey -M ${keymap})$'\n'
# Split string to array by newline
for ((i=$spos;i<$#result;i++)); do
# Save the last whitespace character of the line
# and continue continue handling while meeting `\n`
case "${result:$i:1}" in
' ') spos=$i; i=$i+1; continue;;
[$'\n']);;
*) continue;;
esac
# Check if it has the same prefix keys and retrieve the widgets
if [[ "${result:$((pos+1)):$#keys}" == "$keys" ]]; then
# Get the binding keys
local k=${result:$((pos+1)):$((spos-pos-2))}
# Escape spaces in key bindings (space -> $ZVM_ESCAPE_SPACE)
k=${k// /$ZVM_ESCAPE_SPACE}
widgets+=("$k ${result:$((spos+1)):$((i-spos-1))}")
fi
# Save as new position
pos=$i+1
# Skip 3 characters
# One key and quotes at least (i.e \n"_" )
i=$i+3
done
echo $widgets
fi
}
# Read keys for retrieving widget
function zvm_readkeys() {
local keymap=$1
local keys=${2:-$(zvm_keys)}
local key=
local widget=
local result=
local pattern=
while :; do
# Escape space in pattern
pattern=${keys//$ZVM_ESCAPE_SPACE/ }
# Find out widgets that match this key pattern
result=($(zvm_find_bindkey_widget $keymap "$pattern" true))
# Exit key input if no any more widgets matched
if [[ -z $result ]]; then
break
fi
# Wait for reading next key
key=
if [[ "${result[1]}" == "${keys}" ]]; then
read -t $ZVM_KEYTIMEOUT -k 1 key
else
read -k 1 key
fi
# Transform the non-printed characters
key=$(zvm_escape_non_printed_characters "${key}")
key=${key// /$ZVM_ESCAPE_SPACE}
# Escape keys
# " -> \" It's a special character in bash syntax
# ` -> \` It's a special character in bash syntax
key=${key//\"/\\\"}
key=${key//\`/\\\`}
keys="${keys}${key}"
# Get current widget as final one when keytimeout
if [[ -z "$key" ]]; then
widget=${result[2]}
break
fi
done
# Remove escape slash character
keys=${keys//\\\"/\"}
keys=${keys//\\\`/\`}
echo ${keys} $widget
}
# Add key bindings
function zvm_bindkey() {
local keymap=$1
local keys=$2
local widget=$3
local key=
# If lazy keybindings is enabled, we need to add to the lazy list
if [[ ${ZVM_LAZY_KEYBINDINGS_LIST+x} && ${keymap} != viins ]]; then
keys=${keys//\"/\\\"}
keys=${keys//\`/\\\`}
ZVM_LAZY_KEYBINDINGS_LIST+=("${keymap} \"${keys}\" ${widget}")
return
fi
# Get the first key (especially check if ctrl characters)
if [[ $#keys -gt 1 && "${keys:0:1}" == '^' ]]; then
key=${keys:0:2}
else
key=${keys:0:1}
fi
local result=($(zvm_find_bindkey_widget $keymap "$key"))
local rawfunc=${result[2]}
local wrapper="zvm_${rawfunc}-wrapper"
# Check if we need to wrap the original widget
if [[ ! -z $rawfunc && "$rawfunc" != zvm_*-wrapper ]]; then
eval "$wrapper() { \
local result=(\$(zvm_readkeys $keymap '${key}')); \
ZVM_KEYS=\${result[1]//${ZVM_ESCAPE_SPACE//\\/\\\\}/ }; \
if [[ ! -z '$widget' && \${#ZVM_KEYS} == 1 ]]; then \
local widget=$rawfunc; \
else \
local widget=\${result[2]}; \
fi; \
if [[ -z \${widget} ]]; then \
zle zvm_default_handler; \
else \
zle \$widget; \
case \${ZVM_KEYS} in \
c|d|s|y) zle reset-prompt;; \
esac \
fi; \
ZVM_KEYS=; \
}"
zle -N $wrapper
bindkey -M $keymap "${key}" $wrapper
fi
# We should bind keys with a existing widget
if [[ $widget ]]; then
bindkey -M $keymap "${keys}" $widget
fi
}
# Escape non-printed characters
function zvm_escape_non_printed_characters() {
local str=
for ((i=0;i<$#1;i++)); do
local c=${1:$i:1}
if [[ "$c" < ' ' ]]; then
local ord=$(($(printf '%d' "'$c")+64))
c=$(printf \\$(printf '%03o' $ord))
str="${str}^${c}"
elif [[ "$c" == '' ]]; then
str="${str}^?"
else
str="${str}${c}"
fi
done
echo $str
}
# Change cursor with support for inside/outside tmux
function zvm_set_cursor() {
if [[ -z $TMUX ]]; then
echo -ne $1
else
echo -ne "\ePtmux;\e\e$1\e\\"
fi
}
# Change to normal cursor
function zvm_set_normal_mode_cursor() {
zvm_set_cursor $ZVM_VI_NORMAL_MODE_CURSOR
}
# Change to beam/pipe cursor
function zvm_set_insert_mode_cursor() {
zvm_set_cursor $ZVM_VI_INSERT_MODE_CURSOR
}
# Remove all characters between the cursor position and the
# beginning of the line.
function zvm_backward_kill_line() {
BUFFER=${BUFFER:$CURSOR:$#BUFFER}
CURSOR=0
}
# Remove all characters between the cursor position and the
# end of the line.
function zvm_forward_kill_line() {
BUFFER=${BUFFER:0:$CURSOR}
}
# Remove all characters of the line.
function zvm_kill_line() {
local ret=($(zvm_calc_selection $ZVM_MODE_VISUAL_LINE))
local bpos=${ret[1]} epos=${ret[2]}
CUTBUFFER=${BUFFER:$bpos:$((epos-bpos))}$'\n'
BUFFER="${BUFFER:0:$bpos}${BUFFER:$epos}"
CURSOR=$bpos
}
# Remove all characters of the whole line.
function zvm_kill_whole_line() {
local ret=($(zvm_calc_selection $ZVM_MODE_VISUAL_LINE))
local bpos=$ret[1] epos=$ret[2] cpos=$ret[3]
CUTBUFFER=${BUFFER:$bpos:$((epos-bpos))}$'\n'
# Check if it is visual line mode
if (( $epos < $#BUFFER )); then
epos=$epos+1
elif (( $bpos > 0 )); then
bpos=$bpos-1
fi
BUFFER="${BUFFER:0:$bpos}${BUFFER:$epos}"
MARK=$cpos
}
# Exchange the point and mark
function zvm_exchange_point_and_mark() {
cursor=$MARK
MARK=$CURSOR CURSOR=$cursor
zvm_highlight
}
# Open line below
function zvm_open_line_below() {
ZVM_MODE=$ZVM_MODE_INSERT
zvm_update_cursor_style
zle vi-open-line-below
}
# Open line above
function zvm_open_line_above() {
ZVM_MODE=$ZVM_MODE_INSERT
zvm_update_cursor_style
zle vi-open-line-above
}
# Substitute characters of selection
function zvm_vi_substitue() {
zle vi-substitute
zvm_select_vi_mode $ZVM_MODE_INSERT
}
# Calculate the region of selection
function zvm_calc_selection() {
local bpos= epos= cpos=
# Get the beginning and end position of selection
if (( MARK > CURSOR )) ; then
bpos=$((CURSOR+1)) epos=$((MARK+1))
else
bpos=$MARK epos=$((CURSOR+1))
fi
# Save the current cursor position
cpos=$bpos
# Check if it is visual line mode
if [[ "${1:-$ZVM_MODE}" == $ZVM_MODE_VISUAL_LINE ]]; then
# Extend the selection to whole line
for ((bpos=$bpos-1; $bpos>0; bpos--)); do
if [[ "${BUFFER:$bpos:1}" == $'\n' ]]; then
bpos=$bpos+1
break
fi
done
for (( ; $epos<$#BUFFER; epos++)); do
if [[ "${BUFFER:$epos:1}" == $'\n' ]]; then
break
fi
done
###########################################
# Calculate the new cursor position
# Calculate the indent of current cursor line
for ((cpos=$((CURSOR-1)); $cpos>=0; cpos--)); do
[[ "${BUFFER:$cpos:1}" == $'\n' ]] && break
done
local indent=$((CURSOR-cpos-1))
if (( $epos < $#BUFFER )); then
cpos=$bpos
else
# Calculate the cursor postion on above line
for ((cpos=$((bpos-2)); $cpos>0; cpos--)); do
if [[ "${BUFFER:$cpos:1}" == $'\n' ]]; then
cpos=$cpos+1
break
fi
done
fi
cpos=$((cpos+indent))
fi
echo $bpos $epos $cpos
}
# Yank characters of the marked region
function zvm_yank() {
local ret=($(zvm_calc_selection $1))
local bpos=$ret[1] epos=$ret[2] cpos=$ret[3]
CUTBUFFER=${BUFFER:$bpos:$((epos-bpos))}
if [[ ${1:-$ZVM_MODE} == $ZVM_MODE_VISUAL_LINE ]]; then
CUTBUFFER=${CUTBUFFER}$'\n'
fi
MARK=$bpos CURSOR=$epos
}
# Yank characters of the visual selection
function zvm_vi_yank() {
zvm_yank
zvm_exit_visual_mode
}
# Put cutbuffer after the cursor
function zvm_vi_put_after() {
local head= foot=
local content=${CUTBUFFER}
if [[ ${content: -1} == $'\n' ]]; then
local pos=${CURSOR}
# Find the end of current line
for ((; $pos<$#BUFFER; pos++)); do
if [[ ${BUFFER:$pos:1} == $'\n' ]]; then
pos=$pos+1
break
fi
done
# Check if it is an empty line
if [[ ${BUFFER:$CURSOR:1} == $'\n' &&
${BUFFER:$((CURSOR-1)):1} == $'\n' ]]; then
head=${BUFFER:0:$pos}
foot=${BUFFER:$pos}
else
head=${BUFFER:0:$pos}
foot=${BUFFER:$pos}
if [[ $pos == $#BUFFER ]]; then
content=$'\n'${content:0:-1}
fi
fi
BUFFER="${head}${content}${foot}"
CURSOR=$pos
else
head="${BUFFER:0:$CURSOR}"
foot="${BUFFER:$((CURSOR+1))}"
BUFFER="${head}${BUFFER:$CURSOR:1}${content}${foot}"
CURSOR=$CURSOR+$#content
fi
# Reresh display and highlight buffer
zvm_highlight clear
zvm_highlight custom $#head $(($#head+$#content))
zvm_highlight refresh
}
# Put cutbuffer before the cursor
function zvm_vi_put_before() {
local head= foot=
local content=${CUTBUFFER}
if [[ ${content: -1} == $'\n' ]]; then
local pos=$CURSOR
# Find the beginning of current line
for ((; $pos>0; pos--)); do
if [[ "${BUFFER:$pos:1}" == $'\n' ]]; then
pos=$pos+1
break
fi
done
# Check if it is an empty line
if [[ ${BUFFER:$CURSOR:1} == $'\n' &&
${BUFFER:$((CURSOR-1)):1} == $'\n' ]]; then
head=${BUFFER:0:$((pos-1))}
foot=$'\n'${BUFFER:$pos}
else
head=${BUFFER:0:$pos}
foot=${BUFFER:$pos}
fi
BUFFER="${head}${content}${foot}"
CURSOR=$pos
else
head="${BUFFER:0:$CURSOR}"
foot="${BUFFER:$((CURSOR+1))}"
BUFFER="${head}${content}${BUFFER:$CURSOR:1}${foot}"
CURSOR=$CURSOR+$#content
fi
# Reresh display and highlight buffer
zvm_highlight clear
zvm_highlight custom $#head $(($#head+$#content))
zvm_highlight refresh
}
# Delete characters of the visual selection
function zvm_vi_delete() {
local ret=($(zvm_calc_selection))
local bpos=$ret[1] epos=$ret[2] cpos=$ret[3]
CUTBUFFER=${BUFFER:$bpos:$((epos-bpos))}
# Check if it is visual line mode
if [[ $ZVM_MODE == $ZVM_MODE_VISUAL_LINE ]]; then
if (( $epos < $#BUFFER )); then
epos=$epos+1
elif (( $bpos > 0 )); then
bpos=$bpos-1
fi
CUTBUFFER=${CUTBUFFER}$'\n'
fi
BUFFER="${BUFFER:0:$bpos}${BUFFER:$epos}"
CURSOR=$cpos
zvm_exit_visual_mode
}
# Yank characters of the visual selection
function zvm_vi_change() {
local ret=($(zvm_calc_selection))
local bpos=$ret[1] epos=$ret[2]
CUTBUFFER=${BUFFER:$bpos:$((epos-bpos))}
# Check if it is visual line mode
if [[ $ZVM_MODE == $ZVM_MODE_VISUAL_LINE ]]; then
CUTBUFFER=${CUTBUFFER}$'\n'
fi
BUFFER="${BUFFER:0:$bpos}${BUFFER:$epos}"
CURSOR=$bpos
zvm_exit_visual_mode
zvm_select_vi_mode $ZVM_MODE_INSERT
}
# Handle a range of characters
function zvm_range_handler() {
zle visual-mode
local keys=${1:-$(zvm_keys)}
local cursor=$CURSOR
MARK=$CURSOR
case "${keys:1}" in
'^') zle vi-first-non-blank;;
'$') zle vi-end-of-line;;
'0') zle vi-digit-or-beginning-of-line;;
' ') zle vi-forward-char;;
'h') zle vi-backward-char;;
'j') zle down-line-or-history;;
'k') zle up-line-or-history;;
'l') zle vi-forward-char;;
'w') zle vi-forward-word;;
'e') zle vi-forward-word-end;;
'b') zle vi-backward-word; cursor=$CURSOR;;
'f') zle vi-find-next-char;;
'F') zle vi-find-prev-char; cursor=$CURSOR;;
't') zle vi-find-next-char-skip;;
'T') zle vi-find-prev-char-skip; cursor=$CURSOR;;
'iw') zle select-in-word; cursor=$MARK;;
'aw') zle select-a-word; cursor=$MARK;;
esac
case "${keys}" in
yy)
zvm_yank $ZVM_MODE_VISUAL_LINE
zle visual-mode
;;
dd)
zvm_kill_whole_line
cursor=$CURSOR
zle visual-mode
;;
cc)
zvm_kill_line
cursor=$CURSOR
zle visual-mode
zvm_select_vi_mode $ZVM_MODE_INSERT
;;
y*) zvm_vi_yank;;
d*) zvm_vi_delete;;
c*) zvm_vi_change;;
esac
CURSOR=$cursor
}
# Get the substr position in a string
function zvm_substr_pos() {
local pos=-1
local len=${#1}
local slen=${#2}
local i=${3:-0}
local forward=${4:-true}
local init=${i:-$($forward && echo "$i" || echo "i=$len-1")}
local condition=$($forward && echo "i<$len" || echo "i>=0")
local step=$($forward && echo 'i++' || echo 'i--')
for (($init;$condition;$step)); do
if [[ ${1:$i:$slen} == "$2" ]]; then
pos=$i
break
fi
done
echo $pos
}
# Parse surround from keys
function zvm_parse_surround_keys() {
local keys=${1:-${$(zvm_keys)//$ZVM_ESCAPE_SPACE/ }}
local action=
local surround=
case "${keys}" in
vS*) action=S; surround=${keys:2:1};;
vys*) action=y; surround=${keys:3:1};;
s[adr]*) action=${keys:1:1}; surround=${keys:2:1};;
[acd]s*) action=${keys:0:1}; surround=${keys:2:1};;
[cdvy][ia]*) action=${keys:0:2}; surround=${keys:2:1};;
esac
echo $action ${surround// /$ZVM_ESCAPE_SPACE}
}
# Move around code structure (e.g. (..), {..})
function zvm_move_around_surround() {
local slen=
local bpos=-1
local epos=-1
for ((i=$CURSOR;i>=0;i--)); do
# Check if it's one of the surrounds
for s in {\',\",\`,\(,\[,\{,\<}; do
slen=${#s}
if [[ ${BUFFER:$i:$slen} == "$s" ]]; then
bpos=$i
break
fi
done
if (($bpos == -1)); then
continue
fi
# Search the nearest surround
local ret=($(zvm_search_surround "$s"))
if [[ -z ${ret[@]} ]]; then
continue
fi
bpos=${ret[1]}
epos=${ret[2]}
# Move between the openning and close surrounds
if (( $CURSOR > $((bpos-1)) )) && (( $CURSOR < $((bpos+slen)) )); then
CURSOR=$epos
else
CURSOR=$bpos
fi
break
done
}
# Match the surround pair from the part
function zvm_match_surround() {
local bchar=${1// /$ZVM_ESCAPE_SPACE}
local echar=$bchar
case $bchar in
'(') echar=')';;
'[') echar=']';;
'{') echar='}';;
'<') echar='>';;
')') bchar='(';echar=')';;
']') bchar='[';echar=']';;
'}') bchar='{';echar='}';;
'>') bchar='<';echar='>';;
esac
echo $bchar $echar
}
# Search surround from the string
function zvm_search_surround() {
local ret=($(zvm_match_surround "$1"))
local bchar=${${ret[1]//$ZVM_ESCAPE_SPACE/ }:- }
local echar=${${ret[2]//$ZVM_ESCAPE_SPACE/ }:- }
local bpos=$(zvm_substr_pos $BUFFER $bchar $CURSOR false)
local epos=$(zvm_substr_pos $BUFFER $echar $CURSOR true)
if [[ $bpos == $epos ]]; then
epos=$(zvm_substr_pos $BUFFER $echar $((CURSOR+1)) true)
if [[ $epos == -1 ]]; then
epos=$(zvm_substr_pos $BUFFER $echar $((CURSOR-1)) false)
if [[ $epos != -1 ]]; then
local tmp=$epos; epos=$bpos; bpos=$tmp
fi
fi
fi
if [[ $bpos == -1 ]] || [[ $epos == -1 ]]; then
return
fi
echo $bpos $epos $bchar $echar
}
# Select surround and highlight it in visual mode
function zvm_select_surround() {
local ret=($(zvm_parse_surround_keys))
local action=${ret[1]}
local surround=${ret[2]//$ZVM_ESCAPE_SPACE/ }
ret=($(zvm_search_surround ${surround}))
if [[ ${#ret[@]} == 0 ]]; then
zvm_exit_visual_mode
return
fi
local bpos=${ret[1]}
local epos=${ret[2]}
if [[ ${action:1:1} == 'i' ]]; then
((bpos++))
else
((epos++))
fi
MARK=$bpos; CURSOR=$epos-1
# refresh current mode for prompt redraw
zvm_select_vi_mode
}
# Change surround in vicmd or visual mode
function zvm_change_surround() {
local ret=($(zvm_parse_surround_keys))
local action=${1:-${ret[1]}}
local surround=${2:-${ret[2]//$ZVM_ESCAPE_SPACE/ }}
local bpos=${3} epos=${4}
local is_appending=
case $action in
S|y|a) is_appending=1;;
esac
if [[ $is_appending ]]; then
if [[ -z $bpos && -z $epos ]]; then
if (( MARK > CURSOR )) ; then
bpos=$CURSOR+1 epos=$MARK+1
else
bpos=$MARK epos=$CURSOR+1
fi
fi
else
ret=($(zvm_search_surround "$surround"))
(( ${#ret[@]} )) || return
bpos=${ret[1]}
epos=${ret[2]}
zvm_highlight custom $bpos $(($bpos+1))
zvm_highlight custom $epos $(($epos+1))
zvm_highlight redraw
fi
local key=
case $action in
c|r) read -k 1 key;;
S|y|a)
key=$surround
[[ -z $@ ]] && zle visual-mode
zvm_select_vi_mode $ZVM_MODE_NORMAL
;;
esac
if [[ -z $is_appending ]]; then
zvm_highlight clear
fi
# Check if canceling changing surround (^[)
[[ $key == '' ]] && return
# Start changing surround
ret=($(zvm_match_surround "$key"))
local bchar=${${ret[1]//$ZVM_ESCAPE_SPACE/ }:-$key}
local echar=${${ret[2]//$ZVM_ESCAPE_SPACE/ }:-$key}
local value=$([[ $is_appending ]] && echo 0 || echo 1 )
local head=${BUFFER:0:$bpos}
local body=${BUFFER:$((bpos+value)):$((epos-(bpos+value)))}
local foot=${BUFFER:$((epos+value))}
BUFFER="${head}${bchar}${body}${echar}${foot}"
}
# Change surround text object
function zvm_change_surround_text_object() {
local ret=($(zvm_parse_surround_keys))
local action=${ret[1]}
local surround=${ret[2]//$ZVM_ESCAPE_SPACE/ }
ret=($(zvm_search_surround "${surround}"))
if [[ ${#ret[@]} == 0 ]]; then
zvm_select_vi_mode $ZVM_MODE_NORMAL
return
fi
local bpos=${ret[1]}
local epos=${ret[2]}
if [[ ${action:1:1} == 'i' ]]; then
((bpos++))
else
((epos++))
fi
CUTBUFFER=${BUFFER:$bpos:$(($epos-$bpos))}
case ${action:0:1} in
c)
BUFFER="${BUFFER:0:$bpos}${BUFFER:$epos}"
CURSOR=$bpos
zvm_select_vi_mode $ZVM_MODE_INSERT
;;
d)
BUFFER="${BUFFER:0:$bpos}${BUFFER:$epos}"
CURSOR=$bpos
;;
esac
}
# Highlight content
function zvm_highlight() {
local opt=${1:-mode}
local region=()
local rh_length=${#ZVM_REGION_HIGHLIGHT[@]}
local redraw=
# Hanlde region by the option
case "$opt" in
mode)
case "$ZVM_MODE" in
$ZVM_MODE_VISUAL_LINE)
local ret=($(zvm_calc_selection))
local bpos=$ret[1] epos=$ret[2]
region=("$((bpos)) $((epos)) bg=$ZVM_VI_HIGHLIGHT_BACKGROUND")
;;
esac
redraw=true
;;
custom)
region=("${ZVM_REGION_HIGHLIGHT[@]}")
region+=("$2 $3 bg=${4:-$ZVM_VI_HIGHLIGHT_BACKGROUND}")
;;
clear) redraw=true;;
redraw) redraw=true;;
esac
# Update region highlight
if (( $#region > 0 )) || [[ "$opt" == 'clear' ]]; then
zle redisplay
ZVM_REGION_HIGHLIGHT=("${region[@]}")
# Remove old region highlight
if (( $rh_length > 0 && $rh_length <= ${#region_highlight} )); then
region_highlight=("${region_highlight[@]:0:-$rh_length}")
fi
region_highlight+=("${ZVM_REGION_HIGHLIGHT[@]}")
fi
# Check if we need to refresh the region highlight
if [[ $redraw ]]; then
zle -R
fi
}
# Down line in visual mode
function zvm_down_line() {
zle down-line
zvm_highlight
}
# Up line in visual mode
function zvm_up_line() {
zle up-line
zvm_highlight
}