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