Skip to content
Myr

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

10 files+318 added−169 removed

modified:docs/api.rst+16 added
167 unmodified lines
168169.. autoclass:: OptionParser170 :members:171172173Shell Completion174----------------175176See :doc:`/shell-completion` for information about enabling and177customizing Click's shell completion system.178179.. currentmodule:: click.shell_completion180181.. autoclass:: ShellComplete182 :members:183 :member-order: bysource184185.. autofunction:: add_completion_class186187188Testing189-------190191.. currentmodule:: click.testing
6 unmodified lines
deleted:docs/bashcomplete.rst-163 removed
1Shell Completion2================34.. versionadded:: 2.056Click can provide tab completion for commands, options, and choice7values. Bash, Zsh, and Fish are supported89Completion is only available if a script is installed and invoked10through an entry point, not through the ``python`` command. See11:ref:`setuptools-integration`.121314What it Completes15-----------------1617Generally, the shell completion support will complete commands,18options, and any option or argument values where the type is19:class:`click.Choice`. Options are only listed if at least a dash has20been entered.2122.. code-block:: text2324 $ repo <TAB><TAB>25 clone commit copy delete setuser26 $ repo clone -<TAB><TAB>27 --deep --help --rev --shallow -r2829Custom completions can be provided for argument and option values by30providing an ``autocompletion`` function that returns a list of strings.31This is useful when the suggestions need to be dynamically generated32completion time. The callback function will be passed 3 keyword33arguments:3435- ``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.3940Here is an example of using a callback function to generate dynamic41suggestions:4243.. code-block:: python4445 import os4647 def get_env_vars(ctx, args, incomplete):48 return [k for k in os.environ.keys() if incomplete in k]4950 @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]}")555657Completion help strings58-----------------------5960ZSH and fish support showing documentation strings for completions.61These are taken from the help parameters of options and subcommands. For62dynamically generated completions a help string can be provided by63returning a tuple instead of a string. The first element of the tuple is64the completion and the second is the help string to display.6566Here is an example of using a callback function to generate dynamic67suggestions with help strings:6869.. code-block:: python7071 import os7273 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]]7879 @click.command()80 @click.argument("color", type=click.STRING, autocompletion=get_colors)81 def cmd1(color):82 click.echo(f"Chosen color is {color}")838485Activation86----------8788In order to activate shell completion, you need to inform your shell89that completion is available for your script. Any Click application90automatically provides support for that. If the program is executed with91a special ``_<PROG_NAME>_COMPLETE`` variable, the completion mechanism92is triggered instead of the normal command. ``<PROG_NAME>`` is the93executable name in uppercase with dashes replaced by underscores.9495If your tool is called ``foo-bar``, then the variable is called96``_FOO_BAR_COMPLETE``. By exporting it with the ``source_{shell}``97value it will output the activation script to evaluate.9899Here are examples for a ``foo-bar`` script.100101For Bash, add this to ``~/.bashrc``:102103.. code-block:: text104105 eval "$(_FOO_BAR_COMPLETE=source_bash foo-bar)"106107For Zsh, add this to ``~/.zshrc``:108109.. code-block:: text110111 eval "$(_FOO_BAR_COMPLETE=source_zsh foo-bar)"112113For Fish, add this to ``~/.config/fish/completions/foo-bar.fish``:114115.. code-block:: text116117 eval (env _FOO_BAR_COMPLETE=source_fish foo-bar)118119Open a new shell to enable completion. Or run the ``eval`` command120directly in your current shell to enable it temporarily.121122123Activation Script124-----------------125126The above ``eval`` examples will invoke your application every time a127shell is started. This may slow down shell startup time significantly.128129Alternatively, export the generated completion code as a static script130to be executed. You can ship this file with your builds; tools like Git131do this. At least Zsh will also cache the results of completion files,132but not ``eval`` scripts.133134For Bash:135136.. code-block:: text137138 _FOO_BAR_COMPLETE=source_bash foo-bar > foo-bar-complete.sh139140For Zsh:141142.. code-block:: text143144 _FOO_BAR_COMPLETE=source_zsh foo-bar > foo-bar-complete.sh145146For Fish:147148.. code-block:: text149150 _FOO_BAR_COMPLETE=source_fish foo-bar > foo-bar-complete.fish151152In ``.bashrc`` or ``.zshrc``, source the script instead of the ``eval``153command:154155.. code-block:: text156157 . /path/to/foo-bar-complete.sh158159For Fish, add the file to the completions directory:160161.. code-block:: text162163 _FOO_BAR_COMPLETE=source_fish foo-bar > ~/.config/fish/completions/foo-bar-complete.fish
modified:docs/conf.py+1 added
20 unmodified lines
21 "sphinx.ext.intersphinx",22 "sphinxcontrib.log_cabinet",23 "pallets_sphinx_themes",24 "sphinx_issues",25 "sphinx_tabs.tabs",26]27intersphinx_mapping = {"python": ("https://docs.python.org/3/", None)}28issues_github_path = "pallets/click"29
27 unmodified lines
modified:docs/index.rst+1 added-1 removed
77 unmodified lines
78 complex79 advanced80 testing81 utils82 bashcomplete82 shell-completion83 exceptions84 unicode-support85 wincmd86
21 unmodified lines
added:docs/shell-completion.rst+286 added
1.. currentmodule:: click.shell_completion23Shell Completion4================56Click provides tab completion support for Bash (version 4.4 and up),7Zsh, and Fish. It is possible to add support for other shells too, and8suggestions can be customized at multiple levels.910Shell completion suggests command names, option names, and values for11choice, file, and path parameter types. Options are only listed if at12least a dash has been entered. Hidden commands and options are not13shown.1415.. code-block:: text1617 $ repo <TAB><TAB>18 clone commit copy delete setuser19 $ repo clone -<TAB><TAB>20 --deep --help --rev --shallow -r212223Enabling Completion24-------------------2526Completion is only available if a script is installed and invoked27through an entry point, not through the ``python`` command. See28:doc:`/setuptools`. Once the executable is installed, calling it with29a special environment variable will put Click in completion mode.3031In order for completion to be used, the user needs to register a special32function with their shell. The script is different for every shell, and33Click will output it when called with ``_{PROG_NAME}_COMPLETE`` set to34``source_{shell}``. ``{PROG_NAME}`` is the executable name in uppercase35with dashes replaced by underscores. The built-in shells are ``bash``,36``zsh``, and ``fish``.3738Provide your users with the following instructions customized to your39program name. This uses ``foo-bar`` as an example.4041.. tabs::4243 .. group-tab:: Bash4445 Add this to ``~/.bashrc``:4647 .. code-block:: bash4849 eval "$(_FOO_BAR_COMPLETE=source_bash foo-bar)"5051 .. group-tab:: Zsh5253 Add this to ``~/.zshrc``:5455 .. code-block:: zsh5657 eval "$(_FOO_BAR_COMPLETE=source_zsh foo-bar)"5859 .. group-tab:: Fish6061 Add this to ``~/.config/fish/completions/foo-bar.fish``:6263 .. code-block:: fish6465 eval (env _FOO_BAR_COMPLETE=source_fish foo-bar)6667 This is the same file used for the activation script method68 below. For Fish it's probably always easier to use that method.6970Using ``eval`` means that the command is invoked and evaluated every71time a shell is started, which can delay shell responsiveness. To speed72it up, write the generated script to a file, then source that. You can73generate the files ahead of time and distribute them with your program74to save your users a step.7576.. tabs::7778 .. group-tab:: Bash7980 Save the script somewhere.8182 .. code-block:: bash8384 _FOO_BAR_COMPLETE=source_bash foo-bar > ~/.foo-bar-complete.bash8586 Source the file in ``~/.bashrc``.8788 .. code-block:: bash8990 . ~/.foo-bar-complete.bash9192 .. group-tab:: Zsh9394 Save the script somewhere.9596 .. code-block:: bash9798 _FOO_BAR_COMPLETE=source_zsh foo-bar > ~/.foo-bar-complete.zsh99100 Source the file in ``~/.zshrc``.101102 .. code-block:: bash103104 . ~/.foo-bar-complete.zsh105106 .. group-tab:: Fish107108 Save the script to ``~/.config/fish/completions/foo-bar.fish``:109110 .. code-block:: fish111112 _FOO_BAR_COMPLETE=source_fish foo-bar > ~/.config/fish/completions/foo-bar.fish113114After modifying the shell config, you need to start a new shell in order115for the changes to be loaded.116117118Custom Type Completion119----------------------120121When creating a custom :class:`~click.ParamType`, override its122:meth:`~click.ParamType.shell_complete` method to provide shell123completion for parameters with the type. The method must return a list124of ``(type, value, help)`` tuples. ``type`` will usually be ``"plain"``125unless you've implemented a custom shell script. Some shells know how to126display a ``help`` string next to each suggestion.127128In this example, the type will suggest environment variables that start129with the incomplete value.130131.. code-block:: python132133 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 ]140141 @click.command()142 @click.option("--ev", type=EnvVarType())143 def cli(ev):144 click.echo(os.environ[ev])145146147Overriding Value Completion148---------------------------149150Value completions for a parameter can be customized without a custom151type by providing an ``autocompletion`` function. The function is used152instead of any completion provided by the type. It is passed 3 keyword153arguments, and returns a list of strings to be shown.154155- ``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.159160In this example, the command will suggest environment variables that161start with the incomplete value.162163.. code-block:: python164165 def complete_env_vars(ctx, args, incomplete):166 return [k for k in os.environ if k.startswith(incomplete)]167168 @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]}")173174175Adding Support for a Shell176--------------------------177178Support can be added for shells that do not come built in. Be sure to179check PyPI to see if there's already a package that adds support for180your shell. This topic is very technical, you'll want to look at Click's181source to study the built-in implementations.182183Shell support is provided by subclasses of :class:`ShellComplete`184registered with :func:`add_completion_class`. When Click is invoked in185completion mode, it calls :meth:`~ShellComplete.source` to output the186completion script, or :meth:`~ShellComplete.complete` to output187completions. The base class provides default implementations that188require implementing some smaller parts.189190First, you'll need to figure out how your shell's completion system191works and write a script to integrate it with Click. It must invoke your192program with the environment variable ``_{PROG_NAME}_COMPLETE`` set to193``complete_{shell}`` and pass the complete args and incomplete value.194How it passes those values, and the format of the completion response195from Click is up to you.196197In your subclass, set :attr:`~ShellComplete.source_template` to the198completion script. The default implementation will perform ``%``199formatting with the following variables:200201- ``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.206207The example code is for a made up shell "My Shell" or "mysh" for short.208209.. code-block:: python210211 from click.shell_completion import add_completion_class212 from click.shell_completion import ShellComplete213214 _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 """221222 @add_completion_class223 class MyshComplete(ShellComplete):224 name = "mysh"225 source_template = _mysh_source226227Next, implement :meth:`~ShellComplete.get_completion_args`. This must228get, parse, and return the complete args and incomplete value from the229completion script. For example, for the Bash implementation the230``COMP_WORDS`` env var contains the command line args as a string, and231the ``COMP_CWORD`` env var contains the index of the incomplete arg. The232method must return a ``(args, incomplete)`` tuple.233234.. code-block:: python235236 import os237 from click.parser import split_arg_string238239 class MyshComplete(ShellComplete):240 ...241242 def get_completion_args(self):243 args = split_arg_string(os.environ["COMP_WORDS"])244245 if os.environ["COMP_PARTIAL"] == "1":246 incomplete = args.pop()247 return args, incomplete248249 return args, ""250251Finally, implement :meth:`~ShellComplete.format_completion`. This is252called to format each ``(type, value, help)`` tuples returned by Click253into a string. For example, the Bash implementation returns254``f"{type},{value}`` (it doesn't support help strings), and the Zsh255implementation returns each part separated by a newline, replacing empty256help with a ``_`` placeholder. This format is entirely up to what you257parse with your completion script.258259The ``type`` value is usually ``plain``, but it can be another value260that the completion script can switch on. For example, ``file`` or261``dir`` can tell the shell to handle path completion, since the shell is262better at that than Click.263264.. code-block:: python265266 import os267 from click.parser import split_arg_string268269 class MyshComplete(ShellComplete):270 ...271272 def format_completion(self, item):273 type, value, _ = item274 return f"{type}\t{value}"275276With those three things implemented, the new shell support is ready. In277case those weren't sufficient, there are more parts that can be278overridden, but that probably isn't necessary.279280The activation instructions will again depend on how your shell works.281Use the following to generate the completion script, then load it into282the shell somehow.283284.. code-block:: text285286 _FOO_BAR_COMPLETE=source_mysh foo-bar
modified:requirements/dev.txt+3 added-2 removed
28 unmodified lines
29pip-tools==5.3.1 # via -r requirements/dev.in30pluggy==0.13.1 # via pytest, tox31pre-commit==2.7.1 # via -r requirements/dev.in32py==1.9.0 # via pytest, tox33pygments==2.6.1 # via sphinx33pygments==2.6.1 # via sphinx, sphinx-tabs34pyparsing==2.4.7 # via packaging35pytest==6.1.0 # via -r requirements/tests.in36pytz==2020.1 # via babel37pyyaml==5.3.1 # via pre-commit38requests==2.23.0 # via sphinx39six==1.15.0 # via packaging, pip-tools, tox, virtualenv40snowballstemmer==2.0.0 # via sphinx41sphinx-issues==1.2.0 # via -r requirements/docs.in42sphinx-tabs==1.3.0 # via -r requirements/docs.in42sphinx==3.2.1 # via -r requirements/docs.in, pallets-sphinx-themes, sphinx-issues, sphinxcontrib-log-cabinet43sphinx==3.2.1 # via -r requirements/docs.in, pallets-sphinx-themes, sphinx-issues, sphinx-tabs, sphinxcontrib-log-cabinet44sphinxcontrib-applehelp==1.0.2 # via sphinx45sphinxcontrib-devhelp==1.0.2 # via sphinx46sphinxcontrib-htmlhelp==1.0.3 # via sphinx47sphinxcontrib-jsmath==1.0.1 # via sphinx
12 unmodified lines
modified:requirements/docs.in+1 added
1Pallets-Sphinx-Themes2Sphinx3sphinx-issues4sphinxcontrib-log-cabinet5sphinx-tabs
modified:requirements/docs.txt+3 added-2 removed
13 unmodified lines
14jinja2==2.11.2 # via sphinx15markupsafe==1.1.1 # via jinja216packaging==20.4 # via pallets-sphinx-themes, sphinx17pallets-sphinx-themes==1.2.3 # via -r requirements/docs.in18pygments==2.6.1 # via sphinx18pygments==2.6.1 # via sphinx, sphinx-tabs19pyparsing==2.4.7 # via packaging20pytz==2020.1 # via babel21requests==2.23.0 # via sphinx22six==1.15.0 # via packaging23snowballstemmer==2.0.0 # via sphinx24sphinx-issues==1.2.0 # via -r requirements/docs.in25sphinx-tabs==1.3.0 # via -r requirements/docs.in25sphinx==3.2.1 # via -r requirements/docs.in, pallets-sphinx-themes, sphinx-issues, sphinxcontrib-log-cabinet26sphinx==3.2.1 # via -r requirements/docs.in, pallets-sphinx-themes, sphinx-issues, sphinx-tabs, sphinxcontrib-log-cabinet27sphinxcontrib-applehelp==1.0.2 # via sphinx28sphinxcontrib-devhelp==1.0.2 # via sphinx29sphinxcontrib-htmlhelp==1.0.3 # via sphinx30sphinxcontrib-jsmath==1.0.1 # via sphinx
7 unmodified lines
modified:src/click/shell_completion.py+1 added-1 removed
225 unmodified lines
226 def complete(self):227 """Produce the completion data to send back to the shell.228229 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 lines
modified:CHANGES.rst+6 added
88 unmodified lines
89- 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`9495 - 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.99100101Version 7.1.2102-------------103104Released 2020-04-27
633 unmodified lines