cpl_complete_word(3)

πŸ“¦
version 1.6.3 Β· 2 versions
, in debian bookworm, debian trixie, ubuntu jammy, ubuntu noble, ubuntu questing, ubuntu resolute, ubuntu stonking

✨ NAME ✨

okay bestie so <libtecla> has a whole little squad of functions for looking up possible completions for a word πŸ’… like when you're typing and the library is like "oh honey I got you, here's what you probably meant" β€” that's this. the full lineup is:

  • cpl_complete_word
  • cfc_file_start
  • cfc_literal_escapes
  • cfc_set_check_fn
  • cpl_add_completion
  • cpl_file_completions
  • cpl_last_error
  • cpl_list_completions
  • cpl_recall_matches
  • cpl_record_error
  • del_CplFileConf
  • del_WordCompletion
  • new_CplFileConf
  • new_WordCompletion

and what do they do? lookup possible completions for a word. that's the whole vibe. periodt.


🌸 SYNOPSIS 🌸

first things first, you gotta pull in the headers β€” this is from the Library Functions Manual, section 3, iykyk:

#include <stdio.h>
#include <libtecla.h>

πŸ¦‹ the WordCompletion lifecycle (birth & death)

you make one, you destroy one. iconic duo:

WordCompletion *new_WordCompletion(void);

WordCompletion *del_WordCompletion(WordCompletion *cpl);

πŸŽ€ defining your own match function

this macro is giving "build your own adventure" energy β€” it expands into a function declaration with a signature you gotta match exactly:

#define CPL_MATCH_FN(fn) int (fn)(WordCompletion *cpl, \
                                  void *data, \
                                  const char *line, \
                                  int word_end)
typedef CPL_MATCH_FN(CplMatchFn);

and libtecla already ships one for you, slay:

CPL_MATCH_FN(cpl_file_completions);

πŸ’– the main character: cpl_complete_word

CplMatches *cpl_complete_word(WordCompletion *cpl,
                              const char *line,
                              int word_end, void *data,
                              CplMatchFn *match_fn);

⭐ recalling & listing what you got

CplMatches *cpl_recall_matches(WordCompletion *cpl);

int cpl_list_completions(CplMatches *result, FILE *fp,
                         int term_width);

✨ adding a completion by hand

int cpl_add_completion(WordCompletion *cpl,
                       const char *line, int word_start,
                       int word_end, const char *suffix,
                       const char *type_suffix,
                       const char *cont_suffix);

🫢 error handling (the unglamorous but necessary part)

void cpl_record_error(WordCompletion *cpl,
                      const char *errmsg);

const char *cpl_last_error(WordCompletion *cpl);

🌈 check functions: is this file even valid tho

#define CPL_CHECK_FN(fn) int (fn)(void *data, \
                                  const char *pathname)

typedef CPL_CHECK_FN(CplCheckFn);

CPL_CHECK_FN(cpl_check_exe);

πŸ’œ CplFileConf β€” the config bestie for file completion

CplFileConf *new_CplFileConf(void);

CplFileConf *del_CplFileConf(CplFileConf *cfc);

void cfc_literal_escapes(CplFileConf *cfc, int literal);

void cfc_file_start(CplFileConf *cfc, int start_index);

void cfc_set_check_fn(CplFileConf *cfc, CplCheckFn *chk_fn,
                      void *chk_data);

ok that's the whole SYNOPSIS, every single signature copied character for character no cap πŸ”₯ and there's more coming β€” DESCRIPTION and beyond are next, so don't go anywhere bestie 🧚

πŸ’– DESCRIPTION πŸ’–

Okay bestie, gather round, because this is the moment. cpl_complete_word() is part of the tecla library (peep the libtecla(3) man page for the whole lore, iykyk). Usually it's doing its thing behind the scenes, called by gl_get_line(3), but it can also be called on its own like the independent icon it is. πŸ’…

So here's the vibe: you hand it an input line that has an incomplete word in it, and it calls a user-provided callback function (or the built-in file-completion callback, if that's your thing) to go look up every possible completion suffix for that word. And what does that callback have to do? It's supposed to look backward in the line, starting from the cursor position you gave it, find where the word to be completed actually starts, then look up all the possible completions of that word and record them β€” one at a time β€” by calling cpl_add_completion(). That's the whole loop. Simple. Slay. ✨

