# Enable vi keybindings
bindkey -v
export KEYTIMEOUT=1
autoload -z edit-command-line
zle -N edit-command-line
bindkey '^e' edit-command-line

# Fix backspace character behavior in vi mode
bindkey '^?' backward-delete-char
bindkey '^W' backward-kill-word
bindkey '^H' backward-delete-char # Control-h also deletes the previous char.
bindkey '^U' backward-kill-line

# Change cursor shape for different vi modes
zle-keymap-select() {
    if [[ ${KEYMAP} == vicmd ]] ||
        [[ $1 == block ]]; then
        echo -ne '\e[4 q'
        psvar[1]="(cmd) "
    elif [[ ${KEYMAP} == main ]] ||
        [[ ${KEYMAP} == viins ]] ||
        [[ -z ${KEYMAP} ]] ||
        [[ $1 == beam ]]; then
        echo -ne '\e[6 q'
        psvar[1]="(ins) "
    fi
    zle reset-prompt
}
zle -N zle-keymap-select
zle-line-init() {
    zle -K viins # Initiate `vi insert` as keymap (can be removed if `bindkey -V` has been set elsewhere)
    echo -ne '\e[6 q'
    psvar[1]="(ins) "
}
zle -N zle-line-init
echo -ne '\e[6 q' # Use beam shape cursor on startup
preexec() { echo -ne '\e[6 q' } # Use beam shape cursor for each new prompt
