Skip to content

Commit 2e0e204

Browse files
authored
Add context aware custom completions to the book (#836)
I saw no reference of this anywhere in the documentation so I propose we add this to the custom completions page. Here's an [example](https://github.com/nushell/nu_scripts/blob/main/kubernetes/kubernetes.nu#L172) of this in the nu_scripts repository which is where I figured out it's possible to do it. English isn't my first language don't hesitate to correct me on my grammar and phrasing.
1 parent 82cf280 commit 2e0e204

File tree

1 file changed

+42
-0
lines changed

1 file changed

+42
-0
lines changed

book/custom_completions.md

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -43,6 +43,48 @@ In our module, we've chosen to export only the custom command `my-command` but n
4343

4444
This is possible because custom completion tags using `@` are locked-in as the command is first parsed.
4545

46+
## Context aware custom completions
47+
48+
It is possible to pass the context to the custom completion command. This is useful in situations where it is necessary to know previous arguments or flags to generate accurate completions.
49+
50+
Let's apply this concept to the previous example:
51+
52+
```
53+
module commands {
54+
def animals [] {
55+
["cat", "dog", "eel" ]
56+
}
57+
58+
def animal-names [context: string] {
59+
{
60+
cat: ["Missy", "Phoebe"]
61+
dog: ["Lulu", "Enzo"]
62+
eel: ["Eww", "Slippy"]
63+
} | get -i ($context | split words | last)
64+
}
65+
66+
export def my-command [
67+
animal: string@animals
68+
name: string@animal-names
69+
] {
70+
print $"The ($animal) is named ($name)."
71+
}
72+
}
73+
```
74+
75+
Here, the command `animal-names` returns the appropriate list of names. This is because `$context` is a string with where the value is the command that has been typed until now.
76+
77+
```
78+
>| my-command
79+
cat dog eel
80+
>| my-command dog
81+
Lulu Enzo
82+
>my-command dog enzo
83+
The dog is named Enzo
84+
```
85+
86+
On the second line, once we press the `<tab>` key, the argument `"my-command dog"` is passed to the `animal-names` command as context.
87+
4688
## Custom completion and [`extern`](/commands/docs/extern.md)
4789

4890
A powerful combination is adding custom completions to [known `extern` commands](externs.md). These work the same way as adding a custom completion to a custom command: by creating the custom completion and then attaching it with a `@` to the type of one of the positional or flag arguments of the `extern`.

0 commit comments

Comments
 (0)