Search code examples
pythonbashpython-click

Determine final character in bash tabcompletion


I'm looking to determine whether the final character is a space, or not.

$ mycli fl[TAB]  # no space
flag flare
$ mycli flare [TAB]  # yes space
A B C D

Reason

If it is a space, then the each argument is used to determine completion hints, but if it isn't a space, the former arguments will be used to determine a completion hint to the last. I just need to know which route to take in the Python script I'm using to compute the completion.

_mycli () {
  COMPREPLY=();

  local cur=${COMP_WORDS[COMP_CWORD]}
  local opts=$(mycli tabcompletion $COMP_LINE)
  COMPREPLY=($(compgen -W "${opts}" $cur))

  return 0
}

complete -F _mycli -o bashdefault mycli

It's probably out of scope for the question, here this is what part of the Python script looks like.

@mycli.command()
@click.argument("arguments", nargs=-1, required=False)
def tabcompletion(arguments):
    # Discard `mycli tabcompletion`
    arguments = list(arguments)[2:]

    complete = False
    if ???:
       complete = True

I'm looking to somehow determine (the ???-portion) whether an argument is finished, or whether to provide for completion to it.


Solution

  • The space signals the end of the previous word and the beginning of a new word. Thus, cur will be fl in the first case and the empty string in the second.