1 GL_GET_LINE(3TECLA)           Interactive Command-line Input Library Functions
   2 
   3 
   4 
   5 NAME
   6        gl_get_line, new_GetLine, del_GetLine, gl_customize_completion,
   7        gl_change_terminal, gl_configure_getline, gl_load_history,
   8        gl_save_history, gl_group_history, gl_show_history, gl_watch_fd,
   9        gl_inactivity_timeout, gl_terminal_size, gl_set_term_size,
  10        gl_resize_history, gl_limit_history, gl_clear_history,
  11        gl_toggle_history, gl_lookup_history, gl_state_of_history,
  12        gl_range_of_history, gl_size_of_history, gl_echo_mode,
  13        gl_replace_prompt, gl_prompt_style, gl_ignore_signal, gl_trap_signal,
  14        gl_last_signal, gl_completion_action, gl_register_action,
  15        gl_display_text, gl_return_status, gl_error_message, gl_catch_blocked,
  16        gl_list_signals, gl_bind_keyseq, gl_erase_terminal,
  17        gl_automatic_history, gl_append_history, gl_query_char, gl_read_char -
  18        allow the user to compose an input line
  19 
  20 SYNOPSIS
  21        cc [ flag... ] file... -ltecla [ library... ]
  22        #include <stdio.h>
  23        #include <libtecla.h>
  24 
  25        GetLine *new_GetLine(size_t linelen, size_t histlen);
  26 
  27 
  28        GetLine *del_GetLine(GetLine *gl);
  29 
  30 
  31        char *gl_get_line(GetLine *gl, const char *prompt,
  32             const char *start_line, int start_pos);
  33 
  34 
  35        int gl_query_char(GetLine *gl, const char *prompt, char defchar);
  36 
  37 
  38        int gl_read_char(GetLine *gl);
  39 
  40 
  41        int gl_customize_completion(GetLine *gl, void *data,
  42             CplMatchFn *match_fn);
  43 
  44 
  45        int gl_change_terminal(GetLine *gl, FILE *input_fp,
  46             FILE *output_fp, const char *term);
  47 
  48 
  49        int gl_configure_getline(GetLine *gl, const char *app_string,
  50             const char *app_file, const char *user_file);
  51 
  52 
  53        int gl_bind_keyseq(GetLine *gl, GlKeyOrigin origin,
  54             const char *keyseq, const char *action);
  55 
  56 
  57        int gl_save_history(GetLine *gl, const char *filename,
  58             const char *comment, int max_lines);
  59 
  60 
  61        int gl_load_history(GetLine *gl, const char *filename,
  62             const char *comment);
  63 
  64 
  65        int gl_watch_fd(GetLine *gl, int fd, GlFdEvent event,
  66             GlFdEventFn *callback, void *data);
  67 
  68 
  69        int gl_inactivity_timeout(GetLine *gl, GlTimeoutFn *callback,
  70             void *data, unsigned long sec, unsigned long nsec);
  71 
  72 
  73        int gl_group_history(GetLine *gl, unsigned stream);
  74 
  75 
  76        int gl_show_history(GetLine *gl, FILE *fp, const char *fmt,
  77             int all_groups, int max_lines);
  78 
  79 
  80        int gl_resize_history(GetLine *gl, size_t bufsize);
  81 
  82 
  83        void gl_limit_history(GetLine *gl, int max_lines);
  84 
  85 
  86        void gl_clear_history(GetLine *gl, int all_groups);
  87 
  88 
  89        void gl_toggle_history(GetLine *gl, int enable);
  90 
  91 
  92        GlTerminalSize gl_terminal_size(GetLine *gl, int def_ncolumn,
  93             int def_nline);
  94 
  95 
  96        int gl_set_term_size(GetLine *gl, int ncolumn, int nline);
  97 
  98 
  99        int gl_lookup_history(GetLine *gl, unsigned long id,
 100             GlHistoryLine *hline);
 101 
 102 
 103        void gl_state_of_history(GetLine *gl, GlHistoryState *state);
 104 
 105 
 106        void gl_range_of_history(GetLine *gl, GlHistoryRange *range);
 107 
 108 
 109        void gl_size_of_history(GetLine *gl, GlHistorySize *size);
 110 
 111 
 112        void gl_echo_mode(GetLine *gl, int enable);
 113 
 114 
 115        void gl_replace_prompt(GetLine *gl, const char *prompt);
 116 
 117 
 118        void gl_prompt_style(GetLine *gl, GlPromptStyle style);
 119 
 120 
 121        int gl_ignore_signal(GetLine *gl, int signo);
 122 
 123 
 124        int gl_trap_signal(GetLine *gl, int signo, unsigned flags,
 125             GlAfterSignal after, int errno_value);
 126 
 127 
 128        int gl_last_signal(GetLine *gl);
 129 
 130 
 131        int gl_completion_action(GetLine *gl, void *data,
 132             CplMatchFn *match_fn, int list_only, const char *name,
 133             const char *keyseq);
 134 
 135 
 136        int gl_register_action(GetLine *gl, void *data, GlActionFn *fn,
 137             const char *name, const char *keyseq);
 138 
 139 
 140        int gl_display_text(GetLine *gl, int indentation,
 141             const char *prefix, const char *suffix, int fill_char,
 142             int def_width, int start, const char *string);
 143 
 144 
 145        GlReturnStatus gl_return_status(GetLine *gl);
 146 
 147 
 148        const char *gl_error_message(GetLine *gl, char *buff, size_t n);
 149 
 150 
 151        void gl_catch_blocked(GetLine *gl);
 152 
 153 
 154        int gl_list_signals(GetLine *gl, sigset_t *set);
 155 
 156 
 157        int gl_append_history(GetLine *gl, const char *line);
 158 
 159 
 160        int gl_automatic_history(GetLine *gl, int enable);
 161 
 162 
 163        int gl_erase_terminal(GetLine *gl);
 164 
 165 
 166 DESCRIPTION
 167        The gl_get_line() function is part of the libtecla(3LIB) library.  If
 168        the user is typing at a terminal, each call prompts them for a line of
 169        input, then provides interactive editing facilities, similar to those
 170        of the UNIX tcsh shell. In addition to simple command-line editing, it
 171        supports recall of previously entered command lines, TAB completion of
 172        file names, and in-line wild-card expansion of filenames. Documentation
 173        of both the user-level command-line editing features and all user
 174        configuration options can be found on the tecla(5) manual page.
 175 
 176    An Example
 177        The following shows a complete example of how to use the gl_get_line()
 178        function to get input from the user:
 179 
 180          #include <stdio.h>
 181          #include <locale.h>
 182          #include <libtecla.h>
 183 
 184          int main(int argc, char *argv[])
 185          {
 186            char *line;    /* The line that the user typed */
 187            GetLine *gl;   /* The gl_get_line() resource object */
 188 
 189            setlocale(LC_CTYPE, ""); /* Adopt the user's choice */
 190                                     /* of character set. */
 191 
 192            gl = new_GetLine(1024, 2048);
 193            if(!gl)
 194              return 1;
 195            while((line=gl_get_line(gl, "$ ", NULL, -1)) != NULL &&
 196                   strcmp(line, "exit\n") != 0)
 197              printf("You typed: %s\n", line);
 198 
 199            gl = del_GetLine(gl);
 200            return 0;
 201          }
 202 
 203 
 204 
 205        In the example, first the resources needed by the gl_get_line()
 206        function are created by calling new_GetLine(). This allocates the
 207        memory used in subsequent calls to the gl_get_line() function,
 208        including the history buffer for recording previously entered lines.
 209        Then one or more lines are read from the user, until either an error
 210        occurs, or the user types exit. Then finally the resources that were
 211        allocated by new_GetLine(), are returned to the system by calling
 212        del_GetLine(). Note the use of the NULL return value of del_GetLine()
 213        to make gl NULL. This is a safety precaution. If the program
 214        subsequently attempts to pass gl to gl_get_line(), said function will
 215        complain, and return an error, instead of attempting to use the deleted
 216        resource object.
 217 
 218    The Functions Used In The Example
 219        The new_GetLine() function creates the resources used by the
 220        gl_get_line() function and returns an opaque pointer to the object that
 221        contains them. The maximum length of an input line is specified by the
 222        linelen argument, and the number of bytes to allocate for storing
 223        history lines is set by the histlen argument. History lines are stored
 224        back-to-back in a single buffer of this size. Note that this means that
 225        the number of history lines that can be stored at any given time,
 226        depends on the lengths of the individual lines. If you want to place an
 227        upper limit on the number of lines that can be stored, see the
 228        description of the gl_limit_history() function. If you do not want
 229        history at all, specify histlen as zero, and no history buffer will be
 230        allocated.
 231 
 232 
 233        On error, a message is printed to stderr and NULL is returned.
 234 
 235 
 236        The del_GetLine() function deletes the resources that were returned by
 237        a previous call to new_GetLine(). It always returns NULL (for example,
 238        a deleted object). It does nothing if the gl argument is NULL.
 239 
 240 
 241        The gl_get_line() function can be called any number of times to read
 242        input from the user. The gl argument must have been previously returned
 243        by a call to new_GetLine(). The prompt argument should be a normal
 244        null-terminated string, specifying the prompt to present the user with.
 245        By default prompts are displayed literally, but if enabled with the
 246        gl_prompt_style() function, prompts can contain directives to do
 247        underlining, switch to and from bold fonts, or turn highlighting on and
 248        off.
 249 
 250 
 251        If you want to specify the initial contents of the line for the user to
 252        edit, pass the desired string with the start_line argument. You can
 253        then specify which character of this line the cursor is initially
 254        positioned over by using the start_pos argument. This should be -1 if
 255        you want the cursor to follow the last character of the start line. If
 256        you do not want to preload the line in this manner, send start_line as
 257        NULL, and set start_pos to -1.
 258 
 259 
 260        The gl_get_line() function returns a pointer to the line entered by the
 261        user, or NULL on error or at the end of the input. The returned pointer
 262        is part of the specified gl resource object, and thus should not be
 263        freed by the caller, or assumed to be unchanging from one call to the
 264        next. When reading from a user at a terminal, there will always be a
 265        newline character at the end of the returned line. When standard input
 266        is being taken from a pipe or a file, there will similarly be a newline
 267        unless the input line was too long to store in the internal buffer. In
 268        the latter case you should call gl_get_line() again to read the rest of
 269        the line. Note that this behavior makes gl_get_line() similar to
 270        fgets(3C). When stdin is not connected to a terminal, gl_get_line()
 271        simply calls fgets().
 272 
 273    The Return Status Of gl_get_line()
 274        The gl_get_line() function has two possible return values: a pointer to
 275        the completed input line, or NULL. Additional information about what
 276        caused gl_get_line() to return is available both by inspecting errno
 277        and by calling the gl_return_status() function.
 278 
 279 
 280        The following are the possible enumerated values returned by
 281        gl_return_status():
 282 
 283        GLR_NEWLINE
 284                       The last call to gl_get_line() successfully returned a
 285                       completed input line.
 286 
 287 
 288        GLR_BLOCKED
 289                       The gl_get_line() function was in non-blocking server
 290                       mode, and returned early to avoid blocking the process
 291                       while waiting for terminal I/O. The gl_pending_io()
 292                       function can be used to see what type of I/O
 293                       gl_get_line() was waiting for. See the
 294                       gl_io_mode(3TECLA).
 295 
 296 
 297        GLR_SIGNAL
 298                       A signal was caught by gl_get_line() that had an after-
 299                       signal disposition of GLS_ABORT. See gl_trap_signal().
 300 
 301 
 302        GLR_TIMEOUT
 303                       The inactivity timer expired while gl_get_line() was
 304                       waiting for input, and the timeout callback function
 305                       returned GLTO_ABORT. See gl_inactivity_timeout() for
 306                       information about timeouts.
 307 
 308 
 309        GLR_FDABORT
 310                       An application I/O callback returned GLFD_ABORT. See
 311                       gl_watch_fd().
 312 
 313 
 314        GLR_EOF
 315                       End of file reached. This can happen when input is
 316                       coming from a file or a pipe, instead of the terminal.
 317                       It also occurs if the user invokes the list-or-eof or
 318                       del-char-or-list-or-eof actions at the start of a new
 319                       line.
 320 
 321 
 322        GLR_ERROR
 323                       An unexpected error caused gl_get_line() to abort
 324                       (consult errno and/or gl_error_message() for details.
 325 
 326 
 327 
 328        When gl_return_status() returns GLR_ERROR and the value of errno is not
 329        sufficient to explain what happened, you can use the gl_error_message()
 330        function to request a description of the last error that occurred.
 331 
 332 
 333        The return value of gl_error_message() is a pointer to the message that
 334        occurred. If the buff argument is NULL, this will be a pointer to a
 335        buffer within gl whose value will probably change on the next call to
 336        any function associated with gl_get_line(). Otherwise, if a non-null
 337        buff argument is provided, the error message, including a '\0'
 338        terminator, will be written within the first n elements of this buffer,
 339        and the return value will be a pointer to the first element of this
 340        buffer. If the message will not fit in the provided buffer, it will be
 341        truncated to fit.
 342 
 343    Optional Prompt Formatting
 344        Whereas by default the prompt string that you specify is displayed
 345        literally without any special interpretation of the characters within
 346        it, the gl_prompt_style() function can be used to enable optional
 347        formatting directives within the prompt.
 348 
 349 
 350        The style argument, which specifies the formatting style, can take any
 351        of the following values:
 352 
 353        GL_FORMAT_PROMPT
 354                             In this style, the formatting directives described
 355                             below, when included in prompt strings, are
 356                             interpreted as follows:
 357 
 358                             %B
 359                                   Display subsequent characters with a bold
 360                                   font.
 361 
 362 
 363                             %b
 364                                   Stop displaying characters with the bold
 365                                   font.
 366 
 367 
 368                             %F
 369                                   Make subsequent characters flash.
 370 
 371 
 372                             %f
 373                                   Turn off flashing characters.
 374 
 375 
 376                             %U
 377                                   Underline subsequent characters.
 378 
 379 
 380                             %u
 381                                   Stop underlining characters.
 382 
 383 
 384                             %P
 385                                   Switch to a pale (half brightness) font.
 386 
 387 
 388                             %p
 389                                   Stop using the pale font.
 390 
 391 
 392                             %S
 393                                   Highlight subsequent characters (also known
 394                                   as standout mode).
 395 
 396 
 397                             %s
 398                                   Stop highlighting characters.
 399 
 400 
 401                             %V
 402                                   Turn on reverse video.
 403 
 404 
 405                             %v
 406                                   Turn off reverse video.
 407 
 408 
 409                             %%
 410                                   Display a single % character.
 411 
 412                             For example, in this mode, a prompt string like
 413                             "%UOK%u$" would display the prompt "OK$", but with
 414                             the OK part underlined.
 415 
 416                             Note that although a pair of characters that
 417                             starts with a % character, but does not match any
 418                             of the above directives is displayed literally, if
 419                             a new directive is subsequently introduced which
 420                             does match, the displayed prompt will change, so
 421                             it is better to always use %% to display a literal
 422                             %.
 423 
 424                             Also note that not all terminals support all of
 425                             these text attributes, and that some substitute a
 426                             different attribute for missing ones.
 427 
 428 
 429        GL_LITERAL_PROMPT
 430                             In this style, the prompt string is printed
 431                             literally. This is the default style.
 432 
 433 
 434    Alternate Configuration Sources
 435        By default users have the option of configuring the behavior of
 436        gl_get_line() with a configuration file called .teclarc in their home
 437        directories. The fact that all applications share this same
 438        configuration file is both an advantage and a disadvantage. In most
 439        cases it is an advantage, since it encourages uniformity, and frees the
 440        user from having to configure each application separately. In some
 441        applications, however, this single means of configuration is a problem.
 442        This is particularly true of embedded software, where there's no
 443        filesystem to read a configuration file from, and also in applications
 444        where a radically different choice of keybindings is needed to emulate
 445        a legacy keyboard interface. To cater for such cases, the
 446        gl_configure_getline() function allows the application to control where
 447        configuration information is read from.
 448 
 449 
 450        The gl_configure_getline() function allows the configuration commands
 451        that would normally be read from a user's ~/.teclarc file, to be read
 452        from any or none of, a string, an application specific configuration
 453        file, and/or a user-specific configuration file. If this function is
 454        called before the first call to gl_get_line(), the default behavior of
 455        reading ~/.teclarc on the first call to gl_get_line() is disabled, so
 456        all configurations must be achieved using the configuration sources
 457        specified with this function.
 458 
 459 
 460        If app_string != NULL, then it is interpreted as a string containing
 461        one or more configuration commands, separated from each other in the
 462        string by embedded newline  characters. If app_file != NULL then it is
 463        interpreted as the full pathname of an application-specific
 464        configuration file. If user_file != NULL then it is interpreted as the
 465        full path name of a user-specific configuration file, such as
 466        ~/.teclarc. For example, in the call
 467 
 468          gl_configure_getline(gl, "edit-mode vi \n nobeep",
 469                               "/usr/share/myapp/teclarc", "~/.teclarc");
 470 
 471 
 472 
 473        The app_string argument causes the calling application to start in
 474        vi(1) edit-mode, instead of the default emacs mode, and turns off the
 475        use of the terminal bell by the library. It then attempts to read
 476        system-wide configuration commands from an optional file called
 477        /usr/share/myapp/teclarc, then finally reads user-specific
 478        configuration commands from an optional .teclarc file in the user's
 479        home directory.  Note that the arguments are listed in ascending order
 480        of priority, with the contents of app_string being potentially
 481        overridden by commands in app_file, and commands in app_file
 482        potentially being overridden by commands in user_file.
 483 
 484 
 485        You can call this function as many times as needed, the results being
 486        cumulative, but note that copies of any file names specified with the
 487        app_file and user_file arguments are recorded internally for subsequent
 488        use by the read-init-files key-binding function, so if you plan to call
 489        this function multiple times, be sure that the last call specifies the
 490        filenames that you want re-read when the user requests that the
 491        configuration files be re-read.
 492 
 493 
 494        Individual key sequences can also be bound and unbound using the
 495        gl_bind_keyseq() function. The origin argument specifies the priority
 496        of the binding, according to whom it is being established for, and must
 497        be one of the following two values.
 498 
 499        GL_USER_KEY
 500                       The user requested this key-binding.
 501 
 502 
 503        GL_APP_KEY
 504                       This is a default binding set by the application.
 505 
 506 
 507 
 508        When both user and application bindings for a given key sequence have
 509        been specified, the user binding takes precedence. The application's
 510        binding is subsequently reinstated if the user's binding is later
 511        unbound with either another call to this function, or a call to
 512        gl_configure_getline().
 513 
 514 
 515        The keyseq argument specifies the key sequence to be bound or unbound,
 516        and is expressed in the same way as in a ~/.teclarc configuration file.
 517        The action argument must either be a string containing the name of the
 518        action to bind the key sequence to, or it must be NULL or "" to unbind
 519        the key sequence.
 520 
 521    Customized Word Completion
 522        If in your application you would like to have TAB completion complete
 523        other things in addition to or instead of filenames, you can arrange
 524        this by registering an alternate completion callback function with a
 525        call to the gl_customize_completion() function.
 526 
 527 
 528        The data argument provides a way for your application to pass
 529        arbitrary, application-specific information to the callback function.
 530        This is passed to the callback every time that it is called. It might
 531        for example point to the symbol table from which possible completions
 532        are to be sought. The match_fn argument specifies the callback function
 533        to be called. The CplMatchFn function type is defined in <libtecla.h>,
 534        as is a CPL_MATCH_FN() macro that you can use to declare and prototype
 535        callback functions. The declaration and responsibilities of callback
 536        functions are described in depth on the cpl_complete_word(3TECLA)
 537        manual page.
 538 
 539 
 540        The callback function is responsible for looking backwards in the input
 541        line from the point at which the user pressed TAB, to find the start of
 542        the word being completed. It then must lookup possible completions of
 543        this word, and record them one by one in the WordCompletion object that
 544        is passed to it as an argument, by calling the cpl_add_completion()
 545        function. If the callback function wants to provide filename completion
 546        in addition to its own specific completions, it has the option of
 547        itself calling the builtin filename completion callback. This is also
 548        documented in the cpl_complete_word(3TECLA) manual page.
 549 
 550 
 551        If you would like gl_get_line() to return the current input line when a
 552        successful completion has been made, you can arrange this when you call
 553        cpl_add_completion() by making the last character of the continuation
 554        suffix a newline character. The input line will be updated to display
 555        the completion, together with any continuation suffix up to the newline
 556        character, and gl_get_line() will return this input line.
 557 
 558 
 559        If your callback function needs to write something to the terminal, it
 560        must call gl_normal_io() before doing so. This will start a new line
 561        after the input line that is currently being edited, reinstate normal
 562        terminal I/O, and notify gl_get_line() that the input line will need to
 563        be redrawn when the callback returns.
 564 
 565    Adding Completion Actions
 566        In the previous section the ability to customize the behavior of the
 567        only default completion action, complete-word, was described. In this
 568        section the ability to install additional action functions, so that
 569        different types of word completion can be bound to different key
 570        sequences, is described. This is achieved by using the
 571        gl_completion_action() function.
 572 
 573 
 574        The data and match_fn arguments are as described on the
 575        cpl_complete_word(3TECLA) manual page, and specify the callback
 576        function that should be invoked to identify possible completions. The
 577        list_only argument determines whether the action that is being defined
 578        should attempt to complete the word as far as possible in the input
 579        line before displaying any possible ambiguous completions, or whether
 580        it should simply display the list of possible completions without
 581        touching the input line. The former option is selected by specifying a
 582        value of 0, and the latter by specifying a value of 1.  The name
 583        argument specifies the name by which configuration files and future
 584        invocations of this function should refer to the action. This must
 585        either be the name of an existing completion action to be changed, or
 586        be a new unused name for a new action. Finally, the keyseq argument
 587        specifies the default key sequence to bind the action to. If this is
 588        NULL, no new key sequence will be bound to the action.
 589 
 590 
 591        Beware that in order for the user to be able to change the key sequence
 592        that is bound to actions that are installed in this manner, you should
 593        call gl_completion_action() to install a given action for the first
 594        time between calling new_GetLine() and the first call to gl_get_line().
 595        Otherwise, when the user's configuration file is read on the first call
 596        to gl_get_line(), the name of the your additional action will not be
 597        known, and any reference to it in the configuration file will generate
 598        an error.
 599 
 600 
 601        As discussed for gl_customize_completion(), if your callback function
 602        needs to write anything to the terminal, it must call gl_normal_io()
 603        before doing so.
 604 
 605    Defining Custom Actions
 606        Although the built-in key-binding actions are sufficient for the needs
 607        of most applications, occasionally a specialized application may need
 608        to define one or more custom actions, bound to application-specific key
 609        sequences. For example, a sales application would benefit from having a
 610        key sequence that displayed the part name that corresponded to a part
 611        number preceding the cursor. Such a feature is clearly beyond the scope
 612        of the built-in action functions. So for such special cases, the
 613        gl_register_action() function is provided.
 614 
 615 
 616        The gl_register_action() function lets the application register an
 617        external function, fn, that will thereafter be called whenever either
 618        the specified key sequence, keyseq, is entered by the user, or the user
 619        enters any other key sequence that the user subsequently binds to the
 620        specified action name, name, in their configuration file. The data
 621        argument can be a pointer to anything that the application wants to
 622        have passed to the action function, fn, whenever that function is
 623        invoked.
 624 
 625 
 626        The action function, fn, should be declared using the GL_ACTION_FN()
 627        macro, which is defined in <libtecla.h>.
 628 
 629          #define GL_ACTION_FN(fn) GlAfterAction (fn)(GetLine *gl, \
 630                                 void *data, int count, size_t curpos, \
 631                                 const char *line)
 632 
 633 
 634 
 635        The gl and data arguments are those that were previously passed to
 636        gl_register_action() when the action function was registered. The count
 637        argument is a numeric argument which the user has the option of
 638        entering using the digit-argument action, before invoking the action.
 639        If the user does not enter a number, then the count argument is set to
 640        1.  Nominally this argument is interpreted as a repeat count, meaning
 641        that the action should be repeated that many times. In practice
 642        however, for some actions a repeat count makes little sense. In such
 643        cases, actions can either simply ignore the count argument, or use its
 644        value for a different purpose.
 645 
 646 
 647        A copy of the current input line is passed in the read-only line
 648        argument. The current cursor position within this string is given by
 649        the index contained in the curpos argument. Note that direct
 650        manipulation of the input line and the cursor position is not permitted
 651        because the rules dictated by various modes (such as vi mode versus
 652        emacs mode, no-echo mode, and insert mode versus overstrike mode) make
 653        it too complex for an application writer to write a conforming editing
 654        action, as well as constrain future changes to the internals of
 655        gl_get_line(). A potential solution to this dilemma would be to allow
 656        the action function to edit the line using the existing editing
 657        actions. This is currently under consideration.
 658 
 659 
 660        If the action function wishes to write text to the terminal without
 661        this getting mixed up with the displayed text of the input line, or
 662        read from the terminal without having to handle raw terminal I/O, then
 663        before doing either of these operations, it must temporarily suspend
 664        line editing by calling the gl_normal_io() function. This function
 665        flushes any pending output to the terminal, moves the cursor to the
 666        start of the line that follows the last terminal line of the input
 667        line, then restores the terminal to a state that is suitable for use
 668        with the C stdio facilities. The latter includes such things as
 669        restoring the normal mapping of \n to \r\n, and, when in server mode,
 670        restoring the normal blocking form of terminal I/O. Having called this
 671        function, the action function can read from and write to the terminal
 672        without the fear of creating a mess. It is not necessary for the action
 673        function to restore the original editing environment before it returns.
 674        This is done automatically by gl_get_line() after the action function
 675        returns. The following is a simple example of an action function which
 676        writes the sentence "Hello world" on a new terminal line after the line
 677        being edited. When this function returns, the input line is redrawn on
 678        the line that follows the "Hello world" line, and line editing resumes.
 679 
 680          static GL_ACTION_FN(say_hello_fn)
 681          {
 682              if(gl_normal_io(gl))   /* Temporarily suspend editing */
 683                  return GLA_ABORT;
 684              printf("Hello world\n");
 685              return GLA_CONTINUE;
 686          }
 687 
 688 
 689 
 690        Action functions must return one of the following values, to tell
 691        gl_get_line() how to proceed.
 692 
 693        GLA_ABORT
 694                        Cause gl_get_line() to return NULL.
 695 
 696 
 697        GLA_RETURN
 698                        Cause gl_get_line() to return the completed input line
 699 
 700 
 701        GLA_CONTINUE
 702                        Resume command-line editing.
 703 
 704 
 705 
 706        Note that the name argument of gl_register_action() specifies the name
 707        by which a user can refer to the action in their configuration file.
 708        This allows them to re-bind the action to an alternate key-sequence. In
 709        order for this to work, it is necessary to call gl_register_action()
 710        between calling new_GetLine() and the first call to gl_get_line().
 711 
 712    History Files
 713        To save the contents of the history buffer before quitting your
 714        application and subsequently restore them when you next start the
 715        application, the gl_save_history() and gl_load_history() functions are
 716        provided.
 717 
 718 
 719        The filename argument specifies the name to give the history file when
 720        saving, or the name of an existing history file, when loading. This may
 721        contain home directory and environment variable expressions, such as
 722        ~/.myapp_history or $HOME/.myapp_history.
 723 
 724 
 725        Along with each history line, additional information about it, such as
 726        its nesting level and when it was entered by the user, is recorded as a
 727        comment preceding the line in the history file. Writing this as a
 728        comment allows the history file to double as a command file, just in
 729        case you wish to replay a whole session using it. Since comment
 730        prefixes differ in different languages, the comment argument is
 731        provided for specifying the comment prefix. For example, if your
 732        application were a UNIX shell, such as the Bourne shell, you would
 733        specify "#" here. Whatever you choose for the comment character, you
 734        must specify the same prefix to gl_load_history() that you used when
 735        you called gl_save_history() to write the history file.
 736 
 737 
 738        The max_lines argument must be either -1 to specify that all lines in
 739        the history list be saved, or a positive number specifying a ceiling on
 740        how many of the most recent lines should be saved.
 741 
 742 
 743        Both functions return non-zero on error, after writing an error message
 744        to stderr. Note that gl_load_history() does not consider the non-
 745        existence of a file to be an error.
 746 
 747    Multiple History Lists
 748        If your application uses a single GetLine object for entering many
 749        different types of input lines, you might want gl_get_line() to
 750        distinguish the different types of lines in the history list, and only
 751        recall lines that match the current type of line. To support this
 752        requirement, gl_get_line() marks lines being recorded in the history
 753        list with an integer identifier chosen by the application. Initially
 754        this identifier is set to 0 by new_GetLine(), but it can be changed
 755        subsequently by calling gl_group_history().
 756 
 757 
 758        The integer identifier ID can be any number chosen by the application,
 759        but note that gl_save_history() and gl_load_history() preserve the
 760        association between identifiers and historical input lines between
 761        program invocations, so you should choose fixed identifiers for the
 762        different types of input line used by your application.
 763 
 764 
 765        Whenever gl_get_line() appends a new input line to the history list,
 766        the current history identifier is recorded with it, and when it is
 767        asked to recall a historical input line, it only recalls lines that are
 768        marked with the current identifier.
 769 
 770    Displaying History
 771        The history list can be displayed by calling gl_show_history(). This
 772        function displays the current contents of the history list to the stdio
 773        output stream fp. If the max_lines argument is greater than or equal to
 774        zero, then no more than this number of  the most recent lines will be
 775        displayed. If the all_groups argument is non-zero, lines from all
 776        history groups are displayed. Otherwise only those of the currently
 777        selected history group are displayed. The format string argument, fmt,
 778        determines how the line is displayed. This can contain arbitrary
 779        characters which are written verbatim, interleaved with any of the
 780        following format directives:
 781 
 782        %D
 783              The date on which the line was originally entered, formatted like
 784              2001-11-20.
 785 
 786 
 787        %T
 788              The time of day when the line was entered, formatted like
 789              23:59:59.
 790 
 791 
 792        %N
 793              The sequential entry number of the line in the history buffer.
 794 
 795 
 796        %G
 797              The number of the history group which the line belongs to.
 798 
 799 
 800        %%
 801              A literal % character.
 802 
 803 
 804        %H
 805              The history line itself.
 806 
 807 
 808 
 809        Thus a format string like "%D %T %H0" would output something like:
 810 
 811          2001-11-20 10:23:34  Hello world
 812 
 813 
 814 
 815        Note the inclusion of an explicit newline character in the format
 816        string.
 817 
 818    Looking Up History
 819        The gl_lookup_history() function allows the calling application to look
 820        up lines in the history list.
 821 
 822 
 823        The id argument indicates which line to look up, where the first line
 824        that was entered in the history list after new_GetLine() was called is
 825        denoted by 0, and subsequently entered lines are denoted with
 826        successively higher numbers. Note that the range of lines currently
 827        preserved in the history list can be queried by calling the
 828        gl_range_of_history() function. If the requested line is in the history
 829        list, the details of the line are recorded in the variable pointed to
 830        by the hline argument, and 1 is returned.  Otherwise 0 is returned, and
 831        the variable pointed to by hline is left unchanged.
 832 
 833 
 834        Beware that the string returned in hline->line is part of the history
 835        buffer, so it must not be modified by the caller, and will be recycled
 836        on the next call to any function that takes gl as its argument.
 837        Therefore you should make a private copy of this string if you need to
 838        keep it.
 839 
 840    Manual History Archival
 841        By default, whenever a line is entered by the user, it is automatically
 842        appended to the history list, just before gl_get_line() returns the
 843        line to the caller. This is convenient for the majority of
 844        applications, but there are also applications that need finer-grained
 845        control over what gets added to the history list. In such cases, the
 846        automatic addition of entered lines to the history list can be turned
 847        off by calling the gl_automatic_history() function.
 848 
 849 
 850        If this function is called with its enable argument set to 0,
 851        gl_get_line() will not automatically archive subsequently entered
 852        lines.  Automatic archiving can be reenabled at a later time by calling
 853        this function again, with its enable argument set to 1. While automatic
 854        history archiving is disabled, the calling application can use the
 855        gl_append_history() to append lines to the history list as needed.
 856 
 857 
 858        The line argument specifies the line to be added to the history list.
 859        This must be a normal '\0 ' terminated string. If this string contains
 860        any newline characters, the line that gets archived in the history list
 861        will be terminated by the first of these. Otherwise it will be
 862        terminated by the '\0 ' terminator. If the line is longer than the
 863        maximum input line length that was specified when new_GetLine() was
 864        called, it will be truncated to the actual gl_get_line() line length
 865        when the line is recalled.
 866 
 867 
 868        If successful, gl_append_history() returns 0. Otherwise it returns non-
 869        zero and sets errno to one of the following values.
 870 
 871        EINVAL
 872                  One of the arguments passed to gl_append_history() was NULL.
 873 
 874 
 875        ENOMEM
 876                  The specified line was longer than the allocated size of the
 877                  history buffer (as specified when new_GetLine() was called),
 878                  so it could not be archived.
 879 
 880 
 881 
 882        A textual description of the error can optionally be obtained by
 883        calling gl_error_message(). Note that after such an error, the history
 884        list remains in a valid state to receive new history lines, so there is
 885        little harm in simply ignoring the return status of
 886        gl_append_history().
 887 
 888    Miscellaneous History Configuration
 889        If you wish to change the size of the history buffer that was
 890        originally specified in the call to new_GetLine(), you can do so with
 891        the gl_resize_history() function.
 892 
 893 
 894        The histlen argument specifies the new size in bytes, and if you
 895        specify this as 0, the buffer will be deleted.
 896 
 897 
 898        As mentioned in the discussion of new_GetLine(), the number of lines
 899        that can be stored in the history buffer, depends on the lengths of the
 900        individual lines. For example, a 1000 byte buffer could equally store
 901        10 lines of average length 100 bytes, or 20 lines of average length 50
 902        bytes. Although the buffer is never expanded when new lines are added,
 903        a list of pointers into the buffer does get expanded when needed to
 904        accommodate the number of lines currently stored in the buffer. To
 905        place an upper limit on the number of lines in the buffer, and thus a
 906        ceiling on the amount of memory used in this list, you can call the
 907        gl_limit_history() function.
 908 
 909 
 910        The max_lines should either be a positive number >= 0, specifying an
 911        upper limit on the number of lines in the buffer, or be -1 to cancel
 912        any previously specified limit. When a limit is in effect, only the
 913        max_lines most recently appended lines are kept in the buffer. Older
 914        lines are discarded.
 915 
 916 
 917        To discard lines from the history buffer, use the gl_clear_history()
 918        function.
 919 
 920 
 921        The all_groups argument tells the function whether to delete just the
 922        lines associated with the current history group (see
 923        gl_group_history()) or all historical lines in the buffer.
 924 
 925 
 926        The gl_toggle_history() function allows you to toggle history on and
 927        off without losing the current contents of the history list.
 928 
 929 
 930        Setting the enable argument to 0 turns off the history mechanism, and
 931        setting it to 1 turns it back on. When history is turned off, no new
 932        lines will be added to the history list, and history lookup key-
 933        bindings will act as though there is nothing in the history buffer.
 934 
 935    Querying History Information
 936        The configured state of the history list can be queried with the
 937        gl_history_state() function. On return, the status information is
 938        recorded in the variable pointed to by the state argument.
 939 
 940 
 941        The gl_range_of_history() function returns the number and range of
 942        lines in the history list. The return values are recorded in the
 943        variable pointed to by the range argument. If the nlines member of this
 944        structure is greater than zero, then the oldest and newest members
 945        report the range of lines in the list, and newest=oldest+nlines-1.
 946        Otherwise they are both zero.
 947 
 948 
 949        The gl_size_of_history() function returns the total size of the history
 950        buffer and the amount of the buffer that is currently occupied.
 951 
 952 
 953        On return, the size information is recorded in the variable pointed to
 954        by the size argument.
 955 
 956    Changing Terminals
 957        The new_GetLine() constructor function assumes that input is to be read
 958        from stdin and output written to stdout. The following function allows
 959        you to switch to different input and output streams.
 960 
 961 
 962        The gl argument is the object that was returned by new_GetLine().  The
 963        input_fp argument specifies the stream to read from, and output_fp
 964        specifies the stream to be written to. Only if both of these refer to a
 965        terminal, will interactive terminal input be enabled. Otherwise
 966        gl_get_line() will simply call fgets() to read command input. If both
 967        streams refer to a terminal, then they must refer to the same terminal,
 968        and the type of this terminal must be specified with the term argument.
 969        The value of the term argument is looked up in the terminal information
 970        database (terminfo or termcap), in order to determine which special
 971        control sequences are needed to control various aspects of the
 972        terminal.  new_GetLine() for example, passes the return value of
 973        getenv("TERM") in this argument. Note that if one or both of input_fp
 974        and output_fp do not refer to a terminal, then it is legal to pass NULL
 975        instead of a terminal type.
 976 
 977 
 978        Note that if you want to pass file descriptors to gl_change_terminal(),
 979        you can do this by creating stdio stream wrappers using the POSIX
 980        fdopen(3C) function.
 981 
 982    External Event Handling
 983        By default, gl_get_line() does not return until either a complete input
 984        line has been entered by the user, or an error occurs. In programs that
 985        need to watch for I/O from other sources than the terminal, there are
 986        two options.
 987 
 988            o      Use the functions described in the gl_io_mode(3TECLA) manual
 989                   page to switch gl_get_line() into non-blocking server mode.
 990                   In this mode, gl_get_line() becomes a non-blocking,
 991                   incremental line-editing function that can safely be called
 992                   from an external event loop. Although this is a very
 993                   versatile method, it involves taking on some
 994                   responsibilities that are normally performed behind the
 995                   scenes by gl_get_line().
 996 
 997            o      While gl_get_line() is waiting for keyboard input from the
 998                   user, you can ask it to also watch for activity on arbitrary
 999                   file descriptors, such as network sockets or pipes, and have
