hledger/shell-completion/hledger-completion.bash.m4
2019-01-23 16:46:17 -08:00

95 lines
2.6 KiB
Bash

#!/bin/bash
# Completion script for hledger.
# Created using a Makefile and real hledger.
# No set -e because this file is sourced and is not supposed to quit the current shell.
set -o pipefail
# TODO grep "^$wordToComplete" is not safe to use if the word contains regex
# special chars. But it might be no problem because of COMP_WORDBREAKS.
# TODO Try to get file from -f --file arguments from COMP_WORDS and pass it to
# the 'hledger accounts' call.
# Working with bash arrays is nasty compared to editing a text file. Consider
# for example grepping an array or map a substitution on it.
# Therefore, we create temp files in RAM for completion suggestions (see below).
declare -g HLEDGER_COMPLETION_TEMPDIR
HLEDGER_COMPLETION_TEMPDIR=$(mktemp -d)
hledgerCompletionFunction() {
declare cmd=$1
declare wordToComplete=$2
declare precedingWord=$3
declare subcommand
for subcommand in "${COMP_WORDS[@]}"; do
if grep -Fxqe "$subcommand" "$HLEDGER_COMPLETION_TEMPDIR/commands.txt"; then
#declare -a options
#readarray -t options <(grep "^$wordToComplete" "$HLEDGER_COMPLETION_TEMPDIR/options-$subcommand.txt")
#COMPREPLY+=( "${options[@]}" )
COMPREPLY+=( $(grep -h "^$wordToComplete" -- "$HLEDGER_COMPLETION_TEMPDIR/options-$subcommand.txt") )
break
fi
subcommand=
done
if [[ -z $subcommand ]]; then
declare completeFiles filenameSoFar
case $wordToComplete in
--file=*|--rules-file=*)
completeFiles=1
filenameSoFar=${wordToComplete#*=}
;;
esac
case $precedingWord in
-f|--file|--rules-file)
completeFiles=1
filenameSoFar=$wordToComplete
;;
esac
if [[ -n $completeFiles ]]; then
:
#COMP_WORDBREAKS='= '
COMPREPLY+=( $(compgen -df | grep "^$filenameSoFar") )
else
COMPREPLY+=( $(grep -h "^$wordToComplete" -- "$HLEDGER_COMPLETION_TEMPDIR/commands.txt" "$HLEDGER_COMPLETION_TEMPDIR/generic-options.txt") )
fi
else
# Almost all subcommands accpt [QUERY] -> always add accounts to completion list
COMP_WORDBREAKS=' '
COMPREPLY+=( $(hledger accounts --flat | grep "^$wordToComplete") )
fi
}
complete -F hledgerCompletionFunction hledger
# Include lists of commands and options generated by the Makefile using m4
# macro processor.
# Included files must have exactly one newline at EOF to prevent weired errors.
cat <<TEXT > "$HLEDGER_COMPLETION_TEMPDIR/commands.txt"
include(`commands.txt')dnl
TEXT
cat <<TEXT > "$HLEDGER_COMPLETION_TEMPDIR/generic-options.txt"
include(`generic-options.txt')dnl
TEXT
include(`foreach2.m4')
foreach(`cmd', (include(`commands-list.txt')), `
cat <<TEXT > "$HLEDGER_COMPLETION_TEMPDIR/options-cmd.txt"
include(options-cmd.txt)dnl
TEXT
')