Complete

This module provides autocompletion functionality for widgets and CLI.

Completer basics

All completers are derived from the Completer base class with a simple interface:

class yuio.complete.Completer

An interface for text completion providers.

complete(
text: str,
pos: int,
/,
*,
do_corrections: bool = True,
derive_common_prefix: bool = True,
) list[Completion]

Complete the given text at the given cursor position.

Parameters:
  • text – text that is being completed.

  • pos – position of the cursor in the text. 0 means the cursor is before the first character, len(text) means the cursor is after the last character.

  • do_corrections – if True (default), completion system will try to guess if there are any misspells in the text, and offer to correct them.

  • derive_common_prefix – if True (default), and all returned completions have a non-empty common prefix, return a single completion with this prefix instead.

Returns:

a sorted list of completions.

If all completions start with a common prefix, a single completion is returned containing this prefix.

class yuio.complete.Completion(
iprefix: str,
completion: str,
rsuffix: str,
rsymbols: str,
isuffix: str,
comment: str | None,
dprefix: str,
dsuffix: str,
group_id: SupportsLt[Any],
group_color_tag: str | None,
)

A single completion.

iprefix: str

See CompletionCollector.iprefix for details.

completion: str

Text of the completion.

rsuffix: str

See CompletionCollector.rsuffix for details.

rsymbols: str

See CompletionCollector.rsymbols for details.

isuffix: str

See CompletionCollector.isuffix for details.

comment: str | None

Short comment displayed alongside the completion.

dprefix: str

Prefix that will be displayed before completion when listing completions, but will not be inserted once completion is applied.

dsuffix: str

Like dprefix, but it’s a suffix.

group_id: SupportsLt[Any]

Group id, used to sort completions.

Actual content of this property is an implementation detail.

group_color_tag: str | None

Color tag that’s used when displaying this completion.

See CompletionCollector.add_group() for details.

Completers

Yuio provides basic completers that cover most of the cases:

class yuio.complete.Empty

An empty completer that returns no values.

class yuio.complete.Alternative(completers: list[tuple[str, Completer]], /)

Joins outputs from multiple completers.

Parameters:

completers

list of inner completers.

This is a list of tuples. First tuple element is a description of a completion group. It will be displayed when this completer is used in shells that support it (namely, ZSH). Second tuple element is the inner completer itself.

class yuio.complete.Choice(choices: Collection[Option], /)

Completes input from a predefined list of completions.

Parameters:

choices – options to choose completion from.

class yuio.complete.Option(completion: str, comment: str | None = None)

A single completion option for the Choice completer.

completion: str

This string will replace an element that is being completed.

comment: str | None

Short comment displayed alongside the completion.

class yuio.complete.List(
inner: Completer,
/,
*,
delimiter: str | None = None,
allow_duplicates: bool = False,
)

Completes a value-separated list of elements.

Parameters:
  • inner – completer for list items.

  • delimiter – a character that separates list items. None separates by any whitespace character, similar to str.split().

  • allow_duplicates – whether to show completions that already appear in the list.

class yuio.complete.Tuple(*inner: Completer, delimiter: str | None = None)

Completes a value-separated tuple of elements.

Parameters:
  • inner – completers for each tuple element.

  • delimiter – a character that separates list items. None separates by any whitespace character, similar to str.split().

class yuio.complete.File(extensions: str | Collection[str] | None = None)

Completes file paths.

Parameters:

extensions – allowed file extensions, should include the leading dot.

class yuio.complete.Dir

Completes directories.

Implementing your own completer

To implement a custom completer, subclass Completer and implement its _process() method.

Note

When using a custom completer for CLI flags in yuio.app, completion script will invoke your program with special arguments to run the completer and get its result.

class yuio.complete.Completer
abstractmethod _process(collector: CompletionCollector, /)

Generate completions and add them to the given collector.

Implementing this class is straight forward, just feed all possible completions to the collector. For example, let’s implement a completer for environment variables:

class EnvVarCompleter(Completer):
    def _process(self, collector: CompletionCollector):
        for var in os.environ.keys():
            collector.add(var)
