We all know this comic:

And now in zsh!

With the following snippet all commands that are started with an uppercase word will be prefixed with sudo and then executed.

So MAKE me a sandwich, becomes sudo make me a sandwich.

accept-line() {
    local B
    B=(${=BUFFER})
    if [[ "$B[1]" != [A-Z]* ]]; then
        zle .accept-line
        return
    fi
    if [[ $B[1] != "" && $B[1] == $B[1]:u ]]; then
        BUFFER="sudo $B[1]:l $B[2,-1]"
    fi
    zle .accept-line
}

And activate with:

zle -N accept-line

The avoid clashing with commands that are uppercase already (for instance GET and POST), it can be disabled by using a backslash. So using GET becomes \GET. (The same trick can be used to avoid expanding an alias).

Repo

Any code changes will be done in this Git repo.