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

Re: implementing a control for completing filenames with a defined list of tokens



On Dec 2,  3:26pm, Eric Smith wrote:
} Subject: implementing a control for completing filenames with a defined li
}
} I would like to define a completion widget to complete filenames with
} a defined list of tokens. The widget would look up in a list the
} tokens and suggest these (ideally in order) to the user.

This one is about as straightforward as it's possible to get.

First you need a function that reads tokenfile and passes the lines
therein as arguments to the "compadd" builtin.

    _tokens() { compadd ${(f)"$(<tokenfile)"} }

Next you need a completion widget.  There's a ready-made function for
creating completion widgets, called _generic.

    zle -C token-completion complete-word _generic
    bindkey ^K token-completion

(^K is normally kill-line so you might want to pick another binding.)

Finally tell the completion system that when the token-completer is
invoked, it should use the _tokens function to supply the matches:

    zstyle ':completion:token-completion:*' completer _tokens

And you're done.  If you eventually want it to complete other things, you
can append more functions to the zstyle.

Another way to do this is to create a file in your $fpath having a name
starting with underscore, and begin that file with a "#compdef -k ..."
line.  That could be as simple as this:

---- 8< ---- snip ---- 8< ----
#compdef -k complete-word ^K

_tokens() { compadd ${(f)"$(<tokenfile)"} }
_generic _tokens
---- 8< ---- snip ---- 8< ----

However, that will redefine the _tokens function on each completion.  A
slightly better formulation would be to have the file redefine the same
function as its file name.  If the file is named "_token_completion":

---- 8< ---- snip ---- 8< ----
#compdef -k complete-word ^K

_tokens() { compadd ${(f)"$(<tokenfile)"} }
_token_completion() { _generic _tokens }
_token_completion
---- 8< ---- snip ---- 8< ----

It's probably not necessary to go this far when _tokens is so simple,
but if you eventually write something more involved it's a good pattern.

Note that with the file you don't need the zstyle: passing _tokens as an
argument to _generic has the equivalent effect.  You could omit _tokens
there and instead have the style, just replace "token-completion" in the
style pattern with the name of the file.



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