Skip to content
Myr

shell-completion.rst

This file

Path

docs/shell-completion.rst

285 lines · 9.3 KiB

Last changed by

Merge pull request #1683 from pallets/complete-orderDavid Lordbefore adoptiond15d0cd

History of this file

Take it

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``{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):135        def shell_complete(self, ctx, param, incomplete):136            return [137                CompletionItem(name)138                for name in os.environ if name.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 a ``shell_complete`` function. The function is used152instead of any completion provided by the type. It is passed 3 keyword153arguments:154155-   ``ctx`` - The current command context.156-   ``param`` - The current parameter requesting completion.157-   ``incomplete`` - The partial word that is being completed. May158    be an empty string if no characters have been entered yet.159160It must return a list of :class:`CompletionItem` objects, or as a161shortcut it can return a list of strings.162163In this example, the command will suggest environment variables that164start with the incomplete value.165166.. code-block:: python167168    def complete_env_vars(ctx, param, incomplete):169        return [k for k in os.environ if k.startswith(incomplete)]170171    @click.command()172    @click.argument("name", shell_complete=complete_env_vars)173    def cli(name):174        click.echo(f"Name: {name}")175        click.echo(f"Value: {os.environ[name]}")176177178Adding Support for a Shell179--------------------------180181Support can be added for shells that do not come built in. Be sure to182check PyPI to see if there's already a package that adds support for183your shell. This topic is very technical, you'll want to look at Click's184source to study the built-in implementations.185186Shell support is provided by subclasses of :class:`ShellComplete`187registered with :func:`add_completion_class`. When Click is invoked in188completion mode, it calls :meth:`~ShellComplete.source` to output the189completion script, or :meth:`~ShellComplete.complete` to output190completions. The base class provides default implementations that191require implementing some smaller parts.192193First, you'll need to figure out how your shell's completion system194works and write a script to integrate it with Click. It must invoke your195program with the environment variable ``_{PROG_NAME}_COMPLETE`` set to196``{shell}_complete`` and pass the complete args and incomplete value.197How it passes those values, and the format of the completion response198from Click is up to you.199200In your subclass, set :attr:`~ShellComplete.source_template` to the201completion script. The default implementation will perform ``%``202formatting with the following variables:203204-   ``complete_func`` - A safe name for the completion function defined205    in the script.206-   ``complete_var`` - The environment variable name for passing the207    ``{shell}_complete`` instruction.208-   ``prog_name`` - The name of the executable being completed.209210The example code is for a made up shell "My Shell" or "mysh" for short.211212.. code-block:: python213214    from click.shell_completion import add_completion_class215    from click.shell_completion import ShellComplete216217    _mysh_source = """\218    %(complete_func)s {219        response=$(%(complete_var)s=mysh_complete %(prog_name)s)220        # parse response and set completions somehow221    }222    call-on-complete %(prog_name)s %(complete_func)s223    """224225    @add_completion_class226    class MyshComplete(ShellComplete):227        name = "mysh"228        source_template = _mysh_source229230Next, implement :meth:`~ShellComplete.get_completion_args`. This must231get, parse, and return the complete args and incomplete value from the232completion script. For example, for the Bash implementation the233``COMP_WORDS`` env var contains the command line args as a string, and234the ``COMP_CWORD`` env var contains the index of the incomplete arg. The235method must return a ``(args, incomplete)`` tuple.236237.. code-block:: python238239    import os240    from click.parser import split_arg_string241242    class MyshComplete(ShellComplete):243        ...244245        def get_completion_args(self):246            args = split_arg_string(os.environ["COMP_WORDS"])247248            if os.environ["COMP_PARTIAL"] == "1":249                incomplete = args.pop()250                return args, incomplete251252            return args, ""253254Finally, implement :meth:`~ShellComplete.format_completion`. This is255called to format each :class:`CompletionItem` into a string. For256example, the Bash implementation returns ``f"{item.type},{item.value}``257(it doesn't support help strings), and the Zsh implementation returns258each part separated by a newline, replacing empty help with a ``_``259placeholder. This format is entirely up to what you parse with your260completion script.261262The ``type`` value is usually ``plain``, but it can be another value263that the completion script can switch on. For example, ``file`` or264``dir`` can tell the shell to handle path completion, since the shell is265better at that than Click.266267.. code-block:: python268269    class MyshComplete(ShellComplete):270        ...271272        def format_completion(self, item):273            return f"{item.type}\t{item.value}"274275With those three things implemented, the new shell support is ready. In276case those weren't sufficient, there are more parts that can be277overridden, but that probably isn't necessary.278279The activation instructions will again depend on how your shell works.280Use the following to generate the completion script, then load it into281the shell somehow.282283.. code-block:: text284285    _FOO_BAR_COMPLETE=mysh_source foo-bar