Skip to content
Myr

shell-completion.md

This file

Path

docs/shell-completion.md

249 lines · 9.2 KiB · Markdown

Last changed by

Merge branch 'rstTomyst' of https://github.com/denuoweb/click into rstTomystdenuowebbefore adoptionbb11331

History of this file

Take it

convert from reST to MySTdenuowebbefore adoptionb3a608e

line 1why, one step back
1(shell-completion)=

change extension to .mddenuowebbefore adoption1838a0b

line 2why, one step back
2

convert from reST to MySTdenuowebbefore adoptionb3a608e

line 3why, one step back
3# Shell Completion

change extension to .mddenuowebbefore adoption1838a0b

line 4why, one step back
4

convert from reST to MySTdenuowebbefore adoptionb3a608e

lines 5–6why, one step back
5```{currentmodule} click.shell_completion
6```

change extension to .mddenuowebbefore adoption1838a0b

line 7why, one step back
7

convert from reST to MySTdenuowebbefore adoptionb3a608e

lines 8–9why, one step back
8Click provides tab completion support for Bash (version 4.4 and up), Zsh, and Fish. It is possible to add support for
9other shells too, and suggestions can be customized at multiple levels.

change extension to .mddenuowebbefore adoption1838a0b

line 10why, one step back
10

convert from reST to MySTdenuowebbefore adoptionb3a608e

lines 11–12why, one step back
11Shell completion suggests command names, option names, and values for choice, file, and path parameter types. Options
12are only listed if at least a dash has been entered. Hidden commands and options are not shown.

change extension to .mddenuowebbefore adoption1838a0b

line 13why, one step back
13

convert from reST to MySTdenuowebbefore adoptionb3a608e

lines 14–19why, one step back
14```console
15$ repo <TAB><TAB>16clone commit copy delete setuser17$ repo clone -<TAB><TAB>18--deep --help --rev --shallow -r19```

change extension to .mddenuowebbefore adoption1838a0b

line 20why, one step back
20

convert from reST to MySTdenuowebbefore adoptionb3a608e

line 21why, one step back
21## Enabling Completion

change extension to .mddenuowebbefore adoption1838a0b

line 22why, one step back
22

convert from reST to MySTdenuowebbefore adoptionb3a608e

lines 23–25why, one step back
23Completion 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.

change extension to .mddenuowebbefore adoption1838a0b

line 26why, one step back
26

convert from reST to MySTdenuowebbefore adoptionb3a608e

lines 27–32why, one step back
27To enable shell completion, the user needs to register a special function with their shell. The exact script varies
28depending 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 more32readable and easier to maintain. The built-in shells are `bash`, `zsh`, and `fish`.

change extension to .mddenuowebbefore adoption1838a0b

line 33why, one step back
33

convert from reST to MySTdenuowebbefore adoptionb3a608e

line 34why, one step back
34Provide your users with the following instructions customized to your program name. This uses `foo-bar` as an example.

change extension to .mddenuowebbefore adoption1838a0b

line 35why, one step back
35

convert from reST to MySTdenuowebbefore adoptionb3a608e

line 36why, one step back
36```{eval-rst}

change extension to .mddenuowebbefore adoption1838a0b

lines 37–64why, one step back
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.

convert from reST to MySTdenuowebbefore adoptionb3a608e

line 65why, one step back
65```

change extension to .mddenuowebbefore adoption1838a0b

line 66why, one step back
66

convert from reST to MySTdenuowebbefore adoptionb3a608e

lines 67–69why, one step back
67Using `eval` means that the command is invoked and evaluated every time a shell is started, which can delay shell
68responsiveness. To speed it up, write the generated script to a file, then source that. You can generate the files ahead69of time and distribute them with your program to save your users a step.

change extension to .mddenuowebbefore adoption1838a0b

line 70why, one step back
70

convert from reST to MySTdenuowebbefore adoptionb3a608e

