1gl_get_line(3TECILnAt)eractive Command-line Input Library Functigoln_sget_line(3TECLA)


6       gl_get_line,    new_GetLine,    del_GetLine,   gl_customize_completion,
7       gl_change_terminal, gl_configure_getline, gl_load_history, gl_save_his‐
8       tory,   gl_group_history,   gl_show_history,  gl_watch_fd,  gl_inactiv‐
9       ity_timeout,  gl_terminal_size,  gl_set_term_size,   gl_resize_history,
10       gl_limit_history,  gl_clear_history,  gl_toggle_history, gl_lookup_his‐
11       tory,  gl_state_of_history,  gl_range_of_history,   gl_size_of_history,
12       gl_echo_mode,   gl_replace_prompt,  gl_prompt_style,  gl_ignore_signal,
13       gl_trap_signal,   gl_last_signal,    gl_completion_action,    gl_regis‐
14       ter_action,    gl_display_text,   gl_return_status,   gl_error_message,
15       gl_catch_blocked, gl_list_signals,  gl_bind_keyseq,  gl_erase_terminal,
16       gl_automatic_history,  gl_append_history, gl_query_char, gl_read_char -
17       allow the user to compose an input line


20       cc [ flag... ] file... -ltecla [ library... ]
21       #include <stdio.h>
22       #include <libtecla.h>
24       GetLine *new_GetLine(size_t linelen, size_t histlen);
27       GetLine *del_GetLine(GetLine *gl);
30       char *gl_get_line(GetLine *gl, const char *prompt,
31            const char *start_line, int start_pos);
34       int gl_query_char(GetLine *gl, const char *prompt, char defchar);
37       int gl_read_char(GetLine *gl);
40       int gl_customize_completion(GetLine *gl, void *data,
41            CplMatchFn *match_fn);
44       int gl_change_terminal(GetLine *gl, FILE *input_fp,
45            FILE *output_fp, const char *term);
48       int gl_configure_getline(GetLine *gl, const char *app_string,
49            const char *app_file, const char *user_file);
52       int gl_bind_keyseq(GetLine *gl, GlKeyOrigin origin,
53            const char *keyseq, const char *action);
56       int gl_save_history(GetLine *gl, const char *filename,
57            const char *comment, int max_lines);
60       int gl_load_history(GetLine *gl, const char *filename,
61            const char *comment);
64       int gl_watch_fd(GetLine *gl, int fd, GlFdEvent event,
65            GlFdEventFn *callback, void *data);
68       int gl_inactivity_timeout(GetLine *gl, GlTimeoutFn *callback,
69            void *data, unsigned long sec, unsigned long nsec);
72       int gl_group_history(GetLine *gl, unsigned stream);
75       int gl_show_history(GetLine *gl, FILE *fp, const char *fmt,
76            int all_groups, int max_lines);
79       int gl_resize_history(GetLine *gl, size_t bufsize);
82       void gl_limit_history(GetLine *gl, int max_lines);
85       void gl_clear_history(GetLine *gl, int all_groups);
88       void gl_toggle_history(GetLine *gl, int enable);
91       GlTerminalSize gl_terminal_size(GetLine *gl, int def_ncolumn,
92            int def_nline);
95       int gl_set_term_size(GetLine *gl, int ncolumn, int nline);
98       int gl_lookup_history(GetLine *gl, unsigned long id,
99            GlHistoryLine *hline);
102       void gl_state_of_history(GetLine *gl, GlHistoryState *state);
105       void gl_range_of_history(GetLine *gl, GlHistoryRange *range);
108       void gl_size_of_history(GetLine *gl, GlHistorySize *size);
111       void gl_echo_mode(GetLine *gl, int enable);
114       void gl_replace_prompt(GetLine *gl, const char *prompt);
117       void gl_prompt_style(GetLine *gl, GlPromptStyle style);
120       int gl_ignore_signal(GetLine *gl, int signo);
123       int gl_trap_signal(GetLine *gl, int signo, unsigned flags,
124            GlAfterSignal after, int errno_value);
127       int gl_last_signal(GetLine *gl);
130       int gl_completion_action(GetLine *gl, void *data,
131            CplMatchFn *match_fn, int list_only, const char *name,
132            const char *keyseq);
135       int gl_register_action(GetLine *gl, void *data, GlActionFn *fn,
136            const char *name, const char *keyseq);
139       int gl_display_text(GetLine *gl, int indentation,
140            const char *prefix, const char *suffix, int fill_char,
141            int def_width, int start, const char *string);
144       GlReturnStatus gl_return_status(GetLine *gl);
147       const char *gl_error_message(GetLine *gl, char *buff, size_t n);
150       void gl_catch_blocked(GetLine *gl);
153       int gl_list_signals(GetLine *gl, sigset_t *set);
156       int gl_append_history(GetLine *gl, const char *line);
159       int gl_automatic_history(GetLine *gl, int enable);
162       int gl_erase_terminal(GetLine *gl);


