shell-completion.rst
This file
Path
docs/shell-completion.rst
287 lines · 9.3 KiB
Last changed by
Merge pull request #2219 from pallets/paramtype-nameDavid Lordbefore adoptiond251cb0
History of this fileTake it
The walk stopped after 200 commits: lines older than 82ec44e point at it.
Merge pull request #1703 from pallets/dependabot/pip/pre-commit-2.8.2dependabot-preview[bot]before adoption82ec44e
lines 1–134why, 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. 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``{shell}_source``. ``{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=bash_source foo-bar)"5051 .. group-tab:: Zsh5253 Add this to ``~/.zshrc``:5455 .. code-block:: zsh5657 eval "$(_FOO_BAR_COMPLETE=zsh_source foo-bar)"5859 .. group-tab:: Fish6061 Add this to ``~/.config/fish/completions/foo-bar.fish``:6263 .. code-block:: fish6465 eval (env _FOO_BAR_COMPLETE=fish_source 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=bash_source 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=zsh_source 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=fish_source 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 :class:`~CompletionItem` objects. Besides the value, these objects125hold metadata that shell support might use. The built-in implementations126use ``type`` to indicate special handling for paths, and ``help`` for127shells that support showing a help string next to a suggestion.128129In this example, the type will suggest environment variables that start130with the incomplete value.131132.. code-block:: python133134 class EnvVarType(ParamType):Merge pull request #2219 from pallets/paramtype-nameDavid Lordbefore adoptiond251cb0
lines 135–136why, one step back135 name = "envvar"136Merge pull request #1703 from pallets/dependabot/pip/pre-commit-2.8.2dependabot-preview[bot]before adoption82ec44e
lines 137–287why, one step back137 def shell_complete(self, ctx, param, incomplete):138 return [139 CompletionItem(name)140 for name in os.environ if name.startswith(incomplete)141 ]142143 @click.command()144 @click.option("--ev", type=EnvVarType())145 def cli(ev):146 click.echo(os.environ[ev])147148149Overriding Value Completion150---------------------------151152Value completions for a parameter can be customized without a custom153type by providing a ``shell_complete`` function. The function is used154instead of any completion provided by the type. It is passed 3 keyword155arguments:156157- ``ctx`` - The current command context.158- ``param`` - The current parameter requesting completion.159- ``incomplete`` - The partial word that is being completed. May160 be an empty string if no characters have been entered yet.161162It must return a list of :class:`CompletionItem` objects, or as a163shortcut it can return a list of strings.164165In this example, the command will suggest environment variables that166start with the incomplete value.167168.. code-block:: python169170 def complete_env_vars(ctx, param, incomplete):171 return [k for k in os.environ if k.startswith(incomplete)]172173 @click.command()174 @click.argument("name", shell_complete=complete_env_vars)175 def cli(name):176 click.echo(f"Name: {name}")177 click.echo(f"Value: {os.environ[name]}")178179180Adding Support for a Shell181--------------------------182183Support can be added for shells that do not come built in. Be sure to184check PyPI to see if there's already a package that adds support for185your shell. This topic is very technical, you'll want to look at Click's186source to study the built-in implementations.187188Shell support is provided by subclasses of :class:`ShellComplete`189registered with :func:`add_completion_class`. When Click is invoked in190completion mode, it calls :meth:`~ShellComplete.source` to output the191completion script, or :meth:`~ShellComplete.complete` to output192completions. The base class provides default implementations that193require implementing some smaller parts.194195First, you'll need to figure out how your shell's completion system196works and write a script to integrate it with Click. It must invoke your197program with the environment variable ``_{PROG_NAME}_COMPLETE`` set to198``{shell}_complete`` and pass the complete args and incomplete value.199How it passes those values, and the format of the completion response200from Click is up to you.201202In your subclass, set :attr:`~ShellComplete.source_template` to the203completion script. The default implementation will perform ``%``204formatting with the following variables:205206- ``complete_func`` - A safe name for the completion function defined207 in the script.208- ``complete_var`` - The environment variable name for passing the209 ``{shell}_complete`` instruction.210- ``prog_name`` - The name of the executable being completed.211212The example code is for a made up shell "My Shell" or "mysh" for short.213214.. code-block:: python215216 from click.shell_completion import add_completion_class217 from click.shell_completion import ShellComplete218219 _mysh_source = """\220 %(complete_func)s {221 response=$(%(complete_var)s=mysh_complete %(prog_name)s)222 # parse response and set completions somehow223 }224 call-on-complete %(prog_name)s %(complete_func)s225 """226227 @add_completion_class228 class MyshComplete(ShellComplete):229 name = "mysh"230 source_template = _mysh_source231232Next, implement :meth:`~ShellComplete.get_completion_args`. This must233get, parse, and return the complete args and incomplete value from the234completion script. For example, for the Bash implementation the235``COMP_WORDS`` env var contains the command line args as a string, and236the ``COMP_CWORD`` env var contains the index of the incomplete arg. The237method must return a ``(args, incomplete)`` tuple.238239.. code-block:: python240241 import os242 from click.parser import split_arg_string243244 class MyshComplete(ShellComplete):245 ...246247 def get_completion_args(self):248 args = split_arg_string(os.environ["COMP_WORDS"])249250 if os.environ["COMP_PARTIAL"] == "1":251 incomplete = args.pop()252 return args, incomplete253254 return args, ""255256Finally, implement :meth:`~ShellComplete.format_completion`. This is257called to format each :class:`CompletionItem` into a string. For258example, the Bash implementation returns ``f"{item.type},{item.value}``259(it doesn't support help strings), and the Zsh implementation returns260each part separated by a newline, replacing empty help with a ``_``261placeholder. This format is entirely up to what you parse with your262completion script.263264The ``type`` value is usually ``plain``, but it can be another value265that the completion script can switch on. For example, ``file`` or266``dir`` can tell the shell to handle path completion, since the shell is267better at that than Click.268269.. code-block:: python270271 class MyshComplete(ShellComplete):272 ...273274 def format_completion(self, item):275 return f"{item.type}\t{item.value}"276277With those three things implemented, the new shell support is ready. In278case those weren't sufficient, there are more parts that can be279overridden, but that probably isn't necessary.280281The activation instructions will again depend on how your shell works.282Use the following to generate the completion script, then load it into283the shell somehow.284285.. code-block:: text286287 _FOO_BAR_COMPLETE=mysh_source foo-bar