documentation for new shell completion system
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by Amy · committed by David Lord · parent 7029307 · Browse files · 10 files·+318 added−169 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Trailers
- Co-authored-by: Kai Chen <kaichen120@gmail.com>
- Co-authored-by: David Lord <davidism@gmail.com>
Diff stats
10 files+318 added−169 removed
- other:+318 added−169 removed
Provenance
- Commit
de75b40- Tree
59acdb0- Author
Amy <leiamy12@gmail.com>- Committer
David Lord <davidism@gmail.com>- Parent
7029307
10 files changed+318 added−169 removed
modified:docs/api.rst+16 added
167 unmodified lines168 169 .. autoclass:: OptionParser170 :members:171 172+173+Shell Completion174+----------------175+176+See :doc:`/shell-completion` for information about enabling and177+customizing Click's shell completion system.178+179+.. currentmodule:: click.shell_completion180+181+.. autoclass:: ShellComplete182+ :members:183+ :member-order: bysource184+185+.. autofunction:: add_completion_class186+187+188 Testing189 -------190 191 .. currentmodule:: click.testing6 unmodified linesdeleted:docs/bashcomplete.rst-163 removed
1-Shell Completion2-================3-4-.. versionadded:: 2.05-6-Click can provide tab completion for commands, options, and choice7-values. Bash, Zsh, and Fish are supported8-9-Completion is only available if a script is installed and invoked10-through an entry point, not through the ``python`` command. See11-:ref:`setuptools-integration`.12-13-14-What it Completes15------------------16-17-Generally, the shell completion support will complete commands,18-options, and any option or argument values where the type is19-:class:`click.Choice`. Options are only listed if at least a dash has20-been entered.21-22-.. code-block:: text23-24- $ repo <TAB><TAB>25- clone commit copy delete setuser26- $ repo clone -<TAB><TAB>27- --deep --help --rev --shallow -r28-29-Custom completions can be provided for argument and option values by30-providing an ``autocompletion`` function that returns a list of strings.31-This is useful when the suggestions need to be dynamically generated32-completion time. The callback function will be passed 3 keyword33-arguments:34-35-- ``ctx`` - The current command context.36-- ``args`` - The list of arguments passed in.37-- ``incomplete`` - The partial word that is being completed. May38- be an empty string if no characters have been entered yet.39-40-Here is an example of using a callback function to generate dynamic41-suggestions:42-43-.. code-block:: python44-45- import os46-47- def get_env_vars(ctx, args, incomplete):48- return [k for k in os.environ.keys() if incomplete in k]49-50- @click.command()51- @click.argument("envvar", type=click.STRING, autocompletion=get_env_vars)52- def cmd1(envvar):53- click.echo(f"Environment variable: {envvar}")54- click.echo(f"Value: {os.environ[envvar]}")55-56-57-Completion help strings58------------------------59-60-ZSH and fish support showing documentation strings for completions.61-These are taken from the help parameters of options and subcommands. For62-dynamically generated completions a help string can be provided by63-returning a tuple instead of a string. The first element of the tuple is64-the completion and the second is the help string to display.65-66-Here is an example of using a callback function to generate dynamic67-suggestions with help strings:68-69-.. code-block:: python70-71- import os72-73- def get_colors(ctx, args, incomplete):74- colors = [('red', 'a warm color'),75- ('blue', 'a cool color'),76- ('green', 'the other starter color')]77- return [c for c in colors if incomplete in c[0]]78-79- @click.command()80- @click.argument("color", type=click.STRING, autocompletion=get_colors)81- def cmd1(color):82- click.echo(f"Chosen color is {color}")83-84-85-Activation86-----------87-88-In order to activate shell completion, you need to inform your shell89-that completion is available for your script. Any Click application90-automatically provides support for that. If the program is executed with91-a special ``_<PROG_NAME>_COMPLETE`` variable, the completion mechanism92-is triggered instead of the normal command. ``<PROG_NAME>`` is the93-executable name in uppercase with dashes replaced by underscores.94-95-If your tool is called ``foo-bar``, then the variable is called96-``_FOO_BAR_COMPLETE``. By exporting it with the ``source_{shell}``97-value it will output the activation script to evaluate.98-99-Here are examples for a ``foo-bar`` script.100-101-For Bash, add this to ``~/.bashrc``:102-103-.. code-block:: text104-105- eval "$(_FOO_BAR_COMPLETE=source_bash foo-bar)"106-107-For Zsh, add this to ``~/.zshrc``:108-109-.. code-block:: text110-111- eval "$(_FOO_BAR_COMPLETE=source_zsh foo-bar)"112-113-For Fish, add this to ``~/.config/fish/completions/foo-bar.fish``:114-115-.. code-block:: text116-117- eval (env _FOO_BAR_COMPLETE=source_fish foo-bar)118-119-Open a new shell to enable completion. Or run the ``eval`` command120-directly in your current shell to enable it temporarily.121-122-123-Activation Script124------------------125-126-The above ``eval`` examples will invoke your application every time a127-shell is started. This may slow down shell startup time significantly.128-129-Alternatively, export the generated completion code as a static script130-to be executed. You can ship this file with your builds; tools like Git131-do this. At least Zsh will also cache the results of completion files,132-but not ``eval`` scripts.133-134-For Bash:135-136-.. code-block:: text137-138- _FOO_BAR_COMPLETE=source_bash foo-bar > foo-bar-complete.sh139-140-For Zsh:141-142-.. code-block:: text143-144- _FOO_BAR_COMPLETE=source_zsh foo-bar > foo-bar-complete.sh145-146-For Fish:147-148-.. code-block:: text149-150- _FOO_BAR_COMPLETE=source_fish foo-bar > foo-bar-complete.fish151-152-In ``.bashrc`` or ``.zshrc``, source the script instead of the ``eval``153-command:154-155-.. code-block:: text156-157- . /path/to/foo-bar-complete.sh158-159-For Fish, add the file to the completions directory:160-161-.. code-block:: text162-163- _FOO_BAR_COMPLETE=source_fish foo-bar > ~/.config/fish/completions/foo-bar-complete.fishmodified:docs/conf.py+1 added
20 unmodified lines21 "sphinx.ext.intersphinx",22 "sphinxcontrib.log_cabinet",23 "pallets_sphinx_themes",24 "sphinx_issues",25+ "sphinx_tabs.tabs",26 ]27 intersphinx_mapping = {"python": ("https://docs.python.org/3/", None)}28 issues_github_path = "pallets/click"29 27 unmodified linesmodified:docs/index.rst+1 added-1 removed
77 unmodified lines78 complex79 advanced80 testing81 utils82- bashcomplete82+ shell-completion83 exceptions84 unicode-support85 wincmd86 21 unmodified linesadded:docs/shell-completion.rst+286 added
1+.. currentmodule:: click.shell_completion2+3+Shell Completion4+================5+6+Click provides tab completion support for Bash (version 4.4 and up),7+Zsh, and Fish. It is possible to add support for other shells too, and8+suggestions can be customized at multiple levels.9+10+Shell completion suggests command names, option names, and values for11+choice, file, and path parameter types. Options are only listed if at12+least a dash has been entered. Hidden commands and options are not13+shown.14+15+.. code-block:: text16+17+ $ repo <TAB><TAB>18+ clone commit copy delete setuser19+ $ repo clone -<TAB><TAB>20+ --deep --help --rev --shallow -r21+22+23+Enabling Completion24+-------------------25+26+Completion is only available if a script is installed and invoked27+through an entry point, not through the ``python`` command. See28+:doc:`/setuptools`. Once the executable is installed, calling it with29+a special environment variable will put Click in completion mode.30+31+In order for completion to be used, the user needs to register a special32+function with their shell. The script is different for every shell, and33+Click will output it when called with ``_{PROG_NAME}_COMPLETE`` set to34+``source_{shell}``. ``{PROG_NAME}`` is the executable name in uppercase35+with dashes replaced by underscores. The built-in shells are ``bash``,36+``zsh``, and ``fish``.37+38+Provide your users with the following instructions customized to your39+program name. This uses ``foo-bar`` as an example.40+41+.. tabs::42+43+ .. group-tab:: Bash44+45+ Add this to ``~/.bashrc``:46+47+ .. code-block:: bash48+49+ eval "$(_FOO_BAR_COMPLETE=source_bash foo-bar)"50+51+ .. group-tab:: Zsh52+53+ Add this to ``~/.zshrc``:54+55+ .. code-block:: zsh56+57+ eval "$(_FOO_BAR_COMPLETE=source_zsh foo-bar)"58+59+ .. group-tab:: Fish60+61+ Add this to ``~/.config/fish/completions/foo-bar.fish``:62+63+ .. code-block:: fish64+65+ eval (env _FOO_BAR_COMPLETE=source_fish foo-bar)66+67+ This is the same file used for the activation script method68+ below. For Fish it's probably always easier to use that method.69+70+Using ``eval`` means that the command is invoked and evaluated every71+time a shell is started, which can delay shell responsiveness. To speed72+it up, write the generated script to a file, then source that. You can73+generate the files ahead of time and distribute them with your program74+to save your users a step.75+76+.. tabs::77+78+ .. group-tab:: Bash79+80+ Save the script somewhere.81+82+ .. code-block:: bash83+84+ _FOO_BAR_COMPLETE=source_bash foo-bar > ~/.foo-bar-complete.bash85+86+ Source the file in ``~/.bashrc``.87+88+ .. code-block:: bash89+90+ . ~/.foo-bar-complete.bash91+92+ .. group-tab:: Zsh93+94+ Save the script somewhere.95+96+ .. code-block:: bash97+98+ _FOO_BAR_COMPLETE=source_zsh foo-bar > ~/.foo-bar-complete.zsh99+100+ Source the file in ``~/.zshrc``.101+102+ .. code-block:: bash103+104+ . ~/.foo-bar-complete.zsh105+106+ .. group-tab:: Fish107+108+ Save the script to ``~/.config/fish/completions/foo-bar.fish``:109+110+ .. code-block:: fish111+112+ _FOO_BAR_COMPLETE=source_fish foo-bar > ~/.config/fish/completions/foo-bar.fish113+114+After modifying the shell config, you need to start a new shell in order115+for the changes to be loaded.116+117+118+Custom Type Completion119+----------------------120+121+When creating a custom :class:`~click.ParamType`, override its122+:meth:`~click.ParamType.shell_complete` method to provide shell123+completion for parameters with the type. The method must return a list124+of ``(type, value, help)`` tuples. ``type`` will usually be ``"plain"``125+unless you've implemented a custom shell script. Some shells know how to126+display a ``help`` string next to each suggestion.127+128+In this example, the type will suggest environment variables that start129+with the incomplete value.130+131+.. code-block:: python132+133+ class EnvVarType(ParamType):134+ def shell_complete(self, ctx, args, incomplete):135+ return [136+ ("plain", k, None)137+ for k in os.environ138+ if k.startswith(incomplete)139+ ]140+141+ @click.command()142+ @click.option("--ev", type=EnvVarType())143+ def cli(ev):144+ click.echo(os.environ[ev])145+146+147+Overriding Value Completion148+---------------------------149+150+Value completions for a parameter can be customized without a custom151+type by providing an ``autocompletion`` function. The function is used152+instead of any completion provided by the type. It is passed 3 keyword153+arguments, and returns a list of strings to be shown.154+155+- ``ctx`` - The current command context.156+- ``args`` - The list of complete args before the incomplete value.157+- ``incomplete`` - The partial word that is being completed. May158+ be an empty string if no characters have been entered yet.159+160+In this example, the command will suggest environment variables that161+start with the incomplete value.162+163+.. code-block:: python164+165+ def complete_env_vars(ctx, args, incomplete):166+ return [k for k in os.environ if k.startswith(incomplete)]167+168+ @click.command()169+ @click.argument("name", autocompletion=complete_env_vars)170+ def cli(name):171+ click.echo(f"Name: {name}")172+ click.echo(f"Value: {os.environ[name]}")173+174+175+Adding Support for a Shell176+--------------------------177+178+Support can be added for shells that do not come built in. Be sure to179+check PyPI to see if there's already a package that adds support for180+your shell. This topic is very technical, you'll want to look at Click's181+source to study the built-in implementations.182+183+Shell support is provided by subclasses of :class:`ShellComplete`184+registered with :func:`add_completion_class`. When Click is invoked in185+completion mode, it calls :meth:`~ShellComplete.source` to output the186+completion script, or :meth:`~ShellComplete.complete` to output187+completions. The base class provides default implementations that188+require implementing some smaller parts.189+190+First, you'll need to figure out how your shell's completion system191+works and write a script to integrate it with Click. It must invoke your192+program with the environment variable ``_{PROG_NAME}_COMPLETE`` set to193+``complete_{shell}`` and pass the complete args and incomplete value.194+How it passes those values, and the format of the completion response195+from Click is up to you.196+197+In your subclass, set :attr:`~ShellComplete.source_template` to the198+completion script. The default implementation will perform ``%``199+formatting with the following variables:200+201+- ``complete_func`` - A safe name for the completion function defined202+ in the script.203+- ``complete_var`` - The environment variable name for passing the204+ ``complete_{shell}`` value.205+- ``prog_name`` - The name of the executable being completed.206+207+The example code is for a made up shell "My Shell" or "mysh" for short.208+209+.. code-block:: python210+211+ from click.shell_completion import add_completion_class212+ from click.shell_completion import ShellComplete213+214+ _mysh_source = """\215+ %(complete_func)s {216+ response=$(%(complete_var)s=complete_mysh %(prog_name)s)217+ # parse response and set completions somehow218+ }219+ call-on-complete %(prog_name)s %(complete_func)s220+ """221+222+ @add_completion_class223+ class MyshComplete(ShellComplete):224+ name = "mysh"225+ source_template = _mysh_source226+227+Next, implement :meth:`~ShellComplete.get_completion_args`. This must228+get, parse, and return the complete args and incomplete value from the229+completion script. For example, for the Bash implementation the230+``COMP_WORDS`` env var contains the command line args as a string, and231+the ``COMP_CWORD`` env var contains the index of the incomplete arg. The232+method must return a ``(args, incomplete)`` tuple.233+234+.. code-block:: python235+236+ import os237+ from click.parser import split_arg_string238+239+ class MyshComplete(ShellComplete):240+ ...241+242+ def get_completion_args(self):243+ args = split_arg_string(os.environ["COMP_WORDS"])244+245+ if os.environ["COMP_PARTIAL"] == "1":246+ incomplete = args.pop()247+ return args, incomplete248+249+ return args, ""250+251+Finally, implement :meth:`~ShellComplete.format_completion`. This is252+called to format each ``(type, value, help)`` tuples returned by Click253+into a string. For example, the Bash implementation returns254+``f"{type},{value}`` (it doesn't support help strings), and the Zsh255+implementation returns each part separated by a newline, replacing empty256+help with a ``_`` placeholder. This format is entirely up to what you257+parse with your completion script.258+259+The ``type`` value is usually ``plain``, but it can be another value260+that the completion script can switch on. For example, ``file`` or261+``dir`` can tell the shell to handle path completion, since the shell is262+better at that than Click.263+264+.. code-block:: python265+266+ import os267+ from click.parser import split_arg_string268+269+ class MyshComplete(ShellComplete):270+ ...271+272+ def format_completion(self, item):273+ type, value, _ = item274+ return f"{type}\t{value}"275+276+With those three things implemented, the new shell support is ready. In277+case those weren't sufficient, there are more parts that can be278+overridden, but that probably isn't necessary.279+280+The activation instructions will again depend on how your shell works.281+Use the following to generate the completion script, then load it into282+the shell somehow.283+284+.. code-block:: text285+286+ _FOO_BAR_COMPLETE=source_mysh foo-barmodified:requirements/dev.txt+3 added-2 removed
28 unmodified lines29 pip-tools==5.3.1 # via -r requirements/dev.in30 pluggy==0.13.1 # via pytest, tox31 pre-commit==2.7.1 # via -r requirements/dev.in32 py==1.9.0 # via pytest, tox33-pygments==2.6.1 # via sphinx33+pygments==2.6.1 # via sphinx, sphinx-tabs34 pyparsing==2.4.7 # via packaging35 pytest==6.1.0 # via -r requirements/tests.in36 pytz==2020.1 # via babel37 pyyaml==5.3.1 # via pre-commit38 requests==2.23.0 # via sphinx39 six==1.15.0 # via packaging, pip-tools, tox, virtualenv40 snowballstemmer==2.0.0 # via sphinx41 sphinx-issues==1.2.0 # via -r requirements/docs.in42+sphinx-tabs==1.3.0 # via -r requirements/docs.in42-sphinx==3.2.1 # via -r requirements/docs.in, pallets-sphinx-themes, sphinx-issues, sphinxcontrib-log-cabinet43+sphinx==3.2.1 # via -r requirements/docs.in, pallets-sphinx-themes, sphinx-issues, sphinx-tabs, sphinxcontrib-log-cabinet44 sphinxcontrib-applehelp==1.0.2 # via sphinx45 sphinxcontrib-devhelp==1.0.2 # via sphinx46 sphinxcontrib-htmlhelp==1.0.3 # via sphinx47 sphinxcontrib-jsmath==1.0.1 # via sphinx12 unmodified linesmodified:requirements/docs.in+1 added
1 Pallets-Sphinx-Themes2 Sphinx3 sphinx-issues4 sphinxcontrib-log-cabinet5+sphinx-tabsmodified:requirements/docs.txt+3 added-2 removed
13 unmodified lines14 jinja2==2.11.2 # via sphinx15 markupsafe==1.1.1 # via jinja216 packaging==20.4 # via pallets-sphinx-themes, sphinx17 pallets-sphinx-themes==1.2.3 # via -r requirements/docs.in18-pygments==2.6.1 # via sphinx18+pygments==2.6.1 # via sphinx, sphinx-tabs19 pyparsing==2.4.7 # via packaging20 pytz==2020.1 # via babel21 requests==2.23.0 # via sphinx22 six==1.15.0 # via packaging23 snowballstemmer==2.0.0 # via sphinx24 sphinx-issues==1.2.0 # via -r requirements/docs.in25+sphinx-tabs==1.3.0 # via -r requirements/docs.in25-sphinx==3.2.1 # via -r requirements/docs.in, pallets-sphinx-themes, sphinx-issues, sphinxcontrib-log-cabinet26+sphinx==3.2.1 # via -r requirements/docs.in, pallets-sphinx-themes, sphinx-issues, sphinx-tabs, sphinxcontrib-log-cabinet27 sphinxcontrib-applehelp==1.0.2 # via sphinx28 sphinxcontrib-devhelp==1.0.2 # via sphinx29 sphinxcontrib-htmlhelp==1.0.3 # via sphinx30 sphinxcontrib-jsmath==1.0.1 # via sphinx7 unmodified linesmodified:src/click/shell_completion.py+1 added-1 removed
225 unmodified lines226 def complete(self):227 """Produce the completion data to send back to the shell.228 229 By default this calls :meth:`get_completion_args`, gets the230- completions, then calls `:meth:`format_completion` for each230+ completions, then calls :meth:`format_completion` for each231 completion.232 """233 args, incomplete = self.get_completion_args()234 completions = self.get_completions(args, incomplete)275 unmodified linesmodified:CHANGES.rst+6 added
88 unmodified lines89 - Core objects have a ``to_info_dict()`` method. This gathers90 information about the object's structure that could be useful for a91 tool generating user-facing documentation. To get the structure of92 an entire CLI, use ``Context(cli).to_info_dict()``. :issue:`461`93+- Redesign the shell completion system. :issue:`1484`, :pr:`1622`94 95+ - Support Bash >= 4.4, Zsh, and Fish, with the ability for96+ extensions to add support for other shells.97+ - Allow commands, groups, parameters, and types to override their98+ completions suggestions.99 100+101 Version 7.1.2102 -------------103 104 Released 2020-04-27633 unmodified lines