166       The gl_get_line() function is part of the  libtecla(3LIB)  library.  If
167       the user is typing at a terminal, each call prompts them for an line of
168       input, then provides interactive editing facilities, similar  to  those
169       of  the UNIX tcsh shell. In addition to simple command-line editing, it
170       supports recall of previously entered command lines, TAB completion  of
171       file names, and in-line wild-card expansion of filenames. Documentation
172       of both the user-level command-line editing features and all user  con‐
173       figuration options can be found on the tecla(5) manual page.
175   An Example
176       The  following shows a complete example of how to use the gl_get_line()
177       function to get input from the user:
179         #include <stdio.h>
180         #include <locale.h>
181         #include <libtecla.h>
183         int main(int argc, char *argv[])
184         {
185           char *line;    /* The line that the user typed */
186           GetLine *gl;   /* The gl_get_line() resource object */
188           setlocale(LC_CTYPE, ""); /* Adopt the user's choice */
189                                    /* of character set. */
191           gl = new_GetLine(1024, 2048);
192           if(!gl)
193             return 1;
194           while((line=gl_get_line(gl, "$ ", NULL, -1)) != NULL &&
195                  strcmp(line, "exit\n") != 0)
196             printf("You typed: %s\n", line);
198           gl = del_GetLine(gl);
199           return 0;
200         }
204       In the example, first the resources needed by the  gl_get_line()  func‐
205       tion  are  created  by calling new_GetLine(). This allocates the memory
206       used in subsequent calls to the gl_get_line() function,  including  the
207       history buffer for recording previously entered lines. Then one or more
208       lines are read from the user, until either an error occurs, or the user
209       types  exit. Then finally the resources that were allocated by new_Get‐
210       Line(), are returned to the system by calling del_GetLine().  Note  the
211       use  of the NULL return value of del_GetLine() to make gl NULL. This is
212       a safety precaution. If the program subsequently attempts to pass gl to
213       gl_get_line(),  said  function  will  complain,  and  return  an error,
214       instead of attempting to use the deleted resource object.
216   The Functions Used In The Example
217       The  new_GetLine()  function  creates  the  resources   used   by   the
218       gl_get_line() function and returns an opaque pointer to the object that
219       contains them. The maximum length of an input line is specified by  the
220       linelen  argument, and the number of bytes to allocate for storing his‐
221       tory lines is set by the histlen argument.  History  lines  are  stored
222       back-to-back in a single buffer of this size. Note that this means that
223       the number of history lines that can  be  stored  at  any  given  time,
224       depends on the lengths of the individual lines. If you want to place an
225       upper limit on the number of lines that can be stored, see the descrip‐
226       tion  of the gl_limit_history() function. If you do not want history at
227       all, specify histlen as zero, and no history buffer will be allocated.
230       On error, a message is printed to stderr and NULL is returned.
233       The del_GetLine() function deletes the resources that were returned  by
234       a  previous call to new_GetLine(). It always returns NULL (for example,
235       a deleted object). It does nothing if the gl argument is NULL.
238       The gl_get_line() function can be called any number of  times  to  read
239       input from the user. The gl argument must have been previously returned
240       by a call to new_GetLine(). The prompt  argument  should  be  a  normal
241       null-terminated string, specifying the prompt to present the user with.
242       By default prompts are displayed literally, but  if  enabled  with  the
243       gl_prompt_style() function, prompts can contain directives to do under‐
244       lining, switch to and from bold fonts, or turn highlighting on and off.
247       If you want to specify the initial contents of the line for the user to
248       edit,  pass  the  desired  string with the start_line argument. You can
249       then specify which character of this line the cursor is initially posi‐
250       tioned  over  by using the start_pos argument. This should be -1 if you
251       want the cursor to follow the last character of the start line. If  you
252       do  not  want  to  preload  the line in this manner, send start_line as
253       NULL, and set start_pos to -1.
256       The gl_get_line() function returns a pointer to the line entered by the
257       user, or NULL on error or at the end of the input. The returned pointer
258       is part of the specified gl resource object, and  thus  should  not  be
259       freed  by  the caller, or assumed to be unchanging from one call to the
260       next. When reading from a user at a terminal, there will  always  be  a
261       newline  character at the end of the returned line. When standard input
262       is being taken from a pipe or a file, there will similarly be a newline
263       unless  the input line was too long to store in the internal buffer. In
264       the latter case you should call gl_get_line() again to read the rest of
265       the  line.  Note  that  this  behavior  makes  gl_get_line() similar to
266       fgets(3C). When stdin is not connected  to  a  terminal,  gl_get_line()
267       simply calls fgets().
269   The Return Status Of gl_get_line()
270       The gl_get_line() function has two possible return values: a pointer to
271       the completed input line, or NULL. Additional  information  about  what
272       caused  gl_get_line()  to  return is available both by inspecting errno
273       and by calling the gl_return_status() function.
276       The  following  are  the  possible  enumerated   values   returned   by
277       gl_return_status():
279       GLR_NEWLINE    The  last  call to gl_get_line() successfully returned a
280                      completed input line.
283       GLR_BLOCKED    The gl_get_line() function was  in  non-blocking  server
284                      mode,  and  returned early to avoid blocking the process
285                      while waiting  for  terminal  I/O.  The  gl_pending_io()
286                      function   can   be   used  to  see  what  type  of  I/O
287                      gl_get_line()    was    waiting     for.     See     the
288                      gl_io_mode(3TECLA).
291       GLR_SIGNAL     A  signal was caught by gl_get_line() that had an after-
292                      signal disposition of GLS_ABORT. See gl_trap_signal().
295       GLR_TIMEOUT    The inactivity timer  expired  while  gl_get_line()  was
296                      waiting  for  input,  and  the timeout callback function
297                      returned  GLTO_ABORT.  See  gl_inactivity_timeout()  for
298                      information about timeouts.
301       GLR_FDABORT    An  application  I/O  callback returned GLFD_ABORT. Ssee
302                      gl_watch_fd().
305       GLR_EOF        End of file reached. This can happen when input is  com‐
306                      ing  from  a file or a pipe, instead of the terminal. It
307                      also occurs if the user invokes the list-or-eof or  del-
308                      char-or-list-or-eof actions at the start of a new line.
311       GLR_ERROR      An  unexpected error caused gl_get_line() to abort (con‐
312                      sult errno and/or gl_error_message() for details.
316       When gl_return_status() returns GLR_ERROR and the value of errno is not
317       sufficient to explain what happened, you can use the gl_error_message()
318       function to request a description of the last error that occurred.
321       The return value of gl_error_message() is a pointer to the message that
322       occurred.  If  the  buff  argument is NULL, this will be a pointer to a
323       buffer within gl whose value will probably change on the next  call  to
324       any  function  associated  with gl_get_line(). Otherwise, if a non-null
325       buff argument is provided, the error message, including a '\0' termina‐
326       tor,  will  be  written within the first n elements of this buffer, and
327       the return value will be a pointer to the first element of this buffer.
328       If  the  message  will not fit in the provided buffer, it will be trun‐
329       cated to fit.
331   Optional Prompt Formatting
332       Whereas by default the prompt string that you specify is displayed lit‐
333       erally  without any special interpretation of the characters within it,
334       the gl_prompt_style() function can be used to enable  optional  format‐
335       ting directives within the prompt.
338       The  style argument, which specifies the formatting style, can take any
339       of the following values:
341       GL_FORMAT_PROMPT     In this style, the formatting directives described
342                            below, when included in prompt strings, are inter‐
343                            preted as follows:
345                            %B    Display subsequent characters  with  a  bold
346                                  font.
349                            %b    Stop  displaying  characters  with  the bold
350                                  font.
353                            %F    Make subsequent characters flash.
356                            %f    Turn off flashing characters.
359                            %U    Underline subsequent characters.
362                            %u    Stop underlining characters.
365                            %P    Switch to a pale (half brightness) font.
368                            %p    Stop using the pale font.
371                            %S    Highlight subsequent characters (also  known
372                                  as standout mode).
375                            %s    Stop highlighting characters.
378                            %V    Turn on reverse video.
381                            %v    Turn off reverse video.
384                            %%    Display a single % character.
386                            For  example,  in  this mode, a prompt string like
387                            "%UOK%u$" would display the prompt "OK$", but with
388                            the OK part underlined.
390                            Note  that  although  a  pair  of  characters that
391                            starts with a % character, but does not match  any
392                            of the above directives is displayed literally, if
393                            a new directive is subsequently  introduced  which
394                            does  match,  the displayed prompt will change, so
395                            it is better to always use %% to display a literal
396                            %.
398                            Also  note  that  not all terminals support all of
399                            these text attributes, and that some substitute  a
400                            different attribute for missing ones.
403       GL_LITERAL_PROMPT    In this style, the prompt string is printed liter‐
404                            ally. This is the default style.
407   Alternate Configuration Sources
408       By default users  have  the  option  of  configuring  the  behavior  of
409       gl_get_line()  with  a configuration file called .teclarc in their home
410       directories. The fact that all applications share this same  configura‐
411       tion  file is both an advantage and a disadvantage. In most cases it is
412       an advantage, since it encourages uniformity, and frees the  user  from
413       having  to configure each application separately. In some applications,
414       however, this single means of configuration is a problem. This is  par‐
415       ticularly  true  of  embedded  software, where there's no filesystem to
416       read a configuration file from, and also in applications where a  radi‐
417       cally  different  choice  of  keybindings is needed to emulate a legacy
418       keyboard interface. To cater for such cases, the gl_configure_getline()
419       function allows the application to control where configuration informa‐
420       tion is read from.
423       The gl_configure_getline() function allows the  configuration  commands
424       that  would  normally be read from a user's ~/.teclarc file, to be read
425       from any or none of, a string, an  application  specific  configuration
426       file,  and/or  a  user-specific configuration file. If this function is
427       called before the first call to gl_get_line(), the default behavior  of
428       reading  ~/.teclarc  on the first call to gl_get_line() is disabled, so
429       all configurations must be achieved  using  the  configuration  sources
430       specified with this function.
433       If  app_string  !=  NULL, then it is interpreted as a string containing
434       one or more configuration commands, separated from each  other  in  the
435       string  by embedded newline  characters. If app_file != NULL then it is
436       interpreted as the full pathname of an application-specific  configura‐
437       tion file. If user_file != NULL then it is interpreted as the full path
438       name of a user-specific configuration file,  such  as  ~/.teclarc.  For
439       example, in the call
441         gl_configure_getline(gl, "edit-mode vi nobeep",
442                              "/usr/share/myapp/teclarc", "~/.teclarc");
446       The  app_string  argument  causes  the  calling application to start in
447       vi(1) edit-mode, instead of the default emacs mode, and turns  off  the
448       use  of the terminal bell by the library. It then attempts to read sys‐
449       tem-wide  configuration  commands  from   an   optional   file   called
450       /usr/share/myapp/teclarc,  then  finally reads user-specific configura‐
451       tion commands from an optional .teclarc file in the user's home  direc‐
452       tory.  Note  that the arguments are listed in ascending order of prior‐
453       ity, with the contents of app_string being potentially  over  riden  by
454       commands  in app_file, and commands in app_file potentially being over‐
455       riden by commands in user_file.
458       You can call this function as many times as needed, the  results  being
459       cumulative,  but  note that copies of any file names specified with the
460       app_file and user_file arguments are recorded internally for subsequent
461       use by the read-init-files key-binding function, so if you plan to call
462       this function multiple times, be sure that the last call specifies  the
463       filenames that you want re-read when the user requests that the config‐
464       uration files be re-read.
467       Individual key sequences can  also  be  bound  and  unbound  using  the
468       gl_bind_keyseq()  function.  The origin argument specifies the priority
469       of the binding, according to whom it is being established for, and must
470       be one of the following two values.
472       GL_USER_KEY    The user requested this key-binding.
475       GL_APP_KEY     This is a default binding set by the application.
479       When  both  user and application bindings for a given key sequence have
480       been specified, the user binding takes  precedence.  The  application's
481       binding  is  subsequently  reinstated  if  the  user's binding is later
482       unbound with either another call to this function, or a call to gl_con‐
483       figure_getline().
486       The  keyseq argument specifies the key sequence to be bound or unbound,
487       and is expressed in the same way as in a ~/.teclarc configuration file.
488       The  action argument must either be a string containing the name of the
489       action to bind the key sequence to, or it must be NULL or "" to  unbind
490       the key sequence.
492   Customized Word Completion
493       If  in  your application you would like to have TAB completion complete
494       other things in addition to or instead of filenames,  you  can  arrange
495       this  by  registering  an alternate completion callback function with a
496       call to the gl_customize_completion() function.
499       The data argument provides a way for your  application  to  pass  arbi‐
500       trary,  application-specific information to the callback function. This
501       is passed to the callback every time that it is called.  It  might  for
502       example  point  to the symbol table from which possible completions are
503       to be sought. The match_fn argument specifies the callback function  to
504       be  called. The CplMatchFn function type is defined in <libtecla.h>, as
505       is a CPL_MATCH_FN() macro that you can use  to  declare  and  prototype
506       callback  functions.  The  declaration and responsibilities of callback
507       functions are described in depth on the cpl_complete_word(3TECLA)  man‐
508       ual page.
511       The callback function is responsible for looking backwards in the input
512       line from the point at which the user pressed TAB, to find the start of
513       the  word  being completed. It then must lookup possible completions of
514       this word, and record them one by one in the WordCompletion object that
515       is  passed  to  it  as an argument, by calling the cpl_add_completion()
516       function. If the callback function wants to provide filename completion
517       in  addition  to  its  own  specific  completions, it has the option of
518       itself calling the builtin filename completion callback. This  also  is
519       documented on the cpl_complete_word(3TECLA) manual page.
522       If you would like gl_get_line() to return the current input line when a
523       successful completion is been made, you can arrange this when you  call
524       cpl_add_completion()  by  making the last character of the continuation
525       suffix a newline character. The input line will be updated  to  display
526       the  completion, together with any contiuation suffix up to the newline
527       character, and gl_get_line() will return this input line.
530       If your callback function needs to write something to the terminal,  it
531       must  call  gl_normal_io()  before doing so. This will start a new line
532       after the input line that is currently being edited,  reinstate  normal
533       terminal I/O, and notify gl_get_line() that the input line will need to
534       be redrawn when the callback returns.
536   Adding Completion Actions
537       In the previous section the ability to customize the  behavior  of  the
538       only  default  completion action, complete-word, was described. In this
539       section the ability to install additional  action  functions,  so  that
540       different  types  of  word  completion  can  be  bound to different key
541       sequences, is described. This  is  achieved  by  using  the  gl_comple‐
542       tion_action() function.
545       The  data  and  match_fn  arguments  are  as  described on the cpl_com‐
546       plete_word(3TECLA) manual page, and specify the callback function  that
547       should be invoked to identify possible completions. The list_only argu‐
548       ment determines whether the action that is being defined should attempt
549       to  complete  the word as far as possible in the input line before dis‐
550       playing any possible ambiguous completions, or whether it should simply
551       display  the  list  of  possible completions without touching the input
552       line. The former option is selected by specifying a value of 0, and the
553       latter by specifying a value of 1. The name argument specifies the name
554       by which configuration files and future invocations  of  this  function
555       should refer to the action. This must either be the name of an existing
556       completion action to be changed, or be a new  unused  name  for  a  new
557       action. Finally, the keyseq argument specifies the default key sequence
558       to bind the action to. If this is NULL, no new  key  sequence  will  be
559       bound to the action.
562       Beware that in order for the user to be able to change the key sequence
563       that is bound to actions that are installed in this manner, you should‐
564       call  gl_completion_action()  to  install  a given action for the first
565       time between calling new_GetLine() and the first call to gl_get_line().
566       Otherwise, when the user's configuration file is read on the first call
567       to gl_get_line(), the name of the your additional action  will  not  be
568       known,  and any reference to it in the configuration file will generate
569       an error.
572       As discussed for gl_customize_completion(), if your  callback  function
573       needs  to  write  anything to the terminal, it must call gl_normal_io()
574       before doing so.
576   Defining Custom Actions
577       Although the built-in key-binding actions are sufficient for the  needs
578       of  most  applications, occasionally a specialized application may need
579       to define one or more custom actions, bound to application-specific key
580       sequences. For example, a sales application would benefit from having a
581       key sequence that displayed the part name that corresponded to  a  part
582       number preceding the cursor. Such a feature is clearly beyond the scope
583       of the built-in action  functions.  So  for  such  special  cases,  the
584       gl_register_action() function is provided.
587       The  gl_register_action()  function  lets  the  application register an
588       external function, fn, that will thereafter be called  whenever  either
589       the specified key sequence, keyseq, is entered by the user, or the user
590       enters any other key sequence that the user subsequently binds  to  the
591       specified  action  name,  name,  in  their configuration file. The data
592       argument can be a pointer to anything that  the  application  wants  to
593       have  passed  to  the  action  function,  fn, whenever that function is
594       invoked.
597       The action function, fn, should be declared  using  the  GL_ACTION_FN()
598       macro, which is defined in <libtecla.h>.
600         #define GL_ACTION_FN(fn) GlAfterAction (fn)(GetLine *gl, \
601                                void *data, int count, size_t curpos, \
602                                const char *line)
606       The  gl  and  data  arguments  are those that were previously passed to
607       gl_register_action() when the action function was registered. The count
608       argument  is a numeric argument which the user has the option of enter‐
609       ing using the digit-argument action, before invoking the action. If the
610       user does not enter a number, then the count argument is set to 1. Nom‐
611       inally this argument is interpreted as a repeat count, meaning that the
612       action  should  be  repeated  that many times. In practice however, for
613       some actions a repeat count makes little sense. In such cases,  actions
614       can  either  simply  ignore  the count argument, or use its value for a
615       different purpose.
618       A copy of the current input line is passed in the read-only line  argu‐
619       ment.  The  current  cursor position within this string is given by the
620       index contained in the curpos argument. Note that  direct  manipulation
621       of  the input line and the cursor position is not permitted because the
622       rules dictated by various modes (such as vi mode versus emacs mode, no-
623       echo  mode, and insert mode versus overstrike mode) make it too complex
624       for an application writer to write a conforming editing action, as well
625       as constrain future changes to the internals of gl_get_line(). A poten‐
626       tial solution to this dilemma would be to allow the action function  to
627       edit  the  line  using  the existing editing actions. This is currently
628       under consideration.
631       If the action function wishes to write text  to  the  terminal  without
632       this  getting  mixed  up  with the displayed text of the input line, or
633       read from the terminal without having to handle raw terminal I/O,  then
634       before  doing  either  of these operations, it must temporarily suspend
635       line editing by calling  the  gl_normal_io()  function.  This  function
636       flushes  any  pending  output  to the terminal, moves the cursor to the
637       start of the line that follows the last  terminal  line  of  the  input
638       line,  then  restores  the terminal to a state that is suitable for use
639       with the C stdio facilities. The latter includes such things as restor‐
640       ing the normal mapping of \n to \r\n, and, when in server mode, restor‐
641       ing the normal blocking form of terminal I/O. Having called this  func‐
642       tion, the action function can read from and write to the terminal with‐
643       out the fear of creating a mess. It is not  necessary  for  the  action
644       function to restore the original editing environment before it returns.
645       This is done automatically by gl_get_line() after the  action  function
646       returns.  The following is a simple example of an action function which
647       writes the sentence "Hello world" on a new terminal line after the line
648       being  edited. When this function returns, the input line is redrawn on
649       the line that follows the "Hello world" line, and line editing resumes.
651         static GL_ACTION_FN(say_hello_fn)
652         {
653             if(gl_normal_io(gl))   /* Temporarily suspend editing */
654                 return GLA_ABORT;
655             printf("Hello world\n");
656             return GLA_CONTINUE;
657         }
661       Action functions must return one  of  the  following  values,  to  tell
662       gl_get_line() how to proceed.
664       GLA_ABORT       Cause gl_get_line() to return NULL.
667       GLA_RETURN      Cause gl_get_line() to return the completed input line
670       GLA_CONTINUE    Resume command-line editing.
674       Note  that the name argument of gl_register_action() specifies the name
675       by which a user can refer to the action in  their  configuration  file.
676       This allows them to re-bind the action to an alternate key-seqeunce. In
677       order for this to work, it is necessary  to  call  gl_register_action()
678       between calling new_GetLine() and the first call to gl_get_line().
680   History Files
681       To  save the contents of the history buffer before quitting your appli‐
682       cation and subsequently restore them when you next start  the  applica‐
683       tion,  the  gl_save_history()  and gl_load_history() functions are pro‐
684       vided.
687       The filename argument specifies the name to give the history file  when
688       saving, or the name of an existing history file, when loading. This may
689       contain home directory and environment variable  expressions,  such  as
690       ~/.myapp_history or $HOME/.myapp_history.
693       Along  with each history line, additional information about it, such as
694       its nesting level and when it was entered by the user, is recorded as a
695       comment  preceding the line in the history file. Writing this as a com‐
696       ment allows the history file to double as a command file, just in  case
697       you  wish  to  replay  a whole session using it. Since comment prefixes
698       differ in different languages, the comment  argument  is  provided  for
699       specifying  the comment prefix. For example, if your application were a
700       UNIX  shell, such as the Bourne shell,  you  would  specify  "#"  here.
701       Whatever  you  choose  for  the comment character, you must specify the
702       same  prefix  to  gl_load_history()  that  you  used  when  you  called
703       gl_save_history() to write the history file.
706       The  max_lines  argument must be either -1 to specify that all lines in
707       the history list be saved, or a positive number specifying a ceiling on
708       how many of the most recent lines should be saved.
711       Both  fuctions return non-zero on error, after writing an error message
712       to stderr. Note that gl_load_history() does not consider the  non-exis‐
713       tence of a file to be an error.
715   Multiple History Lists
716       If your application uses a single GetLine object for entering many dif‐
717       ferent types of input lines, you might want  gl_get_line()  to  distin‐
718       guish the different types of lines in the history list, and only recall
719       lines that match the current type of line. To support this requirement,
720       gl_get_line()  marks  lines  being recorded in the history list with an
721       integer identifier chosen by the application. Initially this identifier
722       is  set  to  0  by new_GetLine(), but it can be changed subsequently by
723       calling gl_group_history().
726       The integer identifier ID can be any number chosen by the  application,
727       but  note  that  gl_save_history()  and  gl_load_history() preserve the
728       association between identifiers and historical input lines between pro‐
729       gram  invocations,  so you should choose fixed identifiers for the dif‐
730       ferent types of input line used by your application.
733       Whenever gl_get_line() appends a new input line to  the  history  list,
734       the  current  history  identifier  is  recorded with it, and when it is
735       asked to recall a historical input line, it only recalls lines that are
736       marked with the current identifier.
738   Displaying History
739       The  history  list  can be displayed by calling gl_show_history(). This
740       function displays the current contents of the history list to the stdio
741       output stream fp. If the max_lines argument is greater than or equal to
742       zero, then no more than this number of  the most recent lines  will  be
743       displayed.  If the all_groups argument is non-zero, lines from all his‐
744       tory groups are  displayed.  Otherwise  only  those  of  the  currently
745       selected  history group are displayed. The format string argument, fmt,
746       determines how the line is displayed. This can contain arbitrary  char‐
747       acters  which are written verbatim, interleaved with any of the follow‐
748       ing format directives:
750       %D    The date on which the line was originally entered, formatted like
751             2001-11-20.
754       %T    The  time  of  day  when  the  line  was  entered, formatted like
755             23:59:59.
758       %N    The sequential entry number of the line in the history buffer.
761       %G    The number of the history group which the line belongs to.
764       %%    A literal % character.
767       %H    The history line itself.
771       Thus a format string like "%D %T %H0" would output something like:
773         2001-11-20 10:23:34  Hello world
777       Note the inclusion of an  explicit  newline  character  in  the  format
778       string.
780   Looking Up History
781       The gl_lookup_history() function allows the calling application to look
782       up lines in the history list.
785       The id argument indicates which line to look up, where the  first  line
786       that  was entered in the history list after new_GetLine() was called is
787       denoted by 0, and subsequently entered lines are denoted  with  succes‐
788       sively higher numbers. Note that the range of lines currently preserved
789       in the history list can be queried by calling the gl_range_of_history()
790       function.  If the requested line is in the history list, the details of
791       the line are recorded in the variable pointed to by the hline argument,
792       and 1 is returned. Otherwise 0 is returned, and the variable pointed to
793       by hline is left unchanged.
796       Beware that the string returned in hline->line is part of  the  history
797       buffer,  so it must not be modified by the caller, and will be recycled
798       on the next call to any function that takes gl as its argument.  There‐
799       fore  you should make a private copy of this string if you need to keep
800       it.
802   Manual History Archival
803       By default, whenever a line is entered by the user, it is automatically
804       appended  to  the  history  list, just before gl_get_line() returns the
805       line to the caller. This is convenient for  the  majority  of  applica‐
806       tions,  but there are also applications that need finer-grained control
807       over what gets added to the history list. In such cases, the  automatic
808       addition  of  entered  lines  to  the history list can be turned off by
809       calling the gl_automatic_history() function.
812       If this  function  is  called  with  its  enable  argument  set  to  0,
813       gl_get_line()  will  not  automatically  archive  subsequently  entered
814       lines. Automatic archiving can be reenabled at a later time by  calling
815       this function again, with its enable argument set to 1. While automatic
816       history archiving is disabled, the  calling  application  can  use  the
817       gl_append_history() to append lines to the history list as needed.
820       The  line  argument specifies the line to be added to the history list.
821       This must be a normal '\0 ' terminated string. If this string  contains
822       any newline characters, the line that gets archived in the history list
823       will be terminated by the first of these. Otherwise it will  be  termi‐
824       nated  by  the '\0 ' terminator. If the line is longer than the maximum
825       input line length that was specified when new_GetLine() was called,  it
826       will be truncated to the actual gl_get_line() line length when the line
827       is recalled.
830       If successful, gl_append_history() returns 0. Otherwise it returns non-
831       zero and sets errno to one of the following values.
833       EINVAL    One of the arguments passed to gl_append_history() was NULL.
836       ENOMEM    The  specified line was longer than the allocated size of the
837                 history buffer (as specified when new_GetLine() was  called),
838                 so it could not be archived.
842       A  textual description of the error can optionally be obtained by call‐
843       ing gl_error_message(). Note that after such an error, the history list
844       remains in a valid state to receive new history lines, so there is lit‐
845       tle harm in simply ignoring the return status of gl_append_history().
847   Miscellaneous History Configuration
848       If you wish to change the size of the history buffer  that  was  origi‐
849       nally  specified  in  the call to new_GetLine(), you can do so with the
850       gl_resize_history() function.
853       The histlen argument specifies the new size in bytes, and if you  spec‐
854       ify this as 0, the buffer will be deleted.
857       As  mentioned  in  the discussion of new_GetLine(), the number of lines
858       that can be stored in the history buffer, depends on the lengths of the
859       individual  lines.  For example, a 1000 byte buffer could equally store
860       10 lines of average length 100 bytes, or 20 lines of average length  50
861       bytes.  Although the buffer is never expanded when new lines are added,
862       a list of pointers into the buffer does get  expanded  when  needed  to
863       accomodate the number of lines currently stored in the buffer. To place
864       an upper limit on the number of lines in the buffer, and thus a ceiling
865       on  the  amount  of  memory  used  in  this  list,  you  can  call  the
866       gl_limit_history() function.
869       The max_lines should either be a positive number >=  0,  specifying  an
870       upper  limit  on  the number of lines in the buffer, or be -1 to cancel
871       any previously specified limit. When a limit is  in  effect,  only  the
872       max_lines  most  recently  appended lines are kept in the buffer. Older
873       lines are discarded.
876       To discard lines from the history buffer,  use  the  gl_clear_history()
877       function.
880       The  all_groups  argument tells the function whether to delete just the
881       lines associated with the  current  history  group  (see  gl_group_his‐
882       tory()) or all historical lines in the buffer.
885       The  gl_toggle_history()  function  allows you to toggle history on and
886       off without losing the current contents of the history list.
889       Setting the enable argument to 0 turns off the history  mechanism,  and
890       setting  it  to  1 turns it back on. When history is turned off, no new
891       lines will be added to the history list, and history  lookup  key-bind‐
892       ings will act as though there is nothing in the history buffer.
894   Querying History Information
895       The  configured  state  of  the  history  list  can be queried with the
896       gl_history_state() function.  On  return,  the  status  information  is
897       recorded in the variable pointed to by the state argument.
900       The  gl_range_of_history()  function  returns  the  number and range of
901       lines in the history list. The return values are recorded in the  vari‐
902       able  pointed  to  by  the range argument. If the nlines member of this
903       structure is greater than zero, then  the  oldest  and  newest  members
904       report the range of lines in the list, and newest=oldest+nlines-1. Oth‐
905       erwise they are both zero.
908       The gl_size_of_history() function returns the total size of the history
909       buffer and the amount of the buffer that is currently occupied.
912       On  return, the size information is recorded in the variable pointed to
913       by the size argument.
915   Changing Terminals
916       The new_GetLine() constructor function assumes that input is to be read
917       from  stdin and output written to stdout. The following function allows
918       you to switch to different input and output streams.
921       The gl argument is the object that was returned by  new_GetLine().  The
922       input_fp  argument  specifies  the  stream  to read from, and output_fp
923       specifies the stream to be written to. Only if both of these refer to a
924       terminal,   will  interactive  terminal  input  be  enabled.  Otherwise
925       gl_get_line() will simply call fgets() to read command input.  If  both
926       streams refer to a terminal, then they must refer to the same terminal,
927       and the type of this terminal must be specified with the term argument.
928       The value of the term argument is looked up in the terminal information
929       database (terminfo or termcap), in order  to  determine  which  special
930       control  sequences  are needed to control various aspects of the termi‐
931       nal.  new_GetLine()  for  example,   passes   the   return   value   of
932       getenv("TERM")  in  this argument. Note that if one or both of input_fp
933       and output_fp do not refer to a terminal, then it is legal to pass NULL
934       instead of a terminal type.
937       Note that if you want to pass file descriptors to gl_change_terminal(),
938       you can do this by creating  stdio  stream  wrappers  using  the  POSIX
939       fdopen(3C) function.
941   External Event Handling
942       By default, gl_get_line() does not return until either a complete input
943       line has been entered by the user, or an error occurs. In programs that
944       need  to  watch for I/O from other sources than the terminal, there are
945       two options.
947           o      Use the functions described in the gl_io_mode(3TECLA) manual
948                  page  to switch gl_get_line() into non-blocking server mode.
949                  In this mode, gl_get_line() becomes a  non-blocking,  incre‐
950                  mental  line-editing function that can safely be called from
951                  an external event loop. Although this is  a  very  versatile
952                  method, it involves taking on some responsibilities that are
953                  normally performed behind the scenes by gl_get_line().
955           o      While gl_get_line() is waiting for keyboard input  from  the
956                  user, you can ask it to also watch for activity on arbitrary
957                  file descriptors, such as network sockets or pipes, and have
958                  it  call  functions  of your choosing when activity is seen.
959                  This works on any system that has the  select  system  call,
960                  which is most, if not all flavors of UNIX.
963       Registering  a  file descriptor to be watched by gl_get_line() involves
964       calling the gl_watch_fd() function. If this returns non-zero,  then  it
965       means  that either your arguments are invalid, or that this facility is
966       not supported on the host system.
969       The fd argument is the file descriptor to be watched. The  event  argu‐
970       ment  specifies  what  type of activity is of interest, chosen from the
971       following enumerated values:
973       GLFD_READ      Watch for the arrival of data to be read.
976       GLFD_WRITE     Watch for the ability to write to  the  file  descriptor
977                      without blocking.
980       GLFD_URGENT    Watch  for the arrival of urgent out-of-band data on the
981                      file descriptor.
985       The callback argument is the function to call when the selected  activ‐
986       ity  is  seen.  It should be defined with the following macro, which is
987       defined in libtecla.h.
989         #define GL_FD_EVENT_FN(fn) GlFdStatus (fn)(GetLine *gl,                                    void *data, int fd, GlFdEvent event)
993       The data argument of the gl_watch_fd() function is passed to the  call‐
994       back  function  for  its  own  use, and can point to anything you like,
995       including NULL. The file descriptor and the  event  argument  are  also
996       passed  to  the callback function, and this potentially allows the same
997       callback function to be registered to  more  than  one  type  of  event
998       and/or  more than one file descriptor. The return value of the callback
999       function should be one of the following values.
1001       GLFD_ABORT       Tell  gl_get_line()  to  abort.  When  this   happens,
1002                        gl_get_line()  returns  NULL,  and a following call to
1003                        gl_return_status() will return GLR_FDABORT. Note  that
1004                        if  the application needs errno always to have a mean‐
1005                        ingful value  when  gl_get_line()  returns  NULL,  the
1006                        callback function should set errno appropriately.
1009       GLFD_REFRESH     Redraw  the  input  line   then  continue  waiting for
1010                        input. Return this if your callback wrote to the  ter‐
1011                        minal.
1014       GLFD_CONTINUE    Continue  to  wait  for  input,  without redrawing the
1015                        line.
1019       Note that before calling the callback, gl_get_line() blocks  most  sig‐
1020       nals  and  leaves  its own signal handlers installed, so if you need to
1021       catch a particular signal you will need  to  both  temporarily  install
1022       your  own  signal  handler, and unblock the signal. Be sure to re-block
1023       the signal (if it was originally blocked) and  reinstate  the  original
1024       signal handler, if any, before returning.
1027       Your  callback  should not try to read from the terminal, which is left
1028       in raw mode as far as input is concerned. You can write to the terminal
1029       as  usual,  since  features  like  conversion  of  newline to carriage-
1030       return/linefeed are re-enabled while the callback is running.  If  your
1031       callback  function does write to the terminal, be sure to output a new‐
1032       line first, and when your callback returns, tell gl_get_line() that the
1033       input  line  needs  to be redrawn, by returning the GLFD_REFRESH status
1034       code.
1037       To remove a callback function that  you  previously  registered  for  a
1038       given  file  descriptor  and  event, simply call gl_watch_fd() with the
1039       same fd and event arguments, but with a callback  argument  of  0.  The
1040       data argument is ignored in this case.
1042   Setting An Inactivity Timeout
1043       The  gl_inactivity_timeout()  function  can be used to set or cancel an
1044       inactivity timeout. Inactivity in this case  refers  both  to  keyboard
1045       input,  and to I/O on any file descriptors registered by prior and sub‐
1046       sequent calls to gl_watch_fd().
1049       The timeout is specified in the form of an integral number  of  seconds
1050       and  an  integral  number of nanoseconds, specified by the sec and nsec
1051       arguments, respectively. Subsequently, whenever no activity is seen for
1052       this  time  period,  the function specified by the callback argument is
1053       called. The data argument of gl_inactivity_timeout() is passed to  this
1054       callback  function whenever it is invoked, and can thus be used to pass
1055       arbitrary application-specific information to the callback. The follow‐
1056       ing  macro  is  provided  in  <libtecla.h>  for  applications to use to
1057       declare and prototype timeout callback functions.
1059         #define GL_TIMEOUT_FN(fn) GlAfterTimeout (fn)(GetLine *gl, void *data)
1063       On returning, the application's callback is expected to return  one  of
1064       the  following  enumerators  to tell gl_get_line() how to procede after
1065       the timeout has been handled by the callback.
1067       GLTO_ABORT       Tell  gl_get_line()  to  abort.  When  this   happens,
1068                        gl_get_line()  will  return NULL, and a following call
1069                        to gl_return_status() will  return  GLR_TIMEOUT.  Note
1070                        that  if  the application needs errno always to have a
1071                        meaningful value when gl_get_line() returns NULL,  the
1072                        callback function should set errno appropriately.
1075       GLTO_REFRESH     Redraw  the  input  line,  then  continue  waiting for
1076                        input. You should return this value if  your  callback
1077                        wrote to the terminal.
1080       GLTO_CONTINUE    In  normal  blocking-I/O  mode,  continue  to wait for
1081                        input, without redrawing the  user's  input  line.  In
1082                        non-blocking server I/O mode (see gl_io_mode(3TECLA)),
1083                        gl_get_line() acts as though I/O blocked.  This  means
1084                        that gl_get_line() will immediately return NULL, and a
1085                        following  call  to  gl_return_status()  will   return
1086                        GLR_BLOCKED.
1090       Note  that  before calling the callback, gl_get_line() blocks most sig‐
1091       nals and leaves its own signal handlers installed, so if  you  need  to
1092       catch  a  particular  signal  you will need to both temporarily install
1093       your own signal handler and unblock the signal. Be sure to re-block the
1094       signal (if it was originally blocked) and reinstate the original signal
1095       handler, if any, before returning.
1098       Your callback should not try to read from the terminal, which  is  left
1099       in  raw mode as far as input is concerned. You can however write to the
1100       terminal as usual, since features like conversion of  newline  to  car‐
1101       riage-return/linefeed  are re-enabled while the callback is running. If
1102       your callback function does write to the terminal, be sure to output  a
1103       newline  first, and when your callback returns, tell gl_get_line() that
1104       the input line needs to be redrawn, by returning the GLTO_REFRESH  sta‐
1105       tus code.
1108       Finally,  note that although the timeout arguments include a nanosecond
1109       component, few computer clocks  presently  have  resolutions  that  are
1110       finer  than a few milliseconds, so asking for less than a few millisec‐
1111       onds is equivalent to requesting zero seconds on many systems. If  this
1112       would  be  a  problem,  you  should  base your timeout selection on the
1113       actual  resolution  of  the  host  clock  (for  example,   by   calling
1114       sysconf(_SC_CLK_TCK)).
1117       To  turn off timeouts, simply call gl_inactivity_timeout() with a call‐
1118       back argument of 0. The data argument is ignored in this case.
1120   Signal Handling Defaults
1121       By default, the gl_get_line() function intercepts a number of  signals.
1122       This is particularly important for signals that would by default termi‐
1123       nate the process, since the terminal needs to be restored to  a  usable
1124       state  before this happens. This section describes the signals that are
1125       trapped by default and how gl_get_line()  responds  to  them.  Changing
1126       these defaults is the topic of the following section.
1129       When  the  following  subset of signals are caught, gl_get_line() first
1130       restores the terminal settings and signal handling  to  how  they  were
1131       before  gl_get_line() was called, resends the signal to allow the call‐
1132       ing application's signal handlers to handle it, then,  if  the  process
1133       still exists, returns NULL and sets errno as specified below.
1135       SIGINT     This  signal is generated both by the keyboard interrupt key
1136                  (usually ^C), and the keyboard break key. The errno value is
1137                  EINTR.
1140       SIGHUP     This  signal  is  generated  when  the  controlling terminal
1141                  exits. The errno value is ENOTTY.
1144       SIGPIPE    This signal is generated when a program attempts to write to
1145                  a  pipe  whose  remote end is not being read by any process.
1146                  This  can  happen   for   example   if   you   have   called
1147                  gl_change_terminal()  to  redirect  output  to a pipe hidden
1148                  under a pseudo terminal. The errno value is EPIPE.
1151       SIGQUIT    This signal is generated by the keyboard quit  key  (usually
1152                  ^\fR). The errno value is EINTR.
1155       SIGABRT    This  signal is generated by the standard C, abort function.
1156                  By default it both terminates the process  and  generates  a
1157                  core dump. The errno value is EINTR.
1160       SIGTERM    This  is the default signal that the UNIX kill command sends
1161                  to processes. The errno value is EINTR.
1165       Note that in the case of all of the above signals, POSIX mandates  that
1166       by  default the process is terminated, with the addition of a core dump
1167       in the case of the SIGQUIT signal.  In  other  words,  if  the  calling
1168       application  does not override the default handler by supplying its own
1169       signal handler, receipt of the corresponding signal will terminate  the
1170       application before gl_get_line() returns.
1173       If  gl_get_line() aborts with errno set to EINTR, you can find out what
1174       signal caused it to abort, by calling  the  gl_last_signal()  function.
1175       This  returns the numeric code (for example, SIGINT) of the last signal
1176       that was received during the most recent call to gl_get_line(),  or  -1
1177       if no signals were received.
1180       On  systems  that support it, when a SIGWINCH (window change) signal is
1181       received, gl_get_line() queries the terminal to find out its new  size,
1182       redraws the current input line to accomodate the new size, then returns
1183       to waiting for keyboard input from the user. Unlike other signals, this
1184       signal is not resent to the application.
1187       Finally, the following signals cause gl_get_line() to first restore the
1188       terminal  and  signal  environment  to  that  which  prevailed   before
1189       gl_get_line() was called, then resend the signal to the application. If
1190       the process still exists after the  signal  has  been  delivered,  then
1191       gl_get_line() then re-establishes its own signal handlers, switches the
1192       terminal back to raw mode, redisplays the input line, and goes back  to
1193       awaiting terminal input from the user.
1195       SIGCONT      This  signal  is  generated  when  a  suspended process is
1196                    resumed.
1199       SIGPOLL      On SVR4 systems, this signal notifies the  process  of  an
1200                    asynchronous I/O event. Note that under 4.3+BSD, SIGIO and
1201                    SIGPOLL are the same. On other systems, SIGIO  is  ignored
1202                    by default, so gl_get_line() does not trap it by default.
1205       SIGPWR       This signal is generated when a power failure occurs (pre‐
1206                    sumably when the system is on a UPS).
1209       SIGALRM      This signal is generated when a timer expires.
1212       SIGUSR1      An application specific signal.
1215       SIGUSR2      Another application specific signal.
1218       SIGVTALRM    This signal is generated when a virtual timer expires. See
1219                    setitimer(2).
1222       SIGXCPU      This  signal  is generated when a process exceeds its soft
1223                    CPU time limit.
1226       SIGXFSZ      This signal is generated when a process exceeds  its  soft
1227                    file-size limit.
1230       SIGTSTP      This  signal  is  generated  by  the terminal suspend key,
1231                    which is usually ^Z, or the delayed terminal suspend  key,
1232                    which is usually ^Y.
1235       SIGTTIN      This  signal  is generated if the program attempts to read
1236                    from the terminal while the  program  is  running  in  the
1237                    background.
1240       SIGTTOU      This  signal is generated if the program attempts to write
1241                    to the terminal while the program is running in the  back‐
1242                    ground.
1246       Obviously not all of the above signals are supported on all systems, so
1247       code to support them is conditionally compiled into the tecla library.
1250       Note that if SIGKILL or SIGPOLL, which by definition cannot be  caught,
1251       or  any  of  the hardware generated exception signals, such as SIGSEGV,
1252       SIGBUS, and SIGFPE, are received and unhandled while gl_get_line()  has
1253       the  terminal  in  raw mode, the program will be terminated without the
1254       terminal having been restored to a usable state. In practice,  job-con‐
1255       trol  shells  usually reset the terminal settings when a process relin‐
1256       quishes the controlling terminal, so this is only a problem with  older
1257       shells.
1259   Customized Signal Handling
1260       The  previous  section  listed  the signals that gl_get_line() traps by
1261       default, and described how it responds to them. This section  describes
1262       how  to  both  add and remove signals from the list of trapped signals,
1263       and how to specify how gl_get_line() should respond to a given signal.
1266       If you do not need gl_get_line() to do anything in response to a signal
1267       that  it  normally  traps, you can tell to gl_get_line() to ignore that
1268       signal by calling gl_ignore_signal().
1271       The signo argument is the number of the signal  (for  example,  SIGINT)
1272       that you want to have ignored. If the specified signal is not currently
1273       one of those being trapped, this function does nothing.
1276       The gl_trap_signal() function allows you to either add a new signal  to
1277       the list that gl_get_line() traps or modify how it responds to a signal
1278       that it already traps.
1281       The signo argument is the number of the signal that you  want  to  have
1282       trapped.  The flags argument is a set of flags that determine the envi‐
1283       ronment in which the application's signal handler is invoked. The after
1284       argument  tells gl_get_line() what to do after the application's signal
1285       handler returns. The errno_value tells gl_get_line() what to set  errno
1286       to if told to abort.
1289       The  flags  argument  is  a bitwise OR of zero or more of the following
1290       enumerators:
1292       GLS_RESTORE_SIG     Restore the caller's signal environment while  han‐
1293                           dling the signal.
1296       GLS_RESTORE_TTY     Restore  the  caller's terminal settings while han‐
1297                           dling the signal.
1300       GLS_RESTORE_LINE    Move the cursor to the start of the line  following
1301                           the  input  line  before invoking the application's
1302                           signal handler.
1305       GLS_REDRAW_LINE     Redraw the input line when the application's signal
1306                           handler returns.
1309       GLS_UNBLOCK_SIG     Normally,  if  the  calling  program  has  a signal
1310                           blocked (see  sigprocmask(2)),  gl_get_line()  does
1311                           not trap that signal. This flag tells gl_get_line()
1312                           to trap the signal and unblock it for the  duration
1313                           of the call to gl_get_line().
1316       GLS_DONT_FORWARD    If  this  flag  is included, the signal will not be
1317                           forwarded to the signal handler of the calling pro‐
1318                           gram.
1322       Two commonly useful flag combinations are also enumerated as follows:
1331       If  your  signal handler, or the default system signal handler for this
1332       signal, if you have not overridden it, never either writes to the  ter‐
1333       minal,  nor  suspends  or  terminates the calling program, then you can
1334       safely set the flags argument to 0.
1336           o      The cursor does not get left in  the  middle  of  the  input
1337                  line.
1339           o      So that the user can type in input and have it echoed.
1341           o      So  that  you do not need to end each output line with \r\n,
1342                  instead of just \n.
1345       The GL_RESTORE_ENV combination is the same as GL_SUSPEND_INPUT,  except
1346       that  it does not move the cursor. If your signal handler does not read
1347       or write anything to the terminal, the user will not  see  any  visible
1348       indication  that  a signal was caught. This can be useful if you have a
1349       signal handler that only occasionally writes  to  the  terminal,  where
1350       using  GL_SUSPEND_LINE  would  cause the input line to be unnecessarily
1351       duplicated when nothing had been written to the terminal. Such a signal
1352       handler,  when it does write to the terminal, should be sure to start a
1353       new line at the start of its first write, by writing a new line  before
1354       returning. If the signal arrives while the user is entering a line that
1355       only occupies a signal terminal line, or if the cursor is on  the  last
1356       terminal line of a longer input line, this will have the same effect as
1357       GL_SUSPEND_INPUT. Otherwise it  will  start  writing  on  a  line  that
1358       already contains part of the displayed input line. This does not do any
1359       harm, but it looks a bit ugly, which is why the GL_SUSPEND_INPUT combi‐
1360       nation  is  better if you know that you are always going to be writting
1361       to the terminal.
1364       The after argument, which determines what gl_get_line() does after  the
1365       application's signal handler returns (if  it returns), can take any one
1366       of the following values:
1368       GLS_RETURN      Return the completed input line,  just  as  though  the
1369                       user had pressed the return key.
1372       GLS_ABORT       Cause   gl_get_line()  to  abort.  When  this  happens,
1373                       gl_get_line() returns NULL, and  a  following  call  to
1374                       gl_return_status() will return GLR_SIGNAL. Note that if
1375                       the application needs errno always to have a meaningful
1376                       value  when  gl_get_line()  returns  NULL, the callback
1377                       function should set errno appropriately.
1380       GLS_CONTINUE    Resume command line editing.
1384       The errno_value argument is intended to be combined with the  GLS_ABORT
1385       option,  telling  gl_get_line() what to set the standard errno variable
1386       to before returning NULL to the calling program. It can also,  however,
1387       be  used  with  the GL_RETURN option, in case you want to have a way to
1388       distinguish between an input line that was  entered  using  the  return
1389       key, and one that was entered by the receipt of a signal.
1391   Reliable Signal Handling
1392       Signal  handling is suprisingly hard to do reliably without race condi‐
1393       tions. In gl_get_line() a lot of care has been taken to allow  applica‐
1394       tions  to  perform  reliable signal handling around gl_get_line(). This
1395       section explains how to make use of this.
1398       As an example of the problems that can arise if the application is  not
1399       written  correctly,  imagine that one's application has a SIGINT signal
1400       handler that sets a global flag. Now suppose that the application tests
1401       this  flag  just before invoking gl_get_line(). If a SIGINT signal hap‐
1402       pens to be received in the small window of time between  the  statement
1403       that  tests  the  value  of  this  flag,  and  the statement that calls
1404       gl_get_line(), then gl_get_line() will not see the signal, and will not
1405       be  interrupted.  As  a  result,  the  application  will not be able to
1406       respond to the signal until the user gets around to finishing  entering
1407       the input line and gl_get_line() returns. Depending on the application,
1408       this might or might not be a disaster, but at the very least  it  would
1409       puzzle the user.
1412       The way to avoid such problems is to do the following.
1414           1.     If  needed,  use  the gl_trap_signal() function to configure
1415                  gl_get_line() to abort when important signals are caught.
1417           2.     Configure gl_get_line() such that if any of the signals that
1418                  it  catches  are  blocked when gl_get_line() is called, they
1419                  will  be   unblocked   automatically   during   times   when
1420                  gl_get_line() is waiting for I/O. This can be done either on
1421                  a per signal basis, by calling  the  gl_trap_signal()  func‐
1422                  tion,  and  specifying the GLS_UNBLOCK attribute of the sig‐
1423                  nal, or globally by calling the gl_catch_blocked() function.
1424                  This  function  simply adds the GLS_UNBLOCK attribute to all
1425                  of the signals that it is currently configured to trap.
1427           3.     Just before calling gl_get_line(), block delivery of all  of
1428                  the  signals  that gl_get_line() is configured to trap. This
1429                  can be done using the POSIX sigprocmask function in conjunc‐
1430                  tion  with  the  gl_list_signals()  function.  This function
1431                  returns the set of signals that it is  currently  configured
1432                  to  catch in the set argument, which is in the form required
1433                  by sigprocmask(2).
1435           4.     In the example, one would now test the global flag that  the
1436                  signal  handler sets, knowing that there is now no danger of
1437                  this flag being set again until gl_get_line()  unblocks  its
1438                  signals while performing I/O.
1440           5.     Eventually  gl_get_line()  returns,  either because a signal
1441                  was caught, an error occurred, or the user finished entering
1442                  their input line.
1444           6.     Now  one would check the global signal flag again, and if it
1445                  is set, respond to it, and zero the flag.
1447           7.     Use sigprocmask() to unblock the signals that  were  blocked
1448                  in step 3.
1451       The  same technique can be used around certain POSIX signal-aware func‐
1452       tions, such as sigsetjmp(3C) and sigsuspend(2), and in particular,  the
1453       former  of  these  two  functions  can be used in conjunction with sig‐
1454       longjmp(3C) to implement race-condition  free  signal  handling  around
1455       other  long-running system calls. The gl_get_line() function manages to
1456       reliably trap signals  around  calls  to  functions  like  read(2)  and
1457       select(3C) without race conditions.
1460       The  gl_get_line() function first uses the POSIX sigprocmask() function
1461       to block the delivery of all of the signals that it is  currently  con‐
1462       figured  to  catch.  This  is  redundant if the application has already
1463       blocked them, but it does no harm. It  undoes  this  step  just  before
1464       returning.
1467       Whenever  gl_get_line()  needs to call read or select to wait for input
1468       from the user, it first calls the  POSIX  sigsetjmp()  function,  being
1469       sure to specify a non-zero value for its savemask argument.
1472       If sigsetjmp() returns zero, gl_get_line() then does the following.
1474           1.     It uses the POSIX sigaction(2) function to register a tempo‐
1475                  rary signal handler to all of the signals that it is config‐
1476                  ured to catch. This signal handler does two things.
1478               a.     It records the number of the signal that was received in
1479                      a file-scope variable.
1481               b.     It then calls the POSIX siglongjmp() function using  the
1482                      buffer  that  was  passed  to  sigsetjmp() for its first
1483                      argument and a non-zero value for its second argument.
1484           When this signal handler is registered, the sa_mask member  of  the
1485           struct sigaction act argument of the call to sigaction() is config‐
1486           ured to contain all of the signals that gl_get_line() is  catching.
1487           This  ensures  that  only  one signal will be caught at once by our
1488           signal handler, which in turn ensures that  multiple  instances  of
1489           our signal handler do not tread on each other's toes.
1491           2.     Now  that  the signal handler has been set up, gl_get_line()
1492                  unblocks all of the signals that it is configured to catch.
1494           3.     It then calls the read() or select() function  to  wait  for
1495                  keyboard input.
1497           4.     If  this  function returns (that is, no signal is received),
1498                  gl_get_line() blocks delivery of  the  signals  of  interest
1499                  again.
1501           5.     It  then  reinstates the signal handlers that were displaced
1502                  by the one that was just installed.
1505       Alternatively, if sigsetjmp() returns non-zero, this means that one  of
1506       the signals being trapped was caught while the above steps were execut‐
1507       ing. When this happens, gl_get_line() does the following.
1510       First, note that when a call  to  siglongjmp()  causes  sigsetjmp()  to
1511       return,  provided  that  the  savemask argument of sigsetjmp() was non-
1512       zero,  the  signal  process  mask  is  restored  to  how  it  was  when
1513       sigsetjmp()  was  called.  This  is  the  important  difference between
1514       sigsetjmp() and the older problematic setjmp(3C), and is the  essential
1515       ingredient  that makes it possible to avoid signal handling race condi‐
1516       tions. Because of this we are guaranteed that all of the  signals  that
1517       we  blocked before calling sigsetjmp() are blocked again as soon as any
1518       signal is caught. The following statements, which  are  then  executed,
1519       are  thus  guaranteed  to be executed without any further signals being
1520       caught.
1522           1.     If  so  instructed  by   the   gl_get_line()   configuration
1523                  attributes  of  the  signal  that  was caught, gl_get_line()
1524                  restores the terminal attributes to the state that they  had
1525                  when  gl_get_line()  was called. This is particularly impor‐
1526                  tant for signals that  suspend  or  terminate  the  process,
1527                  since  otherwise  the  terminal would be left in an unusable
1528                  state.
1530           2.     It then reinstates the application's signal handlers.
1532           3.     Then it uses the C standard-library  raise(3C)  function  to
1533                  re-send the application the signal that was caught.
1535           4.     Next  it  unblocks delivery of the signal that we just sent.
1536                  This results in the signal that was  just  sent  by  raise()
1537                  being  caught  by the application's original signal handler,
1538                  which can now handle it as it sees fit.
1540           5.     If the signal handler returns (that is, it does  not  termi‐
1541                  nate  the  process),  gl_get_line()  blocks  delivery of the
1542                  above signal again.
1544           6.     It then undoes any actions performed in  the  first  of  the
1545                  above  steps and redisplays the line, if the signal configu‐
1546                  ration calls for this.
1548           7.     gl_get_line() then either resumes trying to read  a  charac‐
1549                  ter, or aborts, depending on the configuration of the signal
1550                  that was caught.
1553       What the above steps do in essence is to take asynchronously  delivered
1554       signals and handle them synchronously, one at a time, at a point in the
1555       code where gl_get_line() has complete control over its environment.
1557   The Terminal Size
1558       On most systems the combination of the TIOCGWINSZ ioctl  and  the  SIG‐
1559       WINCH signal is used to maintain an accurate idea of the terminal size.
1560       The terminal size is newly queried every  time  that  gl_get_line()  is
1561       called and whenever a SIGWINCH signal is received.
1564       On  the  few  systems where this mechanism is not available, at startup
1565       new_GetLine() first looks for the LINES and COLUMNS  environment  vari‐
1566       ables. If these are not found, or they contain unusable values, then if
1567       a terminal information database like terminfo or termcap is  available,
1568       the default size of the terminal is looked up in this database. If this
1569       too fails to provide the terminal size, a default size of 80 columns by
1570       24 lines is used.
1573       Even  on  systems that do support ioctl(TIOCGWINSZ), if the terminal is
1574       on the other end of a serial line, the terminal driver generally has no
1575       way  of  detecting when a resize occurs or of querying what the current
1576       size is. In such cases no SIGWINCH is sent  to  the  process,  and  the
1577       dimensions  returned by ioctl(TIOCGWINSZ) are not correct. The only way
1578       to handle such instances is to provide a way for the user  to  enter  a
1579       command that tells the remote system what the new size is. This command
1580       would then call the gl_set_term_size() function to  tell  gl_get_line()
1581       about the change in size.
1584       The  ncolumn and nline arguments are used to specify the new dimensions
1585       of the terminal, and must not be less than 1. On systems that  do  sup‐
1586       port  ioctl(TIOCGWINSZ), this function first calls ioctl(TIOCSWINSZ) to
1587       tell the terminal driver about the  change  in  size.  In  non-blocking
1588       server-I/O  mode, if a line is currently being input, the input line is
1589       then redrawn to accomodate the changed size. Finally the new values are
1590       recorded in gl for future use by gl_get_line().
1593       The gl_terminal_size() function allows you to query the current size of
1594       the terminal, and install an alternate fallback size  for  cases  where
1595       the  size  is  not available. Beware that the terminal size will not be
1596       available if reading from a pipe or a file, so the default  values  can
1597       be  important  even  on systems that do support ways of finding out the
1598       terminal size.
1601       This function first updates gl_get_line()'s  fallback  terminal  dimen‐
1602       sions, then records its findings in the return value.
1605       The  def_ncolumn  and def_nline arguments specify the default number of
1606       terminal columns and lines to use if the terminal size cannot be deter‐
1607       mined by ioctl(TIOCGWINSZ) or environment variables.
1609   Hiding What You Type
1610       When  entering sensitive information, such as passwords, it is best not
1611       to have the text that you are entering echoed on the terminal. Further‐
1612       more, such text should not be recorded in the history list, since some‐
1613       body finding your terminal unattended could then recall it, or somebody
1614       snooping  through  your  directories could see it in your history file.
1615       With this in mind, the gl_echo_mode() function allows you to toggle  on
1616       and  off  the  display  and  archival  of any text that is subsequently
1617       entered in calls to gl_get_line().
1620       The enable argument specifies whether entered text should be visible or
1621       not. If it is 0, then subsequently entered lines will not be visible on
1622       the terminal, and will not be recorded in the history list. If it is 1,
1623       then  subsequent input lines will be displayed as they are entered, and
1624       provided that history has not been turned off with a  call  to  gl_tog‐
1625       gle_history(),  then  they  will  also be archived in the history list.
1626       Finally, if the enable argument is -1, then the echoing  mode  is  left
1627       unchanged, which allows you to non-destructively query the current set‐
1628       ting through the return value. In all cases, the return  value  of  the
1629       function  is  0 if echoing was disabled before the function was called,
1630       and 1 if it was enabled.
1633       When echoing is turned off, note  that  although  tab  completion  will
1634       invisibly  complete  your  prefix as far as possible, ambiguous comple‐
1635       tions will not be displayed.
1637   Single Character Queries
1638       Using gl_get_line() to query the user for a single character reply,  is
1639       inconvenient  for the user, since they must hit the enter or return key
1640       before the character that they typed is returned to the  program.  Thus
1641       the  gl_query_char()  function  has  been provided for single character
1642       queries like this.
1645       This function displays the specified prompt at the start of a new line,
1646       and waits for the user to type a character. When the user types a char‐
1647       acter, gl_query_char() displays it to the right of the prompt, starts a
1648       newline,  then returns the character to the calling program. The return
1649       value of the function is the character that was typed. If the read  had
1650       to  be  aborted for some reason, EOF is returned instead. In the latter
1651       case, the application can call the previously documented gl_return_sta‐
1652       tus(),  to find out what went wrong. This could, for example, have been
1653       the reception of a signal, or the optional inactivity timer going off.
1656       If the user simply hits enter, the value of  the  defchar  argument  is
1657       substituted.  This  means  that  when  the  user hits either newline or
1658       return, the character specified in  defchar,  is  displayed  after  the
1659       prompt,  as  though the user had typed it, as well as being returned to
1660       the calling application. If such a replacement is not important, simply
1661       pass '\n' as the value of defchar.
1664       If  the  entered character is an unprintable character, it is displayed
1665       symbolically. For example, control-A is displayed as ^A, and characters
1666       beyond 127 are displayed in octal, preceded by a backslash.
1669       As with gl_get_line(), echoing of the entered character can be disabled
1670       using the gl_echo_mode() function.
1673       If the calling process is suspended while waiting for the user to  type
1674       their  response,  the  cursor is moved to the line following the prompt
1675       line, then when the process resumes, the  prompt  is  redisplayed,  and
1676       gl_query_char() resumes waiting for the user to type a character.
1679       Note  that  in non-blocking server mode, if an incomplete input line is
1680       in the process of being read when gl_query_char() is called,  the  par‐
1681       tial  input line is discarded, and erased from the terminal, before the
1682       new prompt is displayed. The next call to gl_get_line() will thus start
1683       editing a new line.
1685   Reading Raw Characters
1686       Whereas  the  gl_query_char()  function  visibly prompts the user for a
1687       character, and displays what they typed,  the  gl_read_char()  function
1688       reads a signal character from the user, without writing anything to the
1689       terminal, or perturbing any incompletely entered input line. This means
1690       that it can be called not only from between calls to gl_get_line(), but
1691       also from callback functions that the application has registered to  be
1692       called by gl_get_line().
1695       On  success,  the  return value of gl_read_char() is the character that
1696       was read. On failure, EOF is returned, and the gl_return_status() func‐
1697       tion  can  be called to find out what went wrong. Possibilities include
1698       the optional inactivity timer going off, the receipt of a  signal  that
1699       is configured to abort gl_get_line(), or terminal I/O blocking, when in
1700       non-blocking server-I/O mode.
1703       Beware that certain keyboard keys, such as function  keys,  and  cursor
1704       keys, usually generate at least three characters each, so a single call
1705       to gl_read_char() will not be enough to identify such keystrokes.
1707   Clearing The Terminal
1708       The calling program can clear the terminal by  calling  gl_erase_termi‐
1709       nal(). In non-blocking server-I/O mode, this function also arranges for
1710       the current input line to be redrawn from scratch when gl_get_line() is
1711       next called.
1713   Displaying Text Dynamically
1714       Between calls to gl_get_line(), the gl_display_text() function provides
1715       a convenient way to display  paragraphs  of  text,  left-justified  and
1716       split  over  one or more terminal lines according to the constraints of
1717       the current width of the terminal. Examples of the use of this function
1718       may  be  found in the demo programs, where it is used to display intro‐
1719       ductions. In those examples the advanced  use   of  optional  prefixes,
1720       suffixes  and filled lines to draw a box around the text is also illus‐
1721       trated.
1724       If gl is not currently connected to a terminal, for example if the out‐
1725       put of a program that uses gl_get_line() is being piped to another pro‐
1726       gram or redirected to a file, then the value of the def_width parameter
1727       is used as the terminal width.
1730       The  indentation  argument specifies the number of characters to use to
1731       indent each line of ouput. The fill_char argument specifies the charac‐
1732       ter that will be used to perform this indentation.
1735       The  prefix  argument  can  be  either NULL or a string to place at the
1736       beginning of each new line (after any indentation). Similarly, the suf‐
1737       fix argument can be either NULL or a string to place at the end of each
1738       line. The suffix is placed flush against the right edge of  the  termi‐
1739       nal,  and  any  space  between its first character and the last word on
1740       that line is filled with the character specified by the fill_char argu‐
1741       ment. Normally the fill-character is a space.
1744       The  start  argument  tells  gl_display_text() how many characters have
1745       already been written to the current terminal line, and  thus  tells  it
1746       the  starting  column  index  of  the cursor. Since the return value of
1747       gl_display_text() is the ending column index of the cursor, by  passing
1748       the  return value of one call to the start argument of the next call, a
1749       paragraph that is broken between more than one string can  be  composed
1750       by  calling  gl_display_text() for each successive portion of the para‐
1751       graph. Note that literal newline characters are necessary at the end of
1752       each paragraph to force a new line to be started.
1755       On error, gl_display_text() returns -1.
1757   Callback Function Facilities
1758       Unless  otherwise  stated,  callback  functions  such as tab completion
1759       callbacks and event callbacks should not call  any  functions  in  this
1760       module.  The following functions, however, are designed specifically to
1761       be used by callback functions.
1764       Calling  the  gl_replace_prompt()  function  from  a   callback   tells
1765       gl_get_line()  to display a different prompt when the callback returns.
1766       Except in non-blocking server mode, it has no effect  if  used  between
1767       calls  to gl_get_line(). In non-blocking server mode, when used between
1768       two calls to gl_get_line() that are operating on the same  input  line,
1769       the current input line will be re-drawn with the new prompt on the fol‐
1770       lowing call to gl_get_line().
1772   International Character Sets
1773       Since libtecla(3LIB) version 1.4.0, gl_get_line() has been 8-bit clean.
1774       This  means  that all 8-bit characters that are printable in the user's
1775       current locale are now displayed verbatim and included in the  returned
1776       input line. Assuming that the calling program correctly contains a call
1777       like the following,
1779         setlocale(LC_CTYPE, "")
1783       then the current locale is determined by the first of  the  environment
1784       variables  LC_CTYPE,  LC_ALL, and LANG that is found to contain a valid
1785       locale name. If none of these variables are  defined,  or  the  program
1786       neglects  to  call  setlocale(3C),  then  the default C locale is used,
1787       which is US 7-bit ASCII. On most UNIX-like platforms,  you  can  get  a
1788       list of valid locales by typing the command:
1790         locale -a
1795       at the shell prompt. Further documentation on how the user can make use
1796       of this to enter international characters can be found in the  tecla(5)
1797       man page.
1799   Thread Safety
1800       Unfortunately  neither  terminfo  nor termcap were designed to be reen‐
1801       trant, so you cannot safely use the functions of the getline module  in
1802       multiple threads (you can use the separate file-expansion and word-com‐
1803       pletion  modules in multiple threads, see the corresponding  man  pages
1804       for  details).  However due to the use of POSIX reentrant functions for
1805       looking up home directories, it is safe to use this module from a  sin‐
1806       gle  thread  of  a  multi-threaded  program,  provided  that your other
1807       threads do not use any termcap or terminfo functions.


1810       See attributes(5) for descriptions of the following attributes:
1815       ┌─────────────────────────────┬─────────────────────────────┐
1816       │      ATTRIBUTE TYPE         │      ATTRIBUTE VALUE        │
1817       ├─────────────────────────────┼─────────────────────────────┤
1818       │Interface Stability          │Committed                    │
1819       ├─────────────────────────────┼─────────────────────────────┤
1820       │MT-Level                     │MT-Safe                      │
1821       └─────────────────────────────┴─────────────────────────────┘


1824       cpl_complete_word(3TECLA), ef_expand_file(3TECLA),  gl_io_mode(3TECLA),
1825       libtecla(3LIB), pca_lookup_file(3TECLA), attributes(5), tecla(5)
1829SunOS 5.11                        28 Nov 2007              gl_get_line(3TECLA)