DEV Community

Discussion on: Using keyboard-shortcuts with zsh

Collapse
 
voyeg3r profile image
Sérgio Araújo • Edited

I am sharing some of my zsh widgets:

# toggles background shell
fancy-ctrl-z () {
  if [[ $#BUFFER -eq 0 ]]; then
    BUFFER="fg"
    zle accept-line
  else
    zle push-input
    zle clear-screen
  fi
}
zle -N fancy-ctrl-z
bindkey '^Z' fancy-ctrl-z

# add a command line to the shells history without executing it
commit-to-history() {
    print -s ${(z)BUFFER}
    zle send-break
}
zle -N commit-to-history
bindkey "^x^h" commit-to-history

# sometimes you find a nice piece of code and want to change something before
# executing it, so you want to get the clipboard content in a new vim buffer
# Edit content of clipboard on vim (scratch buffer)
function _edit_clipboard(){
    # pbpaste | vim -c 'setlocal bt=nofile bh=wipe nobl noswapfile nu'
    pbpaste | vim
}
zle -N edit-clipboard _edit_clipboard
bindkey '^x^v' edit-clipboard

# Copy the most recent command to the clipboard
function _pbcopy_last_command(){
    fc -ln -1 | sed -r 's/(\\n)//g' | xclip -selection clipboard
    echo "last cmd -> $(xclip -i -selection clipboard -o)"
}
zle -N pbcopy-last-command _pbcopy_last_command
bindkey '^x^l' pbcopy-last-command

# put the cursor in a subshell $()
# using Ctrl-j
function _zle_subshell {
    RBUFFER='$()'"$RBUFFER"
    ((CURSOR=CURSOR+2))
}
zle -N _zle_subshell
bindkey '^J' _zle_subshell
Enter fullscreen mode Exit fullscreen mode

in my "autoloaded" folder I also have this function:

# source:https://stackoverflow.com/a/65375231/2571881
# fzf list of files to vim (if you give up it does nothing)
function vif() {
    local fname
    local current_dir=$PWD
    cd ~/.dotfiles
    fname=$(fzf) || return
    vim "$fname"
    cd $current_dir
}
Enter fullscreen mode Exit fullscreen mode

The keybinding to open it automatically is: bindkey -s '^o' 'vif^M', so it will run when I press Ctrl-o.

Some useful aliases:

(( $+commands[xclip] )) && {
    alias pbpaste='xclip -i -selection clipboard -o'
    alias pbcopy='xclip -selection clipboard'
}
Enter fullscreen mode Exit fullscreen mode