sudo.plugin.zsh 1.58 KB
Newer Older
dongweiming's avatar
dongweiming committed
1
2
3
4
# ------------------------------------------------------------------------------
# Description
# -----------
#
5
# sudo or sudoedit will be inserted before the command
dongweiming's avatar
dongweiming committed
6
7
8
9
10
11
12
13
14
15
#
# ------------------------------------------------------------------------------
# Authors
# -------
#
# * Dongweiming <ciici123@gmail.com>
#
# ------------------------------------------------------------------------------

sudo-command-line() {
16
    [[ -z $BUFFER ]] && LBUFFER="$(fc -ln -1)"
17
18
19
20
21
22
23
24

    # Save beginning space
    local WHITESPACE=""
    if [[ ${LBUFFER:0:1} == " " ]] ; then 
        WHITESPACE=" "
        LBUFFER="${LBUFFER:1}"
    fi

25
26
27
28
29
30
31
    if [[ -n $EDITOR && $BUFFER == $EDITOR\ * ]]; then
        if [[ ${#LBUFFER} -le ${#EDITOR} ]]; then
            RBUFFER=" ${BUFFER#$EDITOR }"
            LBUFFER="sudoedit"
        else
            LBUFFER="sudoedit ${LBUFFER#$EDITOR }"
        fi
32
    elif [[ $BUFFER == sudoedit\ * ]]; then
33
34
35
36
37
38
39
40
41
42
43
44
45
        if [[ ${#LBUFFER} -le 8 ]]; then
            RBUFFER=" ${BUFFER#sudoedit }"
            LBUFFER="$EDITOR"
        else
            LBUFFER="$EDITOR ${LBUFFER#sudoedit }"
        fi
    elif [[ $BUFFER == sudo\ * ]]; then
        if [[ ${#LBUFFER} -le 4 ]]; then
            RBUFFER="${BUFFER#sudo }"
            LBUFFER=""
        else
            LBUFFER="${LBUFFER#sudo }"
        fi
Fabio Strozzi's avatar
Fabio Strozzi committed
46
47
48
    else
        LBUFFER="sudo $LBUFFER"
    fi
49
50
51

    # Preserve beginning space
    LBUFFER="${WHITESPACE}${LBUFFER}"
dongweiming's avatar
dongweiming committed
52
53
54
}
zle -N sudo-command-line
# Defined shortcut keys: [Esc] [Esc]
55
56
57
bindkey -M emacs '\e\e' sudo-command-line
bindkey -M vicmd '\e\e' sudo-command-line
bindkey -M viins '\e\e' sudo-command-line