#
# Configure the zsh line editor
#
# Copyright © 1994–2017 martin f. krafft <madduck@madduck.net>
# Released under the terms of the Artistic Licence 2.0
#
# Source repository: http://git.madduck.net/v/etc/zsh.git
#

# allow 700ms between esc and subsequent character
KEYTIMEOUT=70

# do not consider '/' to be part of a word, i.e. delete-word
# iterates through URL components
WORDCHARS="${WORDCHARS//\/}"

# esc-= :: Repeat the previous shell-word ($WORDCHARS)
bindkey '\e=' copy-prev-shell-word

# esc-q :: allow for better ad-hoc multiline editing
bindkey '\eq' push-line-or-edit

# Perform history expansion and insert a space into the buffer.
bindkey ' ' magic-space

# Automatically escape URLs
autoload -U url-quote-magic
zle -N self-insert url-quote-magic
# … even when pasted
autoload -U bracketed-paste-magic
zle -N bracketed-paste bracketed-paste-magic

# Change defaults and remove {} from the meta characters, as we often use them
# in the shell to create multiple URLs, e.g. http://example.org/{1,2,3}.txt
zstyle ':url-quote-magic:*' url-metas '*?[]^(|)~#='

# Allow editing of the command line using $EDITOR with esc-e
autoload -U edit-command-line
zle -N edit-command-line
bindkey '\ee' edit-command-line

# Bind esc-u/-U to insert date-/timestamp based on shell timezones
# (esc-t/-T does it from urxvt in the local timezone
_insert_datestamp() { LBUFFER+=${(%):-'%D{%Y-%m-%d}'}; }
zle -N insert-datestamp _insert_datestamp
bindkey '\eu' insert-datestamp
_insert_timestamp() { LBUFFER+=${(%):-'%D{%Y-%m-%d-%H%M%S}'}; }
zle -N insert-timestamp _insert_timestamp
bindkey '\eU' insert-timestamp

# Jump behind the first word (and the space) on the cmdline to add options
function _jump_after_first_word() {
  emulate -L zsh
  local words
  words=(${(z)BUFFER})

  if (( ${#words} <= 1 )) ; then
    CURSOR=${#BUFFER}
  else
    CURSOR=$((${#${words[1]}}+1))
  fi
}
zle -N _jump_after_first_word
bindkey '\e1' _jump_after_first_word

# ^k :: kill through the end of the line
bindkey '^k' kill-line

# ^? :: borrow backspace behaviour from emacs-mode, rather than stilly limited
# viins
bindkey $terminfo[kbs] backward-delete-char

# ^a/^e :: move to beginning and end of line, like emacs
bindkey '^a' beginning-of-line
bindkey '^e' end-of-line

# \ew :: print pwd to status line
function _whereami() {
  zle -M "${(%):-"%m:%~"}"
}
zle -N _whereami
bindkey '\ew' _whereami

# ^x^x :: execute widgets directory
bindkey '^x^x' execute-named-cmd

# vim:ft=zsh