Skip to content
Myr

Add documentation on how callback function autocompletion works

Before adoption: this commit came in with the history the project adopted, so no landing records it.

authored by Brett Bethke · committed by Brett Bethke · parent f0b70a7 · Browse files · 1 file+29 added−4 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

1 file+29 added−4 removed

  • other:+29 added−4 removed

1 file+29 added−4 removed

modified:docs/bashcomplete.rst+29 added-4 removed
19 unmodified lines
2021What it Completes22-----------------2324Generally, the Bash completion support will complete subcommands and24By default, the Bash completion support will complete subcommands and25parameters. Subcommands are always listed whereas parameters only if at26least a dash has been provided. Example::2728 $ repo <TAB><TAB>29 clone commit copy delete setuser30 $ repo clone -<TAB><TAB>31 --deep --help --rev --shallow -r32 33Additionally, custom suggestions can be given to an argument with the34``autocompletion`` parameter. ``autocompletion`` may be a list of strings, or a35callback function that returns a list of strings.33Additionally, custom suggestions can be provided for arguments with the34``autocompletion`` parameter. ``autocompletion`` may be a list of strings, as35in the following example:3637.. click:example::3839 @click.command()40 @click.argument("name", type=click.STRING, autocompletion=["John", "Simon", "Doe"])41 def cmd1(name):42 click.echo('Name: %s' % name)43 44Alternatively, ``autocompletion`` may be a callback function that returns a list45of strings. This is useful when the suggestions need to be dynamically generated46at bash completion time. The callback function will be passed 4 keyword47arguments:4849- ``ctx`` - The current click context.50- ``incomplete`` - The partial word that is being completed, as a string. May51 be an empty string ``''`` if no characters have been entered yet.52- ``cwords`` - The bash `COMP_WORDS <https://www.gnu.org/software/bash/manual/html_node/Programmable-Completion.html#Programmable-Completion>`_ array, as a list of strings.53- ``cword`` - The bash `COMP_CWORD <https://www.gnu.org/software/bash/manual/html_node/Programmable-Completion.html#Programmable-Completion>`_ variable, as an integer.5455Here is an example of using a callback function to generate dynamic suggestions:5657.. click:example::5859 def lookup_names(ctx, incomplete, cwords, cword):60 names = []61 # Do stuff here to dynamically generate the list of names...62 return names6364 @click.command()65 @click.argument("name", type=click.STRING, autocompletion=lookup_names)66 def cmd1(name):67 click.echo('Name: %s' % name)6869 7071Activation72----------7374In order to activate Bash completion, you need to inform Bash that
33 unmodified lines