Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I move the cursor after a Zsh abbreviation?

I'm using this excellent script in my .zshrc file to accomplish zsh abbreviations: http://zshwiki.org/home/examples/zleiab

The above works great.

Here's my question:

How can I modify these abbreviations or the script to have the cursor end up in specific parts of the abbreviation instead of the end like so:

 "ac"    "ack -C 5 {cursorHere} --ignore-dir=.build"¬

Should abbreviate to:

ack -C 5  [cursor]  --ignore-dir=.build
like image 507
Jamis Charles Avatar asked Dec 06 '25 12:12

Jamis Charles


1 Answers

Update the magic-abbrev-expand to

magic-abbrev-expand() {
    local MATCH
    LBUFFER=${LBUFFER%%(#m)[_a-zA-Z0-9]#}
    command=${abbreviations[$MATCH]}
    LBUFFER+=${command:-$MATCH}

    if [[ "${command}" =~ "__CURSOR__" ]]
    then
        RBUFFER=${LBUFFER[(ws:__CURSOR__:)2]}
        LBUFFER=${LBUFFER[(ws:__CURSOR__:)1]}
    else
        zle self-insert
    fi
}

The abbreviation would be set as

"ac"    "ack -C 5__CURSOR__--ignore-dir=.build"
"Ii"    "Hello__CURSOR__! How are you"

Full script

setopt extendedglob
typeset -Ag abbreviations
abbreviations=(
  "ac"    "ack -C 5__CURSOR__--ignore-dir=.build"
  "Ii"    "Hello__CURSOR__! How are you"
  "Im"    "| more"
  "Ia"    "| awk"
  "Ig"    "| grep"
  "Ieg"   "| egrep"
  "Iag"   "| agrep"
  "Igr"   "| groff -s -p -t -e -Tlatin1 -mandoc"
  "Ip"    "| $PAGER"
  "Ih"    "| head"
  "Ik"    "| keep"
  "It"    "| tail"
  "Is"    "| sort"
  "Iv"    "| ${VISUAL:-${EDITOR}}"
  "Iw"    "| wc"
  "Ix"    "| xargs"
)

magic-abbrev-expand() {
    local MATCH
    LBUFFER=${LBUFFER%%(#m)[_a-zA-Z0-9]#}
    command=${abbreviations[$MATCH]}
    LBUFFER+=${command:-$MATCH}

    if [[ "${command}" =~ "__CURSOR__" ]]
    then
        RBUFFER=${LBUFFER[(ws:__CURSOR__:)2]}
        LBUFFER=${LBUFFER[(ws:__CURSOR__:)1]}
    else
        zle self-insert
    fi
}

no-magic-abbrev-expand() {
  LBUFFER+=' '
}

zle -N magic-abbrev-expand
zle -N no-magic-abbrev-expand
bindkey " " magic-abbrev-expand
bindkey "^x " no-magic-abbrev-expand
bindkey -M isearch " " self-insert
like image 103
amit_g Avatar answered Dec 08 '25 00:12

amit_g



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!