line 71why, one step back
71```{eval-rst}

change extension to .mddenuowebbefore adoption1838a0b

lines 72–108why, one step back
72.. tabs::
7374 .. group-tab:: Bash7576 Save the script somewhere.7778 .. code-block:: bash7980 _FOO_BAR_COMPLETE=bash_source foo-bar > ~/.foo-bar-complete.bash8182 Source the file in ``~/.bashrc``.8384 .. code-block:: bash8586 . ~/.foo-bar-complete.bash8788 .. group-tab:: Zsh8990 Save the script somewhere.9192 .. code-block:: bash9394 _FOO_BAR_COMPLETE=zsh_source foo-bar > ~/.foo-bar-complete.zsh9596 Source the file in ``~/.zshrc``.9798 .. code-block:: bash99100 . ~/.foo-bar-complete.zsh101102 .. group-tab:: Fish103104 Save the script to ``~/.config/fish/completions/foo-bar.fish``:105106 .. code-block:: fish107108 _FOO_BAR_COMPLETE=fish_source foo-bar > ~/.config/fish/completions/foo-bar.fish

convert from reST to MySTdenuowebbefore adoptionb3a608e

line 109why, one step back
109```

change extension to .mddenuowebbefore adoption1838a0b

line 110why, one step back
110

convert from reST to MySTdenuowebbefore adoptionb3a608e

line 111why, one step back
111After modifying the shell config, you need to start a new shell in order for the changes to be loaded.

change extension to .mddenuowebbefore adoption1838a0b

line 112why, one step back
112

convert from reST to MySTdenuowebbefore adoptionb3a608e

line 113why, one step back
113## Custom Type Completion

change extension to .mddenuowebbefore adoption1838a0b

line 114why, one step back
114

convert from reST to MySTdenuowebbefore adoptionb3a608e

lines 115–118why, one step back
115When creating a custom {class}`~click.ParamType`, override its {meth}`~click.ParamType.shell_complete` method to provide
116shell completion for parameters with the type. The method must return a list of {class}`~CompletionItem` objects.117Besides the value, these objects hold metadata that shell support might use. The built-in implementations use `type` to118indicate special handling for paths, and `help` for shells that support showing a help string next to a suggestion.

change extension to .mddenuowebbefore adoption1838a0b

line 119why, one step back
119

convert from reST to MySTdenuowebbefore adoptionb3a608e

line 120why, one step back
120In this example, the type will suggest environment variables that start with the incomplete value.

change extension to .mddenuowebbefore adoption1838a0b

line 121why, one step back
121

convert from reST to MySTdenuowebbefore adoptionb3a608e

lines 122–124why, one step back
122```python
123class EnvVarType(ParamType):124 name = "envvar"

change extension to .mddenuowebbefore adoption1838a0b

line 125why, one step back
125

convert from reST to MySTdenuowebbefore adoptionb3a608e

lines 126–130why, one step back
126 def shell_complete(self, ctx, param, incomplete):
127 return [128 CompletionItem(name)129 for name in os.environ if name.startswith(incomplete)130 ]

change extension to .mddenuowebbefore adoption1838a0b

line 131why, one step back
131

convert from reST to MySTdenuowebbefore adoptionb3a608e

lines 132–136why, one step back
132@click.command()
133@click.option("--ev", type=EnvVarType())134def cli(ev):135 click.echo(os.environ[ev])136```

change extension to .mddenuowebbefore adoption1838a0b

line 137why, one step back
137

convert from reST to MySTdenuowebbefore adoptionb3a608e

line 138why, one step back
138## Overriding Value Completion

change extension to .mddenuowebbefore adoption1838a0b

line 139why, one step back
139

convert from reST to MySTdenuowebbefore adoptionb3a608e

line 140why, one step back
140Value completions for a parameter can be customized without a custom type by providing a `shell_complete` function. The

Merge branch 'rstTomyst' of https://github.com/denuoweb/click into rstTomystdenuowebbefore adoptionbb11331

line 141why, one step back
141function is used instead of any completion provided by the type. It is passed 3 positional arguments:

change extension to .mddenuowebbefore adoption1838a0b

line 142why, one step back
142

convert from reST to MySTdenuowebbefore adoptionb3a608e

lines 143–146why, one step back
143- `ctx` - The current command context.
144- `param` - The current parameter requesting completion.145- `incomplete` - The partial word that is being completed. May be an empty string if no characters have been entered146 yet.

