xref: /titanic_44/usr/src/lib/libtecla/libtecla.h (revision 62a24de03df1f2399ceda704cb3874dabc98bbbd)
1 #ifndef libtecla_h
2 #define libtecla_h
3 
4 /*
5  * Copyright (c) 2000, 2001, 2002, 2003, 2004 by Martin C. Shepherd.
6  *
7  * All rights reserved.
8  *
9  * Permission is hereby granted, free of charge, to any person obtaining a
10  * copy of this software and associated documentation files (the
11  * "Software"), to deal in the Software without restriction, including
12  * without limitation the rights to use, copy, modify, merge, publish,
13  * distribute, and/or sell copies of the Software, and to permit persons
14  * to whom the Software is furnished to do so, provided that the above
15  * copyright notice(s) and this permission notice appear in all copies of
16  * the Software and that both the above copyright notice(s) and this
17  * permission notice appear in supporting documentation.
18  *
19  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
20  * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
21  * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT
22  * OF THIRD PARTY RIGHTS. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
23  * HOLDERS INCLUDED IN THIS NOTICE BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL
24  * INDIRECT OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING
25  * FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT,
26  * NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION
27  * WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
28  *
29  * Except as contained in this notice, the name of a copyright holder
30  * shall not be used in advertising or otherwise to promote the sale, use
31  * or other dealings in this Software without prior written authorization
32  * of the copyright holder.
33  */
34 
35 #pragma ident	"%Z%%M%	%I%	%E% SMI"
36 
37 #ifdef __cplusplus
38 extern "C" {
39 #endif
40 
41 #include <stdio.h>   /* FILE * */
42 #include <stdlib.h>  /* size_t */
43 #include <time.h>    /* time_t */
44 #include <signal.h>  /* struct sigaction */
45 
46 /*
47  * The following are the three components of the libtecla version number.
48  * Note that it is better to use the libtecla_version() function than these
49  * macros since the macros only tell you which version of the library your
50  * code was compiled against, whereas the libtecla_version() function
51  * tells you which version of the shared tecla library your program is
52  * actually linked to.
53  */
54 #define TECLA_MAJOR_VER 1
55 #define TECLA_MINOR_VER 6
56 #define TECLA_MICRO_VER 0
57 
58 /*.......................................................................
59  * Query the version number of the tecla library.
60  *
61  * Input:
62  *  major    int *   The major version number of the library
63  *                   will be assigned to *major. This number is
64  *                   only incremented when a change to the library is
65  *                   made that breaks binary (shared library) and/or
66  *                   compilation backwards compatibility.
67  *  minor    int *   The minor version number of the library
68  *                   will be assigned to *minor. This number is
69  *                   incremented whenever new functions are added to
70  *                   the public API.
71  *  micro    int *   The micro version number of the library will be
72  *                   assigned to *micro. This number is incremented
73  *                   whenever internal changes are made that don't
74  *                   change the public API, such as bug fixes and
75  *                   performance enhancements.
76  */
77 void libtecla_version(int *major, int *minor, int *micro);
78 
79 /*-----------------------------------------------------------------------
80  * The getline module provides interactive command-line input, recall
81  * and editing by users at terminals. See the gl_getline(3) man page for
82  * more details.
83  *-----------------------------------------------------------------------*/
84 
85 /*
86  * Provide an opaque handle for the resource object that is defined in
87  * getline.h.
88  */
89 typedef struct GetLine GetLine;
90 
91 /*
92  * The following two functions are used to create and delete the
93  * resource objects that are used by the gl_getline() function.
94  */
95 GetLine *new_GetLine(size_t linelen, size_t histlen);
96 GetLine *del_GetLine(GetLine *gl);
97 
98 /*
99  * Read a line into an internal buffer of gl.
100  */
101 char *gl_get_line(GetLine *gl, const char *prompt, const char *start_line,
102 		  int start_pos);
103 
104 /*.......................................................................
105  * Prompt the user for a single-character reply.
106  *
107  * Input:
108  *  gl       GetLine *  A resource object returned by new_GetLine().
109  *  prompt      char *  The prompt to prefix the query with, or NULL
110  *                      to reuse the previous prompt.
111  *  defchar     char    The character to substitute if the
112  *                      user simply hits return, or '\n' if you don't
113  *                      need to substitute anything.
114  * Output:
115  *  return       int    The character that was read, or EOF if the read
116  *                      had to be aborted (in which case you can call
117  *                      gl_return_status() to find out why).
118  */
119 int gl_query_char(GetLine *gl, const char *prompt, char defchar);
120 
121 /*.......................................................................
122  * Read a single uninterpretted character from the user, without
123  * displaying anything.
124  *
125  * Input:
126  *  gl     GetLine *  A resource object previously returned by
127  *                    new_GetLine().
128  * Output:
129  *  return     int    The character that was read, or EOF if the read
130  *                    had to be aborted (in which case you can call
131  *                    gl_return_status() to find out why).
132  */
133 int gl_read_char(GetLine *gl);
134 
135 /*
136  * Configure the application specific and/or user-specific behavior of
137  * gl_get_line().
138  */
139 int gl_configure_getline(GetLine *gl, const char *app_string,
140 			 const char *app_file, const char *user_file);
141 
142 /*
143  * The following enumerators specify the origin of a key binding, and
144  * are listed in order of decreasing priority, such that user-specified
145  * key-bindings take precedence over application default bindings.
146  */
147 typedef enum {
148   GL_USER_KEY,  /* A key-binding specified by the user */
149   GL_APP_KEY    /* A key-binding specified by the application */
150 } GlKeyOrigin;
151 
152 /*
153  * Bind a key sequence to a given action. If action==NULL, unbind the
154  * key-sequence.
155  */
156 int gl_bind_keyseq(GetLine *gl, GlKeyOrigin origin, const char *keyseq,
157 		   const char *action);
158 
159 /*-----------------------------------------------------------------------
160  * The file-expansion module provides facilities for expanding ~user/ and
161  * $envvar expressions, and for expanding glob-style wildcards.
162  * See the ef_expand_file(3) man page for more details.
163  *-----------------------------------------------------------------------*/
164 
165 /*
166  * ExpandFile objects contain the resources needed to expand pathnames.
167  */
168 typedef struct ExpandFile ExpandFile;
169 
170 /*
171  * The following functions are used to create and delete the resource
172  * objects that are used by the ef_expand_file() function.
173  */
174 ExpandFile *new_ExpandFile(void);
175 ExpandFile *del_ExpandFile(ExpandFile *ef);
176 
177 /*
178  * A container of the following type is returned by ef_expand_file().
179  */
180 typedef struct {
181   int exists;       /* True if the files in files[] currently exist. */
182                     /*  This only time that this may not be true is if */
183                     /*  the input filename didn't contain any wildcards */
184                     /*  and thus wasn't matched against existing files. */
185                     /*  In this case the single entry in 'nfile' may not */
186                     /*  refer to an existing file. */
187   int nfile;        /* The number of files in files[] */
188   char **files;     /* An array of 'nfile' filenames. */
189 } FileExpansion;
190 
191 /*
192  * The ef_expand_file() function expands a specified pathname, converting
193  * ~user/ and ~/ patterns at the start of the pathname to the
194  * corresponding home directories, replacing $envvar with the value of
195  * the corresponding environment variable, and then, if there are any
196  * wildcards, matching these against existing filenames.
197  *
198  * If no errors occur, a container is returned containing the array of
199  * files that resulted from the expansion. If there were no wildcards
200  * in the input pathname, this will contain just the original pathname
201  * after expansion of ~ and $ expressions. If there were any wildcards,
202  * then the array will contain the files that matched them. Note that
203  * if there were any wildcards but no existing files match them, this
204  * is counted as an error and NULL is returned.
205  *
206  * The supported wildcards and their meanings are:
207  *  *        -  Match any sequence of zero or more characters.
208  *  ?        -  Match any single character.
209  *  [chars]  -  Match any single character that appears in 'chars'.
210  *              If 'chars' contains an expression of the form a-b,
211  *              then any character between a and b, including a and b,
212  *              matches. The '-' character looses its special meaning
213  *              as a range specifier when it appears at the start
214  *              of the sequence of characters.
215  *  [^chars] -  The same as [chars] except that it matches any single
216  *              character that doesn't appear in 'chars'.
217  *
218  * Wildcard expressions are applied to individual filename components.
219  * They don't match across directory separators. A '.' character at
220  * the beginning of a filename component must also be matched
221  * explicitly by a '.' character in the input pathname, since these
222  * are UNIX's hidden files.
223  *
224  * Input:
225  *  fe         ExpandFile *  The pathname expansion resource object.
226  *  path       const char *  The path name to be expanded.
227  *  pathlen           int    The length of the suffix of path[] that
228  *                           constitutes the filename to be expanded,
229  *                           or -1 to specify that the whole of the
230  *                           path string should be used.
231  * Output:
232  *  return  FileExpansion *  A pointer to a results container within the
233  *                           given ExpandFile object. This contains an
234  *                           array of the pathnames that resulted from
235  *                           expanding ~ and $ expressions and from
236  *                           matching any wildcards, sorted into lexical
237  *                           order.
238  *
239  *                           This container and its contents will be
240  *                           recycled on subsequent calls, so if you need
241  *                           to keep the results of two successive runs,
242  *                           you will either have to allocate a private
243  *                           copy of the array, or use two ExpandFile
244  *                           objects.
245  *
246  *                           On error, NULL is returned. A description
247  *                           of the error can be acquired by calling the
248  *                           ef_last_error() function.
249  */
250 FileExpansion *ef_expand_file(ExpandFile *ef, const char *path, int pathlen);
251 
252 /*.......................................................................
253  * Print out an array of matching files.
254  *
255  * Input:
256  *  result  FileExpansion *   The container of the sorted array of
257  *                            expansions.
258  *  fp               FILE *   The output stream to write to.
259  *  term_width        int     The width of the terminal.
260  * Output:
261  *  return            int     0 - OK.
262  *                            1 - Error.
263  */
264 int ef_list_expansions(FileExpansion *result, FILE *fp, int term_width);
265 
266 /*
267  * The ef_last_error() function returns a description of the last error
268  * that occurred in a call ef_expand_file(). Note that this message is
269  * contained in an array which is allocated as part of *ef, and its
270  * contents thus potentially change on every call to ef_expand_file().
271  */
272 const char *ef_last_error(ExpandFile *ef);
273 
274 /*-----------------------------------------------------------------------
275  * The WordCompletion module is used for completing incomplete words, such
276  * as filenames. Programs can use functions within this module to register
277  * their own customized completion functions.
278  *-----------------------------------------------------------------------*/
279 
280 /*
281  * Ambiguous completion matches are recorded in objects of the
282  * following type.
283  */
284 typedef struct WordCompletion WordCompletion;
285 
286 /*
287  * Create a new completion object.
288  */
289 WordCompletion *new_WordCompletion(void);
290 
291 /*
292  * Delete a redundant completion object.
293  */
294 WordCompletion *del_WordCompletion(WordCompletion *cpl);
295 
296 /*.......................................................................
297  * Callback functions declared and prototyped using the following macro
298  * are called upon to return an array of possible completion suffixes
299  * for the token that precedes a specified location in the given
300  * input line. It is up to this function to figure out where the token
301  * starts, and to call cpl_add_completion() to register each possible
302  * completion before returning.
303  *
304  * Input:
305  *  cpl  WordCompletion *  An opaque pointer to the object that will
306  *                         contain the matches. This should be filled
307  *                         via zero or more calls to cpl_add_completion().
308  *  data           void *  The anonymous 'data' argument that was
309  *                         passed to cpl_complete_word() or
310  *                         gl_customize_completion()).
311  *  line     const char *  The current input line.
312  *  word_end        int    The index of the character in line[] which
313  *                         follows the end of the token that is being
314  *                         completed.
315  * Output
316  *  return          int    0 - OK.
317  *                         1 - Error.
318  */
319 #define CPL_MATCH_FN(fn) int (fn)(WordCompletion *cpl, void *data, \
320                                   const char *line, int word_end)
321 typedef CPL_MATCH_FN(CplMatchFn);
322 
323 /*.......................................................................
324  * Optional callback functions declared and prototyped using the
325  * following macro are called upon to return non-zero if a given
326  * file, specified by its pathname, is to be included in a list of
327  * completions.
328  *
329  * Input:
330  *  data            void *  The application specified pointer which
331  *                          was specified when this callback function
332  *                          was registered. This can be used to have
333  *                          anything you like passed to your callback.
334  *  pathname  const char *  The pathname of the file to be checked to
335  *                          see if it should be included in the list
336  *                          of completions.
337  * Output
338  *  return           int    0 - Ignore this file.
339  *                          1 - Do include this file in the list
340  *                              of completions.
341  */
342 #define CPL_CHECK_FN(fn) int (fn)(void *data, const char *pathname)
343 typedef CPL_CHECK_FN(CplCheckFn);
344 
345 /*
346  * You can use the following CplCheckFn callback function to only
347  * have executables included in a list of completions.
348  */
349 CPL_CHECK_FN(cpl_check_exe);
350 
351 /*
352  * cpl_file_completions() is the builtin filename completion callback
353  * function. This can also be called by your own custom CPL_MATCH_FN()
354  * callback functions. To do this pass on all of the arguments of your
355  * custom callback function to cpl_file_completions(), with the exception
356  * of the (void *data) argument. The data argument should either be passed
357  * NULL to request the default behaviour of the file-completion function,
358  * or be passed a pointer to a CplFileConf structure (see below). In the
359  * latter case the contents of the structure modify the behavior of the
360  * file-completer.
361  */
362 CPL_MATCH_FN(cpl_file_completions);
363 
364 /*
365  * Objects of the following type can be used to change the default
366  * behavior of the cpl_file_completions() callback function.
367  */
368 typedef struct CplFileConf CplFileConf;
369 
370 /*
371  * If you want to change the behavior of the cpl_file_completions()
372  * callback function, call the following function to allocate a
373  * configuration object, then call one or more of the subsequent
374  * functions to change any of the default configuration parameters
375  * that you don't want. This function returns NULL when there is
376  * insufficient memory.
377  */
378 CplFileConf *new_CplFileConf(void);
379 
380 /*
381  * If backslashes in the prefix being passed to cpl_file_completions()
382  * should be treated as literal characters, call the following function
383  * with literal=1. Otherwise the default is to treat them as escape
384  * characters which remove the special meanings of spaces etc..
385  */
386 void cfc_literal_escapes(CplFileConf *cfc, int literal);
387 
388 /*
389  * Before calling cpl_file_completions(), call this function if you
390  * know the index at which the filename prefix starts in the input line.
391  * Otherwise by default, or if you specify start_index to be -1, the
392  * filename is taken to start after the first unescaped space preceding
393  * the cursor, or the start of the line, which ever comes first.
394  */
395 void cfc_file_start(CplFileConf *cfc, int start_index);
396 
397 /*
398  * If you only want certain types of files to be included in the
399  * list of completions, use the following function to specify a
400  * callback function which will be called to ask whether a given file
401  * should be included. The chk_data argument is will be passed to the
402  * callback function whenever it is called and can be anything you want.
403  */
404 void cfc_set_check_fn(CplFileConf *cfc, CplCheckFn *chk_fn, void *chk_data);
405 
406 /*
407  * The following function deletes a CplFileConf objects previously
408  * returned by new_CplFileConf(). It always returns NULL.
409  */
410 CplFileConf *del_CplFileConf(CplFileConf *cfc);
411 
412 /*
413  * The following configuration structure is deprecated. Do not change
414  * its contents, since this will break any programs that still use it,
415  * and don't use it in new programs. Instead use opaque CplFileConf
416  * objects as described above. cpl_file_completions() figures out
417  * what type of structure you pass it, by virtue of a magic int code
418  * placed at the start of CplFileConf object by new_CplFileConf().
419  */
420 typedef struct {
421   int escaped;     /* Opposite to the argument of cfc_literal_escapes() */
422   int file_start;  /* Equivalent to the argument of cfc_file_start() */
423 } CplFileArgs;
424 /*
425  * This initializes the deprecated CplFileArgs structures.
426  */
427 void cpl_init_FileArgs(CplFileArgs *cfa);
428 
429 /*.......................................................................
430  * When an error occurs while performing a completion, custom completion
431  * callback functions should register a terse description of the error
432  * by calling cpl_record_error(). This message will then be returned on
433  * the next call to cpl_last_error() and used by getline to display an
434  * error message to the user.
435  *
436  * Input:
437  *  cpl  WordCompletion *  The string-completion resource object that was
438  *                         originally passed to the callback.
439  *  errmsg   const char *  The description of the error.
440  */
441 void cpl_record_error(WordCompletion *cpl, const char *errmsg);
442 
443 /*.......................................................................
444  * This function can be used to replace the builtin filename-completion
445  * function with one of the user's choice. The user's completion function
446  * has the option of calling the builtin filename-completion function
447  * if it believes that the token that it has been presented with is a
448  * filename (see cpl_file_completions() above).
449  *
450  * Input:
451  *  gl            GetLine *  The resource object of the command-line input
452  *                           module.
453  *  data             void *  This is passed to match_fn() whenever it is
454  *                           called. It could, for example, point to a
455  *                           symbol table that match_fn() would look up
456  *                           matches in.
457  *  match_fn   CplMatchFn *  The function that will identify the prefix
458  *                           to be completed from the input line, and
459  *                           report matching symbols.
460  * Output:
461  *  return            int    0 - OK.
462  *                           1 - Error.
463  */
464 int gl_customize_completion(GetLine *gl, void *data, CplMatchFn *match_fn);
465 
466 /*.......................................................................
467  * This function allows you to install alternate completion action
468  * functions or completion listing functions, or to change the
469  * completion function of an existing action of the same type. This
470  * should preferably be called before the first call to gl_get_line()
471  * so that the name of the action becomes defined before the user's
472  * configuration file is read.
473  *
474  * Input:
475  *  gl            GetLine *  The resource object of the command-line input
476  *                           module.
477  *  data             void *  This is passed to match_fn() whenever it is
478  *                           called. It could, for example, point to a
479  *                           symbol table that match_fn() would look up
480  *                           matches in.
481  *  match_fn   CplMatchFn *  The function that will identify the prefix
482  *                           to be completed from the input line, and
483  *                           report matching symbols.
484  *  list_only         int    If non-zero, install an action that only lists
485  *                           possible completions, rather than attempting
486  *                           to perform the completion.
487  *  name       const char *  The name with which users can refer to the
488  *                           binding in tecla configuration files.
489  *  keyseq     const char *  The key sequence with which to invoke
490  *                           the binding. This should be specified in the
491  *                           same manner as key-sequences in tecla
492  *                           configuration files (eg. "M-^I").
493  * Output:
494  *  return            int    0 - OK.
495  *                           1 - Error.
496  */
497 int gl_completion_action(GetLine *gl, void *data, CplMatchFn *match_fn,
498 			 int list_only, const char *name, const char *keyseq);
499 
500 /*.......................................................................
501  * Change the terminal (or stream) that getline interacts with.
502  *
503  * Input:
504  *  gl            GetLine *  The resource object of the command-line input
505  *                           module.
506  *  input_fp         FILE *  The stdio stream to read from.
507  *  output_fp        FILE *  The stdio stream to write to.
508  *  term       const char *  The terminal type. This can be NULL if
509  *                           either or both of input_fp and output_fp don't
510  *                           refer to a terminal. Otherwise it should refer
511  *                           to an entry in the terminal information database.
512  * Output:
513  *  return            int    0 - OK.
514  *                           1 - Error.
515  */
516 int gl_change_terminal(GetLine *gl, FILE *input_fp, FILE *output_fp,
517 		       const char *term);
518 
519 /*.......................................................................
520  * The following functions can be used to save and restore the contents
521  * of the history buffer.
522  *
523  * Input:
524  *  gl            GetLine *  The resource object of the command-line input
525  *                           module.
526  *  filename   const char *  The name of the new file to write to.
527  *  comment    const char *  Extra information such as timestamps will
528  *                           be recorded on a line started with this
529  *                           string, the idea being that the file can
530  *                           double as a command file. Specify "" if
531  *                           you don't care. Be sure to specify the
532  *                           same string to both functions.
533  *  max_lines         int    The maximum number of lines to save, or -1
534  *                           to save all of the lines in the history
535  *                           list.
536  * Output:
537  *  return            int     0 - OK.
538  *                            1 - Error.
539  */
540 int gl_save_history(GetLine *gl, const char *filename, const char *comment,
541 		    int max_lines);
542 int gl_load_history(GetLine *gl, const char *filename, const char *comment);
543 
544 /*
545  * Enumerate file-descriptor events that can be waited for.
546  */
547 typedef enum {
548   GLFD_READ,   /* Watch for data waiting to be read from a file descriptor */
549   GLFD_WRITE,  /* Watch for ability to write to a file descriptor */
550   GLFD_URGENT  /* Watch for urgent out-of-band data on the file descriptor */
551 } GlFdEvent;
552 
553 /*
554  * The following enumeration is used for the return status of file
555  * descriptor event callbacks.
556  */
557 typedef enum {
558   GLFD_ABORT,    /* Cause gl_get_line() to abort with an error */
559   GLFD_REFRESH,  /* Redraw the input line and continue waiting for input */
560   GLFD_CONTINUE  /* Continue to wait for input, without redrawing the line */
561 } GlFdStatus;
562 
563 /*.......................................................................
564  * On systems that have the select() system call, while gl_get_line()
565  * is waiting for terminal input, it can also be asked to listen for
566  * activity on arbitrary file descriptors.  Callback functions of the
567  * following type can be registered to be called when activity is
568  * seen. If your callback needs to write to the terminal or use
569  * signals, please see the gl_get_line(3) man page.
570  *
571  * Input:
572  *  gl       GetLine *  The gl_get_line() resource object. You can use
573  *                      this safely to call gl_watch_fd() or
574  *                      gl_inactivity_timeout(). The effect of calling other
575  *                      functions that take a gl argument is undefined,
576  *                      and must be avoided.
577  *  data        void *  A pointer to arbitrary callback data, as originally
578  *                      registered with gl_watch_fd().
579  *  fd           int    The file descriptor that has activity.
580  *  event  GlFdEvent    The activity seen on the file descriptor. The
581  *                      inclusion of this argument allows the same
582  *                      callback to be registered for multiple events.
583  * Output:
584  *  return GlFdStatus   GLFD_ABORT    - Cause gl_get_line() to abort with
585  *                                      an error (set errno if you need it).
586  *                      GLFD_REFRESH  - Redraw the input line and continue
587  *                                      waiting for input. Use this if you
588  *                                      wrote something to the terminal.
589  *                      GLFD_CONTINUE - Continue to wait for input, without
590  *                                      redrawing the line.
591  */
592 #define GL_FD_EVENT_FN(fn) GlFdStatus (fn)(GetLine *gl, void *data, int fd, \
593 					   GlFdEvent event)
594 typedef GL_FD_EVENT_FN(GlFdEventFn);
595 
596 /*.......................................................................
597  * Where possible, register a function and associated data to be called
598  * whenever a specified event is seen on a file descriptor.
599  *
600  * Input:
601  *  gl            GetLine *  The resource object of the command-line input
602  *                           module.
603  *  fd                int    The file descriptor to watch.
604  *  event       GlFdEvent    The type of activity to watch for.
605  *  callback  GlFdEventFn *  The function to call when the specified
606  *                           event occurs. Setting this to 0 removes
607  *                           any existing callback.
608  *  data             void *  A pointer to arbitrary data to pass to the
609  *                           callback function.
610  * Output:
611  *  return            int    0 - OK.
612  *                           1 - Either gl==NULL, or this facility isn't
613  *                               available on the the host system
614  *                               (ie. select() isn't available). No
615  *                               error message is generated in the latter
616  *                               case.
617  */
618 int gl_watch_fd(GetLine *gl, int fd, GlFdEvent event,
619 		GlFdEventFn *callback, void *data);
620 
621 /*
622  * Enumerators from the following list are returned by activity
623  * timeout callbacks registered by gl_inactivity_timeout(). They tell
624  * gl_get_line() whether and how to procede.
625  */
626 typedef enum {
627   GLTO_ABORT,    /* Cause gl_get_line() to abort with an error */
628   GLTO_REFRESH,  /* Redraw the input line and continue waiting for input */
629   GLTO_CONTINUE  /* Continue to wait for input, without redrawing the line */
630 } GlAfterTimeout;
631 
632 /*.......................................................................
633  * On systems that have the select() system call, the application has
634  * the option of providing a callback function of the following type,
635  * which is called whenever no terminal input or other I/O activity is
636  * seen for the timeout duration specified in the last call to
637  * gl_inactivity_timeout().
638  *
639  * Input:
640  *  gl            GetLine *  The gl_get_line() resource object. You can use
641  *                           this safely to call gl_watch_fd() or
642  *                           gl_inactivity_timeout(). The effect of calling other
643  *                           functions that take a gl argument is undefined,
644  *                           and must be avoided.
645  *  data             void *  A pointer to arbitrary callback data, as
646  *                           originally registered with gl_inactivity_timeout().
647  * Output:
648  *  return GlAfterTimeout    GLTO_ABORT    - Cause gl_get_line() to
649  *                                           abort with an error (set
650  *                                           errno if you need it).
651  *                           GLTO_REFRESH  - Redraw the input line and
652  *                                           continue waiting for
653  *                                           input. Use this if you
654  *                                           wrote something to the
655  *                                           terminal.
656  *                           GLTO_CONTINUE - Continue to wait for
657  *                                           input, without redrawing
658  *                                           the line.
659  */
660 #define GL_TIMEOUT_FN(fn) GlAfterTimeout (fn)(GetLine *gl, void *data)
661 typedef GL_TIMEOUT_FN(GlTimeoutFn);
662 
663 /*.......................................................................
664  * On systems with the select() system call, the gl_inactivity_timeout()
665  * function provides the option of setting (or cancelling) an
666  * inactivity timeout. Inactivity, in this case, refers both to
667  * terminal input received from the user, and to I/O on any file
668  * descriptors registered by calls to gl_watch_fd(). If at any time,
669  * no activity is seen for the requested time period, the specified
670  * timeout callback function is called. On returning, this callback
671  * returns a code which tells gl_get_line() what to do next. Note that
672  * each call to gl_inactivity_timeout() replaces any previously installed
673  * timeout callback, and that specifying a callback of 0, turns off
674  * inactivity timing.
675  *
676  * Beware that although the timeout argument includes a nano-second
677  * component, few computer clocks presently have resolutions finer
678  * than a few milliseconds, so asking for less than a few milliseconds
679  * is equivalent to zero on a lot of systems.
680  *
681  * Input:
682  *  gl            GetLine *  The resource object of the command-line input
683  *                           module.
684  *  callback  GlTimeoutFn *  The function to call when the inactivity
685  *                           timeout is exceeded. To turn off
686  *                           inactivity timeouts altogether, send 0.
687  *  data             void *  A pointer to arbitrary data to pass to the
688  *                           callback function.
689  *  sec     unsigned long    The number of whole seconds in the timeout.
690  *  nsec    unsigned long    The fractional number of seconds in the
691  *                           timeout, expressed in nano-seconds (see
692  *                           the caveat above).
693  * Output:
694  *  return            int    0 - OK.
695  *                           1 - Either gl==NULL, or this facility isn't
696  *                               available on the the host system
697  *                               (ie. select() isn't available). No
698  *                               error message is generated in the latter
699  *                               case.
700  */
701 int gl_inactivity_timeout(GetLine *gl, GlTimeoutFn *timeout_fn, void *data,
702 		   unsigned long sec, unsigned long nsec);
703 
704 /*.......................................................................
705  * Switch history streams. History streams represent separate history
706  * lists recorded within a single history buffer. Different streams
707  * are distinguished by integer identifiers chosen by the calling
708  * appplicaton. Initially new_GetLine() sets the stream identifier to
709  * 0. Whenever a new line is appended to the history list, the current
710  * stream identifier is recorded with it, and history lookups only
711  * consider lines marked with the current stream identifier.
712  *
713  * Input:
714  *  gl      GetLine *  The resource object of gl_get_line().
715  *  id     unsigned    The new history stream identifier.
716  * Output:
717  *  return      int    0 - OK.
718  *                     1 - Error.
719  */
720 int gl_group_history(GetLine *gl, unsigned id);
721 
722 /*.......................................................................
723  * Display the contents of the history list.
724  *
725  * Input:
726  *  gl      GetLine *  The resource object of gl_get_line().
727  *  fp         FILE *  The stdio output stream to write to.
728  *  fmt  const char *  A format string. This containing characters to be
729  *                     written verbatim, plus any of the following
730  *                     format directives:
731  *                       %D  -  The date, formatted like 2001-11-20
732  *                       %T  -  The time of day, formatted like 23:59:59
733  *                       %N  -  The sequential entry number of the
734  *                              line in the history buffer.
735  *                       %G  -  The number of the history group that
736  *                              the line belongs to.
737  *                       %%  -  A literal % character.
738  *                       %H  -  The history line itself.
739  *                     Note that a '\n' newline character is not
740  *                     appended by default.
741  *  all_groups  int    If true, display history lines from all
742  *                     history groups. Otherwise only display
743  *                     those of the current history group.
744  *  max_lines   int    If max_lines is < 0, all available lines
745  *                     are displayed. Otherwise only the most
746  *                     recent max_lines lines will be displayed.
747  * Output:
748  *  return      int    0 - OK.
749  *                     1 - Error.
750  */
751 int gl_show_history(GetLine *gl, FILE *fp, const char *fmt, int all_groups,
752 		    int max_lines);
753 
754 /*.......................................................................
755  * Resize or delete the history buffer.
756  *
757  * Input:
758  *  gl      GetLine *  The resource object of gl_get_line().
759  *  bufsize  size_t    The number of bytes in the history buffer, or 0
760  *                     to delete the buffer completely.
761  * Output:
762  *  return      int    0 - OK.
763  *                     1 - Insufficient memory (the previous buffer
764  *                         will have been retained). No error message
765  *                         will be displayed.
766  */
767 int gl_resize_history(GetLine *gl, size_t bufsize);
768 
769 /*.......................................................................
770  * Set an upper limit to the number of lines that can be recorded in the
771  * history list, or remove a previously specified limit.
772  *
773  * Input:
774  *  gl      GetLine *  The resource object of gl_get_line().
775  *  max_lines   int    The maximum number of lines to allow, or -1 to
776  *                     cancel a previous limit and allow as many lines
777  *                     as will fit in the current history buffer size.
778  */
779 void gl_limit_history(GetLine *gl, int max_lines);
780 
781 /*.......................................................................
782  * Discard either all historical lines, or just those associated with the
783  * current history group.
784  *
785  * Input:
786  *  gl      GetLine *  The resource object of gl_get_line().
787  *  all_groups  int    If true, clear all of the history. If false,
788  *                     clear only the stored lines associated with the
789  *                     currently selected history group.
790  */
791 void gl_clear_history(GetLine *gl, int all_groups);
792 
793 /*.......................................................................
794  * Temporarily enable or disable the gl_get_line() history mechanism.
795  *
796  * Input:
797  *  gl      GetLine *  The resource object of gl_get_line().
798  *  enable      int    If true, turn on the history mechanism. If
799  *                     false, disable it.
800  */
801 void gl_toggle_history(GetLine *gl, int enable);
802 
803 /*
804  * Objects of the following type are returned by gl_terminal_size().
805  */
806 typedef struct {
807   int nline;        /* The terminal has nline lines */
808   int ncolumn;      /* The terminal has ncolumn columns */
809 } GlTerminalSize;
810 
811 /*.......................................................................
812  * Update if necessary, and return the current size of the terminal.
813  *
814  * Input:
815  *  gl            GetLine *  The resource object of gl_get_line().
816  *  def_ncolumn       int    If the number of columns in the terminal
817  *                           can't be determined, substitute this number.
818  *  def_nline         int    If the number of lines in the terminal can't
819  *                           be determined, substitute this number.
820  * Output:
821  *  return GlTerminalSize    The current terminal size.
822  */
823 GlTerminalSize gl_terminal_size(GetLine *gl, int def_ncolumn, int def_nline);
824 
825 /*.......................................................................
826  * Tell gl_get_line() the current terminal size. Note that this is only
827  * necessary on systems where changes in terminal size aren't reported
828  * via SIGWINCH.
829  *
830  * Input:
831  *  gl            GetLine *  The resource object of gl_get_line().
832  *  ncolumn           int    The number of columns in the terminal.
833  *  nline             int    The number of rows in the terminal.
834  * Output:
835  *  return            int    0 - OK.
836  *                           1 - Error.
837  */
838 int gl_set_term_size(GetLine *gl, int ncolumn, int nline);
839 
840 /*
841  * The gl_lookup_history() function returns information in an
842  * argument of the following type.
843  */
844 typedef struct {
845   const char *line;    /* The requested history line */
846   unsigned group;      /* The history group to which the */
847                        /*  line belongs. */
848   time_t timestamp;    /* The date and time at which the */
849                        /*  line was originally entered. */
850 } GlHistoryLine;
851 
852 /*.......................................................................
853  * Lookup a history line by its sequential number of entry in the
854  * history buffer.
855  *
856  * Input:
857  *  gl            GetLine *  The resource object of gl_get_line().
858  *  id      unsigned long    The identification number of the line to
859  *                           be returned, where 0 denotes the first line
860  *                           that was entered in the history list, and
861  *                           each subsequently added line has a number
862  *                           one greater than the previous one. For
863  *                           the range of lines currently in the list,
864  *                           see the gl_range_of_history() function.
865  * Input/Output:
866  *  line    GlHistoryLine *  A pointer to the variable in which to
867  *                           return the details of the line.
868  * Output:
869  *  return            int    0 - The line is no longer in the history
870  *                               list, and *line has not been changed.
871  *                           1 - The requested line can be found in
872  *                               *line. Note that the string in
873  *                               line->line is part of the history
874  *                               buffer and will change, so a private
875  *                               copy should be made if you wish to
876  *                               use it after subsequent calls to any
877  *                               functions that take gl as an argument.
878  */
879 int gl_lookup_history(GetLine *gl, unsigned long id, GlHistoryLine *line);
880 
881 /*
882  * The gl_state_of_history() function returns information in an argument
883  * of the following type.
884  */
885 typedef struct {
886   int enabled;     /* True if history is enabled */
887   unsigned group;  /* The current history group */
888   int max_lines;   /* The current upper limit on the number of lines */
889                    /*  in the history list, or -1 if unlimited. */
890 } GlHistoryState;
891 
892 /*.......................................................................
893  * Query the state of the history list. Note that any of the input/output
894  * pointers can be specified as NULL.
895  *
896  * Input:
897  *  gl            GetLine *  The resource object of gl_get_line().
898  * Input/Output:
899  *  state  GlHistoryState *  A pointer to the variable in which to record
900  *                           the return values.
901  */
902 void gl_state_of_history(GetLine *gl, GlHistoryState *state);
903 
904 /*
905  * The gl_range_of_history() function returns information in an argument
906  * of the following type.
907  */
908 typedef struct {
909   unsigned long oldest;  /* The sequential entry number of the oldest */
910                          /*  line in the history list. */
911   unsigned long newest;  /* The sequential entry number of the newest */
912                          /*  line in the history list. */
913   int nlines;            /* The number of lines in the history list */
914 } GlHistoryRange;
915 
916 /*.......................................................................
917  * Query the number and range of lines in the history buffer.
918  *
919  * Input:
920  *  gl            GetLine *  The resource object of gl_get_line().
921  *  range  GlHistoryRange *  A pointer to the variable in which to record
922  *                           the return values. If range->nline=0, the
923  *                           range of lines will be given as 0-0.
924  */
925 void gl_range_of_history(GetLine *gl, GlHistoryRange *range);
926 
927 /*
928  * The gl_size_of_history() function returns information in an argument
929  * of the following type.
930  */
931 typedef struct {
932   size_t size;      /* The size of the history buffer (bytes) */
933   size_t used;      /* The number of bytes of the history buffer */
934                     /*  that are currently occupied. */
935 } GlHistorySize;
936 
937 /*.......................................................................
938  * Return the size of the history buffer and the amount of the
939  * buffer that is currently in use.
940  *
941  * Input:
942  *  gl         GetLine *  The resource object of gl_get_line().
943  * Input/Output:
944  *  GlHistorySize size *  A pointer to the variable in which to return
945  *                        the results.
946  */
947 void gl_size_of_history(GetLine *gl, GlHistorySize *size);
948 
949 /*.......................................................................
950  * Enable or disable the automatic addition of newly entered lines to the
951  * history list.
952  *
953  * Input:
954  *  gl          GetLine *   The resource object of gl_get_line().
955  *  enable          int     If true, subsequently entered lines will
956  *                          automatically be added to the history list
957  *                          before they are returned to the caller of
958  *                          gl_get_line(). If 0, the choice of how and
959  *                          when to archive lines in the history list,
960  *                          is left up to the calling application, which
961  *                          can do so via calls to gl_append_history().
962  * Output:
963  *  return          int     0 - OK.
964  *                          1 - Error.
965  */
966 int gl_automatic_history(GetLine *gl, int enable);
967 
968 /*.......................................................................
969  * Append a specified line to the history list.
970  *
971  * Input:
972  *  gl          GetLine *   The resource object of gl_get_line().
973  *  line     const char *   The line to be added.
974  * Output:
975  *  return          int     0 - OK.
976  *                          1 - Error.
977  */
978 int gl_append_history(GetLine *gl, const char *line);
979 
980 /*.......................................................................
981  * Specify whether text that users type should be displayed or hidden.
982  * In the latter case, only the prompt is displayed, and the final
983  * input line is not archived in the history list.
984  *
985  * Input:
986  *  gl         GetLine *  The input-line history maintenance object.
987  *  enable         int     0 - Disable echoing.
988  *                         1 - Enable echoing.
989  *                        -1 - Just query the mode without changing it.
990  * Output:
991  *  return         int    The echoing disposition that was in effect
992  *                        before this function was called:
993  *                         0 - Echoing was disabled.
994  *                         1 - Echoing was enabled.
995  */
996 int gl_echo_mode(GetLine *gl, int enable);
997 
998 /*.......................................................................
999  * This function can be called from gl_get_line() callbacks to have
1000  * the prompt changed when they return. It has no effect if gl_get_line()
1001  * is not currently being invoked.
1002  *
1003  * Input:
1004  *  gl         GetLine *  The resource object of gl_get_line().
1005  *  prompt  const char *  The new prompt.
1006  */
1007 void gl_replace_prompt(GetLine *gl, const char *prompt);
1008 
1009 /*
1010  * Enumerate the available prompt formatting styles.
1011  */
1012 typedef enum {
1013   GL_LITERAL_PROMPT,   /* Display the prompt string literally */
1014   GL_FORMAT_PROMPT     /* The prompt string can contain any of the */
1015                        /* following formatting directives: */
1016                        /*   %B  -  Display subsequent characters */
1017                        /*          with a bold font. */
1018                        /*   %b  -  Stop displaying characters */
1019                        /*          with the bold font. */
1020                        /*   %U  -  Underline subsequent characters. */
1021                        /*   %u  -  Stop underlining characters. */
1022                        /*   %S  -  Highlight subsequent characters */
1023                        /*          (also known as standout mode). */
1024                        /*   %s  -  Stop highlighting characters */
1025                        /*   %%  -  Display a single % character. */
1026 } GlPromptStyle;
1027 
1028 /*.......................................................................
1029  * Specify whether to heed text attribute directives within prompt
1030  * strings.
1031  *
1032  * Input:
1033  *  gl           GetLine *  The resource object of gl_get_line().
1034  *  style  GlPromptStyle    The style of prompt (see the definition of
1035  *                          GlPromptStyle in libtecla.h for details).
1036  */
1037 void gl_prompt_style(GetLine *gl, GlPromptStyle style);
1038 
1039 /*.......................................................................
1040  * Remove a signal from the list of signals that gl_get_line() traps.
1041  *
1042  * Input:
1043  *  gl           GetLine *  The resource object of gl_get_line().
1044  *  signo            int    The number of the signal to be ignored.
1045  * Output:
1046  *  return           int    0 - OK.
1047  *                          1 - Error.
1048  */
1049 int gl_ignore_signal(GetLine *gl, int signo);
1050 
1051 /*
1052  * A bitwise union of the following enumerators is passed to
1053  * gl_trap_signal() to specify the environment in which the
1054  * application's signal handler is to be called.
1055  */
1056 typedef enum {
1057   GLS_RESTORE_SIG=1,  /* Restore the caller's signal environment */
1058                       /* while handling the signal. */
1059   GLS_RESTORE_TTY=2,  /* Restore the caller's terminal settings */
1060                       /* while handling the signal. */
1061   GLS_RESTORE_LINE=4, /* Move the cursor to the start of the next line */
1062   GLS_REDRAW_LINE=8,  /* Redraw the input line when the signal handler */
1063                       /*  returns. */
1064   GLS_UNBLOCK_SIG=16, /* Normally a signal who's delivery is found to */
1065                       /*  be blocked by the calling application is not */
1066                       /*  trapped by gl_get_line(). Including this flag */
1067                       /*  causes it to be temporarily unblocked and */
1068                       /*  trapped while gl_get_line() is executing. */
1069   GLS_DONT_FORWARD=32,/* Don't forward the signal to the signal handler */
1070                       /*  of the calling program. */
1071   GLS_RESTORE_ENV = GLS_RESTORE_SIG | GLS_RESTORE_TTY | GLS_REDRAW_LINE,
1072   GLS_SUSPEND_INPUT = GLS_RESTORE_ENV | GLS_RESTORE_LINE
1073 } GlSignalFlags;
1074 
1075 /*
1076  * The following enumerators are passed to gl_trap_signal() to tell
1077  * it what to do after the application's signal handler has been called.
1078  */
1079 typedef enum {
1080   GLS_RETURN,      /* Return the line as though the user had pressed the */
1081                    /*  return key. */
1082   GLS_ABORT,       /* Cause gl_get_line() to return NULL */
1083   GLS_CONTINUE     /* After handling the signal, resume command line editing */
1084 } GlAfterSignal;
1085 
1086 /*.......................................................................
1087  * Tell gl_get_line() how to respond to a given signal. This can be used
1088  * both to override the default responses to signals that gl_get_line()
1089  * normally catches and to add new signals to the list that are to be
1090  * caught.
1091  *
1092  * Input:
1093  *  gl           GetLine *  The resource object of gl_get_line().
1094  *  signo            int    The number of the signal to be caught.
1095  *  flags       unsigned    A bitwise union of GlSignalFlags enumerators.
1096  *  after  GlAfterSignal    What to do after the application's signal
1097  *                          handler has been called.
1098  *  errno_value      int    The value to set errno to.
1099  * Output:
1100  *  return           int    0 - OK.
1101  *                          1 - Insufficient memory to record the
1102  *                              new signal disposition.
1103  */
1104 int gl_trap_signal(GetLine *gl, int signo, unsigned flags,
1105 		   GlAfterSignal after, int errno_value);
1106 
1107 /*.......................................................................
1108  * By default, gl_get_line() doesn't trap signals that are blocked
1109  * when it is called. This default can be changed either on a
1110  * per-signal basis by calling gl_trap_signal(), or on a global basis
1111  * by calling this function. What this function does is add the
1112  * GLS_UNBLOCK_SIG flag to all signals that are currently configured
1113  * to be trapped by gl_get_line(), such that when subsequent calls to
1114  * gl_get_line() wait for I/O, these signals are temporarily
1115  * unblocked. This behavior is useful in non-blocking server-I/O mode,
1116  * where it is used to avoid race conditions related to handling these
1117  * signals externally to gl_get_line(). See the demonstration code in
1118  * demo3.c, or the gl_handle_signal() man page for further
1119  * information.
1120  *
1121  * Input:
1122  *  gl         GetLine *   The resource object of gl_get_line().
1123  */
1124 void gl_catch_blocked(GetLine *gl);
1125 
1126 /*.......................................................................
1127  * In server-I/O mode the terminal is left in raw mode between calls
1128  * to gl_get_line(), so it is necessary for the application to install
1129  * terminal restoring signal handlers for signals that could terminate
1130  * or suspend the process, plus a terminal reconfiguration handler to
1131  * be called when a process resumption signal is received, and finally
1132  * a handler to be called when a terminal-resize signal is received.
1133  *
1134  * Since there are many signals that by default terminate or suspend
1135  * processes, and different systems support different sub-sets of
1136  * these signals, this function provides a convenient wrapper around
1137  * sigaction() for assigning the specified handlers to all appropriate
1138  * signals. It also arranges that when any one of these signals is
1139  * being handled, all other catchable signals are blocked. This is
1140  * necessary so that the specified signal handlers can safely call
1141  * gl_raw_io(), gl_normal_io() and gl_update_size() without reentrancy
1142  * issues.
1143  *
1144  * Input:
1145  *  term_handler  void (*)(int)  The signal handler to invoke when
1146  *                               a process terminating signal is
1147  *                               received.
1148  *  susp_handler  void (*)(int)  The signal handler to invoke when
1149  *                               a process suspending signal is
1150  *                               received.
1151  *  cont_handler  void (*)(int)  The signal handler to invoke when
1152  *                               a process resumption signal is
1153  *                               received (ie. SIGCONT).
1154  *  size_handler  void (*)(int)  The signal handler to invoke when
1155  *                               a terminal-resize signal (ie. SIGWINCH)
1156  *                               is received.
1157  * Output:
1158  *  return                  int  0 - OK.
1159  *                               1 - Error.
1160  */
1161 int gl_tty_signals(void (*term_handler)(int), void (*susp_handler)(int),
1162 		   void (*cont_handler)(int), void (*size_handler)(int));
1163 
1164 /*.......................................................................
1165  * Return the last signal that was caught by the most recent call to
1166  * gl_get_line(), or -1 if no signals were caught. This is useful if
1167  * gl_get_line() returns errno=EINTR and you need to find out what signal
1168  * caused it to abort.
1169  *
1170  * Input:
1171  *  gl           GetLine *  The resource object of gl_get_line().
1172  * Output:
1173  *  return           int    The last signal caught by the most recent
1174  *                          call to gl_get_line(), or -1 if no signals
1175  *                          were caught.
1176  */
1177 int gl_last_signal(GetLine *gl);
1178 
1179 /*.......................................................................
1180  * Return the signal mask used by gl_get_line(). This is the set of
1181  * signals that gl_get_line() is currently configured to trap.
1182  *
1183  * Input:
1184  *  gl         GetLine *  The resource object of gl_get_line().
1185  * Input/Output:
1186  *  set       sigset_t *  The set of signals will be returned in *set,
1187  *                        in the form of a signal process mask, as
1188  *                        used by sigaction(), sigprocmask(),
1189  *                        sigpending(), sigsuspend(), sigsetjmp() and
1190  *                        other standard POSIX signal-aware
1191  *                        functions.
1192  * Output:
1193  *  return         int    0 - OK.
1194  *                        1 - Error (examine errno for reason).
1195  */
1196 int gl_list_signals(GetLine *gl, sigset_t *set);
1197 
1198 /*.......................................................................
1199  * Respond to signals who's default effects have important
1200  * consequences to gl_get_line(). This is intended for use in
1201  * non-blocking server mode, where the external event loop is
1202  * responsible for catching signals. Signals that are handled include
1203  * those that by default terminate or suspend the process, and the
1204  * signal that indicates that the terminal size has changed. Note that
1205  * this function is not signal safe and should thus not be called from
1206  * a signal handler itself. See the gl_io_mode() man page for how it
1207  * should be used.
1208  *
1209  * In the case of signals that by default terminate or suspend
1210  * processes, command-line editing will be suspended, the terminal
1211  * returned to a usable state, then the default disposition of the
1212  * signal restored and the signal resent, in order to suspend or
1213  * terminate the process.  If the process subsequently resumes,
1214  * command-line editing is resumed.
1215  *
1216  * In the case of signals that indicate that the terminal has been
1217  * resized, the new size will be queried, and any input line that is
1218  * being edited will be redrawn to fit the new dimensions of the
1219  * terminal.
1220  *
1221  * Input:
1222  *  signo    int    The number of the signal to respond to.
1223  *  gl   GetLine *  The first element of an array of 'ngl' GetLine
1224  *                  objects.
1225  *  ngl      int    The number of elements in the gl[] array. Normally
1226  *                  this will be one.
1227  */
1228 void gl_handle_signal(int signo, GetLine *gl, int ngl);
1229 
1230 /*.......................................................................
1231  * Return extra information (ie. in addition to that provided by errno)
1232  * about the last error to occur in either gl_get_line() or its
1233  * associated public functions.
1234  *
1235  * Input:
1236  *  gl         GetLine *  The resource object of gl_get_line().
1237  * Input/Output:
1238  *  buff          char *  An optional output buffer. Note that if the
1239  *                        calling application calls any gl_*()
1240  *                        functions from signal handlers, it should
1241  *                        provide a buffer here, so that a copy of
1242  *                        the latest error message can safely be made
1243  *                        while signals are blocked.
1244  *  n           size_t    The allocated size of buff[].
1245  * Output:
1246  *  return  const char *  A pointer to the error message. This will
1247  *                        be the buff argument, unless buff==NULL, in
1248  *                        which case it will be a pointer to an
1249  *                        internal error buffer. In the latter case,
1250  *                        note that the contents of the returned buffer
1251  *                        will change on subsequent calls to any gl_*()
1252  *                        functions.
1253  */
1254 const char *gl_error_message(GetLine *gl, char *buff, size_t n);
1255 
1256 /*.......................................................................
1257  * Clear the terminal and leave the cursor at the home position.  In
1258  * server I/O mode, arrange for the input line to be redrawn from scratch
1259  * when gl_get_line() is next called.
1260  *
1261  * Input:
1262  *  gl          GetLine *   The resource object of gl_get_line().
1263  * Output:
1264  *  return          int     0 - OK.
1265  *                          1 - Error.
1266  */
1267 int gl_erase_terminal(GetLine *gl);
1268 
1269 /*.......................................................................
1270  * Display a left-justified string over multiple terminal lines,
1271  * taking account of the current width of the terminal. Optional
1272  * indentation and an optional prefix string can be specified to be
1273  * displayed at the start of each new terminal line used. Similarly,
1274  * an optional suffix can be specified to be displayed at the end of
1275  * each terminal line.  If needed, a single paragraph can be broken
1276  * across multiple calls.  Note that literal newlines in the input
1277  * string can be used to force a newline at any point and that you
1278  * should use this feature to explicitly end all paragraphs, including
1279  * at the end of the last string that you write. Note that when a new
1280  * line is started between two words that are separated by spaces,
1281  * those spaces are not output, whereas when a new line is started
1282  * because a newline character was found in the string, only the
1283  * spaces before the newline character are discarded.
1284  *
1285  * Input:
1286  *  gl         GetLine *  The resource object of gl_get_line().
1287  *  indentation    int    The number of spaces of indentation to write
1288  *                        at the beginning of each new terminal line.
1289  *  prefix  const char *  An optional prefix string to write after the
1290  *                        indentation margin at the start of each new
1291  *                        terminal line. You can specify NULL if no
1292  *                        prefix is required.
1293  *  suffix  const char *  An optional suffix string to draw at the end
1294  *                        of the terminal line. Spaces will be added
1295  *                        where necessary to ensure that the suffix ends
1296  *                        in the last column of the terminal line. If
1297  *                        no suffix is desired, specify NULL.
1298  *  fill_char      int    The padding character to use when indenting
1299  *                        the line or padding up to the suffix.
1300  *  def_width      int    If the terminal width isn't known, such as when
1301  *                        writing to a pipe or redirecting to a file,
1302  *                        this number specifies what width to assume.
1303  *  start          int    The number of characters already written to
1304  *                        the start of the current terminal line. This
1305  *                        is primarily used to allow individual
1306  *                        paragraphs to be written over multiple calls
1307  *                        to this function, but can also be used to
1308  *                        allow you to start the first line of a
1309  *                        paragraph with a different prefix or
1310  *                        indentation than those specified above.
1311  *  string  const char *  The string to be written.
1312  * Output:
1313  *  return         int    On error -1 is returned. Otherwise the
1314  *                        return value is the terminal column index at
1315  *                        which the cursor was left after writing the
1316  *                        final word in the string. Successful return
1317  *                        values can thus be passed verbatim to the
1318  *                        'start' arguments of subsequent calls to
1319  *                        gl_display_text() to allow the printing of a
1320  *                        paragraph to be broken across multiple calls
1321  *                        to gl_display_text().
1322  */
1323 int gl_display_text(GetLine *gl, int indentation, const char *prefix,
1324 		    const char *suffix, int fill_char, int def_width,
1325 		    int start, const char *string);
1326 
1327 
1328 /*
1329  * Enumerate the I/O modes supported by gl_get_line().
1330  */
1331 typedef enum {
1332   GL_NORMAL_MODE,    /* Normal line-at-a-time mode using gl_get_line()'s */
1333                      /*  internal event loop. */
1334   GL_SERVER_MODE     /* Non-blocking server mode, driven by an external */
1335                      /*  event loop. */
1336 } GlIOMode;
1337 
1338 /*.......................................................................
1339  * Select the I/O mode to be used by gl_get_line().
1340  *
1341  * Input:
1342  *  gl         GetLine *         The resource object of gl_get_line().
1343  *  mode      GlIOMode           The I/O mode to establish. Note that
1344  *                               when server mode, the terminal is placed
1345  *                               in raw mode, as though gl_raw_io() had
1346  *                               been called.
1347  * Output:
1348  *  return                  int  0 - OK.
1349  *                               1 - Error.
1350  */
1351 int gl_io_mode(GetLine *gl, GlIOMode mode);
1352 
1353 /*.......................................................................
1354  * In server mode, this function configures the terminal for non-blocking
1355  * raw terminal I/O. In normal I/O mode it does nothing.
1356  *
1357  * Callers of this function must be careful to trap all signals that
1358  * terminate or suspend the program, and call gl_normal_io()
1359  * from the corresponding signal handlers in order to restore the
1360  * terminal to its original settings before the program is terminated
1361  * or suspended. They should also trap the SIGCONT signal to detect
1362  * when the program resumes, and ensure that its signal handler
1363  * call gl_raw_io() to redisplay the line and resume editing.
1364  *
1365  * Input:
1366  *  gl      GetLine *  The line editor resource object.
1367  * Output:
1368  *  return      int    0 - OK.
1369  *                     1 - Error.
1370  */
1371 int gl_raw_io(GetLine *gl);
1372 
1373 /*.......................................................................
1374  * Restore the terminal to the state that it had when gl_raw_io() was
1375  * last called. After calling gl_raw_io(), this function must be called
1376  * before terminating or suspending the program, and before attempting
1377  * other uses of the terminal from within the program. See gl_raw_io()
1378  * for more details.
1379  *
1380  * Input:
1381  *  gl      GetLine *  The line editor resource object.
1382  * Output:
1383  *  return      int    0 - OK.
1384  *                     1 - Error.
1385  */
1386 int gl_normal_io(GetLine *gl);
1387 
1388 /*.......................................................................
1389  * When in non-blocking server mode, this function can be used to abandon
1390  * the current incompletely entered input line, and prepare to start
1391  * editing a new line on the next call to gl_get_line().
1392  *
1393  * Input:
1394  *  gl      GetLine *  The line editor resource object.
1395  * Output:
1396  *  return      int    0 - OK.
1397  *                     1 - Error.
1398  */
1399 void gl_abandon_line(GetLine *gl);
1400 
1401 /*
1402  * Enumerators of the following type are used to report why
1403  * gl_get_line() returned. This is most useful in non-blocking
1404  * server mode, since in that mode a NULL return value can mean
1405  * either that an error occurred, or that I/O blocked.
1406  */
1407 typedef enum {
1408   GLR_NEWLINE,  /* A new input line was returned */
1409   GLR_BLOCKED,  /* The terminal was in non-blocking mode, and input */
1410                 /* or output would have blocked. */
1411   GLR_SIGNAL,   /* A signal caused gl_get_line() to return. */
1412   GLR_TIMEOUT,  /* An application timeout callback returned GLTO_ABORT */
1413   GLR_FDABORT,  /* An application I/O callack returned GLFD_ABORT */
1414   GLR_EOF,      /* End of file reached */
1415   GLR_ERROR     /* An unexpected error caused gl_get_line() to abort */
1416 } GlReturnStatus;
1417 
1418 /*.......................................................................
1419  * Ask gl_get_line() what caused it to return.
1420  *
1421  * Input:
1422  *  gl             GetLine *  The line editor resource object.
1423  * Output:
1424  *  return  GlReturnStatus    The return status of the last call to
1425  *                            gl_get_line().
1426  */
1427 GlReturnStatus gl_return_status(GetLine *gl);
1428 
1429 /*
1430  * Enumerate the types of I/O that gl_get_line() can be waiting for
1431  * in non-blocking sedrver I/O mode.
1432  */
1433 typedef enum {
1434   GLP_READ,   /* gl_get_line() is waiting to write to the terminal */
1435   GLP_WRITE   /* gl_get_line() is waiting to read from the terminal */
1436 } GlPendingIO;
1437 
1438 /*.......................................................................
1439  * In non-blocking server-I/O mode, this function should be called
1440  * from the application's external event loop to see what type of
1441  * terminal I/O is being waited for by gl_get_line(), and thus what
1442  * direction of I/O to wait for with select() or poll().
1443  *
1444  * Input:
1445  *  gl          GetLine *  The resource object of gl_get_line().
1446  * Output:
1447  *  return  GlPendingIO    The type of pending I/O being waited for.
1448  */
1449 GlPendingIO gl_pending_io(GetLine *gl);
1450 
1451 /*
1452  * The following enumerators are returned by externally defined action
1453  * functions to tell gl_get_line() how to procede after the action
1454  * function returns.
1455  */
1456 typedef enum {
1457   GLA_ABORT,     /* Cause gl_get_line() to return NULL */
1458   GLA_RETURN,    /* Return the line as though the user had pressed the */
1459                  /*  return key. */
1460   GLA_CONTINUE   /* Resume command-line editing */
1461 } GlAfterAction;
1462 
1463 /*.......................................................................
1464  * Functions of the following form implement external
1465  * application-specific action functions, which can then be bound to
1466  * sequences of terminal keys.
1467  *
1468  * Input:
1469  *  gl            GetLine *  The line editor resource object.
1470  *  data             void *  The anonymous 'data' argument that was
1471  *                           passed to gl_external_action() when the
1472  *                           callback function was registered.
1473  *  count             int    A positive repeat count specified by the user,
1474  *                           or 1 if not specified. Action functions should
1475  *                           ignore this if repeating the action multiple
1476  *                           times isn't appropriate. Alternatively they
1477  *                           can interpret it as a general numeric
1478  *                           argument.
1479  *  curpos         size_t    The position of the cursor within the input
1480  *                           line, expressed as the index of the
1481  *                           corresponding character within the line[]
1482  *                           array.
1483  *  line       const char *  A read-only copy of the current input line.
1484  * Output
1485  *  return  GlAfterAction    What should gl_get_line() do when the action
1486  *                           function returns?
1487  *                            GLA_ABORT    - Cause gl_get_line() to
1488  *                                           abort with an error (set
1489  *                                           errno if you need it).
1490  *                            GLA_RETURN   - Return the input line as
1491  *                                           though the user had typed
1492  *                                           the return key.
1493  *                            GLA_CONTINUE - Resume waiting for keyboard
1494  *                                           input.
1495  */
1496 #define GL_ACTION_FN(fn) GlAfterAction (fn)(GetLine *gl, void *data, \
1497 	      int count, size_t curpos, const char *line)
1498 
1499 typedef GL_ACTION_FN(GlActionFn);
1500 
1501 /*.......................................................................
1502  * Register an application-provided function as an action function.
1503  * This should preferably be called before the first call to gl_get_line()
1504  * so that the name of the action becomes defined before the user's
1505  * configuration file is read.
1506  *
1507  * Input:
1508  *  gl            GetLine *  The resource object of the command-line input
1509  *                           module.
1510  *  data             void *  Arbitrary application-specific callback
1511  *                           data to be passed to the callback
1512  *                           function, fn().
1513  *  fn         GlActionFn *  The application-specific function that
1514  *                           implements the action. This will be invoked
1515  *                           whenever the user presses any
1516  *                           key-sequence which is bound to this action.
1517  *  name       const char *  The name with which users can refer to the
1518  *                           binding in tecla configuration files.
1519  *  keyseq     const char *  The key sequence with which to invoke
1520  *                           the binding. This should be specified in the
1521  *                           same manner as key-sequences in tecla
1522  *                           configuration files (eg. "M-^I").
1523  * Output:
1524  *  return            int    0 - OK.
1525  *                           1 - Error.
1526  */
1527 int gl_register_action(GetLine *gl, void *data, GlActionFn *fn,
1528                        const char *name, const char *keyseq);
1529 
1530 /*.......................................................................
1531  * This function is designed to be called by CPL_MATCH_FN() callback
1532  * functions. It adds one possible completion of the token that is being
1533  * completed to an array of completions. If the completion needs any
1534  * special quoting to be valid when displayed in the input line, this
1535  * quoting must be included in the string.
1536  *
1537  * Input:
1538  *  cpl      WordCompletion *  The argument of the same name that was passed
1539  *                             to the calling CPL_MATCH_FN() callback function.
1540  *  line         const char *  The input line, as received by the callback
1541  *                             function.
1542  *  word_start          int    The index within line[] of the start of the
1543  *                             word that is being completed. If an empty
1544  *                             string is being completed, set this to be
1545  *                             the same as word_end.
1546  *  word_end            int    The index within line[] of the character which
1547  *                             follows the incomplete word, as received by the
1548  *                             callback function.
1549  *  suffix       const char *  The appropriately quoted string that could
1550  *                             be appended to the incomplete token to complete
1551  *                             it. A copy of this string will be allocated
1552  *                             internally.
1553  *  type_suffix  const char *  When listing multiple completions, gl_get_line()
1554  *                             appends this string to the completion to indicate
1555  *                             its type to the user. If not pertinent pass "".
1556  *                             Otherwise pass a literal or static string.
1557  *  cont_suffix  const char *  If this turns out to be the only completion,
1558  *                             gl_get_line() will append this string as
1559  *                             a continuation. For example, the builtin
1560  *                             file-completion callback registers a directory
1561  *                             separator here for directory matches, and a
1562  *                             space otherwise. If the match were a function
1563  *                             name you might want to append an open
1564  *                             parenthesis, etc.. If not relevant pass "".
1565  *                             Otherwise pass a literal or static string.
1566  * Output:
1567  *  return              int    0 - OK.
1568  *                             1 - Error.
1569  */
1570 int cpl_add_completion(WordCompletion *cpl, const char *line,
1571 		       int word_start, int word_end, const char *suffix,
1572 		       const char *type_suffix, const char *cont_suffix);
1573 
1574 /*
1575  * Each possible completion string is recorded in an array element of
1576  * the following type.
1577  */
1578 typedef struct {
1579   char *completion;        /* The matching completion string */
1580   char *suffix;            /* The pointer into completion[] at which the */
1581                            /*  string was extended. */
1582   const char *type_suffix; /* A suffix to be added when listing completions */
1583                            /*  to indicate the type of the completion. */
1584 } CplMatch;
1585 
1586 /*
1587  * Completions are returned in a container of the following form.
1588  */
1589 typedef struct {
1590   char *suffix;            /* The common initial part of all of the */
1591                            /*  completion suffixes. */
1592   const char *cont_suffix; /* Optional continuation string to be appended to */
1593                            /*  the sole completion when nmatch==1. */
1594   CplMatch *matches;       /* The array of possible completion strings, */
1595                            /*  sorted into lexical order. */
1596   int nmatch;              /* The number of elements in matches[] */
1597 } CplMatches;
1598 
1599 /*.......................................................................
1600  * Given an input line and the point at which completion is to be
1601  * attempted, return an array of possible completions.
1602  *
1603  * Input:
1604  *  cpl    WordCompletion *  The word-completion resource object.
1605  *  line       const char *  The current input line.
1606  *  word_end          int    The index of the character in line[] which
1607  *                           follows the end of the token that is being
1608  *                           completed.
1609  *  data             void *  Anonymous 'data' to be passed to match_fn().
1610  *  match_fn   CplMatchFn *  The function that will identify the prefix
1611  *                           to be completed from the input line, and
1612  *                           record completion suffixes.
1613  * Output:
1614  *  return     CplMatches *  The container of the array of possible
1615  *                           completions. The returned pointer refers
1616  *                           to a container owned by the parent Completion
1617  *                           object, and its contents thus potentially
1618  *                           change on every call to cpl_complete_word().
1619  */
1620 CplMatches *cpl_complete_word(WordCompletion *cpl, const char *line,
1621 			      int word_end, void *data,
1622 			      CplMatchFn *match_fn);
1623 
1624 /*.......................................................................
1625  * Recall the return value of the last call to cpl_complete_word().
1626  *
1627  * Input:
1628  *  cpl    WordCompletion *  The completion resource object.
1629  * Output:
1630  *  return     CplMatches *  The container of the array of possible
1631  *                           completions, as returned by the last call to
1632  *                           cpl_complete_word(). The returned pointer refers
1633  *                           to a container owned by the parent WordCompletion
1634  *                           object, and its contents thus potentially
1635  *                           change on every call to cpl_complete_word().
1636  *                           On error, either in the execution of this
1637  *                           function, or in the last call to
1638  *                           cpl_complete_word(), NULL is returned, and a
1639  *                           description of the error can be acquired by
1640  *                           calling cpl_last_error(cpl).
1641  */
1642 CplMatches *cpl_recall_matches(WordCompletion *cpl);
1643 
1644 /*.......................................................................
1645  * Print out an array of matching completions.
1646  *
1647  * Input:
1648  *  result  CplMatches *   The container of the sorted array of
1649  *                         completions.
1650  *  fp            FILE *   The output stream to write to.
1651  *  term_width     int     The width of the terminal.
1652  * Output:
1653  *  return         int     0 - OK.
1654  *                         1 - Error.
1655  */
1656 int cpl_list_completions(CplMatches *result, FILE *fp, int term_width);
1657 
1658 /*.......................................................................
1659  * Return a description of the error that occurred on the last call to
1660  * cpl_complete_word() or cpl_add_completion().
1661  *
1662  * Input:
1663  *  cpl   WordCompletion *  The string-completion resource object.
1664  * Output:
1665  *  return    const char *  The description of the last error.
1666  */
1667 const char *cpl_last_error(WordCompletion *cpl);
1668 
1669 /*
1670  * PathCache objects encapsulate the resources needed to record
1671  * files of interest from comma-separated lists of directories.
1672  */
1673 typedef struct PathCache PathCache;
1674 
1675 /*.......................................................................
1676  * Create an object who's function is to maintain a cache of filenames
1677  * found within a list of directories, and provide quick lookup and
1678  * completion of selected files in this cache.
1679  *
1680  * Output:
1681  *  return     PathCache *  The new, initially empty cache, or NULL
1682  *                          on error.
1683  */
1684 PathCache *new_PathCache(void);
1685 
1686 /*.......................................................................
1687  * Delete a given cache of files, returning the resources that it
1688  * was using to the system.
1689  *
1690  * Input:
1691  *  pc      PathCache *  The cache to be deleted (can be NULL).
1692  * Output:
1693  *  return  PathCache *  The deleted object (ie. allways NULL).
1694  */
1695 PathCache *del_PathCache(PathCache *pc);
1696 
1697 /*.......................................................................
1698  * Return a description of the last path-caching error that occurred.
1699  *
1700  * Input:
1701  *  pc     PathCache *   The filename cache that suffered the error.
1702  * Output:
1703  *  return      char *   The description of the last error.
1704  */
1705 const char *pca_last_error(PathCache *pc);
1706 
1707 /*.......................................................................
1708  * Build the list of files of interest contained in a given
1709  * colon-separated list of directories.
1710  *
1711  * Input:
1712  *  pc         PathCache *  The cache in which to store the names of
1713  *                          the files that are found in the list of
1714  *                          directories.
1715  *  path      const char *  A colon-separated list of directory
1716  *                          paths. Under UNIX, when searching for
1717  *                          executables, this should be the return
1718  *                          value of getenv("PATH").
1719  * Output:
1720  *  return           int    0 - OK.
1721  *                          1 - An error occurred.
1722  */
1723 int pca_scan_path(PathCache *pc, const char *path);
1724 
1725 /*.......................................................................
1726  * If you want subsequent calls to pca_lookup_file() and
1727  * pca_path_completions() to only return the filenames of certain
1728  * types of files, for example executables, or filenames ending in
1729  * ".ps", call this function to register a file-selection callback
1730  * function. This callback function takes the full pathname of a file,
1731  * plus application-specific data, and returns 1 if the file is of
1732  * interest, and zero otherwise.
1733  *
1734  * Input:
1735  *  pc         PathCache *  The filename cache.
1736  *  check_fn  CplCheckFn *  The function to call to see if the name of
1737  *                          a given file should be included in the
1738  *                          cache. This determines what type of files
1739  *                          will reside in the cache. To revert to
1740  *                          selecting all files, regardless of type,
1741  *                          pass 0 here.
1742  *  data            void *  You can pass a pointer to anything you
1743  *                          like here, including NULL. It will be
1744  *                          passed to your check_fn() callback
1745  *                          function, for its private use.
1746  */
1747 void pca_set_check_fn(PathCache *pc, CplCheckFn *check_fn, void *data);
1748 
1749 /*.......................................................................
1750  * Given the simple name of a file, search the cached list of files
1751  * in the order in which they where found in the list of directories
1752  * previously presented to pca_scan_path(), and return the pathname
1753  * of the first file which has this name.
1754  *
1755  * Input:
1756  *  pc     PathCache *  The cached list of files.
1757  *  name  const char *  The name of the file to lookup.
1758  *  name_len     int    The length of the filename substring at the
1759  *                      beginning of name[], or -1 to assume that the
1760  *                      filename occupies the whole of the string.
1761  *  literal      int    If this argument is zero, lone backslashes
1762  *                      in name[] are ignored during comparison
1763  *                      with filenames in the cache, under the
1764  *                      assumption that they were in the input line
1765  *                      soley to escape the special significance of
1766  *                      characters like spaces. To have them treated
1767  *                      as normal characters, give this argument a
1768  *                      non-zero value, such as 1.
1769  * Output:
1770  *  return      char *  The pathname of the first matching file,
1771  *                      or NULL if not found. Note that the returned
1772  *                      pointer points to memory owned by *pc, and
1773  *                      will become invalid on the next call.
1774  */
1775 char *pca_lookup_file(PathCache *pc, const char *name, int name_len,
1776 		      int literal);
1777 
1778 /*
1779  * Objects of the following type can be used to change the default
1780  * behavior of the pca_path_completions() callback function.
1781  */
1782 typedef struct PcaPathConf PcaPathConf;
1783 
1784 /*
1785  * pca_path_completions() is a completion callback function for use directly
1786  * with cpl_complete_word() or gl_customize_completions(), or indirectly
1787  * from your own completion callback function. It requires that a PcaPathConf
1788  * object be passed via its 'void *data' argument (see below).
1789  */
1790 CPL_MATCH_FN(pca_path_completions);
1791 
1792 /*.......................................................................
1793  * Allocate and initialize a pca_path_completions() configuration object.
1794  *
1795  * Input:
1796  *  pc         PathCache *  The filename cache in which to look for
1797  *                          file name completions.
1798  * Output:
1799  *  return   PcaPathConf *  The new configuration structure, or NULL
1800  *                          on error.
1801  */
1802 PcaPathConf *new_PcaPathConf(PathCache *pc);
1803 
1804 /*.......................................................................
1805  * Deallocate memory, previously allocated by new_PcaPathConf().
1806  *
1807  * Input:
1808  *  ppc     PcaPathConf *  Any pointer previously returned by
1809  *                         new_PcaPathConf() [NULL is allowed].
1810  * Output:
1811  *  return  PcaPathConf *  The deleted structure (always NULL).
1812  */
1813 PcaPathConf *del_PcaPathConf(PcaPathConf *ppc);
1814 
1815 /*
1816  * If backslashes in the prefix being passed to pca_path_completions()
1817  * should be treated as literal characters, call the following function
1818  * with literal=1. Otherwise the default is to treat them as escape
1819  * characters which remove the special meanings of spaces etc..
1820  */
1821 void ppc_literal_escapes(PcaPathConf *ppc, int literal);
1822 
1823 /*
1824  * Before calling pca_path_completions, call this function if you know
1825  * the index at which the filename prefix starts in the input line.
1826  * Otherwise by default, or if you specify start_index to be -1, the
1827  * filename is taken to start after the first unescaped space preceding
1828  * the cursor, or the start of the line, whichever comes first.
1829  */
1830 void ppc_file_start(PcaPathConf *ppc, int start_index);
1831 
1832 #ifdef __cplusplus
1833 }
1834 #endif
1835 
1836 #endif
1837