#!/bin/bash

function __keep_preexec {
  KEEP_META_command="$1"
  KEEP_META_tty=${KEEP_META_tty:-$(tty)}
}

function __keep_preexec_init {
  for f in "${preexec_functions[@]}"; do
    [[ $f = __keep_preexec ]] && return
  done
  preexec_functions+=(__keep_preexec)
}

function keep {
  (
    if [[ $BASH_SUBSHELL -le 2 ]]; then
      export KEEP_META_command
    fi

    export KEEP_META_tty

    exec keep "$@"
  )
}

function @ {
  keep --save "$@"
}

function @@ {
  keep --get "$@"
}

# Shell completions
. <(command keep --generate-completion bash)

___keep_complete() {
    local mode="$1"
    COMP_WORDS=(keep "$mode" "${COMP_WORDS[@]:1}")
    COMP_CWORD=$((COMP_CWORD + 1))
    _keep
}

___keep_save_completion() { ___keep_complete --save; }
___keep_get_completion() { ___keep_complete --get; }

complete -F ___keep_save_completion @
complete -F ___keep_get_completion @@

__keep_preexec_init
