I have this snippet:
insert_sudo () { zle beginning-of-line; zle -U "sudo "; zle end-of-line; }
zle -N insert-sudo insert_sudo
bindkey "\es" insert-sudo
But \es
only appends "sudo" to the end of a line, not the beginning of line as I expected. Please help!
Try the following:
insert_sudo() { BUFFER="sudo $BUFFER"; zle end-of-line; }
This directly modifies the special $BUFFER
variable containing the contents of the command line by prepending sudo
and then placing the cursor at the end of the line.
The problem with zle -U
is that it only takes effect AFTER the widget finishes. From the zsh
manual:
After the widget currently executed finishes, ZLE will behave as if the characters in the string were typed by the user.