Debian Codegraph @

site/content/completions/_index.md

raw
1 # Generating shell completions
2
3 Cobra can generate shell completions for multiple shells.
4 The currently supported shells are:
5 - Bash
6 - Zsh
7 - fish
8 - PowerShell
9
10 Cobra will automatically provide your program with a fully functional `completion` command,
11 similarly to how it provides the `help` command. If there are no other subcommands, the
12 default `completion` command will be hidden, but still functional.
13
14 ## Creating your own completion command
15
16 If you do not wish to use the default `completion` command, you can choose to
17 provide your own, which will take precedence over the default one. (This also provides
18 backwards-compatibility with programs that already have their own `completion` command.)
19
20 If you are using the `cobra-cli` generator,
21 which can be found at [spf13/cobra-cli](https://github.com/spf13/cobra-cli),
22 you can create a completion command by running
23
24 ```bash
25 cobra-cli add completion
26 ```
27 and then modifying the generated `cmd/completion.go` file to look something like this
28 (writing the shell script to stdout allows the most flexible use):
29
30 ```go
31 var completionCmd = &cobra.Command{
32 Use: "completion [bash|zsh|fish|powershell]",
33 Short: "Generate completion script",
34 Long: fmt.Sprintf(`To load completions:
35
36 Bash:
37
38 $ source <(%[1]s completion bash)
39
40 # To load completions for each session, execute once:
41 # Linux:
42 $ %[1]s completion bash > /etc/bash_completion.d/%[1]s
43 # macOS:
44 $ %[1]s completion bash > $(brew --prefix)/etc/bash_completion.d/%[1]s
45
46 Zsh:
47
48 # If shell completion is not already enabled in your environment,
49 # you will need to enable it. You can execute the following once:
50
51 $ echo "autoload -U compinit; compinit" >> ~/.zshrc
52
53 # To load completions for each session, execute once:
54 $ %[1]s completion zsh > "${fpath[1]}/_%[1]s"
55
56 # You will need to start a new shell for this setup to take effect.
57
58 fish:
59
60 $ %[1]s completion fish | source
61
62 # To load completions for each session, execute once:
63 $ %[1]s completion fish > ~/.config/fish/completions/%[1]s.fish
64
65 PowerShell:
66
67 PS> %[1]s completion powershell | Out-String | Invoke-Expression
68
69 # To load completions for every new session, run:
70 PS> %[1]s completion powershell > %[1]s.ps1
71 # and source this file from your PowerShell profile.
72 `,cmd.Root().Name()),
73 DisableFlagsInUseLine: true,
74 ValidArgs: []string{"bash", "zsh", "fish", "powershell"},
75 Args: cobra.MatchAll(cobra.ExactArgs(1), cobra.OnlyValidArgs),
76 Run: func(cmd *cobra.Command, args []string) {
77 switch args[0] {
78 case "bash":
79 cmd.Root().GenBashCompletion(os.Stdout)
80 case "zsh":
81 cmd.Root().GenZshCompletion(os.Stdout)
82 case "fish":
83 cmd.Root().GenFishCompletion(os.Stdout, true)
84 case "powershell":
85 cmd.Root().GenPowerShellCompletionWithDesc(os.Stdout)
86 }
87 },
88 }
89 ```
90
91 **Note:** The cobra generator may include messages printed to stdout, for example, if the config file is loaded; this will break the auto-completion script so must be removed.
92
93 ## Adapting the default completion command
94
95 Cobra provides a few options for the default `completion` command. To configure such options you must set
96 the `CompletionOptions` field on the *root* command.
97
98 To tell Cobra *not* to provide the default `completion` command:
99 ```
100 rootCmd.CompletionOptions.DisableDefaultCmd = true
101 ```
102
103 To tell Cobra to mark the default `completion` command as *hidden*:
104 ```
105 rootCmd.CompletionOptions.HiddenDefaultCmd = true
106 ```
107
108 To tell Cobra *not* to provide the user with the `--no-descriptions` flag to the completion sub-commands:
109 ```
110 rootCmd.CompletionOptions.DisableNoDescFlag = true
111 ```
112
113 To tell Cobra to completely disable descriptions for completions:
114 ```
115 rootCmd.CompletionOptions.DisableDescriptions = true
116 ```
117
118 # Customizing completions
119
120 The generated completion scripts will automatically handle completing commands and flags. However, you can make your completions much more powerful by providing information to complete your program's nouns and flag values.
121
122 ## Completion of nouns
123
124 ### Static completion of nouns
125
126 Cobra allows you to provide a pre-defined list of completion choices for your nouns using the `ValidArgs` field.
127 For example, if you want `kubectl get [tab][tab]` to show a list of valid "nouns" you have to set them.
128 Some simplified code from `kubectl get` looks like:
129
130 ```go
131 validArgs = []string{ "pod", "node", "service", "replicationcontroller" }
132
133 cmd := &cobra.Command{
134 Use: "get [(-o|--output=)json|yaml|template|...] (RESOURCE [NAME] | RESOURCE/NAME ...)",
135 Short: "Display one or many resources",
136 Long: get_long,
137 Example: get_example,
138 Run: func(cmd *cobra.Command, args []string) {
139 cobra.CheckErr(RunGet(f, out, cmd, args))
140 },
141 ValidArgs: validArgs,
142 }
143 ```
144
145 Notice we put the `ValidArgs` field on the `get` sub-command. Doing so will give results like:
146
147 ```bash
148 $ kubectl get [tab][tab]
149 node pod replicationcontroller service
150 ```
151
152 #### Aliases for nouns
153
154 If your nouns have aliases, you can define them alongside `ValidArgs` using `ArgAliases`:
155
156 ```go
157 argAliases = []string { "pods", "nodes", "services", "svc", "replicationcontrollers", "rc" }
158
159 cmd := &cobra.Command{
160 ...
161 ValidArgs: validArgs,
162 ArgAliases: argAliases
163 }
164 ```
165
166 The aliases are shown to the user on tab completion only if no completions were found within sub-commands or `ValidArgs`.
167
168 ### Dynamic completion of nouns
169
170 In some cases it is not possible to provide a list of completions in advance. Instead, the list of completions must be determined at execution-time. In a similar fashion as for static completions, you can use the `ValidArgsFunction` field to provide a Go function that Cobra will execute when it needs the list of completion choices for the nouns of a command. Note that either `ValidArgs` or `ValidArgsFunction` can be used for a single cobra command, but not both.
171 Simplified code from `helm status` looks like:
172
173 ```go
174 cmd := &cobra.Command{
175 Use: "status RELEASE_NAME",
176 Short: "Display the status of the named release",
177 Long: status_long,
178 RunE: func(cmd *cobra.Command, args []string) {
179 RunGet(args[0])
180 },
181 ValidArgsFunction: func(cmd *cobra.Command, args []string, toComplete string) ([]cobra.Completion, cobra.ShellCompDirective) {
182 if len(args) != 0 {
183 return nil, cobra.ShellCompDirectiveNoFileComp
184 }
185 return getReleasesFromCluster(toComplete), cobra.ShellCompDirectiveNoFileComp
186 },
187 }
188 ```
189 Where `getReleasesFromCluster()` is a Go function that obtains the list of current Helm releases running on the Kubernetes cluster.
190 Notice we put the `ValidArgsFunction` on the `status` sub-command. Let's assume the Helm releases on the cluster are: `harbor`, `notary`, `rook` and `thanos` then this dynamic completion will give results like:
191
192 ```bash
193 $ helm status [tab][tab]
194 harbor notary rook thanos
195 ```
196 You may have noticed the use of `cobra.ShellCompDirective`. These directives are bit fields allowing to control some shell completion behaviors for your particular completion. You can combine them with the bit-or operator such as `cobra.ShellCompDirectiveNoSpace | cobra.ShellCompDirectiveNoFileComp`
197 ```go
198 // Indicates that the shell will perform its default behavior after completions
199 // have been provided (this implies none of the other directives).
200 ShellCompDirectiveDefault
201
202 // Indicates an error occurred and completions should be ignored.
203 ShellCompDirectiveError
204
205 // Indicates that the shell should not add a space after the completion,
206 // even if there is a single completion provided.
207 ShellCompDirectiveNoSpace
208
209 // Indicates that the shell should not provide file completion even when
210 // no completion is provided.
211 ShellCompDirectiveNoFileComp
212
213 // Indicates that the returned completions should be used as file extension filters.
214 // For example, to complete only files of the form *.json or *.yaml:
215 // return []cobra.Completion{"yaml", "json"}, cobra.ShellCompDirectiveFilterFileExt
216 // For flags, using MarkFlagFilename() and MarkPersistentFlagFilename()
217 // is a shortcut to using this directive explicitly.
218 //
219 ShellCompDirectiveFilterFileExt
220
221 // Indicates that only directory names should be provided in file completion.
222 // For example:
223 // return nil, cobra.ShellCompDirectiveFilterDirs
224 // For flags, using MarkFlagDirname() is a shortcut to using this directive explicitly.
225 //
226 // To request directory names within another directory, the returned completions
227 // should specify a single directory name within which to search. For example,
228 // to complete directories within "themes/":
229 // return []cobra.Completion{"themes"}, cobra.ShellCompDirectiveFilterDirs
230 //
231 ShellCompDirectiveFilterDirs
232
233 // ShellCompDirectiveKeepOrder indicates that the shell should preserve the order
234 // in which the completions are provided
235 ShellCompDirectiveKeepOrder
236 ```
237
238 ***Note***: When using the `ValidArgsFunction`, Cobra will call your registered function after having parsed all flags and arguments provided in the command-line. You therefore don't need to do this parsing yourself. For example, when a user calls `helm status --namespace my-rook-ns [tab][tab]`, Cobra will call your registered `ValidArgsFunction` after having parsed the `--namespace` flag, as it would have done when calling the `RunE` function.
239
240 #### Debugging
241
242 Cobra achieves dynamic completion through the use of a hidden command called by the completion script. To debug your Go completion code, you can call this hidden command directly:
243 ```bash
244 $ helm __complete status har<ENTER>
245 harbor
246 :4
247 Completion ended with directive: ShellCompDirectiveNoFileComp # This is on stderr
248 ```
249 ***Important:*** If the noun to complete is empty (when the user has not yet typed any letters of that noun), you must pass an empty parameter to the `__complete` command:
250 ```bash
251 $ helm __complete status ""<ENTER>
252 harbor
253 notary
254 rook
255 thanos
256 :4
257 Completion ended with directive: ShellCompDirectiveNoFileComp # This is on stderr
258 ```
259 Calling the `__complete` command directly allows you to run the Go debugger to troubleshoot your code. You can also add printouts to your code; Cobra provides the following functions to use for printouts in Go completion code:
260 ```go
261 // Prints to the completion script debug file (if BASH_COMP_DEBUG_FILE
262 // is set to a file path) and optionally prints to stderr.
263 cobra.CompDebug(msg string, printToStdErr bool)
264 cobra.CompDebugln(msg string, printToStdErr bool)
265
266 // Prints to the completion script debug file (if BASH_COMP_DEBUG_FILE
267 // is set to a file path) and to stderr.
268 cobra.CompError(msg string)
269 cobra.CompErrorln(msg string)
270 ```
271 ***Important:*** You should **not** leave traces that print directly to stdout in your completion code as they will be interpreted as completion choices by the completion script. Instead, use the cobra-provided debugging traces functions mentioned above.
272
273 ## Completions for flags
274
275 ### Mark flags as required
276
277 Most of the time completions will only show sub-commands. But if a flag is required to make a sub-command work, you probably want it to show up when the user types [tab][tab]. You can mark a flag as 'Required' like so:
278
279 ```go
280 cmd.MarkFlagRequired("pod")
281 cmd.MarkFlagRequired("container")
282 ```
283
284 and you'll get something like
285
286 ```bash
287 $ kubectl exec [tab][tab]
288 -c --container= -p --pod=
289 ```
290
291 ### Specify dynamic flag completion
292
293 As for nouns, Cobra provides a way of defining dynamic completion of flags. To provide a Go function that Cobra will execute when it needs the list of completion choices for a flag, you must register the function using the `command.RegisterFlagCompletionFunc()` function.
294
295 ```go
296 flagName := "output"
297 cmd.RegisterFlagCompletionFunc(flagName, func(cmd *cobra.Command, args []string, toComplete string) ([]cobra.Completion, cobra.ShellCompDirective) {
298 return []cobra.Completion{"json", "table", "yaml"}, cobra.ShellCompDirectiveDefault
299 })
300 ```
301 Notice that calling `RegisterFlagCompletionFunc()` is done through the `command` with which the flag is associated. In our example this dynamic completion will give results like so:
302
303 ```bash
304 $ helm status --output [tab][tab]
305 json table yaml
306 ```
307
308 #### Change the default ShellCompDirective
309
310 When no completion function is registered for a leaf command or for a flag, Cobra will
311 automatically use `ShellCompDirectiveDefault`, which will invoke the shell's filename completion.
312 This implies that when file completion does not apply to a leaf command or to a flag (the command
313 or flag does not operate on a filename), turning off file completion requires you to register a
314 completion function for that command/flag.
315 For example:
316
317 ```go
318 cmd.RegisterFlagCompletionFunc("flag-name", cobra.NoFileCompletions)
319 ```
320
321 If you find that there are more situations where file completion should be turned off than
322 when it is applicable, you can recursively change the default `ShellCompDirective` for a command
323 and its subcommands to `ShellCompDirectiveNoFileComp`:
324
325 ```go
326 cmd.CompletionOptions.SetDefaultShellCompDirective(ShellCompDirectiveNoFileComp)
327 ```
328
329 If doing so, keep in mind that you should instead register a completion function for leaf commands or
330 flags where file completion is applicable. For example:
331
332 ```go
333 cmd.RegisterFlagCompletionFunc("flag-name", cobra.FixedCompletions(nil, ShellCompDirectiveDefault))
334 ```
335
336 To change the default directive for the entire program, set the DefaultShellCompDirective on the root command.
337
338 #### Debugging
339
340 You can also easily debug your Go completion code for flags:
341 ```bash
342 $ helm __complete status --output ""
343 json
344 table
345 yaml
346 :4
347 Completion ended with directive: ShellCompDirectiveNoFileComp # This is on stderr
348 ```
349 ***Important:*** You should **not** leave traces that print to stdout in your completion code as they will be interpreted as completion choices by the completion script. Instead, use the cobra-provided debugging traces functions mentioned further above.
350
351 ### Specify valid filename extensions for flags that take a filename
352
353 To limit completions of flag values to file names with certain extensions you can either use the different `MarkFlagFilename()` functions or a combination of `RegisterFlagCompletionFunc()` and `ShellCompDirectiveFilterFileExt`, like so:
354 ```go
355 flagName := "output"
356 cmd.MarkFlagFilename(flagName, "yaml", "json")
357 ```
358 or
359 ```go
360 flagName := "output"
361 cmd.RegisterFlagCompletionFunc(flagName, func(cmd *cobra.Command, args []string, toComplete string) ([]cobra.Completion, cobra.ShellCompDirective) {
362 return []cobra.Completion{"yaml", "json"}, cobra.ShellCompDirectiveFilterFileExt})
363 ```
364
365 ### Limit flag completions to directory names
366
367 To limit completions of flag values to directory names you can either use the `MarkFlagDirname()` functions or a combination of `RegisterFlagCompletionFunc()` and `ShellCompDirectiveFilterDirs`, like so:
368 ```go
369 flagName := "output"
370 cmd.MarkFlagDirname(flagName)
371 ```
372 or
373 ```go
374 flagName := "output"
375 cmd.RegisterFlagCompletionFunc(flagName, func(cmd *cobra.Command, args []string, toComplete string) ([]cobra.Completion, cobra.ShellCompDirective) {
376 return nil, cobra.ShellCompDirectiveFilterDirs
377 })
378 ```
379 To limit completions of flag values to directory names *within another directory* you can use a combination of `RegisterFlagCompletionFunc()` and `ShellCompDirectiveFilterDirs` like so:
380 ```go
381 flagName := "output"
382 cmd.RegisterFlagCompletionFunc(flagName, func(cmd *cobra.Command, args []string, toComplete string) ([]cobra.Completion, cobra.ShellCompDirective) {
383 return []cobra.Completion{"themes"}, cobra.ShellCompDirectiveFilterDirs
384 })
385 ```
386 ### Descriptions for completions
387
388 Cobra provides support for completion descriptions. Such descriptions are supported for each shell
389 (however, for bash, it is only available in the [completion V2 version](#bash-completion-v2)).
390 For commands and flags, Cobra will provide the descriptions automatically, based on usage information.
391 For example, using zsh:
392 ```
393 $ helm s[tab]
394 search -- search for a keyword in charts
395 show -- show information of a chart
396 status -- displays the status of the named release
397 ```
398 while using fish:
399 ```
400 $ helm s[tab]
401 search (search for a keyword in charts) show (show information of a chart) status (displays the status of the named release)
402 ```
403
404 Cobra allows you to add descriptions to your own completions. Simply add the description text after each completion, following a `\t` separator. Cobra provides the helper function `CompletionWithDesc(string, string)` to create a completion with a description. This technique applies to completions returned by `ValidArgs`, `ValidArgsFunction` and `RegisterFlagCompletionFunc()`. For example:
405 ```go
406 ValidArgsFunction: func(cmd *cobra.Command, args []string, toComplete string) ([]cobra.Completion, cobra.ShellCompDirective) {
407 return []cobra.Completion{
408 cobra.CompletionWithDesc("harbor", "An image registry"),
409 cobra.CompletionWithDesc("thanos", "Long-term metrics")
410 }, cobra.ShellCompDirectiveNoFileComp
411 }}
412 ```
413 or
414 ```go
415 ValidArgs: []cobra.Completion{
416 cobra.CompletionWithDesc("bash", "Completions for bash"),
417 cobra.CompletionWithDesc("zsh", "Completions for zsh")
418 }
419 ```
420
421 If you don't want to show descriptions in the completions, you can add `--no-descriptions` to the default `completion` command to disable them, like:
422
423 ```bash
424 $ source <(helm completion bash)
425 $ helm completion [tab][tab]
426 bash (generate autocompletion script for bash) powershell (generate autocompletion script for powershell)
427 fish (generate autocompletion script for fish) zsh (generate autocompletion script for zsh)
428
429 $ source <(helm completion bash --no-descriptions)
430 $ helm completion [tab][tab]
431 bash fish powershell zsh
432 ```
433
434 Setting the `<PROGRAM>_COMPLETION_DESCRIPTIONS` environment variable (falling back to `COBRA_COMPLETION_DESCRIPTIONS` if empty or not set) to a [falsey value](https://pkg.go.dev/strconv#ParseBool) achieves the same. `<PROGRAM>` is the name of your program with all non-ASCII-alphanumeric characters replaced by `_`.
435
436 ## Bash completions
437
438 ### Dependencies
439
440 The bash completion script generated by Cobra requires the `bash_completion` package. You should update the help text of your completion command to show how to install the `bash_completion` package ([Kubectl docs](https://kubernetes.io/docs/tasks/tools/install-kubectl/#enabling-shell-autocompletion))
441
442 ### Aliases
443
444 You can also configure `bash` aliases for your program and they will also support completions.
445
446 ```bash
447 alias aliasname=origcommand
448 complete -o default -F __start_origcommand aliasname
449
450 # and now when you run `aliasname` completion will make
451 # suggestions as it did for `origcommand`.
452
453 $ aliasname <tab><tab>
454 completion firstcommand secondcommand
455 ```
456 ### Bash legacy dynamic completions
457
458 For backward compatibility, Cobra still supports its bash legacy dynamic completion solution.
459 Please refer to [Bash Completions](bash.md) for details.
460
461 ### Bash completion V2
462
463 Cobra provides two versions for bash completion. The original bash completion (which started it all!) can be used by calling
464 `GenBashCompletion()` or `GenBashCompletionFile()`.
465
466 A new V2 bash completion version is also available. This version can be used by calling `GenBashCompletionV2()` or
467 `GenBashCompletionFileV2()`. The V2 version does **not** support the legacy dynamic completion
468 (see [Bash Completions](bash.md)) but instead works only with the Go dynamic completion
469 solution described in this document.
470 Unless your program already uses the legacy dynamic completion solution, it is recommended that you use the bash
471 completion V2 solution which provides the following extra features:
472 - Supports completion descriptions (like the other shells)
473 - Small completion script of less than 300 lines (v1 generates scripts of thousands of lines; `kubectl` for example has a bash v1 completion script of over 13K lines)
474 - Streamlined user experience thanks to a completion behavior aligned with the other shells
475
476 `Bash` completion V2 supports descriptions for completions. When calling `GenBashCompletionV2()` or `GenBashCompletionFileV2()`
477 you must provide these functions with a parameter indicating if the completions should be annotated with a description; Cobra
478 will provide the description automatically based on usage information. You can choose to make this option configurable by
479 your users.
480
481 ```
482 # With descriptions
483 $ helm s[tab][tab]
484 search (search for a keyword in charts) status (display the status of the named release)
485 show (show information of a chart)
486
487 # Without descriptions
488 $ helm s[tab][tab]
489 search show status
490 ```
491 **Note**: Cobra's default `completion` command uses bash completion V2. If for some reason you need to use bash completion V1, you will need to implement your own `completion` command.
492 ## Zsh completions
493
494 Cobra supports native zsh completion generated from the root `cobra.Command`.
495 The generated completion script should be put somewhere in your `$fpath` and be named
496 `_<yourProgram>`. You will need to start a new shell for the completions to become available.
497
498 Zsh supports descriptions for completions. Cobra will provide the description automatically,
499 based on usage information. Cobra provides a way to completely disable such descriptions by
500 using `GenZshCompletionNoDesc()` or `GenZshCompletionFileNoDesc()`. You can choose to make
501 this a configurable option to your users.
502 ```
503 # With descriptions
504 $ helm s[tab]
505 search -- search for a keyword in charts
506 show -- show information of a chart
507 status -- displays the status of the named release
508
509 # Without descriptions
510 $ helm s[tab]
511 search show status
512 ```
513 *Note*: Because of backward-compatibility requirements, we were forced to have a different API to disable completion descriptions between `zsh` and `fish`.
514
515 ### Limitations
516
517 * Custom completions implemented in Bash scripting (legacy) are not supported and will be ignored for `zsh` (including the use of the `BashCompCustom` flag annotation).
518 * You should instead use `ValidArgsFunction` and `RegisterFlagCompletionFunc()` which are portable to the different shells (`bash`, `zsh`, `fish`, `powershell`).
519 * The function `MarkFlagCustom()` is not supported and will be ignored for `zsh`.
520 * You should instead use `RegisterFlagCompletionFunc()`.
521
522 ### Zsh completions standardization
523
524 Cobra 1.1 standardized its zsh completion support to align it with its other shell completions. Although the API was kept backward-compatible, some small changes in behavior were introduced.
525 Please refer to [Zsh Completions](zsh.md) for details.
526
527 ## fish completions
528
529 Cobra supports native fish completions generated from the root `cobra.Command`. You can use the `command.GenFishCompletion()` or `command.GenFishCompletionFile()` functions. You must provide these functions with a parameter indicating if the completions should be annotated with a description; Cobra will provide the description automatically based on usage information. You can choose to make this option configurable by your users.
530 ```
531 # With descriptions
532 $ helm s[tab]
533 search (search for a keyword in charts) show (show information of a chart) status (displays the status of the named release)
534
535 # Without descriptions
536 $ helm s[tab]
537 search show status
538 ```
539 *Note*: Because of backward-compatibility requirements, we were forced to have a different API to disable completion descriptions between `zsh` and `fish`.
540
541 ### Limitations
542
543 * Custom completions implemented in bash scripting (legacy) are not supported and will be ignored for `fish` (including the use of the `BashCompCustom` flag annotation).
544 * You should instead use `ValidArgsFunction` and `RegisterFlagCompletionFunc()` which are portable to the different shells (`bash`, `zsh`, `fish`, `powershell`).
545 * The function `MarkFlagCustom()` is not supported and will be ignored for `fish`.
546 * You should instead use `RegisterFlagCompletionFunc()`.
547 * The following flag completion annotations are not supported and will be ignored for `fish`:
548 * `BashCompFilenameExt` (filtering by file extension)
549 * `BashCompSubdirsInDir` (filtering by directory)
550 * The functions corresponding to the above annotations are consequently not supported and will be ignored for `fish`:
551 * `MarkFlagFilename()` and `MarkPersistentFlagFilename()` (filtering by file extension)
552 * `MarkFlagDirname()` and `MarkPersistentFlagDirname()` (filtering by directory)
553 * Similarly, the following completion directives are not supported and will be ignored for `fish`:
554 * `ShellCompDirectiveFilterFileExt` (filtering by file extension)
555 * `ShellCompDirectiveFilterDirs` (filtering by directory)
556
557 ## PowerShell completions
558
559 Cobra supports native PowerShell completions generated from the root `cobra.Command`. You can use the `command.GenPowerShellCompletion()` or `command.GenPowerShellCompletionFile()` functions. To include descriptions use `command.GenPowerShellCompletionWithDesc()` and `command.GenPowerShellCompletionFileWithDesc()`. Cobra will provide the description automatically based on usage information. You can choose to make this option configurable by your users.
560
561 The script is designed to support all three PowerShell completion modes:
562
563 * TabCompleteNext (default windows style - on each key press the next option is displayed)
564 * Complete (works like bash)
565 * MenuComplete (works like zsh)
566
567 You set the mode with `Set-PSReadLineKeyHandler -Key Tab -Function <mode>`. Descriptions are only displayed when using the `Complete` or `MenuComplete` mode.
568
569 Users need PowerShell version 5.0 or above, which comes with Windows 10 and can be downloaded separately for Windows 7 or 8.1. They can then write the completions to a file and source this file from their PowerShell profile, which is referenced by the `$Profile` environment variable. See `Get-Help about_Profiles` for more info about PowerShell profiles.
570
571 ```
572 # With descriptions and Mode 'Complete'
573 $ helm s[tab]
574 search (search for a keyword in charts) show (show information of a chart) status (displays the status of the named release)
575
576 # With descriptions and Mode 'MenuComplete' The description of the current selected value will be displayed below the suggestions.
577 $ helm s[tab]
578 search show status
579
580 search for a keyword in charts
581
582 # Without descriptions
583 $ helm s[tab]
584 search show status
585 ```
586 ### Aliases
587
588 You can also configure `powershell` aliases for your program and they will also support completions.
589
590 ```
591 $ sal aliasname origcommand
592 $ Register-ArgumentCompleter -CommandName 'aliasname' -ScriptBlock $__origcommandCompleterBlock
593
594 # and now when you run `aliasname` completion will make
595 # suggestions as it did for `origcommand`.
596
597 $ aliasname <tab>
598 completion firstcommand secondcommand
599 ```
600 The name of the completer block variable is of the form `$__<programName>CompleterBlock` where every `-` and `:` in the program name have been replaced with `_`, to respect powershell naming syntax.
601
602 ### Limitations
603
604 * Custom completions implemented in bash scripting (legacy) are not supported and will be ignored for `powershell` (including the use of the `BashCompCustom` flag annotation).
605 * You should instead use `ValidArgsFunction` and `RegisterFlagCompletionFunc()` which are portable to the different shells (`bash`, `zsh`, `fish`, `powershell`).
606 * The function `MarkFlagCustom()` is not supported and will be ignored for `powershell`.
607 * You should instead use `RegisterFlagCompletionFunc()`.
608 * The following flag completion annotations are not supported and will be ignored for `powershell`:
609 * `BashCompFilenameExt` (filtering by file extension)
610 * `BashCompSubdirsInDir` (filtering by directory)
611 * The functions corresponding to the above annotations are consequently not supported and will be ignored for `powershell`:
612 * `MarkFlagFilename()` and `MarkPersistentFlagFilename()` (filtering by file extension)
613 * `MarkFlagDirname()` and `MarkPersistentFlagDirname()` (filtering by directory)
614 * Similarly, the following completion directives are not supported and will be ignored for `powershell`:
615 * `ShellCompDirectiveFilterFileExt` (filtering by file extension)
616 * `ShellCompDirectiveFilterDirs` (filtering by directory)