class yuio.complete.CompletionCollector(text: str, pos: int, /)

A class that collects completions as completers are running.

The text that is being completed is split into four parts, similar to what you might see in ZSH completion widgets. The main two are:

prefix: str

Portion of the completed text before the cursor.

suffix: str

Portion of the completed text after the cursor.

When completions are added to the collector, they are checked against the current prefix to determine if they match the entered text. If they do, the completion system will replace text from prefix and suffix with the new completion string.

The two additional parts are:

iprefix: str

Contains text that goes before the prefix.

This prefix is not considered when checking whether a completion matches a text, and it is not replaced by the completion. It will also not be shown in the table of completions.

This prefix starts empty, and then parts of prefix are moved to iprefix as completers split it into list elements.

isuffix: str

Similar to CompletionCollector.iprefix, but for suffixes.

For example, suppose you’re completing a second element of a colon-separated list. The list completer will set up the collector so that prefix and suffix contain parts of the current list element, while iprefix and isuffix contain the rest of the elements:

list_element_1:list_el|ement_2:list_element_3
└┬────────────┘└┬────┘│└┬────┘└┬────────────┘
 iprefix       prefix │ suffix isuffix
                      └ cursor

Now, if the completer adds a completion "list_elements", this text will replace the prefix and suffix, but not iprefix and isuffix. So, after the completion is applied, the string will look like so:

list_element_1:list_elements:list_element_3
               └┬──────────┘
                this got replaced

Finally, there is rsuffix:

rsuffix: str

Starts empty, and may be set to hold a list separator.

This suffix will be added after the completion. However, it will be automatically removed if the user types one of CompletionCollector.rsymbols, or moves cursor, or alters input in some other way.

This property is mutable and can be changed by completers.

rsymbols: str

If user types one of the symbols from this string, rsuffix will be removed.

This property is mutable and can be changed by completers.

So, when completing a colon-separated list, colons will be added and removed automatically, similar to how ZSH does it.

dedup_words: frozenset[str]

Completions from this set will not be added. This is useful when completing lists of unique values.

This property is mutable and can be changed by completers.

full_prefix

Portion of the final completed text that goes before the cursor.

full_suffix

Portion of the final completed text that goes after the cursor.

text

Portion of the text that is being autocompleted.

num_completions

Number of completions added so far.

add(
completion: str,
/,
*,
comment: str | None = None,
dprefix: str = '',
dsuffix: str = '',
color_tag: str | None = None,
)

Add a new completion.

Parameters:
  • completion – completed text without iprefix and isuffix. This text will replace prefix and suffix.

  • comment – additional comment that will be displayed near the completion.

  • color_tag – allows overriding color tag from the group.

add_group(
*,
sorted: bool = True,
color_tag: str | None = None,
)

Add a new completions group.

All completions added after call to this method will be placed to the new group. They will be grouped together, and colored according to the group’s color tag.

Parameters:
  • sorted – controls whether completions in the new group should be sorted lexicographically.

  • color_tag

    which color tag should be used to display completions and their help messages for this group.

    See yuio.widget.Option.color_tag for details.

save_state()

Save current state of the collector, i.e. prefixes, suffixes, etc., upon entering this context manager, then restore state upon exiting.

Use this context manager when you need to call nested completers more than once to prevent changes made in one nested completer bleeding out into another nested completer.

split_off_prefix(delim: str | None = None, /)

Move everything up to the last occurrence of delim from prefix to iprefix.

Parameters:

delim – delimiter to split off; None value splits off on any whitespace character, similar to str.rsplit().

split_off_suffix(delim: str | None = None, /)

Move everything past the first occurrence of delim from suffix to isuffix.

Parameters:

delim – delimiter to split off; None value splits off on any whitespace character, similar to str.split().

finalize(
*,
derive_common_prefix: bool = True,
) list[Completion]

Finish collecting completions and return everything that was collected.

Do not reuse a collector after it was finalized.

Returns:

list of completions, sorted by their groups and preferred ordering within each group.

If all completions start with a common prefix, a single completion is returned containing this prefix.