change extension to .mddenuowebbefore adoption1838a0b

line 147why, one step back
147

convert from reST to MySTdenuowebbefore adoptionb3a608e

line 148why, one step back
148It must return a list of {class}`CompletionItem` objects, or as a shortcut it can return a list of strings.

change extension to .mddenuowebbefore adoption1838a0b

line 149why, one step back
149

convert from reST to MySTdenuowebbefore adoptionb3a608e

line 150why, one step back
150In this example, the command will suggest environment variables that start with the incomplete value.

change extension to .mddenuowebbefore adoption1838a0b

line 151why, one step back
151

convert from reST to MySTdenuowebbefore adoptionb3a608e

lines 152–154why, one step back
152```python
153def complete_env_vars(ctx, param, incomplete):154 return [k for k in os.environ if k.startswith(incomplete)]

change extension to .mddenuowebbefore adoption1838a0b

line 155why, one step back
155

convert from reST to MySTdenuowebbefore adoptionb3a608e

lines 156–161why, one step back
156@click.command()
157@click.argument("name", shell_complete=complete_env_vars)158def cli(name):159 click.echo(f"Name: {name}")160 click.echo(f"Value: {os.environ[name]}")161```

change extension to .mddenuowebbefore adoption1838a0b

line 162why, one step back
162

convert from reST to MySTdenuowebbefore adoptionb3a608e

line 163why, one step back
163## Adding Support for a Shell

change extension to .mddenuowebbefore adoption1838a0b

line 164why, one step back
164

convert from reST to MySTdenuowebbefore adoptionb3a608e

lines 165–167why, one step back
165Support can be added for shells that do not come built in. Be sure to check PyPI to see if there's already a package
166that adds support for your shell. This topic is very technical, you'll want to look at Click's source to study the167built-in implementations.

change extension to .mddenuowebbefore adoption1838a0b

line 168why, one step back
168

convert from reST to MySTdenuowebbefore adoptionb3a608e

lines 169–172why, one step back
169Shell support is provided by subclasses of {class}`ShellComplete` registered with {func}`add_completion_class`. When
170Click is invoked in completion mode, it calls {meth}`~ShellComplete.source` to output the completion script, or171{meth}`~ShellComplete.complete` to output completions. The base class provides default implementations that require172implementing some smaller parts.

change extension to .mddenuowebbefore adoption1838a0b

line 173why, one step back
173

convert from reST to MySTdenuowebbefore adoptionb3a608e

lines 174–177why, one step back
174First, you'll need to figure out how your shell's completion system works and write a script to integrate it with Click.
175It must invoke your program with the environment variable `_{FOO_BAR}_COMPLETE` set to `{shell}_complete` and pass the176complete args and incomplete value. How it passes those values, and the format of the completion response from Click is177up to you.

change extension to .mddenuowebbefore adoption1838a0b

line 178why, one step back
178

convert from reST to MySTdenuowebbefore adoptionb3a608e

lines 179–180why, one step back
179In your subclass, set {attr}`ShellComplete.source_template` to the completion script. The default implementation will
180perform `%` formatting with the following variables:

change extension to .mddenuowebbefore adoption1838a0b

line 181why, one step back
181

convert from reST to MySTdenuowebbefore adoptionb3a608e

lines 182–184why, one step back
182- `complete_func` - A safe name for the completion function defined in the script.
183- `complete_var` - The environment variable name for passing the `{shell}_complete` instruction.184- `foo_bar` - The name of the executable being completed.

change extension to .mddenuowebbefore adoption1838a0b

lines 185–187why, one step back
185
186The example code is for a made up shell "My Shell" or "mysh" for short.187

convert from reST to MySTdenuowebbefore adoptionb3a608e

lines 188–190why, one step back
188```python
189from click.shell_completion import add_completion_class190from click.shell_completion import ShellComplete

change extension to .mddenuowebbefore adoption1838a0b

line 191why, one step back
191

convert from reST to MySTdenuowebbefore adoptionb3a608e

lines 192–198why, one step back
192_mysh_source = """\
193%(complete_func)s {194 response=$(%(complete_var)s=mysh_complete %(foo_bar)s)195 # parse response and set completions somehow196}197call-on-complete %(foo_bar)s %(complete_func)s198"""

change extension to .mddenuowebbefore adoption1838a0b

line 199why, one step back
199

convert from reST to MySTdenuowebbefore adoptionb3a608e

lines 200–204why, one step back
200@add_completion_class
201class MyshComplete(ShellComplete):202 name = "mysh"203 source_template = _mysh_source204```

