# history select - search history and insert into prompt
# C-r: open history selector, type to filter, C-n/C-p to move, Enter to insert

histselect() {
  local lines=("${(@f)$(fc -l -n -r 1 | awk '!seen[$0]++')}")
  [[ ${#lines} -eq 0 ]] && return
  local query="" cursor=1 selected=""
  while true; do
    local filtered=()
    for l in "${lines[@]}"; do
      local match=1
      for word in ${(s: :)query}; do
        [[ "${l:l}" != *"${word:l}"* ]] && match=0 && break
      done
      [[ $match -eq 1 ]] && filtered+=("$l")
    done
    [[ $cursor -gt ${#filtered} ]] && cursor=${#filtered}
    [[ $cursor -lt 1 ]] && cursor=1
    clear
    echo "hist> $query"
    local i=1
    for l in "${filtered[@]}"; do
      if [[ $i -eq $cursor ]]; then
        printf "\e[7m  %s\e[0m\n" "$l"
      else
        printf "  %s\n" "$l"
      fi
      ((i++))
      [[ $i -gt 20 ]] && break
    done
    read -k1 key 2>/dev/null
    if [[ "$key" == $'\x1b' ]]; then
      read -k1 -t 0.1 k2 2>/dev/null
      if [[ "$k2" == "[" ]]; then
        read -k1 -t 0.1 k3 2>/dev/null
        case "$k3" in
          A) ((cursor--)) ;;
          B) ((cursor++)) ;;
        esac
        continue
      else
        break
      fi
    fi
    case "$key" in
      $'\n'|$'\r') [[ ${#filtered} -gt 0 ]] && selected="${filtered[$cursor]}"; break ;;
      $'\x0e') ((cursor++)) ;;  # C-n
      $'\x10') ((cursor--)) ;;  # C-p
      $'\x7f'|$'\b') query="${query%?}"; cursor=1 ;;
      *) query+="$key"; cursor=1 ;;
    esac
  done
  clear
  if [[ -n "$selected" ]]; then
    BUFFER="$selected"
    CURSOR=${#BUFFER}
  fi
  zle reset-prompt
}
zle -N histselect
bindkey '^r' histselect
