Bohr
Bohr

Reputation: 1726

How to move the cursor position in zsh widget definition

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!

Upvotes: 6

Views: 1413

Answers (1)

mklement0
mklement0

Reputation: 437618

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.

Upvotes: 7

Related Questions