Skip to content

Instantly share code, notes, and snippets.

@dceddia
Created May 7, 2020 23:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dceddia/0a45a88dd61cbdf1be023d0a8f157150 to your computer and use it in GitHub Desktop.
Save dceddia/0a45a88dd61cbdf1be023d0a8f157150 to your computer and use it in GitHub Desktop.
A custom zsh "widget" for inserting a duplicate of the last argument on the line. Good for renaming a file to a similar name.
# Press Alt-/ to insert the last argument from the same line
# ex:
# type "cp foo", press Alt-/, and it will insert " foo" so that your command will be
# cp foo foo
# Great when you want to rename a file to a similar name at the same path
# (This is different from Alt-. to insert the last arg from the previous command)
insertPreviousArg() {
echo $LBUFFER | read -A args
LAST_CHAR="${${:-$LBUFFER}[-1]}"
LAST_ARG="${args[$#args]}"
BEFORE_LAST_ARG="${args[$#args - 1]}"
if [[ $LAST_CHAR == " " ]]; then
LBUFFER="$LBUFFER$BEFORE_LAST_ARG"
else
LBUFFER="$LBUFFER $LAST_ARG"
fi
}
zle -N insertPreviousArg
bindkey '^[/' insertPreviousArg
@fugkco
Copy link

fugkco commented Feb 12, 2021

You can use copy-prev-shell-word (split on shell args) or copy-prev-word (split on blanks), which is built-in:

bindkey "^[/" copy-prev-shell-word

@dceddia
Copy link
Author

dceddia commented Feb 14, 2021

Oh awesome, thanks! I went searching for that before I hacked this together and I guess I just wasn't using the right terms.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment