Zsh Mailing List Archive
Messages sorted by: Reverse Date, Date, Thread, Author

Re: Aliases (abbreviations) for command completion?

On Thu, Jul 22, 2021 at 1:52 AM Peter Slížik <peter.slizik@xxxxxxxxx> wrote:
> is it possible to define something like "aliases" (apologies for the lack of a better term) for command completion?

So the problem statement, paraphrased, is:
  Without using the "alias" builtin to create command shorthands,
provide for command completion to expand a short string to an
arbitrary longer one.

Is that correct?

> If the completed command consists of multiple words, I would like to be able to type the first letters of individual words

You don't mean space-separated shell syntax "words" here, I take it.

This is going to be nearly impossible unless you predefine specific
abbreviations, because determining "the first letters" without some
kind of delimiter (even as simple as camel-casing) is a hard problem.

> and have this abbreviation expanded to the whole command name (taking into account that the abbreviation is not a prefix of the completed text).

The way to do this (in general) is to use "compadd -U", which says to
ignore (erase) the word on the command line and substitute the
completion.  The tricky bit here is that if your abbreviation is also
a prefix of some other command name, the result becomes ambiguous, in
which case completion is likely to delete a trailing portion of the
string on the line and offer you the menu (e.g., in your first
example, "ome" might become "o" and a listing of commands).

To avoid creating the ambiguity, you need to define a completer
function (to be referenced in zstyle :completion::::: completer ...)
and make that the first function in the completer zstyle.  Because the
completer zstyle is looked up with incomplete context (:-command-: is
not yet known), your function will have to check internally whether
((CURRENT==1)) and return nonzero when not.  Otherwise, the function
should look up, using ${words[CURRENT]} as the key, what the
completion should be, and then either pass that result to "compadd
-U", or return nonzero if there is no result.  A zero return from this
function will cause its replacement to be used in preference to
anything that might be found by later completers in the list.

Exactly what "look up" means, is up to you.  You could use a case/esac
in the function, or an associative array variable, or even a zstyle.

In the event that you want to discover potential ambiguity, there are
some other approaches, but I won't go into that unless there is

Messages sorted by: Reverse Date, Date, Thread, Author