Debian Codegraph @

docs/shell-completion.md

raw
1 (shell-completion)=
2
3 # Shell Completion
4
5 ```{currentmodule} click.shell_completion
6 ```
7
8 Click provides tab completion support for Bash (version 4.4 and up), Zsh, and Fish. It is possible to add support for
9 other shells too, and suggestions can be customized at multiple levels.
10
11 Shell completion suggests command names, option names, and values for choice, file, and path parameter types. Options
12 are only listed if at least a dash has been entered. Hidden commands and options are not shown.
13
14 ```console
15 $ repo <TAB><TAB>
16 clone commit copy delete setuser
17 $ repo clone -<TAB><TAB>
18 --deep --help --rev --shallow -r
19 ```
20
21 ## Enabling Completion
22
23 Completion is only available if a script is installed and invoked through an entry point, not through the `python`
24 command. See {doc}`entry-points`. Once the executable is installed, calling it with a special environment variable will
25 put Click in completion mode.
26
27 To enable shell completion, the user needs to register a special function with their shell. The exact script varies
28 depending on the shell you are using. Click will output it when called with `_{FOO_BAR}_COMPLETE` set to
29 `{shell}_source`. `{FOO_BAR}` is the executable name in uppercase with dashes replaced by underscores. It is
30 conventional but not strictly required for environment variable names to be in upper case. This convention helps
31 distinguish environment variables from regular shell variables and commands, making scripts and configuration files more
32 readable and easier to maintain. The built-in shells are `bash`, `zsh`, and `fish`.
33
34 Provide your users with the following instructions customized to your program name. This uses `foo-bar` as an example.
35
36 ```{eval-rst}
37 .. tabs::
38
39 .. group-tab:: Bash
40
41 Add this to ``~/.bashrc``:
42
43 .. code-block:: bash
44
45 eval "$(_FOO_BAR_COMPLETE=bash_source foo-bar)"
46
47 .. group-tab:: Zsh
48
49 Add this to ``~/.zshrc``:
50
51 .. code-block:: zsh
52
53 eval "$(_FOO_BAR_COMPLETE=zsh_source foo-bar)"
54
55 .. group-tab:: Fish
56
57 Add this to ``~/.config/fish/completions/foo-bar.fish``:
58
59 .. code-block:: fish
60
61 _FOO_BAR_COMPLETE=fish_source foo-bar | source
62
63 This is the same file used for the activation script method
64 below. For Fish it's probably always easier to use that method.
65 ```
66
67 Using `eval` means that the command is invoked and evaluated every time a shell is started, which can delay shell
68 responsiveness. To speed it up, write the generated script to a file, then source that. You can generate the files ahead
69 of time and distribute them with your program to save your users a step.
70
71 ```{eval-rst}
72 .. tabs::
73
74 .. group-tab:: Bash
75
76 Save the script somewhere.
77
78 .. code-block:: bash
79
80 _FOO_BAR_COMPLETE=bash_source foo-bar > ~/.foo-bar-complete.bash
81
82 Source the file in ``~/.bashrc``.
83
84 .. code-block:: bash
85
86 . ~/.foo-bar-complete.bash
87
88 .. group-tab:: Zsh
89
90 Save the script somewhere.
91
92 .. code-block:: bash
93
94 _FOO_BAR_COMPLETE=zsh_source foo-bar > ~/.foo-bar-complete.zsh
95
96 Source the file in ``~/.zshrc``.
97
98 .. code-block:: bash
99
100 . ~/.foo-bar-complete.zsh
101
102 .. group-tab:: Fish
103
104 Save the script to ``~/.config/fish/completions/foo-bar.fish``:
105
106 .. code-block:: fish
107
108 _FOO_BAR_COMPLETE=fish_source foo-bar > ~/.config/fish/completions/foo-bar.fish
109 ```
110
111 After modifying the shell config, you need to start a new shell in order for the changes to be loaded.
112
113 ## Custom Type Completion
114
115 When creating a custom {class}`~click.ParamType`, override its {meth}`~click.ParamType.shell_complete` method to provide
116 shell completion for parameters with the type. The method must return a list of {class}`~CompletionItem` objects.
117 Besides the value, these objects hold metadata that shell support might use. The built-in implementations use `type` to
118 indicate special handling for paths, and `help` for shells that support showing a help string next to a suggestion.
119
120 In this example, the type will suggest environment variables that start with the incomplete value.
121
122 ```python
123 class EnvVarType(ParamType):
124 name = "envvar"
125
126 def shell_complete(self, ctx, param, incomplete):
127 return [
128 CompletionItem(name)
129 for name in os.environ if name.startswith(incomplete)
130 ]
131
132 @click.command()
133 @click.option("--ev", type=EnvVarType())
134 def cli(ev):
135 click.echo(os.environ[ev])
136 ```
137
138 ## Overriding Value Completion
139
140 Value completions for a parameter can be customized without a custom type by providing a `shell_complete` function. The
141 function is used instead of any completion provided by the type. It is passed 3 positional arguments:
142
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 entered
146 yet.
147
148 It must return a list of {class}`CompletionItem` objects, or as a shortcut it can return a list of strings.
149
150 In this example, the command will suggest environment variables that start with the incomplete value.
151
152 ```python
153 def complete_env_vars(ctx, param, incomplete):
154 return [k for k in os.environ if k.startswith(incomplete)]
155
156 @click.command()
157 @click.argument("name", shell_complete=complete_env_vars)
158 def cli(name):
159 click.echo(f"Name: {name}")
160 click.echo(f"Value: {os.environ[name]}")
161 ```
162
163 ## Adding Support for a Shell
164
165 Support can be added for shells that do not come built in. Be sure to check PyPI to see if there's already a package
166 that adds support for your shell. This topic is very technical, you'll want to look at Click's source to study the
167 built-in implementations.
168
169 Shell support is provided by subclasses of {class}`ShellComplete` registered with {func}`add_completion_class`. When
170 Click is invoked in completion mode, it calls {meth}`~ShellComplete.source` to output the completion script, or
171 {meth}`~ShellComplete.complete` to output completions. The base class provides default implementations that require
172 implementing some smaller parts.
173
174 First, you'll need to figure out how your shell's completion system works and write a script to integrate it with Click.
175 It must invoke your program with the environment variable `_{FOO_BAR}_COMPLETE` set to `{shell}_complete` and pass the
176 complete args and incomplete value. How it passes those values, and the format of the completion response from Click is
177 up to you.
178
179 In your subclass, set {attr}`ShellComplete.source_template` to the completion script. The default implementation will
180 perform `%` formatting with the following variables:
181
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.
185
186 The example code is for a made up shell "My Shell" or "mysh" for short.
187
188 ```python
189 from click.shell_completion import add_completion_class
190 from click.shell_completion import ShellComplete
191
192 _mysh_source = """\
193 %(complete_func)s {
194 response=$(%(complete_var)s=mysh_complete %(foo_bar)s)
195 # parse response and set completions somehow
196 }
197 call-on-complete %(foo_bar)s %(complete_func)s
198 """
199
200 @add_completion_class
201 class MyshComplete(ShellComplete):
202 name = "mysh"
203 source_template = _mysh_source
204 ```
205
206 Next, implement {meth}`~ShellComplete.get_completion_args`. This must get, parse, and return the complete args and
207 incomplete value from the completion script. For example, for the Bash implementation the `COMP_WORDS` env var contains
208 the command line args as a string, and the `COMP_CWORD` env var contains the index of the incomplete arg. The method
209 must return a `(args, incomplete)` tuple.
210
211 ```python
212 import os
213 from click.parser import split_arg_string
214
215 class MyshComplete(ShellComplete):
216 ...
217
218 def get_completion_args(self):
219 args = split_arg_string(os.environ["COMP_WORDS"])
220
221 if os.environ["COMP_PARTIAL"] == "1":
222 incomplete = args.pop()
223 return args, incomplete
224
225 return args, ""
226 ```
227
228 Finally, 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.
229
230 The `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.
232
233 ```python
234 class MyshComplete(ShellComplete):
235 ...
236
237 def format_completion(self, item):
238 return f"{item.type}\t{item.value}"
239 ```
240
241 With those three things implemented, the new shell support is ready. In case those weren't sufficient, there are more
242 parts that can be overridden, but that probably isn't necessary.
243
244 The activation instructions will again depend on how your shell works. Use the following to generate the completion
245 script, then load it into the shell somehow.
246
247 ```console
248 _FOO_BAR_COMPLETE=mysh_source foo-bar
249 ```