# lyx(1) completion 
# Copyleft 2010 Cengiz Gunay <cengique@users.sf.net>

_have lyx &&
_lyx()
{
        local cur g last

	# turn on extglob	
	shopt -q extglob && g=1
	test $g -eq 0 && shopt -s extglob

        COMPREPLY=()
        cur=${COMP_WORDS[COMP_CWORD]}

	local dbg_cmds=( "none info init key gui \
			parser lyxrc kbmap latex mathed font tclass \
			lyxvc lyxserver action lyxlex depend insets \
			files workarea clipboard graphics changes \
			external painting debug any undo scrolling \
			macros rtl locale selection find" )

	# The below code would get rid of the hardcoding, but could be fragile:
	# local dbg_cmds=$( lyx -dbg | awk '{print $2}' | tail -n +2 )
	# If it is ever used, please put a comment in the code for -dbg output
	# about breaking auto completion if the format is changed.

	#echo "cmds: '$dbg_cmds'"

	if [[ $COMP_CWORD > 1 ]]; then
		last=${COMP_WORDS[$(($COMP_CWORD - 1))]}
	else
		last=''
	fi

	case "$last" in
		# check for export fmt. Short list presented
	--export|-e|-E|--export-to)
		COMPREPLY=( $(compgen -W 'latex pdflatex luatex xetex xhtml' -- $cur) );;
	--import|-i)
		# check for import format. Short list presented
		# (-i | --import) requireas a second input _filedir 
		# must point to *tex | *text | *xhtml depending on choice
		COMPREPLY=( $(compgen -W 'latex text luatex xetex xhtml' -- $cur) );;
	-dbg)
		# check for multiple debug commands
		if [[ $cur == *,* ]]; then #
			COMPREPLY=( $( compgen -W '$dbg_cmds' \
					       -P ${cur%,*}, -- ${cur##*,} ) )
		else
			COMPREPLY=( $( compgen -W '$dbg_cmds' -- $cur ) )
		fi;;
	--force-overwrite|-f)
		COMPREPLY=( $( compgen -W 'all main none' -- $cur ) );;

	latex|xetex|luatex|text|xhtml)
		# we need to know if previous token was -i or -E
		if [[ $COMP_CWORD > 2 ]]; then
			prev=${COMP_WORDS[$(($COMP_CWORD - 2))]}
		else
			prev=''
		fi
		if (test $prev=="-i")|(test $prev=="-E"); then
			case $last in
				text)
					_filedir '@(txt)' ;;
				latex|luatex|xetex)
					_filedir '@(tex)' ;;
				xhtml)
					_filedir '@(xhtml)' ;;
			esac
		fi;;
	pdflatex)
		# we need to know if previous token was -E
		if [[ $COMP_CWORD > 2 ]]; then
			prev=${COMP_WORDS[$(($COMP_CWORD - 2))]}
		else
			prev=''
		fi
		if test $prev == "-E"; then
					_filedir '@(pdf)' 
		fi;;
	*)
          case "$cur" in
          -*)
		# LyX command line options
                COMPREPLY=( $( compgen -W '-help -userdir -sysdir \
				-geometry -dbg -x --execute -e --export \
 				-i --import -version -batch -E --export-to \
				-f --force-overwrite -n --no-remote \
				-r --remote ' -- $cur ) ) ;;
	  
          *)
		# LyX files
		_filedir '@(lyx)' 
          esac
	esac

	# turn it off if necessary
	test $g -eq 0 && shopt -u extglob

} && complete -F _lyx $filenames lyx