Zsh Mailing List Archive
Messages sorted by: Reverse Date, Date, Thread, Author

Zle function for moving list elements



Here's a function move-element I've just written to move an element in a
colon- or comma-separated list in the shell's editor up or down.  This
makes it very easy to reorder a PATH in vared, or whatever.  You can
tweak the separator characters by changing the "local chars=" assignment
if you like (you might not want IFS characters in it).

autoload -U move-element
zle -N move-element move-element-backward
zle -N move-element move-element-forward


#start
# Take a list like foo=prev:blah:next or foo=prev,blah,next or even without
# the foo= and move the current element backward (foo=blah,prev,next)
# or forward (foo=prev,next,blah)

emulate -L zsh

local chars='[:IFS:],:='
integer curs=$CURSOR
integer elstart=$((CURSOR+1)) elend=$((CURSOR+1))
while [[ $elstart -gt 1 && $BUFFER[$elstart-1] != [${~chars}] ]]; do
  (( elstart-- ))
done
while [[ $elend -lt ${#BUFFER} && $BUFFER[$elend+1] != [${~chars}] ]]; do
  (( elend++ ))
done

integer inspos
if [[ $WIDGET = *forward* ]]; then
  (( inspos = elend + 1))
  while [[ $inspos -lt ${#BUFFER} && $BUFFER[$inspos+1] != [${~chars}] ]]; do
    (( inspos++ ))
  done

  # Insert first to keep the indexes the same
  BUFFER[$inspos+1]=\
"$BUFFER[$elend+1]$BUFFER[$elstart,$elend]$BUFFER[$inspos+1]"
  BUFFER[$elstart,$elend+1]=
  (( CURSOR = curs + inspos - elend ))
else
  (( inspos = elstart - 1 ))
  while [[ $inspos -gt 1 && $BUFFER[$inspos-1] != [${~chars}] ]]; do
    (( inspos-- ))
  done

  # Delete first to keep the indexes the same
  local sep=$BUFFER[$elstart-1] str=$BUFFER[$elstart,$elend]
  BUFFER[$elstart-1,$elend]=
  BUFFER[$inspos]="$str$sep$BUFFER[$inspos]"
  (( CURSOR = curs - (elstart - inspos) ))
fi
#end

-- 
Peter Stephenson <pws@xxxxxxx>                  Software Engineer
CSR PLC, Churchill House, Cambridge Business Park, Cowley Road
Cambridge, CB4 0WZ, UK                          Tel: +44 (0)1223 692070


To access the latest news from CSR copy this link into a web browser:  http://www.csr.com/email_sig.php



Messages sorted by: Reverse Date, Date, Thread, Author