Shell completion¶
Generate a completion script, or compute the candidates directly. See the Shell completion guide.
generate_completion ¶
Return a context-aware shell completion script for the CLI described by doc.
The script is a thin callback carrying no grammar of its own. At each Tab it re-invokes the program with
a completion request in the environment, and that program's docopt call resolves the
tokens legal at the cursor from the usage grammar. Suggestions therefore narrow to the matched subcommand's options
and arguments, rather than a flat global list.
A docopt program answers those requests by default. A program that does not want this passes
docopt(..., complete=False) to opt out.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
doc
|
str
|
The usage message (the same string given to |
required |
prog
|
str
|
The command name the script completes for. Must be a plain command name
(letters, digits, |
required |
shell
|
str
|
One of |
'bash'
|
Returns:
| Type | Description |
|---|---|
str
|
The completion script as text. It depends only on |
str
|
since the grammar stays in the program. |
Raises:
| Type | Description |
|---|---|
ValueError
|
|
DocoptLanguageError
|
The usage message is malformed. It fails here rather than at Tab time. |
Source code in src/docopt2/_completion.py
complete ¶
Return the completion candidates for the last (cursor) word of words.
Earlier tokens are consumed against the usage pattern. The command literals and option names that could legally come next are returned, filtered to the partial word. A malformed doc yields no candidates, never raises.
A value is a candidate only with schema, and only for a field that takes a closed set, a
Literal or an Enum. Such a field completes as the next positional, as the argument the
last option is waiting for, and as --option=value beside the option's own name. Without it,
a prefix that ends on an option waiting for its argument yields no candidates.
The next positional is the one docopt would give the next word to: with
[<name>] [<mode>] a word typed first is a <name>, so no <mode> is offered before it.
A schema other than a pydantic model reads the typed words too: after a value that its field does not take there are no candidates, since no argv that starts that way can be bound.