zshoh-my-zshpreztozsh-zle

ZSH and ZLE, move to the beginning-of-line, write string, move to the end


Its not essential but it bugs me a bit, here is the fragment from my .zshrc

a function/widget called add_sudo, that will go at the beginning of line, writes sudo there and then should go at the end of the line.

Its bind to ctrl+f

But it does not go at the end of the line, it ignores last command and sits there after it wrote sudo.

add_sudo() {
  zle beginning-of-line;
  zle -U "sudo ";
  zle end-of-line;
}

zle -N add_sudo
bindkey "^f" add_sudo

any solution to this?


Solution

  • I can answer this one! I just joined, glad to help..... and I read the question wrong, but now I'm here to redeem myself, with the help of @4ae1e1, all credit to him for mentioning to use BUFFER= and CURSOR=

    add_sudo (){
    prefix="sudo"
    BUFFER="$prefix $BUFFER"
    CURSOR=$(($CURSOR + $#prefix + 1))
    }
    zle -N add_sudo
    bindkey "^f" add_sudo
    

    Does what you would like, and now I can use this after every time I forget to sudo, too!

    EDITx2

    Of note, this actually places the cursor back to wherever it was prior, my preferred use. You can, as 4aelel stated, use CURSOR+=5 to place it at the end of the line.

    Also of note, again, I realized I truly haven't fulfilled the question, as it was how to do this with zsh and zli, rather than how to do this. If I come across an answer I'll append with both solutions.I'm new to zli and it's nuances, just recently moving to zsh.