GL_GET_LINE(3TECLA) | Interactive Command-line Input Library Functions | GL_GET_LINE(3TECLA) |
cc [ flag... ] file... -ltecla [ library... ] #include <stdio.h> #include <libtecla.h> GetLine *new_GetLine(size_t linelen, size_t histlen);
GetLine *del_GetLine(GetLine *gl);
char *gl_get_line(GetLine *gl, const char *prompt, const char *start_line, int start_pos);
int gl_query_char(GetLine *gl, const char *prompt, char defchar);
int gl_read_char(GetLine *gl);
int gl_customize_completion(GetLine *gl, void *data, CplMatchFn *match_fn);
int gl_change_terminal(GetLine *gl, FILE *input_fp, FILE *output_fp, const char *term);
int gl_configure_getline(GetLine *gl, const char *app_string, const char *app_file, const char *user_file);
int gl_bind_keyseq(GetLine *gl, GlKeyOrigin origin, const char *keyseq, const char *action);
int gl_save_history(GetLine *gl, const char *filename, const char *comment, int max_lines);
int gl_load_history(GetLine *gl, const char *filename, const char *comment);
int gl_watch_fd(GetLine *gl, int fd, GlFdEvent event, GlFdEventFn *callback, void *data);
int gl_inactivity_timeout(GetLine *gl, GlTimeoutFn *callback, void *data, unsigned long sec, unsigned long nsec);
int gl_group_history(GetLine *gl, unsigned stream);
int gl_show_history(GetLine *gl, FILE *fp, const char *fmt, int all_groups, int max_lines);
int gl_resize_history(GetLine *gl, size_t bufsize);
void gl_limit_history(GetLine *gl, int max_lines);
void gl_clear_history(GetLine *gl, int all_groups);
void gl_toggle_history(GetLine *gl, int enable);
GlTerminalSize gl_terminal_size(GetLine *gl, int def_ncolumn, int def_nline);
int gl_set_term_size(GetLine *gl, int ncolumn, int nline);
int gl_lookup_history(GetLine *gl, unsigned long id, GlHistoryLine *hline);
void gl_state_of_history(GetLine *gl, GlHistoryState *state);
void gl_range_of_history(GetLine *gl, GlHistoryRange *range);
void gl_size_of_history(GetLine *gl, GlHistorySize *size);
void gl_echo_mode(GetLine *gl, int enable);
void gl_replace_prompt(GetLine *gl, const char *prompt);
void gl_prompt_style(GetLine *gl, GlPromptStyle style);
int gl_ignore_signal(GetLine *gl, int signo);
int gl_trap_signal(GetLine *gl, int signo, unsigned flags, GlAfterSignal after, int errno_value);
int gl_last_signal(GetLine *gl);
int gl_completion_action(GetLine *gl, void *data, CplMatchFn *match_fn, int list_only, const char *name, const char *keyseq);
int gl_register_action(GetLine *gl, void *data, GlActionFn *fn, const char *name, const char *keyseq);
int gl_display_text(GetLine *gl, int indentation, const char *prefix, const char *suffix, int fill_char, int def_width, int start, const char *string);
GlReturnStatus gl_return_status(GetLine *gl);
const char *gl_error_message(GetLine *gl, char *buff, size_t n);
void gl_catch_blocked(GetLine *gl);
int gl_list_signals(GetLine *gl, sigset_t *set);
int gl_append_history(GetLine *gl, const char *line);
int gl_automatic_history(GetLine *gl, int enable);
int gl_erase_terminal(GetLine *gl);
#include <stdio.h> #include <locale.h> #include <libtecla.h> int main(int argc, char *argv[]) { char *line; /* The line that the user typed */ GetLine *gl; /* The gl_get_line() resource object */ setlocale(LC_CTYPE, ""); /* Adopt the user's choice */ /* of character set. */ gl = new_GetLine(1024, 2048); if(!gl) return 1; while((line=gl_get_line(gl, "$ ", NULL, -1)) != NULL && strcmp(line, "exit\n") != 0) printf("You typed: %s\n", line); gl = del_GetLine(gl); return 0; }
In the example, first the resources needed by the gl_get_line() function are created by calling new_GetLine(). This allocates the memory used in subsequent calls to the gl_get_line() function, including the history buffer for recording previously entered lines. Then one or more lines are read from the user, until either an error occurs, or the user types exit. Then finally the resources that were allocated by new_GetLine(), are returned to the system by calling del_GetLine(). Note the use of the NULL return value of del_GetLine() to make gl NULL. This is a safety precaution. If the program subsequently attempts to pass gl to gl_get_line(), said function will complain, and return an error, instead of attempting to use the deleted resource object.
On error, a message is printed to stderr and NULL is returned.
The del_GetLine() function deletes the resources that were returned by a previous call to new_GetLine(). It always returns NULL (for example, a deleted object). It does nothing if the gl argument is NULL.
The gl_get_line() function can be called any number of times to read input from the user. The gl argument must have been previously returned by a call to new_GetLine(). The prompt argument should be a normal null-terminated string, specifying the prompt to present the user with. By default prompts are displayed literally, but if enabled with the gl_prompt_style() function, prompts can contain directives to do underlining, switch to and from bold fonts, or turn highlighting on and off.
If you want to specify the initial contents of the line for the user to edit, pass the desired string with the start_line argument. You can then specify which character of this line the cursor is initially positioned over by using the start_pos argument. This should be -1 if you want the cursor to follow the last character of the start line. If you do not want to preload the line in this manner, send start_line as NULL, and set start_pos to -1.
The gl_get_line() function returns a pointer to the line entered by the user, or NULL on error or at the end of the input. The returned pointer is part of the specified gl resource object, and thus should not be freed by the caller, or assumed to be unchanging from one call to the next. When reading from a user at a terminal, there will always be a newline character at the end of the returned line. When standard input is being taken from a pipe or a file, there will similarly be a newline unless the input line was too long to store in the internal buffer. In the latter case you should call gl_get_line() again to read the rest of the line. Note that this behavior makes gl_get_line() similar to fgets(3C). When stdin is not connected to a terminal, gl_get_line() simply calls fgets().
The following are the possible enumerated values returned by gl_return_status():
GLR_NEWLINE
GLR_BLOCKED
GLR_SIGNAL
GLR_TIMEOUT
GLR_FDABORT
GLR_EOF
GLR_ERROR
When gl_return_status() returns GLR_ERROR and the value of errno is not sufficient to explain what happened, you can use the gl_error_message() function to request a description of the last error that occurred.
The return value of gl_error_message() is a pointer to the message that occurred. If the buff argument is NULL, this will be a pointer to a buffer within gl whose value will probably change on the next call to any function associated with gl_get_line(). Otherwise, if a non-null buff argument is provided, the error message, including a '\0' terminator, will be written within the first n elements of this buffer, and the return value will be a pointer to the first element of this buffer. If the message will not fit in the provided buffer, it will be truncated to fit.
The style argument, which specifies the formatting style, can take any of the following values:
GL_FORMAT_PROMPT
%B
%b
%F
%f
%U
%u
%P
%p
%S
%s
%V
%v
%%
For example, in this mode, a prompt string like "%UOK%u$" would display the prompt "OK$", but with the OK part underlined.
Note that although a pair of characters that starts with a % character, but does not match any of the above directives is displayed literally, if a new directive is subsequently introduced which does match, the displayed prompt will change, so it is better to always use %% to display a literal %.
Also note that not all terminals support all of these text attributes, and that some substitute a different attribute for missing ones.
GL_LITERAL_PROMPT
The gl_configure_getline() function allows the configuration commands that would normally be read from a user's ~/.teclarc file, to be read from any or none of, a string, an application specific configuration file, and/or a user-specific configuration file. If this function is called before the first call to gl_get_line(), the default behavior of reading ~/.teclarc on the first call to gl_get_line() is disabled, so all configurations must be achieved using the configuration sources specified with this function.
If app_string != NULL, then it is interpreted as a string containing one or more configuration commands, separated from each other in the string by embedded newline characters. If app_file != NULL then it is interpreted as the full pathname of an application-specific configuration file. If user_file != NULL then it is interpreted as the full path name of a user-specific configuration file, such as ~/.teclarc. For example, in the call
gl_configure_getline(gl, "edit-mode vi \n nobeep", "/usr/share/myapp/teclarc", "~/.teclarc");
The app_string argument causes the calling application to start in vi(1) edit-mode, instead of the default emacs mode, and turns off the use of the terminal bell by the library. It then attempts to read system-wide configuration commands from an optional file called /usr/share/myapp/teclarc, then finally reads user-specific configuration commands from an optional .teclarc file in the user's home directory. Note that the arguments are listed in ascending order of priority, with the contents of app_string being potentially overridden by commands in app_file, and commands in app_file potentially being overridden by commands in user_file.
You can call this function as many times as needed, the results being cumulative, but note that copies of any file names specified with the app_file and user_file arguments are recorded internally for subsequent use by the read-init-files key-binding function, so if you plan to call this function multiple times, be sure that the last call specifies the filenames that you want re-read when the user requests that the configuration files be re-read.
Individual key sequences can also be bound and unbound using the gl_bind_keyseq() function. The origin argument specifies the priority of the binding, according to whom it is being established for, and must be one of the following two values.
GL_USER_KEY
GL_APP_KEY
When both user and application bindings for a given key sequence have been specified, the user binding takes precedence. The application's binding is subsequently reinstated if the user's binding is later unbound with either another call to this function, or a call to gl_configure_getline().
The keyseq argument specifies the key sequence to be bound or unbound, and is expressed in the same way as in a ~/.teclarc configuration file. The action argument must either be a string containing the name of the action to bind the key sequence to, or it must be NULL or "" to unbind the key sequence.
The data argument provides a way for your application to pass arbitrary, application-specific information to the callback function. This is passed to the callback every time that it is called. It might for example point to the symbol table from which possible completions are to be sought. The match_fn argument specifies the callback function to be called. The CplMatchFn function type is defined in <libtecla.h>, as is a CPL_MATCH_FN() macro that you can use to declare and prototype callback functions. The declaration and responsibilities of callback functions are described in depth on the cpl_complete_word(3TECLA) manual page.
The callback function is responsible for looking backwards in the input line from the point at which the user pressed TAB, to find the start of the word being completed. It then must lookup possible completions of this word, and record them one by one in the WordCompletion object that is passed to it as an argument, by calling the cpl_add_completion() function. If the callback function wants to provide filename completion in addition to its own specific completions, it has the option of itself calling the builtin filename completion callback. This is also documented in the cpl_complete_word(3TECLA) manual page.
If you would like gl_get_line() to return the current input line when a successful completion has been made, you can arrange this when you call cpl_add_completion() by making the last character of the continuation suffix a newline character. The input line will be updated to display the completion, together with any continuation suffix up to the newline character, and gl_get_line() will return this input line.
If your callback function needs to write something to the terminal, it must call gl_normal_io() before doing so. This will start a new line after the input line that is currently being edited, reinstate normal terminal I/O, and notify gl_get_line() that the input line will need to be redrawn when the callback returns.
The data and match_fn arguments are as described on the cpl_complete_word(3TECLA) manual page, and specify the callback function that should be invoked to identify possible completions. The list_only argument determines whether the action that is being defined should attempt to complete the word as far as possible in the input line before displaying any possible ambiguous completions, or whether it should simply display the list of possible completions without touching the input line. The former option is selected by specifying a value of 0, and the latter by specifying a value of 1. The name argument specifies the name by which configuration files and future invocations of this function should refer to the action. This must either be the name of an existing completion action to be changed, or be a new unused name for a new action. Finally, the keyseq argument specifies the default key sequence to bind the action to. If this is NULL, no new key sequence will be bound to the action.
Beware that in order for the user to be able to change the key sequence that is bound to actions that are installed in this manner, you should call gl_completion_action() to install a given action for the first time between calling new_GetLine() and the first call to gl_get_line(). Otherwise, when the user's configuration file is read on the first call to gl_get_line(), the name of the your additional action will not be known, and any reference to it in the configuration file will generate an error.
As discussed for gl_customize_completion(), if your callback function needs to write anything to the terminal, it must call gl_normal_io() before doing so.
The gl_register_action() function lets the application register an external function, fn, that will thereafter be called whenever either the specified key sequence, keyseq, is entered by the user, or the user enters any other key sequence that the user subsequently binds to the specified action name, name, in their configuration file. The data argument can be a pointer to anything that the application wants to have passed to the action function, fn, whenever that function is invoked.
The action function, fn, should be declared using the GL_ACTION_FN() macro, which is defined in <libtecla.h>.
#define GL_ACTION_FN(fn) GlAfterAction (fn)(GetLine *gl, \ void *data, int count, size_t curpos, \ const char *line)
The gl and data arguments are those that were previously passed to gl_register_action() when the action function was registered. The count argument is a numeric argument which the user has the option of entering using the digit-argument action, before invoking the action. If the user does not enter a number, then the count argument is set to 1. Nominally this argument is interpreted as a repeat count, meaning that the action should be repeated that many times. In practice however, for some actions a repeat count makes little sense. In such cases, actions can either simply ignore the count argument, or use its value for a different purpose.
A copy of the current input line is passed in the read-only line argument. The current cursor position within this string is given by the index contained in the curpos argument. Note that direct manipulation of the input line and the cursor position is not permitted because the rules dictated by various modes (such as vi mode versus emacs mode, no-echo mode, and insert mode versus overstrike mode) make it too complex for an application writer to write a conforming editing action, as well as constrain future changes to the internals of gl_get_line(). A potential solution to this dilemma would be to allow the action function to edit the line using the existing editing actions. This is currently under consideration.
If the action function wishes to write text to the terminal without this getting mixed up with the displayed text of the input line, or read from the terminal without having to handle raw terminal I/O, then before doing either of these operations, it must temporarily suspend line editing by calling the gl_normal_io() function. This function flushes any pending output to the terminal, moves the cursor to the start of the line that follows the last terminal line of the input line, then restores the terminal to a state that is suitable for use with the C stdio facilities. The latter includes such things as restoring the normal mapping of \n to \r\n, and, when in server mode, restoring the normal blocking form of terminal I/O. Having called this function, the action function can read from and write to the terminal without the fear of creating a mess. It is not necessary for the action function to restore the original editing environment before it returns. This is done automatically by gl_get_line() after the action function returns. The following is a simple example of an action function which writes the sentence "Hello world" on a new terminal line after the line being edited. When this function returns, the input line is redrawn on the line that follows the "Hello world" line, and line editing resumes.
static GL_ACTION_FN(say_hello_fn) { if(gl_normal_io(gl)) /* Temporarily suspend editing */ return GLA_ABORT; printf("Hello world\n"); return GLA_CONTINUE; }
Action functions must return one of the following values, to tell gl_get_line() how to proceed.
GLA_ABORT
GLA_RETURN
GLA_CONTINUE
Note that the name argument of gl_register_action() specifies the name by which a user can refer to the action in their configuration file. This allows them to re-bind the action to an alternate key-sequence. In order for this to work, it is necessary to call gl_register_action() between calling new_GetLine() and the first call to gl_get_line().
The filename argument specifies the name to give the history file when saving, or the name of an existing history file, when loading. This may contain home directory and environment variable expressions, such as ~/.myapp_history or $HOME/.myapp_history.
Along with each history line, additional information about it, such as its nesting level and when it was entered by the user, is recorded as a comment preceding the line in the history file. Writing this as a comment allows the history file to double as a command file, just in case you wish to replay a whole session using it. Since comment prefixes differ in different languages, the comment argument is provided for specifying the comment prefix. For example, if your application were a UNIX shell, such as the Bourne shell, you would specify "#" here. Whatever you choose for the comment character, you must specify the same prefix to gl_load_history() that you used when you called gl_save_history() to write the history file.
The max_lines argument must be either -1 to specify that all lines in the history list be saved, or a positive number specifying a ceiling on how many of the most recent lines should be saved.
Both functions return non-zero on error, after writing an error message to stderr. Note that gl_load_history() does not consider the non-existence of a file to be an error.
The integer identifier ID can be any number chosen by the application, but note that gl_save_history() and gl_load_history() preserve the association between identifiers and historical input lines between program invocations, so you should choose fixed identifiers for the different types of input line used by your application.
Whenever gl_get_line() appends a new input line to the history list, the current history identifier is recorded with it, and when it is asked to recall a historical input line, it only recalls lines that are marked with the current identifier.
%D
%T
%N
%G
%%
%H
Thus a format string like "%D %T %H0" would output something like:
2001-11-20 10:23:34 Hello world
Note the inclusion of an explicit newline character in the format string.
The id argument indicates which line to look up, where the first line that was entered in the history list after new_GetLine() was called is denoted by 0, and subsequently entered lines are denoted with successively higher numbers. Note that the range of lines currently preserved in the history list can be queried by calling the gl_range_of_history() function. If the requested line is in the history list, the details of the line are recorded in the variable pointed to by the hline argument, and 1 is returned. Otherwise 0 is returned, and the variable pointed to by hline is left unchanged.
Beware that the string returned in hline->line is part of the history buffer, so it must not be modified by the caller, and will be recycled on the next call to any function that takes gl as its argument. Therefore you should make a private copy of this string if you need to keep it.
If this function is called with its enable argument set to 0, gl_get_line() will not automatically archive subsequently entered lines. Automatic archiving can be reenabled at a later time by calling this function again, with its enable argument set to 1. While automatic history archiving is disabled, the calling application can use the gl_append_history() to append lines to the history list as needed.
The line argument specifies the line to be added to the history list. This must be a normal '\0 ' terminated string. If this string contains any newline characters, the line that gets archived in the history list will be terminated by the first of these. Otherwise it will be terminated by the '\0 ' terminator. If the line is longer than the maximum input line length that was specified when new_GetLine() was called, it will be truncated to the actual gl_get_line() line length when the line is recalled.
If successful, gl_append_history() returns 0. Otherwise it returns non-zero and sets errno to one of the following values.
EINVAL
ENOMEM
A textual description of the error can optionally be obtained by calling gl_error_message(). Note that after such an error, the history list remains in a valid state to receive new history lines, so there is little harm in simply ignoring the return status of gl_append_history().
The histlen argument specifies the new size in bytes, and if you specify this as 0, the buffer will be deleted.
As mentioned in the discussion of new_GetLine(), the number of lines that can be stored in the history buffer, depends on the lengths of the individual lines. For example, a 1000 byte buffer could equally store 10 lines of average length 100 bytes, or 20 lines of average length 50 bytes. Although the buffer is never expanded when new lines are added, a list of pointers into the buffer does get expanded when needed to accommodate the number of lines currently stored in the buffer. To place an upper limit on the number of lines in the buffer, and thus a ceiling on the amount of memory used in this list, you can call the gl_limit_history() function.
The max_lines should either be a positive number >= 0, specifying an upper limit on the number of lines in the buffer, or be -1 to cancel any previously specified limit. When a limit is in effect, only the max_lines most recently appended lines are kept in the buffer. Older lines are discarded.
To discard lines from the history buffer, use the gl_clear_history() function.
The all_groups argument tells the function whether to delete just the lines associated with the current history group (see gl_group_history()) or all historical lines in the buffer.
The gl_toggle_history() function allows you to toggle history on and off without losing the current contents of the history list.
Setting the enable argument to 0 turns off the history mechanism, and setting it to 1 turns it back on. When history is turned off, no new lines will be added to the history list, and history lookup key-bindings will act as though there is nothing in the history buffer.
The gl_range_of_history() function returns the number and range of lines in the history list. The return values are recorded in the variable pointed to by the range argument. If the nlines member of this structure is greater than zero, then the oldest and newest members report the range of lines in the list, and newest=oldest+nlines-1. Otherwise they are both zero.
The gl_size_of_history() function returns the total size of the history buffer and the amount of the buffer that is currently occupied.
On return, the size information is recorded in the variable pointed to by the size argument.
The gl argument is the object that was returned by new_GetLine(). The input_fp argument specifies the stream to read from, and output_fp specifies the stream to be written to. Only if both of these refer to a terminal, will interactive terminal input be enabled. Otherwise gl_get_line() will simply call fgets() to read command input. If both streams refer to a terminal, then they must refer to the same terminal, and the type of this terminal must be specified with the term argument. The value of the term argument is looked up in the terminal information database (terminfo or termcap), in order to determine which special control sequences are needed to control various aspects of the terminal. new_GetLine() for example, passes the return value of getenv("TERM") in this argument. Note that if one or both of input_fp and output_fp do not refer to a terminal, then it is legal to pass NULL instead of a terminal type.
Note that if you want to pass file descriptors to gl_change_terminal(), you can do this by creating stdio stream wrappers using the POSIX fdopen(3C) function.
Registering a file descriptor to be watched by gl_get_line() involves calling the gl_watch_fd() function. If this returns non-zero, then it means that either your arguments are invalid, or that this facility is not supported on the host system.
The fd argument is the file descriptor to be watched. The event argument specifies what type of activity is of interest, chosen from the following enumerated values:
GLFD_READ
GLFD_WRITE
GLFD_URGENT
The callback argument is the function to call when the selected activity is seen. It should be defined with the following macro, which is defined in libtecla.h.
#define GL_FD_EVENT_FN(fn) GlFdStatus (fn)(GetLine *gl, void *data, int fd, GlFdEvent event)
The data argument of the gl_watch_fd() function is passed to the callback function for its own use, and can point to anything you like, including NULL. The file descriptor and the event argument are also passed to the callback function, and this potentially allows the same callback function to be registered to more than one type of event and/or more than one file descriptor. The return value of the callback function should be one of the following values.
GLFD_ABORT
GLFD_REFRESH
GLFD_CONTINUE
Note that before calling the callback, gl_get_line() blocks most signals and leaves its own signal handlers installed, so if you need to catch a particular signal you will need to both temporarily install your own signal handler, and unblock the signal. Be sure to re-block the signal (if it was originally blocked) and reinstate the original signal handler, if any, before returning.
Your callback should not try to read from the terminal, which is left in raw mode as far as input is concerned. You can write to the terminal as usual, since features like conversion of newline to carriage-return/linefeed are re-enabled while the callback is running. If your callback function does write to the terminal, be sure to output a newline first, and when your callback returns, tell gl_get_line() that the input line needs to be redrawn, by returning the GLFD_REFRESH status code.
To remove a callback function that you previously registered for a given file descriptor and event, simply call gl_watch_fd() with the same fd and event arguments, but with a callback argument of 0. The data argument is ignored in this case.
The timeout is specified in the form of an integral number of seconds and an integral number of nanoseconds, specified by the sec and nsec arguments, respectively. Subsequently, whenever no activity is seen for this time period, the function specified by the callback argument is called. The data argument of gl_inactivity_timeout() is passed to this callback function whenever it is invoked, and can thus be used to pass arbitrary application-specific information to the callback. The following macro is provided in <libtecla.h> for applications to use to declare and prototype timeout callback functions.
#define GL_TIMEOUT_FN(fn) GlAfterTimeout (fn)(GetLine *gl, void *data)
On returning, the application's callback is expected to return one of the following enumerators to tell gl_get_line() how to proceed after the timeout has been handled by the callback.
GLTO_ABORT
GLTO_REFRESH
GLTO_CONTINUE
Note that before calling the callback, gl_get_line() blocks most signals and leaves its own signal handlers installed, so if you need to catch a particular signal you will need to both temporarily install your own signal handler and unblock the signal. Be sure to re-block the signal (if it was originally blocked) and reinstate the original signal handler, if any, before returning.
Your callback should not try to read from the terminal, which is left in raw mode as far as input is concerned. You can however write to the terminal as usual, since features like conversion of newline to carriage-return/linefeed are re-enabled while the callback is running. If your callback function does write to the terminal, be sure to output a newline first, and when your callback returns, tell gl_get_line() that the input line needs to be redrawn, by returning the GLTO_REFRESH status code.
Finally, note that although the timeout arguments include a nanosecond component, few computer clocks presently have resolutions that are finer than a few milliseconds, so asking for less than a few milliseconds is equivalent to requesting zero seconds on many systems. If this would be a problem, you should base your timeout selection on the actual resolution of the host clock (for example, by calling sysconf(_SC_CLK_TCK)).
To turn off timeouts, simply call gl_inactivity_timeout() with a callback argument of 0. The data argument is ignored in this case.
When the following subset of signals are caught, gl_get_line() first restores the terminal settings and signal handling to how they were before gl_get_line() was called, resends the signal to allow the calling application's signal handlers to handle it, then, if the process still exists, returns NULL and sets errno as specified below.
SIGINT
SIGHUP
SIGPIPE
SIGQUIT
SIGABRT
SIGTERM
Note that in the case of all of the above signals, POSIX mandates that by default the process is terminated, with the addition of a core dump in the case of the SIGQUIT signal. In other words, if the calling application does not override the default handler by supplying its own signal handler, receipt of the corresponding signal will terminate the application before gl_get_line() returns.
If gl_get_line() aborts with errno set to EINTR, you can find out what signal caused it to abort, by calling the gl_last_signal() function. This returns the numeric code (for example, SIGINT) of the last signal that was received during the most recent call to gl_get_line(), or -1 if no signals were received.
On systems that support it, when a SIGWINCH (window change) signal is received, gl_get_line() queries the terminal to find out its new size, redraws the current input line to accommodate the new size, then returns to waiting for keyboard input from the user. Unlike other signals, this signal is not resent to the application.
Finally, the following signals cause gl_get_line() to first restore the terminal and signal environment to that which prevailed before gl_get_line() was called, then resend the signal to the application. If the process still exists after the signal has been delivered, then gl_get_line() then re-establishes its own signal handlers, switches the terminal back to raw mode, redisplays the input line, and goes back to awaiting terminal input from the user.
SIGCONT
SIGPOLL
SIGPWR
SIGALRM
SIGUSR1
SIGUSR2
SIGVTALRM
SIGXCPU
SIGXFSZ
SIGTSTP
SIGTTIN
SIGTTOU
Obviously not all of the above signals are supported on all systems, so code to support them is conditionally compiled into the tecla library.
Note that if SIGKILL or SIGPOLL, which by definition cannot be caught, or any of the hardware generated exception signals, such as SIGSEGV, SIGBUS, and SIGFPE, are received and unhandled while gl_get_line() has the terminal in raw mode, the program will be terminated without the terminal having been restored to a usable state. In practice, job-control shells usually reset the terminal settings when a process relinquishes the controlling terminal, so this is only a problem with older shells.
If you do not need gl_get_line() to do anything in response to a signal that it normally traps, you can tell to gl_get_line() to ignore that signal by calling gl_ignore_signal().
The signo argument is the number of the signal (for example, SIGINT) that you want to have ignored. If the specified signal is not currently one of those being trapped, this function does nothing.
The gl_trap_signal() function allows you to either add a new signal to the list that gl_get_line() traps or modify how it responds to a signal that it already traps.
The signo argument is the number of the signal that you want to have trapped. The flags argument is a set of flags that determine the environment in which the application's signal handler is invoked. The after argument tells gl_get_line() what to do after the application's signal handler returns. The errno_value tells gl_get_line() what to set errno to if told to abort.
The flags argument is a bitwise OR of zero or more of the following enumerators:
GLS_RESTORE_SIG
GLS_RESTORE_TTY
GLS_RESTORE_LINE
GLS_REDRAW_LINE
GLS_UNBLOCK_SIG
GLS_DONT_FORWARD
Two commonly useful flag combinations are also enumerated as follows:
GLS_RESTORE_ENV
GLS_SUSPEND_INPUT
If your signal handler, or the default system signal handler for this signal, if you have not overridden it, never either writes to the terminal, nor suspends or terminates the calling program, then you can safely set the flags argument to 0.
The GL_RESTORE_ENV combination is the same as GL_SUSPEND_INPUT, except that it does not move the cursor. If your signal handler does not read or write anything to the terminal, the user will not see any visible indication that a signal was caught. This can be useful if you have a signal handler that only occasionally writes to the terminal, where using GL_SUSPEND_LINE would cause the input line to be unnecessarily duplicated when nothing had been written to the terminal. Such a signal handler, when it does write to the terminal, should be sure to start a new line at the start of its first write, by writing a new line before returning. If the signal arrives while the user is entering a line that only occupies a signal terminal line, or if the cursor is on the last terminal line of a longer input line, this will have the same effect as GL_SUSPEND_INPUT. Otherwise it will start writing on a line that already contains part of the displayed input line. This does not do any harm, but it looks a bit ugly, which is why the GL_SUSPEND_INPUT combination is better if you know that you are always going to be writing to the terminal.
The after argument, which determines what gl_get_line() does after the application's signal handler returns (if it returns), can take any one of the following values:
GLS_RETURN
GLS_ABORT
GLS_CONTINUE
The errno_value argument is intended to be combined with the GLS_ABORT option, telling gl_get_line() what to set the standard errno variable to before returning NULL to the calling program. It can also, however, be used with the GL_RETURN option, in case you want to have a way to distinguish between an input line that was entered using the return key, and one that was entered by the receipt of a signal.
As an example of the problems that can arise if the application is not written correctly, imagine that one's application has a SIGINT signal handler that sets a global flag. Now suppose that the application tests this flag just before invoking gl_get_line(). If a SIGINT signal happens to be received in the small window of time between the statement that tests the value of this flag, and the statement that calls gl_get_line(), then gl_get_line() will not see the signal, and will not be interrupted. As a result, the application will not be able to respond to the signal until the user gets around to finishing entering the input line and gl_get_line() returns. Depending on the application, this might or might not be a disaster, but at the very least it would puzzle the user.
The way to avoid such problems is to do the following.
The same technique can be used around certain POSIX signal-aware functions, such as sigsetjmp(3C) and sigsuspend(2), and in particular, the former of these two functions can be used in conjunction with siglongjmp(3C) to implement race-condition free signal handling around other long-running system calls. The gl_get_line() function manages to reliably trap signals around calls to functions like read(2) and select(3C) without race conditions.
The gl_get_line() function first uses the POSIX sigprocmask() function to block the delivery of all of the signals that it is currently configured to catch. This is redundant if the application has already blocked them, but it does no harm. It undoes this step just before returning.
Whenever gl_get_line() needs to call read or select to wait for input from the user, it first calls the POSIX sigsetjmp() function, being sure to specify a non-zero value for its savemask argument.
If sigsetjmp() returns zero, gl_get_line() then does the following.
Alternatively, if sigsetjmp() returns non-zero, this means that one of the signals being trapped was caught while the above steps were executing. When this happens, gl_get_line() does the following.
First, note that when a call to siglongjmp() causes sigsetjmp() to return, provided that the savemask argument of sigsetjmp() was non-zero, the signal process mask is restored to how it was when sigsetjmp() was called. This is the important difference between sigsetjmp() and the older problematic setjmp(3C), and is the essential ingredient that makes it possible to avoid signal handling race conditions. Because of this we are guaranteed that all of the signals that we blocked before calling sigsetjmp() are blocked again as soon as any signal is caught. The following statements, which are then executed, are thus guaranteed to be executed without any further signals being caught.
What the above steps do in essence is to take asynchronously delivered signals and handle them synchronously, one at a time, at a point in the code where gl_get_line() has complete control over its environment.
On the few systems where this mechanism is not available, at startup new_GetLine() first looks for the LINES and COLUMNS environment variables. If these are not found, or they contain unusable values, then if a terminal information database like terminfo or termcap is available, the default size of the terminal is looked up in this database. If this too fails to provide the terminal size, a default size of 80 columns by 24 lines is used.
Even on systems that do support ioctl(TIOCGWINSZ), if the terminal is on the other end of a serial line, the terminal driver generally has no way of detecting when a resize occurs or of querying what the current size is. In such cases no SIGWINCH is sent to the process, and the dimensions returned by ioctl(TIOCGWINSZ) are not correct. The only way to handle such instances is to provide a way for the user to enter a command that tells the remote system what the new size is. This command would then call the gl_set_term_size() function to tell gl_get_line() about the change in size.
The ncolumn and nline arguments are used to specify the new dimensions of the terminal, and must not be less than 1. On systems that do support ioctl(TIOCGWINSZ), this function first calls ioctl(TIOCSWINSZ) to tell the terminal driver about the change in size. In non-blocking server-I/O mode, if a line is currently being input, the input line is then redrawn to accommodate the changed size. Finally the new values are recorded in gl for future use by gl_get_line().
The gl_terminal_size() function allows you to query the current size of the terminal, and install an alternate fallback size for cases where the size is not available. Beware that the terminal size will not be available if reading from a pipe or a file, so the default values can be important even on systems that do support ways of finding out the terminal size.
This function first updates gl_get_line()'s fallback terminal dimensions, then records its findings in the return value.
The def_ncolumn and def_nline arguments specify the default number of terminal columns and lines to use if the terminal size cannot be determined by ioctl(TIOCGWINSZ) or environment variables.
The enable argument specifies whether entered text should be visible or not. If it is 0, then subsequently entered lines will not be visible on the terminal, and will not be recorded in the history list. If it is 1, then subsequent input lines will be displayed as they are entered, and provided that history has not been turned off with a call to gl_toggle_history(), then they will also be archived in the history list. Finally, if the enable argument is -1, then the echoing mode is left unchanged, which allows you to non-destructively query the current setting through the return value. In all cases, the return value of the function is 0 if echoing was disabled before the function was called, and 1 if it was enabled.
When echoing is turned off, note that although tab completion will invisibly complete your prefix as far as possible, ambiguous completions will not be displayed.
This function displays the specified prompt at the start of a new line, and waits for the user to type a character. When the user types a character, gl_query_char() displays it to the right of the prompt, starts a newline, then returns the character to the calling program. The return value of the function is the character that was typed. If the read had to be aborted for some reason, EOF is returned instead. In the latter case, the application can call the previously documented gl_return_status(), to find out what went wrong. This could, for example, have been the reception of a signal, or the optional inactivity timer going off.
If the user simply hits enter, the value of the defchar argument is substituted. This means that when the user hits either newline or return, the character specified in defchar, is displayed after the prompt, as though the user had typed it, as well as being returned to the calling application. If such a replacement is not important, simply pass '\n' as the value of defchar.
If the entered character is an unprintable character, it is displayed symbolically. For example, control-A is displayed as ^A, and characters beyond 127 are displayed in octal, preceded by a backslash.
As with gl_get_line(), echoing of the entered character can be disabled using the gl_echo_mode() function.
If the calling process is suspended while waiting for the user to type their response, the cursor is moved to the line following the prompt line, then when the process resumes, the prompt is redisplayed, and gl_query_char() resumes waiting for the user to type a character.
Note that in non-blocking server mode, if an incomplete input line is in the process of being read when gl_query_char() is called, the partial input line is discarded, and erased from the terminal, before the new prompt is displayed. The next call to gl_get_line() will thus start editing a new line.
On success, the return value of gl_read_char() is the character that was read. On failure, EOF is returned, and the gl_return_status() function can be called to find out what went wrong. Possibilities include the optional inactivity timer going off, the receipt of a signal that is configured to abort gl_get_line(), or terminal I/O blocking, when in non-blocking server-I/O mode.
Beware that certain keyboard keys, such as function keys, and cursor keys, usually generate at least three characters each, so a single call to gl_read_char() will not be enough to identify such keystrokes.
If gl is not currently connected to a terminal, for example if the output of a program that uses gl_get_line() is being piped to another program or redirected to a file, then the value of the def_width parameter is used as the terminal width.
The indentation argument specifies the number of characters to use to indent each line of output. The fill_char argument specifies the character that will be used to perform this indentation.
The prefix argument can be either NULL or a string to place at the beginning of each new line (after any indentation). Similarly, the suffix argument can be either NULL or a string to place at the end of each line. The suffix is placed flush against the right edge of the terminal, and any space between its first character and the last word on that line is filled with the character specified by the fill_char argument. Normally the fill-character is a space.
The start argument tells gl_display_text() how many characters have already been written to the current terminal line, and thus tells it the starting column index of the cursor. Since the return value of gl_display_text() is the ending column index of the cursor, by passing the return value of one call to the start argument of the next call, a paragraph that is broken between more than one string can be composed by calling gl_display_text() for each successive portion of the paragraph. Note that literal newline characters are necessary at the end of each paragraph to force a new line to be started.
On error, gl_display_text() returns -1.
Calling the gl_replace_prompt() function from a callback tells gl_get_line() to display a different prompt when the callback returns. Except in non-blocking server mode, it has no effect if used between calls to gl_get_line(). In non-blocking server mode, when used between two calls to gl_get_line() that are operating on the same input line, the current input line will be re-drawn with the new prompt on the following call to gl_get_line().
setlocale(LC_CTYPE, "")
then the current locale is determined by the first of the environment variables LC_CTYPE, LC_ALL, and LANG that is found to contain a valid locale name. If none of these variables are defined, or the program neglects to call setlocale(3C), then the default C locale is used, which is US 7-bit ASCII. On most UNIX-like platforms, you can get a list of valid locales by typing the command:
locale -a
at the shell prompt. Further documentation on how the user can make use of this to enter international characters can be found in the tecla(5) man page.
ATTRIBUTE TYPE | ATTRIBUTE VALUE |
Interface Stability | Committed |
MT-Level | MT-Safe |
January 18, 2020 |