shell-completion.md
This file
Path
docs/shell-completion.md
275 lines · 9.9 KiB · Markdown
Last changed by
Merge main into stable (#3800)Rowlando13before adoption420c8fb
History of this fileTake it
Move Setuptools and Shell-completion docs from reST to MyST (#2987)Rowlando13before adoption528fd7a
lines 1–7why, one step back1(shell-completion)=23# Shell Completion45```{currentmodule} click.shell_completion6```7Merge main into stable (#3800)Rowlando13before adoption420c8fb
lines 8–9why, one step back8Click provides tab completion support for Bash (version 4.4 and up), Zsh, Fish, and PowerShell. It is possible to add9support for other shells too, and suggestions can be customized at multiple levels.Move Setuptools and Shell-completion docs from reST to MyST (#2987)Rowlando13before adoption528fd7a
lines 10–31why, one step back1011Shell completion suggests command names, option names, and values for choice, file, and path parameter types. Options12are only listed if at least a dash has been entered. Hidden commands and options are not shown.1314```console15$ repo <TAB><TAB>16clone commit copy delete setuser17$ repo clone -<TAB><TAB>18--deep --help --rev --shallow -r19```2021## Enabling Completion2223Completion is only available if a script is installed and invoked through an entry point, not through the `python`24command. See {doc}`entry-points`. Once the executable is installed, calling it with a special environment variable will25put Click in completion mode.2627To enable shell completion, the user needs to register a special function with their shell. The exact script varies28depending on the shell you are using. Click will output it when called with `_{FOO_BAR}_COMPLETE` set to29`{shell}_source`. `{FOO_BAR}` is the executable name in uppercase with dashes replaced by underscores. It is30conventional but not strictly required for environment variable names to be in upper case. This convention helps31distinguish environment variables from regular shell variables and commands, making scripts and configuration files moreAdd built-in PowerShell shell completion support (#3637)Rowlando13before adoption7df2f82
line 32why, one step back32readable and easier to maintain. The built-in shells are `bash`, `zsh`, `fish`, and `powershell`.Move Setuptools and Shell-completion docs from reST to MyST (#2987)Rowlando13before adoption528fd7a
lines 33–64why, one step back3334Provide your users with the following instructions customized to your program name. This uses `foo-bar` as an example.3536```{eval-rst}37.. tabs::3839 .. group-tab:: Bash4041 Add this to ``~/.bashrc``:4243 .. code-block:: bash4445 eval "$(_FOO_BAR_COMPLETE=bash_source foo-bar)"4647 .. group-tab:: Zsh4849 Add this to ``~/.zshrc``:5051 .. code-block:: zsh5253 eval "$(_FOO_BAR_COMPLETE=zsh_source foo-bar)"5455 .. group-tab:: Fish5657 Add this to ``~/.config/fish/completions/foo-bar.fish``:5859 .. code-block:: fish6061 _FOO_BAR_COMPLETE=fish_source foo-bar | source6263 This is the same file used for the activation script method64 below. For Fish it's probably always easier to use that method.Add built-in PowerShell shell completion support (#3637)Rowlando13before adoption7df2f82
lines 65–74why, one step back6566 .. group-tab:: PowerShell6768 Add this to your PowerShell profile (the path of ``$PROFILE``):6970 .. code-block:: powershell7172 $env:_FOO_BAR_COMPLETE = 'powershell_source'73 foo-bar | Out-String | Invoke-Expression74 Remove-Item Env:_FOO_BAR_COMPLETEMove Setuptools and Shell-completion docs from reST to MyST (#2987)Rowlando13before adoption528fd7a
lines 75–118why, one step back75```7677Using `eval` means that the command is invoked and evaluated every time a shell is started, which can delay shell78responsiveness. To speed it up, write the generated script to a file, then source that. You can generate the files ahead79of time and distribute them with your program to save your users a step.8081```{eval-rst}82.. tabs::8384 .. group-tab:: Bash8586 Save the script somewhere.8788 .. code-block:: bash8990 _FOO_BAR_COMPLETE=bash_source foo-bar > ~/.foo-bar-complete.bash9192 Source the file in ``~/.bashrc``.9394 .. code-block:: bash9596 . ~/.foo-bar-complete.bash9798 .. group-tab:: Zsh99100 Save the script somewhere.101102 .. code-block:: bash103104 _FOO_BAR_COMPLETE=zsh_source foo-bar > ~/.foo-bar-complete.zsh105106 Source the file in ``~/.zshrc``.107108 .. code-block:: bash109110 . ~/.foo-bar-complete.zsh111112 .. group-tab:: Fish113114 Save the script to ``~/.config/fish/completions/foo-bar.fish``:115116 .. code-block:: fish117118 _FOO_BAR_COMPLETE=fish_source foo-bar > ~/.config/fish/completions/foo-bar.fishAdd built-in PowerShell shell completion support (#3637)Rowlando13before adoption7df2f82
lines 119–134why, one step back119120 .. group-tab:: PowerShell121122 Save the script somewhere.123124 .. code-block:: powershell125126 $env:_FOO_BAR_COMPLETE = 'powershell_source'127 foo-bar | Out-File -Encoding utf8 ~/.foo-bar-complete.ps1128 Remove-Item Env:_FOO_BAR_COMPLETE129130 Source the file in your PowerShell profile (the path of ``$PROFILE``):131132 .. code-block:: powershell133134 . ~/.foo-bar-complete.ps1Move Setuptools and Shell-completion docs from reST to MyST (#2987)Rowlando13before adoption528fd7a
lines 135–148why, one step back135```136137After modifying the shell config, you need to start a new shell in order for the changes to be loaded.138139## Custom Type Completion140141When creating a custom {class}`~click.ParamType`, override its {meth}`~click.ParamType.shell_complete` method to provide142shell completion for parameters with the type. The method must return a list of {class}`~CompletionItem` objects.143Besides the value, these objects hold metadata that shell support might use. The built-in implementations use `type` to144indicate special handling for paths, and `help` for shells that support showing a help string next to a suggestion.145146In this example, the type will suggest environment variables that start with the incomplete value.147148```python`ParamType` and other typing improvements (#3371)Rowlando13before adoption8a2b489
line 149why, one step back149class EnvVarType(ParamType[str]):Move Setuptools and Shell-completion docs from reST to MyST (#2987)Rowlando13before adoption528fd7a
lines 150–166why, one step back150 name = "envvar"151152 def shell_complete(self, ctx, param, incomplete):153 return [154 CompletionItem(name)155 for name in os.environ if name.startswith(incomplete)156 ]157158@click.command()159@click.option("--ev", type=EnvVarType())160def cli(ev):161 click.echo(os.environ[ev])162```163164## Overriding Value Completion165166Value completions for a parameter can be customized without a custom type by providing a `shell_complete` function. TheShell completion overrides are documented as taking keyword arguments (#2854)Rowlando13before adoption3be1f33
line 167why, one step back167function is used instead of any completion provided by the type. It is passed 3 positional arguments:Move Setuptools and Shell-completion docs from reST to MyST (#2987)Rowlando13before adoption528fd7a
lines 168–275why, one step back168169- `ctx` - The current command context.170- `param` - The current parameter requesting completion.171- `incomplete` - The partial word that is being completed. May be an empty string if no characters have been entered172 yet.173174It must return a list of {class}`CompletionItem` objects, or as a shortcut it can return a list of strings.175176In this example, the command will suggest environment variables that start with the incomplete value.177178```python179def complete_env_vars(ctx, param, incomplete):180 return [k for k in os.environ if k.startswith(incomplete)]181182@click.command()183@click.argument("name", shell_complete=complete_env_vars)184def cli(name):185 click.echo(f"Name: {name}")186 click.echo(f"Value: {os.environ[name]}")187```188189## Adding Support for a Shell190191Support can be added for shells that do not come built in. Be sure to check PyPI to see if there's already a package192that adds support for your shell. This topic is very technical, you'll want to look at Click's source to study the193built-in implementations.194195Shell support is provided by subclasses of {class}`ShellComplete` registered with {func}`add_completion_class`. When196Click is invoked in completion mode, it calls {meth}`~ShellComplete.source` to output the completion script, or197{meth}`~ShellComplete.complete` to output completions. The base class provides default implementations that require198implementing some smaller parts.199200First, you'll need to figure out how your shell's completion system works and write a script to integrate it with Click.201It must invoke your program with the environment variable `_{FOO_BAR}_COMPLETE` set to `{shell}_complete` and pass the202complete args and incomplete value. How it passes those values, and the format of the completion response from Click is203up to you.204205In your subclass, set {attr}`ShellComplete.source_template` to the completion script. The default implementation will206perform `%` formatting with the following variables:207208- `complete_func` - A safe name for the completion function defined in the script.209- `complete_var` - The environment variable name for passing the `{shell}_complete` instruction.210- `foo_bar` - The name of the executable being completed.211212The example code is for a made up shell "My Shell" or "mysh" for short.213214```python215from click.shell_completion import add_completion_class216from click.shell_completion import ShellComplete217218_mysh_source = """\219%(complete_func)s {220 response=$(%(complete_var)s=mysh_complete %(foo_bar)s)221 # parse response and set completions somehow222}223call-on-complete %(foo_bar)s %(complete_func)s224"""225226@add_completion_class227class MyshComplete(ShellComplete):228 name = "mysh"229 source_template = _mysh_source230```231232Next, implement {meth}`~ShellComplete.get_completion_args`. This must get, parse, and return the complete args and233incomplete value from the completion script. For example, for the Bash implementation the `COMP_WORDS` env var contains234the command line args as a string, and the `COMP_CWORD` env var contains the index of the incomplete arg. The method235must return a `(args, incomplete)` tuple.236237```python238import os239from click.parser import split_arg_string240241class MyshComplete(ShellComplete):242 ...243244 def get_completion_args(self):245 args = split_arg_string(os.environ["COMP_WORDS"])246247 if os.environ["COMP_PARTIAL"] == "1":248 incomplete = args.pop()249 return args, incomplete250251 return args, ""252```253254Finally, implement {meth}`~ShellComplete.format_completion`. This is called to format each {class}`CompletionItem` into a string. For example, the Bash implementation returns `f"{item.type},{item.value}` (it doesn't support help strings), and the Zsh implementation returns each part separated by a newline, replacing empty help with a `_` placeholder. This format is entirely up to what you parse with your completion script.255256The `type` value is usually `plain`, but it can be another value that the completion script can switch on. For example,257`file` or `dir` can tell the shell to handle path completion, since the shell is better at that than Click.258259```python260class MyshComplete(ShellComplete):261 ...262263 def format_completion(self, item):264 return f"{item.type}\t{item.value}"265```266267With those three things implemented, the new shell support is ready. In case those weren't sufficient, there are more268parts that can be overridden, but that probably isn't necessary.269270The activation instructions will again depend on how your shell works. Use the following to generate the completion271script, then load it into the shell somehow.272273```console274_FOO_BAR_COMPLETE=mysh_source foo-bar275```