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.