# nlsh zsh widget — add to ~/.zshrc
# Invoke with ctrl+space at any prompt.
# If you've already typed something, it becomes the query.

_nlsh_widget() {
  local query="$BUFFER"
  local tmpfile
  tmpfile=$(mktemp)

  # Clear the current line visually
  BUFFER=""
  zle reset-prompt

  # zle -I hands full terminal control to nlsh so curses can draw.
  # --print makes nlsh write the chosen command to stdout (tmpfile)
  # instead of executing it.
  zle -I
  nlsh ${query:+"$query"} --print > "$tmpfile"
  local exit_code=$?

  if [[ $exit_code -eq 0 ]] && [[ -s "$tmpfile" ]]; then
    BUFFER=$(cat "$tmpfile")
    rm -f "$tmpfile"
    CURSOR=${#BUFFER}
    zle accept-line   # execute immediately
  else
    BUFFER="$query"   # restore original text if user quit
    rm -f "$tmpfile"
    CURSOR=${#BUFFER}
    zle reset-prompt
  fi
}

zle -N _nlsh_widget
bindkey '^F' _nlsh_widget   # ctrl+f  (mnemonic: "find me a command")