Descriptions of the functions of this module are as follows, so let's get into it:

πŸ¦‹ WordCompletion *new_WordCompletion(void)

This function creates the resources that cpl_complete_word() uses. Specifically β€” and this is the part that matters β€” it maintains the memory used to return the results of calling cpl_complete_word(). So yeah, it's the container, the storage, the whole setup. 🌸

πŸŽ€ WordCompletion *del_WordCompletion(WordCompletion *cpl)

This one deletes the resources that came back from a previous call to new_WordCompletion(). And here's a fun lil quirk: it always returns NULL β€” like, a deleted object, periodt. Also, if the cpl argument is NULL, it just does nothing at all. No drama, no errors, it simply vibes. πŸ’€

The callback functions that look up possible completions should be defined with the following macro (which, btw, lives in libtecla.h):

#define CPL_MATCH_FN(fn) int (fn)(WordCompletion *cpl, \
                                  void *data, \
                                  const char *line, \
                                  int word_end)

Functions of this type get called by cpl_complete_word(), and all of the arguments of the callback are exactly the ones that were passed to that function. Specifically:

  • the line argument holds the input line containing the word to be completed, and
  • word_end is the index of the character that comes right after the last character of the incomplete word, inside that string.

The callback is expected to look backwards from word_end to find the start of the incomplete word. And like β€” what counts as "the start of a word" clearly depends on your application, so it makes total sense that the callback takes on that responsibility. For example, the builtin filename completion function looks backwards until it hits an unescaped space, or the start of the line. Once it's found the start of the word, the callback should look up all possible completions of that word, and record each completion via separate calls to cpl_add_completion(). 🫢

And if the callback needs access to an application-specific symbol table? It can pass that β€” plus any other data it needs β€” through the data argument. Which removes any need for globals. No globals, no problems. 🧚

The callback function should return 0 if no errors occur. On failure it should return 1, and register a terse description of the error by calling cpl_record_error(). That's the deal. πŸ”₯

🌈 void cpl_record_error(WordCompletion *cpl, const char *errmsg);

The last error message recorded by calling cpl_record_error() can later be queried by calling cpl_last_error() β€” as described later on in this page. So it's not lost, it's just waiting for you to ask. πŸ’œ

⭐ int cpl_add_completion(WordCompletion *cpl, const char *line, int word_start, int word_end, const char *suffix, const char *type_suffix, const char *cont_suffix);

The cpl_add_completion() function gets called zero or more times by the completion callback function, to record each possible completion in the specified WordCompletion object. Those completions are then returned by cpl_complete_word(), as described later. πŸ“

Now, the arguments:

  • cpl, line, and word_end should be the ones that were passed to the callback function.
  • word_start should be the index within the input line string of the start of the word being completed. This should equal word_end if a zero-length string is being completed.
  • suffix is the string that would have to be appended to the incomplete word to complete it. If this needs any quoting (eg. the addition of backslashes before special characters) to be valid within the displayed input line, that should be included. A copy of the suffix string is allocated internally, so there's no need to maintain your copy of the string after cpl_add_completion() returns. Free yourself, bestie. πŸ¦‹
Note that in the array of possible completions which the cpl_complete_word() function returns, the suffix recorded by cpl_add_completion() is listed along with the concatentation of this suffix with the word that lies between word_start and word_end in the input line.

The type_suffix argument specifies an optional string to be appended to the completion if it's displayed as part of a list of completions by cpl_list_completions(). The intention is that this indicates to the user the type of each completion. For example, the file completion function places a directory separator after completions that are directories, to indicate their nature to the user. Similary, if the completion were a function, you could indicate this to the user by setting type_suffix to "()". πŸ’…

Careful though: the type_suffix string isn't copied, so if the argument isn't a literal string between speech marks, be sure that the string remains valid for at least as long as the results of cpl_complete_word() are needed. Not me forgetting this and then wondering why everything broke 😭

