shell-completion.rst
This file
Path
docs/shell-completion.rst
291 lines · 9.5 KiB
Last changed by
Merge branch '8.1.x'David Lordbefore adoption99015e1
History of this fileTake it
The walk stopped after 200 commits: lines older than 2e9907a point at it.
Merge pull request #1983 from pallets/dependabot/pip/mypy-0.910David Lordbefore adoption2e9907a
lines 1–27why, one step back1.. 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. Seeswitch to flit build backend (#2543)David Lordbefore adoption3fcf338
line 28why, one step back28:doc:`entry-points`. Once the executable is installed, calling it withMerge pull request #1983 from pallets/dependabot/pip/mypy-0.910David Lordbefore adoption2e9907a
lines 29–30why, one step back29a special environment variable will put Click in completion mode.30Merge branch '8.1.x'David Lordbefore adoption99015e1
lines 31–40why, one step back31To enable shell completion, the user needs to register a special32function with their shell. The exact script varies depending on the33shell you are using. Click will output it when called with34``_{FOO_BAR}_COMPLETE`` set to ``{shell}_source``. ``{FOO_BAR}`` is35the executable name in uppercase with dashes replaced by underscores.36It is conventional but not strictly required for environment variable37names to be in upper case. This convention helps distinguish environment38variables from regular shell variables and commands, making scripts39and configuration files more readable and easier to maintain. The40built-in shells are ``bash``, ``zsh``, and ``fish``.Merge pull request #1983 from pallets/dependabot/pip/mypy-0.910David Lordbefore adoption2e9907a
lines 41–68why, one step back4142Provide your users with the following instructions customized to your43program name. This uses ``foo-bar`` as an example.4445.. tabs::4647 .. group-tab:: Bash4849 Add this to ``~/.bashrc``:5051 .. code-block:: bash5253 eval "$(_FOO_BAR_COMPLETE=bash_source foo-bar)"5455 .. group-tab:: Zsh5657 Add this to ``~/.zshrc``:5859 .. code-block:: zsh6061 eval "$(_FOO_BAR_COMPLETE=zsh_source foo-bar)"6263 .. group-tab:: Fish6465 Add this to ``~/.config/fish/completions/foo-bar.fish``:6667 .. code-block:: fish68Merge branch '8.1.x'David Lordbefore adoptionb765b12
line 69why, one step back69 _FOO_BAR_COMPLETE=fish_source foo-bar | sourceMerge pull request #1983 from pallets/dependabot/pip/mypy-0.910David Lordbefore adoption2e9907a
lines 70–138why, one step back7071 This is the same file used for the activation script method72 below. For Fish it's probably always easier to use that method.7374Using ``eval`` means that the command is invoked and evaluated every75time a shell is started, which can delay shell responsiveness. To speed76it up, write the generated script to a file, then source that. You can77generate the files ahead of time and distribute them with your program78to save your users a step.7980.. tabs::8182 .. group-tab:: Bash8384 Save the script somewhere.8586 .. code-block:: bash8788 _FOO_BAR_COMPLETE=bash_source foo-bar > ~/.foo-bar-complete.bash8990 Source the file in ``~/.bashrc``.9192 .. code-block:: bash9394 . ~/.foo-bar-complete.bash9596 .. group-tab:: Zsh9798 Save the script somewhere.99100 .. code-block:: bash101102 _FOO_BAR_COMPLETE=zsh_source foo-bar > ~/.foo-bar-complete.zsh103104 Source the file in ``~/.zshrc``.105106 .. code-block:: bash107108 . ~/.foo-bar-complete.zsh109110 .. group-tab:: Fish111112 Save the script to ``~/.config/fish/completions/foo-bar.fish``:113114 .. code-block:: fish115116 _FOO_BAR_COMPLETE=fish_source foo-bar > ~/.config/fish/completions/foo-bar.fish117118After modifying the shell config, you need to start a new shell in order119for the changes to be loaded.120121122Custom Type Completion123----------------------124125When creating a custom :class:`~click.ParamType`, override its126:meth:`~click.ParamType.shell_complete` method to provide shell127completion for parameters with the type. The method must return a list128of :class:`~CompletionItem` objects. Besides the value, these objects129hold metadata that shell support might use. The built-in implementations130use ``type`` to indicate special handling for paths, and ``help`` for131shells that support showing a help string next to a suggestion.132133In this example, the type will suggest environment variables that start134with the incomplete value.135136.. code-block:: python137138 class EnvVarType(ParamType):Merge pull request #2219 from pallets/paramtype-nameDavid Lordbefore adoptiond251cb0
lines 139–140why, one step back139 name = "envvar"140Merge pull request #1983 from pallets/dependabot/pip/mypy-0.910David Lordbefore adoption2e9907a
lines 141–200why, one step back141 def shell_complete(self, ctx, param, incomplete):142 return [143 CompletionItem(name)144 for name in os.environ if name.startswith(incomplete)145 ]146147 @click.command()148 @click.option("--ev", type=EnvVarType())149 def cli(ev):150 click.echo(os.environ[ev])151152153Overriding Value Completion154---------------------------155156Value completions for a parameter can be customized without a custom157type by providing a ``shell_complete`` function. The function is used158instead of any completion provided by the type. It is passed 3 keyword159arguments:160161- ``ctx`` - The current command context.162- ``param`` - The current parameter requesting completion.163- ``incomplete`` - The partial word that is being completed. May164 be an empty string if no characters have been entered yet.165166It must return a list of :class:`CompletionItem` objects, or as a167shortcut it can return a list of strings.168169In this example, the command will suggest environment variables that170start with the incomplete value.171172.. code-block:: python173174 def complete_env_vars(ctx, param, incomplete):175 return [k for k in os.environ if k.startswith(incomplete)]176177 @click.command()178 @click.argument("name", shell_complete=complete_env_vars)179 def cli(name):180 click.echo(f"Name: {name}")181 click.echo(f"Value: {os.environ[name]}")182183184Adding Support for a Shell185--------------------------186187Support can be added for shells that do not come built in. Be sure to188check PyPI to see if there's already a package that adds support for189your shell. This topic is very technical, you'll want to look at Click's190source to study the built-in implementations.191192Shell support is provided by subclasses of :class:`ShellComplete`193registered with :func:`add_completion_class`. When Click is invoked in194completion mode, it calls :meth:`~ShellComplete.source` to output the195completion script, or :meth:`~ShellComplete.complete` to output196completions. The base class provides default implementations that197require implementing some smaller parts.198199First, you'll need to figure out how your shell's completion system200works and write a script to integrate it with Click. It must invoke yourMerge branch '8.1.x'David Lordbefore adoption99015e1
line 201why, one step back201program with the environment variable ``_{FOO_BAR}_COMPLETE`` set toMerge pull request #1983 from pallets/dependabot/pip/mypy-0.910David Lordbefore adoption2e9907a
lines 202–213why, one step back202``{shell}_complete`` and pass the complete args and incomplete value.203How it passes those values, and the format of the completion response204from Click is up to you.205206In your subclass, set :attr:`~ShellComplete.source_template` to the207completion script. The default implementation will perform ``%``208formatting with the following variables:209210- ``complete_func`` - A safe name for the completion function defined211 in the script.212- ``complete_var`` - The environment variable name for passing the213 ``{shell}_complete`` instruction.Merge branch '8.1.x'David Lordbefore adoption99015e1
line 214why, one step back214- ``foo_bar`` - The name of the executable being completed.Merge pull request #1983 from pallets/dependabot/pip/mypy-0.910David Lordbefore adoption2e9907a
lines 215–224why, one step back215216The example code is for a made up shell "My Shell" or "mysh" for short.217218.. code-block:: python219220 from click.shell_completion import add_completion_class221 from click.shell_completion import ShellComplete222223 _mysh_source = """\224 %(complete_func)s {Merge branch '8.1.x'David Lordbefore adoption99015e1
line 225why, one step back225 response=$(%(complete_var)s=mysh_complete %(foo_bar)s)Merge pull request #1983 from pallets/dependabot/pip/mypy-0.910David Lordbefore adoption2e9907a
lines 226–227why, one step back226 # parse response and set completions somehow227 }Merge branch '8.1.x'David Lordbefore adoption99015e1
line 228why, one step back228 call-on-complete %(foo_bar)s %(complete_func)sMerge pull request #1983 from pallets/dependabot/pip/mypy-0.910David Lordbefore adoption2e9907a
lines 229–291why, one step back229 """230231 @add_completion_class232 class MyshComplete(ShellComplete):233 name = "mysh"234 source_template = _mysh_source235236Next, implement :meth:`~ShellComplete.get_completion_args`. This must237get, parse, and return the complete args and incomplete value from the238completion script. For example, for the Bash implementation the239``COMP_WORDS`` env var contains the command line args as a string, and240the ``COMP_CWORD`` env var contains the index of the incomplete arg. The241method must return a ``(args, incomplete)`` tuple.242243.. code-block:: python244245 import os246 from click.parser import split_arg_string247248 class MyshComplete(ShellComplete):249 ...250251 def get_completion_args(self):252 args = split_arg_string(os.environ["COMP_WORDS"])253254 if os.environ["COMP_PARTIAL"] == "1":255 incomplete = args.pop()256 return args, incomplete257258 return args, ""259260Finally, implement :meth:`~ShellComplete.format_completion`. This is261called to format each :class:`CompletionItem` into a string. For262example, the Bash implementation returns ``f"{item.type},{item.value}``263(it doesn't support help strings), and the Zsh implementation returns264each part separated by a newline, replacing empty help with a ``_``265placeholder. This format is entirely up to what you parse with your266completion script.267268The ``type`` value is usually ``plain``, but it can be another value269that the completion script can switch on. For example, ``file`` or270``dir`` can tell the shell to handle path completion, since the shell is271better at that than Click.272273.. code-block:: python274275 class MyshComplete(ShellComplete):276 ...277278 def format_completion(self, item):279 return f"{item.type}\t{item.value}"280281With those three things implemented, the new shell support is ready. In282case those weren't sufficient, there are more parts that can be283overridden, but that probably isn't necessary.284285The activation instructions will again depend on how your shell works.286Use the following to generate the completion script, then load it into287the shell somehow.288289.. code-block:: text290291 _FOO_BAR_COMPLETE=mysh_source foo-bar