874d83f7b86afbc395915e796cff4e4fe949a204
- Author
- Subhaditya Nath <56714626+subnut@users.noreply.github.com>
- Committer
- GitHub <noreply@github.com>
- Date
Message
feat(sudo): support aliases to $EDITOR (#9431)
Co-authored-by: Marc Cornellà <marc.cornella@live.com>
Diff
1diff --git a/plugins/sudo/sudo.plugin.zsh b/plugins/sudo/sudo.plugin.zsh
2index b3749eff79f0663837c6b87a367399e21436d30a..f2445a7624739b82f6a7fa464e6e16444f725677 100644
3--- a/plugins/sudo/sudo.plugin.zsh
4+++ b/plugins/sudo/sudo.plugin.zsh
5@@ -9,40 +9,48 @@
6 # -------
7 #
8 # * Dongweiming <ciici123@gmail.com>
9+# * Subhaditya Nath <github.com/subnut>
10+# * Marc Cornellà <github.com/mcornella>
11 #
12 # ------------------------------------------------------------------------------
13
14+__sudo-replace-buffer() {
15+ local old=$1 new=$2 space=${2:+ }
16+ if [[ ${#LBUFFER} -le ${#old} ]]; then
17+ RBUFFER="${space}${BUFFER#$old }"
18+ LBUFFER="${new}"
19+ else
20+ LBUFFER="${new}${space}${LBUFFER#$old }"
21+ fi
22+}
23+
24 sudo-command-line() {
25 [[ -z $BUFFER ]] && LBUFFER="$(fc -ln -1)"
26
27 # Save beginning space
28 local WHITESPACE=""
29- if [[ ${LBUFFER:0:1} == " " ]] ; then
30+ if [[ ${LBUFFER:0:1} = " " ]]; then
31 WHITESPACE=" "
32 LBUFFER="${LBUFFER:1}"
33 fi
34
35- if [[ -n $EDITOR && $BUFFER == $EDITOR\ * ]]; then
36- if [[ ${#LBUFFER} -le ${#EDITOR} ]]; then
37- RBUFFER=" ${BUFFER#$EDITOR }"
38- LBUFFER="sudoedit"
39- else
40- LBUFFER="sudoedit ${LBUFFER#$EDITOR }"
41- fi
42- elif [[ $BUFFER == sudoedit\ * ]]; then
43- if [[ ${#LBUFFER} -le 8 ]]; then
44- RBUFFER=" ${BUFFER#sudoedit }"
45- LBUFFER="$EDITOR"
46- else
47- LBUFFER="$EDITOR ${LBUFFER#sudoedit }"
48- fi
49- elif [[ $BUFFER == sudo\ * ]]; then
50- if [[ ${#LBUFFER} -le 4 ]]; then
51- RBUFFER="${BUFFER#sudo }"
52- LBUFFER=""
53- else
54- LBUFFER="${LBUFFER#sudo }"
55+ # Get the first part of the typed command and check if it's an alias to $EDITOR
56+ # If so, locally change $EDITOR to the alias so that it matches below
57+ if [[ -n "$EDITOR" ]]; then
58+ local cmd="${${(Az)BUFFER}[1]}"
59+ if [[ "${aliases[$cmd]} " = (\$EDITOR|$EDITOR)\ * ]]; then
60+ local EDITOR="$cmd"
61 fi
62+ fi
63+
64+ if [[ -n $EDITOR && $BUFFER = $EDITOR\ * ]]; then
65+ __sudo-replace-buffer "$EDITOR" "sudoedit"
66+ elif [[ -n $EDITOR && $BUFFER = \$EDITOR\ * ]]; then
67+ __sudo-replace-buffer "\$EDITOR" "sudoedit"
68+ elif [[ $BUFFER = sudoedit\ * ]]; then
69+ __sudo-replace-buffer "sudoedit" "$EDITOR"
70+ elif [[ $BUFFER = sudo\ * ]]; then
71+ __sudo-replace-buffer "sudo" ""
72 else
73 LBUFFER="sudo $LBUFFER"
74 fi
75@@ -50,7 +58,9 @@ sudo-command-line() {
76 # Preserve beginning space
77 LBUFFER="${WHITESPACE}${LBUFFER}"
78 }
79+
80 zle -N sudo-command-line
81+
82 # Defined shortcut keys: [Esc] [Esc]
83 bindkey -M emacs '\e\e' sudo-command-line
84 bindkey -M vicmd '\e\e' sudo-command-line