# file select - search files and insert into prompt
# C-f: open file selector

fileselect() {
  local files=("${(@f)$(find . -maxdepth 3 -not -path '*/\.git/*' -type f 2>/dev/null | sed 's|^\./||' | sort)}")
  [[ ${#files} -eq 0 ]] && return
  local query="" cursor=1 selected=""
  while true; do
    local filtered=()
    for f in "${files[@]}"; do
      local match=1
      for word in ${(s: :)query}; do
        [[ "${f:l}" != *"${word:l}"* ]] && match=0 && break
      done
      [[ $match -eq 1 ]] && filtered+=("$f")
    done
    [[ $cursor -gt ${#filtered} ]] && cursor=${#filtered}
    [[ $cursor -lt 1 ]] && cursor=1
    clear
    echo "file> $query (${#filtered})"
    local i=1
    for f in "${filtered[@]}"; do
      if [[ $i -eq $cursor ]]; then
        printf "\e[7m  %s\e[0m\n" "$f"
      else
        printf "  %s\n" "$f"
      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 fileselect
bindkey '^f' fileselect