change extension to .mddenuowebbefore adoption1838a0b

line 205why, one step back
205

convert from reST to MySTdenuowebbefore adoptionb3a608e

lines 206–209why, one step back
206Next, implement {meth}`~ShellComplete.get_completion_args`. This must get, parse, and return the complete args and
207incomplete value from the completion script. For example, for the Bash implementation the `COMP_WORDS` env var contains208the command line args as a string, and the `COMP_CWORD` env var contains the index of the incomplete arg. The method209must return a `(args, incomplete)` tuple.

change extension to .mddenuowebbefore adoption1838a0b

line 210why, one step back
210

convert from reST to MySTdenuowebbefore adoptionb3a608e

lines 211–213why, one step back
211```python
212import os213from click.parser import split_arg_string

change extension to .mddenuowebbefore adoption1838a0b

line 214why, one step back
214

convert from reST to MySTdenuowebbefore adoptionb3a608e

lines 215–216why, one step back
215class MyshComplete(ShellComplete):
216 ...

change extension to .mddenuowebbefore adoption1838a0b

line 217why, one step back
217

convert from reST to MySTdenuowebbefore adoptionb3a608e

lines 218–219why, one step back
218 def get_completion_args(self):
219 args = split_arg_string(os.environ["COMP_WORDS"])

change extension to .mddenuowebbefore adoption1838a0b

line 220why, one step back
220

convert from reST to MySTdenuowebbefore adoptionb3a608e

lines 221–223why, one step back
221 if os.environ["COMP_PARTIAL"] == "1":
222 incomplete = args.pop()223 return args, incomplete

change extension to .mddenuowebbefore adoption1838a0b

line 224why, one step back
224

convert from reST to MySTdenuowebbefore adoptionb3a608e

lines 225–226why, one step back
225 return args, ""
226```

change extension to .mddenuowebbefore adoption1838a0b

line 227why, one step back
227

convert from reST to MySTdenuowebbefore adoptionb3a608e

line 228why, one step back
228Finally, 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.

change extension to .mddenuowebbefore adoption1838a0b

line 229why, one step back
229

convert from reST to MySTdenuowebbefore adoptionb3a608e

lines 230–231why, one step back
230The `type` value is usually `plain`, but it can be another value that the completion script can switch on. For example,
231`file` or `dir` can tell the shell to handle path completion, since the shell is better at that than Click.

change extension to .mddenuowebbefore adoption1838a0b

line 232why, one step back
232

convert from reST to MySTdenuowebbefore adoptionb3a608e

lines 233–235why, one step back
233```python
234class MyshComplete(ShellComplete):235 ...

change extension to .mddenuowebbefore adoption1838a0b

line 236why, one step back
236

convert from reST to MySTdenuowebbefore adoptionb3a608e

lines 237–239why, one step back
237 def format_completion(self, item):
238 return f"{item.type}\t{item.value}"239```

change extension to .mddenuowebbefore adoption1838a0b

line 240why, one step back
240

convert from reST to MySTdenuowebbefore adoptionb3a608e

lines 241–242why, one step back
241With those three things implemented, the new shell support is ready. In case those weren't sufficient, there are more
242parts that can be overridden, but that probably isn't necessary.

change extension to .mddenuowebbefore adoption1838a0b

line 243why, one step back
243

convert from reST to MySTdenuowebbefore adoptionb3a608e

lines 244–245why, one step back
244The activation instructions will again depend on how your shell works. Use the following to generate the completion
245script, then load it into the shell somehow.

change extension to .mddenuowebbefore adoption1838a0b

line 246why, one step back
246

convert from reST to MySTdenuowebbefore adoptionb3a608e

lines 247–249why, one step back
247```console
248_FOO_BAR_COMPLETE=mysh_source foo-bar249```