The cont_suffix is a continuation suffix to append to the completed word in the input line if this is the only completion. This is something that isn't part of the completion itself, but that gives the user an indication about how they might continue to extend the token. For example, the file-completion callback function adds a directory separator if the completed word is a directory. And if the completed word were a function name, you could similarly aid the user by arranging for an open parenthesis to be appended. So thoughtful, honestly. πŸ‘‘

πŸ’« CplMatches *cpl_complete_word(WordCompletion *cpl, const char *line, int word_end, void *data, CplMatchFn *match_fn);

The cpl_complete_word() is normally called behind the scenes by gl_get_line(3), but it can also be called separately if you separately allocate a WordCompletion object. It performs word completion, as described at the beginning of this section. πŸ“–

Its arguments:

  • First up: cpl, a resource object previously returned by new_WordCompletion().
  • line is the input line string, containing the word to be completed.
  • word_end contains the index of the character in the input line that just follows the last character of the word to be completed. When called by gl_get_line(), this is the character over which the user pressed TAB. ⌨️
  • match_fn is the function pointer of the callback function that will look up possible completions of the word, as described above.
  • And data provides a way for the application to pass arbitrary data to the callback function.

If no errors occur, cpl_complete_word() returns a pointer to a CplMatches container, as defined below. This container is allocated as part of the cpl object that was passed to cpl_complete_word(), and will thus change on each call which uses the same cpl argument. So don't go holding onto it like it's forever, because it is not. πŸ™ˆ

typedef struct {
  char *completion;        /* A matching completion */
                           /*  string */
  char *suffix;            /* The part of the */
                           /*  completion string which */
                           /*  would have to be */
                           /*  appended to complete the */
                           /*  original word. */
  const char *type_suffix; /* A suffix to be added when */
                           /*  listing completions, to */
                           /*  indicate the type of the */
                           /*  completion. */
} CplMatch;

typedef struct {
  char *suffix;            /* The common initial part */
                           /*  of all of the completion */
                           /*  suffixes. */
  const char *cont_suffix; /* Optional continuation */
                           /*  string to be appended to */
                           /*  the sole completion when */
                           /*  nmatch==1. */
  CplMatch *matches;       /* The array of possible */
                           /*  completion strings, */
                           /*  sorted into lexical */
                           /*  order. */
  int nmatch;              /* The number of elements in */
                           /*  the above matches[] */
                           /*  array. */
} CplMatches;

If an error occurs during completion, cpl_complete_word() returns NULL. A description of the error can be acquired by calling the cpl_last_error() function. So NULL isn't the end of the world, it's just a vibe check fail. πŸ’€

🌸 const char *cpl_last_error(WordCompletion *cpl);

The cpl_last_error() function returns a terse description of the error which occurred on the last call to cpl_complete_word() or cpl_add_completion(). Terse. Short. To the point. Main character energy, honestly. ✨

πŸŽ€ CplMatches *cpl_recall_matches(WordCompletion *cpl);

As a convenience, the return value of the last call to cpl_complete_word() can be recalled at a later time by calling cpl_recall_matches(). And here's the cute lil symmetry: if cpl_complete_word() returned NULL, so will cpl_recall_matches(). Matching energy. 🫢

πŸ¦‹ int cpl_list_completions(CplMatches *result, FILE *fp, int terminal_width);

When the cpl_complete_word() function returns multiple possible completions, the cpl_list_completions() function can be called upon to list them, suitably arranged across the available width of the terminal. πŸ“Ί

It arranges for the displayed columns of completions to all have the same width, set by the longest completion. It also appends the type_suffix strings that were recorded with each completion, thus indicating their types to the user. Aesthetic and informative. We love to see it. πŸ’–

✨ THE BUILT-IN FILENAME-COMPLETION CALLBACK ✨

okay so bestie, by default gl_get_line(3) hands the following completion callback function straight to cpl_complete_word(). and the tea is β€” you can also use it all by itself, either by sending it to cpl_complete_word(), or by calling it directly from your very own completion callback function. main character behavior fr fr πŸ’…

CPL_MATCH_FN(cpl_file_completions);

