#compdef -k complete-word \C-xt

#
#

emulate -L zsh

local c_Tagsfile=${TAGSFILE:-TAGS} c_tagsfile=${tagsfile:-tags} expl
integer c_maxdir=10
local curcontext="$curcontext"
local -a c_tags_array

if [[ -z "$curcontext" ]]; then
  curcontext="complete-tag:::"
else
  curcontext="complete-tag:${curcontext#*:}"
fi

local c_path=
integer c_idir
while [[ ! -f $c_path$c_Tagsfile &&
         ! -f $c_path$c_tagsfile && $c_idir -lt $c_maxdir ]]; do
  (( c_idir++ ))
  c_path=../$c_path
done

if [[ -f $c_path$c_Tagsfile && $c_path$c_Tagsfile -ef $c_path$c_tagsfile &&
      "$(head -1 $c_path$c_tagsfile)" == '!_TAG_'* ]]; then
        c_Tagsfile=
fi

if [[ -f $c_path$c_Tagsfile ]]; then
  c_tags_array=($(sed -n \
        -e 's/^\(.*[a-zA-Z_0-9]\)[[ '$'\t'':;,()]*'$'\177''.*$/\1/' \
        -e 's/^.*[^a-zA-Z_0-9]//' \
        -e '/^[a-zA-Z_].*/p' $c_path$c_Tagsfile))
  _main_complete - '' _wanted etags expl 'emacs tags' \
      compadd -a c_tags_array
elif [[ -f $c_path$c_tagsfile ]]; then
  c_tags_array=($(awk '{ print $1 }' $c_path$c_tagsfile))
  _main_complete - '' _wanted vtags expl 'vi tags' compadd -a c_tags_array
else
  return 1
fi
