# Copyright 2019 Misha Brukman
# SPDX-License-Identifier: Apache-2.0
# https://misha.brukman.net/blog/2019/12/uniting-vim-and-emacs-in-zsh/

setopt prompt_subst
VIMODE=" I"

# This string is in single quotes to avoid early evaluation; we will
# periodically re-evaluate this string, at which time we will need to
# capture then-current value of $VIMODE.
readonly PS1_TEMPLATE='%B%n%b@%U%m%u${VIMODE}%(!.#.>) '
PS1="${PS1_TEMPLATE}"

# Show current path with at most 5 dirs on the right prompt, collapsing
# $HOME as `~`.
RPS1="%5~"

# Vi with some Emacs flavor control keys.
bindkey -v
bindkey "^A" beginning-of-line
bindkey "^E" end-of-line
bindkey "^K" kill-line
bindkey "^L" clear-screen
bindkey "^R" history-incremental-search-backward
bindkey "^U" kill-whole-line
bindkey "^W" backward-kill-word
bindkey "^Y" yank

function zle-line-init() {
  # Note: this initial mode must match the $VIMODE initial value above.
  zle -K viins
}

zle -N zle-line-init

# Show insert/command mode in vi.
# zle-keymap-select is executed every time KEYMAP changes.
function zle-keymap-select {
  VIMODE="${${KEYMAP/vicmd/ C}/(main|viins)/ I}"
  PS1="${PS1_TEMPLATE}"
  zle reset-prompt
}

zle -N zle-keymap-select

# 'v' in visual mode opens VIM to edit the command in a full editor.
autoload -U edit-command-line
zle -N edit-command-line
bindkey -M vicmd v edit-command-line