some aspects of how this callback behaves can be changed via its data argument. if you're living your life happily with the default behavior, you can just pass NULL in that argument. otherwise it should be a pointer to a CplFileConf object, previously allocated by calling new_CplFileConf(). 🫢

CplFileConf *new_CplFileConf(void);

CplFileConf objects encapsulate the configuration parameters of cpl_file_completions(). these parameters, which start out with default values, can be changed by calling the accessor functions described below. it's giving little control panel for your completions, no cap ✨

by default, the cpl_file_completions() callback function searches backwards for the start of the filename being completed, looking for the first un-escaped space or the start of the input line. if you wish to specify a different location, call cfc_file_start() with the index at which the filename starts in the input line. passing start_index=-1 re-enables the default behavior. πŸ”₯

void cfc_file_start(CplFileConf *cfc, int start_index);

by default, when cpl_file_completions() looks at a filename in the input line, each lone backslash in the input line is interpreted as being a special character which removes any special significance of the character which follows it β€” like a space which should be taken as part of the filename rather than delimiting the start of the filename. so those backslashes are thus ignored while looking for completions, and subsequently added before spaces, tabs and literal backslashes in the list of completions. to have unescaped backslashes treated as normal characters, call cfc_literal_escapes() with a non-zero value in its literal argument. πŸ’€

void cfc_literal_escapes(CplFileConf *cfc, int literal);

by default, cpl_file_completions() reports all files who's names start with the prefix that is being completed. if you only want a selected subset of these files to be reported in the list of completions, you can arrange this by providing a callback function which takes the full pathname of a file, and returns 0 if the file should be ignored, or 1 if the file should be included in the list of completions. to register such a function for use by cpl_file_completions(), call cfc_set_check_fn(), and pass it a pointer to the function, together with a pointer to any data that you would like passed to this callback whenever it is called. your callback can make its decisions based on any property of the file β€” the filename itself, whether the file is readable, writable or executable, or even based on what the file contains. obsessed with the flexibility honestly 🌈

#define CPL_CHECK_FN(fn) int (fn)(void *data, \
                                  const char *pathname)
typedef CPL_CHECK_FN(CplCheckFn);

void cfc_set_check_fn(CplFileConf *cfc,
                      CplCheckFn *chk_fn, void *chk_data);

the cpl_check_exe() function is a provided callback of the above type, for use with cpl_file_completions(). it returns non-zero if the filename that it is given represents a normal file that the user has execute permission to. you could use this to have cpl_file_completions() only list completions of executable files. iconic, actually πŸ‘‘

when you have finished with a CplFileConf variable, you can pass it to the del_CplFileConf() destructor function to reclaim its memory. clean up after yourself bestie, we love a tidy queen πŸŽ€

CplFileConf *del_CplFileConf(CplFileConf *cfc);

πŸ¦‹ THREAD SAFETY πŸ¦‹

in multi-threaded programs, you should use the libtecla_r.a version of the library. this uses POSIX reentrant functions where available (hence the _r suffix), and disables features that rely on non-reentrant system functions. in the case of this module, the only disabled feature is username completion in ~username/ expressions, in cpl_file_completions(). note it down, it's important πŸ“

using the libtecla_r.a version of the library, it is safe to use the facilities of this module in multiple threads, provided that each thread uses a separately allocated WordCompletion object. in other words, if two threads want to do word completion, they should each call new_WordCompletion() to allocate their own completion objects. no sharing, bestie β€” everybody gets their own ✨

fr fr do not share a WordCompletion across threads. separate objects or nothing.

🌸 FILES 🌸

  • libtecla.a β€” the tecla library
  • libtecla.h β€” the tecla header file

πŸ’œ SEE ALSO πŸ’œ


πŸ‘‘ AUTHOR πŸ‘‘

Martin Shepherd (mcs@astro.caltech.edu)


and that's the whole page bestie, we made it to the very end 🫢 the little footer signature down there is cpl_complete_word(3) β€” that's the page's own name and its spot in the manual's section 3, sitting right at the bottom where the version/date line lives. ate and left no crumbs πŸ’–βœ¨

πŸ“¦ where this page comes from