1000                   it call functions of your choosing when activity is seen.
1001                   This works on any system that has the select system call,
1002                   which is most, if not all flavors of UNIX.
1003 
1004 
1005        Registering a file descriptor to be watched by gl_get_line() involves
1006        calling the gl_watch_fd() function. If this returns non-zero, then it
1007        means that either your arguments are invalid, or that this facility is
1008        not supported on the host system.
1009 
1010 
1011        The fd argument is the file descriptor to be watched. The event
1012        argument specifies what type of activity is of interest, chosen from
1013        the following enumerated values:
1014 
1015        GLFD_READ
1016                       Watch for the arrival of data to be read.
1017 
1018 
1019        GLFD_WRITE
1020                       Watch for the ability to write to the file descriptor
1021                       without blocking.
1022 
1023 
1024        GLFD_URGENT
1025                       Watch for the arrival of urgent out-of-band data on the
1026                       file descriptor.
1027 
1028 
1029 
1030        The callback argument is the function to call when the selected
1031        activity is seen. It should be defined with the following macro, which
1032        is defined in libtecla.h.
1033 
1034          #define GL_FD_EVENT_FN(fn) GlFdStatus (fn)(GetLine *gl,                                    void *data, int fd, GlFdEvent event)
1035 
1036 
1037 
1038        The data argument of the gl_watch_fd() function is passed to the
1039        callback function for its own use, and can point to anything you like,
1040        including NULL. The file descriptor and the event argument are also
1041        passed to the callback function, and this potentially allows the same
1042        callback function to be registered to more than one type of event
1043        and/or more than one file descriptor.  The return value of the callback
1044        function should be one of the following values.
1045 
1046        GLFD_ABORT
1047                         Tell gl_get_line() to abort. When this happens,
1048                         gl_get_line() returns NULL, and a following call to
1049                         gl_return_status() will return GLR_FDABORT. Note that
1050                         if the application needs errno always to have a
1051                         meaningful value when gl_get_line() returns NULL, the
1052                         callback function should set errno appropriately.
1053 
1054 
1055        GLFD_REFRESH
1056                         Redraw the input line  then continue waiting for
1057                         input. Return this if your callback wrote to the
1058                         terminal.
1059 
1060 
1061        GLFD_CONTINUE
1062                         Continue to wait for input, without redrawing the
1063                         line.
1064 
1065 
1066 
1067        Note that before calling the callback, gl_get_line() blocks most
1068        signals and leaves its own signal handlers installed, so if you need to
1069        catch a particular signal you will need to both temporarily install
1070        your own signal handler, and unblock the signal. Be sure to re-block
1071        the signal (if it was originally blocked) and reinstate the original
1072        signal handler, if any, before returning.
1073 
1074 
1075        Your callback should not try to read from the terminal, which is left
1076        in raw mode as far as input is concerned. You can write to the terminal
1077        as usual, since features like conversion of newline to carriage-
1078        return/linefeed are re-enabled while the callback is running. If your
1079        callback function does write to the terminal, be sure to output a
1080        newline first, and when your callback returns, tell gl_get_line() that
1081        the input line needs to be redrawn, by returning the GLFD_REFRESH
1082        status code.
1083 
1084 
1085        To remove a callback function that you previously registered for a
1086        given file descriptor and event, simply call gl_watch_fd() with the
1087        same fd and event arguments, but with a callback argument of 0. The
1088        data argument is ignored in this case.
1089 
1090    Setting An Inactivity Timeout
1091        The gl_inactivity_timeout() function can be used to set or cancel an
1092        inactivity timeout. Inactivity in this case refers both to keyboard
1093        input, and to I/O on any file descriptors registered by prior and
1094        subsequent calls to gl_watch_fd().
1095 
1096 
1097        The timeout is specified in the form of an integral number of seconds
1098        and an integral number of nanoseconds, specified by the sec and nsec
1099        arguments, respectively. Subsequently, whenever no activity is seen for
1100        this time period, the function specified by the callback argument is
1101        called.  The data argument of gl_inactivity_timeout() is passed to this
1102        callback function whenever it is invoked, and can thus be used to pass
1103        arbitrary application-specific information to the callback. The
1104        following macro is provided in <libtecla.h> for applications to use to
1105        declare and prototype timeout callback functions.
1106 
1107          #define GL_TIMEOUT_FN(fn) GlAfterTimeout (fn)(GetLine *gl, void *data)
1108 
1109 
1110 
1111        On returning, the application's callback is expected to return one of
1112        the following enumerators to tell gl_get_line() how to proceed after
1113        the timeout has been handled by the callback.
1114 
1115        GLTO_ABORT
1116                         Tell gl_get_line() to abort. When this happens,
1117                         gl_get_line() will return NULL, and a following call
1118                         to gl_return_status() will return GLR_TIMEOUT. Note
1119                         that if the application needs errno always to have a
1120                         meaningful value when gl_get_line() returns NULL, the
1121                         callback function should set errno appropriately.
1122 
1123 
1124        GLTO_REFRESH
1125                         Redraw the input line, then continue waiting for
1126                         input. You should return this value if your callback
1127                         wrote to the terminal.
1128 
1129 
1130        GLTO_CONTINUE
1131                         In normal blocking-I/O mode, continue to wait for
1132                         input, without redrawing the user's input line. In
1133                         non-blocking server I/O mode (see gl_io_mode(3TECLA)),
1134                         gl_get_line() acts as though I/O blocked. This means
1135                         that gl_get_line() will immediately return NULL, and a
1136                         following call to gl_return_status() will return
1137                         GLR_BLOCKED.
1138 
1139 
1140 
1141        Note that before calling the callback, gl_get_line() blocks most
1142        signals and leaves its own signal handlers installed, so if you need to
1143        catch a particular signal you will need to both temporarily install
1144        your own signal handler and unblock the signal. Be sure to re-block the
1145        signal (if it was originally blocked) and reinstate the original signal
1146        handler, if any, before returning.
1147 
1148 
1149        Your callback should not try to read from the terminal, which is left
1150        in raw mode as far as input is concerned. You can however write to the
1151        terminal as usual, since features like conversion of newline to
1152        carriage-return/linefeed are re-enabled while the callback is running.
1153        If your callback function does write to the terminal, be sure to output
1154        a newline first, and when your callback returns, tell gl_get_line()
1155        that the input line needs to be redrawn, by returning the GLTO_REFRESH
1156        status code.
1157 
1158 
1159        Finally, note that although the timeout arguments include a nanosecond
1160        component, few computer clocks presently have resolutions that are
1161        finer than a few milliseconds, so asking for less than a few
1162        milliseconds is equivalent to requesting zero seconds on many systems.
1163        If this would be a problem, you should base your timeout selection on
1164        the actual resolution of the host clock (for example, by calling
1165        sysconf(_SC_CLK_TCK)).
1166 
1167 
1168        To turn off timeouts, simply call gl_inactivity_timeout() with a
1169        callback argument of 0. The data argument is ignored in this case.
1170 
1171    Signal Handling Defaults
1172        By default, the gl_get_line() function intercepts a number of signals.
1173        This is particularly important for signals that would by default
1174        terminate the process, since the terminal needs to be restored to a
1175        usable state before this happens. This section describes the signals
1176        that are trapped by default and how gl_get_line() responds to them.
1177        Changing these defaults is the topic of the following section.
1178 
1179 
1180        When the following subset of signals are caught, gl_get_line() first
1181        restores the terminal settings and signal handling to how they were
1182        before gl_get_line() was called, resends the signal to allow the
1183        calling application's signal handlers to handle it, then, if the
1184        process still exists, returns NULL and sets errno as specified below.
1185 
1186        SIGINT
1187                   This signal is generated both by the keyboard interrupt key
1188                   (usually ^C), and the keyboard break key. The errno value is
1189                   EINTR.
1190 
1191 
1192        SIGHUP
1193                   This signal is generated when the controlling terminal
1194                   exits. The errno value is ENOTTY.
1195 
1196 
1197        SIGPIPE
1198                   This signal is generated when a program attempts to write to
1199                   a pipe whose remote end is not being read by any process.
1200                   This can happen for example if you have called
1201                   gl_change_terminal() to redirect output to a pipe hidden
1202                   under a pseudo terminal. The errno value is EPIPE.
1203 
1204 
1205        SIGQUIT
1206                   This signal is generated by the keyboard quit key (usually
1207                   ^\). The errno value is EINTR.
1208 
1209 
1210        SIGABRT
1211                   This signal is generated by the standard C, abort function.
1212                   By default it both terminates the process and generates a
1213                   core dump. The errno value is EINTR.
1214 
1215 
1216        SIGTERM
1217                   This is the default signal that the UNIX kill command sends
1218                   to processes. The errno value is EINTR.
1219 
1220 
1221 
1222        Note that in the case of all of the above signals, POSIX mandates that
1223        by default the process is terminated, with the addition of a core dump
1224        in the case of the SIGQUIT signal. In other words, if the calling
1225        application does not override the default handler by supplying its own
1226        signal handler, receipt of the corresponding signal will terminate the
1227        application before gl_get_line() returns.
1228 
1229 
1230        If gl_get_line() aborts with errno set to EINTR, you can find out what
1231        signal caused it to abort, by calling the gl_last_signal() function.
1232        This returns the numeric code (for example, SIGINT) of the last signal
1233        that was received during the most recent call to gl_get_line(), or -1
1234        if no signals were received.
1235 
1236 
1237        On systems that support it, when a SIGWINCH (window change) signal is
1238        received, gl_get_line() queries the terminal to find out its new size,
1239        redraws the current input line to accommodate the new size, then
1240        returns to waiting for keyboard input from the user. Unlike other
1241        signals, this signal is not resent to the application.
1242 
1243 
1244        Finally, the following signals cause gl_get_line() to first restore the
1245        terminal and signal environment to that which prevailed before
1246        gl_get_line() was called, then resend the signal to the application. If
1247        the process still exists after the signal has been delivered, then
1248        gl_get_line() then re-establishes its own signal handlers, switches the
1249        terminal back to raw mode, redisplays the input line, and goes back to
1250        awaiting terminal input from the user.
1251 
1252        SIGCONT
1253                     This signal is generated when a suspended process is
1254                     resumed.
1255 
1256 
1257        SIGPOLL
1258                     On SVR4 systems, this signal notifies the process of an
1259                     asynchronous I/O event.  Note that under 4.3+BSD, SIGIO
1260                     and SIGPOLL are the same. On other systems, SIGIO is
1261                     ignored by default, so gl_get_line() does not trap it by
1262                     default.
1263 
1264 
1265        SIGPWR
1266                     This signal is generated when a power failure occurs
1267                     (presumably when the system is on a UPS).
1268 
1269 
1270        SIGALRM
1271                     This signal is generated when a timer expires.
1272 
1273 
1274        SIGUSR1
1275                     An application specific signal.
1276 
1277 
1278        SIGUSR2
1279                     Another application specific signal.
1280 
1281 
1282        SIGVTALRM
1283                     This signal is generated when a virtual timer expires. See
1284                     setitimer(2).
1285 
1286 
1287        SIGXCPU
1288                     This signal is generated when a process exceeds its soft
1289                     CPU time limit.
1290 
1291 
1292        SIGXFSZ
1293                     This signal is generated when a process exceeds its soft
1294                     file-size limit.
1295 
1296 
1297        SIGTSTP
1298                     This signal is generated by the terminal suspend key,
1299                     which is usually ^Z, or the delayed terminal suspend key,
1300                     which is usually ^Y.
1301 
1302 
1303        SIGTTIN
1304                     This signal is generated if the program attempts to read
1305                     from the terminal while the program is running in the
1306                     background.
1307 
1308 
1309        SIGTTOU
1310                     This signal is generated if the program attempts to write
1311                     to the terminal while the program is running in the
1312                     background.
1313 
1314 
1315 
1316        Obviously not all of the above signals are supported on all systems, so
1317        code to support them is conditionally compiled into the tecla library.
1318 
1319 
1320        Note that if SIGKILL or SIGPOLL, which by definition cannot be caught,
1321        or any of the hardware generated exception signals, such as SIGSEGV,
1322        SIGBUS, and SIGFPE, are received and unhandled while gl_get_line() has
1323        the terminal in raw mode, the program will be terminated without the
1324        terminal having been restored to a usable state. In practice, job-
1325        control shells usually reset the terminal settings when a process
1326        relinquishes the controlling terminal, so this is only a problem with
1327        older shells.
1328 
1329    Customized Signal Handling
1330        The previous section listed the signals that gl_get_line() traps by
1331        default, and described how it responds to them. This section describes
1332        how to both add and remove signals from the list of trapped signals,
1333        and how to specify how gl_get_line() should respond to a given signal.
1334 
1335 
1336        If you do not need gl_get_line() to do anything in response to a signal
1337        that it normally traps, you can tell to gl_get_line() to ignore that
1338        signal by calling gl_ignore_signal().
1339 
1340 
1341        The signo argument is the number of the signal (for example, SIGINT)
1342        that you want to have ignored. If the specified signal is not currently
1343        one of those being trapped, this function does nothing.
1344 
1345 
1346        The gl_trap_signal() function allows you to either add a new signal to
1347        the list that gl_get_line() traps or modify how it responds to a signal
1348        that it already traps.
1349 
1350 
1351        The signo argument is the number of the signal that you want to have
1352        trapped. The flags argument is a set of flags that determine the
1353        environment in which the application's signal handler is invoked. The
1354        after argument tells gl_get_line() what to do after the application's
1355        signal handler returns. The errno_value tells gl_get_line() what to set
1356        errno to if told to abort.
1357 
1358 
1359        The flags argument is a bitwise OR of zero or more of the following
1360        enumerators:
1361 
1362        GLS_RESTORE_SIG
1363                            Restore the caller's signal environment while
1364                            handling the signal.
1365 
1366 
1367        GLS_RESTORE_TTY
1368                            Restore the caller's terminal settings while
1369                            handling the signal.
1370 
1371 
1372        GLS_RESTORE_LINE
1373                            Move the cursor to the start of the line following
1374                            the input line before invoking the application's
1375                            signal handler.
1376 
1377 
1378        GLS_REDRAW_LINE
1379                            Redraw the input line when the application's signal
1380                            handler returns.
1381 
1382 
1383        GLS_UNBLOCK_SIG
1384                            Normally, if the calling program has a signal
1385                            blocked (see sigprocmask(2)), gl_get_line() does
1386                            not trap that signal. This flag tells gl_get_line()
1387                            to trap the signal and unblock it for the duration
1388                            of the call to gl_get_line().
1389 
1390 
1391        GLS_DONT_FORWARD
1392                            If this flag is included, the signal will not be
1393                            forwarded to the signal handler of the calling
1394                            program.
1395 
1396 
1397 
1398        Two commonly useful flag combinations are also enumerated as follows:
1399 
1400        GLS_RESTORE_ENV
1401                             GLS_RESTORE_SIG | GLS_RESTORE_TTY |GLS_REDRAW_LINE
1402 
1403 
1404        GLS_SUSPEND_INPUT
1405                             GLS_RESTORE_ENV | GLS_RESTORE_LINE
1406 
1407 
1408 
1409        If your signal handler, or the default system signal handler for this
1410        signal, if you have not overridden it, never either writes to the
1411        terminal, nor suspends or terminates the calling program, then you can
1412        safely set the flags argument to 0.
1413 
1414            o      The cursor does not get left in the middle of the input
1415                   line.
1416 
1417            o      So that the user can type in input and have it echoed.
1418 
1419            o      So that you do not need to end each output line with \r\n,
1420                   instead of just \n.
1421 
1422 
1423        The GL_RESTORE_ENV combination is the same as GL_SUSPEND_INPUT, except
1424        that it does not move the cursor. If your signal handler does not read
1425        or write anything to the terminal, the user will not see any visible
1426        indication that a signal was caught. This can be useful if you have a
1427        signal handler that only occasionally writes to the terminal, where
1428        using GL_SUSPEND_LINE would cause the input line to be unnecessarily
1429        duplicated when nothing had been written to the terminal. Such a signal
1430        handler, when it does write to the terminal, should be sure to start a
1431        new line at the start of its first write, by writing a new line before
1432        returning. If the signal arrives while the user is entering a line that
1433        only occupies a signal terminal line, or if the cursor is on the last
1434        terminal line of a longer input line, this will have the same effect as
1435        GL_SUSPEND_INPUT. Otherwise it will start writing on a line that
1436        already contains part of the displayed input line. This does not do any
1437        harm, but it looks a bit ugly, which is why the GL_SUSPEND_INPUT
1438        combination is better if you know that you are always going to be
1439        writing to the terminal.
1440 
1441 
1442        The after argument, which determines what gl_get_line() does after the
1443        application's signal handler returns (if  it returns), can take any one
1444        of the following values:
1445 
1446        GLS_RETURN
1447                        Return the completed input line, just as though the
1448                        user had pressed the return key.
1449 
1450 
1451        GLS_ABORT
1452                        Cause gl_get_line() to abort. When this happens,
1453                        gl_get_line() returns NULL, and a following call to
1454                        gl_return_status() will return GLR_SIGNAL. Note that if
1455                        the application needs errno always to have a meaningful
1456                        value when gl_get_line() returns NULL, the callback
1457                        function should set errno appropriately.
1458 
1459 
1460        GLS_CONTINUE
1461                        Resume command line editing.
1462 
1463 
1464 
1465        The errno_value argument is intended to be combined with the GLS_ABORT
1466        option, telling gl_get_line() what to set the standard errno variable
1467        to before returning NULL to the calling program. It can also, however,
1468        be used with the GL_RETURN option, in case you want to have a way to
1469        distinguish between an input line that was entered using the return
1470        key, and one that was entered by the receipt of a signal.
1471 
1472    Reliable Signal Handling
1473        Signal handling is surprisingly hard to do reliably without race
1474        conditions. In gl_get_line() a lot of care has been taken to allow
1475        applications to perform reliable signal handling around gl_get_line().
1476        This section explains how to make use of this.
1477 
1478 
1479        As an example of the problems that can arise if the application is not
1480        written correctly, imagine that one's application has a SIGINT signal
1481        handler that sets a global flag. Now suppose that the application tests
1482        this flag just before invoking gl_get_line(). If a SIGINT signal
1483        happens to be received in the small window of time between the
1484        statement that tests the value of this flag, and the statement that
1485        calls gl_get_line(), then gl_get_line() will not see the signal, and
1486        will not be interrupted. As a result, the application will not be able
1487        to respond to the signal until the user gets around to finishing
1488        entering the input line and gl_get_line() returns. Depending on the
1489        application, this might or might not be a disaster, but at the very
1490        least it would puzzle the user.
1491 
1492 
1493        The way to avoid such problems is to do the following.
1494 
1495            1.     If needed, use the gl_trap_signal() function to configure
1496                   gl_get_line() to abort when important signals are caught.
1497 
1498            2.     Configure gl_get_line() such that if any of the signals that
1499                   it catches are blocked when gl_get_line() is called, they
1500                   will be unblocked automatically during times when
1501                   gl_get_line() is waiting for I/O. This can be done either on
1502                   a per signal basis, by calling the gl_trap_signal()
1503                   function, and specifying the GLS_UNBLOCK attribute of the
1504                   signal, or globally by calling the gl_catch_blocked()
1505                   function. This function simply adds the GLS_UNBLOCK
1506                   attribute to all of the signals that it is currently
1507                   configured to trap.
1508 
1509            3.     Just before calling gl_get_line(), block delivery of all of
1510                   the signals that gl_get_line() is configured to trap. This
1511                   can be done using the POSIX sigprocmask function in
1512                   conjunction with the gl_list_signals() function. This
1513                   function returns the set of signals that it is currently
1514                   configured to catch in the set argument, which is in the
1515                   form required by sigprocmask(2).
1516 
1517            4.     In the example, one would now test the global flag that the
1518                   signal handler sets, knowing that there is now no danger of
1519                   this flag being set again until gl_get_line() unblocks its
1520                   signals while performing I/O.
1521 
1522            5.     Eventually gl_get_line() returns, either because a signal
1523                   was caught, an error occurred, or the user finished entering
1524                   their input line.
1525 
1526            6.     Now one would check the global signal flag again, and if it
1527                   is set, respond to it, and zero the flag.
1528 
1529            7.     Use sigprocmask() to unblock the signals that were blocked
1530                   in step 3.
1531 
1532 
1533        The same technique can be used around certain POSIX signal-aware
1534        functions, such as sigsetjmp(3C) and sigsuspend(2), and in particular,
1535        the former of these two functions can be used in conjunction with
1536        siglongjmp(3C) to implement race-condition free signal handling around
1537        other long-running system calls. The gl_get_line() function manages to
1538        reliably trap signals around calls to functions like read(2) and
1539        select(3C) without race conditions.
1540 
1541 
1542        The gl_get_line() function first uses the POSIX sigprocmask() function
1543        to block the delivery of all of the signals that it is currently
1544        configured to catch. This is redundant if the application has already
1545        blocked them, but it does no harm. It undoes this step just before
1546        returning.
1547 
1548 
1549        Whenever gl_get_line() needs to call read or select to wait for input
1550        from the user, it first calls the POSIX sigsetjmp() function, being
1551        sure to specify a non-zero value for its savemask argument.
1552 
1553 
1554        If sigsetjmp() returns zero, gl_get_line() then does the following.
1555 
1556            1.     It uses the POSIX sigaction(2) function to register a
1557                   temporary signal handler to all of the signals that it is
1558                   configured to catch. This signal handler does two things.
1559 
1560                a.     It records the number of the signal that was received in
1561                       a file-scope variable.
1562 
1563                b.     It then calls the POSIX siglongjmp() function using the
1564                       buffer that was passed to sigsetjmp() for its first
1565                       argument and a non-zero value for its second argument.
1566            When this signal handler is registered, the sa_mask member of the
1567            struct sigaction act argument of the call to sigaction() is
1568            configured to contain all of the signals that gl_get_line() is
1569            catching.  This ensures that only one signal will be caught at once
1570            by our signal handler, which in turn ensures that multiple
1571            instances of our signal handler do not tread on each other's toes.
1572 
1573            2.     Now that the signal handler has been set up, gl_get_line()
1574                   unblocks all of the signals that it is configured to catch.
1575 
1576            3.     It then calls the read() or select() function to wait for
1577                   keyboard input.
1578 
1579            4.     If this function returns (that is, no signal is received),
1580                   gl_get_line() blocks delivery of the signals of interest
1581                   again.
1582 
1583            5.     It then reinstates the signal handlers that were displaced
1584                   by the one that was just installed.
1585 
1586 
1587        Alternatively, if sigsetjmp() returns non-zero, this means that one of
1588        the signals being trapped was caught while the above steps were
1589        executing. When this happens, gl_get_line() does the following.
1590 
1591 
1592        First, note that when a call to siglongjmp() causes sigsetjmp() to
1593        return, provided that the savemask argument of sigsetjmp() was non-
1594        zero, the signal process mask is restored to how it was when
1595        sigsetjmp() was called. This is the important difference between
1596        sigsetjmp() and the older problematic setjmp(3C), and is the essential
1597        ingredient that makes it possible to avoid signal handling race
1598        conditions. Because of this we are guaranteed that all of the signals
1599        that we blocked before calling sigsetjmp() are blocked again as soon as
1600        any signal is caught. The following statements, which are then
1601        executed, are thus guaranteed to be executed without any further
1602        signals being caught.
1603 
1604            1.     If so instructed by the gl_get_line() configuration
1605                   attributes of the signal that was caught, gl_get_line()
1606                   restores the terminal attributes to the state that they had
1607                   when gl_get_line() was called. This is particularly
1608                   important for signals that suspend or terminate the process,
1609                   since otherwise the terminal would be left in an unusable
1610                   state.
1611 
1612            2.     It then reinstates the application's signal handlers.
1613 
1614            3.     Then it uses the C standard-library raise(3C) function to
1615                   re-send the application the signal that was caught.
1616 
1617            4.     Next it unblocks delivery of the signal that we just sent.
1618                   This results in the signal that was just sent by raise()
1619                   being caught by the application's original signal handler,
1620                   which can now handle it as it sees fit.
1621 
1622            5.     If the signal handler returns (that is, it does not
1623                   terminate the process), gl_get_line() blocks delivery of the
1624                   above signal again.
1625 
1626            6.     It then undoes any actions performed in the first of the
1627                   above steps and redisplays the line, if the signal
1628                   configuration calls for this.
1629 
1630            7.     gl_get_line() then either resumes trying to read a
1631                   character, or aborts, depending on the configuration of the
1632                   signal that was caught.
1633 
1634 
1635        What the above steps do in essence is to take asynchronously delivered
1636        signals and handle them synchronously, one at a time, at a point in the
1637        code where gl_get_line() has complete control over its environment.
1638 
1639    The Terminal Size
1640        On most systems the combination of the TIOCGWINSZ ioctl and the
1641        SIGWINCH signal is used to maintain an accurate idea of the terminal
1642        size. The terminal size is newly queried every time that gl_get_line()
1643        is called and whenever a SIGWINCH signal is received.
1644 
1645 
1646        On the few systems where this mechanism is not available, at startup
1647        new_GetLine() first looks for the LINES and COLUMNS environment
1648        variables. If these are not found, or they contain unusable values,
1649        then if a terminal information database like terminfo or termcap is
1650        available, the default size of the terminal is looked up in this
1651        database. If this too fails to provide the terminal size, a default
1652        size of 80 columns by 24 lines is used.
1653 
1654 
1655        Even on systems that do support ioctl(TIOCGWINSZ), if the terminal is
1656        on the other end of a serial line, the terminal driver generally has no
1657        way of detecting when a resize occurs or of querying what the current
1658        size is. In such cases no SIGWINCH is sent to the process, and the
1659        dimensions returned by ioctl(TIOCGWINSZ) are not correct. The only way
1660        to handle such instances is to provide a way for the user to enter a
1661        command that tells the remote system what the new size is. This command
1662        would then call the gl_set_term_size() function to tell gl_get_line()
1663        about the change in size.
1664 
1665 
1666        The ncolumn and nline arguments are used to specify the new dimensions
1667        of the terminal, and must not be less than 1. On systems that do
1668        support ioctl(TIOCGWINSZ), this function first calls ioctl(TIOCSWINSZ)
1669        to tell the terminal driver about the change in size.  In non-blocking
1670        server-I/O mode, if a line is currently being input, the input line is
1671        then redrawn to accommodate the changed size. Finally the new values
1672        are recorded in gl for future use by gl_get_line().
1673 
1674 
1675        The gl_terminal_size() function allows you to query the current size of
1676        the terminal, and install an alternate fallback size for cases where
1677        the size is not available. Beware that the terminal size will not be
1678        available if reading from a pipe or a file, so the default values can
1679        be important even on systems that do support ways of finding out the
1680        terminal size.
1681 
1682 
1683        This function first updates gl_get_line()'s fallback terminal
1684        dimensions, then records its findings in the return value.
1685 
1686 
1687        The def_ncolumn and def_nline arguments specify the default number of
1688        terminal columns and lines to use if the terminal size cannot be
1689        determined by ioctl(TIOCGWINSZ) or environment variables.
1690 
1691    Hiding What You Type
1692        When entering sensitive information, such as passwords, it is best not
1693        to have the text that you are entering echoed on the terminal.
1694        Furthermore, such text should not be recorded in the history list,
1695        since somebody finding your terminal unattended could then recall it,
1696        or somebody snooping through your directories could see it in your
1697        history file. With this in mind, the gl_echo_mode() function allows you
1698        to toggle on and off the display and archival of any text that is
1699        subsequently entered in calls to gl_get_line().
1700 
1701 
1702        The enable argument specifies whether entered text should be visible or
1703        not. If it is 0, then subsequently entered lines will not be visible on
1704        the terminal, and will not be recorded in the history list. If it is 1,
1705        then subsequent input lines will be displayed as they are entered, and
1706        provided that history has not been turned off with a call to
1707        gl_toggle_history(), then they will also be archived in the history
1708        list. Finally, if the enable argument is -1, then the echoing mode is
1709        left unchanged, which allows you to non-destructively query the current
1710        setting through the return value. In all cases, the return value of the
1711        function is 0 if echoing was disabled before the function was called,
1712        and 1 if it was enabled.
1713 
1714 
1715        When echoing is turned off, note that although tab completion will
1716        invisibly complete your prefix as far as possible, ambiguous
1717        completions will not be displayed.
1718 
1719    Single Character Queries
1720        Using gl_get_line() to query the user for a single character reply, is
1721        inconvenient for the user, since they must hit the enter or return key
1722        before the character that they typed is returned to the program. Thus
1723        the gl_query_char() function has been provided for single character
1724        queries like this.
1725 
1726 
1727        This function displays the specified prompt at the start of a new line,
1728        and waits for the user to type a character. When the user types a
1729        character, gl_query_char() displays it to the right of the prompt,
1730        starts a newline, then returns the character to the calling program.
1731        The return value of the function is the character that was typed. If
1732        the read had to be aborted for some reason, EOF is returned instead. In
1733        the latter case, the application can call the previously documented
1734        gl_return_status(), to find out what went wrong. This could, for
1735        example, have been the reception of a signal, or the optional
1736        inactivity timer going off.
1737 
1738 
1739        If the user simply hits enter, the value of the defchar argument is
1740        substituted. This means that when the user hits either newline or
1741        return, the character specified in defchar, is displayed after the
1742        prompt, as though the user had typed it, as well as being returned to
1743        the calling application. If such a replacement is not important, simply
1744        pass '\n' as the value of defchar.
1745 
1746 
1747        If the entered character is an unprintable character, it is displayed
1748        symbolically. For example, control-A is displayed as ^A, and characters
1749        beyond 127 are displayed in octal, preceded by a backslash.
1750 
1751 
1752        As with gl_get_line(), echoing of the entered character can be disabled
1753        using the gl_echo_mode() function.
1754 
1755 
1756        If the calling process is suspended while waiting for the user to type
1757        their response, the cursor is moved to the line following the prompt
1758        line, then when the process resumes, the prompt is redisplayed, and
1759        gl_query_char() resumes waiting for the user to type a character.
1760 
1761 
1762        Note that in non-blocking server mode, if an incomplete input line is
1763        in the process of being read when gl_query_char() is called, the
1764        partial input line is discarded, and erased from the terminal, before
1765        the new prompt is displayed. The next call to gl_get_line() will thus
1766        start editing a new line.
1767 
1768    Reading Raw Characters
1769        Whereas the gl_query_char() function visibly prompts the user for a
1770        character, and displays what they typed, the gl_read_char() function
1771        reads a signal character from the user, without writing anything to the
1772        terminal, or perturbing any incompletely entered input line. This means
1773        that it can be called not only from between calls to gl_get_line(), but
1774        also from callback functions that the application has registered to be
1775        called by gl_get_line().
1776 
1777 
1778        On success, the return value of gl_read_char() is the character that
1779        was read. On failure, EOF is returned, and the gl_return_status()
1780        function can be called to find out what went wrong. Possibilities
1781        include the optional inactivity timer going off, the receipt of a
1782        signal that is configured to abort gl_get_line(), or terminal I/O
1783        blocking, when in non-blocking server-I/O mode.
1784 
1785 
1786        Beware that certain keyboard keys, such as function keys, and cursor
1787        keys, usually generate at least three characters each, so a single call
1788        to gl_read_char() will not be enough to identify such keystrokes.
1789 
1790    Clearing The Terminal
1791        The calling program can clear the terminal by calling
1792        gl_erase_terminal(). In non-blocking server-I/O mode, this function
1793        also arranges for the current input line to be redrawn from scratch
1794        when gl_get_line() is next called.
1795 
1796    Displaying Text Dynamically
1797        Between calls to gl_get_line(), the gl_display_text() function provides
1798        a convenient way to display paragraphs of text, left-justified and
1799        split over one or more terminal lines according to the constraints of
1800        the current width of the terminal. Examples of the use of this function
1801        may be found in the demo programs, where it is used to display
1802        introductions. In those examples the advanced use  of optional
1803        prefixes, suffixes and filled lines to draw a box around the text is
1804        also illustrated.
1805 
1806 
1807        If gl is not currently connected to a terminal, for example if the
1808        output of a program that uses gl_get_line() is being piped to another
1809        program or redirected to a file, then the value of the def_width
1810        parameter is used as the terminal width.
1811 
1812 
1813        The indentation argument specifies the number of characters to use to
1814        indent each line of output. The fill_char argument specifies the
1815        character that will be used to perform this indentation.
1816 
1817 
1818        The prefix argument can be either NULL or a string to place at the
1819        beginning of each new line (after any indentation). Similarly, the
1820        suffix argument can be either NULL or a string to place at the end of
1821        each line.  The suffix is placed flush against the right edge of the
1822        terminal, and any space between its first character and the last word
1823        on that line is filled with the character specified by the fill_char
1824        argument. Normally the fill-character is a space.
1825 
1826 
1827        The start argument tells gl_display_text() how many characters have
1828        already been written to the current terminal line, and thus tells it
1829        the starting column index of the cursor. Since the return value of
1830        gl_display_text() is the ending column index of the cursor, by passing
1831        the return value of one call to the start argument of the next call, a
1832        paragraph that is broken between more than one string can be composed
1833        by calling gl_display_text() for each successive portion of the
1834        paragraph.  Note that literal newline characters are necessary at the
1835        end of each paragraph to force a new line to be started.
1836 
1837 
1838        On error, gl_display_text() returns -1.
1839 
1840    Callback Function Facilities
1841        Unless otherwise stated, callback functions such as tab completion
1842        callbacks and event callbacks should not call any functions in this
1843        module. The following functions, however, are designed specifically to
1844        be used by callback functions.
1845 
1846 
1847        Calling the gl_replace_prompt() function from a callback tells
1848        gl_get_line() to display a different prompt when the callback returns.
1849        Except in non-blocking server mode, it has no effect if used between
1850        calls to gl_get_line(). In non-blocking server mode, when used between
1851        two calls to gl_get_line() that are operating on the same input line,
1852        the current input line will be re-drawn with the new prompt on the
1853        following call to gl_get_line().
1854 
1855    International Character Sets
1856        Since libtecla(3LIB) version 1.4.0, gl_get_line() has been 8-bit clean.
1857        This means that all 8-bit characters that are printable in the user's
1858        current locale are now displayed verbatim and included in the returned
1859        input line. Assuming that the calling program correctly contains a call
1860        like the following,
1861 
1862          setlocale(LC_CTYPE, "")
1863 
1864 
1865 
1866        then the current locale is determined by the first of the environment
1867        variables LC_CTYPE, LC_ALL, and LANG that is found to contain a valid
1868        locale name. If none of these variables are defined, or the program
1869        neglects to call setlocale(3C), then the default C locale is used,
1870        which is US 7-bit ASCII. On most UNIX-like platforms, you can get a
1871        list of valid locales by typing the command:
1872 
1873          locale -a
1874 
1875 
1876 
1877 
1878        at the shell prompt. Further documentation on how the user can make use
1879        of this to enter international characters can be found in the tecla(5)
1880        man page.
1881 
1882    Thread Safety
1883        Unfortunately neither terminfo nor termcap were designed to be
1884        reentrant, so you cannot safely use the functions of the getline module
1885        in multiple threads (you can use the separate file-expansion and word-
1886        completion modules in multiple threads, see the corresponding man pages
1887        for details).  However due to the use of POSIX reentrant functions for
1888        looking up home directories, it is safe to use this module from a
1889        single thread of a multi-threaded program, provided that your other
1890        threads do not use any termcap or terminfo functions.
1891 
1892 ATTRIBUTES
1893        See attributes(5) for descriptions of the following attributes:
1894 
1895 
1896 
1897 
1898        +--------------------+-----------------+
1899        |  ATTRIBUTE TYPE    | ATTRIBUTE VALUE |
1900        +--------------------+-----------------+
1901        |Interface Stability | Committed       |
1902        +--------------------+-----------------+
1903        |MT-Level            | MT-Safe         |
1904        +--------------------+-----------------+
1905 
1906 SEE ALSO
1907        cpl_complete_word(3TECLA), ef_expand_file(3TECLA), gl_io_mode(3TECLA),
1908        libtecla(3LIB), pca_lookup_file(3TECLA), attributes(5), tecla(5)
1909 
1910 
1911 
1912                                January 18, 2020            GL_GET_LINE(3TECLA)