sd: remove 'ssd' driver support
[unleashed/tickless.git] / usr / src / lib / libtecla / common / getline.c
blob125d1e9a2c69bd051d8ff34d0d080a7611216380
1 /*
2 * Copyright (c) 2000, 2001, 2002, 2003, 2004 by Martin C. Shepherd.
4 * All rights reserved.
6 * Permission is hereby granted, free of charge, to any person obtaining a
7 * copy of this software and associated documentation files (the
8 * "Software"), to deal in the Software without restriction, including
9 * without limitation the rights to use, copy, modify, merge, publish,
10 * distribute, and/or sell copies of the Software, and to permit persons
11 * to whom the Software is furnished to do so, provided that the above
12 * copyright notice(s) and this permission notice appear in all copies of
13 * the Software and that both the above copyright notice(s) and this
14 * permission notice appear in supporting documentation.
16 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
17 * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
18 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT
19 * OF THIRD PARTY RIGHTS. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
20 * HOLDERS INCLUDED IN THIS NOTICE BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL
21 * INDIRECT OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING
22 * FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT,
23 * NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION
24 * WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
26 * Except as contained in this notice, the name of a copyright holder
27 * shall not be used in advertising or otherwise to promote the sale, use
28 * or other dealings in this Software without prior written authorization
29 * of the copyright holder.
33 * Copyright 2004 Sun Microsystems, Inc. All rights reserved.
34 * Use is subject to license terms.
35 * Copyright (c) 2016 by Delphix. All rights reserved.
39 * Standard headers.
41 #include <stdio.h>
42 #include <stdlib.h>
43 #include <signal.h>
44 #include <string.h>
45 #include <errno.h>
46 #include <ctype.h>
47 #include <setjmp.h>
48 #include <stdarg.h>
51 * UNIX headers.
53 #include <sys/ioctl.h>
54 #ifdef HAVE_SELECT
55 #ifdef HAVE_SYS_SELECT_H
56 #include <sys/select.h>
57 #endif
58 #include <sys/time.h>
59 #include <sys/types.h>
60 #endif
62 #include <curses.h>
63 #include <term.h>
65 * When using termcap, include termcap.h on systems that have it.
66 * Otherwise assume that all prototypes are provided by curses.h.
68 #if defined(USE_TERMCAP) && defined(HAVE_TERMCAP_H)
69 #include <termcap.h>
70 #endif
72 typedef int TputsRetType;
73 typedef int TputsArgType; /* int tputs(int c, FILE *fp) */
74 #define TPUTS_RETURNS_VALUE 1
77 * Use the above specifications to prototype our tputs callback function.
79 static TputsRetType gl_tputs_putchar(TputsArgType c);
83 * If the library is being compiled without filesystem access facilities,
84 * ensure that none of the action functions that normally do access the
85 * filesystem are bound by default, and that it they do get bound, that
86 * they don't do anything.
88 #if WITHOUT_FILE_SYSTEM
89 #define HIDE_FILE_SYSTEM
90 #endif
93 * POSIX headers.
95 #include <unistd.h>
96 #include <fcntl.h>
97 #include <termios.h>
100 * Provide typedefs for standard POSIX structures.
102 typedef struct sigaction SigAction;
103 typedef struct termios Termios;
106 * Which flag is used to select non-blocking I/O with fcntl()?
108 #undef NON_BLOCKING_FLAG
109 #if defined(O_NONBLOCK)
110 #define NON_BLOCKING_FLAG (O_NONBLOCK)
111 #elif defined(O_NDELAY)
112 #define NON_BLOCKING_FLAG (O_NDELAY)
113 #endif
116 * What value should we give errno if I/O blocks when it shouldn't.
118 #undef BLOCKED_ERRNO
119 #if defined(EAGAIN)
120 #define BLOCKED_ERRNO (EAGAIN)
121 #elif defined(EWOULDBLOCK)
122 #define BLOCKED_ERRNO (EWOULDBLOCK)
123 #elif defined(EIO)
124 #define BLOCKED_ERRNO (EIO)
125 #else
126 #define BLOCKED_ERRNO 0
127 #endif
130 * Local headers.
132 #ifndef WITHOUT_FILE_SYSTEM
133 #include "pathutil.h"
134 #endif
135 #include "libtecla.h"
136 #include "keytab.h"
137 #include "getline.h"
138 #include "ioutil.h"
139 #include "history.h"
140 #include "freelist.h"
141 #include "stringrp.h"
142 #include "chrqueue.h"
143 #include "cplmatch.h"
144 #ifndef WITHOUT_FILE_SYSTEM
145 #include "expand.h"
146 #endif
147 #include "errmsg.h"
150 * Enumerate the available editing styles.
152 typedef enum {
153 GL_EMACS_MODE, /* Emacs style editing */
154 GL_VI_MODE, /* Vi style editing */
155 GL_NO_EDITOR /* Fall back to the basic OS-provided editing */
156 } GlEditor;
159 * Set the largest key-sequence that can be handled.
161 #define GL_KEY_MAX 64
164 * In vi mode, the following datatype is used to implement the
165 * undo command. It records a copy of the input line from before
166 * the command-mode action which edited the input line.
168 typedef struct {
169 char *line; /* A historical copy of the input line */
170 int buff_curpos; /* The historical location of the cursor in */
171 /* line[] when the line was modified. */
172 int ntotal; /* The number of characters in line[] */
173 int saved; /* True once a line has been saved after the */
174 /* last call to gl_interpret_char(). */
175 } ViUndo;
178 * In vi mode, the following datatype is used to record information
179 * needed by the vi-repeat-change command.
181 typedef struct {
182 KtAction action; /* The last action function that made a */
183 /* change to the line. */
184 int count; /* The repeat count that was passed to the */
185 /* above command. */
186 int input_curpos; /* Whenever vi command mode is entered, the */
187 /* the position at which it was first left */
188 /* is recorded here. */
189 int command_curpos; /* Whenever vi command mode is entered, the */
190 /* the location of the cursor is recorded */
191 /* here. */
192 char input_char; /* Commands that call gl_read_terminal() */
193 /* record the character here, so that it can */
194 /* used on repeating the function. */
195 int saved; /* True if a function has been saved since the */
196 /* last call to gl_interpret_char(). */
197 int active; /* True while a function is being repeated. */
198 } ViRepeat;
201 * The following datatype is used to encapsulate information specific
202 * to vi mode.
204 typedef struct {
205 ViUndo undo; /* Information needed to implement the vi */
206 /* undo command. */
207 ViRepeat repeat; /* Information needed to implement the vi */
208 /* repeat command. */
209 int command; /* True in vi command-mode */
210 int find_forward; /* True if the last character search was in the */
211 /* forward direction. */
212 int find_onto; /* True if the last character search left the */
213 /* on top of the located character, as opposed */
214 /* to just before or after it. */
215 char find_char; /* The last character sought, or '\0' if no */
216 /* searches have been performed yet. */
217 } ViMode;
219 #ifdef HAVE_SELECT
221 * Define a type for recording a file-descriptor callback and its associated
222 * data.
224 typedef struct {
225 GlFdEventFn *fn; /* The callback function */
226 void *data; /* Anonymous data to pass to the callback function */
227 } GlFdHandler;
230 * A list of nodes of the following type is used to record file-activity
231 * event handlers, but only on systems that have the select() system call.
233 typedef struct GlFdNode GlFdNode;
234 struct GlFdNode {
235 GlFdNode *next; /* The next in the list of nodes */
236 int fd; /* The file descriptor being watched */
237 GlFdHandler rd; /* The callback to call when fd is readable */
238 GlFdHandler wr; /* The callback to call when fd is writable */
239 GlFdHandler ur; /* The callback to call when fd has urgent data */
243 * Set the number of the above structures to allocate every time that
244 * the freelist of GlFdNode's becomes exhausted.
246 #define GLFD_FREELIST_BLOCKING 10
249 static int gl_call_fd_handler(GetLine *gl, GlFdHandler *gfh, int fd,
250 GlFdEvent event);
252 static int gl_call_timeout_handler(GetLine *gl);
254 #endif
257 * Each signal that gl_get_line() traps is described by a list node
258 * of the following type.
260 typedef struct GlSignalNode GlSignalNode;
261 struct GlSignalNode {
262 GlSignalNode *next; /* The next signal in the list */
263 int signo; /* The number of the signal */
264 sigset_t proc_mask; /* A process mask which only includes signo */
265 SigAction original; /* The signal disposition of the calling program */
266 /* for this signal. */
267 unsigned flags; /* A bitwise union of GlSignalFlags enumerators */
268 GlAfterSignal after; /* What to do after the signal has been handled */
269 int errno_value; /* What to set errno to */
273 * Set the number of the above structures to allocate every time that
274 * the freelist of GlSignalNode's becomes exhausted.
276 #define GLS_FREELIST_BLOCKING 30
279 * Completion handlers and their callback data are recorded in
280 * nodes of the following type.
282 typedef struct GlCplCallback GlCplCallback;
283 struct GlCplCallback {
284 CplMatchFn *fn; /* The completion callback function */
285 void *data; /* Arbitrary callback data */
289 * The following function is used as the default completion handler when
290 * the filesystem is to be hidden. It simply reports no completions.
292 #ifdef HIDE_FILE_SYSTEM
293 static CPL_MATCH_FN(gl_no_completions);
294 #endif
297 * Specify how many GlCplCallback nodes are added to the GlCplCallback freelist
298 * whenever it becomes exhausted.
300 #define GL_CPL_FREELIST_BLOCKING 10
303 * External action functions and their callback data are recorded in
304 * nodes of the following type.
306 typedef struct GlExternalAction GlExternalAction;
307 struct GlExternalAction {
308 GlActionFn *fn; /* The function which implements the action */
309 void *data; /* Arbitrary callback data */
313 * Specify how many GlExternalAction nodes are added to the
314 * GlExternalAction freelist whenever it becomes exhausted.
316 #define GL_EXT_ACT_FREELIST_BLOCKING 10
319 * Define the contents of the GetLine object.
320 * Note that the typedef for this object can be found in libtecla.h.
322 struct GetLine {
323 ErrMsg *err; /* The error-reporting buffer */
324 GlHistory *glh; /* The line-history buffer */
325 WordCompletion *cpl; /* String completion resource object */
326 GlCplCallback cplfn; /* The completion callback */
327 #ifndef WITHOUT_FILE_SYSTEM
328 ExpandFile *ef; /* ~user/, $envvar and wildcard expansion */
329 /* resource object. */
330 #endif
331 StringGroup *capmem; /* Memory for recording terminal capability */
332 /* strings. */
333 GlCharQueue *cq; /* The terminal output character queue */
334 int input_fd; /* The file descriptor to read on */
335 int output_fd; /* The file descriptor to write to */
336 FILE *input_fp; /* A stream wrapper around input_fd */
337 FILE *output_fp; /* A stream wrapper around output_fd */
338 FILE *file_fp; /* When input is being temporarily taken from */
339 /* a file, this is its file-pointer. Otherwise */
340 /* it is NULL. */
341 char *term; /* The terminal type specified on the last call */
342 /* to gl_change_terminal(). */
343 int is_term; /* True if stdin is a terminal */
344 GlWriteFn *flush_fn; /* The function to call to write to the terminal */
345 GlIOMode io_mode; /* The I/O mode established by gl_io_mode() */
346 int raw_mode; /* True while the terminal is in raw mode */
347 GlPendingIO pending_io; /* The type of I/O that is currently pending */
348 GlReturnStatus rtn_status; /* The reason why gl_get_line() returned */
349 int rtn_errno; /* THe value of errno associated with rtn_status */
350 size_t linelen; /* The max number of characters per line */
351 char *line; /* A line-input buffer of allocated size */
352 /* linelen+2. The extra 2 characters are */
353 /* reserved for "\n\0". */
354 char *cutbuf; /* A cut-buffer of the same size as line[] */
355 char *prompt; /* The current prompt string */
356 int prompt_len; /* The length of the prompt string */
357 int prompt_changed; /* True after a callback changes the prompt */
358 int prompt_style; /* How the prompt string is displayed */
359 FreeList *cpl_mem; /* Memory for GlCplCallback objects */
360 FreeList *ext_act_mem; /* Memory for GlExternalAction objects */
361 FreeList *sig_mem; /* Memory for nodes of the signal list */
362 GlSignalNode *sigs; /* The head of the list of signals */
363 int signals_masked; /* True between calls to gl_mask_signals() and */
364 /* gl_unmask_signals() */
365 int signals_overriden; /* True between calls to gl_override_signals() */
366 /* and gl_restore_signals() */
367 sigset_t all_signal_set; /* The set of all signals that we are trapping */
368 sigset_t old_signal_set; /* The set of blocked signals on entry to */
369 /* gl_get_line(). */
370 sigset_t use_signal_set; /* The subset of all_signal_set to unblock */
371 /* while waiting for key-strokes */
372 Termios oldattr; /* Saved terminal attributes. */
373 KeyTab *bindings; /* A table of key-bindings */
374 int ntotal; /* The number of characters in gl->line[] */
375 int buff_curpos; /* The cursor position within gl->line[] */
376 int term_curpos; /* The cursor position on the terminal */
377 int term_len; /* The number of terminal characters used to */
378 /* display the current input line. */
379 int buff_mark; /* A marker location in the buffer */
380 int insert_curpos; /* The cursor position at start of insert */
381 int insert; /* True in insert mode */
382 int number; /* If >= 0, a numeric argument is being read */
383 int endline; /* True to tell gl_get_input_line() to return */
384 /* the current contents of gl->line[] */
385 int displayed; /* True if an input line is currently displayed */
386 int redisplay; /* If true, the input line will be redrawn */
387 /* either after the current action function */
388 /* returns, or when gl_get_input_line() */
389 /* is next called. */
390 int postpone; /* _gl_normal_io() sets this flag, to */
391 /* postpone any redisplays until */
392 /* is next called, to resume line editing. */
393 char keybuf[GL_KEY_MAX+1]; /* A buffer of currently unprocessed key presses */
394 int nbuf; /* The number of characters in keybuf[] */
395 int nread; /* The number of characters read from keybuf[] */
396 KtAction current_action; /* The action function that is being invoked */
397 int current_count; /* The repeat count passed to */
398 /* current_acction.fn() */
399 GlhLineID preload_id; /* When not zero, this should be the ID of a */
400 /* line in the history buffer for potential */
401 /* recall. */
402 int preload_history; /* If true, preload the above history line when */
403 /* gl_get_input_line() is next called. */
404 long keyseq_count; /* The number of key sequences entered by the */
405 /* the user since new_GetLine() was called. */
406 long last_search; /* The value of keyseq_count during the last */
407 /* history search operation. */
408 GlEditor editor; /* The style of editing, (eg. vi or emacs) */
409 int silence_bell; /* True if gl_ring_bell() should do nothing. */
410 int automatic_history; /* True to automatically archive entered lines */
411 /* in the history list. */
412 ViMode vi; /* Parameters used when editing in vi mode */
413 const char *left; /* The string that moves the cursor 1 character */
414 /* left. */
415 const char *right; /* The string that moves the cursor 1 character */
416 /* right. */
417 const char *up; /* The string that moves the cursor 1 character */
418 /* up. */
419 const char *down; /* The string that moves the cursor 1 character */
420 /* down. */
421 const char *home; /* The string that moves the cursor home */
422 const char *bol; /* Move cursor to beginning of line */
423 const char *clear_eol; /* The string that clears from the cursor to */
424 /* the end of the line. */
425 const char *clear_eod; /* The string that clears from the cursor to */
426 /* the end of the display. */
427 const char *u_arrow; /* The string returned by the up-arrow key */
428 const char *d_arrow; /* The string returned by the down-arrow key */
429 const char *l_arrow; /* The string returned by the left-arrow key */
430 const char *r_arrow; /* The string returned by the right-arrow key */
431 const char *sound_bell; /* The string needed to ring the terminal bell */
432 const char *bold; /* Switch to the bold font */
433 const char *underline; /* Underline subsequent characters */
434 const char *standout; /* Turn on standout mode */
435 const char *dim; /* Switch to a dim font */
436 const char *reverse; /* Turn on reverse video */
437 const char *blink; /* Switch to a blinking font */
438 const char *text_attr_off; /* Turn off all text attributes */
439 int nline; /* The height of the terminal in lines */
440 int ncolumn; /* The width of the terminal in columns */
441 #ifdef USE_TERMCAP
442 char *tgetent_buf; /* The buffer that is used by tgetent() to */
443 /* store a terminal description. */
444 char *tgetstr_buf; /* The buffer that is used by tgetstr() to */
445 /* store terminal capabilities. */
446 #endif
447 #ifdef USE_TERMINFO
448 const char *left_n; /* The parameter string that moves the cursor */
449 /* n characters left. */
450 const char *right_n; /* The parameter string that moves the cursor */
451 /* n characters right. */
452 #endif
453 char *app_file; /* The pathname of the application-specific */
454 /* .teclarc configuration file, or NULL. */
455 char *user_file; /* The pathname of the user-specific */
456 /* .teclarc configuration file, or NULL. */
457 int configured; /* True as soon as any teclarc configuration */
458 /* file has been read. */
459 int echo; /* True to display the line as it is being */
460 /* entered. If 0, only the prompt will be */
461 /* displayed, and the line will not be */
462 /* archived in the history list. */
463 int last_signal; /* The last signal that was caught by */
464 /* the last call to gl_get_line(), or -1 */
465 /* if no signal has been caught yet. */
466 #ifdef HAVE_SELECT
467 FreeList *fd_node_mem; /* A freelist of GlFdNode structures */
468 GlFdNode *fd_nodes; /* The list of fd event descriptions */
469 fd_set rfds; /* The set of fds to watch for readability */
470 fd_set wfds; /* The set of fds to watch for writability */
471 fd_set ufds; /* The set of fds to watch for urgent data */
472 int max_fd; /* The maximum file-descriptor being watched */
473 struct { /* Inactivity timeout related data */
474 struct timeval dt; /* The inactivity timeout when timer.fn() */
475 /* isn't 0 */
476 GlTimeoutFn *fn; /* The application callback to call when */
477 /* the inactivity timer expires, or 0 if */
478 /* timeouts are not required. */
479 void *data; /* Application provided data to be passed to */
480 /* timer.fn(). */
481 } timer;
482 #endif
486 * Define the max amount of space needed to store a termcap terminal
487 * description. Unfortunately this has to be done by guesswork, so
488 * there is the potential for buffer overflows if we guess too small.
489 * Fortunately termcap has been replaced by terminfo on most
490 * platforms, and with terminfo this isn't an issue. The value that I
491 * am using here is the conventional value, as recommended by certain
492 * web references.
494 #ifdef USE_TERMCAP
495 #define TERMCAP_BUF_SIZE 2048
496 #endif
499 * Set the size of the string segments used to store terminal capability
500 * strings.
502 #define CAPMEM_SEGMENT_SIZE 512
505 * If no terminal size information is available, substitute the
506 * following vt100 default sizes.
508 #define GL_DEF_NLINE 24
509 #define GL_DEF_NCOLUMN 80
512 * Enumerate the attributes needed to classify different types of
513 * signals. These attributes reflect the standard default
514 * characteristics of these signals (according to Richard Steven's
515 * Advanced Programming in the UNIX Environment). Note that these values
516 * are all powers of 2, so that they can be combined in a bitwise union.
518 typedef enum {
519 GLSA_TERM=1, /* A signal that terminates processes */
520 GLSA_SUSP=2, /* A signal that suspends processes */
521 GLSA_CONT=4, /* A signal that is sent when suspended processes resume */
522 GLSA_IGN=8, /* A signal that is ignored */
523 GLSA_CORE=16, /* A signal that generates a core dump */
524 GLSA_HARD=32, /* A signal generated by a hardware exception */
525 GLSA_SIZE=64 /* A signal indicating terminal size changes */
526 } GlSigAttr;
529 * List the signals that we need to catch. In general these are
530 * those that by default terminate or suspend the process, since
531 * in such cases we need to restore terminal settings.
533 static const struct GlDefSignal {
534 int signo; /* The number of the signal */
535 unsigned flags; /* A bitwise union of GlSignalFlags enumerators */
536 GlAfterSignal after; /* What to do after the signal has been delivered */
537 int attr; /* The default attributes of this signal, expressed */
538 /* as a bitwise union of GlSigAttr enumerators */
539 int errno_value; /* What to set errno to */
540 } gl_signal_list[] = {
541 {SIGABRT, GLS_SUSPEND_INPUT, GLS_ABORT, GLSA_TERM|GLSA_CORE, EINTR},
542 {SIGALRM, GLS_RESTORE_ENV, GLS_CONTINUE, GLSA_TERM, 0},
543 {SIGCONT, GLS_RESTORE_ENV, GLS_CONTINUE, GLSA_CONT|GLSA_IGN, 0},
544 #if defined(SIGHUP)
545 #ifdef ENOTTY
546 {SIGHUP, GLS_SUSPEND_INPUT, GLS_ABORT, GLSA_TERM, ENOTTY},
547 #else
548 {SIGHUP, GLS_SUSPEND_INPUT, GLS_ABORT, GLSA_TERM, EINTR},
549 #endif
550 #endif
551 {SIGINT, GLS_SUSPEND_INPUT, GLS_ABORT, GLSA_TERM, EINTR},
552 #if defined(SIGPIPE)
553 #ifdef EPIPE
554 {SIGPIPE, GLS_SUSPEND_INPUT, GLS_ABORT, GLSA_TERM, EPIPE},
555 #else
556 {SIGPIPE, GLS_SUSPEND_INPUT, GLS_ABORT, GLSA_TERM, EINTR},
557 #endif
558 #endif
559 #ifdef SIGPOLL
560 {SIGPOLL, GLS_SUSPEND_INPUT, GLS_ABORT, GLSA_TERM, EINTR},
561 #endif
562 #ifdef SIGPWR
563 {SIGPWR, GLS_RESTORE_ENV, GLS_CONTINUE, GLSA_IGN, 0},
564 #endif
565 #ifdef SIGQUIT
566 {SIGQUIT, GLS_SUSPEND_INPUT, GLS_ABORT, GLSA_TERM|GLSA_CORE, EINTR},
567 #endif
568 {SIGTERM, GLS_SUSPEND_INPUT, GLS_ABORT, GLSA_TERM, EINTR},
569 #ifdef SIGTSTP
570 {SIGTSTP, GLS_SUSPEND_INPUT, GLS_CONTINUE, GLSA_SUSP, 0},
571 #endif
572 #ifdef SIGTTIN
573 {SIGTTIN, GLS_SUSPEND_INPUT, GLS_CONTINUE, GLSA_SUSP, 0},
574 #endif
575 #ifdef SIGTTOU
576 {SIGTTOU, GLS_SUSPEND_INPUT, GLS_CONTINUE, GLSA_SUSP, 0},
577 #endif
578 #ifdef SIGUSR1
579 {SIGUSR1, GLS_RESTORE_ENV, GLS_CONTINUE, GLSA_TERM, 0},
580 #endif
581 #ifdef SIGUSR2
582 {SIGUSR2, GLS_RESTORE_ENV, GLS_CONTINUE, GLSA_TERM, 0},
583 #endif
584 #ifdef SIGVTALRM
585 {SIGVTALRM, GLS_RESTORE_ENV, GLS_CONTINUE, GLSA_TERM, 0},
586 #endif
587 #ifdef SIGWINCH
588 {SIGWINCH, GLS_RESTORE_ENV, GLS_CONTINUE, GLSA_SIZE|GLSA_IGN, 0},
589 #endif
590 #ifdef SIGXCPU
591 {SIGXCPU, GLS_RESTORE_ENV, GLS_CONTINUE, GLSA_TERM|GLSA_CORE, 0},
592 #endif
593 #ifdef SIGXFSZ
594 {SIGXFSZ, GLS_RESTORE_ENV, GLS_CONTINUE, GLSA_TERM|GLSA_CORE, 0},
595 #endif
599 * Define file-scope variables for use in signal handlers.
601 static volatile sig_atomic_t gl_pending_signal = -1;
602 static sigjmp_buf gl_setjmp_buffer;
604 static void gl_signal_handler(int signo);
606 static int gl_check_caught_signal(GetLine *gl);
609 * Respond to an externally caught process suspension or
610 * termination signal.
612 static void gl_suspend_process(int signo, GetLine *gl, int ngl);
614 /* Return the default attributes of a given signal */
616 static int gl_classify_signal(int signo);
619 * Unfortunately both terminfo and termcap require one to use the tputs()
620 * function to output terminal control characters, and this function
621 * doesn't allow one to specify a file stream. As a result, the following
622 * file-scope variable is used to pass the current output file stream.
623 * This is bad, but there doesn't seem to be any alternative.
625 static GetLine *tputs_gl = NULL;
628 * Define a tab to be a string of 8 spaces.
630 #define TAB_WIDTH 8
633 * Lookup the current size of the terminal.
635 static void gl_query_size(GetLine *gl, int *ncolumn, int *nline);
638 * Getline calls this to temporarily override certain signal handlers
639 * of the calling program.
641 static int gl_override_signal_handlers(GetLine *gl);
644 * Getline calls this to restore the signal handlers of the calling
645 * program.
647 static int gl_restore_signal_handlers(GetLine *gl);
650 * Temporarily block the delivery of all signals that gl_get_line()
651 * is currently configured to trap.
653 static int gl_mask_signals(GetLine *gl, sigset_t *oldset);
656 * Restore the process signal mask that was overriden by a previous
657 * call to gl_mask_signals().
659 static int gl_unmask_signals(GetLine *gl, sigset_t *oldset);
662 * Unblock the signals that gl_get_line() has been configured to catch.
664 static int gl_catch_signals(GetLine *gl);
667 * Return the set of all trappable signals.
669 static void gl_list_trappable_signals(sigset_t *signals);
672 * Put the terminal into raw input mode, after saving the original
673 * terminal attributes in gl->oldattr.
675 static int gl_raw_terminal_mode(GetLine *gl);
678 * Restore the terminal attributes from gl->oldattr.
680 static int gl_restore_terminal_attributes(GetLine *gl);
683 * Switch to non-blocking I/O if possible.
685 static int gl_nonblocking_io(GetLine *gl, int fd);
688 * Switch to blocking I/O if possible.
690 static int gl_blocking_io(GetLine *gl, int fd);
693 * Read a line from the user in raw mode.
695 static int gl_get_input_line(GetLine *gl, const char *prompt,
696 const char *start_line, int start_pos);
699 * Query the user for a single character.
701 static int gl_get_query_char(GetLine *gl, const char *prompt, int defchar);
704 * Read input from a non-interactive input stream.
706 static int gl_read_stream_line(GetLine *gl);
709 * Read a single character from a non-interactive input stream.
711 static int gl_read_stream_char(GetLine *gl);
714 * Prepare to edit a new line.
716 static int gl_present_line(GetLine *gl, const char *prompt,
717 const char *start_line, int start_pos);
720 * Reset all line input parameters for a new input line.
722 static void gl_reset_input_line(GetLine *gl);
725 * Handle the receipt of the potential start of a new key-sequence from
726 * the user.
728 static int gl_interpret_char(GetLine *gl, char c);
731 * Bind a single control or meta character to an action.
733 static int gl_bind_control_char(GetLine *gl, KtBinder binder,
734 char c, const char *action);
737 * Set up terminal-specific key bindings.
739 static int gl_bind_terminal_keys(GetLine *gl);
742 * Lookup terminal control string and size information.
744 static int gl_control_strings(GetLine *gl, const char *term);
747 * Wrappers around the terminfo and termcap functions that lookup
748 * strings in the terminal information databases.
750 #ifdef USE_TERMINFO
751 static const char *gl_tigetstr(GetLine *gl, const char *name);
752 #elif defined(USE_TERMCAP)
753 static const char *gl_tgetstr(GetLine *gl, const char *name, char **bufptr);
754 #endif
757 * Output a binary string directly to the terminal.
759 static int gl_print_raw_string(GetLine *gl, int buffered,
760 const char *string, int n);
763 * Print an informational message, starting and finishing on new lines.
764 * After the list of strings to be printed, the last argument MUST be
765 * GL_END_INFO.
767 static int gl_print_info(GetLine *gl, ...);
768 #define GL_END_INFO ((const char *)0)
771 * Start a newline and place the cursor at its start.
773 static int gl_start_newline(GetLine *gl, int buffered);
776 * Output a terminal control sequence.
778 static int gl_print_control_sequence(GetLine *gl, int nline,
779 const char *string);
782 * Output a character or string to the terminal after converting tabs
783 * to spaces and control characters to a caret followed by the modified
784 * character.
786 static int gl_print_char(GetLine *gl, char c, char pad);
787 static int gl_print_string(GetLine *gl, const char *string, char pad);
790 * Delete nc characters starting from the one under the cursor.
791 * Optionally copy the deleted characters to the cut buffer.
793 static int gl_delete_chars(GetLine *gl, int nc, int cut);
796 * Add a character to the line buffer at the current cursor position,
797 * inserting or overwriting according the current mode.
799 static int gl_add_char_to_line(GetLine *gl, char c);
802 * Insert/append a string to the line buffer and terminal at the current
803 * cursor position.
805 static int gl_add_string_to_line(GetLine *gl, const char *s);
808 * Record a new character in the input-line buffer.
810 static int gl_buffer_char(GetLine *gl, char c, int bufpos);
813 * Record a string in the input-line buffer.
815 static int gl_buffer_string(GetLine *gl, const char *s, int n, int bufpos);
818 * Make way to insert a string in the input-line buffer.
820 static int gl_make_gap_in_buffer(GetLine *gl, int start, int n);
823 * Remove characters from the input-line buffer, and move any characters
824 * that followed them to the start of the vacated space.
826 static void gl_remove_from_buffer(GetLine *gl, int start, int n);
829 * Terminate the input-line buffer after a specified number of characters.
831 static int gl_truncate_buffer(GetLine *gl, int n);
834 * Delete the displayed part of the input line that follows the current
835 * terminal cursor position.
837 static int gl_truncate_display(GetLine *gl);
840 * Accomodate changes to the contents of the input line buffer
841 * that weren't made by the above gl_*buffer functions.
843 static void gl_update_buffer(GetLine *gl);
846 * Read a single character from the terminal.
848 static int gl_read_terminal(GetLine *gl, int keep, char *c);
851 * Discard processed characters from the key-press lookahead buffer.
853 static void gl_discard_chars(GetLine *gl, int nused);
856 * Move the terminal cursor n positions to the left or right.
858 static int gl_terminal_move_cursor(GetLine *gl, int n);
861 * Move the terminal cursor to a given position.
863 static int gl_set_term_curpos(GetLine *gl, int term_curpos);
866 * Set the position of the cursor both in the line input buffer and on the
867 * terminal.
869 static int gl_place_cursor(GetLine *gl, int buff_curpos);
872 * How many characters are needed to write a number as an octal string?
874 static int gl_octal_width(unsigned num);
877 * Return the number of spaces needed to display a tab character at
878 * a given location of the terminal.
880 static int gl_displayed_tab_width(GetLine *gl, int term_curpos);
883 * Return the number of terminal characters needed to display a
884 * given raw character.
886 static int gl_displayed_char_width(GetLine *gl, char c, int term_curpos);
889 * Return the number of terminal characters needed to display a
890 * given substring.
892 static int gl_displayed_string_width(GetLine *gl, const char *string, int nc,
893 int term_curpos);
896 * Return non-zero if 'c' is to be considered part of a word.
898 static int gl_is_word_char(int c);
901 * Read a tecla configuration file.
903 static int _gl_read_config_file(GetLine *gl, const char *filename, KtBinder who);
906 * Read a tecla configuration string.
908 static int _gl_read_config_string(GetLine *gl, const char *buffer, KtBinder who);
911 * Define the callback function used by _gl_parse_config_line() to
912 * read the next character of a configuration stream.
914 #define GLC_GETC_FN(fn) int (fn)(void *stream)
915 typedef GLC_GETC_FN(GlcGetcFn);
917 static GLC_GETC_FN(glc_file_getc); /* Read from a file */
918 static GLC_GETC_FN(glc_buff_getc); /* Read from a string */
921 * Parse a single configuration command line.
923 static int _gl_parse_config_line(GetLine *gl, void *stream, GlcGetcFn *getc_fn,
924 const char *origin, KtBinder who, int *lineno);
925 static int gl_report_config_error(GetLine *gl, const char *origin, int lineno,
926 const char *errmsg);
929 * Bind the actual arrow key bindings to match those of the symbolic
930 * arrow-key bindings.
932 static int _gl_bind_arrow_keys(GetLine *gl);
935 * Copy the binding of the specified symbolic arrow-key binding to
936 * the terminal specific, and default arrow-key key-sequences.
938 static int _gl_rebind_arrow_key(GetLine *gl, const char *name,
939 const char *term_seq,
940 const char *def_seq1,
941 const char *def_seq2);
944 * After the gl_read_from_file() action has been used to tell gl_get_line()
945 * to temporarily read input from a file, gl_revert_input() arranges
946 * for input to be reverted to the input stream last registered with
947 * gl_change_terminal().
949 static void gl_revert_input(GetLine *gl);
952 * Flush unwritten characters to the terminal.
954 static int gl_flush_output(GetLine *gl);
957 * The callback through which all terminal output is routed.
958 * This simply appends characters to a queue buffer, which is
959 * subsequently flushed to the output channel by gl_flush_output().
961 static GL_WRITE_FN(gl_write_fn);
964 * The callback function which the output character queue object
965 * calls to transfer characters to the output channel.
967 static GL_WRITE_FN(gl_flush_terminal);
970 * Enumerate the possible return statuses of gl_read_input().
972 typedef enum {
973 GL_READ_OK, /* A character was read successfully */
974 GL_READ_ERROR, /* A read-error occurred */
975 GL_READ_BLOCKED, /* The read would have blocked the caller */
976 GL_READ_EOF /* The end of the current input file was reached */
977 } GlReadStatus;
979 static GlReadStatus gl_read_input(GetLine *gl, char *c);
981 * Private functions of gl_read_input().
983 static int gl_event_handler(GetLine *gl, int fd);
984 static int gl_read_unmasked(GetLine *gl, int fd, char *c);
988 * A private function of gl_tty_signals().
990 static int gl_set_tty_signal(int signo, void (*handler)(int));
993 * Change the editor style being emulated.
995 static int gl_change_editor(GetLine *gl, GlEditor editor);
998 * Searching in a given direction, return the index of a given (or
999 * read) character in the input line, or the character that precedes
1000 * it in the specified search direction. Return -1 if not found.
1002 static int gl_find_char(GetLine *gl, int count, int forward, int onto, char c);
1005 * Return the buffer index of the nth word ending after the cursor.
1007 static int gl_nth_word_end_forward(GetLine *gl, int n);
1010 * Return the buffer index of the nth word start after the cursor.
1012 static int gl_nth_word_start_forward(GetLine *gl, int n);
1015 * Return the buffer index of the nth word start before the cursor.
1017 static int gl_nth_word_start_backward(GetLine *gl, int n);
1020 * When called when vi command mode is enabled, this function saves the
1021 * current line and cursor position for potential restoration later
1022 * by the vi undo command.
1024 static void gl_save_for_undo(GetLine *gl);
1027 * If in vi mode, switch to vi command mode.
1029 static void gl_vi_command_mode(GetLine *gl);
1032 * In vi mode this is used to delete up to or onto a given or read
1033 * character in the input line. Also switch to insert mode if requested
1034 * after the deletion.
1036 static int gl_delete_find(GetLine *gl, int count, char c, int forward,
1037 int onto, int change);
1040 * Copy the characters between the cursor and the count'th instance of
1041 * a specified (or read) character in the input line, into the cut buffer.
1043 static int gl_copy_find(GetLine *gl, int count, char c, int forward, int onto);
1046 * Return the line index of the parenthesis that either matches the one under
1047 * the cursor, or not over a parenthesis character, the index of the next
1048 * close parenthesis. Return -1 if not found.
1050 static int gl_index_of_matching_paren(GetLine *gl);
1053 * Replace a malloc'd string (or NULL), with another malloc'd copy of
1054 * a string (or NULL).
1056 static int gl_record_string(char **sptr, const char *string);
1059 * Enumerate text display attributes as powers of two, suitable for
1060 * use in a bit-mask.
1062 typedef enum {
1063 GL_TXT_STANDOUT=1, /* Display text highlighted */
1064 GL_TXT_UNDERLINE=2, /* Display text underlined */
1065 GL_TXT_REVERSE=4, /* Display text with reverse video */
1066 GL_TXT_BLINK=8, /* Display blinking text */
1067 GL_TXT_DIM=16, /* Display text in a dim font */
1068 GL_TXT_BOLD=32 /* Display text using a bold font */
1069 } GlTextAttr;
1072 * Display the prompt regardless of the current visibility mode.
1074 static int gl_display_prompt(GetLine *gl);
1077 * Return the number of characters used by the prompt on the terminal.
1079 static int gl_displayed_prompt_width(GetLine *gl);
1082 * Prepare to return the current input line to the caller of gl_get_line().
1084 static int gl_line_ended(GetLine *gl, int newline_char);
1087 * Arrange for the input line to be redisplayed when the current contents
1088 * of the output queue have been flushed.
1090 static void gl_queue_redisplay(GetLine *gl);
1093 * Erase the displayed representation of the input line, without
1094 * touching the buffered copy.
1096 static int gl_erase_line(GetLine *gl);
1099 * This function is called whenever the input line has been erased.
1101 static void gl_line_erased(GetLine *gl);
1104 * Arrange for the current input line to be discarded.
1106 void _gl_abandon_line(GetLine *gl);
1109 * The following are private internally callable versions of pertinent
1110 * public functions. Unlike their public wrapper functions, they don't
1111 * block signals while running, and assume that their arguments are valid.
1112 * They are designed to be called from places where signals are already
1113 * blocked, and where simple sanity checks have already been applied to
1114 * their arguments.
1116 static char *_gl_get_line(GetLine *gl, const char *prompt,
1117 const char *start_line, int start_pos);
1118 static int _gl_query_char(GetLine *gl, const char *prompt, char defchar);
1119 static int _gl_read_char(GetLine *gl);
1120 static int _gl_update_size(GetLine *gl);
1122 * Redraw the current input line to account for a change in the terminal
1123 * size. Also install the new size in gl.
1125 static int gl_handle_tty_resize(GetLine *gl, int ncolumn, int nline);
1127 static int _gl_change_terminal(GetLine *gl, FILE *input_fp, FILE *output_fp,
1128 const char *term);
1129 static int _gl_configure_getline(GetLine *gl, const char *app_string,
1130 const char *app_file, const char *user_file);
1131 static int _gl_save_history(GetLine *gl, const char *filename,
1132 const char *comment, int max_lines);
1133 static int _gl_load_history(GetLine *gl, const char *filename,
1134 const char *comment);
1135 static int _gl_watch_fd(GetLine *gl, int fd, GlFdEvent event,
1136 GlFdEventFn *callback, void *data);
1137 static void _gl_terminal_size(GetLine *gl, int def_ncolumn, int def_nline,
1138 GlTerminalSize *size);
1139 static void _gl_replace_prompt(GetLine *gl, const char *prompt);
1140 static int _gl_trap_signal(GetLine *gl, int signo, unsigned flags,
1141 GlAfterSignal after, int errno_value);
1142 static int _gl_raw_io(GetLine *gl, int redisplay);
1143 static int _gl_normal_io(GetLine *gl);
1144 static int _gl_completion_action(GetLine *gl, void *data, CplMatchFn *match_fn,
1145 int list_only, const char *name,
1146 const char *keyseq);
1147 static int _gl_register_action(GetLine *gl, void *data, GlActionFn *fn,
1148 const char *name, const char *keyseq);
1149 static int _gl_io_mode(GetLine *gl, GlIOMode mode);
1150 static int _gl_set_term_size(GetLine *gl, int ncolumn, int nline);
1151 static int _gl_append_history(GetLine *gl, const char *line);
1154 * Reset the completion status and associated errno value in
1155 * gl->rtn_status and gl->rtn_errno.
1157 static void gl_clear_status(GetLine *gl);
1160 * Record a completion status, unless a previous abnormal completion
1161 * status has already been recorded for the current call.
1163 static void gl_record_status(GetLine *gl, GlReturnStatus rtn_status,
1164 int rtn_errno);
1167 * Set the maximum length of a line in a user's tecla configuration
1168 * file (not counting comments).
1170 #define GL_CONF_BUFLEN 100
1173 * Set the maximum number of arguments supported by individual commands
1174 * in tecla configuration files.
1176 #define GL_CONF_MAXARG 10
1179 * Prototype the available action functions.
1181 static KT_KEY_FN(gl_user_interrupt);
1182 static KT_KEY_FN(gl_abort);
1183 static KT_KEY_FN(gl_suspend);
1184 static KT_KEY_FN(gl_stop_output);
1185 static KT_KEY_FN(gl_start_output);
1186 static KT_KEY_FN(gl_literal_next);
1187 static KT_KEY_FN(gl_cursor_left);
1188 static KT_KEY_FN(gl_cursor_right);
1189 static KT_KEY_FN(gl_insert_mode);
1190 static KT_KEY_FN(gl_beginning_of_line);
1191 static KT_KEY_FN(gl_end_of_line);
1192 static KT_KEY_FN(gl_delete_line);
1193 static KT_KEY_FN(gl_kill_line);
1194 static KT_KEY_FN(gl_forward_word);
1195 static KT_KEY_FN(gl_backward_word);
1196 static KT_KEY_FN(gl_forward_delete_char);
1197 static KT_KEY_FN(gl_backward_delete_char);
1198 static KT_KEY_FN(gl_forward_delete_word);
1199 static KT_KEY_FN(gl_backward_delete_word);
1200 static KT_KEY_FN(gl_delete_refind);
1201 static KT_KEY_FN(gl_delete_invert_refind);
1202 static KT_KEY_FN(gl_delete_to_column);
1203 static KT_KEY_FN(gl_delete_to_parenthesis);
1204 static KT_KEY_FN(gl_forward_delete_find);
1205 static KT_KEY_FN(gl_backward_delete_find);
1206 static KT_KEY_FN(gl_forward_delete_to);
1207 static KT_KEY_FN(gl_backward_delete_to);
1208 static KT_KEY_FN(gl_upcase_word);
1209 static KT_KEY_FN(gl_downcase_word);
1210 static KT_KEY_FN(gl_capitalize_word);
1211 static KT_KEY_FN(gl_redisplay);
1212 static KT_KEY_FN(gl_clear_screen);
1213 static KT_KEY_FN(gl_transpose_chars);
1214 static KT_KEY_FN(gl_set_mark);
1215 static KT_KEY_FN(gl_exchange_point_and_mark);
1216 static KT_KEY_FN(gl_kill_region);
1217 static KT_KEY_FN(gl_copy_region_as_kill);
1218 static KT_KEY_FN(gl_yank);
1219 static KT_KEY_FN(gl_up_history);
1220 static KT_KEY_FN(gl_down_history);
1221 static KT_KEY_FN(gl_history_search_backward);
1222 static KT_KEY_FN(gl_history_re_search_backward);
1223 static KT_KEY_FN(gl_history_search_forward);
1224 static KT_KEY_FN(gl_history_re_search_forward);
1225 static KT_KEY_FN(gl_complete_word);
1226 #ifndef HIDE_FILE_SYSTEM
1227 static KT_KEY_FN(gl_expand_filename);
1228 static KT_KEY_FN(gl_read_from_file);
1229 static KT_KEY_FN(gl_read_init_files);
1230 static KT_KEY_FN(gl_list_glob);
1231 #endif
1232 static KT_KEY_FN(gl_del_char_or_list_or_eof);
1233 static KT_KEY_FN(gl_list_or_eof);
1234 static KT_KEY_FN(gl_beginning_of_history);
1235 static KT_KEY_FN(gl_end_of_history);
1236 static KT_KEY_FN(gl_digit_argument);
1237 static KT_KEY_FN(gl_newline);
1238 static KT_KEY_FN(gl_repeat_history);
1239 static KT_KEY_FN(gl_vi_insert);
1240 static KT_KEY_FN(gl_vi_overwrite);
1241 static KT_KEY_FN(gl_change_case);
1242 static KT_KEY_FN(gl_vi_insert_at_bol);
1243 static KT_KEY_FN(gl_vi_append_at_eol);
1244 static KT_KEY_FN(gl_vi_append);
1245 static KT_KEY_FN(gl_backward_kill_line);
1246 static KT_KEY_FN(gl_goto_column);
1247 static KT_KEY_FN(gl_forward_to_word);
1248 static KT_KEY_FN(gl_vi_replace_char);
1249 static KT_KEY_FN(gl_vi_change_rest_of_line);
1250 static KT_KEY_FN(gl_vi_change_line);
1251 static KT_KEY_FN(gl_vi_change_to_bol);
1252 static KT_KEY_FN(gl_vi_change_refind);
1253 static KT_KEY_FN(gl_vi_change_invert_refind);
1254 static KT_KEY_FN(gl_vi_change_to_column);
1255 static KT_KEY_FN(gl_vi_change_to_parenthesis);
1256 static KT_KEY_FN(gl_vi_forward_change_word);
1257 static KT_KEY_FN(gl_vi_backward_change_word);
1258 static KT_KEY_FN(gl_vi_forward_change_find);
1259 static KT_KEY_FN(gl_vi_backward_change_find);
1260 static KT_KEY_FN(gl_vi_forward_change_to);
1261 static KT_KEY_FN(gl_vi_backward_change_to);
1262 static KT_KEY_FN(gl_vi_forward_change_char);
1263 static KT_KEY_FN(gl_vi_backward_change_char);
1264 static KT_KEY_FN(gl_forward_copy_char);
1265 static KT_KEY_FN(gl_backward_copy_char);
1266 static KT_KEY_FN(gl_forward_find_char);
1267 static KT_KEY_FN(gl_backward_find_char);
1268 static KT_KEY_FN(gl_forward_to_char);
1269 static KT_KEY_FN(gl_backward_to_char);
1270 static KT_KEY_FN(gl_repeat_find_char);
1271 static KT_KEY_FN(gl_invert_refind_char);
1272 static KT_KEY_FN(gl_append_yank);
1273 static KT_KEY_FN(gl_backward_copy_word);
1274 static KT_KEY_FN(gl_forward_copy_word);
1275 static KT_KEY_FN(gl_copy_to_bol);
1276 static KT_KEY_FN(gl_copy_refind);
1277 static KT_KEY_FN(gl_copy_invert_refind);
1278 static KT_KEY_FN(gl_copy_to_column);
1279 static KT_KEY_FN(gl_copy_to_parenthesis);
1280 static KT_KEY_FN(gl_copy_rest_of_line);
1281 static KT_KEY_FN(gl_copy_line);
1282 static KT_KEY_FN(gl_backward_copy_find);
1283 static KT_KEY_FN(gl_forward_copy_find);
1284 static KT_KEY_FN(gl_backward_copy_to);
1285 static KT_KEY_FN(gl_forward_copy_to);
1286 static KT_KEY_FN(gl_vi_undo);
1287 static KT_KEY_FN(gl_emacs_editing_mode);
1288 static KT_KEY_FN(gl_vi_editing_mode);
1289 static KT_KEY_FN(gl_ring_bell);
1290 static KT_KEY_FN(gl_vi_repeat_change);
1291 static KT_KEY_FN(gl_find_parenthesis);
1292 static KT_KEY_FN(gl_list_history);
1293 static KT_KEY_FN(gl_list_completions);
1294 static KT_KEY_FN(gl_run_external_action);
1297 * Name the available action functions.
1299 static const struct {const char *name; KT_KEY_FN(*fn);} gl_actions[] = {
1300 {"user-interrupt", gl_user_interrupt},
1301 {"abort", gl_abort},
1302 {"suspend", gl_suspend},
1303 {"stop-output", gl_stop_output},
1304 {"start-output", gl_start_output},
1305 {"literal-next", gl_literal_next},
1306 {"cursor-right", gl_cursor_right},
1307 {"cursor-left", gl_cursor_left},
1308 {"insert-mode", gl_insert_mode},
1309 {"beginning-of-line", gl_beginning_of_line},
1310 {"end-of-line", gl_end_of_line},
1311 {"delete-line", gl_delete_line},
1312 {"kill-line", gl_kill_line},
1313 {"forward-word", gl_forward_word},
1314 {"backward-word", gl_backward_word},
1315 {"forward-delete-char", gl_forward_delete_char},
1316 {"backward-delete-char", gl_backward_delete_char},
1317 {"forward-delete-word", gl_forward_delete_word},
1318 {"backward-delete-word", gl_backward_delete_word},
1319 {"delete-refind", gl_delete_refind},
1320 {"delete-invert-refind", gl_delete_invert_refind},
1321 {"delete-to-column", gl_delete_to_column},
1322 {"delete-to-parenthesis", gl_delete_to_parenthesis},
1323 {"forward-delete-find", gl_forward_delete_find},
1324 {"backward-delete-find", gl_backward_delete_find},
1325 {"forward-delete-to", gl_forward_delete_to},
1326 {"backward-delete-to", gl_backward_delete_to},
1327 {"upcase-word", gl_upcase_word},
1328 {"downcase-word", gl_downcase_word},
1329 {"capitalize-word", gl_capitalize_word},
1330 {"redisplay", gl_redisplay},
1331 {"clear-screen", gl_clear_screen},
1332 {"transpose-chars", gl_transpose_chars},
1333 {"set-mark", gl_set_mark},
1334 {"exchange-point-and-mark", gl_exchange_point_and_mark},
1335 {"kill-region", gl_kill_region},
1336 {"copy-region-as-kill", gl_copy_region_as_kill},
1337 {"yank", gl_yank},
1338 {"up-history", gl_up_history},
1339 {"down-history", gl_down_history},
1340 {"history-search-backward", gl_history_search_backward},
1341 {"history-re-search-backward", gl_history_re_search_backward},
1342 {"history-search-forward", gl_history_search_forward},
1343 {"history-re-search-forward", gl_history_re_search_forward},
1344 {"complete-word", gl_complete_word},
1345 #ifndef HIDE_FILE_SYSTEM
1346 {"expand-filename", gl_expand_filename},
1347 {"read-from-file", gl_read_from_file},
1348 {"read-init-files", gl_read_init_files},
1349 {"list-glob", gl_list_glob},
1350 #endif
1351 {"del-char-or-list-or-eof", gl_del_char_or_list_or_eof},
1352 {"beginning-of-history", gl_beginning_of_history},
1353 {"end-of-history", gl_end_of_history},
1354 {"digit-argument", gl_digit_argument},
1355 {"newline", gl_newline},
1356 {"repeat-history", gl_repeat_history},
1357 {"vi-insert", gl_vi_insert},
1358 {"vi-overwrite", gl_vi_overwrite},
1359 {"vi-insert-at-bol", gl_vi_insert_at_bol},
1360 {"vi-append-at-eol", gl_vi_append_at_eol},
1361 {"vi-append", gl_vi_append},
1362 {"change-case", gl_change_case},
1363 {"backward-kill-line", gl_backward_kill_line},
1364 {"goto-column", gl_goto_column},
1365 {"forward-to-word", gl_forward_to_word},
1366 {"vi-replace-char", gl_vi_replace_char},
1367 {"vi-change-rest-of-line", gl_vi_change_rest_of_line},
1368 {"vi-change-line", gl_vi_change_line},
1369 {"vi-change-to-bol", gl_vi_change_to_bol},
1370 {"vi-change-refind", gl_vi_change_refind},
1371 {"vi-change-invert-refind", gl_vi_change_invert_refind},
1372 {"vi-change-to-column", gl_vi_change_to_column},
1373 {"vi-change-to-parenthesis", gl_vi_change_to_parenthesis},
1374 {"forward-copy-char", gl_forward_copy_char},
1375 {"backward-copy-char", gl_backward_copy_char},
1376 {"forward-find-char", gl_forward_find_char},
1377 {"backward-find-char", gl_backward_find_char},
1378 {"forward-to-char", gl_forward_to_char},
1379 {"backward-to-char", gl_backward_to_char},
1380 {"repeat-find-char", gl_repeat_find_char},
1381 {"invert-refind-char", gl_invert_refind_char},
1382 {"append-yank", gl_append_yank},
1383 {"backward-copy-word", gl_backward_copy_word},
1384 {"forward-copy-word", gl_forward_copy_word},
1385 {"copy-to-bol", gl_copy_to_bol},
1386 {"copy-refind", gl_copy_refind},
1387 {"copy-invert-refind", gl_copy_invert_refind},
1388 {"copy-to-column", gl_copy_to_column},
1389 {"copy-to-parenthesis", gl_copy_to_parenthesis},
1390 {"copy-rest-of-line", gl_copy_rest_of_line},
1391 {"copy-line", gl_copy_line},
1392 {"backward-copy-find", gl_backward_copy_find},
1393 {"forward-copy-find", gl_forward_copy_find},
1394 {"backward-copy-to", gl_backward_copy_to},
1395 {"forward-copy-to", gl_forward_copy_to},
1396 {"list-or-eof", gl_list_or_eof},
1397 {"vi-undo", gl_vi_undo},
1398 {"vi-backward-change-word", gl_vi_backward_change_word},
1399 {"vi-forward-change-word", gl_vi_forward_change_word},
1400 {"vi-backward-change-find", gl_vi_backward_change_find},
1401 {"vi-forward-change-find", gl_vi_forward_change_find},
1402 {"vi-backward-change-to", gl_vi_backward_change_to},
1403 {"vi-forward-change-to", gl_vi_forward_change_to},
1404 {"vi-backward-change-char", gl_vi_backward_change_char},
1405 {"vi-forward-change-char", gl_vi_forward_change_char},
1406 {"emacs-mode", gl_emacs_editing_mode},
1407 {"vi-mode", gl_vi_editing_mode},
1408 {"ring-bell", gl_ring_bell},
1409 {"vi-repeat-change", gl_vi_repeat_change},
1410 {"find-parenthesis", gl_find_parenthesis},
1411 {"list-history", gl_list_history},
1415 * Define the default key-bindings in emacs mode.
1417 static const KtKeyBinding gl_emacs_bindings[] = {
1418 {"right", "cursor-right"},
1419 {"^F", "cursor-right"},
1420 {"left", "cursor-left"},
1421 {"^B", "cursor-left"},
1422 {"M-i", "insert-mode"},
1423 {"M-I", "insert-mode"},
1424 {"^A", "beginning-of-line"},
1425 {"^E", "end-of-line"},
1426 {"^U", "delete-line"},
1427 {"^K", "kill-line"},
1428 {"M-f", "forward-word"},
1429 {"M-F", "forward-word"},
1430 {"M-b", "backward-word"},
1431 {"M-B", "backward-word"},
1432 {"^D", "del-char-or-list-or-eof"},
1433 {"^H", "backward-delete-char"},
1434 {"^?", "backward-delete-char"},
1435 {"M-d", "forward-delete-word"},
1436 {"M-D", "forward-delete-word"},
1437 {"M-^H", "backward-delete-word"},
1438 {"M-^?", "backward-delete-word"},
1439 {"M-u", "upcase-word"},
1440 {"M-U", "upcase-word"},
1441 {"M-l", "downcase-word"},
1442 {"M-L", "downcase-word"},
1443 {"M-c", "capitalize-word"},
1444 {"M-C", "capitalize-word"},
1445 {"^R", "redisplay"},
1446 {"^L", "clear-screen"},
1447 {"^T", "transpose-chars"},
1448 {"^@", "set-mark"},
1449 {"^X^X", "exchange-point-and-mark"},
1450 {"^W", "kill-region"},
1451 {"M-w", "copy-region-as-kill"},
1452 {"M-W", "copy-region-as-kill"},
1453 {"^Y", "yank"},
1454 {"^P", "up-history"},
1455 {"up", "up-history"},
1456 {"^N", "down-history"},
1457 {"down", "down-history"},
1458 {"M-p", "history-search-backward"},
1459 {"M-P", "history-search-backward"},
1460 {"M-n", "history-search-forward"},
1461 {"M-N", "history-search-forward"},
1462 {"\t", "complete-word"},
1463 #ifndef HIDE_FILE_SYSTEM
1464 {"^X*", "expand-filename"},
1465 {"^X^F", "read-from-file"},
1466 {"^X^R", "read-init-files"},
1467 {"^Xg", "list-glob"},
1468 {"^XG", "list-glob"},
1469 #endif
1470 {"^Xh", "list-history"},
1471 {"^XH", "list-history"},
1472 {"M-<", "beginning-of-history"},
1473 {"M->", "end-of-history"},
1474 {"M-0", "digit-argument"},
1475 {"M-1", "digit-argument"},
1476 {"M-2", "digit-argument"},
1477 {"M-3", "digit-argument"},
1478 {"M-4", "digit-argument"},
1479 {"M-5", "digit-argument"},
1480 {"M-6", "digit-argument"},
1481 {"M-7", "digit-argument"},
1482 {"M-8", "digit-argument"},
1483 {"M-9", "digit-argument"},
1484 {"\r", "newline"},
1485 {"\n", "newline"},
1486 {"M-o", "repeat-history"},
1487 {"M-C-v", "vi-mode"},
1491 * Define the default key-bindings in vi mode. Note that in vi-mode
1492 * meta-key bindings are command-mode bindings. For example M-i first
1493 * switches to command mode if not already in that mode, then moves
1494 * the cursor one position right, as in vi.
1496 static const KtKeyBinding gl_vi_bindings[] = {
1497 {"^D", "list-or-eof"},
1498 #ifndef HIDE_FILE_SYSTEM
1499 {"^G", "list-glob"},
1500 #endif
1501 {"^H", "backward-delete-char"},
1502 {"\t", "complete-word"},
1503 {"\r", "newline"},
1504 {"\n", "newline"},
1505 {"^L", "clear-screen"},
1506 {"^N", "down-history"},
1507 {"^P", "up-history"},
1508 {"^R", "redisplay"},
1509 {"^U", "backward-kill-line"},
1510 {"^W", "backward-delete-word"},
1511 #ifndef HIDE_FILE_SYSTEM
1512 {"^X^F", "read-from-file"},
1513 {"^X^R", "read-init-files"},
1514 {"^X*", "expand-filename"},
1515 #endif
1516 {"^?", "backward-delete-char"},
1517 {"M- ", "cursor-right"},
1518 {"M-$", "end-of-line"},
1519 #ifndef HIDE_FILE_SYSTEM
1520 {"M-*", "expand-filename"},
1521 #endif
1522 {"M-+", "down-history"},
1523 {"M--", "up-history"},
1524 {"M-<", "beginning-of-history"},
1525 {"M->", "end-of-history"},
1526 {"M-^", "beginning-of-line"},
1527 {"M-;", "repeat-find-char"},
1528 {"M-,", "invert-refind-char"},
1529 {"M-|", "goto-column"},
1530 {"M-~", "change-case"},
1531 {"M-.", "vi-repeat-change"},
1532 {"M-%", "find-parenthesis"},
1533 {"M-0", "digit-argument"},
1534 {"M-1", "digit-argument"},
1535 {"M-2", "digit-argument"},
1536 {"M-3", "digit-argument"},
1537 {"M-4", "digit-argument"},
1538 {"M-5", "digit-argument"},
1539 {"M-6", "digit-argument"},
1540 {"M-7", "digit-argument"},
1541 {"M-8", "digit-argument"},
1542 {"M-9", "digit-argument"},
1543 {"M-a", "vi-append"},
1544 {"M-A", "vi-append-at-eol"},
1545 {"M-b", "backward-word"},
1546 {"M-B", "backward-word"},
1547 {"M-C", "vi-change-rest-of-line"},
1548 {"M-cb", "vi-backward-change-word"},
1549 {"M-cB", "vi-backward-change-word"},
1550 {"M-cc", "vi-change-line"},
1551 {"M-ce", "vi-forward-change-word"},
1552 {"M-cE", "vi-forward-change-word"},
1553 {"M-cw", "vi-forward-change-word"},
1554 {"M-cW", "vi-forward-change-word"},
1555 {"M-cF", "vi-backward-change-find"},
1556 {"M-cf", "vi-forward-change-find"},
1557 {"M-cT", "vi-backward-change-to"},
1558 {"M-ct", "vi-forward-change-to"},
1559 {"M-c;", "vi-change-refind"},
1560 {"M-c,", "vi-change-invert-refind"},
1561 {"M-ch", "vi-backward-change-char"},
1562 {"M-c^H", "vi-backward-change-char"},
1563 {"M-c^?", "vi-backward-change-char"},
1564 {"M-cl", "vi-forward-change-char"},
1565 {"M-c ", "vi-forward-change-char"},
1566 {"M-c^", "vi-change-to-bol"},
1567 {"M-c0", "vi-change-to-bol"},
1568 {"M-c$", "vi-change-rest-of-line"},
1569 {"M-c|", "vi-change-to-column"},
1570 {"M-c%", "vi-change-to-parenthesis"},
1571 {"M-dh", "backward-delete-char"},
1572 {"M-d^H", "backward-delete-char"},
1573 {"M-d^?", "backward-delete-char"},
1574 {"M-dl", "forward-delete-char"},
1575 {"M-d ", "forward-delete-char"},
1576 {"M-dd", "delete-line"},
1577 {"M-db", "backward-delete-word"},
1578 {"M-dB", "backward-delete-word"},
1579 {"M-de", "forward-delete-word"},
1580 {"M-dE", "forward-delete-word"},
1581 {"M-dw", "forward-delete-word"},
1582 {"M-dW", "forward-delete-word"},
1583 {"M-dF", "backward-delete-find"},
1584 {"M-df", "forward-delete-find"},
1585 {"M-dT", "backward-delete-to"},
1586 {"M-dt", "forward-delete-to"},
1587 {"M-d;", "delete-refind"},
1588 {"M-d,", "delete-invert-refind"},
1589 {"M-d^", "backward-kill-line"},
1590 {"M-d0", "backward-kill-line"},
1591 {"M-d$", "kill-line"},
1592 {"M-D", "kill-line"},
1593 {"M-d|", "delete-to-column"},
1594 {"M-d%", "delete-to-parenthesis"},
1595 {"M-e", "forward-word"},
1596 {"M-E", "forward-word"},
1597 {"M-f", "forward-find-char"},
1598 {"M-F", "backward-find-char"},
1599 {"M--", "up-history"},
1600 {"M-h", "cursor-left"},
1601 {"M-H", "beginning-of-history"},
1602 {"M-i", "vi-insert"},
1603 {"M-I", "vi-insert-at-bol"},
1604 {"M-j", "down-history"},
1605 {"M-J", "history-search-forward"},
1606 {"M-k", "up-history"},
1607 {"M-K", "history-search-backward"},
1608 {"M-l", "cursor-right"},
1609 {"M-L", "end-of-history"},
1610 {"M-n", "history-re-search-forward"},
1611 {"M-N", "history-re-search-backward"},
1612 {"M-p", "append-yank"},
1613 {"M-P", "yank"},
1614 {"M-r", "vi-replace-char"},
1615 {"M-R", "vi-overwrite"},
1616 {"M-s", "vi-forward-change-char"},
1617 {"M-S", "vi-change-line"},
1618 {"M-t", "forward-to-char"},
1619 {"M-T", "backward-to-char"},
1620 {"M-u", "vi-undo"},
1621 {"M-w", "forward-to-word"},
1622 {"M-W", "forward-to-word"},
1623 {"M-x", "forward-delete-char"},
1624 {"M-X", "backward-delete-char"},
1625 {"M-yh", "backward-copy-char"},
1626 {"M-y^H", "backward-copy-char"},
1627 {"M-y^?", "backward-copy-char"},
1628 {"M-yl", "forward-copy-char"},
1629 {"M-y ", "forward-copy-char"},
1630 {"M-ye", "forward-copy-word"},
1631 {"M-yE", "forward-copy-word"},
1632 {"M-yw", "forward-copy-word"},
1633 {"M-yW", "forward-copy-word"},
1634 {"M-yb", "backward-copy-word"},
1635 {"M-yB", "backward-copy-word"},
1636 {"M-yf", "forward-copy-find"},
1637 {"M-yF", "backward-copy-find"},
1638 {"M-yt", "forward-copy-to"},
1639 {"M-yT", "backward-copy-to"},
1640 {"M-y;", "copy-refind"},
1641 {"M-y,", "copy-invert-refind"},
1642 {"M-y^", "copy-to-bol"},
1643 {"M-y0", "copy-to-bol"},
1644 {"M-y$", "copy-rest-of-line"},
1645 {"M-yy", "copy-line"},
1646 {"M-Y", "copy-line"},
1647 {"M-y|", "copy-to-column"},
1648 {"M-y%", "copy-to-parenthesis"},
1649 {"M-^E", "emacs-mode"},
1650 {"M-^H", "cursor-left"},
1651 {"M-^?", "cursor-left"},
1652 {"M-^L", "clear-screen"},
1653 {"M-^N", "down-history"},
1654 {"M-^P", "up-history"},
1655 {"M-^R", "redisplay"},
1656 {"M-^D", "list-or-eof"},
1657 {"M-\r", "newline"},
1658 {"M-\t", "complete-word"},
1659 {"M-\n", "newline"},
1660 #ifndef HIDE_FILE_SYSTEM
1661 {"M-^X^R", "read-init-files"},
1662 #endif
1663 {"M-^Xh", "list-history"},
1664 {"M-^XH", "list-history"},
1665 {"down", "down-history"},
1666 {"up", "up-history"},
1667 {"left", "cursor-left"},
1668 {"right", "cursor-right"},
1671 /*.......................................................................
1672 * Create a new GetLine object.
1674 * Input:
1675 * linelen size_t The maximum line length to allow for.
1676 * histlen size_t The number of bytes to allocate for recording
1677 * a circular buffer of history lines.
1678 * Output:
1679 * return GetLine * The new object, or NULL on error.
1681 GetLine *new_GetLine(size_t linelen, size_t histlen)
1683 GetLine *gl; /* The object to be returned */
1684 int i;
1686 * Check the arguments.
1688 if(linelen < 10) {
1689 errno = ENOMEM;
1690 return NULL;
1693 * Allocate the container.
1695 gl = (GetLine *) malloc(sizeof(GetLine));
1696 if(!gl) {
1697 errno = ENOMEM;
1698 return NULL;
1701 * Before attempting any operation that might fail, initialize the
1702 * container at least up to the point at which it can safely be passed
1703 * to del_GetLine().
1705 gl->err = NULL;
1706 gl->glh = NULL;
1707 gl->cpl = NULL;
1708 #ifndef HIDE_FILE_SYSTEM
1709 gl->cplfn.fn = cpl_file_completions;
1710 #else
1711 gl->cplfn.fn = gl_no_completions;
1712 #endif
1713 gl->cplfn.data = NULL;
1714 #ifndef WITHOUT_FILE_SYSTEM
1715 gl->ef = NULL;
1716 #endif
1717 gl->capmem = NULL;
1718 gl->cq = NULL;
1719 gl->input_fd = -1;
1720 gl->output_fd = -1;
1721 gl->input_fp = NULL;
1722 gl->output_fp = NULL;
1723 gl->file_fp = NULL;
1724 gl->term = NULL;
1725 gl->is_term = 0;
1726 gl->flush_fn = gl_flush_terminal;
1727 gl->io_mode = GL_NORMAL_MODE;
1728 gl->raw_mode = 0;
1729 gl->pending_io = GLP_WRITE; /* We will start by writing the prompt */
1730 gl_clear_status(gl);
1731 gl->linelen = linelen;
1732 gl->line = NULL;
1733 gl->cutbuf = NULL;
1734 gl->prompt = NULL;
1735 gl->prompt_len = 0;
1736 gl->prompt_changed = 0;
1737 gl->prompt_style = GL_LITERAL_PROMPT;
1738 gl->cpl_mem = NULL;
1739 gl->ext_act_mem = NULL;
1740 gl->sig_mem = NULL;
1741 gl->sigs = NULL;
1742 gl->signals_masked = 0;
1743 gl->signals_overriden = 0;
1744 sigemptyset(&gl->all_signal_set);
1745 sigemptyset(&gl->old_signal_set);
1746 sigemptyset(&gl->use_signal_set);
1747 gl->bindings = NULL;
1748 gl->ntotal = 0;
1749 gl->buff_curpos = 0;
1750 gl->term_curpos = 0;
1751 gl->term_len = 0;
1752 gl->buff_mark = 0;
1753 gl->insert_curpos = 0;
1754 gl->insert = 1;
1755 gl->number = -1;
1756 gl->endline = 1;
1757 gl->displayed = 0;
1758 gl->redisplay = 0;
1759 gl->postpone = 0;
1760 gl->keybuf[0]='\0';
1761 gl->nbuf = 0;
1762 gl->nread = 0;
1763 gl->current_action.fn = 0;
1764 gl->current_action.data = NULL;
1765 gl->current_count = 0;
1766 gl->preload_id = 0;
1767 gl->preload_history = 0;
1768 gl->keyseq_count = 0;
1769 gl->last_search = -1;
1770 gl->editor = GL_EMACS_MODE;
1771 gl->silence_bell = 0;
1772 gl->automatic_history = 1;
1773 gl->vi.undo.line = NULL;
1774 gl->vi.undo.buff_curpos = 0;
1775 gl->vi.undo.ntotal = 0;
1776 gl->vi.undo.saved = 0;
1777 gl->vi.repeat.action.fn = 0;
1778 gl->vi.repeat.action.data = 0;
1779 gl->vi.repeat.count = 0;
1780 gl->vi.repeat.input_curpos = 0;
1781 gl->vi.repeat.command_curpos = 0;
1782 gl->vi.repeat.input_char = '\0';
1783 gl->vi.repeat.saved = 0;
1784 gl->vi.repeat.active = 0;
1785 gl->vi.command = 0;
1786 gl->vi.find_forward = 0;
1787 gl->vi.find_onto = 0;
1788 gl->vi.find_char = '\0';
1789 gl->left = NULL;
1790 gl->right = NULL;
1791 gl->up = NULL;
1792 gl->down = NULL;
1793 gl->home = NULL;
1794 gl->bol = 0;
1795 gl->clear_eol = NULL;
1796 gl->clear_eod = NULL;
1797 gl->u_arrow = NULL;
1798 gl->d_arrow = NULL;
1799 gl->l_arrow = NULL;
1800 gl->r_arrow = NULL;
1801 gl->sound_bell = NULL;
1802 gl->bold = NULL;
1803 gl->underline = NULL;
1804 gl->standout = NULL;
1805 gl->dim = NULL;
1806 gl->reverse = NULL;
1807 gl->blink = NULL;
1808 gl->text_attr_off = NULL;
1809 gl->nline = 0;
1810 gl->ncolumn = 0;
1811 #ifdef USE_TERMINFO
1812 gl->left_n = NULL;
1813 gl->right_n = NULL;
1814 #elif defined(USE_TERMCAP)
1815 gl->tgetent_buf = NULL;
1816 gl->tgetstr_buf = NULL;
1817 #endif
1818 gl->app_file = NULL;
1819 gl->user_file = NULL;
1820 gl->configured = 0;
1821 gl->echo = 1;
1822 gl->last_signal = -1;
1823 #ifdef HAVE_SELECT
1824 gl->fd_node_mem = NULL;
1825 gl->fd_nodes = NULL;
1826 FD_ZERO(&gl->rfds);
1827 FD_ZERO(&gl->wfds);
1828 FD_ZERO(&gl->ufds);
1829 gl->max_fd = 0;
1830 gl->timer.dt.tv_sec = 0;
1831 gl->timer.dt.tv_usec = 0;
1832 gl->timer.fn = 0;
1833 gl->timer.data = NULL;
1834 #endif
1836 * Allocate an error reporting buffer.
1838 gl->err = _new_ErrMsg();
1839 if(!gl->err)
1840 return del_GetLine(gl);
1842 * Allocate the history buffer.
1844 gl->glh = _new_GlHistory(histlen);
1845 if(!gl->glh)
1846 return del_GetLine(gl);
1848 * Allocate the resource object for file-completion.
1850 gl->cpl = new_WordCompletion();
1851 if(!gl->cpl)
1852 return del_GetLine(gl);
1854 * Allocate the resource object for file-completion.
1856 #ifndef WITHOUT_FILE_SYSTEM
1857 gl->ef = new_ExpandFile();
1858 if(!gl->ef)
1859 return del_GetLine(gl);
1860 #endif
1862 * Allocate a string-segment memory allocator for use in storing terminal
1863 * capablity strings.
1865 gl->capmem = _new_StringGroup(CAPMEM_SEGMENT_SIZE);
1866 if(!gl->capmem)
1867 return del_GetLine(gl);
1869 * Allocate the character queue that is used to buffer terminal output.
1871 gl->cq = _new_GlCharQueue();
1872 if(!gl->cq)
1873 return del_GetLine(gl);
1875 * Allocate a line buffer, leaving 2 extra characters for the terminating
1876 * '\n' and '\0' characters
1878 gl->line = (char *) malloc(linelen + 2);
1879 if(!gl->line) {
1880 errno = ENOMEM;
1881 return del_GetLine(gl);
1884 * Start with an empty input line.
1886 gl_truncate_buffer(gl, 0);
1888 * Allocate a cut buffer.
1890 gl->cutbuf = (char *) malloc(linelen + 2);
1891 if(!gl->cutbuf) {
1892 errno = ENOMEM;
1893 return del_GetLine(gl);
1895 gl->cutbuf[0] = '\0';
1897 * Allocate an initial empty prompt.
1899 _gl_replace_prompt(gl, NULL);
1900 if(!gl->prompt) {
1901 errno = ENOMEM;
1902 return del_GetLine(gl);
1905 * Allocate a vi undo buffer.
1907 gl->vi.undo.line = (char *) malloc(linelen + 2);
1908 if(!gl->vi.undo.line) {
1909 errno = ENOMEM;
1910 return del_GetLine(gl);
1912 gl->vi.undo.line[0] = '\0';
1914 * Allocate a freelist from which to allocate nodes for the list
1915 * of completion functions.
1917 gl->cpl_mem = _new_FreeList(sizeof(GlCplCallback), GL_CPL_FREELIST_BLOCKING);
1918 if(!gl->cpl_mem)
1919 return del_GetLine(gl);
1921 * Allocate a freelist from which to allocate nodes for the list
1922 * of external action functions.
1924 gl->ext_act_mem = _new_FreeList(sizeof(GlExternalAction),
1925 GL_EXT_ACT_FREELIST_BLOCKING);
1926 if(!gl->ext_act_mem)
1927 return del_GetLine(gl);
1929 * Allocate a freelist from which to allocate nodes for the list
1930 * of signals.
1932 gl->sig_mem = _new_FreeList(sizeof(GlSignalNode), GLS_FREELIST_BLOCKING);
1933 if(!gl->sig_mem)
1934 return del_GetLine(gl);
1936 * Install initial dispositions for the default list of signals that
1937 * gl_get_line() traps.
1939 for(i=0; i<sizeof(gl_signal_list)/sizeof(gl_signal_list[0]); i++) {
1940 const struct GlDefSignal *sig = gl_signal_list + i;
1941 if(_gl_trap_signal(gl, sig->signo, sig->flags, sig->after,
1942 sig->errno_value))
1943 return del_GetLine(gl);
1946 * Allocate an empty table of key bindings.
1948 gl->bindings = _new_KeyTab();
1949 if(!gl->bindings)
1950 return del_GetLine(gl);
1952 * Define the available actions that can be bound to key sequences.
1954 for(i=0; i<sizeof(gl_actions)/sizeof(gl_actions[0]); i++) {
1955 if(_kt_set_action(gl->bindings, gl_actions[i].name, gl_actions[i].fn, NULL))
1956 return del_GetLine(gl);
1959 * Set up the default bindings.
1961 if(gl_change_editor(gl, gl->editor))
1962 return del_GetLine(gl);
1964 * Allocate termcap buffers.
1966 #ifdef USE_TERMCAP
1967 gl->tgetent_buf = (char *) malloc(TERMCAP_BUF_SIZE);
1968 gl->tgetstr_buf = (char *) malloc(TERMCAP_BUF_SIZE);
1969 if(!gl->tgetent_buf || !gl->tgetstr_buf) {
1970 errno = ENOMEM;
1971 return del_GetLine(gl);
1973 #endif
1975 * Set up for I/O assuming stdin and stdout.
1977 if(_gl_change_terminal(gl, stdin, stdout, getenv("TERM")))
1978 return del_GetLine(gl);
1980 * Create a freelist for use in allocating GlFdNode list nodes.
1982 #ifdef HAVE_SELECT
1983 gl->fd_node_mem = _new_FreeList(sizeof(GlFdNode), GLFD_FREELIST_BLOCKING);
1984 if(!gl->fd_node_mem)
1985 return del_GetLine(gl);
1986 #endif
1988 * We are done for now.
1990 return gl;
1993 /*.......................................................................
1994 * Delete a GetLine object.
1996 * Input:
1997 * gl GetLine * The object to be deleted.
1998 * Output:
1999 * return GetLine * The deleted object (always NULL).
2001 GetLine *del_GetLine(GetLine *gl)
2003 if(gl) {
2005 * If the terminal is in raw server mode, reset it.
2007 _gl_normal_io(gl);
2009 * Deallocate all objects contained by gl.
2011 gl->err = _del_ErrMsg(gl->err);
2012 gl->glh = _del_GlHistory(gl->glh);
2013 gl->cpl = del_WordCompletion(gl->cpl);
2014 #ifndef WITHOUT_FILE_SYSTEM
2015 gl->ef = del_ExpandFile(gl->ef);
2016 #endif
2017 gl->capmem = _del_StringGroup(gl->capmem);
2018 gl->cq = _del_GlCharQueue(gl->cq);
2019 if(gl->file_fp)
2020 fclose(gl->file_fp);
2021 free(gl->term);
2022 free(gl->line);
2023 free(gl->cutbuf);
2024 free(gl->prompt);
2025 gl->cpl_mem = _del_FreeList(gl->cpl_mem, 1);
2026 gl->ext_act_mem = _del_FreeList(gl->ext_act_mem, 1);
2027 gl->sig_mem = _del_FreeList(gl->sig_mem, 1);
2028 gl->sigs = NULL; /* Already freed by freeing sig_mem */
2029 gl->bindings = _del_KeyTab(gl->bindings);
2030 free(gl->vi.undo.line);
2031 #ifdef USE_TERMCAP
2032 free(gl->tgetent_buf);
2033 free(gl->tgetstr_buf);
2034 #endif
2035 free(gl->app_file);
2036 free(gl->user_file);
2037 #ifdef HAVE_SELECT
2038 gl->fd_node_mem = _del_FreeList(gl->fd_node_mem, 1);
2039 gl->fd_nodes = NULL; /* Already freed by freeing gl->fd_node_mem */
2040 #endif
2042 * Delete the now empty container.
2044 free(gl);
2046 return NULL;
2049 /*.......................................................................
2050 * Bind a control or meta character to an action.
2052 * Input:
2053 * gl GetLine * The resource object of this program.
2054 * binder KtBinder The source of the binding.
2055 * c char The control or meta character.
2056 * If this is '\0', the call is ignored.
2057 * action const char * The action name to bind the key to.
2058 * Output:
2059 * return int 0 - OK.
2060 * 1 - Error.
2062 static int gl_bind_control_char(GetLine *gl, KtBinder binder, char c,
2063 const char *action)
2065 char keyseq[2];
2067 * Quietly reject binding to the NUL control character, since this
2068 * is an ambiguous prefix of all bindings.
2070 if(c == '\0')
2071 return 0;
2073 * Making sure not to bind characters which aren't either control or
2074 * meta characters.
2076 if(IS_CTRL_CHAR(c) || IS_META_CHAR(c)) {
2077 keyseq[0] = c;
2078 keyseq[1] = '\0';
2079 } else {
2080 return 0;
2083 * Install the binding.
2085 if(_kt_set_keybinding(gl->bindings, binder, keyseq, action)) {
2086 _err_record_msg(gl->err, _kt_last_error(gl->bindings), END_ERR_MSG);
2087 return 1;
2089 return 0;
2092 /*.......................................................................
2093 * Read a line from the user.
2095 * Input:
2096 * gl GetLine * A resource object returned by new_GetLine().
2097 * prompt char * The prompt to prefix the line with.
2098 * start_line char * The initial contents of the input line, or NULL
2099 * if it should start out empty.
2100 * start_pos int If start_line isn't NULL, this specifies the
2101 * index of the character over which the cursor
2102 * should initially be positioned within the line.
2103 * If you just want it to follow the last character
2104 * of the line, send -1.
2105 * Output:
2106 * return char * An internal buffer containing the input line, or
2107 * NULL at the end of input. If the line fitted in
2108 * the buffer there will be a '\n' newline character
2109 * before the terminating '\0'. If it was truncated
2110 * there will be no newline character, and the remains
2111 * of the line should be retrieved via further calls
2112 * to this function.
2114 char *gl_get_line(GetLine *gl, const char *prompt,
2115 const char *start_line, int start_pos)
2117 char *retval; /* The return value of _gl_get_line() */
2119 * Check the arguments.
2121 if(!gl) {
2122 errno = EINVAL;
2123 return NULL;
2126 * Temporarily block all of the signals that we have been asked to trap.
2128 if(gl_mask_signals(gl, &gl->old_signal_set))
2129 return NULL;
2131 * Perform the command-line editing task.
2133 retval = _gl_get_line(gl, prompt, start_line, start_pos);
2135 * Restore the process signal mask to how it was when this function was
2136 * first called.
2138 gl_unmask_signals(gl, &gl->old_signal_set);
2139 return retval;
2143 /*.......................................................................
2144 * This is the main body of the public function gl_get_line().
2146 static char *_gl_get_line(GetLine *gl, const char *prompt,
2147 const char *start_line, int start_pos)
2149 int waserr = 0; /* True if an error occurs */
2151 * Assume that this call will successfully complete the input
2152 * line until proven otherwise.
2154 gl_clear_status(gl);
2156 * If this is the first call to this function since new_GetLine(),
2157 * complete any postponed configuration.
2159 if(!gl->configured) {
2160 (void) _gl_configure_getline(gl, NULL, NULL, TECLA_CONFIG_FILE);
2161 gl->configured = 1;
2164 * Before installing our signal handler functions, record the fact
2165 * that there are no pending signals.
2167 gl_pending_signal = -1;
2169 * Temporarily override the signal handlers of the calling program,
2170 * so that we can intercept signals that would leave the terminal
2171 * in a bad state.
2173 waserr = gl_override_signal_handlers(gl);
2175 * After recording the current terminal settings, switch the terminal
2176 * into raw input mode.
2178 waserr = waserr || _gl_raw_io(gl, 1);
2180 * Attempt to read the line. This will require more than one attempt if
2181 * either a current temporary input file is opened by gl_get_input_line()
2182 * or the end of a temporary input file is reached by gl_read_stream_line().
2184 while(!waserr) {
2186 * Read a line from a non-interactive stream?
2188 if(gl->file_fp || !gl->is_term) {
2189 if(gl_read_stream_line(gl)==0) {
2190 break;
2191 } else if(gl->file_fp) {
2192 gl_revert_input(gl);
2193 gl_record_status(gl, GLR_NEWLINE, 0);
2194 } else {
2195 waserr = 1;
2196 break;
2200 * Read from the terminal? Note that the above if() block may have
2201 * changed gl->file_fp, so it is necessary to retest it here, rather
2202 * than using an else statement.
2204 if(!gl->file_fp && gl->is_term) {
2205 if(gl_get_input_line(gl, prompt, start_line, start_pos))
2206 waserr = 1;
2207 else
2208 break;
2212 * If an error occurred, but gl->rtn_status is still set to
2213 * GLR_NEWLINE, change the status to GLR_ERROR. Otherwise
2214 * leave it at whatever specific value was assigned by the function
2215 * that aborted input. This means that only functions that trap
2216 * non-generic errors have to remember to update gl->rtn_status
2217 * themselves.
2219 if(waserr && gl->rtn_status == GLR_NEWLINE)
2220 gl_record_status(gl, GLR_ERROR, errno);
2222 * Restore terminal settings.
2224 if(gl->io_mode != GL_SERVER_MODE)
2225 _gl_normal_io(gl);
2227 * Restore the signal handlers.
2229 gl_restore_signal_handlers(gl);
2231 * If gl_get_line() gets aborted early, the errno value associated
2232 * with the event that caused this to happen is recorded in
2233 * gl->rtn_errno. Since errno may have been overwritten by cleanup
2234 * functions after this, restore its value to the value that it had
2235 * when the error condition occured, so that the caller can examine it
2236 * to find out what happened.
2238 errno = gl->rtn_errno;
2240 * Check the completion status to see how to return.
2242 switch(gl->rtn_status) {
2243 case GLR_NEWLINE: /* Success */
2244 return gl->line;
2245 case GLR_BLOCKED: /* These events abort the current input line, */
2246 case GLR_SIGNAL: /* when in normal blocking I/O mode, but only */
2247 case GLR_TIMEOUT: /* temporarily pause line editing when in */
2248 case GLR_FDABORT: /* non-blocking server I/O mode. */
2249 if(gl->io_mode != GL_SERVER_MODE)
2250 _gl_abandon_line(gl);
2251 return NULL;
2252 case GLR_ERROR: /* Unrecoverable errors abort the input line, */
2253 case GLR_EOF: /* regardless of the I/O mode. */
2254 default:
2255 _gl_abandon_line(gl);
2256 return NULL;
2260 /*.......................................................................
2261 * Read a single character from the user.
2263 * Input:
2264 * gl GetLine * A resource object returned by new_GetLine().
2265 * prompt char * The prompt to prefix the line with, or NULL if
2266 * no prompt is required.
2267 * defchar char The character to substitute if the
2268 * user simply hits return, or '\n' if you don't
2269 * need to substitute anything.
2270 * Output:
2271 * return int The character that was read, or EOF if the read
2272 * had to be aborted (in which case you can call
2273 * gl_return_status() to find out why).
2275 int gl_query_char(GetLine *gl, const char *prompt, char defchar)
2277 int retval; /* The return value of _gl_query_char() */
2279 * Check the arguments.
2281 if(!gl) {
2282 errno = EINVAL;
2283 return EOF;
2286 * Temporarily block all of the signals that we have been asked to trap.
2288 if(gl_mask_signals(gl, &gl->old_signal_set))
2289 return EOF;
2291 * Perform the character reading task.
2293 retval = _gl_query_char(gl, prompt, defchar);
2295 * Restore the process signal mask to how it was when this function was
2296 * first called.
2298 gl_unmask_signals(gl, &gl->old_signal_set);
2299 return retval;
2302 /*.......................................................................
2303 * This is the main body of the public function gl_query_char().
2305 static int _gl_query_char(GetLine *gl, const char *prompt, char defchar)
2307 int c = EOF; /* The character to be returned */
2308 int waserr = 0; /* True if an error occurs */
2310 * Assume that this call will successfully complete the input operation
2311 * until proven otherwise.
2313 gl_clear_status(gl);
2315 * If this is the first call to this function or gl_get_line(),
2316 * since new_GetLine(), complete any postponed configuration.
2318 if(!gl->configured) {
2319 (void) _gl_configure_getline(gl, NULL, NULL, TECLA_CONFIG_FILE);
2320 gl->configured = 1;
2323 * Before installing our signal handler functions, record the fact
2324 * that there are no pending signals.
2326 gl_pending_signal = -1;
2328 * Temporarily override the signal handlers of the calling program,
2329 * so that we can intercept signals that would leave the terminal
2330 * in a bad state.
2332 waserr = gl_override_signal_handlers(gl);
2334 * After recording the current terminal settings, switch the terminal
2335 * into raw input mode without redisplaying any partially entered
2336 * input line.
2338 waserr = waserr || _gl_raw_io(gl, 0);
2340 * Attempt to read the line. This will require more than one attempt if
2341 * either a current temporary input file is opened by gl_get_input_line()
2342 * or the end of a temporary input file is reached by gl_read_stream_line().
2344 while(!waserr) {
2346 * Read a line from a non-interactive stream?
2348 if(gl->file_fp || !gl->is_term) {
2349 c = gl_read_stream_char(gl);
2350 if(c != EOF) { /* Success? */
2351 if(c=='\n') c = defchar;
2352 break;
2353 } else if(gl->file_fp) { /* End of temporary input file? */
2354 gl_revert_input(gl);
2355 gl_record_status(gl, GLR_NEWLINE, 0);
2356 } else { /* An error? */
2357 waserr = 1;
2358 break;
2362 * Read from the terminal? Note that the above if() block may have
2363 * changed gl->file_fp, so it is necessary to retest it here, rather
2364 * than using an else statement.
2366 if(!gl->file_fp && gl->is_term) {
2367 c = gl_get_query_char(gl, prompt, defchar);
2368 if(c==EOF)
2369 waserr = 1;
2370 else
2371 break;
2375 * If an error occurred, but gl->rtn_status is still set to
2376 * GLR_NEWLINE, change the status to GLR_ERROR. Otherwise
2377 * leave it at whatever specific value was assigned by the function
2378 * that aborted input. This means that only functions that trap
2379 * non-generic errors have to remember to update gl->rtn_status
2380 * themselves.
2382 if(waserr && gl->rtn_status == GLR_NEWLINE)
2383 gl_record_status(gl, GLR_ERROR, errno);
2385 * Restore terminal settings.
2387 if(gl->io_mode != GL_SERVER_MODE)
2388 _gl_normal_io(gl);
2390 * Restore the signal handlers.
2392 gl_restore_signal_handlers(gl);
2394 * If this function gets aborted early, the errno value associated
2395 * with the event that caused this to happen is recorded in
2396 * gl->rtn_errno. Since errno may have been overwritten by cleanup
2397 * functions after this, restore its value to the value that it had
2398 * when the error condition occured, so that the caller can examine it
2399 * to find out what happened.
2401 errno = gl->rtn_errno;
2403 * Error conditions are signalled to the caller, by setting the returned
2404 * character to EOF.
2406 if(gl->rtn_status != GLR_NEWLINE)
2407 c = EOF;
2409 * In this mode, every character that is read is a completed
2410 * transaction, just like reading a completed input line, so prepare
2411 * for the next input line or character.
2413 _gl_abandon_line(gl);
2415 * Return the acquired character.
2417 return c;
2420 /*.......................................................................
2421 * Record of the signal handlers of the calling program, so that they
2422 * can be restored later.
2424 * Input:
2425 * gl GetLine * The resource object of this library.
2426 * Output:
2427 * return int 0 - OK.
2428 * 1 - Error.
2430 static int gl_override_signal_handlers(GetLine *gl)
2432 GlSignalNode *sig; /* A node in the list of signals to be caught */
2434 * Set up our signal handler.
2436 SigAction act;
2437 act.sa_handler = gl_signal_handler;
2438 memcpy(&act.sa_mask, &gl->all_signal_set, sizeof(sigset_t));
2439 act.sa_flags = 0;
2441 * Get the subset of the signals that we are supposed to trap that
2442 * should actually be trapped.
2444 sigemptyset(&gl->use_signal_set);
2445 for(sig=gl->sigs; sig; sig=sig->next) {
2447 * Trap this signal? If it is blocked by the calling program and we
2448 * haven't been told to unblock it, don't arrange to trap this signal.
2450 if(sig->flags & GLS_UNBLOCK_SIG ||
2451 !sigismember(&gl->old_signal_set, sig->signo)) {
2452 if(sigaddset(&gl->use_signal_set, sig->signo) == -1) {
2453 _err_record_msg(gl->err, "sigaddset error", END_ERR_MSG);
2454 return 1;
2459 * Override the actions of the signals that we are trapping.
2461 for(sig=gl->sigs; sig; sig=sig->next) {
2462 if(sigismember(&gl->use_signal_set, sig->signo)) {
2463 sigdelset(&act.sa_mask, sig->signo);
2464 if(sigaction(sig->signo, &act, &sig->original)) {
2465 _err_record_msg(gl->err, "sigaction error", END_ERR_MSG);
2466 return 1;
2468 sigaddset(&act.sa_mask, sig->signo);
2472 * Record the fact that the application's signal handlers have now
2473 * been overriden.
2475 gl->signals_overriden = 1;
2477 * Just in case a SIGWINCH signal was sent to the process while our
2478 * SIGWINCH signal handler wasn't in place, check to see if the terminal
2479 * size needs updating.
2481 if(_gl_update_size(gl))
2482 return 1;
2483 return 0;
2486 /*.......................................................................
2487 * Restore the signal handlers of the calling program.
2489 * Input:
2490 * gl GetLine * The resource object of this library.
2491 * Output:
2492 * return int 0 - OK.
2493 * 1 - Error.
2495 static int gl_restore_signal_handlers(GetLine *gl)
2497 GlSignalNode *sig; /* A node in the list of signals to be caught */
2499 * Restore application signal handlers that were overriden
2500 * by gl_override_signal_handlers().
2502 for(sig=gl->sigs; sig; sig=sig->next) {
2503 if(sigismember(&gl->use_signal_set, sig->signo) &&
2504 sigaction(sig->signo, &sig->original, NULL)) {
2505 _err_record_msg(gl->err, "sigaction error", END_ERR_MSG);
2506 return 1;
2510 * Record the fact that the application's signal handlers have now
2511 * been restored.
2513 gl->signals_overriden = 0;
2514 return 0;
2517 /*.......................................................................
2518 * This signal handler simply records the fact that a given signal was
2519 * caught in the file-scope gl_pending_signal variable.
2521 static void gl_signal_handler(int signo)
2523 gl_pending_signal = signo;
2524 siglongjmp(gl_setjmp_buffer, 1);
2527 /*.......................................................................
2528 * Switch the terminal into raw mode after storing the previous terminal
2529 * settings in gl->attributes.
2531 * Input:
2532 * gl GetLine * The resource object of this program.
2533 * Output:
2534 * return int 0 - OK.
2535 * 1 - Error.
2537 static int gl_raw_terminal_mode(GetLine *gl)
2539 Termios newattr; /* The new terminal attributes */
2541 * If the terminal is already in raw mode, do nothing.
2543 if(gl->raw_mode)
2544 return 0;
2546 * Record the current terminal attributes.
2548 if(tcgetattr(gl->input_fd, &gl->oldattr)) {
2549 _err_record_msg(gl->err, "tcgetattr error", END_ERR_MSG);
2550 return 1;
2553 * This function shouldn't do anything but record the current terminal
2554 * attritubes if editing has been disabled.
2556 if(gl->editor == GL_NO_EDITOR)
2557 return 0;
2559 * Modify the existing attributes.
2561 newattr = gl->oldattr;
2563 * Turn off local echo, canonical input mode and extended input processing.
2565 newattr.c_lflag &= ~(ECHO | ICANON | IEXTEN);
2567 * Don't translate carriage return to newline, turn off input parity
2568 * checking, don't strip off 8th bit, turn off output flow control.
2570 newattr.c_iflag &= ~(ICRNL | INPCK | ISTRIP);
2572 * Clear size bits, turn off parity checking, and allow 8-bit characters.
2574 newattr.c_cflag &= ~(CSIZE | PARENB);
2575 newattr.c_cflag |= CS8;
2577 * Turn off output processing.
2579 newattr.c_oflag &= ~(OPOST);
2581 * Request one byte at a time, without waiting.
2583 newattr.c_cc[VMIN] = gl->io_mode==GL_SERVER_MODE ? 0:1;
2584 newattr.c_cc[VTIME] = 0;
2586 * Install the new terminal modes.
2588 while(tcsetattr(gl->input_fd, TCSADRAIN, &newattr)) {
2589 if(errno != EINTR) {
2590 _err_record_msg(gl->err, "tcsetattr error", END_ERR_MSG);
2591 return 1;
2595 * Record the new terminal mode.
2597 gl->raw_mode = 1;
2598 return 0;
2601 /*.......................................................................
2602 * Restore the terminal attributes recorded in gl->oldattr.
2604 * Input:
2605 * gl GetLine * The resource object of this library.
2606 * Output:
2607 * return int 0 - OK.
2608 * 1 - Error.
2610 static int gl_restore_terminal_attributes(GetLine *gl)
2612 int waserr = 0;
2614 * If not in raw mode, do nothing.
2616 if(!gl->raw_mode)
2617 return 0;
2619 * Before changing the terminal attributes, make sure that all output
2620 * has been passed to the terminal.
2622 if(gl_flush_output(gl))
2623 waserr = 1;
2625 * Reset the terminal attributes to the values that they had on
2626 * entry to gl_get_line().
2628 while(tcsetattr(gl->input_fd, TCSADRAIN, &gl->oldattr)) {
2629 if(errno != EINTR) {
2630 _err_record_msg(gl->err, "tcsetattr error", END_ERR_MSG);
2631 waserr = 1;
2632 break;
2636 * Record the new terminal mode.
2638 gl->raw_mode = 0;
2639 return waserr;
2642 /*.......................................................................
2643 * Switch the terminal file descriptor to use non-blocking I/O.
2645 * Input:
2646 * gl GetLine * The resource object of gl_get_line().
2647 * fd int The file descriptor to make non-blocking.
2649 static int gl_nonblocking_io(GetLine *gl, int fd)
2651 int fcntl_flags; /* The new file-descriptor control flags */
2653 * Is non-blocking I/O supported on this system? Note that even
2654 * without non-blocking I/O, the terminal will probably still act as
2655 * though it was non-blocking, because we also set the terminal
2656 * attributes to return immediately if no input is available and we
2657 * use select() to wait to be able to write. If select() also isn't
2658 * available, then input will probably remain fine, but output could
2659 * block, depending on the behaviour of the terminal driver.
2661 #if defined(NON_BLOCKING_FLAG)
2663 * Query the current file-control flags, and add the
2664 * non-blocking I/O flag.
2666 fcntl_flags = fcntl(fd, F_GETFL) | NON_BLOCKING_FLAG;
2668 * Install the new control flags.
2670 if(fcntl(fd, F_SETFL, fcntl_flags) == -1) {
2671 _err_record_msg(gl->err, "fcntl error", END_ERR_MSG);
2672 return 1;
2674 #endif
2675 return 0;
2678 /*.......................................................................
2679 * Switch to blocking terminal I/O.
2681 * Input:
2682 * gl GetLine * The resource object of gl_get_line().
2683 * fd int The file descriptor to make blocking.
2685 static int gl_blocking_io(GetLine *gl, int fd)
2687 int fcntl_flags; /* The new file-descriptor control flags */
2689 * Is non-blocking I/O implemented on this system?
2691 #if defined(NON_BLOCKING_FLAG)
2693 * Query the current file control flags and remove the non-blocking
2694 * I/O flag.
2696 fcntl_flags = fcntl(fd, F_GETFL) & ~NON_BLOCKING_FLAG;
2698 * Install the modified control flags.
2700 if(fcntl(fd, F_SETFL, fcntl_flags) == -1) {
2701 _err_record_msg(gl->err, "fcntl error", END_ERR_MSG);
2702 return 1;
2704 #endif
2705 return 0;
2708 /*.......................................................................
2709 * Read a new input line from the user.
2711 * Input:
2712 * gl GetLine * The resource object of this library.
2713 * prompt char * The prompt to prefix the line with, or NULL to
2714 * use the same prompt that was used by the previous
2715 * line.
2716 * start_line char * The initial contents of the input line, or NULL
2717 * if it should start out empty.
2718 * start_pos int If start_line isn't NULL, this specifies the
2719 * index of the character over which the cursor
2720 * should initially be positioned within the line.
2721 * If you just want it to follow the last character
2722 * of the line, send -1.
2723 * Output:
2724 * return int 0 - OK.
2725 * 1 - Error.
2727 static int gl_get_input_line(GetLine *gl, const char *prompt,
2728 const char *start_line, int start_pos)
2730 char c; /* The character being read */
2732 * Flush any pending output to the terminal.
2734 if(_glq_char_count(gl->cq) > 0 && gl_flush_output(gl))
2735 return 1;
2737 * Are we starting a new line?
2739 if(gl->endline) {
2741 * Delete any incompletely enterred line.
2743 if(gl_erase_line(gl))
2744 return 1;
2746 * Display the new line to be edited.
2748 if(gl_present_line(gl, prompt, start_line, start_pos))
2749 return 1;
2752 * Read one character at a time.
2754 while(gl_read_terminal(gl, 1, &c) == 0) {
2756 * Increment the count of the number of key sequences entered.
2758 gl->keyseq_count++;
2760 * Interpret the character either as the start of a new key-sequence,
2761 * as a continuation of a repeat count, or as a printable character
2762 * to be added to the line.
2764 if(gl_interpret_char(gl, c))
2765 break;
2767 * If we just ran an action function which temporarily asked for
2768 * input to be taken from a file, abort this call.
2770 if(gl->file_fp)
2771 return 0;
2773 * Has the line been completed?
2775 if(gl->endline)
2776 return gl_line_ended(gl, c);
2779 * To get here, gl_read_terminal() must have returned non-zero. See
2780 * whether a signal was caught that requested that the current line
2781 * be returned.
2783 if(gl->endline)
2784 return gl_line_ended(gl, '\n');
2786 * If I/O blocked while attempting to get the latest character
2787 * of the key sequence, rewind the key buffer to allow interpretation of
2788 * the current key sequence to be restarted on the next call to this
2789 * function.
2791 if(gl->rtn_status == GLR_BLOCKED && gl->pending_io == GLP_READ)
2792 gl->nread = 0;
2793 return 1;
2796 /*.......................................................................
2797 * This is the private function of gl_query_char() that handles
2798 * prompting the user, reading a character from the terminal, and
2799 * displaying what the user entered.
2801 * Input:
2802 * gl GetLine * The resource object of this library.
2803 * prompt char * The prompt to prefix the line with.
2804 * defchar char The character to substitute if the
2805 * user simply hits return, or '\n' if you don't
2806 * need to substitute anything.
2807 * Output:
2808 * return int The character that was read, or EOF if something
2809 * prevented a character from being read.
2811 static int gl_get_query_char(GetLine *gl, const char *prompt, int defchar)
2813 char c; /* The character being read */
2814 int retval; /* The return value of this function */
2816 * Flush any pending output to the terminal.
2818 if(_glq_char_count(gl->cq) > 0 && gl_flush_output(gl))
2819 return EOF;
2821 * Delete any incompletely entered line.
2823 if(gl_erase_line(gl))
2824 return EOF;
2826 * Reset the line input parameters and display the prompt, if any.
2828 if(gl_present_line(gl, prompt, NULL, 0))
2829 return EOF;
2831 * Read one character.
2833 if(gl_read_terminal(gl, 1, &c) == 0) {
2835 * In this mode, count each character as being a new key-sequence.
2837 gl->keyseq_count++;
2839 * Delete the character that was read, from the key-press buffer.
2841 gl_discard_chars(gl, gl->nread);
2843 * Convert carriage returns to newlines.
2845 if(c == '\r')
2846 c = '\n';
2848 * If the user just hit return, subsitute the default character.
2850 if(c == '\n')
2851 c = defchar;
2853 * Display the entered character to the right of the prompt.
2855 if(c!='\n') {
2856 if(gl_end_of_line(gl, 1, NULL)==0)
2857 gl_print_char(gl, c, ' ');
2860 * Record the return character, and mark the call as successful.
2862 retval = c;
2863 gl_record_status(gl, GLR_NEWLINE, 0);
2865 * Was a signal caught whose disposition is to cause the current input
2866 * line to be returned? If so return a newline character.
2868 } else if(gl->endline) {
2869 retval = '\n';
2870 gl_record_status(gl, GLR_NEWLINE, 0);
2871 } else {
2872 retval = EOF;
2875 * Start a new line.
2877 if(gl_start_newline(gl, 1))
2878 return EOF;
2880 * Attempt to flush any pending output.
2882 (void) gl_flush_output(gl);
2884 * Return either the character that was read, or EOF if an error occurred.
2886 return retval;
2889 /*.......................................................................
2890 * Add a character to the line buffer at the current cursor position,
2891 * inserting or overwriting according the current mode.
2893 * Input:
2894 * gl GetLine * The resource object of this library.
2895 * c char The character to be added.
2896 * Output:
2897 * return int 0 - OK.
2898 * 1 - Insufficient room.
2900 static int gl_add_char_to_line(GetLine *gl, char c)
2903 * Keep a record of the current cursor position.
2905 int buff_curpos = gl->buff_curpos;
2906 int term_curpos = gl->term_curpos;
2908 * Work out the displayed width of the new character.
2910 int width = gl_displayed_char_width(gl, c, term_curpos);
2912 * If we are in insert mode, or at the end of the line,
2913 * check that we can accomodate a new character in the buffer.
2914 * If not, simply return, leaving it up to the calling program
2915 * to check for the absence of a newline character.
2917 if((gl->insert || buff_curpos >= gl->ntotal) && gl->ntotal >= gl->linelen)
2918 return 0;
2920 * Are we adding characters to the line (ie. inserting or appending)?
2922 if(gl->insert || buff_curpos >= gl->ntotal) {
2924 * If inserting, make room for the new character.
2926 if(buff_curpos < gl->ntotal)
2927 gl_make_gap_in_buffer(gl, buff_curpos, 1);
2929 * Copy the character into the buffer.
2931 gl_buffer_char(gl, c, buff_curpos);
2932 gl->buff_curpos++;
2934 * Redraw the line from the cursor position to the end of the line,
2935 * and move the cursor to just after the added character.
2937 if(gl_print_string(gl, gl->line + buff_curpos, '\0') ||
2938 gl_set_term_curpos(gl, term_curpos + width))
2939 return 1;
2941 * Are we overwriting an existing character?
2943 } else {
2945 * Get the width of the character being overwritten.
2947 int old_width = gl_displayed_char_width(gl, gl->line[buff_curpos],
2948 term_curpos);
2950 * Overwrite the character in the buffer.
2952 gl_buffer_char(gl, c, buff_curpos);
2954 * If we are replacing with a narrower character, we need to
2955 * redraw the terminal string to the end of the line, then
2956 * overwrite the trailing old_width - width characters
2957 * with spaces.
2959 if(old_width > width) {
2960 if(gl_print_string(gl, gl->line + buff_curpos, '\0'))
2961 return 1;
2963 * Clear to the end of the terminal.
2965 if(gl_truncate_display(gl))
2966 return 1;
2968 * Move the cursor to the end of the new character.
2970 if(gl_set_term_curpos(gl, term_curpos + width))
2971 return 1;
2972 gl->buff_curpos++;
2974 * If we are replacing with a wider character, then we will be
2975 * inserting new characters, and thus extending the line.
2977 } else if(width > old_width) {
2979 * Redraw the line from the cursor position to the end of the line,
2980 * and move the cursor to just after the added character.
2982 if(gl_print_string(gl, gl->line + buff_curpos, '\0') ||
2983 gl_set_term_curpos(gl, term_curpos + width))
2984 return 1;
2985 gl->buff_curpos++;
2987 * The original and replacement characters have the same width,
2988 * so simply overwrite.
2990 } else {
2992 * Copy the character into the buffer.
2994 gl_buffer_char(gl, c, buff_curpos);
2995 gl->buff_curpos++;
2997 * Overwrite the original character.
2999 if(gl_print_char(gl, c, gl->line[gl->buff_curpos]))
3000 return 1;
3003 return 0;
3006 /*.......................................................................
3007 * Insert/append a string to the line buffer and terminal at the current
3008 * cursor position.
3010 * Input:
3011 * gl GetLine * The resource object of this library.
3012 * s char * The string to be added.
3013 * Output:
3014 * return int 0 - OK.
3015 * 1 - Insufficient room.
3017 static int gl_add_string_to_line(GetLine *gl, const char *s)
3019 int buff_slen; /* The length of the string being added to line[] */
3020 int term_slen; /* The length of the string being written to the terminal */
3021 int buff_curpos; /* The original value of gl->buff_curpos */
3022 int term_curpos; /* The original value of gl->term_curpos */
3024 * Keep a record of the current cursor position.
3026 buff_curpos = gl->buff_curpos;
3027 term_curpos = gl->term_curpos;
3029 * How long is the string to be added?
3031 buff_slen = strlen(s);
3032 term_slen = gl_displayed_string_width(gl, s, buff_slen, term_curpos);
3034 * Check that we can accomodate the string in the buffer.
3035 * If not, simply return, leaving it up to the calling program
3036 * to check for the absence of a newline character.
3038 if(gl->ntotal + buff_slen > gl->linelen)
3039 return 0;
3041 * Move the characters that follow the cursor in the buffer by
3042 * buff_slen characters to the right.
3044 if(gl->ntotal > gl->buff_curpos)
3045 gl_make_gap_in_buffer(gl, gl->buff_curpos, buff_slen);
3047 * Copy the string into the buffer.
3049 gl_buffer_string(gl, s, buff_slen, gl->buff_curpos);
3050 gl->buff_curpos += buff_slen;
3052 * Write the modified part of the line to the terminal, then move
3053 * the terminal cursor to the end of the displayed input string.
3055 if(gl_print_string(gl, gl->line + buff_curpos, '\0') ||
3056 gl_set_term_curpos(gl, term_curpos + term_slen))
3057 return 1;
3058 return 0;
3061 /*.......................................................................
3062 * Read a single character from the terminal.
3064 * Input:
3065 * gl GetLine * The resource object of this library.
3066 * keep int If true, the returned character will be kept in
3067 * the input buffer, for potential replays. It should
3068 * subsequently be removed from the buffer when the
3069 * key sequence that it belongs to has been fully
3070 * processed, by calling gl_discard_chars().
3071 * Input/Output:
3072 * c char * The character that is read, is assigned to *c.
3073 * Output:
3074 * return int 0 - OK.
3075 * 1 - Either an I/O error occurred, or a signal was
3076 * caught who's disposition is to abort gl_get_line()
3077 * or to have gl_get_line() return the current line
3078 * as though the user had pressed return. In the
3079 * latter case gl->endline will be non-zero.
3081 static int gl_read_terminal(GetLine *gl, int keep, char *c)
3084 * Before waiting for a new character to be input, flush unwritten
3085 * characters to the terminal.
3087 if(gl_flush_output(gl))
3088 return 1;
3090 * Record the fact that we are about to read from the terminal.
3092 gl->pending_io = GLP_READ;
3094 * If there is already an unread character in the buffer,
3095 * return it.
3097 if(gl->nread < gl->nbuf) {
3098 *c = gl->keybuf[gl->nread];
3100 * Retain the character in the key buffer, but mark it as having been read?
3102 if(keep) {
3103 gl->nread++;
3105 * Completely remove the character from the key buffer?
3107 } else {
3108 memmove(gl->keybuf + gl->nread, gl->keybuf + gl->nread + 1,
3109 gl->nbuf - gl->nread - 1);
3111 return 0;
3114 * Make sure that there is space in the key buffer for one more character.
3115 * This should always be true if gl_interpret_char() is called for each
3116 * new character added, since it will clear the buffer once it has recognized
3117 * or rejected a key sequence.
3119 if(gl->nbuf + 1 > GL_KEY_MAX) {
3120 gl_print_info(gl, "gl_read_terminal: Buffer overflow avoided.",
3121 GL_END_INFO);
3122 errno = EIO;
3123 return 1;
3126 * Read one character from the terminal.
3128 switch(gl_read_input(gl, c)) {
3129 case GL_READ_OK:
3130 break;
3131 case GL_READ_BLOCKED:
3132 gl_record_status(gl, GLR_BLOCKED, BLOCKED_ERRNO);
3133 return 1;
3134 break;
3135 default:
3136 return 1;
3137 break;
3140 * Append the character to the key buffer?
3142 if(keep) {
3143 gl->keybuf[gl->nbuf] = *c;
3144 gl->nread = ++gl->nbuf;
3146 return 0;
3149 /*.......................................................................
3150 * Read one or more keypresses from the terminal of an input stream.
3152 * Input:
3153 * gl GetLine * The resource object of this module.
3154 * c char * The character that was read is assigned to *c.
3155 * Output:
3156 * return GlReadStatus The completion status of the read operation.
3158 static GlReadStatus gl_read_input(GetLine *gl, char *c)
3161 * We may have to repeat the read if window change signals are received.
3163 for(;;) {
3165 * Which file descriptor should we read from? Mark this volatile, so
3166 * that siglongjmp() can't clobber it.
3168 volatile int fd = gl->file_fp ? fileno(gl->file_fp) : gl->input_fd;
3170 * If the endline flag becomes set, don't wait for another character.
3172 if(gl->endline)
3173 return GL_READ_ERROR;
3175 * Since the code in this function can block, trap signals.
3177 if(sigsetjmp(gl_setjmp_buffer, 1)==0) {
3179 * Handle the different I/O modes.
3181 switch(gl->io_mode) {
3183 * In normal I/O mode, we call the event handler before attempting
3184 * to read, since read() blocks.
3186 case GL_NORMAL_MODE:
3187 if(gl_event_handler(gl, fd))
3188 return GL_READ_ERROR;
3189 return gl_read_unmasked(gl, fd, c); /* Read one character */
3190 break;
3192 * In non-blocking server I/O mode, we attempt to read a character,
3193 * and only if this fails, call the event handler to wait for a any
3194 * user-configured timeout and any other user-configured events. In
3195 * addition, we turn off the fcntl() non-blocking flag when reading
3196 * from the terminal, to work around a bug in Solaris. We can do this
3197 * without causing the read() to block, because when in non-blocking
3198 * server-I/O mode, gl_raw_io() sets the VMIN terminal attribute to 0,
3199 * which tells the terminal driver to return immediately if no
3200 * characters are available to be read.
3202 case GL_SERVER_MODE:
3204 GlReadStatus status; /* The return status */
3205 if(isatty(fd)) /* If we reading from a terminal, */
3206 gl_blocking_io(gl, fd); /* switch to blocking I/O */
3207 status = gl_read_unmasked(gl, fd, c); /* Try reading */
3208 if(status == GL_READ_BLOCKED) { /* Nothing readable yet */
3209 if(gl_event_handler(gl, fd)) /* Wait for input */
3210 status = GL_READ_ERROR;
3211 else
3212 status = gl_read_unmasked(gl, fd, c); /* Try reading again */
3214 gl_nonblocking_io(gl, fd); /* Restore non-blocking I/O */
3215 return status;
3217 break;
3221 * To get here, one of the signals that we are trapping must have
3222 * been received. Note that by using sigsetjmp() instead of setjmp()
3223 * the signal mask that was blocking these signals will have been
3224 * reinstated, so we can be sure that no more of these signals will
3225 * be received until we explicitly unblock them again.
3227 * First, if non-blocking I/O was temporarily disabled, reinstate it.
3229 if(gl->io_mode == GL_SERVER_MODE)
3230 gl_nonblocking_io(gl, fd);
3232 * Now respond to the signal that was caught.
3234 if(gl_check_caught_signal(gl))
3235 return GL_READ_ERROR;
3239 /*.......................................................................
3240 * This is a private function of gl_read_input(), which unblocks signals
3241 * temporarily while it reads a single character from the specified file
3242 * descriptor.
3244 * Input:
3245 * gl GetLine * The resource object of this module.
3246 * fd int The file descriptor to read from.
3247 * c char * The character that was read is assigned to *c.
3248 * Output:
3249 * return GlReadStatus The completion status of the read.
3251 static int gl_read_unmasked(GetLine *gl, int fd, char *c)
3253 int nread; /* The return value of read() */
3255 * Unblock the signals that we are trapping, while waiting for I/O.
3257 gl_catch_signals(gl);
3259 * Attempt to read one character from the terminal, restarting the read
3260 * if any signals that we aren't trapping, are received.
3262 do {
3263 errno = 0;
3264 nread = read(fd, c, 1);
3265 } while(nread < 0 && errno==EINTR);
3267 * Block all of the signals that we are trapping.
3269 gl_mask_signals(gl, NULL);
3271 * Check the completion status of the read.
3273 switch(nread) {
3274 case 1:
3275 return GL_READ_OK;
3276 case 0:
3277 return (isatty(fd) || errno != 0) ? GL_READ_BLOCKED : GL_READ_EOF;
3278 default:
3279 return GL_READ_ERROR;
3283 /*.......................................................................
3284 * Remove a specified number of characters from the start of the
3285 * key-press lookahead buffer, gl->keybuf[], and arrange for the next
3286 * read to start from the character at the start of the shifted buffer.
3288 * Input:
3289 * gl GetLine * The resource object of this module.
3290 * nused int The number of characters to discard from the start
3291 * of the buffer.
3293 static void gl_discard_chars(GetLine *gl, int nused)
3295 int nkeep = gl->nbuf - nused;
3296 if(nkeep > 0) {
3297 memmove(gl->keybuf, gl->keybuf + nused, nkeep);
3298 gl->nbuf = nkeep;
3299 gl->nread = 0;
3300 } else {
3301 gl->nbuf = gl->nread = 0;
3305 /*.......................................................................
3306 * This function is called to handle signals caught between calls to
3307 * sigsetjmp() and siglongjmp().
3309 * Input:
3310 * gl GetLine * The resource object of this library.
3311 * Output:
3312 * return int 0 - Signal handled internally.
3313 * 1 - Signal requires gl_get_line() to abort.
3315 static int gl_check_caught_signal(GetLine *gl)
3317 GlSignalNode *sig; /* The signal disposition */
3318 SigAction keep_action; /* The signal disposition of tecla signal handlers */
3319 unsigned flags; /* The signal processing flags to use */
3320 int signo; /* The signal to be handled */
3322 * Was no signal caught?
3324 if(gl_pending_signal == -1)
3325 return 0;
3327 * Get the signal to be handled.
3329 signo = gl_pending_signal;
3331 * Mark the signal as handled. Note that at this point, all of
3332 * the signals that we are trapping are blocked from delivery.
3334 gl_pending_signal = -1;
3336 * Record the signal that was caught, so that the user can query it later.
3338 gl->last_signal = signo;
3340 * In non-blocking server mode, the application is responsible for
3341 * responding to terminal signals, and we don't want gl_get_line()s
3342 * normal signal handling to clash with this, so whenever a signal
3343 * is caught, we arrange for gl_get_line() to abort and requeue the
3344 * signal while signals are still blocked. If the application
3345 * had the signal unblocked when gl_get_line() was called, the signal
3346 * will be delivered again as soon as gl_get_line() restores the
3347 * process signal mask, just before returning to the application.
3348 * Note that the caller of this function should set gl->pending_io
3349 * to the appropriate choice of GLP_READ and GLP_WRITE, before returning.
3351 if(gl->io_mode==GL_SERVER_MODE) {
3352 gl_record_status(gl, GLR_SIGNAL, EINTR);
3353 raise(signo);
3354 return 1;
3357 * Lookup the requested disposition of this signal.
3359 for(sig=gl->sigs; sig && sig->signo != signo; sig=sig->next)
3361 if(!sig)
3362 return 0;
3364 * Get the signal response flags for this signal.
3366 flags = sig->flags;
3368 * Did we receive a terminal size signal?
3370 #ifdef SIGWINCH
3371 if(signo == SIGWINCH && _gl_update_size(gl))
3372 return 1;
3373 #endif
3375 * Start a fresh line?
3377 if(flags & GLS_RESTORE_LINE) {
3378 if(gl_start_newline(gl, 0))
3379 return 1;
3382 * Restore terminal settings to how they were before gl_get_line() was
3383 * called?
3385 if(flags & GLS_RESTORE_TTY)
3386 gl_restore_terminal_attributes(gl);
3388 * Restore signal handlers to how they were before gl_get_line() was
3389 * called? If this hasn't been requested, only reinstate the signal
3390 * handler of the signal that we are handling.
3392 if(flags & GLS_RESTORE_SIG) {
3393 gl_restore_signal_handlers(gl);
3394 gl_unmask_signals(gl, &gl->old_signal_set);
3395 } else {
3396 (void) sigaction(sig->signo, &sig->original, &keep_action);
3397 (void) sigprocmask(SIG_UNBLOCK, &sig->proc_mask, NULL);
3400 * Forward the signal to the application's signal handler.
3402 if(!(flags & GLS_DONT_FORWARD))
3403 raise(signo);
3405 * Reinstate our signal handlers.
3407 if(flags & GLS_RESTORE_SIG) {
3408 gl_mask_signals(gl, NULL);
3409 gl_override_signal_handlers(gl);
3410 } else {
3411 (void) sigaction(sig->signo, &keep_action, NULL);
3412 (void) sigprocmask(SIG_BLOCK, &sig->proc_mask, NULL);
3415 * Do we need to reinstate our terminal settings?
3417 if(flags & GLS_RESTORE_TTY)
3418 gl_raw_terminal_mode(gl);
3420 * Redraw the line?
3422 if(flags & GLS_REDRAW_LINE)
3423 gl_queue_redisplay(gl);
3425 * What next?
3427 switch(sig->after) {
3428 case GLS_RETURN:
3429 gl_newline(gl, 1, NULL);
3430 return gl_flush_output(gl);
3431 break;
3432 case GLS_ABORT:
3433 gl_record_status(gl, GLR_SIGNAL, sig->errno_value);
3434 return 1;
3435 break;
3436 case GLS_CONTINUE:
3437 return gl_flush_output(gl);
3438 break;
3440 return 0;
3443 /*.......................................................................
3444 * Get pertinent terminal control strings and the initial terminal size.
3446 * Input:
3447 * gl GetLine * The resource object of this library.
3448 * term char * The type of the terminal.
3449 * Output:
3450 * return int 0 - OK.
3451 * 1 - Error.
3453 static int gl_control_strings(GetLine *gl, const char *term)
3455 int bad_term = 0; /* True if term is unusable */
3457 * Discard any existing control strings from a previous terminal.
3459 gl->left = NULL;
3460 gl->right = NULL;
3461 gl->up = NULL;
3462 gl->down = NULL;
3463 gl->home = NULL;
3464 gl->bol = 0;
3465 gl->clear_eol = NULL;
3466 gl->clear_eod = NULL;
3467 gl->u_arrow = NULL;
3468 gl->d_arrow = NULL;
3469 gl->l_arrow = NULL;
3470 gl->r_arrow = NULL;
3471 gl->sound_bell = NULL;
3472 gl->bold = NULL;
3473 gl->underline = NULL;
3474 gl->standout = NULL;
3475 gl->dim = NULL;
3476 gl->reverse = NULL;
3477 gl->blink = NULL;
3478 gl->text_attr_off = NULL;
3479 gl->nline = 0;
3480 gl->ncolumn = 0;
3481 #ifdef USE_TERMINFO
3482 gl->left_n = NULL;
3483 gl->right_n = NULL;
3484 #endif
3486 * If possible lookup the information in a terminal information
3487 * database.
3489 #ifdef USE_TERMINFO
3491 int errret;
3492 if(!term || setupterm((char *)term, gl->input_fd, &errret) == ERR) {
3493 bad_term = 1;
3494 } else {
3495 _clr_StringGroup(gl->capmem);
3496 gl->left = gl_tigetstr(gl, "cub1");
3497 gl->right = gl_tigetstr(gl, "cuf1");
3498 gl->up = gl_tigetstr(gl, "cuu1");
3499 gl->down = gl_tigetstr(gl, "cud1");
3500 gl->home = gl_tigetstr(gl, "home");
3501 gl->clear_eol = gl_tigetstr(gl, "el");
3502 gl->clear_eod = gl_tigetstr(gl, "ed");
3503 gl->u_arrow = gl_tigetstr(gl, "kcuu1");
3504 gl->d_arrow = gl_tigetstr(gl, "kcud1");
3505 gl->l_arrow = gl_tigetstr(gl, "kcub1");
3506 gl->r_arrow = gl_tigetstr(gl, "kcuf1");
3507 gl->left_n = gl_tigetstr(gl, "cub");
3508 gl->right_n = gl_tigetstr(gl, "cuf");
3509 gl->sound_bell = gl_tigetstr(gl, "bel");
3510 gl->bold = gl_tigetstr(gl, "bold");
3511 gl->underline = gl_tigetstr(gl, "smul");
3512 gl->standout = gl_tigetstr(gl, "smso");
3513 gl->dim = gl_tigetstr(gl, "dim");
3514 gl->reverse = gl_tigetstr(gl, "rev");
3515 gl->blink = gl_tigetstr(gl, "blink");
3516 gl->text_attr_off = gl_tigetstr(gl, "sgr0");
3519 #elif defined(USE_TERMCAP)
3520 if(!term || tgetent(gl->tgetent_buf, (char *)term) < 0) {
3521 bad_term = 1;
3522 } else {
3523 char *tgetstr_buf_ptr = gl->tgetstr_buf;
3524 _clr_StringGroup(gl->capmem);
3525 gl->left = gl_tgetstr(gl, "le", &tgetstr_buf_ptr);
3526 gl->right = gl_tgetstr(gl, "nd", &tgetstr_buf_ptr);
3527 gl->up = gl_tgetstr(gl, "up", &tgetstr_buf_ptr);
3528 gl->down = gl_tgetstr(gl, "do", &tgetstr_buf_ptr);
3529 gl->home = gl_tgetstr(gl, "ho", &tgetstr_buf_ptr);
3530 gl->clear_eol = gl_tgetstr(gl, "ce", &tgetstr_buf_ptr);
3531 gl->clear_eod = gl_tgetstr(gl, "cd", &tgetstr_buf_ptr);
3532 gl->u_arrow = gl_tgetstr(gl, "ku", &tgetstr_buf_ptr);
3533 gl->d_arrow = gl_tgetstr(gl, "kd", &tgetstr_buf_ptr);
3534 gl->l_arrow = gl_tgetstr(gl, "kl", &tgetstr_buf_ptr);
3535 gl->r_arrow = gl_tgetstr(gl, "kr", &tgetstr_buf_ptr);
3536 gl->sound_bell = gl_tgetstr(gl, "bl", &tgetstr_buf_ptr);
3537 gl->bold = gl_tgetstr(gl, "md", &tgetstr_buf_ptr);
3538 gl->underline = gl_tgetstr(gl, "us", &tgetstr_buf_ptr);
3539 gl->standout = gl_tgetstr(gl, "so", &tgetstr_buf_ptr);
3540 gl->dim = gl_tgetstr(gl, "mh", &tgetstr_buf_ptr);
3541 gl->reverse = gl_tgetstr(gl, "mr", &tgetstr_buf_ptr);
3542 gl->blink = gl_tgetstr(gl, "mb", &tgetstr_buf_ptr);
3543 gl->text_attr_off = gl_tgetstr(gl, "me", &tgetstr_buf_ptr);
3545 #endif
3547 * Report term being unusable.
3549 if(bad_term) {
3550 gl_print_info(gl, "Bad terminal type: \"", term ? term : "(null)",
3551 "\". Will assume vt100.", GL_END_INFO);
3554 * Fill in missing information with ANSI VT100 strings.
3556 if(!gl->left)
3557 gl->left = "\b"; /* ^H */
3558 if(!gl->right)
3559 gl->right = GL_ESC_STR "[C";
3560 if(!gl->up)
3561 gl->up = GL_ESC_STR "[A";
3562 if(!gl->down)
3563 gl->down = "\n";
3564 if(!gl->home)
3565 gl->home = GL_ESC_STR "[H";
3566 if(!gl->bol)
3567 gl->bol = "\r";
3568 if(!gl->clear_eol)
3569 gl->clear_eol = GL_ESC_STR "[K";
3570 if(!gl->clear_eod)
3571 gl->clear_eod = GL_ESC_STR "[J";
3572 if(!gl->u_arrow)
3573 gl->u_arrow = GL_ESC_STR "[A";
3574 if(!gl->d_arrow)
3575 gl->d_arrow = GL_ESC_STR "[B";
3576 if(!gl->l_arrow)
3577 gl->l_arrow = GL_ESC_STR "[D";
3578 if(!gl->r_arrow)
3579 gl->r_arrow = GL_ESC_STR "[C";
3580 if(!gl->sound_bell)
3581 gl->sound_bell = "\a";
3582 if(!gl->bold)
3583 gl->bold = GL_ESC_STR "[1m";
3584 if(!gl->underline)
3585 gl->underline = GL_ESC_STR "[4m";
3586 if(!gl->standout)
3587 gl->standout = GL_ESC_STR "[1;7m";
3588 if(!gl->dim)
3589 gl->dim = ""; /* Not available */
3590 if(!gl->reverse)
3591 gl->reverse = GL_ESC_STR "[7m";
3592 if(!gl->blink)
3593 gl->blink = GL_ESC_STR "[5m";
3594 if(!gl->text_attr_off)
3595 gl->text_attr_off = GL_ESC_STR "[m";
3597 * Find out the current terminal size.
3599 (void) _gl_terminal_size(gl, GL_DEF_NCOLUMN, GL_DEF_NLINE, NULL);
3600 return 0;
3603 #ifdef USE_TERMINFO
3604 /*.......................................................................
3605 * This is a private function of gl_control_strings() used to look up
3606 * a termninal capability string from the terminfo database and make
3607 * a private copy of it.
3609 * Input:
3610 * gl GetLine * The resource object of gl_get_line().
3611 * name const char * The name of the terminfo string to look up.
3612 * Output:
3613 * return const char * The local copy of the capability, or NULL
3614 * if not available.
3616 static const char *gl_tigetstr(GetLine *gl, const char *name)
3618 const char *value = tigetstr((char *)name);
3619 if(!value || value == (char *) -1)
3620 return NULL;
3621 return _sg_store_string(gl->capmem, value, 0);
3623 #elif defined(USE_TERMCAP)
3624 /*.......................................................................
3625 * This is a private function of gl_control_strings() used to look up
3626 * a termninal capability string from the termcap database and make
3627 * a private copy of it. Note that some emulations of tgetstr(), such
3628 * as that used by Solaris, ignores the buffer pointer that is past to
3629 * it, so we can't assume that a private copy has been made that won't
3630 * be trashed by another call to gl_control_strings() by another
3631 * GetLine object. So we make what may be a redundant private copy
3632 * of the string in gl->capmem.
3634 * Input:
3635 * gl GetLine * The resource object of gl_get_line().
3636 * name const char * The name of the terminfo string to look up.
3637 * Input/Output:
3638 * bufptr char ** On input *bufptr points to the location in
3639 * gl->tgetstr_buf at which to record the
3640 * capability string. On output *bufptr is
3641 * incremented over the stored string.
3642 * Output:
3643 * return const char * The local copy of the capability, or NULL
3644 * on error.
3646 static const char *gl_tgetstr(GetLine *gl, const char *name, char **bufptr)
3648 const char *value = tgetstr((char *)name, bufptr);
3649 if(!value || value == (char *) -1)
3650 return NULL;
3651 return _sg_store_string(gl->capmem, value, 0);
3653 #endif
3655 /*.......................................................................
3656 * This is an action function that implements a user interrupt (eg. ^C).
3658 static KT_KEY_FN(gl_user_interrupt)
3660 raise(SIGINT);
3661 return 1;
3664 /*.......................................................................
3665 * This is an action function that implements the abort signal.
3667 static KT_KEY_FN(gl_abort)
3669 raise(SIGABRT);
3670 return 1;
3673 /*.......................................................................
3674 * This is an action function that sends a suspend signal (eg. ^Z) to the
3675 * the parent process.
3677 static KT_KEY_FN(gl_suspend)
3679 raise(SIGTSTP);
3680 return 0;
3683 /*.......................................................................
3684 * This is an action function that halts output to the terminal.
3686 static KT_KEY_FN(gl_stop_output)
3688 tcflow(gl->output_fd, TCOOFF);
3689 return 0;
3692 /*.......................................................................
3693 * This is an action function that resumes halted terminal output.
3695 static KT_KEY_FN(gl_start_output)
3697 tcflow(gl->output_fd, TCOON);
3698 return 0;
3701 /*.......................................................................
3702 * This is an action function that allows the next character to be accepted
3703 * without any interpretation as a special character.
3705 static KT_KEY_FN(gl_literal_next)
3707 char c; /* The character to be added to the line */
3708 int i;
3710 * Get the character to be inserted literally.
3712 if(gl_read_terminal(gl, 1, &c))
3713 return 1;
3715 * Add the character to the line 'count' times.
3717 for(i=0; i<count; i++)
3718 gl_add_char_to_line(gl, c);
3719 return 0;
3722 /*.......................................................................
3723 * Return the width of a tab character at a given position when
3724 * displayed at a given position on the terminal. This is needed
3725 * because the width of tab characters depends on where they are,
3726 * relative to the preceding tab stops.
3728 * Input:
3729 * gl GetLine * The resource object of this library.
3730 * term_curpos int The destination terminal location of the character.
3731 * Output:
3732 * return int The number of terminal charaters needed.
3734 static int gl_displayed_tab_width(GetLine *gl, int term_curpos)
3736 return TAB_WIDTH - ((term_curpos % gl->ncolumn) % TAB_WIDTH);
3739 /*.......................................................................
3740 * Return the number of characters needed to display a given character
3741 * on the screen. Tab characters require eight spaces, and control
3742 * characters are represented by a caret followed by the modified
3743 * character.
3745 * Input:
3746 * gl GetLine * The resource object of this library.
3747 * c char The character to be displayed.
3748 * term_curpos int The destination terminal location of the character.
3749 * This is needed because the width of tab characters
3750 * depends on where they are, relative to the
3751 * preceding tab stops.
3752 * Output:
3753 * return int The number of terminal charaters needed.
3755 static int gl_displayed_char_width(GetLine *gl, char c, int term_curpos)
3757 if(c=='\t')
3758 return gl_displayed_tab_width(gl, term_curpos);
3759 if(IS_CTRL_CHAR(c))
3760 return 2;
3761 if(!isprint((int)(unsigned char) c))
3762 return gl_octal_width((int)(unsigned char)c) + 1;
3763 return 1;
3767 /*.......................................................................
3768 * Work out the length of given string of characters on the terminal.
3770 * Input:
3771 * gl GetLine * The resource object of this library.
3772 * string char * The string to be measured.
3773 * nc int The number of characters to be measured, or -1
3774 * to measure the whole string.
3775 * term_curpos int The destination terminal location of the character.
3776 * This is needed because the width of tab characters
3777 * depends on where they are, relative to the
3778 * preceding tab stops.
3779 * Output:
3780 * return int The number of displayed characters.
3782 static int gl_displayed_string_width(GetLine *gl, const char *string, int nc,
3783 int term_curpos)
3785 int slen = 0; /* The displayed number of characters */
3786 int i;
3788 * How many characters are to be measured?
3790 if(nc < 0)
3791 nc = strlen(string);
3793 * Add up the length of the displayed string.
3795 for(i=0; i<nc; i++)
3796 slen += gl_displayed_char_width(gl, string[i], term_curpos + slen);
3797 return slen;
3800 /*.......................................................................
3801 * Write a string verbatim to the current terminal or output stream.
3803 * Note that when async-signal safety is required, the 'buffered'
3804 * argument must be 0, and n must not be -1.
3806 * Input:
3807 * gl GetLine * The resource object of the gl_get_line().
3808 * buffered int If true, used buffered I/O when writing to
3809 * the terminal. Otherwise use async-signal-safe
3810 * unbuffered I/O.
3811 * string const char * The string to be written (this need not be
3812 * '\0' terminated unless n<0).
3813 * n int The number of characters to write from the
3814 * prefix of string[], or -1 to request that
3815 * gl_print_raw_string() use strlen() to figure
3816 * out the length.
3817 * Output:
3818 * return int 0 - OK.
3819 * 1 - Error.
3821 static int gl_print_raw_string(GetLine *gl, int buffered,
3822 const char *string, int n)
3824 GlWriteFn *write_fn = buffered ? gl_write_fn : gl->flush_fn;
3826 * Only display output when echoing is turned on.
3828 if(gl->echo) {
3829 int ndone = 0; /* The number of characters written so far */
3831 * When using un-buffered I/O, flush pending output first.
3833 if(!buffered) {
3834 if(gl_flush_output(gl))
3835 return 1;
3838 * If no length has been provided, measure the length of the string.
3840 if(n < 0)
3841 n = strlen(string);
3843 * Write the string.
3845 if(write_fn(gl, string + ndone, n-ndone) != n)
3846 return 1;
3848 return 0;
3851 /*.......................................................................
3852 * Output a terminal control sequence. When using terminfo,
3853 * this must be a sequence returned by tgetstr() or tigetstr()
3854 * respectively.
3856 * Input:
3857 * gl GetLine * The resource object of this library.
3858 * nline int The number of lines affected by the operation,
3859 * or 1 if not relevant.
3860 * string char * The control sequence to be sent.
3861 * Output:
3862 * return int 0 - OK.
3863 * 1 - Error.
3865 static int gl_print_control_sequence(GetLine *gl, int nline, const char *string)
3867 int waserr = 0; /* True if an error occurs */
3869 * Only write characters to the terminal when echoing is enabled.
3871 if(gl->echo) {
3872 #if defined(USE_TERMINFO) || defined(USE_TERMCAP)
3873 tputs_gl = gl;
3874 errno = 0;
3875 tputs((char *)string, nline, gl_tputs_putchar);
3876 waserr = errno != 0;
3877 #else
3878 waserr = gl_print_raw_string(gl, 1, string, -1);
3879 #endif
3881 return waserr;
3884 #if defined(USE_TERMINFO) || defined(USE_TERMCAP)
3885 /*.......................................................................
3886 * The following callback function is called by tputs() to output a raw
3887 * control character to the terminal.
3889 static TputsRetType gl_tputs_putchar(TputsArgType c)
3891 char ch = c;
3892 #if TPUTS_RETURNS_VALUE
3893 return gl_print_raw_string(tputs_gl, 1, &ch, 1);
3894 #else
3895 (void) gl_print_raw_string(tputs_gl, 1, &ch, 1);
3896 #endif
3898 #endif
3900 /*.......................................................................
3901 * Move the terminal cursor n characters to the left or right.
3903 * Input:
3904 * gl GetLine * The resource object of this program.
3905 * n int number of positions to the right (> 0) or left (< 0).
3906 * Output:
3907 * return int 0 - OK.
3908 * 1 - Error.
3910 static int gl_terminal_move_cursor(GetLine *gl, int n)
3912 int cur_row, cur_col; /* The current terminal row and column index of */
3913 /* the cursor wrt the start of the input line. */
3914 int new_row, new_col; /* The target terminal row and column index of */
3915 /* the cursor wrt the start of the input line. */
3917 * Do nothing if the input line isn't currently displayed. In this
3918 * case, the cursor will be moved to the right place when the line
3919 * is next redisplayed.
3921 if(!gl->displayed)
3922 return 0;
3924 * How far can we move left?
3926 if(gl->term_curpos + n < 0)
3927 n = gl->term_curpos;
3929 * Break down the current and target cursor locations into rows and columns.
3931 cur_row = gl->term_curpos / gl->ncolumn;
3932 cur_col = gl->term_curpos % gl->ncolumn;
3933 new_row = (gl->term_curpos + n) / gl->ncolumn;
3934 new_col = (gl->term_curpos + n) % gl->ncolumn;
3936 * Move down to the next line.
3938 for(; cur_row < new_row; cur_row++) {
3939 if(gl_print_control_sequence(gl, 1, gl->down))
3940 return 1;
3943 * Move up to the previous line.
3945 for(; cur_row > new_row; cur_row--) {
3946 if(gl_print_control_sequence(gl, 1, gl->up))
3947 return 1;
3950 * Move to the right within the target line?
3952 if(cur_col < new_col) {
3953 #ifdef USE_TERMINFO
3955 * Use a parameterized control sequence if it generates less control
3956 * characters (guess based on ANSI terminal termcap entry).
3958 if(gl->right_n != NULL && new_col - cur_col > 1) {
3959 if(gl_print_control_sequence(gl, 1, tparm((char *)gl->right_n,
3960 (long)(new_col - cur_col), 0l, 0l, 0l, 0l, 0l, 0l, 0l, 0l)))
3961 return 1;
3962 } else
3963 #endif
3965 for(; cur_col < new_col; cur_col++) {
3966 if(gl_print_control_sequence(gl, 1, gl->right))
3967 return 1;
3971 * Move to the left within the target line?
3973 } else if(cur_col > new_col) {
3974 #ifdef USE_TERMINFO
3976 * Use a parameterized control sequence if it generates less control
3977 * characters (guess based on ANSI terminal termcap entry).
3979 if(gl->left_n != NULL && cur_col - new_col > 3) {
3980 if(gl_print_control_sequence(gl, 1, tparm((char *)gl->left_n,
3981 (long)(cur_col - new_col), 0l, 0l, 0l, 0l, 0l, 0l, 0l, 0l)))
3982 return 1;
3983 } else
3984 #endif
3986 for(; cur_col > new_col; cur_col--) {
3987 if(gl_print_control_sequence(gl, 1, gl->left))
3988 return 1;
3993 * Update the recorded position of the terminal cursor.
3995 gl->term_curpos += n;
3996 return 0;
3999 /*.......................................................................
4000 * Write a character to the terminal after expanding tabs and control
4001 * characters to their multi-character representations.
4003 * Input:
4004 * gl GetLine * The resource object of this program.
4005 * c char The character to be output.
4006 * pad char Many terminals have the irritating feature that
4007 * when one writes a character in the last column of
4008 * of the terminal, the cursor isn't wrapped to the
4009 * start of the next line until one more character
4010 * is written. Some terminals don't do this, so
4011 * after such a write, we don't know where the
4012 * terminal is unless we output an extra character.
4013 * This argument specifies the character to write.
4014 * If at the end of the input line send '\0' or a
4015 * space, and a space will be written. Otherwise,
4016 * pass the next character in the input line
4017 * following the one being written.
4018 * Output:
4019 * return int 0 - OK.
4021 static int gl_print_char(GetLine *gl, char c, char pad)
4023 char string[TAB_WIDTH + 4]; /* A work area for composing compound strings */
4024 int nchar; /* The number of terminal characters */
4025 int i;
4027 * Check for special characters.
4029 if(c == '\t') {
4031 * How many spaces do we need to represent a tab at the current terminal
4032 * column?
4034 nchar = gl_displayed_tab_width(gl, gl->term_curpos);
4036 * Compose the tab string.
4038 for(i=0; i<nchar; i++)
4039 string[i] = ' ';
4040 } else if(IS_CTRL_CHAR(c)) {
4041 string[0] = '^';
4042 string[1] = CTRL_TO_CHAR(c);
4043 nchar = 2;
4044 } else if(!isprint((int)(unsigned char) c)) {
4045 snprintf(string, sizeof(string), "\\%o", (int)(unsigned char)c);
4046 nchar = strlen(string);
4047 } else {
4048 string[0] = c;
4049 nchar = 1;
4052 * Terminate the string.
4054 string[nchar] = '\0';
4056 * Write the string to the terminal.
4058 if(gl_print_raw_string(gl, 1, string, -1))
4059 return 1;
4061 * Except for one exception to be described in a moment, the cursor should
4062 * now have been positioned after the character that was just output.
4064 gl->term_curpos += nchar;
4066 * Keep a record of the number of characters in the terminal version
4067 * of the input line.
4069 if(gl->term_curpos > gl->term_len)
4070 gl->term_len = gl->term_curpos;
4072 * If the new character ended exactly at the end of a line,
4073 * most terminals won't move the cursor onto the next line until we
4074 * have written a character on the next line, so append an extra
4075 * space then move the cursor back.
4077 if(gl->term_curpos % gl->ncolumn == 0) {
4078 int term_curpos = gl->term_curpos;
4079 if(gl_print_char(gl, pad ? pad : ' ', ' ') ||
4080 gl_set_term_curpos(gl, term_curpos))
4081 return 1;
4083 return 0;
4086 /*.......................................................................
4087 * Write a string to the terminal after expanding tabs and control
4088 * characters to their multi-character representations.
4090 * Input:
4091 * gl GetLine * The resource object of this program.
4092 * string char * The string to be output.
4093 * pad char Many terminals have the irritating feature that
4094 * when one writes a character in the last column of
4095 * of the terminal, the cursor isn't wrapped to the
4096 * start of the next line until one more character
4097 * is written. Some terminals don't do this, so
4098 * after such a write, we don't know where the
4099 * terminal is unless we output an extra character.
4100 * This argument specifies the character to write.
4101 * If at the end of the input line send '\0' or a
4102 * space, and a space will be written. Otherwise,
4103 * pass the next character in the input line
4104 * following the one being written.
4105 * Output:
4106 * return int 0 - OK.
4108 static int gl_print_string(GetLine *gl, const char *string, char pad)
4110 const char *cptr; /* A pointer into string[] */
4111 for(cptr=string; *cptr; cptr++) {
4112 char nextc = cptr[1];
4113 if(gl_print_char(gl, *cptr, nextc ? nextc : pad))
4114 return 1;
4116 return 0;
4119 /*.......................................................................
4120 * Move the terminal cursor position.
4122 * Input:
4123 * gl GetLine * The resource object of this library.
4124 * term_curpos int The destination terminal cursor position.
4125 * Output:
4126 * return int 0 - OK.
4127 * 1 - Error.
4129 static int gl_set_term_curpos(GetLine *gl, int term_curpos)
4131 return gl_terminal_move_cursor(gl, term_curpos - gl->term_curpos);
4134 /*.......................................................................
4135 * This is an action function that moves the buffer cursor one character
4136 * left, and updates the terminal cursor to match.
4138 static KT_KEY_FN(gl_cursor_left)
4140 return gl_place_cursor(gl, gl->buff_curpos - count);
4143 /*.......................................................................
4144 * This is an action function that moves the buffer cursor one character
4145 * right, and updates the terminal cursor to match.
4147 static KT_KEY_FN(gl_cursor_right)
4149 return gl_place_cursor(gl, gl->buff_curpos + count);
4152 /*.......................................................................
4153 * This is an action function that toggles between overwrite and insert
4154 * mode.
4156 static KT_KEY_FN(gl_insert_mode)
4158 gl->insert = !gl->insert;
4159 return 0;
4162 /*.......................................................................
4163 * This is an action function which moves the cursor to the beginning of
4164 * the line.
4166 static KT_KEY_FN(gl_beginning_of_line)
4168 return gl_place_cursor(gl, 0);
4171 /*.......................................................................
4172 * This is an action function which moves the cursor to the end of
4173 * the line.
4175 static KT_KEY_FN(gl_end_of_line)
4177 return gl_place_cursor(gl, gl->ntotal);
4180 /*.......................................................................
4181 * This is an action function which deletes the entire contents of the
4182 * current line.
4184 static KT_KEY_FN(gl_delete_line)
4187 * If in vi command mode, preserve the current line for potential
4188 * use by vi-undo.
4190 gl_save_for_undo(gl);
4192 * Copy the contents of the line to the cut buffer.
4194 strlcpy(gl->cutbuf, gl->line, gl->linelen);
4196 * Clear the buffer.
4198 gl_truncate_buffer(gl, 0);
4200 * Move the terminal cursor to just after the prompt.
4202 if(gl_place_cursor(gl, 0))
4203 return 1;
4205 * Clear from the end of the prompt to the end of the terminal.
4207 if(gl_truncate_display(gl))
4208 return 1;
4209 return 0;
4212 /*.......................................................................
4213 * This is an action function which deletes all characters between the
4214 * current cursor position and the end of the line.
4216 static KT_KEY_FN(gl_kill_line)
4219 * If in vi command mode, preserve the current line for potential
4220 * use by vi-undo.
4222 gl_save_for_undo(gl);
4224 * Copy the part of the line that is about to be deleted to the cut buffer.
4226 strlcpy(gl->cutbuf, gl->line + gl->buff_curpos, gl->linelen);
4228 * Terminate the buffered line at the current cursor position.
4230 gl_truncate_buffer(gl, gl->buff_curpos);
4232 * Clear the part of the line that follows the cursor.
4234 if(gl_truncate_display(gl))
4235 return 1;
4237 * Explicitly reset the cursor position to allow vi command mode
4238 * constraints on its position to be set.
4240 return gl_place_cursor(gl, gl->buff_curpos);
4243 /*.......................................................................
4244 * This is an action function which deletes all characters between the
4245 * start of the line and the current cursor position.
4247 static KT_KEY_FN(gl_backward_kill_line)
4250 * How many characters are to be deleted from before the cursor?
4252 int nc = gl->buff_curpos - gl->insert_curpos;
4253 if (!nc)
4254 return 0;
4256 * Move the cursor to the start of the line, or in vi input mode,
4257 * the start of the sub-line at which insertion started, and delete
4258 * up to the old cursor position.
4260 return gl_place_cursor(gl, gl->insert_curpos) ||
4261 gl_delete_chars(gl, nc, gl->editor == GL_EMACS_MODE || gl->vi.command);
4264 /*.......................................................................
4265 * This is an action function which moves the cursor forward by a word.
4267 static KT_KEY_FN(gl_forward_word)
4269 return gl_place_cursor(gl, gl_nth_word_end_forward(gl, count) +
4270 (gl->editor==GL_EMACS_MODE));
4273 /*.......................................................................
4274 * This is an action function which moves the cursor forward to the start
4275 * of the next word.
4277 static KT_KEY_FN(gl_forward_to_word)
4279 return gl_place_cursor(gl, gl_nth_word_start_forward(gl, count));
4282 /*.......................................................................
4283 * This is an action function which moves the cursor backward by a word.
4285 static KT_KEY_FN(gl_backward_word)
4287 return gl_place_cursor(gl, gl_nth_word_start_backward(gl, count));
4290 /*.......................................................................
4291 * Delete one or more characters, starting with the one under the cursor.
4293 * Input:
4294 * gl GetLine * The resource object of this library.
4295 * nc int The number of characters to delete.
4296 * cut int If true, copy the characters to the cut buffer.
4297 * Output:
4298 * return int 0 - OK.
4299 * 1 - Error.
4301 static int gl_delete_chars(GetLine *gl, int nc, int cut)
4304 * If in vi command mode, preserve the current line for potential
4305 * use by vi-undo.
4307 gl_save_for_undo(gl);
4309 * If there are fewer than nc characters following the cursor, limit
4310 * nc to the number available.
4312 if(gl->buff_curpos + nc > gl->ntotal)
4313 nc = gl->ntotal - gl->buff_curpos;
4315 * Copy the about to be deleted region to the cut buffer.
4317 if(cut) {
4318 memcpy(gl->cutbuf, gl->line + gl->buff_curpos, nc);
4319 gl->cutbuf[nc] = '\0';
4322 * Nothing to delete?
4324 if(nc <= 0)
4325 return 0;
4327 * In vi overwrite mode, restore any previously overwritten characters
4328 * from the undo buffer.
4330 if(gl->editor == GL_VI_MODE && !gl->vi.command && !gl->insert) {
4332 * How many of the characters being deleted can be restored from the
4333 * undo buffer?
4335 int nrestore = gl->buff_curpos + nc <= gl->vi.undo.ntotal ?
4336 nc : gl->vi.undo.ntotal - gl->buff_curpos;
4338 * Restore any available characters.
4340 if(nrestore > 0) {
4341 gl_buffer_string(gl, gl->vi.undo.line + gl->buff_curpos, nrestore,
4342 gl->buff_curpos);
4345 * If their were insufficient characters in the undo buffer, then this
4346 * implies that we are deleting from the end of the line, so we need
4347 * to terminate the line either where the undo buffer ran out, or if
4348 * we are deleting from beyond the end of the undo buffer, at the current
4349 * cursor position.
4351 if(nc != nrestore) {
4352 gl_truncate_buffer(gl, (gl->vi.undo.ntotal > gl->buff_curpos) ?
4353 gl->vi.undo.ntotal : gl->buff_curpos);
4355 } else {
4357 * Copy the remaining part of the line back over the deleted characters.
4359 gl_remove_from_buffer(gl, gl->buff_curpos, nc);
4362 * Redraw the remaining characters following the cursor.
4364 if(gl_print_string(gl, gl->line + gl->buff_curpos, '\0'))
4365 return 1;
4367 * Clear to the end of the terminal.
4369 if(gl_truncate_display(gl))
4370 return 1;
4372 * Place the cursor at the start of where the deletion was performed.
4374 return gl_place_cursor(gl, gl->buff_curpos);
4377 /*.......................................................................
4378 * This is an action function which deletes character(s) under the
4379 * cursor without moving the cursor.
4381 static KT_KEY_FN(gl_forward_delete_char)
4384 * Delete 'count' characters.
4386 return gl_delete_chars(gl, count, gl->vi.command);
4389 /*.......................................................................
4390 * This is an action function which deletes character(s) under the
4391 * cursor and moves the cursor back one character.
4393 static KT_KEY_FN(gl_backward_delete_char)
4396 * Restrict the deletion count to the number of characters that
4397 * precede the insertion point.
4399 if(count > gl->buff_curpos - gl->insert_curpos)
4400 count = gl->buff_curpos - gl->insert_curpos;
4402 * If in vi command mode, preserve the current line for potential
4403 * use by vi-undo.
4405 gl_save_for_undo(gl);
4406 return gl_cursor_left(gl, count, NULL) ||
4407 gl_delete_chars(gl, count, gl->vi.command);
4410 /*.......................................................................
4411 * Starting from the cursor position delete to the specified column.
4413 static KT_KEY_FN(gl_delete_to_column)
4415 if (--count >= gl->buff_curpos)
4416 return gl_forward_delete_char(gl, count - gl->buff_curpos, NULL);
4417 else
4418 return gl_backward_delete_char(gl, gl->buff_curpos - count, NULL);
4421 /*.......................................................................
4422 * Starting from the cursor position delete characters to a matching
4423 * parenthesis.
4425 static KT_KEY_FN(gl_delete_to_parenthesis)
4427 int curpos = gl_index_of_matching_paren(gl);
4428 if(curpos >= 0) {
4429 gl_save_for_undo(gl);
4430 if(curpos >= gl->buff_curpos)
4431 return gl_forward_delete_char(gl, curpos - gl->buff_curpos + 1, NULL);
4432 else
4433 return gl_backward_delete_char(gl, ++gl->buff_curpos - curpos + 1, NULL);
4435 return 0;
4438 /*.......................................................................
4439 * This is an action function which deletes from the cursor to the end
4440 * of the word that the cursor is either in or precedes.
4442 static KT_KEY_FN(gl_forward_delete_word)
4445 * If in vi command mode, preserve the current line for potential
4446 * use by vi-undo.
4448 gl_save_for_undo(gl);
4450 * In emacs mode delete to the end of the word. In vi mode delete to the
4451 * start of the net word.
4453 if(gl->editor == GL_EMACS_MODE) {
4454 return gl_delete_chars(gl,
4455 gl_nth_word_end_forward(gl,count) - gl->buff_curpos + 1, 1);
4456 } else {
4457 return gl_delete_chars(gl,
4458 gl_nth_word_start_forward(gl,count) - gl->buff_curpos,
4459 gl->vi.command);
4463 /*.......................................................................
4464 * This is an action function which deletes the word that precedes the
4465 * cursor.
4467 static KT_KEY_FN(gl_backward_delete_word)
4470 * Keep a record of the current cursor position.
4472 int buff_curpos = gl->buff_curpos;
4474 * If in vi command mode, preserve the current line for potential
4475 * use by vi-undo.
4477 gl_save_for_undo(gl);
4479 * Move back 'count' words.
4481 if(gl_backward_word(gl, count, NULL))
4482 return 1;
4484 * Delete from the new cursor position to the original one.
4486 return gl_delete_chars(gl, buff_curpos - gl->buff_curpos,
4487 gl->editor == GL_EMACS_MODE || gl->vi.command);
4490 /*.......................................................................
4491 * Searching in a given direction, delete to the count'th
4492 * instance of a specified or queried character, in the input line.
4494 * Input:
4495 * gl GetLine * The getline resource object.
4496 * count int The number of times to search.
4497 * c char The character to be searched for, or '\0' if
4498 * the character should be read from the user.
4499 * forward int True if searching forward.
4500 * onto int True if the search should end on top of the
4501 * character, false if the search should stop
4502 * one character before the character in the
4503 * specified search direction.
4504 * change int If true, this function is being called upon
4505 * to do a vi change command, in which case the
4506 * user will be left in insert mode after the
4507 * deletion.
4508 * Output:
4509 * return int 0 - OK.
4510 * 1 - Error.
4512 static int gl_delete_find(GetLine *gl, int count, char c, int forward,
4513 int onto, int change)
4516 * Search for the character, and abort the deletion if not found.
4518 int pos = gl_find_char(gl, count, forward, onto, c);
4519 if(pos < 0)
4520 return 0;
4522 * If in vi command mode, preserve the current line for potential
4523 * use by vi-undo.
4525 gl_save_for_undo(gl);
4527 * Allow the cursor to be at the end of the line if this is a change
4528 * command.
4530 if(change)
4531 gl->vi.command = 0;
4533 * Delete the appropriate span of characters.
4535 if(forward) {
4536 if(gl_delete_chars(gl, pos - gl->buff_curpos + 1, 1))
4537 return 1;
4538 } else {
4539 int buff_curpos = gl->buff_curpos;
4540 if(gl_place_cursor(gl, pos) ||
4541 gl_delete_chars(gl, buff_curpos - gl->buff_curpos, 1))
4542 return 1;
4545 * If this is a change operation, switch the insert mode.
4547 if(change && gl_vi_insert(gl, 0, NULL))
4548 return 1;
4549 return 0;
4552 /*.......................................................................
4553 * This is an action function which deletes forward from the cursor up to and
4554 * including a specified character.
4556 static KT_KEY_FN(gl_forward_delete_find)
4558 return gl_delete_find(gl, count, '\0', 1, 1, 0);
4561 /*.......................................................................
4562 * This is an action function which deletes backward from the cursor back to
4563 * and including a specified character.
4565 static KT_KEY_FN(gl_backward_delete_find)
4567 return gl_delete_find(gl, count, '\0', 0, 1, 0);
4570 /*.......................................................................
4571 * This is an action function which deletes forward from the cursor up to but
4572 * not including a specified character.
4574 static KT_KEY_FN(gl_forward_delete_to)
4576 return gl_delete_find(gl, count, '\0', 1, 0, 0);
4579 /*.......................................................................
4580 * This is an action function which deletes backward from the cursor back to
4581 * but not including a specified character.
4583 static KT_KEY_FN(gl_backward_delete_to)
4585 return gl_delete_find(gl, count, '\0', 0, 0, 0);
4588 /*.......................................................................
4589 * This is an action function which deletes to a character specified by a
4590 * previous search.
4592 static KT_KEY_FN(gl_delete_refind)
4594 return gl_delete_find(gl, count, gl->vi.find_char, gl->vi.find_forward,
4595 gl->vi.find_onto, 0);
4598 /*.......................................................................
4599 * This is an action function which deletes to a character specified by a
4600 * previous search, but in the opposite direction.
4602 static KT_KEY_FN(gl_delete_invert_refind)
4604 return gl_delete_find(gl, count, gl->vi.find_char,
4605 !gl->vi.find_forward, gl->vi.find_onto, 0);
4608 /*.......................................................................
4609 * This is an action function which converts the characters in the word
4610 * following the cursor to upper case.
4612 static KT_KEY_FN(gl_upcase_word)
4615 * Locate the count'th word ending after the cursor.
4617 int last = gl_nth_word_end_forward(gl, count);
4619 * If in vi command mode, preserve the current line for potential
4620 * use by vi-undo.
4622 gl_save_for_undo(gl);
4624 * Upcase characters from the current cursor position to 'last'.
4626 while(gl->buff_curpos <= last) {
4627 char *cptr = gl->line + gl->buff_curpos;
4629 * Convert the character to upper case?
4631 if(islower((int)(unsigned char) *cptr))
4632 gl_buffer_char(gl, toupper((int) *cptr), gl->buff_curpos);
4633 gl->buff_curpos++;
4635 * Write the possibly modified character back. Note that for non-modified
4636 * characters we want to do this as well, so as to advance the cursor.
4638 if(gl_print_char(gl, *cptr, cptr[1]))
4639 return 1;
4641 return gl_place_cursor(gl, gl->buff_curpos); /* bounds check */
4644 /*.......................................................................
4645 * This is an action function which converts the characters in the word
4646 * following the cursor to lower case.
4648 static KT_KEY_FN(gl_downcase_word)
4651 * Locate the count'th word ending after the cursor.
4653 int last = gl_nth_word_end_forward(gl, count);
4655 * If in vi command mode, preserve the current line for potential
4656 * use by vi-undo.
4658 gl_save_for_undo(gl);
4660 * Upcase characters from the current cursor position to 'last'.
4662 while(gl->buff_curpos <= last) {
4663 char *cptr = gl->line + gl->buff_curpos;
4665 * Convert the character to upper case?
4667 if(isupper((int)(unsigned char) *cptr))
4668 gl_buffer_char(gl, tolower((int) *cptr), gl->buff_curpos);
4669 gl->buff_curpos++;
4671 * Write the possibly modified character back. Note that for non-modified
4672 * characters we want to do this as well, so as to advance the cursor.
4674 if(gl_print_char(gl, *cptr, cptr[1]))
4675 return 1;
4677 return gl_place_cursor(gl, gl->buff_curpos); /* bounds check */
4680 /*.......................................................................
4681 * This is an action function which converts the first character of the
4682 * following word to upper case, in order to capitalize the word, and
4683 * leaves the cursor at the end of the word.
4685 static KT_KEY_FN(gl_capitalize_word)
4687 char *cptr; /* &gl->line[gl->buff_curpos] */
4688 int first; /* True for the first letter of the word */
4689 int i;
4691 * Keep a record of the current insert mode and the cursor position.
4693 int insert = gl->insert;
4695 * If in vi command mode, preserve the current line for potential
4696 * use by vi-undo.
4698 gl_save_for_undo(gl);
4700 * We want to overwrite the modified word.
4702 gl->insert = 0;
4704 * Capitalize 'count' words.
4706 for(i=0; i<count && gl->buff_curpos < gl->ntotal; i++) {
4707 int pos = gl->buff_curpos;
4709 * If we are not already within a word, skip to the start of the word.
4711 for(cptr = gl->line + pos ; pos<gl->ntotal && !gl_is_word_char((int) *cptr);
4712 pos++, cptr++)
4715 * Move the cursor to the new position.
4717 if(gl_place_cursor(gl, pos))
4718 return 1;
4720 * While searching for the end of the word, change lower case letters
4721 * to upper case.
4723 for(first=1; gl->buff_curpos<gl->ntotal && gl_is_word_char((int) *cptr);
4724 gl->buff_curpos++, cptr++) {
4726 * Convert the character to upper case?
4728 if(first) {
4729 if(islower((int)(unsigned char) *cptr))
4730 gl_buffer_char(gl, toupper((int) *cptr), cptr - gl->line);
4731 } else {
4732 if(isupper((int)(unsigned char) *cptr))
4733 gl_buffer_char(gl, tolower((int) *cptr), cptr - gl->line);
4735 first = 0;
4737 * Write the possibly modified character back. Note that for non-modified
4738 * characters we want to do this as well, so as to advance the cursor.
4740 if(gl_print_char(gl, *cptr, cptr[1]))
4741 return 1;
4745 * Restore the insertion mode.
4747 gl->insert = insert;
4748 return gl_place_cursor(gl, gl->buff_curpos); /* bounds check */
4751 /*.......................................................................
4752 * This is an action function which redraws the current line.
4754 static KT_KEY_FN(gl_redisplay)
4757 * Keep a record of the current cursor position.
4759 int buff_curpos = gl->buff_curpos;
4761 * Do nothing if there is no line to be redisplayed.
4763 if(gl->endline)
4764 return 0;
4766 * Erase the current input line.
4768 if(gl_erase_line(gl))
4769 return 1;
4771 * Display the current prompt.
4773 if(gl_display_prompt(gl))
4774 return 1;
4776 * Render the part of the line that the user has typed in so far.
4778 if(gl_print_string(gl, gl->line, '\0'))
4779 return 1;
4781 * Restore the cursor position.
4783 if(gl_place_cursor(gl, buff_curpos))
4784 return 1;
4786 * Mark the redisplay operation as having been completed.
4788 gl->redisplay = 0;
4790 * Flush the redisplayed line to the terminal.
4792 return gl_flush_output(gl);
4795 /*.......................................................................
4796 * This is an action function which clears the display and redraws the
4797 * input line from the home position.
4799 static KT_KEY_FN(gl_clear_screen)
4802 * Home the cursor and clear from there to the end of the display.
4804 if(gl_print_control_sequence(gl, gl->nline, gl->home) ||
4805 gl_print_control_sequence(gl, gl->nline, gl->clear_eod))
4806 return 1;
4808 * The input line is no longer displayed.
4810 gl_line_erased(gl);
4812 * Arrange for the input line to be redisplayed.
4814 gl_queue_redisplay(gl);
4815 return 0;
4818 /*.......................................................................
4819 * This is an action function which swaps the character under the cursor
4820 * with the character to the left of the cursor.
4822 static KT_KEY_FN(gl_transpose_chars)
4824 char from[3]; /* The original string of 2 characters */
4825 char swap[3]; /* The swapped string of two characters */
4827 * If we are at the beginning or end of the line, there aren't two
4828 * characters to swap.
4830 if(gl->buff_curpos < 1 || gl->buff_curpos >= gl->ntotal)
4831 return 0;
4833 * If in vi command mode, preserve the current line for potential
4834 * use by vi-undo.
4836 gl_save_for_undo(gl);
4838 * Get the original and swapped strings of the two characters.
4840 from[0] = gl->line[gl->buff_curpos - 1];
4841 from[1] = gl->line[gl->buff_curpos];
4842 from[2] = '\0';
4843 swap[0] = gl->line[gl->buff_curpos];
4844 swap[1] = gl->line[gl->buff_curpos - 1];
4845 swap[2] = '\0';
4847 * Move the cursor to the start of the two characters.
4849 if(gl_place_cursor(gl, gl->buff_curpos-1))
4850 return 1;
4852 * Swap the two characters in the buffer.
4854 gl_buffer_char(gl, swap[0], gl->buff_curpos);
4855 gl_buffer_char(gl, swap[1], gl->buff_curpos+1);
4857 * If the sum of the displayed width of the two characters
4858 * in their current and final positions is the same, swapping can
4859 * be done by just overwriting with the two swapped characters.
4861 if(gl_displayed_string_width(gl, from, -1, gl->term_curpos) ==
4862 gl_displayed_string_width(gl, swap, -1, gl->term_curpos)) {
4863 int insert = gl->insert;
4864 gl->insert = 0;
4865 if(gl_print_char(gl, swap[0], swap[1]) ||
4866 gl_print_char(gl, swap[1], gl->line[gl->buff_curpos+2]))
4867 return 1;
4868 gl->insert = insert;
4870 * If the swapped substring has a different displayed size, we need to
4871 * redraw everything after the first of the characters.
4873 } else {
4874 if(gl_print_string(gl, gl->line + gl->buff_curpos, '\0') ||
4875 gl_truncate_display(gl))
4876 return 1;
4879 * Advance the cursor to the character after the swapped pair.
4881 return gl_place_cursor(gl, gl->buff_curpos + 2);
4884 /*.......................................................................
4885 * This is an action function which sets a mark at the current cursor
4886 * location.
4888 static KT_KEY_FN(gl_set_mark)
4890 gl->buff_mark = gl->buff_curpos;
4891 return 0;
4894 /*.......................................................................
4895 * This is an action function which swaps the mark location for the
4896 * cursor location.
4898 static KT_KEY_FN(gl_exchange_point_and_mark)
4901 * Get the old mark position, and limit to the extent of the input
4902 * line.
4904 int old_mark = gl->buff_mark <= gl->ntotal ? gl->buff_mark : gl->ntotal;
4906 * Make the current cursor position the new mark.
4908 gl->buff_mark = gl->buff_curpos;
4910 * Move the cursor to the old mark position.
4912 return gl_place_cursor(gl, old_mark);
4915 /*.......................................................................
4916 * This is an action function which deletes the characters between the
4917 * mark and the cursor, recording them in gl->cutbuf for later pasting.
4919 static KT_KEY_FN(gl_kill_region)
4922 * If in vi command mode, preserve the current line for potential
4923 * use by vi-undo.
4925 gl_save_for_undo(gl);
4927 * Limit the mark to be within the line.
4929 if(gl->buff_mark > gl->ntotal)
4930 gl->buff_mark = gl->ntotal;
4932 * If there are no characters between the cursor and the mark, simply clear
4933 * the cut buffer.
4935 if(gl->buff_mark == gl->buff_curpos) {
4936 gl->cutbuf[0] = '\0';
4937 return 0;
4940 * If the mark is before the cursor, swap the cursor and the mark.
4942 if(gl->buff_mark < gl->buff_curpos && gl_exchange_point_and_mark(gl,1,NULL))
4943 return 1;
4945 * Delete the characters.
4947 if(gl_delete_chars(gl, gl->buff_mark - gl->buff_curpos, 1))
4948 return 1;
4950 * Make the mark the same as the cursor position.
4952 gl->buff_mark = gl->buff_curpos;
4953 return 0;
4956 /*.......................................................................
4957 * This is an action function which records the characters between the
4958 * mark and the cursor, in gl->cutbuf for later pasting.
4960 static KT_KEY_FN(gl_copy_region_as_kill)
4962 int ca, cb; /* The indexes of the first and last characters in the region */
4963 int mark; /* The position of the mark */
4965 * Get the position of the mark, limiting it to lie within the line.
4967 mark = gl->buff_mark > gl->ntotal ? gl->ntotal : gl->buff_mark;
4969 * If there are no characters between the cursor and the mark, clear
4970 * the cut buffer.
4972 if(mark == gl->buff_curpos) {
4973 gl->cutbuf[0] = '\0';
4974 return 0;
4977 * Get the line indexes of the first and last characters in the region.
4979 if(mark < gl->buff_curpos) {
4980 ca = mark;
4981 cb = gl->buff_curpos - 1;
4982 } else {
4983 ca = gl->buff_curpos;
4984 cb = mark - 1;
4987 * Copy the region to the cut buffer.
4989 memcpy(gl->cutbuf, gl->line + ca, cb + 1 - ca);
4990 gl->cutbuf[cb + 1 - ca] = '\0';
4991 return 0;
4994 /*.......................................................................
4995 * This is an action function which inserts the contents of the cut
4996 * buffer at the current cursor location.
4998 static KT_KEY_FN(gl_yank)
5000 int i;
5002 * Set the mark at the current location.
5004 gl->buff_mark = gl->buff_curpos;
5006 * Do nothing else if the cut buffer is empty.
5008 if(gl->cutbuf[0] == '\0')
5009 return gl_ring_bell(gl, 1, NULL);
5011 * If in vi command mode, preserve the current line for potential
5012 * use by vi-undo.
5014 gl_save_for_undo(gl);
5016 * Insert the string count times.
5018 for(i=0; i<count; i++) {
5019 if(gl_add_string_to_line(gl, gl->cutbuf))
5020 return 1;
5023 * gl_add_string_to_line() leaves the cursor after the last character that
5024 * was pasted, whereas vi leaves the cursor over the last character pasted.
5026 if(gl->editor == GL_VI_MODE && gl_cursor_left(gl, 1, NULL))
5027 return 1;
5028 return 0;
5031 /*.......................................................................
5032 * This is an action function which inserts the contents of the cut
5033 * buffer one character beyond the current cursor location.
5035 static KT_KEY_FN(gl_append_yank)
5037 int was_command = gl->vi.command;
5038 int i;
5040 * If the cut buffer is empty, ring the terminal bell.
5042 if(gl->cutbuf[0] == '\0')
5043 return gl_ring_bell(gl, 1, NULL);
5045 * Set the mark at the current location + 1.
5047 gl->buff_mark = gl->buff_curpos + 1;
5049 * If in vi command mode, preserve the current line for potential
5050 * use by vi-undo.
5052 gl_save_for_undo(gl);
5054 * Arrange to paste the text in insert mode after the current character.
5056 if(gl_vi_append(gl, 0, NULL))
5057 return 1;
5059 * Insert the string count times.
5061 for(i=0; i<count; i++) {
5062 if(gl_add_string_to_line(gl, gl->cutbuf))
5063 return 1;
5066 * Switch back to command mode if necessary.
5068 if(was_command)
5069 gl_vi_command_mode(gl);
5070 return 0;
5073 /*.......................................................................
5074 * Attempt to ask the terminal for its current size. On systems that
5075 * don't support the TIOCWINSZ ioctl() for querying the terminal size,
5076 * the current values of gl->ncolumn and gl->nrow are returned.
5078 * Input:
5079 * gl GetLine * The resource object of gl_get_line().
5080 * Input/Output:
5081 * ncolumn int * The number of columns will be assigned to *ncolumn.
5082 * nline int * The number of lines will be assigned to *nline.
5084 static void gl_query_size(GetLine *gl, int *ncolumn, int *nline)
5086 #ifdef TIOCGWINSZ
5088 * Query the new terminal window size. Ignore invalid responses.
5090 struct winsize size;
5091 if(ioctl(gl->output_fd, TIOCGWINSZ, &size) == 0 &&
5092 size.ws_row > 0 && size.ws_col > 0) {
5093 *ncolumn = size.ws_col;
5094 *nline = size.ws_row;
5095 return;
5097 #endif
5099 * Return the existing values.
5101 *ncolumn = gl->ncolumn;
5102 *nline = gl->nline;
5103 return;
5106 /*.......................................................................
5107 * Query the size of the terminal, and if it has changed, redraw the
5108 * current input line accordingly.
5110 * Input:
5111 * gl GetLine * The resource object of gl_get_line().
5112 * Output:
5113 * return int 0 - OK.
5114 * 1 - Error.
5116 static int _gl_update_size(GetLine *gl)
5118 int ncolumn, nline; /* The new size of the terminal */
5120 * Query the new terminal window size.
5122 gl_query_size(gl, &ncolumn, &nline);
5124 * Update gl and the displayed line to fit the new dimensions.
5126 return gl_handle_tty_resize(gl, ncolumn, nline);
5129 /*.......................................................................
5130 * Redraw the current input line to account for a change in the terminal
5131 * size. Also install the new size in gl.
5133 * Input:
5134 * gl GetLine * The resource object of gl_get_line().
5135 * ncolumn int The new number of columns.
5136 * nline int The new number of lines.
5137 * Output:
5138 * return int 0 - OK.
5139 * 1 - Error.
5141 static int gl_handle_tty_resize(GetLine *gl, int ncolumn, int nline)
5144 * If the input device isn't a terminal, just record the new size.
5146 if(!gl->is_term) {
5147 gl->nline = nline;
5148 gl->ncolumn = ncolumn;
5150 * Has the size actually changed?
5152 } else if(ncolumn != gl->ncolumn || nline != gl->nline) {
5154 * If we are currently editing a line, erase it.
5156 if(gl_erase_line(gl))
5157 return 1;
5159 * Update the recorded window size.
5161 gl->nline = nline;
5162 gl->ncolumn = ncolumn;
5164 * Arrange for the input line to be redrawn before the next character
5165 * is read from the terminal.
5167 gl_queue_redisplay(gl);
5169 return 0;
5172 /*.......................................................................
5173 * This is the action function that recalls the previous line in the
5174 * history buffer.
5176 static KT_KEY_FN(gl_up_history)
5179 * In vi mode, switch to command mode, since the user is very
5180 * likely to want to move around newly recalled lines.
5182 gl_vi_command_mode(gl);
5184 * Forget any previous recall session.
5186 gl->preload_id = 0;
5188 * Record the key sequence number of this search action.
5190 gl->last_search = gl->keyseq_count;
5192 * We don't want a search prefix for this function.
5194 if(_glh_search_prefix(gl->glh, gl->line, 0)) {
5195 _err_record_msg(gl->err, _glh_last_error(gl->glh), END_ERR_MSG);
5196 return 1;
5199 * Recall the count'th next older line in the history list. If the first one
5200 * fails we can return since nothing has changed, otherwise we must continue
5201 * and update the line state.
5203 if(_glh_find_backwards(gl->glh, gl->line, gl->linelen+1) == NULL)
5204 return 0;
5205 while(--count && _glh_find_backwards(gl->glh, gl->line, gl->linelen+1))
5208 * Accomodate the new contents of gl->line[].
5210 gl_update_buffer(gl);
5212 * Arrange to have the cursor placed at the end of the new line.
5214 gl->buff_curpos = gl->ntotal;
5216 * Erase and display the new line.
5218 gl_queue_redisplay(gl);
5219 return 0;
5222 /*.......................................................................
5223 * This is the action function that recalls the next line in the
5224 * history buffer.
5226 static KT_KEY_FN(gl_down_history)
5229 * In vi mode, switch to command mode, since the user is very
5230 * likely to want to move around newly recalled lines.
5232 gl_vi_command_mode(gl);
5234 * Record the key sequence number of this search action.
5236 gl->last_search = gl->keyseq_count;
5238 * If no search is currently in progress continue a previous recall
5239 * session from a previous entered line if possible.
5241 if(_glh_line_id(gl->glh, 0) == 0 && gl->preload_id) {
5242 _glh_recall_line(gl->glh, gl->preload_id, gl->line, gl->linelen+1);
5243 gl->preload_id = 0;
5244 } else {
5246 * We don't want a search prefix for this function.
5248 if(_glh_search_prefix(gl->glh, gl->line, 0)) {
5249 _err_record_msg(gl->err, _glh_last_error(gl->glh), END_ERR_MSG);
5250 return 1;
5253 * Recall the count'th next newer line in the history list. If the first one
5254 * fails we can return since nothing has changed otherwise we must continue
5255 * and update the line state.
5257 if(_glh_find_forwards(gl->glh, gl->line, gl->linelen+1) == NULL)
5258 return 0;
5259 while(--count && _glh_find_forwards(gl->glh, gl->line, gl->linelen+1))
5263 * Accomodate the new contents of gl->line[].
5265 gl_update_buffer(gl);
5267 * Arrange to have the cursor placed at the end of the new line.
5269 gl->buff_curpos = gl->ntotal;
5271 * Erase and display the new line.
5273 gl_queue_redisplay(gl);
5274 return 0;
5277 /*.......................................................................
5278 * This is the action function that recalls the previous line in the
5279 * history buffer whos prefix matches the characters that currently
5280 * precede the cursor. By setting count=-1, this can be used internally
5281 * to force searching for the prefix used in the last search.
5283 static KT_KEY_FN(gl_history_search_backward)
5286 * In vi mode, switch to command mode, since the user is very
5287 * likely to want to move around newly recalled lines.
5289 gl_vi_command_mode(gl);
5291 * Forget any previous recall session.
5293 gl->preload_id = 0;
5295 * Record the key sequence number of this search action.
5297 gl->last_search = gl->keyseq_count;
5299 * If a prefix search isn't already in progress, replace the search
5300 * prefix to the string that precedes the cursor. In vi command mode
5301 * include the character that is under the cursor in the string. If
5302 * count<0 keep the previous search prefix regardless, so as to force
5303 * a repeat search even if the last command wasn't a history command.
5305 if(count >= 0 && !_glh_search_active(gl->glh) &&
5306 _glh_search_prefix(gl->glh, gl->line, gl->buff_curpos +
5307 (gl->editor==GL_VI_MODE && gl->ntotal>0))) {
5308 _err_record_msg(gl->err, _glh_last_error(gl->glh), END_ERR_MSG);
5309 return 1;
5312 * Search backwards for a match to the part of the line which precedes the
5313 * cursor.
5315 if(_glh_find_backwards(gl->glh, gl->line, gl->linelen+1) == NULL)
5316 return 0;
5318 * Accomodate the new contents of gl->line[].
5320 gl_update_buffer(gl);
5322 * Arrange to have the cursor placed at the end of the new line.
5324 gl->buff_curpos = gl->ntotal;
5326 * Erase and display the new line.
5328 gl_queue_redisplay(gl);
5329 return 0;
5332 /*.......................................................................
5333 * This is the action function that recalls the previous line in the
5334 * history buffer who's prefix matches that specified in an earlier call
5335 * to gl_history_search_backward() or gl_history_search_forward().
5337 static KT_KEY_FN(gl_history_re_search_backward)
5339 return gl_history_search_backward(gl, -1, NULL);
5342 /*.......................................................................
5343 * This is the action function that recalls the next line in the
5344 * history buffer who's prefix matches that specified in the earlier call
5345 * to gl_history_search_backward) which started the history search.
5346 * By setting count=-1, this can be used internally to force searching
5347 * for the prefix used in the last search.
5349 static KT_KEY_FN(gl_history_search_forward)
5352 * In vi mode, switch to command mode, since the user is very
5353 * likely to want to move around newly recalled lines.
5355 gl_vi_command_mode(gl);
5357 * Record the key sequence number of this search action.
5359 gl->last_search = gl->keyseq_count;
5361 * If a prefix search isn't already in progress, replace the search
5362 * prefix to the string that precedes the cursor. In vi command mode
5363 * include the character that is under the cursor in the string. If
5364 * count<0 keep the previous search prefix regardless, so as to force
5365 * a repeat search even if the last command wasn't a history command.
5367 if(count >= 0 && !_glh_search_active(gl->glh) &&
5368 _glh_search_prefix(gl->glh, gl->line, gl->buff_curpos +
5369 (gl->editor==GL_VI_MODE && gl->ntotal>0))) {
5370 _err_record_msg(gl->err, _glh_last_error(gl->glh), END_ERR_MSG);
5371 return 1;
5374 * Search forwards for the next matching line.
5376 if(_glh_find_forwards(gl->glh, gl->line, gl->linelen+1) == NULL)
5377 return 0;
5379 * Accomodate the new contents of gl->line[].
5381 gl_update_buffer(gl);
5383 * Arrange for the cursor to be placed at the end of the new line.
5385 gl->buff_curpos = gl->ntotal;
5387 * Erase and display the new line.
5389 gl_queue_redisplay(gl);
5390 return 0;
5393 /*.......................................................................
5394 * This is the action function that recalls the next line in the
5395 * history buffer who's prefix matches that specified in an earlier call
5396 * to gl_history_search_backward() or gl_history_search_forward().
5398 static KT_KEY_FN(gl_history_re_search_forward)
5400 return gl_history_search_forward(gl, -1, NULL);
5403 #ifdef HIDE_FILE_SYSTEM
5404 /*.......................................................................
5405 * The following function is used as the default completion handler when
5406 * the filesystem is to be hidden. It simply reports no completions.
5408 static CPL_MATCH_FN(gl_no_completions)
5410 return 0;
5412 #endif
5414 /*.......................................................................
5415 * This is the tab completion function that completes the filename that
5416 * precedes the cursor position. Its callback data argument must be a
5417 * pointer to a GlCplCallback containing the completion callback function
5418 * and its callback data, or NULL to use the builtin filename completer.
5420 static KT_KEY_FN(gl_complete_word)
5422 CplMatches *matches; /* The possible completions */
5423 int suffix_len; /* The length of the completion extension */
5424 int cont_len; /* The length of any continuation suffix */
5425 int nextra; /* The number of characters being added to the */
5426 /* total length of the line. */
5427 int buff_pos; /* The buffer index at which the completion is */
5428 /* to be inserted. */
5429 int waserr = 0; /* True after errors */
5431 * Get the container of the completion callback and its callback data.
5433 GlCplCallback *cb = data ? (GlCplCallback *) data : &gl->cplfn;
5435 * In vi command mode, switch to append mode so that the character under
5436 * the cursor is included in the completion (otherwise people can't
5437 * complete at the end of the line).
5439 if(gl->vi.command && gl_vi_append(gl, 0, NULL))
5440 return 1;
5442 * Get the cursor position at which the completion is to be inserted.
5444 buff_pos = gl->buff_curpos;
5446 * Perform the completion.
5448 matches = cpl_complete_word(gl->cpl, gl->line, gl->buff_curpos, cb->data,
5449 cb->fn);
5451 * No matching completions?
5453 if(!matches) {
5454 waserr = gl_print_info(gl, cpl_last_error(gl->cpl), GL_END_INFO);
5456 * Are there any completions?
5458 } else if(matches->nmatch >= 1) {
5460 * If there any ambiguous matches, report them, starting on a new line.
5462 if(matches->nmatch > 1 && gl->echo) {
5463 if(_gl_normal_io(gl) ||
5464 _cpl_output_completions(matches, gl_write_fn, gl, gl->ncolumn))
5465 waserr = 1;
5468 * Get the length of the suffix and any continuation suffix to add to it.
5470 suffix_len = strlen(matches->suffix);
5471 cont_len = strlen(matches->cont_suffix);
5473 * If there is an unambiguous match, and the continuation suffix ends in
5474 * a newline, strip that newline and arrange to have getline return
5475 * after this action function returns.
5477 if(matches->nmatch==1 && cont_len > 0 &&
5478 matches->cont_suffix[cont_len - 1] == '\n') {
5479 cont_len--;
5480 if(gl_newline(gl, 1, NULL))
5481 waserr = 1;
5484 * Work out the number of characters that are to be added.
5486 nextra = suffix_len + cont_len;
5488 * Is there anything to be added?
5490 if(!waserr && nextra) {
5492 * Will there be space for the expansion in the line buffer?
5494 if(gl->ntotal + nextra < gl->linelen) {
5496 * Make room to insert the filename extension.
5498 gl_make_gap_in_buffer(gl, gl->buff_curpos, nextra);
5500 * Insert the filename extension.
5502 gl_buffer_string(gl, matches->suffix, suffix_len, gl->buff_curpos);
5504 * Add the terminating characters.
5506 gl_buffer_string(gl, matches->cont_suffix, cont_len,
5507 gl->buff_curpos + suffix_len);
5509 * Place the cursor position at the end of the completion.
5511 gl->buff_curpos += nextra;
5513 * If we don't have to redisplay the whole line, redisplay the part
5514 * of the line which follows the original cursor position, and place
5515 * the cursor at the end of the completion.
5517 if(gl->displayed) {
5518 if(gl_truncate_display(gl) ||
5519 gl_print_string(gl, gl->line + buff_pos, '\0') ||
5520 gl_place_cursor(gl, gl->buff_curpos))
5521 waserr = 1;
5523 } else {
5524 (void) gl_print_info(gl,
5525 "Insufficient room in line for file completion.",
5526 GL_END_INFO);
5527 waserr = 1;
5532 * If any output had to be written to the terminal, then editing will
5533 * have been suspended, make sure that we are back in raw line editing
5534 * mode before returning.
5536 if(_gl_raw_io(gl, 1))
5537 waserr = 1;
5538 return 0;
5541 #ifndef HIDE_FILE_SYSTEM
5542 /*.......................................................................
5543 * This is the function that expands the filename that precedes the
5544 * cursor position. It expands ~user/ expressions, $envvar expressions,
5545 * and wildcards.
5547 static KT_KEY_FN(gl_expand_filename)
5549 char *start_path; /* The pointer to the start of the pathname in */
5550 /* gl->line[]. */
5551 FileExpansion *result; /* The results of the filename expansion */
5552 int pathlen; /* The length of the pathname being expanded */
5553 int length; /* The number of characters needed to display the */
5554 /* expanded files. */
5555 int nextra; /* The number of characters to be added */
5556 int i,j;
5558 * In vi command mode, switch to append mode so that the character under
5559 * the cursor is included in the completion (otherwise people can't
5560 * complete at the end of the line).
5562 if(gl->vi.command && gl_vi_append(gl, 0, NULL))
5563 return 1;
5565 * Locate the start of the filename that precedes the cursor position.
5567 start_path = _pu_start_of_path(gl->line, gl->buff_curpos);
5568 if(!start_path)
5569 return 1;
5571 * Get the length of the string that is to be expanded.
5573 pathlen = gl->buff_curpos - (start_path - gl->line);
5575 * Attempt to expand it.
5577 result = ef_expand_file(gl->ef, start_path, pathlen);
5579 * If there was an error, report the error on a new line.
5581 if(!result)
5582 return gl_print_info(gl, ef_last_error(gl->ef), GL_END_INFO);
5584 * If no files matched, report this as well.
5586 if(result->nfile == 0 || !result->exists)
5587 return gl_print_info(gl, "No files match.", GL_END_INFO);
5589 * If in vi command mode, preserve the current line for potential use by
5590 * vi-undo.
5592 gl_save_for_undo(gl);
5594 * Work out how much space we will need to display all of the matching
5595 * filenames, taking account of the space that we need to place between
5596 * them, and the number of additional '\' characters needed to escape
5597 * spaces, tabs and backslash characters in the individual filenames.
5599 length = 0;
5600 for(i=0; i<result->nfile; i++) {
5601 char *file = result->files[i];
5602 while(*file) {
5603 int c = *file++;
5604 switch(c) {
5605 case ' ': case '\t': case '\\': case '*': case '?': case '[':
5606 length++; /* Count extra backslash characters */
5608 length++; /* Count the character itself */
5610 length++; /* Count the space that follows each filename */
5613 * Work out the number of characters that are to be added.
5615 nextra = length - pathlen;
5617 * Will there be space for the expansion in the line buffer?
5619 if(gl->ntotal + nextra >= gl->linelen) {
5620 return gl_print_info(gl, "Insufficient room in line for file expansion.",
5621 GL_END_INFO);
5622 } else {
5624 * Do we need to move the part of the line that followed the unexpanded
5625 * filename?
5627 if(nextra > 0) {
5628 gl_make_gap_in_buffer(gl, gl->buff_curpos, nextra);
5629 } else if(nextra < 0) {
5630 gl->buff_curpos += nextra;
5631 gl_remove_from_buffer(gl, gl->buff_curpos, -nextra);
5634 * Insert the filenames, separated by spaces, and with internal spaces,
5635 * tabs and backslashes escaped with backslashes.
5637 for(i=0,j=start_path - gl->line; i<result->nfile; i++) {
5638 char *file = result->files[i];
5639 while(*file) {
5640 int c = *file++;
5641 switch(c) {
5642 case ' ': case '\t': case '\\': case '*': case '?': case '[':
5643 gl_buffer_char(gl, '\\', j++);
5645 gl_buffer_char(gl, c, j++);
5647 gl_buffer_char(gl, ' ', j++);
5651 * Redisplay the part of the line which follows the start of
5652 * the original filename.
5654 if(gl_place_cursor(gl, start_path - gl->line) ||
5655 gl_truncate_display(gl) ||
5656 gl_print_string(gl, start_path, start_path[length]))
5657 return 1;
5659 * Move the cursor to the end of the expansion.
5661 return gl_place_cursor(gl, (start_path - gl->line) + length);
5663 #endif
5665 #ifndef HIDE_FILE_SYSTEM
5666 /*.......................................................................
5667 * This is the action function that lists glob expansions of the
5668 * filename that precedes the cursor position. It expands ~user/
5669 * expressions, $envvar expressions, and wildcards.
5671 static KT_KEY_FN(gl_list_glob)
5673 char *start_path; /* The pointer to the start of the pathname in */
5674 /* gl->line[]. */
5675 FileExpansion *result; /* The results of the filename expansion */
5676 int pathlen; /* The length of the pathname being expanded */
5678 * Locate the start of the filename that precedes the cursor position.
5680 start_path = _pu_start_of_path(gl->line, gl->buff_curpos);
5681 if(!start_path)
5682 return 1;
5684 * Get the length of the string that is to be expanded.
5686 pathlen = gl->buff_curpos - (start_path - gl->line);
5688 * Attempt to expand it.
5690 result = ef_expand_file(gl->ef, start_path, pathlen);
5692 * If there was an error, report it.
5694 if(!result) {
5695 return gl_print_info(gl, ef_last_error(gl->ef), GL_END_INFO);
5697 * If no files matched, report this as well.
5699 } else if(result->nfile == 0 || !result->exists) {
5700 return gl_print_info(gl, "No files match.", GL_END_INFO);
5702 * List the matching expansions.
5704 } else if(gl->echo) {
5705 if(gl_start_newline(gl, 1) ||
5706 _ef_output_expansions(result, gl_write_fn, gl, gl->ncolumn))
5707 return 1;
5708 gl_queue_redisplay(gl);
5710 return 0;
5712 #endif
5714 /*.......................................................................
5715 * Return non-zero if a character should be considered a part of a word.
5717 * Input:
5718 * c int The character to be tested.
5719 * Output:
5720 * return int True if the character should be considered part of a word.
5722 static int gl_is_word_char(int c)
5724 return isalnum((int)(unsigned char)c) || strchr(GL_WORD_CHARS, c) != NULL;
5727 /*.......................................................................
5728 * Override the builtin file-completion callback that is bound to the
5729 * "complete_word" action function.
5731 * Input:
5732 * gl GetLine * The resource object of the command-line input
5733 * module.
5734 * data void * This is passed to match_fn() whenever it is
5735 * called. It could, for example, point to a
5736 * symbol table where match_fn() could look
5737 * for possible completions.
5738 * match_fn CplMatchFn * The function that will identify the prefix
5739 * to be completed from the input line, and
5740 * report matching symbols.
5741 * Output:
5742 * return int 0 - OK.
5743 * 1 - Error.
5745 int gl_customize_completion(GetLine *gl, void *data, CplMatchFn *match_fn)
5747 sigset_t oldset; /* The signals that were blocked on entry to this function */
5749 * Check the arguments.
5751 if(!gl || !match_fn) {
5752 if(gl)
5753 _err_record_msg(gl->err, "NULL argument", END_ERR_MSG);
5754 errno = EINVAL;
5755 return 1;
5758 * Temporarily block all signals.
5760 gl_mask_signals(gl, &oldset);
5762 * Record the new completion function and its callback data.
5764 gl->cplfn.fn = match_fn;
5765 gl->cplfn.data = data;
5767 * Restore the process signal mask before returning.
5769 gl_unmask_signals(gl, &oldset);
5770 return 0;
5773 /*.......................................................................
5774 * Change the terminal (or stream) that getline interacts with.
5776 * Input:
5777 * gl GetLine * The resource object of the command-line input
5778 * module.
5779 * input_fp FILE * The stdio stream to read from.
5780 * output_fp FILE * The stdio stream to write to.
5781 * term char * The terminal type. This can be NULL if
5782 * either or both of input_fp and output_fp don't
5783 * refer to a terminal. Otherwise it should refer
5784 * to an entry in the terminal information database.
5785 * Output:
5786 * return int 0 - OK.
5787 * 1 - Error.
5789 int gl_change_terminal(GetLine *gl, FILE *input_fp, FILE *output_fp,
5790 const char *term)
5792 sigset_t oldset; /* The signals that were blocked on entry to this function */
5793 int status; /* The return status of _gl_change_terminal() */
5795 * Check the arguments.
5797 if(!gl) {
5798 errno = EINVAL;
5799 return 1;
5802 * Block all signals.
5804 if(gl_mask_signals(gl, &oldset))
5805 return 1;
5807 * Execute the private body of the function while signals are blocked.
5809 status = _gl_change_terminal(gl, input_fp, output_fp, term);
5811 * Restore the process signal mask.
5813 gl_unmask_signals(gl, &oldset);
5814 return status;
5817 /*.......................................................................
5818 * This is the private body of the gl_change_terminal() function. It
5819 * assumes that the caller has checked its arguments and blocked the
5820 * delivery of signals.
5822 static int _gl_change_terminal(GetLine *gl, FILE *input_fp, FILE *output_fp,
5823 const char *term)
5825 int is_term = 0; /* True if both input_fd and output_fd are associated */
5826 /* with a terminal. */
5828 * Require that input_fp and output_fp both be valid.
5830 if(!input_fp || !output_fp) {
5831 gl_print_info(gl, "Can't change terminal. Bad input/output stream(s).",
5832 GL_END_INFO);
5833 return 1;
5836 * Are we displacing an existing terminal (as opposed to setting the
5837 * initial terminal)?
5839 if(gl->input_fd >= 0) {
5841 * Make sure to leave the previous terminal in a usable state.
5843 if(_gl_normal_io(gl))
5844 return 1;
5846 * Remove the displaced terminal from the list of fds to watch.
5848 #ifdef HAVE_SELECT
5849 FD_CLR(gl->input_fd, &gl->rfds);
5850 #endif
5853 * Record the file descriptors and streams.
5855 gl->input_fp = input_fp;
5856 gl->input_fd = fileno(input_fp);
5857 gl->output_fp = output_fp;
5858 gl->output_fd = fileno(output_fp);
5860 * If needed, expand the record of the maximum file-descriptor that might
5861 * need to be monitored with select().
5863 #ifdef HAVE_SELECT
5864 if(gl->input_fd > gl->max_fd)
5865 gl->max_fd = gl->input_fd;
5866 #endif
5868 * Disable terminal interaction until we have enough info to interact
5869 * with the terminal.
5871 gl->is_term = 0;
5873 * For terminal editing, we need both output_fd and input_fd to refer to
5874 * a terminal. While we can't verify that they both point to the same
5875 * terminal, we can verify that they point to terminals.
5877 is_term = isatty(gl->input_fd) && isatty(gl->output_fd);
5879 * If we are interacting with a terminal and no terminal type has been
5880 * specified, treat it as a generic ANSI terminal.
5882 if(is_term && !term)
5883 term = "ansi";
5885 * Make a copy of the terminal type string.
5887 if(term != gl->term) {
5889 * Delete any old terminal type string.
5891 if(gl->term) {
5892 free(gl->term);
5893 gl->term = NULL;
5896 * Make a copy of the new terminal-type string, if any.
5898 if(term) {
5899 size_t termsz = strlen(term)+1;
5901 gl->term = (char *) malloc(termsz);
5902 if(gl->term)
5903 strlcpy(gl->term, term, termsz);
5907 * Clear any terminal-specific key bindings that were taken from the
5908 * settings of the last terminal.
5910 _kt_clear_bindings(gl->bindings, KTB_TERM);
5912 * If we have a terminal install new bindings for it.
5914 if(is_term) {
5916 * Get the current settings of the terminal.
5918 if(tcgetattr(gl->input_fd, &gl->oldattr)) {
5919 _err_record_msg(gl->err, "tcgetattr error", END_ERR_MSG);
5920 return 1;
5923 * If we don't set this now, gl_control_strings() won't know
5924 * that it is talking to a terminal.
5926 gl->is_term = 1;
5928 * Lookup the terminal control string and size information.
5930 if(gl_control_strings(gl, term)) {
5931 gl->is_term = 0;
5932 return 1;
5935 * Bind terminal-specific keys.
5937 if(gl_bind_terminal_keys(gl))
5938 return 1;
5941 * Assume that the caller has given us a terminal in a sane state.
5943 gl->io_mode = GL_NORMAL_MODE;
5945 * Switch into the currently configured I/O mode.
5947 if(_gl_io_mode(gl, gl->io_mode))
5948 return 1;
5949 return 0;
5952 /*.......................................................................
5953 * Set up terminal-specific key bindings.
5955 * Input:
5956 * gl GetLine * The resource object of the command-line input
5957 * module.
5958 * Output:
5959 * return int 0 - OK.
5960 * 1 - Error.
5962 static int gl_bind_terminal_keys(GetLine *gl)
5965 * Install key-bindings for the special terminal characters.
5967 if(gl_bind_control_char(gl, KTB_TERM, gl->oldattr.c_cc[VINTR],
5968 "user-interrupt") ||
5969 gl_bind_control_char(gl, KTB_TERM, gl->oldattr.c_cc[VQUIT], "abort") ||
5970 gl_bind_control_char(gl, KTB_TERM, gl->oldattr.c_cc[VSUSP], "suspend"))
5971 return 1;
5973 * In vi-mode, arrange for the above characters to be seen in command
5974 * mode.
5976 if(gl->editor == GL_VI_MODE) {
5977 if(gl_bind_control_char(gl, KTB_TERM, MAKE_META(gl->oldattr.c_cc[VINTR]),
5978 "user-interrupt") ||
5979 gl_bind_control_char(gl, KTB_TERM, MAKE_META(gl->oldattr.c_cc[VQUIT]),
5980 "abort") ||
5981 gl_bind_control_char(gl, KTB_TERM, MAKE_META(gl->oldattr.c_cc[VSUSP]),
5982 "suspend"))
5983 return 1;
5986 * Non-universal special keys.
5988 #ifdef VLNEXT
5989 if(gl_bind_control_char(gl, KTB_TERM, gl->oldattr.c_cc[VLNEXT],
5990 "literal-next"))
5991 return 1;
5992 #else
5993 if(_kt_set_keybinding(gl->bindings, KTB_TERM, "^V", "literal-next")) {
5994 _err_record_msg(gl->err, _kt_last_error(gl->bindings), END_ERR_MSG);
5995 return 1;
5997 #endif
5999 * Bind action functions to the terminal-specific arrow keys
6000 * looked up by gl_control_strings().
6002 if(_gl_bind_arrow_keys(gl))
6003 return 1;
6004 return 0;
6007 /*.......................................................................
6008 * This function is normally bound to control-D. When it is invoked within
6009 * a line it deletes the character which follows the cursor. When invoked
6010 * at the end of the line it lists possible file completions, and when
6011 * invoked on an empty line it causes gl_get_line() to return EOF. This
6012 * function emulates the one that is normally bound to control-D by tcsh.
6014 static KT_KEY_FN(gl_del_char_or_list_or_eof)
6017 * If we have an empty line arrange to return EOF.
6019 if(gl->ntotal < 1) {
6020 gl_record_status(gl, GLR_EOF, 0);
6021 return 1;
6023 * If we are at the end of the line list possible completions.
6025 } else if(gl->buff_curpos >= gl->ntotal) {
6026 return gl_list_completions(gl, 1, NULL);
6028 * Within the line delete the character that follows the cursor.
6030 } else {
6032 * If in vi command mode, first preserve the current line for potential use
6033 * by vi-undo.
6035 gl_save_for_undo(gl);
6037 * Delete 'count' characters.
6039 return gl_forward_delete_char(gl, count, NULL);
6043 /*.......................................................................
6044 * This function is normally bound to control-D in vi mode. When it is
6045 * invoked within a line it lists possible file completions, and when
6046 * invoked on an empty line it causes gl_get_line() to return EOF. This
6047 * function emulates the one that is normally bound to control-D by tcsh.
6049 static KT_KEY_FN(gl_list_or_eof)
6052 * If we have an empty line arrange to return EOF.
6054 if(gl->ntotal < 1) {
6055 gl_record_status(gl, GLR_EOF, 0);
6056 return 1;
6058 * Otherwise list possible completions.
6060 } else {
6061 return gl_list_completions(gl, 1, NULL);
6065 /*.......................................................................
6066 * List possible completions of the word that precedes the cursor. The
6067 * callback data argument must either be NULL to select the default
6068 * file completion callback, or be a GlCplCallback object containing the
6069 * completion callback function to call.
6071 static KT_KEY_FN(gl_list_completions)
6073 int waserr = 0; /* True after errors */
6075 * Get the container of the completion callback and its callback data.
6077 GlCplCallback *cb = data ? (GlCplCallback *) data : &gl->cplfn;
6079 * Get the list of possible completions.
6081 CplMatches *matches = cpl_complete_word(gl->cpl, gl->line, gl->buff_curpos,
6082 cb->data, cb->fn);
6084 * No matching completions?
6086 if(!matches) {
6087 waserr = gl_print_info(gl, cpl_last_error(gl->cpl), GL_END_INFO);
6089 * List the matches.
6091 } else if(matches->nmatch > 0 && gl->echo) {
6092 if(_gl_normal_io(gl) ||
6093 _cpl_output_completions(matches, gl_write_fn, gl, gl->ncolumn))
6094 waserr = 1;
6097 * If any output had to be written to the terminal, then editing will
6098 * have been suspended, make sure that we are back in raw line editing
6099 * mode before returning.
6101 if(_gl_raw_io(gl, 1))
6102 waserr = 1;
6103 return waserr;
6106 /*.......................................................................
6107 * Where the user has used the symbolic arrow-key names to specify
6108 * arrow key bindings, bind the specified action functions to the default
6109 * and terminal specific arrow key sequences.
6111 * Input:
6112 * gl GetLine * The getline resource object.
6113 * Output:
6114 * return int 0 - OK.
6115 * 1 - Error.
6117 static int _gl_bind_arrow_keys(GetLine *gl)
6120 * Process each of the arrow keys.
6122 if(_gl_rebind_arrow_key(gl, "up", gl->u_arrow, "^[[A", "^[OA") ||
6123 _gl_rebind_arrow_key(gl, "down", gl->d_arrow, "^[[B", "^[OB") ||
6124 _gl_rebind_arrow_key(gl, "left", gl->l_arrow, "^[[D", "^[OD") ||
6125 _gl_rebind_arrow_key(gl, "right", gl->r_arrow, "^[[C", "^[OC"))
6126 return 1;
6127 return 0;
6130 /*.......................................................................
6131 * Lookup the action function of a symbolic arrow-key binding, and bind
6132 * it to the terminal-specific and default arrow-key sequences. Note that
6133 * we don't trust the terminal-specified key sequences to be correct.
6134 * The main reason for this is that on some machines the xterm terminfo
6135 * entry is for hardware X-terminals, rather than xterm terminal emulators
6136 * and the two terminal types emit different character sequences when the
6137 * their cursor keys are pressed. As a result we also supply a couple
6138 * of default key sequences.
6140 * Input:
6141 * gl GetLine * The resource object of gl_get_line().
6142 * name char * The symbolic name of the arrow key.
6143 * term_seq char * The terminal-specific arrow-key sequence.
6144 * def_seq1 char * The first default arrow-key sequence.
6145 * def_seq2 char * The second arrow-key sequence.
6146 * Output:
6147 * return int 0 - OK.
6148 * 1 - Error.
6150 static int _gl_rebind_arrow_key(GetLine *gl, const char *name,
6151 const char *term_seq, const char *def_seq1,
6152 const char *def_seq2)
6154 KeySym *keysym; /* The binding-table entry matching the arrow-key name */
6155 int nsym; /* The number of ambiguous matches */
6157 * Lookup the key binding for the symbolic name of the arrow key. This
6158 * will either be the default action, or a user provided one.
6160 if(_kt_lookup_keybinding(gl->bindings, name, strlen(name), &keysym, &nsym)
6161 == KT_EXACT_MATCH) {
6163 * Get the action function.
6165 KtAction *action = keysym->actions + keysym->binder;
6166 KtKeyFn *fn = action->fn;
6167 void *data = action->data;
6169 * Bind this to each of the specified key sequences.
6171 if((term_seq &&
6172 _kt_set_keyfn(gl->bindings, KTB_TERM, term_seq, fn, data)) ||
6173 (def_seq1 &&
6174 _kt_set_keyfn(gl->bindings, KTB_NORM, def_seq1, fn, data)) ||
6175 (def_seq2 &&
6176 _kt_set_keyfn(gl->bindings, KTB_NORM, def_seq2, fn, data))) {
6177 _err_record_msg(gl->err, _kt_last_error(gl->bindings), END_ERR_MSG);
6178 return 1;
6181 return 0;
6184 /*.......................................................................
6185 * Read getline configuration information from a given file.
6187 * Input:
6188 * gl GetLine * The getline resource object.
6189 * filename const char * The name of the file to read configuration
6190 * information from. The contents of this file
6191 * are as described in the gl_get_line(3) man
6192 * page for the default ~/.teclarc configuration
6193 * file.
6194 * who KtBinder Who bindings are to be installed for.
6195 * Output:
6196 * return int 0 - OK.
6197 * 1 - Irrecoverable error.
6199 static int _gl_read_config_file(GetLine *gl, const char *filename, KtBinder who)
6202 * If filesystem access is to be excluded, configuration files can't
6203 * be read.
6205 #ifdef WITHOUT_FILE_SYSTEM
6206 _err_record_msg(gl->err,
6207 "Can't read configuration files without filesystem access",
6208 END_ERR_MSG);
6209 errno = EINVAL;
6210 return 1;
6211 #else
6212 FileExpansion *expansion; /* The expansion of the filename */
6213 FILE *fp; /* The opened file */
6214 int waserr = 0; /* True if an error occurred while reading */
6215 int lineno = 1; /* The line number being processed */
6217 * Check the arguments.
6219 if(!gl || !filename) {
6220 if(gl)
6221 _err_record_msg(gl->err, "NULL argument(s)", END_ERR_MSG);
6222 errno = EINVAL;
6223 return 1;
6226 * Expand the filename.
6228 expansion = ef_expand_file(gl->ef, filename, -1);
6229 if(!expansion) {
6230 gl_print_info(gl, "Unable to expand ", filename, " (",
6231 ef_last_error(gl->ef), ").", GL_END_INFO);
6232 return 1;
6235 * Attempt to open the file.
6237 fp = fopen(expansion->files[0], "r");
6239 * It isn't an error for there to be no configuration file.
6241 if(!fp)
6242 return 0;
6244 * Parse the contents of the file.
6246 while(!waserr && !feof(fp))
6247 waserr = _gl_parse_config_line(gl, fp, glc_file_getc, filename, who,
6248 &lineno);
6250 * Bind action functions to the terminal-specific arrow keys.
6252 if(_gl_bind_arrow_keys(gl))
6253 return 1;
6255 * Clean up.
6257 (void) fclose(fp);
6258 return waserr;
6259 #endif
6262 /*.......................................................................
6263 * Read GetLine configuration information from a string. The contents of
6264 * the string are the same as those described in the gl_get_line(3)
6265 * man page for the contents of the ~/.teclarc configuration file.
6267 static int _gl_read_config_string(GetLine *gl, const char *buffer, KtBinder who)
6269 const char *bptr; /* A pointer into buffer[] */
6270 int waserr = 0; /* True if an error occurred while reading */
6271 int lineno = 1; /* The line number being processed */
6273 * Check the arguments.
6275 if(!gl || !buffer) {
6276 if(gl)
6277 _err_record_msg(gl->err, "NULL argument(s)", END_ERR_MSG);
6278 errno = EINVAL;
6279 return 1;
6282 * Get a pointer to the start of the buffer.
6284 bptr = buffer;
6286 * Parse the contents of the buffer.
6288 while(!waserr && *bptr)
6289 waserr = _gl_parse_config_line(gl, &bptr, glc_buff_getc, "", who, &lineno);
6291 * Bind action functions to the terminal-specific arrow keys.
6293 if(_gl_bind_arrow_keys(gl))
6294 return 1;
6295 return waserr;
6298 /*.......................................................................
6299 * Parse the next line of a getline configuration file.
6301 * Input:
6302 * gl GetLine * The getline resource object.
6303 * stream void * The pointer representing the stream to be read
6304 * by getc_fn().
6305 * getc_fn GlcGetcFn * A callback function which when called with
6306 * 'stream' as its argument, returns the next
6307 * unread character from the stream.
6308 * origin const char * The name of the entity being read (eg. a
6309 * file name).
6310 * who KtBinder Who bindings are to be installed for.
6311 * Input/Output:
6312 * lineno int * The line number being processed is to be
6313 * maintained in *lineno.
6314 * Output:
6315 * return int 0 - OK.
6316 * 1 - Irrecoverable error.
6318 static int _gl_parse_config_line(GetLine *gl, void *stream, GlcGetcFn *getc_fn,
6319 const char *origin, KtBinder who, int *lineno)
6321 char buffer[GL_CONF_BUFLEN+1]; /* The input line buffer */
6322 char *argv[GL_CONF_MAXARG]; /* The argument list */
6323 int argc = 0; /* The number of arguments in argv[] */
6324 int c; /* A character from the file */
6325 int escaped = 0; /* True if the next character is escaped */
6326 int i;
6328 * Skip spaces and tabs.
6330 do c = getc_fn(stream); while(c==' ' || c=='\t');
6332 * Comments extend to the end of the line.
6334 if(c=='#')
6335 do c = getc_fn(stream); while(c != '\n' && c != EOF);
6337 * Ignore empty lines.
6339 if(c=='\n' || c==EOF) {
6340 (*lineno)++;
6341 return 0;
6344 * Record the buffer location of the start of the first argument.
6346 argv[argc] = buffer;
6348 * Read the rest of the line, stopping early if a comment is seen, or
6349 * the buffer overflows, and replacing sequences of spaces with a
6350 * '\0', and recording the thus terminated string as an argument.
6352 i = 0;
6353 while(i<GL_CONF_BUFLEN) {
6355 * Did we hit the end of the latest argument?
6357 if(c==EOF || (!escaped && (c==' ' || c=='\n' || c=='\t' || c=='#'))) {
6359 * Terminate the argument.
6361 buffer[i++] = '\0';
6362 argc++;
6364 * Skip spaces and tabs.
6366 while(c==' ' || c=='\t')
6367 c = getc_fn(stream);
6369 * If we hit the end of the line, or the start of a comment, exit the loop.
6371 if(c==EOF || c=='\n' || c=='#')
6372 break;
6374 * Start recording the next argument.
6376 if(argc >= GL_CONF_MAXARG) {
6377 gl_report_config_error(gl, origin, *lineno, "Too many arguments.");
6378 do c = getc_fn(stream); while(c!='\n' && c!=EOF); /* Skip past eol */
6379 return 0;
6381 argv[argc] = buffer + i;
6383 * The next character was preceded by spaces, so it isn't escaped.
6385 escaped = 0;
6386 } else {
6388 * If we hit an unescaped backslash, this means that we should arrange
6389 * to treat the next character like a simple alphabetical character.
6391 if(c=='\\' && !escaped) {
6392 escaped = 1;
6394 * Splice lines where the newline is escaped.
6396 } else if(c=='\n' && escaped) {
6397 (*lineno)++;
6399 * Record a normal character, preserving any preceding backslash.
6401 } else {
6402 if(escaped)
6403 buffer[i++] = '\\';
6404 if(i>=GL_CONF_BUFLEN)
6405 break;
6406 escaped = 0;
6407 buffer[i++] = c;
6410 * Get the next character.
6412 c = getc_fn(stream);
6416 * Did the buffer overflow?
6418 if(i>=GL_CONF_BUFLEN) {
6419 gl_report_config_error(gl, origin, *lineno, "Line too long.");
6420 return 0;
6423 * The first argument should be a command name.
6425 if(strcmp(argv[0], "bind") == 0) {
6426 const char *action = NULL; /* A NULL action removes a keybinding */
6427 const char *keyseq = NULL;
6428 switch(argc) {
6429 case 3:
6430 action = argv[2];
6431 case 2: /* Note the intentional fallthrough */
6432 keyseq = argv[1];
6434 * Attempt to record the new keybinding.
6436 if(_kt_set_keybinding(gl->bindings, who, keyseq, action)) {
6437 gl_report_config_error(gl, origin, *lineno,
6438 _kt_last_error(gl->bindings));
6440 break;
6441 default:
6442 gl_report_config_error(gl, origin, *lineno, "Wrong number of arguments.");
6444 } else if(strcmp(argv[0], "edit-mode") == 0) {
6445 if(argc == 2 && strcmp(argv[1], "emacs") == 0) {
6446 gl_change_editor(gl, GL_EMACS_MODE);
6447 } else if(argc == 2 && strcmp(argv[1], "vi") == 0) {
6448 gl_change_editor(gl, GL_VI_MODE);
6449 } else if(argc == 2 && strcmp(argv[1], "none") == 0) {
6450 gl_change_editor(gl, GL_NO_EDITOR);
6451 } else {
6452 gl_report_config_error(gl, origin, *lineno,
6453 "The argument of editor should be vi or emacs.");
6455 } else if(strcmp(argv[0], "nobeep") == 0) {
6456 gl->silence_bell = 1;
6457 } else {
6458 gl_report_config_error(gl, origin, *lineno, "Unknown command name.");
6461 * Skip any trailing comment.
6463 while(c != '\n' && c != EOF)
6464 c = getc_fn(stream);
6465 (*lineno)++;
6466 return 0;
6469 /*.......................................................................
6470 * This is a private function of _gl_parse_config_line() which prints
6471 * out an error message about the contents of the line, prefixed by the
6472 * name of the origin of the line and its line number.
6474 * Input:
6475 * gl GetLine * The resource object of gl_get_line().
6476 * origin const char * The name of the entity being read (eg. a
6477 * file name).
6478 * lineno int The line number at which the error occurred.
6479 * errmsg const char * The error message.
6480 * Output:
6481 * return int 0 - OK.
6482 * 1 - Error.
6484 static int gl_report_config_error(GetLine *gl, const char *origin, int lineno,
6485 const char *errmsg)
6487 char lnum[20]; /* A buffer in which to render a single integer */
6489 * Convert the line number into a string.
6491 snprintf(lnum, sizeof(lnum), "%d", lineno);
6493 * Have the string printed on the terminal.
6495 return gl_print_info(gl, origin, ":", lnum, ": ", errmsg, GL_END_INFO);
6498 /*.......................................................................
6499 * This is the _gl_parse_config_line() callback function which reads the
6500 * next character from a configuration file.
6502 static GLC_GETC_FN(glc_file_getc)
6504 return fgetc((FILE *) stream);
6507 /*.......................................................................
6508 * This is the _gl_parse_config_line() callback function which reads the
6509 * next character from a buffer. Its stream argument is a pointer to a
6510 * variable which is, in turn, a pointer into the buffer being read from.
6512 static GLC_GETC_FN(glc_buff_getc)
6514 const char **lptr = (char const **) stream;
6515 return **lptr ? *(*lptr)++ : EOF;
6518 #ifndef HIDE_FILE_SYSTEM
6519 /*.......................................................................
6520 * When this action is triggered, it arranges to temporarily read command
6521 * lines from the regular file whos name precedes the cursor.
6522 * The current line is first discarded.
6524 static KT_KEY_FN(gl_read_from_file)
6526 char *start_path; /* The pointer to the start of the pathname in */
6527 /* gl->line[]. */
6528 FileExpansion *result; /* The results of the filename expansion */
6529 int pathlen; /* The length of the pathname being expanded */
6531 * Locate the start of the filename that precedes the cursor position.
6533 start_path = _pu_start_of_path(gl->line, gl->buff_curpos);
6534 if(!start_path)
6535 return 1;
6537 * Get the length of the pathname string.
6539 pathlen = gl->buff_curpos - (start_path - gl->line);
6541 * Attempt to expand the pathname.
6543 result = ef_expand_file(gl->ef, start_path, pathlen);
6545 * If there was an error, report the error on a new line.
6547 if(!result) {
6548 return gl_print_info(gl, ef_last_error(gl->ef), GL_END_INFO);
6550 * If no files matched, report this as well.
6552 } else if(result->nfile == 0 || !result->exists) {
6553 return gl_print_info(gl, "No files match.", GL_END_INFO);
6555 * Complain if more than one file matches.
6557 } else if(result->nfile > 1) {
6558 return gl_print_info(gl, "More than one file matches.", GL_END_INFO);
6560 * Disallow input from anything but normal files. In principle we could
6561 * also support input from named pipes. Terminal files would be a problem
6562 * since we wouldn't know the terminal type, and other types of files
6563 * might cause the library to lock up.
6565 } else if(!_pu_path_is_file(result->files[0])) {
6566 return gl_print_info(gl, "Not a normal file.", GL_END_INFO);
6567 } else {
6569 * Attempt to open and install the specified file for reading.
6571 gl->file_fp = fopen(result->files[0], "r");
6572 if(!gl->file_fp) {
6573 return gl_print_info(gl, "Unable to open: ", result->files[0],
6574 GL_END_INFO);
6577 * If needed, expand the record of the maximum file-descriptor that might
6578 * need to be monitored with select().
6580 #ifdef HAVE_SELECT
6581 if(fileno(gl->file_fp) > gl->max_fd)
6582 gl->max_fd = fileno(gl->file_fp);
6583 #endif
6585 * Is non-blocking I/O needed?
6587 if(gl->raw_mode && gl->io_mode==GL_SERVER_MODE &&
6588 gl_nonblocking_io(gl, fileno(gl->file_fp))) {
6589 gl_revert_input(gl);
6590 return gl_print_info(gl, "Can't read file %s with non-blocking I/O",
6591 result->files[0]);
6594 * Inform the user what is happening.
6596 if(gl_print_info(gl, "<Taking input from ", result->files[0], ">",
6597 GL_END_INFO))
6598 return 1;
6600 return 0;
6602 #endif
6604 /*.......................................................................
6605 * Close any temporary file that is being used for input.
6607 * Input:
6608 * gl GetLine * The getline resource object.
6610 static void gl_revert_input(GetLine *gl)
6612 if(gl->file_fp)
6613 fclose(gl->file_fp);
6614 gl->file_fp = NULL;
6615 gl->endline = 1;
6618 /*.......................................................................
6619 * This is the action function that recalls the oldest line in the
6620 * history buffer.
6622 static KT_KEY_FN(gl_beginning_of_history)
6625 * In vi mode, switch to command mode, since the user is very
6626 * likely to want to move around newly recalled lines.
6628 gl_vi_command_mode(gl);
6630 * Forget any previous recall session.
6632 gl->preload_id = 0;
6634 * Record the key sequence number of this search action.
6636 gl->last_search = gl->keyseq_count;
6638 * Recall the next oldest line in the history list.
6640 if(_glh_oldest_line(gl->glh, gl->line, gl->linelen+1) == NULL)
6641 return 0;
6643 * Accomodate the new contents of gl->line[].
6645 gl_update_buffer(gl);
6647 * Arrange to have the cursor placed at the end of the new line.
6649 gl->buff_curpos = gl->ntotal;
6651 * Erase and display the new line.
6653 gl_queue_redisplay(gl);
6654 return 0;
6657 /*.......................................................................
6658 * If a history session is currently in progress, this action function
6659 * recalls the line that was being edited when the session started. If
6660 * no history session is in progress, it does nothing.
6662 static KT_KEY_FN(gl_end_of_history)
6665 * In vi mode, switch to command mode, since the user is very
6666 * likely to want to move around newly recalled lines.
6668 gl_vi_command_mode(gl);
6670 * Forget any previous recall session.
6672 gl->preload_id = 0;
6674 * Record the key sequence number of this search action.
6676 gl->last_search = gl->keyseq_count;
6678 * Recall the next oldest line in the history list.
6680 if(_glh_current_line(gl->glh, gl->line, gl->linelen+1) == NULL)
6681 return 0;
6683 * Accomodate the new contents of gl->line[].
6685 gl_update_buffer(gl);
6687 * Arrange to have the cursor placed at the end of the new line.
6689 gl->buff_curpos = gl->ntotal;
6691 * Erase and display the new line.
6693 gl_queue_redisplay(gl);
6694 return 0;
6697 /*.......................................................................
6698 * This action function is treated specially, in that its count argument
6699 * is set to the end keystroke of the keysequence that activated it.
6700 * It accumulates a numeric argument, adding one digit on each call in
6701 * which the last keystroke was a numeric digit.
6703 static KT_KEY_FN(gl_digit_argument)
6706 * Was the last keystroke a digit?
6708 int is_digit = isdigit((int)(unsigned char) count);
6710 * In vi command mode, a lone '0' means goto-start-of-line.
6712 if(gl->vi.command && gl->number < 0 && count == '0')
6713 return gl_beginning_of_line(gl, count, NULL);
6715 * Are we starting to accumulate a new number?
6717 if(gl->number < 0 || !is_digit)
6718 gl->number = 0;
6720 * Was the last keystroke a digit?
6722 if(is_digit) {
6724 * Read the numeric value of the digit, without assuming ASCII.
6726 int n;
6727 char s[2]; s[0] = count; s[1] = '\0';
6728 n = atoi(s);
6730 * Append the new digit.
6732 gl->number = gl->number * 10 + n;
6734 return 0;
6737 /*.......................................................................
6738 * The newline action function sets gl->endline to tell
6739 * gl_get_input_line() that the line is now complete.
6741 static KT_KEY_FN(gl_newline)
6743 GlhLineID id; /* The last history line recalled while entering this line */
6745 * Flag the line as ended.
6747 gl->endline = 1;
6749 * Record the next position in the history buffer, for potential
6750 * recall by an action function on the next call to gl_get_line().
6752 id = _glh_line_id(gl->glh, 1);
6753 if(id)
6754 gl->preload_id = id;
6755 return 0;
6758 /*.......................................................................
6759 * The 'repeat' action function sets gl->endline to tell
6760 * gl_get_input_line() that the line is now complete, and records the
6761 * ID of the next history line in gl->preload_id so that the next call
6762 * to gl_get_input_line() will preload the line with that history line.
6764 static KT_KEY_FN(gl_repeat_history)
6766 gl->endline = 1;
6767 gl->preload_id = _glh_line_id(gl->glh, 1);
6768 gl->preload_history = 1;
6769 return 0;
6772 /*.......................................................................
6773 * Flush unwritten characters to the terminal.
6775 * Input:
6776 * gl GetLine * The getline resource object.
6777 * Output:
6778 * return int 0 - OK.
6779 * 1 - Either an error occured, or the output
6780 * blocked and non-blocking I/O is being used.
6781 * See gl->rtn_status for details.
6783 static int gl_flush_output(GetLine *gl)
6786 * Record the fact that we are about to write to the terminal.
6788 gl->pending_io = GLP_WRITE;
6790 * Attempt to flush the output to the terminal.
6792 errno = 0;
6793 switch(_glq_flush_queue(gl->cq, gl->flush_fn, gl)) {
6794 case GLQ_FLUSH_DONE:
6795 return gl->redisplay && !gl->postpone && gl_redisplay(gl, 1, NULL);
6796 break;
6797 case GLQ_FLUSH_AGAIN: /* Output blocked */
6798 gl_record_status(gl, GLR_BLOCKED, BLOCKED_ERRNO);
6799 return 1;
6800 break;
6801 default: /* Abort the line if an error occurs */
6802 gl_record_status(gl, errno==EINTR ? GLR_SIGNAL : GLR_ERROR, errno);
6803 return 1;
6804 break;
6808 /*.......................................................................
6809 * This is the callback which _glq_flush_queue() uses to write buffered
6810 * characters to the terminal.
6812 static GL_WRITE_FN(gl_flush_terminal)
6814 int ndone = 0; /* The number of characters written so far */
6816 * Get the line-editor resource object.
6818 GetLine *gl = (GetLine *) data;
6820 * Transfer the latest array of characters to stdio.
6822 while(ndone < n) {
6823 int nnew = write(gl->output_fd, s, n-ndone);
6825 * If the write was successful, add to the recorded number of bytes
6826 * that have now been written.
6828 if(nnew > 0) {
6829 ndone += nnew;
6831 * If a signal interrupted the call, restart the write(), since all of
6832 * the signals that gl_get_line() has been told to watch for are
6833 * currently blocked.
6835 } else if(errno == EINTR) {
6836 continue;
6838 * If we managed to write something before an I/O error occurred, or
6839 * output blocked before anything was written, report the number of
6840 * bytes that were successfully written before this happened.
6842 } else if(ndone > 0
6843 #if defined(EAGAIN)
6844 || errno==EAGAIN
6845 #endif
6846 #if defined(EWOULDBLOCK)
6847 || errno==EWOULDBLOCK
6848 #endif
6850 return ndone;
6853 * To get here, an error must have occurred before anything new could
6854 * be written.
6856 } else {
6857 return -1;
6861 * To get here, we must have successfully written the number of
6862 * bytes that was specified.
6864 return n;
6867 /*.......................................................................
6868 * Change the style of editing to emulate a given editor.
6870 * Input:
6871 * gl GetLine * The getline resource object.
6872 * editor GlEditor The type of editor to emulate.
6873 * Output:
6874 * return int 0 - OK.
6875 * 1 - Error.
6877 static int gl_change_editor(GetLine *gl, GlEditor editor)
6880 * Install the default key-bindings of the requested editor.
6882 switch(editor) {
6883 case GL_EMACS_MODE:
6884 _kt_clear_bindings(gl->bindings, KTB_NORM);
6885 _kt_clear_bindings(gl->bindings, KTB_TERM);
6886 (void) _kt_add_bindings(gl->bindings, KTB_NORM, gl_emacs_bindings,
6887 sizeof(gl_emacs_bindings)/sizeof(gl_emacs_bindings[0]));
6888 break;
6889 case GL_VI_MODE:
6890 _kt_clear_bindings(gl->bindings, KTB_NORM);
6891 _kt_clear_bindings(gl->bindings, KTB_TERM);
6892 (void) _kt_add_bindings(gl->bindings, KTB_NORM, gl_vi_bindings,
6893 sizeof(gl_vi_bindings)/sizeof(gl_vi_bindings[0]));
6894 break;
6895 case GL_NO_EDITOR:
6896 break;
6897 default:
6898 _err_record_msg(gl->err, "Unknown editor", END_ERR_MSG);
6899 errno = EINVAL;
6900 return 1;
6903 * Record the new editing mode.
6905 gl->editor = editor;
6906 gl->vi.command = 0; /* Start in input mode */
6907 gl->insert_curpos = 0;
6909 * Reinstate terminal-specific bindings.
6911 if(gl->editor != GL_NO_EDITOR && gl->input_fp)
6912 (void) gl_bind_terminal_keys(gl);
6913 return 0;
6916 /*.......................................................................
6917 * This is an action function that switches to editing using emacs bindings
6919 static KT_KEY_FN(gl_emacs_editing_mode)
6921 return gl_change_editor(gl, GL_EMACS_MODE);
6924 /*.......................................................................
6925 * This is an action function that switches to editing using vi bindings
6927 static KT_KEY_FN(gl_vi_editing_mode)
6929 return gl_change_editor(gl, GL_VI_MODE);
6932 /*.......................................................................
6933 * This is the action function that switches to insert mode.
6935 static KT_KEY_FN(gl_vi_insert)
6938 * If in vi command mode, preserve the current line for potential
6939 * use by vi-undo.
6941 gl_save_for_undo(gl);
6943 * Switch to vi insert mode.
6945 gl->insert = 1;
6946 gl->vi.command = 0;
6947 gl->insert_curpos = gl->buff_curpos;
6948 return 0;
6951 /*.......................................................................
6952 * This is an action function that switches to overwrite mode.
6954 static KT_KEY_FN(gl_vi_overwrite)
6957 * If in vi command mode, preserve the current line for potential
6958 * use by vi-undo.
6960 gl_save_for_undo(gl);
6962 * Switch to vi overwrite mode.
6964 gl->insert = 0;
6965 gl->vi.command = 0;
6966 gl->insert_curpos = gl->buff_curpos;
6967 return 0;
6970 /*.......................................................................
6971 * This action function toggles the case of the character under the
6972 * cursor.
6974 static KT_KEY_FN(gl_change_case)
6976 int i;
6978 * Keep a record of the current insert mode and the cursor position.
6980 int insert = gl->insert;
6982 * If in vi command mode, preserve the current line for potential
6983 * use by vi-undo.
6985 gl_save_for_undo(gl);
6987 * We want to overwrite the modified word.
6989 gl->insert = 0;
6991 * Toggle the case of 'count' characters.
6993 for(i=0; i<count && gl->buff_curpos < gl->ntotal; i++) {
6994 char *cptr = gl->line + gl->buff_curpos++;
6996 * Convert the character to upper case?
6998 if(islower((int)(unsigned char) *cptr))
6999 gl_buffer_char(gl, toupper((int) *cptr), cptr - gl->line);
7000 else if(isupper((int)(unsigned char) *cptr))
7001 gl_buffer_char(gl, tolower((int) *cptr), cptr - gl->line);
7003 * Write the possibly modified character back. Note that for non-modified
7004 * characters we want to do this as well, so as to advance the cursor.
7006 if(gl_print_char(gl, *cptr, cptr[1]))
7007 return 1;
7010 * Restore the insertion mode.
7012 gl->insert = insert;
7013 return gl_place_cursor(gl, gl->buff_curpos); /* bounds check */
7016 /*.......................................................................
7017 * This is the action function which implements the vi-style action which
7018 * moves the cursor to the start of the line, then switches to insert mode.
7020 static KT_KEY_FN(gl_vi_insert_at_bol)
7022 gl_save_for_undo(gl);
7023 return gl_beginning_of_line(gl, 0, NULL) ||
7024 gl_vi_insert(gl, 0, NULL);
7028 /*.......................................................................
7029 * This is the action function which implements the vi-style action which
7030 * moves the cursor to the end of the line, then switches to insert mode
7031 * to allow text to be appended to the line.
7033 static KT_KEY_FN(gl_vi_append_at_eol)
7035 gl_save_for_undo(gl);
7036 gl->vi.command = 0; /* Allow cursor at EOL */
7037 return gl_end_of_line(gl, 0, NULL) ||
7038 gl_vi_insert(gl, 0, NULL);
7041 /*.......................................................................
7042 * This is the action function which implements the vi-style action which
7043 * moves the cursor to right one then switches to insert mode, thus
7044 * allowing text to be appended after the next character.
7046 static KT_KEY_FN(gl_vi_append)
7048 gl_save_for_undo(gl);
7049 gl->vi.command = 0; /* Allow cursor at EOL */
7050 return gl_cursor_right(gl, 1, NULL) ||
7051 gl_vi_insert(gl, 0, NULL);
7054 /*.......................................................................
7055 * This action function moves the cursor to the column specified by the
7056 * numeric argument. Column indexes start at 1.
7058 static KT_KEY_FN(gl_goto_column)
7060 return gl_place_cursor(gl, count - 1);
7063 /*.......................................................................
7064 * Starting with the character under the cursor, replace 'count'
7065 * characters with the next character that the user types.
7067 static KT_KEY_FN(gl_vi_replace_char)
7069 char c; /* The replacement character */
7070 int i;
7072 * Keep a record of the current insert mode.
7074 int insert = gl->insert;
7076 * Get the replacement character.
7078 if(gl->vi.repeat.active) {
7079 c = gl->vi.repeat.input_char;
7080 } else {
7081 if(gl_read_terminal(gl, 1, &c))
7082 return 1;
7083 gl->vi.repeat.input_char = c;
7086 * Are there 'count' characters to be replaced?
7088 if(gl->ntotal - gl->buff_curpos >= count) {
7090 * If in vi command mode, preserve the current line for potential
7091 * use by vi-undo.
7093 gl_save_for_undo(gl);
7095 * Temporarily switch to overwrite mode.
7097 gl->insert = 0;
7099 * Overwrite the current character plus count-1 subsequent characters
7100 * with the replacement character.
7102 for(i=0; i<count; i++)
7103 gl_add_char_to_line(gl, c);
7105 * Restore the original insert/overwrite mode.
7107 gl->insert = insert;
7109 return gl_place_cursor(gl, gl->buff_curpos); /* bounds check */
7112 /*.......................................................................
7113 * This is an action function which changes all characters between the
7114 * current cursor position and the end of the line.
7116 static KT_KEY_FN(gl_vi_change_rest_of_line)
7118 gl_save_for_undo(gl);
7119 gl->vi.command = 0; /* Allow cursor at EOL */
7120 return gl_kill_line(gl, count, NULL) || gl_vi_insert(gl, 0, NULL);
7123 /*.......................................................................
7124 * This is an action function which changes all characters between the
7125 * start of the line and the current cursor position.
7127 static KT_KEY_FN(gl_vi_change_to_bol)
7129 return gl_backward_kill_line(gl,count,NULL) || gl_vi_insert(gl,0,NULL);
7132 /*.......................................................................
7133 * This is an action function which deletes the entire contents of the
7134 * current line and switches to insert mode.
7136 static KT_KEY_FN(gl_vi_change_line)
7138 return gl_delete_line(gl,count,NULL) || gl_vi_insert(gl,0,NULL);
7141 /*.......................................................................
7142 * Starting from the cursor position and looking towards the end of the
7143 * line, copy 'count' characters to the cut buffer.
7145 static KT_KEY_FN(gl_forward_copy_char)
7148 * Limit the count to the number of characters available.
7150 if(gl->buff_curpos + count >= gl->ntotal)
7151 count = gl->ntotal - gl->buff_curpos;
7152 if(count < 0)
7153 count = 0;
7155 * Copy the characters to the cut buffer.
7157 memcpy(gl->cutbuf, gl->line + gl->buff_curpos, count);
7158 gl->cutbuf[count] = '\0';
7159 return 0;
7162 /*.......................................................................
7163 * Starting from the character before the cursor position and looking
7164 * backwards towards the start of the line, copy 'count' characters to
7165 * the cut buffer.
7167 static KT_KEY_FN(gl_backward_copy_char)
7170 * Limit the count to the number of characters available.
7172 if(count > gl->buff_curpos)
7173 count = gl->buff_curpos;
7174 if(count < 0)
7175 count = 0;
7176 gl_place_cursor(gl, gl->buff_curpos - count);
7178 * Copy the characters to the cut buffer.
7180 memcpy(gl->cutbuf, gl->line + gl->buff_curpos, count);
7181 gl->cutbuf[count] = '\0';
7182 return 0;
7185 /*.......................................................................
7186 * Starting from the cursor position copy to the specified column into the
7187 * cut buffer.
7189 static KT_KEY_FN(gl_copy_to_column)
7191 if (--count >= gl->buff_curpos)
7192 return gl_forward_copy_char(gl, count - gl->buff_curpos, NULL);
7193 else
7194 return gl_backward_copy_char(gl, gl->buff_curpos - count, NULL);
7197 /*.......................................................................
7198 * Starting from the cursor position copy characters up to a matching
7199 * parenthesis into the cut buffer.
7201 static KT_KEY_FN(gl_copy_to_parenthesis)
7203 int curpos = gl_index_of_matching_paren(gl);
7204 if(curpos >= 0) {
7205 gl_save_for_undo(gl);
7206 if(curpos >= gl->buff_curpos)
7207 return gl_forward_copy_char(gl, curpos - gl->buff_curpos + 1, NULL);
7208 else
7209 return gl_backward_copy_char(gl, ++gl->buff_curpos - curpos + 1, NULL);
7211 return 0;
7214 /*.......................................................................
7215 * Starting from the cursor position copy the rest of the line into the
7216 * cut buffer.
7218 static KT_KEY_FN(gl_copy_rest_of_line)
7221 * Copy the characters to the cut buffer.
7223 memcpy(gl->cutbuf, gl->line + gl->buff_curpos, gl->ntotal - gl->buff_curpos);
7224 gl->cutbuf[gl->ntotal - gl->buff_curpos] = '\0';
7225 return 0;
7228 /*.......................................................................
7229 * Copy from the beginning of the line to the cursor position into the
7230 * cut buffer.
7232 static KT_KEY_FN(gl_copy_to_bol)
7235 * Copy the characters to the cut buffer.
7237 memcpy(gl->cutbuf, gl->line, gl->buff_curpos);
7238 gl->cutbuf[gl->buff_curpos] = '\0';
7239 gl_place_cursor(gl, 0);
7240 return 0;
7243 /*.......................................................................
7244 * Copy the entire line into the cut buffer.
7246 static KT_KEY_FN(gl_copy_line)
7249 * Copy the characters to the cut buffer.
7251 memcpy(gl->cutbuf, gl->line, gl->ntotal);
7252 gl->cutbuf[gl->ntotal] = '\0';
7253 return 0;
7256 /*.......................................................................
7257 * Search forwards for the next character that the user enters.
7259 static KT_KEY_FN(gl_forward_find_char)
7261 int pos = gl_find_char(gl, count, 1, 1, '\0');
7262 return pos >= 0 && gl_place_cursor(gl, pos);
7265 /*.......................................................................
7266 * Search backwards for the next character that the user enters.
7268 static KT_KEY_FN(gl_backward_find_char)
7270 int pos = gl_find_char(gl, count, 0, 1, '\0');
7271 return pos >= 0 && gl_place_cursor(gl, pos);
7274 /*.......................................................................
7275 * Search forwards for the next character that the user enters. Move up to,
7276 * but not onto, the found character.
7278 static KT_KEY_FN(gl_forward_to_char)
7280 int pos = gl_find_char(gl, count, 1, 0, '\0');
7281 return pos >= 0 && gl_place_cursor(gl, pos);
7284 /*.......................................................................
7285 * Search backwards for the next character that the user enters. Move back to,
7286 * but not onto, the found character.
7288 static KT_KEY_FN(gl_backward_to_char)
7290 int pos = gl_find_char(gl, count, 0, 0, '\0');
7291 return pos >= 0 && gl_place_cursor(gl, pos);
7294 /*.......................................................................
7295 * Searching in a given direction, return the index of a given (or
7296 * read) character in the input line, or the character that precedes
7297 * it in the specified search direction. Return -1 if not found.
7299 * Input:
7300 * gl GetLine * The getline resource object.
7301 * count int The number of times to search.
7302 * forward int True if searching forward.
7303 * onto int True if the search should end on top of the
7304 * character, false if the search should stop
7305 * one character before the character in the
7306 * specified search direction.
7307 * c char The character to be sought, or '\0' if the
7308 * character should be read from the user.
7309 * Output:
7310 * return int The index of the character in gl->line[], or
7311 * -1 if not found.
7313 static int gl_find_char(GetLine *gl, int count, int forward, int onto, char c)
7315 int pos; /* The index reached in searching the input line */
7316 int i;
7318 * Get a character from the user?
7320 if(!c) {
7322 * If we are in the process of repeating a previous change command, substitute
7323 * the last find character.
7325 if(gl->vi.repeat.active) {
7326 c = gl->vi.find_char;
7327 } else {
7328 if(gl_read_terminal(gl, 1, &c))
7329 return -1;
7331 * Record the details of the new search, for use by repeat finds.
7333 gl->vi.find_forward = forward;
7334 gl->vi.find_onto = onto;
7335 gl->vi.find_char = c;
7339 * Which direction should we search?
7341 if(forward) {
7343 * Search forwards 'count' times for the character, starting with the
7344 * character that follows the cursor.
7346 for(i=0, pos=gl->buff_curpos; i<count && pos < gl->ntotal; i++) {
7348 * Advance past the last match (or past the current cursor position
7349 * on the first search).
7351 pos++;
7353 * Search for the next instance of c.
7355 for( ; pos<gl->ntotal && c!=gl->line[pos]; pos++)
7359 * If the character was found and we have been requested to return the
7360 * position of the character that precedes the desired character, then
7361 * we have gone one character too far.
7363 if(!onto && pos<gl->ntotal)
7364 pos--;
7365 } else {
7367 * Search backwards 'count' times for the character, starting with the
7368 * character that precedes the cursor.
7370 for(i=0, pos=gl->buff_curpos; i<count && pos >= gl->insert_curpos; i++) {
7372 * Step back one from the last match (or from the current cursor
7373 * position on the first search).
7375 pos--;
7377 * Search for the next instance of c.
7379 for( ; pos>=gl->insert_curpos && c!=gl->line[pos]; pos--)
7383 * If the character was found and we have been requested to return the
7384 * position of the character that precedes the desired character, then
7385 * we have gone one character too far.
7387 if(!onto && pos>=gl->insert_curpos)
7388 pos++;
7391 * If found, return the cursor position of the count'th match.
7392 * Otherwise ring the terminal bell.
7394 if(pos >= gl->insert_curpos && pos < gl->ntotal) {
7395 return pos;
7396 } else {
7397 (void) gl_ring_bell(gl, 1, NULL);
7398 return -1;
7402 /*.......................................................................
7403 * Repeat the last character search in the same direction as the last
7404 * search.
7406 static KT_KEY_FN(gl_repeat_find_char)
7408 int pos = gl->vi.find_char ?
7409 gl_find_char(gl, count, gl->vi.find_forward, gl->vi.find_onto,
7410 gl->vi.find_char) : -1;
7411 return pos >= 0 && gl_place_cursor(gl, pos);
7414 /*.......................................................................
7415 * Repeat the last character search in the opposite direction as the last
7416 * search.
7418 static KT_KEY_FN(gl_invert_refind_char)
7420 int pos = gl->vi.find_char ?
7421 gl_find_char(gl, count, !gl->vi.find_forward, gl->vi.find_onto,
7422 gl->vi.find_char) : -1;
7423 return pos >= 0 && gl_place_cursor(gl, pos);
7426 /*.......................................................................
7427 * Search forward from the current position of the cursor for 'count'
7428 * word endings, returning the index of the last one found, or the end of
7429 * the line if there were less than 'count' words.
7431 * Input:
7432 * gl GetLine * The getline resource object.
7433 * n int The number of word boundaries to search for.
7434 * Output:
7435 * return int The buffer index of the located position.
7437 static int gl_nth_word_end_forward(GetLine *gl, int n)
7439 int bufpos; /* The buffer index being checked. */
7440 int i;
7442 * In order to guarantee forward motion to the next word ending,
7443 * we need to start from one position to the right of the cursor
7444 * position, since this may already be at the end of a word.
7446 bufpos = gl->buff_curpos + 1;
7448 * If we are at the end of the line, return the index of the last
7449 * real character on the line. Note that this will be -1 if the line
7450 * is empty.
7452 if(bufpos >= gl->ntotal)
7453 return gl->ntotal - 1;
7455 * Search 'n' times, unless the end of the input line is reached first.
7457 for(i=0; i<n && bufpos<gl->ntotal; i++) {
7459 * If we are not already within a word, skip to the start of the next word.
7461 for( ; bufpos<gl->ntotal && !gl_is_word_char((int)gl->line[bufpos]);
7462 bufpos++)
7465 * Find the end of the next word.
7467 for( ; bufpos<gl->ntotal && gl_is_word_char((int)gl->line[bufpos]);
7468 bufpos++)
7472 * We will have overshot.
7474 return bufpos > 0 ? bufpos-1 : bufpos;
7477 /*.......................................................................
7478 * Search forward from the current position of the cursor for 'count'
7479 * word starts, returning the index of the last one found, or the end of
7480 * the line if there were less than 'count' words.
7482 * Input:
7483 * gl GetLine * The getline resource object.
7484 * n int The number of word boundaries to search for.
7485 * Output:
7486 * return int The buffer index of the located position.
7488 static int gl_nth_word_start_forward(GetLine *gl, int n)
7490 int bufpos; /* The buffer index being checked. */
7491 int i;
7493 * Get the current cursor position.
7495 bufpos = gl->buff_curpos;
7497 * Search 'n' times, unless the end of the input line is reached first.
7499 for(i=0; i<n && bufpos<gl->ntotal; i++) {
7501 * Find the end of the current word.
7503 for( ; bufpos<gl->ntotal && gl_is_word_char((int)gl->line[bufpos]);
7504 bufpos++)
7507 * Skip to the start of the next word.
7509 for( ; bufpos<gl->ntotal && !gl_is_word_char((int)gl->line[bufpos]);
7510 bufpos++)
7513 return bufpos;
7516 /*.......................................................................
7517 * Search backward from the current position of the cursor for 'count'
7518 * word starts, returning the index of the last one found, or the start
7519 * of the line if there were less than 'count' words.
7521 * Input:
7522 * gl GetLine * The getline resource object.
7523 * n int The number of word boundaries to search for.
7524 * Output:
7525 * return int The buffer index of the located position.
7527 static int gl_nth_word_start_backward(GetLine *gl, int n)
7529 int bufpos; /* The buffer index being checked. */
7530 int i;
7532 * Get the current cursor position.
7534 bufpos = gl->buff_curpos;
7536 * Search 'n' times, unless the beginning of the input line (or vi insertion
7537 * point) is reached first.
7539 for(i=0; i<n && bufpos > gl->insert_curpos; i++) {
7541 * Starting one character back from the last search, so as not to keep
7542 * settling on the same word-start, search backwards until finding a
7543 * word character.
7545 while(--bufpos >= gl->insert_curpos &&
7546 !gl_is_word_char((int)gl->line[bufpos]))
7549 * Find the start of the word.
7551 while(--bufpos >= gl->insert_curpos &&
7552 gl_is_word_char((int)gl->line[bufpos]))
7555 * We will have gone one character too far.
7557 bufpos++;
7559 return bufpos >= gl->insert_curpos ? bufpos : gl->insert_curpos;
7562 /*.......................................................................
7563 * Copy one or more words into the cut buffer without moving the cursor
7564 * or deleting text.
7566 static KT_KEY_FN(gl_forward_copy_word)
7569 * Find the location of the count'th start or end of a word
7570 * after the cursor, depending on whether in emacs or vi mode.
7572 int next = gl->editor == GL_EMACS_MODE ?
7573 gl_nth_word_end_forward(gl, count) :
7574 gl_nth_word_start_forward(gl, count);
7576 * How many characters are to be copied into the cut buffer?
7578 int n = next - gl->buff_curpos;
7580 * Copy the specified segment and terminate the string.
7582 memcpy(gl->cutbuf, gl->line + gl->buff_curpos, n);
7583 gl->cutbuf[n] = '\0';
7584 return 0;
7587 /*.......................................................................
7588 * Copy one or more words preceding the cursor into the cut buffer,
7589 * without moving the cursor or deleting text.
7591 static KT_KEY_FN(gl_backward_copy_word)
7594 * Find the location of the count'th start of word before the cursor.
7596 int next = gl_nth_word_start_backward(gl, count);
7598 * How many characters are to be copied into the cut buffer?
7600 int n = gl->buff_curpos - next;
7601 gl_place_cursor(gl, next);
7603 * Copy the specified segment and terminate the string.
7605 memcpy(gl->cutbuf, gl->line + next, n);
7606 gl->cutbuf[n] = '\0';
7607 return 0;
7610 /*.......................................................................
7611 * Copy the characters between the cursor and the count'th instance of
7612 * a specified character in the input line, into the cut buffer.
7614 * Input:
7615 * gl GetLine * The getline resource object.
7616 * count int The number of times to search.
7617 * c char The character to be searched for, or '\0' if
7618 * the character should be read from the user.
7619 * forward int True if searching forward.
7620 * onto int True if the search should end on top of the
7621 * character, false if the search should stop
7622 * one character before the character in the
7623 * specified search direction.
7624 * Output:
7625 * return int 0 - OK.
7626 * 1 - Error.
7629 static int gl_copy_find(GetLine *gl, int count, char c, int forward, int onto)
7631 int n; /* The number of characters in the cut buffer */
7633 * Search for the character, and abort the operation if not found.
7635 int pos = gl_find_char(gl, count, forward, onto, c);
7636 if(pos < 0)
7637 return 0;
7639 * Copy the specified segment.
7641 if(forward) {
7642 n = pos + 1 - gl->buff_curpos;
7643 memcpy(gl->cutbuf, gl->line + gl->buff_curpos, n);
7644 } else {
7645 n = gl->buff_curpos - pos;
7646 memcpy(gl->cutbuf, gl->line + pos, n);
7647 if(gl->editor == GL_VI_MODE)
7648 gl_place_cursor(gl, pos);
7651 * Terminate the copy.
7653 gl->cutbuf[n] = '\0';
7654 return 0;
7657 /*.......................................................................
7658 * Copy a section up to and including a specified character into the cut
7659 * buffer without moving the cursor or deleting text.
7661 static KT_KEY_FN(gl_forward_copy_find)
7663 return gl_copy_find(gl, count, '\0', 1, 1);
7666 /*.......................................................................
7667 * Copy a section back to and including a specified character into the cut
7668 * buffer without moving the cursor or deleting text.
7670 static KT_KEY_FN(gl_backward_copy_find)
7672 return gl_copy_find(gl, count, '\0', 0, 1);
7675 /*.......................................................................
7676 * Copy a section up to and not including a specified character into the cut
7677 * buffer without moving the cursor or deleting text.
7679 static KT_KEY_FN(gl_forward_copy_to)
7681 return gl_copy_find(gl, count, '\0', 1, 0);
7684 /*.......................................................................
7685 * Copy a section back to and not including a specified character into the cut
7686 * buffer without moving the cursor or deleting text.
7688 static KT_KEY_FN(gl_backward_copy_to)
7690 return gl_copy_find(gl, count, '\0', 0, 0);
7693 /*.......................................................................
7694 * Copy to a character specified in a previous search into the cut
7695 * buffer without moving the cursor or deleting text.
7697 static KT_KEY_FN(gl_copy_refind)
7699 return gl_copy_find(gl, count, gl->vi.find_char, gl->vi.find_forward,
7700 gl->vi.find_onto);
7703 /*.......................................................................
7704 * Copy to a character specified in a previous search, but in the opposite
7705 * direction, into the cut buffer without moving the cursor or deleting text.
7707 static KT_KEY_FN(gl_copy_invert_refind)
7709 return gl_copy_find(gl, count, gl->vi.find_char, !gl->vi.find_forward,
7710 gl->vi.find_onto);
7713 /*.......................................................................
7714 * Set the position of the cursor in the line input buffer and the
7715 * terminal.
7717 * Input:
7718 * gl GetLine * The getline resource object.
7719 * buff_curpos int The new buffer cursor position.
7720 * Output:
7721 * return int 0 - OK.
7722 * 1 - Error.
7724 static int gl_place_cursor(GetLine *gl, int buff_curpos)
7727 * Don't allow the cursor position to go out of the bounds of the input
7728 * line.
7730 if(buff_curpos >= gl->ntotal)
7731 buff_curpos = gl->vi.command ? gl->ntotal-1 : gl->ntotal;
7732 if(buff_curpos < 0)
7733 buff_curpos = 0;
7735 * Record the new buffer position.
7737 gl->buff_curpos = buff_curpos;
7739 * Move the terminal cursor to the corresponding character.
7741 return gl_set_term_curpos(gl, gl->prompt_len +
7742 gl_displayed_string_width(gl, gl->line, buff_curpos, gl->prompt_len));
7745 /*.......................................................................
7746 * In vi command mode, this function saves the current line to the
7747 * historical buffer needed by the undo command. In emacs mode it does
7748 * nothing. In order to allow action functions to call other action
7749 * functions, gl_interpret_char() sets gl->vi.undo.saved to 0 before
7750 * invoking an action, and thereafter once any call to this function
7751 * has set it to 1, further calls are ignored.
7753 * Input:
7754 * gl GetLine * The getline resource object.
7756 static void gl_save_for_undo(GetLine *gl)
7758 if(gl->vi.command && !gl->vi.undo.saved) {
7759 strlcpy(gl->vi.undo.line, gl->line, gl->linelen);
7760 gl->vi.undo.buff_curpos = gl->buff_curpos;
7761 gl->vi.undo.ntotal = gl->ntotal;
7762 gl->vi.undo.saved = 1;
7764 if(gl->vi.command && !gl->vi.repeat.saved &&
7765 gl->current_action.fn != gl_vi_repeat_change) {
7766 gl->vi.repeat.action = gl->current_action;
7767 gl->vi.repeat.count = gl->current_count;
7768 gl->vi.repeat.saved = 1;
7770 return;
7773 /*.......................................................................
7774 * In vi mode, restore the line to the way it was before the last command
7775 * mode operation, storing the current line in the buffer so that the
7776 * undo operation itself can subsequently be undone.
7778 static KT_KEY_FN(gl_vi_undo)
7781 * Get pointers into the two lines.
7783 char *undo_ptr = gl->vi.undo.line;
7784 char *line_ptr = gl->line;
7786 * Swap the characters of the two buffers up to the length of the shortest
7787 * line.
7789 while(*undo_ptr && *line_ptr) {
7790 char c = *undo_ptr;
7791 *undo_ptr++ = *line_ptr;
7792 *line_ptr++ = c;
7795 * Copy the rest directly.
7797 if(gl->ntotal > gl->vi.undo.ntotal) {
7798 strlcpy(undo_ptr, line_ptr, gl->linelen);
7799 *line_ptr = '\0';
7800 } else {
7801 strlcpy(line_ptr, undo_ptr, gl->linelen);
7802 *undo_ptr = '\0';
7805 * Record the length of the stored string.
7807 gl->vi.undo.ntotal = gl->ntotal;
7809 * Accomodate the new contents of gl->line[].
7811 gl_update_buffer(gl);
7813 * Set both cursor positions to the leftmost of the saved and current
7814 * cursor positions to emulate what vi does.
7816 if(gl->buff_curpos < gl->vi.undo.buff_curpos)
7817 gl->vi.undo.buff_curpos = gl->buff_curpos;
7818 else
7819 gl->buff_curpos = gl->vi.undo.buff_curpos;
7821 * Since we have bipassed calling gl_save_for_undo(), record repeat
7822 * information inline.
7824 gl->vi.repeat.action.fn = gl_vi_undo;
7825 gl->vi.repeat.action.data = NULL;
7826 gl->vi.repeat.count = 1;
7828 * Display the restored line.
7830 gl_queue_redisplay(gl);
7831 return 0;
7834 /*.......................................................................
7835 * Delete the following word and leave the user in vi insert mode.
7837 static KT_KEY_FN(gl_vi_forward_change_word)
7839 gl_save_for_undo(gl);
7840 gl->vi.command = 0; /* Allow cursor at EOL */
7841 return gl_forward_delete_word(gl, count, NULL) || gl_vi_insert(gl, 0, NULL);
7844 /*.......................................................................
7845 * Delete the preceding word and leave the user in vi insert mode.
7847 static KT_KEY_FN(gl_vi_backward_change_word)
7849 return gl_backward_delete_word(gl, count, NULL) || gl_vi_insert(gl, 0, NULL);
7852 /*.......................................................................
7853 * Delete the following section and leave the user in vi insert mode.
7855 static KT_KEY_FN(gl_vi_forward_change_find)
7857 return gl_delete_find(gl, count, '\0', 1, 1, 1);
7860 /*.......................................................................
7861 * Delete the preceding section and leave the user in vi insert mode.
7863 static KT_KEY_FN(gl_vi_backward_change_find)
7865 return gl_delete_find(gl, count, '\0', 0, 1, 1);
7868 /*.......................................................................
7869 * Delete the following section and leave the user in vi insert mode.
7871 static KT_KEY_FN(gl_vi_forward_change_to)
7873 return gl_delete_find(gl, count, '\0', 1, 0, 1);
7876 /*.......................................................................
7877 * Delete the preceding section and leave the user in vi insert mode.
7879 static KT_KEY_FN(gl_vi_backward_change_to)
7881 return gl_delete_find(gl, count, '\0', 0, 0, 1);
7884 /*.......................................................................
7885 * Delete to a character specified by a previous search and leave the user
7886 * in vi insert mode.
7888 static KT_KEY_FN(gl_vi_change_refind)
7890 return gl_delete_find(gl, count, gl->vi.find_char, gl->vi.find_forward,
7891 gl->vi.find_onto, 1);
7894 /*.......................................................................
7895 * Delete to a character specified by a previous search, but in the opposite
7896 * direction, and leave the user in vi insert mode.
7898 static KT_KEY_FN(gl_vi_change_invert_refind)
7900 return gl_delete_find(gl, count, gl->vi.find_char, !gl->vi.find_forward,
7901 gl->vi.find_onto, 1);
7904 /*.......................................................................
7905 * Delete the following character and leave the user in vi insert mode.
7907 static KT_KEY_FN(gl_vi_forward_change_char)
7909 gl_save_for_undo(gl);
7910 gl->vi.command = 0; /* Allow cursor at EOL */
7911 return gl_delete_chars(gl, count, 1) || gl_vi_insert(gl, 0, NULL);
7914 /*.......................................................................
7915 * Delete the preceding character and leave the user in vi insert mode.
7917 static KT_KEY_FN(gl_vi_backward_change_char)
7919 return gl_backward_delete_char(gl, count, NULL) || gl_vi_insert(gl, 0, NULL);
7922 /*.......................................................................
7923 * Starting from the cursor position change characters to the specified column.
7925 static KT_KEY_FN(gl_vi_change_to_column)
7927 if (--count >= gl->buff_curpos)
7928 return gl_vi_forward_change_char(gl, count - gl->buff_curpos, NULL);
7929 else
7930 return gl_vi_backward_change_char(gl, gl->buff_curpos - count, NULL);
7933 /*.......................................................................
7934 * Starting from the cursor position change characters to a matching
7935 * parenthesis.
7937 static KT_KEY_FN(gl_vi_change_to_parenthesis)
7939 int curpos = gl_index_of_matching_paren(gl);
7940 if(curpos >= 0) {
7941 gl_save_for_undo(gl);
7942 if(curpos >= gl->buff_curpos)
7943 return gl_vi_forward_change_char(gl, curpos - gl->buff_curpos + 1, NULL);
7944 else
7945 return gl_vi_backward_change_char(gl, ++gl->buff_curpos - curpos + 1,
7946 NULL);
7948 return 0;
7951 /*.......................................................................
7952 * If in vi mode, switch to vi command mode.
7954 * Input:
7955 * gl GetLine * The getline resource object.
7957 static void gl_vi_command_mode(GetLine *gl)
7959 if(gl->editor == GL_VI_MODE && !gl->vi.command) {
7960 gl->insert = 1;
7961 gl->vi.command = 1;
7962 gl->vi.repeat.input_curpos = gl->insert_curpos;
7963 gl->vi.repeat.command_curpos = gl->buff_curpos;
7964 gl->insert_curpos = 0; /* unrestrict left motion boundary */
7965 gl_cursor_left(gl, 1, NULL); /* Vi moves 1 left on entering command mode */
7969 /*.......................................................................
7970 * This is an action function which rings the terminal bell.
7972 static KT_KEY_FN(gl_ring_bell)
7974 return gl->silence_bell ? 0 :
7975 gl_print_control_sequence(gl, 1, gl->sound_bell);
7978 /*.......................................................................
7979 * This is the action function which implements the vi-repeat-change
7980 * action.
7982 static KT_KEY_FN(gl_vi_repeat_change)
7984 int status; /* The return status of the repeated action function */
7985 int i;
7987 * Nothing to repeat?
7989 if(!gl->vi.repeat.action.fn)
7990 return gl_ring_bell(gl, 1, NULL);
7992 * Provide a way for action functions to know whether they are being
7993 * called by us.
7995 gl->vi.repeat.active = 1;
7997 * Re-run the recorded function.
7999 status = gl->vi.repeat.action.fn(gl, gl->vi.repeat.count,
8000 gl->vi.repeat.action.data);
8002 * Mark the repeat as completed.
8004 gl->vi.repeat.active = 0;
8006 * Is we are repeating a function that has just switched to input
8007 * mode to allow the user to type, re-enter the text that the user
8008 * previously entered.
8010 if(status==0 && !gl->vi.command) {
8012 * Make sure that the current line has been saved.
8014 gl_save_for_undo(gl);
8016 * Repeat a previous insertion or overwrite?
8018 if(gl->vi.repeat.input_curpos >= 0 &&
8019 gl->vi.repeat.input_curpos <= gl->vi.repeat.command_curpos &&
8020 gl->vi.repeat.command_curpos <= gl->vi.undo.ntotal) {
8022 * Using the current line which is saved in the undo buffer, plus
8023 * the range of characters therein, as recorded by gl_vi_command_mode(),
8024 * add the characters that the user previously entered, to the input
8025 * line.
8027 for(i=gl->vi.repeat.input_curpos; i<gl->vi.repeat.command_curpos; i++) {
8028 if(gl_add_char_to_line(gl, gl->vi.undo.line[i]))
8029 return 1;
8033 * Switch back to command mode, now that the insertion has been repeated.
8035 gl_vi_command_mode(gl);
8037 return status;
8040 /*.......................................................................
8041 * If the cursor is currently over a parenthesis character, return the
8042 * index of its matching parenthesis. If not currently over a parenthesis
8043 * character, return the next close parenthesis character to the right of
8044 * the cursor. If the respective parenthesis character isn't found,
8045 * ring the terminal bell and return -1.
8047 * Input:
8048 * gl GetLine * The getline resource object.
8049 * Output:
8050 * return int Either the index of the matching parenthesis,
8051 * or -1 if not found.
8053 static int gl_index_of_matching_paren(GetLine *gl)
8055 int i;
8057 * List the recognized parentheses, and their matches.
8059 const char *o_paren = "([{";
8060 const char *c_paren = ")]}";
8061 const char *cptr;
8063 * Get the character that is currently under the cursor.
8065 char c = gl->line[gl->buff_curpos];
8067 * If the character under the cursor is an open parenthesis, look forward
8068 * for the matching close parenthesis.
8070 if((cptr=strchr(o_paren, c))) {
8071 char match = c_paren[cptr - o_paren];
8072 int matches_needed = 1;
8073 for(i=gl->buff_curpos+1; i<gl->ntotal; i++) {
8074 if(gl->line[i] == c)
8075 matches_needed++;
8076 else if(gl->line[i] == match && --matches_needed==0)
8077 return i;
8080 * If the character under the cursor is an close parenthesis, look forward
8081 * for the matching open parenthesis.
8083 } else if((cptr=strchr(c_paren, c))) {
8084 char match = o_paren[cptr - c_paren];
8085 int matches_needed = 1;
8086 for(i=gl->buff_curpos-1; i>=0; i--) {
8087 if(gl->line[i] == c)
8088 matches_needed++;
8089 else if(gl->line[i] == match && --matches_needed==0)
8090 return i;
8093 * If not currently over a parenthesis character, search forwards for
8094 * the first close parenthesis (this is what the vi % binding does).
8096 } else {
8097 for(i=gl->buff_curpos+1; i<gl->ntotal; i++)
8098 if(strchr(c_paren, gl->line[i]) != NULL)
8099 return i;
8102 * Not found.
8104 (void) gl_ring_bell(gl, 1, NULL);
8105 return -1;
8108 /*.......................................................................
8109 * If the cursor is currently over a parenthesis character, this action
8110 * function moves the cursor to its matching parenthesis.
8112 static KT_KEY_FN(gl_find_parenthesis)
8114 int curpos = gl_index_of_matching_paren(gl);
8115 if(curpos >= 0)
8116 return gl_place_cursor(gl, curpos);
8117 return 0;
8120 /*.......................................................................
8121 * Handle the receipt of the potential start of a new key-sequence from
8122 * the user.
8124 * Input:
8125 * gl GetLine * The resource object of this library.
8126 * first_char char The first character of the sequence.
8127 * Output:
8128 * return int 0 - OK.
8129 * 1 - Error.
8131 static int gl_interpret_char(GetLine *gl, char first_char)
8133 char keyseq[GL_KEY_MAX+1]; /* A special key sequence being read */
8134 int nkey=0; /* The number of characters in the key sequence */
8135 int count; /* The repeat count of an action function */
8136 int ret; /* The return value of an action function */
8137 int i;
8139 * Get the first character.
8141 char c = first_char;
8143 * If editing is disabled, just add newly entered characters to the
8144 * input line buffer, and watch for the end of the line.
8146 if(gl->editor == GL_NO_EDITOR) {
8147 gl_discard_chars(gl, 1);
8148 if(gl->ntotal >= gl->linelen)
8149 return 0;
8150 if(c == '\n' || c == '\r')
8151 return gl_newline(gl, 1, NULL);
8152 gl_buffer_char(gl, c, gl->ntotal);
8153 return 0;
8156 * If the user is in the process of specifying a repeat count and the
8157 * new character is a digit, increment the repeat count accordingly.
8159 if(gl->number >= 0 && isdigit((int)(unsigned char) c)) {
8160 gl_discard_chars(gl, 1);
8161 return gl_digit_argument(gl, c, NULL);
8163 * In vi command mode, all key-sequences entered need to be
8164 * either implicitly or explicitly prefixed with an escape character.
8166 } else if(gl->vi.command && c != GL_ESC_CHAR) {
8167 keyseq[nkey++] = GL_ESC_CHAR;
8169 * If the first character of the sequence is a printable character,
8170 * then to avoid confusion with the special "up", "down", "left"
8171 * or "right" cursor key bindings, we need to prefix the
8172 * printable character with a backslash escape before looking it up.
8174 } else if(!IS_META_CHAR(c) && !IS_CTRL_CHAR(c)) {
8175 keyseq[nkey++] = '\\';
8178 * Compose a potentially multiple key-sequence in gl->keyseq.
8180 while(nkey < GL_KEY_MAX) {
8181 KtAction *action; /* An action function */
8182 KeySym *keysym; /* The symbol-table entry of a key-sequence */
8183 int nsym; /* The number of ambiguously matching key-sequences */
8185 * If the character is an unprintable meta character, split it
8186 * into two characters, an escape character and the character
8187 * that was modified by the meta key.
8189 if(IS_META_CHAR(c)) {
8190 keyseq[nkey++] = GL_ESC_CHAR;
8191 c = META_TO_CHAR(c);
8192 continue;
8195 * Append the latest character to the key sequence.
8197 keyseq[nkey++] = c;
8199 * When doing vi-style editing, an escape at the beginning of any binding
8200 * switches to command mode.
8202 if(keyseq[0] == GL_ESC_CHAR && !gl->vi.command)
8203 gl_vi_command_mode(gl);
8205 * Lookup the key sequence.
8207 switch(_kt_lookup_keybinding(gl->bindings, keyseq, nkey, &keysym, &nsym)) {
8208 case KT_EXACT_MATCH:
8210 * Get the matching action function.
8212 action = keysym->actions + keysym->binder;
8214 * Get the repeat count, passing the last keystroke if executing the
8215 * digit-argument action.
8217 if(action->fn == gl_digit_argument) {
8218 count = c;
8219 } else {
8220 count = gl->number >= 0 ? gl->number : 1;
8223 * Record the function that is being invoked.
8225 gl->current_action = *action;
8226 gl->current_count = count;
8228 * Mark the current line as not yet preserved for use by the vi undo command.
8230 gl->vi.undo.saved = 0;
8231 gl->vi.repeat.saved = 0;
8233 * Execute the action function. Note the action function can tell
8234 * whether the provided repeat count was defaulted or specified
8235 * explicitly by looking at whether gl->number is -1 or not. If
8236 * it is negative, then no repeat count was specified by the user.
8238 ret = action->fn(gl, count, action->data);
8240 * In server mode, the action will return immediately if it tries to
8241 * read input from the terminal, and no input is currently available.
8242 * If this happens, abort. Note that gl_get_input_line() will rewind
8243 * the read-ahead buffer to allow the next call to redo the function
8244 * from scratch.
8246 if(gl->rtn_status == GLR_BLOCKED && gl->pending_io==GLP_READ)
8247 return 1;
8249 * Discard the now processed characters from the key sequence buffer.
8251 gl_discard_chars(gl, gl->nread);
8253 * If the latest action function wasn't a history action, cancel any
8254 * current history search.
8256 if(gl->last_search != gl->keyseq_count)
8257 _glh_cancel_search(gl->glh);
8259 * Reset the repeat count after running action functions.
8261 if(action->fn != gl_digit_argument)
8262 gl->number = -1;
8263 return ret ? 1 : 0;
8264 break;
8265 case KT_AMBIG_MATCH: /* Ambiguous match - so read the next character */
8266 if(gl_read_terminal(gl, 1, &c))
8267 return 1;
8268 break;
8269 case KT_NO_MATCH:
8271 * If the first character looked like it might be a prefix of a key-sequence
8272 * but it turned out not to be, ring the bell to tell the user that it
8273 * wasn't recognised.
8275 if(keyseq[0] != '\\' && keyseq[0] != '\t') {
8276 gl_ring_bell(gl, 1, NULL);
8277 } else {
8279 * The user typed a single printable character that doesn't match
8280 * the start of any keysequence, so add it to the line in accordance
8281 * with the current repeat count.
8283 count = gl->number >= 0 ? gl->number : 1;
8284 for(i=0; i<count; i++)
8285 gl_add_char_to_line(gl, first_char);
8286 gl->number = -1;
8288 gl_discard_chars(gl, 1);
8289 _glh_cancel_search(gl->glh);
8290 return 0;
8291 break;
8292 case KT_BAD_MATCH:
8293 gl_ring_bell(gl, 1, NULL);
8294 gl_discard_chars(gl, gl->nread);
8295 _glh_cancel_search(gl->glh);
8296 return 1;
8297 break;
8301 * If the key sequence was too long to match, ring the bell, then
8302 * discard the first character, so that the next attempt to match a
8303 * key-sequence continues with the next key press. In practice this
8304 * shouldn't happen, since one isn't allowed to bind action functions
8305 * to keysequences that are longer than GL_KEY_MAX.
8307 gl_ring_bell(gl, 1, NULL);
8308 gl_discard_chars(gl, 1);
8309 return 0;
8312 /*.......................................................................
8313 * Configure the application and/or user-specific behavior of
8314 * gl_get_line().
8316 * Note that calling this function between calling new_GetLine() and
8317 * the first call to gl_get_line(), disables the otherwise automatic
8318 * reading of ~/.teclarc on the first call to gl_get_line().
8320 * Input:
8321 * gl GetLine * The resource object of this library.
8322 * app_string const char * Either NULL, or a string containing one
8323 * or more .teclarc command lines, separated
8324 * by newline characters. This can be used to
8325 * establish an application-specific
8326 * configuration, without the need for an external
8327 * file. This is particularly useful in embedded
8328 * environments where there is no filesystem.
8329 * app_file const char * Either NULL, or the pathname of an
8330 * application-specific .teclarc file. The
8331 * contents of this file, if provided, are
8332 * read after the contents of app_string[].
8333 * user_file const char * Either NULL, or the pathname of a
8334 * user-specific .teclarc file. Except in
8335 * embedded applications, this should
8336 * usually be "~/.teclarc".
8337 * Output:
8338 * return int 0 - OK.
8339 * 1 - Bad argument(s).
8341 int gl_configure_getline(GetLine *gl, const char *app_string,
8342 const char *app_file, const char *user_file)
8344 sigset_t oldset; /* The signals that were blocked on entry to this function */
8345 int status; /* The return status of _gl_configure_getline() */
8347 * Check the arguments.
8349 if(!gl) {
8350 errno = EINVAL;
8351 return 1;
8354 * Block all signals.
8356 if(gl_mask_signals(gl, &oldset))
8357 return 1;
8359 * Execute the private body of the function while signals are blocked.
8361 status = _gl_configure_getline(gl, app_string, app_file, user_file);
8363 * Restore the process signal mask.
8365 gl_unmask_signals(gl, &oldset);
8366 return status;
8369 /*.......................................................................
8370 * This is the private body of the gl_configure_getline() function. It
8371 * assumes that the caller has checked its arguments and blocked the
8372 * delivery of signals.
8374 static int _gl_configure_getline(GetLine *gl, const char *app_string,
8375 const char *app_file, const char *user_file)
8378 * Mark getline as having been explicitly configured.
8380 gl->configured = 1;
8382 * Start by parsing the configuration string, if provided.
8384 if(app_string)
8385 (void) _gl_read_config_string(gl, app_string, KTB_NORM);
8387 * Now parse the application-specific configuration file, if provided.
8389 if(app_file)
8390 (void) _gl_read_config_file(gl, app_file, KTB_NORM);
8392 * Finally, parse the user-specific configuration file, if provided.
8394 if(user_file)
8395 (void) _gl_read_config_file(gl, user_file, KTB_USER);
8397 * Record the names of the configuration files to allow them to
8398 * be re-read if requested at a later time.
8400 if(gl_record_string(&gl->app_file, app_file) ||
8401 gl_record_string(&gl->user_file, user_file)) {
8402 errno = ENOMEM;
8403 _err_record_msg(gl->err,
8404 "Insufficient memory to record tecla configuration file names",
8405 END_ERR_MSG);
8406 return 1;
8408 return 0;
8411 /*.......................................................................
8412 * Replace a malloc'd string (or NULL), with another malloc'd copy of
8413 * a string (or NULL).
8415 * Input:
8416 * sptr char ** On input if *sptr!=NULL, *sptr will be
8417 * free'd and *sptr will be set to NULL. Then,
8418 * on output, if string!=NULL a malloc'd copy
8419 * of this string will be assigned to *sptr.
8420 * string const char * The string to be copied, or NULL to simply
8421 * discard any existing string.
8422 * Output:
8423 * return int 0 - OK.
8424 * 1 - Malloc failure (no error message is generated).
8426 static int gl_record_string(char **sptr, const char *string)
8429 * If the original string is the same string, don't do anything.
8431 if(*sptr == string || (*sptr && string && strcmp(*sptr, string)==0))
8432 return 0;
8434 * Discard any existing cached string.
8436 if(*sptr) {
8437 free(*sptr);
8438 *sptr = NULL;
8441 * Allocate memory for a copy of the specified string.
8443 if(string) {
8444 size_t ssz = strlen(string) + 1;
8445 *sptr = (char *) malloc(ssz);
8446 if(!*sptr)
8447 return 1;
8449 * Copy the string.
8451 strlcpy(*sptr, string, ssz);
8453 return 0;
8456 #ifndef HIDE_FILE_SYSTEM
8457 /*.......................................................................
8458 * Re-read any application-specific and user-specific files previously
8459 * specified via the gl_configure_getline() function.
8461 static KT_KEY_FN(gl_read_init_files)
8463 return _gl_configure_getline(gl, NULL, gl->app_file, gl->user_file);
8465 #endif
8467 /*.......................................................................
8468 * Save the contents of the history buffer to a given new file.
8470 * Input:
8471 * gl GetLine * The resource object of this library.
8472 * filename const char * The name of the new file to write to.
8473 * comment const char * Extra information such as timestamps will
8474 * be recorded on a line started with this
8475 * string, the idea being that the file can
8476 * double as a command file. Specify "" if
8477 * you don't care.
8478 * max_lines int The maximum number of lines to save, or -1
8479 * to save all of the lines in the history
8480 * list.
8481 * Output:
8482 * return int 0 - OK.
8483 * 1 - Error.
8485 int gl_save_history(GetLine *gl, const char *filename, const char *comment,
8486 int max_lines)
8488 sigset_t oldset; /* The signals that were blocked on entry to this function */
8489 int status; /* The return status of _gl_save_history() */
8491 * Check the arguments.
8493 if(!gl || !filename || !comment) {
8494 if(gl)
8495 _err_record_msg(gl->err, "NULL argument(s)", END_ERR_MSG);
8496 errno = EINVAL;
8497 return 1;
8500 * Block all signals.
8502 if(gl_mask_signals(gl, &oldset))
8503 return 1;
8505 * Execute the private body of the function while signals are blocked.
8507 status = _gl_save_history(gl, filename, comment, max_lines);
8509 * Restore the process signal mask.
8511 gl_unmask_signals(gl, &oldset);
8512 return status;
8515 /*.......................................................................
8516 * This is the private body of the gl_save_history() function. It
8517 * assumes that the caller has checked its arguments and blocked the
8518 * delivery of signals.
8520 static int _gl_save_history(GetLine *gl, const char *filename,
8521 const char *comment, int max_lines)
8524 * If filesystem access is to be excluded, then history files can't
8525 * be written.
8527 #ifdef WITHOUT_FILE_SYSTEM
8528 _err_record_msg(gl->err, "Can't save history without filesystem access",
8529 END_ERR_MSG);
8530 errno = EINVAL;
8531 return 1;
8532 #else
8533 FileExpansion *expansion; /* The expansion of the filename */
8535 * Expand the filename.
8537 expansion = ef_expand_file(gl->ef, filename, -1);
8538 if(!expansion) {
8539 gl_print_info(gl, "Unable to expand ", filename, " (",
8540 ef_last_error(gl->ef), ").", GL_END_INFO);
8541 return 1;
8544 * Attempt to save to the specified file.
8546 if(_glh_save_history(gl->glh, expansion->files[0], comment, max_lines)) {
8547 _err_record_msg(gl->err, _glh_last_error(gl->glh), END_ERR_MSG);
8548 return 1;
8550 return 0;
8551 #endif
8554 /*.......................................................................
8555 * Restore the contents of the history buffer from a given new file.
8557 * Input:
8558 * gl GetLine * The resource object of this library.
8559 * filename const char * The name of the new file to write to.
8560 * comment const char * This must be the same string that was
8561 * passed to gl_save_history() when the file
8562 * was written.
8563 * Output:
8564 * return int 0 - OK.
8565 * 1 - Error.
8567 int gl_load_history(GetLine *gl, const char *filename, const char *comment)
8569 sigset_t oldset; /* The signals that were blocked on entry to this function */
8570 int status; /* The return status of _gl_load_history() */
8572 * Check the arguments.
8574 if(!gl || !filename || !comment) {
8575 if(gl)
8576 _err_record_msg(gl->err, "NULL argument(s)", END_ERR_MSG);
8577 errno = EINVAL;
8578 return 1;
8581 * Block all signals.
8583 if(gl_mask_signals(gl, &oldset))
8584 return 1;
8586 * Execute the private body of the function while signals are blocked.
8588 status = _gl_load_history(gl, filename, comment);
8590 * Restore the process signal mask.
8592 gl_unmask_signals(gl, &oldset);
8593 return status;
8596 /*.......................................................................
8597 * This is the private body of the gl_load_history() function. It
8598 * assumes that the caller has checked its arguments and blocked the
8599 * delivery of signals.
8601 static int _gl_load_history(GetLine *gl, const char *filename,
8602 const char *comment)
8605 * If filesystem access is to be excluded, then history files can't
8606 * be read.
8608 #ifdef WITHOUT_FILE_SYSTEM
8609 _err_record_msg(gl->err, "Can't load history without filesystem access",
8610 END_ERR_MSG);
8611 errno = EINVAL;
8612 return 1;
8613 #else
8614 FileExpansion *expansion; /* The expansion of the filename */
8616 * Expand the filename.
8618 expansion = ef_expand_file(gl->ef, filename, -1);
8619 if(!expansion) {
8620 gl_print_info(gl, "Unable to expand ", filename, " (",
8621 ef_last_error(gl->ef), ").", GL_END_INFO);
8622 return 1;
8625 * Attempt to load from the specified file.
8627 if(_glh_load_history(gl->glh, expansion->files[0], comment,
8628 gl->cutbuf, gl->linelen+1)) {
8629 _err_record_msg(gl->err, _glh_last_error(gl->glh), END_ERR_MSG);
8630 gl->cutbuf[0] = '\0';
8631 return 1;
8633 gl->cutbuf[0] = '\0';
8634 return 0;
8635 #endif
8638 /*.......................................................................
8639 * Where possible, register a function and associated data to be called
8640 * whenever a specified event is seen on a file descriptor.
8642 * Input:
8643 * gl GetLine * The resource object of the command-line input
8644 * module.
8645 * fd int The file descriptor to watch.
8646 * event GlFdEvent The type of activity to watch for.
8647 * callback GlFdEventFn * The function to call when the specified
8648 * event occurs. Setting this to 0 removes
8649 * any existing callback.
8650 * data void * A pointer to arbitrary data to pass to the
8651 * callback function.
8652 * Output:
8653 * return int 0 - OK.
8654 * 1 - Either gl==NULL, or this facility isn't
8655 * available on the the host system
8656 * (ie. select() isn't available). No
8657 * error message is generated in the latter
8658 * case.
8660 int gl_watch_fd(GetLine *gl, int fd, GlFdEvent event,
8661 GlFdEventFn *callback, void *data)
8663 sigset_t oldset; /* The signals that were blocked on entry to this function */
8664 int status; /* The return status of _gl_watch_fd() */
8666 * Check the arguments.
8668 if(!gl) {
8669 errno = EINVAL;
8670 return 1;
8672 if(fd < 0) {
8673 _err_record_msg(gl->err, "Error: fd < 0", END_ERR_MSG);
8674 errno = EINVAL;
8675 return 1;
8678 * Block all signals.
8680 if(gl_mask_signals(gl, &oldset))
8681 return 1;
8683 * Execute the private body of the function while signals are blocked.
8685 status = _gl_watch_fd(gl, fd, event, callback, data);
8687 * Restore the process signal mask.
8689 gl_unmask_signals(gl, &oldset);
8690 return status;
8693 /*.......................................................................
8694 * This is the private body of the gl_watch_fd() function. It
8695 * assumes that the caller has checked its arguments and blocked the
8696 * delivery of signals.
8698 static int _gl_watch_fd(GetLine *gl, int fd, GlFdEvent event,
8699 GlFdEventFn *callback, void *data)
8700 #if !defined(HAVE_SELECT)
8701 {return 1;} /* The facility isn't supported on this system */
8702 #else
8704 GlFdNode *prev; /* The node that precedes 'node' in gl->fd_nodes */
8705 GlFdNode *node; /* The file-descriptor node being checked */
8707 * Search the list of already registered fd activity nodes for the specified
8708 * file descriptor.
8710 for(prev=NULL,node=gl->fd_nodes; node && node->fd != fd;
8711 prev=node, node=node->next)
8714 * Hasn't a node been allocated for this fd yet?
8716 if(!node) {
8718 * If there is no callback to record, just ignore the call.
8720 if(!callback)
8721 return 0;
8723 * Allocate the new node.
8725 node = (GlFdNode *) _new_FreeListNode(gl->fd_node_mem);
8726 if(!node) {
8727 errno = ENOMEM;
8728 _err_record_msg(gl->err, "Insufficient memory", END_ERR_MSG);
8729 return 1;
8732 * Prepend the node to the list.
8734 node->next = gl->fd_nodes;
8735 gl->fd_nodes = node;
8737 * Initialize the node.
8739 node->fd = fd;
8740 node->rd.fn = 0;
8741 node->rd.data = NULL;
8742 node->ur = node->wr = node->rd;
8745 * Record the new callback.
8747 switch(event) {
8748 case GLFD_READ:
8749 node->rd.fn = callback;
8750 node->rd.data = data;
8751 if(callback)
8752 FD_SET(fd, &gl->rfds);
8753 else
8754 FD_CLR(fd, &gl->rfds);
8755 break;
8756 case GLFD_WRITE:
8757 node->wr.fn = callback;
8758 node->wr.data = data;
8759 if(callback)
8760 FD_SET(fd, &gl->wfds);
8761 else
8762 FD_CLR(fd, &gl->wfds);
8763 break;
8764 case GLFD_URGENT:
8765 node->ur.fn = callback;
8766 node->ur.data = data;
8767 if(callback)
8768 FD_SET(fd, &gl->ufds);
8769 else
8770 FD_CLR(fd, &gl->ufds);
8771 break;
8774 * Keep a record of the largest file descriptor being watched.
8776 if(fd > gl->max_fd)
8777 gl->max_fd = fd;
8779 * If we are deleting an existing callback, also delete the parent
8780 * activity node if no callbacks are registered to the fd anymore.
8782 if(!callback) {
8783 if(!node->rd.fn && !node->wr.fn && !node->ur.fn) {
8784 if(prev)
8785 prev->next = node->next;
8786 else
8787 gl->fd_nodes = node->next;
8788 node = (GlFdNode *) _del_FreeListNode(gl->fd_node_mem, node);
8791 return 0;
8793 #endif
8795 /*.......................................................................
8796 * On systems with the select() system call, the gl_inactivity_timeout()
8797 * function provides the option of setting (or cancelling) an
8798 * inactivity timeout. Inactivity, in this case, refers both to
8799 * terminal input received from the user, and to I/O on any file
8800 * descriptors registered by calls to gl_watch_fd(). If at any time,
8801 * no activity is seen for the requested time period, the specified
8802 * timeout callback function is called. On returning, this callback
8803 * returns a code which tells gl_get_line() what to do next. Note that
8804 * each call to gl_inactivity_timeout() replaces any previously installed
8805 * timeout callback, and that specifying a callback of 0, turns off
8806 * inactivity timing.
8808 * Beware that although the timeout argument includes a nano-second
8809 * component, few computer clocks presently have resolutions finer
8810 * than a few milliseconds, so asking for less than a few milliseconds
8811 * is equivalent to zero on a lot of systems.
8813 * Input:
8814 * gl GetLine * The resource object of the command-line input
8815 * module.
8816 * callback GlTimeoutFn * The function to call when the inactivity
8817 * timeout is exceeded. To turn off
8818 * inactivity timeouts altogether, send 0.
8819 * data void * A pointer to arbitrary data to pass to the
8820 * callback function.
8821 * sec unsigned long The number of whole seconds in the timeout.
8822 * nsec unsigned long The fractional number of seconds in the
8823 * timeout, expressed in nano-seconds (see
8824 * the caveat above).
8825 * Output:
8826 * return int 0 - OK.
8827 * 1 - Either gl==NULL, or this facility isn't
8828 * available on the the host system
8829 * (ie. select() isn't available). No
8830 * error message is generated in the latter
8831 * case.
8833 int gl_inactivity_timeout(GetLine *gl, GlTimeoutFn *timeout_fn, void *data,
8834 unsigned long sec, unsigned long nsec)
8835 #if !defined(HAVE_SELECT)
8836 {return 1;} /* The facility isn't supported on this system */
8837 #else
8839 sigset_t oldset; /* The signals that were blocked on entry to this function */
8841 * Check the arguments.
8843 if(!gl) {
8844 errno = EINVAL;
8845 return 1;
8848 * Block all signals.
8850 if(gl_mask_signals(gl, &oldset))
8851 return 1;
8853 * Install a new timeout?
8855 if(timeout_fn) {
8856 gl->timer.dt.tv_sec = sec;
8857 gl->timer.dt.tv_usec = nsec / 1000;
8858 gl->timer.fn = timeout_fn;
8859 gl->timer.data = data;
8860 } else {
8861 gl->timer.fn = 0;
8862 gl->timer.data = NULL;
8865 * Restore the process signal mask.
8867 gl_unmask_signals(gl, &oldset);
8868 return 0;
8870 #endif
8872 /*.......................................................................
8873 * When select() is available, this is a private function of
8874 * gl_read_input() which responds to file-descriptor events registered by
8875 * the caller. Note that it assumes that it is being called from within
8876 * gl_read_input()'s sigsetjump() clause.
8878 * Input:
8879 * gl GetLine * The resource object of this module.
8880 * fd int The file descriptor to be watched for user input.
8881 * Output:
8882 * return int 0 - OK.
8883 * 1 - An error occurred.
8885 static int gl_event_handler(GetLine *gl, int fd)
8887 #if !defined(HAVE_SELECT)
8888 return 0;
8889 #else
8891 * Set up a zero-second timeout.
8893 struct timeval zero;
8894 zero.tv_sec = zero.tv_usec = 0;
8896 * If at any time no external callbacks remain, quit the loop return,
8897 * so that we can simply wait in read(). This is designed as an
8898 * optimization for when no callbacks have been registered on entry to
8899 * this function, but since callbacks can delete themselves, it can
8900 * also help later.
8902 while(gl->fd_nodes || gl->timer.fn) {
8903 int nready; /* The number of file descriptors that are ready for I/O */
8905 * Get the set of descriptors to be watched.
8907 fd_set rfds = gl->rfds;
8908 fd_set wfds = gl->wfds;
8909 fd_set ufds = gl->ufds;
8911 * Get the appropriate timeout.
8913 struct timeval dt = gl->timer.fn ? gl->timer.dt : zero;
8915 * Add the specified user-input file descriptor to the set that is to
8916 * be watched.
8918 FD_SET(fd, &rfds);
8920 * Unblock the signals that we are watching, while select is blocked
8921 * waiting for I/O.
8923 gl_catch_signals(gl);
8925 * Wait for activity on any of the file descriptors.
8927 nready = select(gl->max_fd+1, &rfds, &wfds, &ufds,
8928 (gl->timer.fn || gl->io_mode==GL_SERVER_MODE) ? &dt : NULL);
8930 * We don't want to do a longjmp in the middle of a callback that
8931 * might be modifying global or heap data, so block all the signals
8932 * that we are trapping before executing callback functions. Note that
8933 * the caller will unblock them again when it needs to, so there is
8934 * no need to undo this before returning.
8936 gl_mask_signals(gl, NULL);
8938 * If select() returns but none of the file descriptors are reported
8939 * to have activity, then select() timed out.
8941 if(nready == 0) {
8943 * Note that in non-blocking server mode, the inactivity timer is used
8944 * to allow I/O to block for a specified amount of time, so in this
8945 * mode we return the postponed blocked status when an abort is
8946 * requested.
8948 if(gl_call_timeout_handler(gl)) {
8949 return 1;
8950 } else if(gl->io_mode == GL_SERVER_MODE) {
8951 gl_record_status(gl, GLR_BLOCKED, BLOCKED_ERRNO);
8952 return 1;
8955 * If nready < 0, this means an error occurred.
8957 } else if(nready < 0) {
8958 if(errno != EINTR) {
8959 gl_record_status(gl, GLR_ERROR, errno);
8960 return 1;
8963 * If the user-input file descriptor has data available, return.
8965 } else if(FD_ISSET(fd, &rfds)) {
8966 return 0;
8968 * Check for activity on any of the file descriptors registered by the
8969 * calling application, and call the associated callback functions.
8971 } else {
8972 GlFdNode *node; /* The fd event node being checked */
8974 * Search the list for the file descriptor that caused select() to return.
8976 for(node=gl->fd_nodes; node; node=node->next) {
8978 * Is there urgent out of band data waiting to be read on fd?
8980 if(node->ur.fn && FD_ISSET(node->fd, &ufds)) {
8981 if(gl_call_fd_handler(gl, &node->ur, node->fd, GLFD_URGENT))
8982 return 1;
8983 break; /* The callback may have changed the list of nodes */
8985 * Is the fd readable?
8987 } else if(node->rd.fn && FD_ISSET(node->fd, &rfds)) {
8988 if(gl_call_fd_handler(gl, &node->rd, node->fd, GLFD_READ))
8989 return 1;
8990 break; /* The callback may have changed the list of nodes */
8992 * Is the fd writable?
8994 } else if(node->wr.fn && FD_ISSET(node->fd, &wfds)) {
8995 if(gl_call_fd_handler(gl, &node->wr, node->fd, GLFD_WRITE))
8996 return 1;
8997 break; /* The callback may have changed the list of nodes */
9002 * Just in case the above event handlers asked for the input line to
9003 * be redrawn, flush any pending output.
9005 if(gl_flush_output(gl))
9006 return 1;
9008 return 0;
9010 #endif
9012 #if defined(HAVE_SELECT)
9013 /*.......................................................................
9014 * This is a private function of gl_event_handler(), used to call a
9015 * file-descriptor callback.
9017 * Input:
9018 * gl GetLine * The resource object of gl_get_line().
9019 * gfh GlFdHandler * The I/O handler.
9020 * fd int The file-descriptor being reported.
9021 * event GlFdEvent The I/O event being reported.
9022 * Output:
9023 * return int 0 - OK.
9024 * 1 - Error.
9026 static int gl_call_fd_handler(GetLine *gl, GlFdHandler *gfh, int fd,
9027 GlFdEvent event)
9029 Termios attr; /* The terminal attributes */
9030 int waserr = 0; /* True after any error */
9032 * Re-enable conversion of newline characters to carriage-return/linefeed,
9033 * so that the callback can write to the terminal without having to do
9034 * anything special.
9036 if(tcgetattr(gl->input_fd, &attr)) {
9037 _err_record_msg(gl->err, "tcgetattr error", END_ERR_MSG);
9038 return 1;
9040 attr.c_oflag |= OPOST;
9041 while(tcsetattr(gl->input_fd, TCSADRAIN, &attr)) {
9042 if(errno != EINTR) {
9043 _err_record_msg(gl->err, "tcsetattr error", END_ERR_MSG);
9044 return 1;
9048 * Invoke the application's callback function.
9050 switch(gfh->fn(gl, gfh->data, fd, event)) {
9051 default:
9052 case GLFD_ABORT:
9053 gl_record_status(gl, GLR_FDABORT, 0);
9054 waserr = 1;
9055 break;
9056 case GLFD_REFRESH:
9057 gl_queue_redisplay(gl);
9058 break;
9059 case GLFD_CONTINUE:
9060 break;
9063 * Disable conversion of newline characters to carriage-return/linefeed.
9065 attr.c_oflag &= ~(OPOST);
9066 while(tcsetattr(gl->input_fd, TCSADRAIN, &attr)) {
9067 if(errno != EINTR) {
9068 _err_record_msg(gl->err, "tcsetattr error", END_ERR_MSG);
9069 return 1;
9072 return waserr;
9075 /*.......................................................................
9076 * This is a private function of gl_event_handler(), used to call a
9077 * inactivity timer callbacks.
9079 * Input:
9080 * gl GetLine * The resource object of gl_get_line().
9081 * Output:
9082 * return int 0 - OK.
9083 * 1 - Error.
9085 static int gl_call_timeout_handler(GetLine *gl)
9087 Termios attr; /* The terminal attributes */
9088 int waserr = 0; /* True after any error */
9090 * Make sure that there is an inactivity timeout callback.
9092 if(!gl->timer.fn)
9093 return 0;
9095 * Re-enable conversion of newline characters to carriage-return/linefeed,
9096 * so that the callback can write to the terminal without having to do
9097 * anything special.
9099 if(tcgetattr(gl->input_fd, &attr)) {
9100 _err_record_msg(gl->err, "tcgetattr error", END_ERR_MSG);
9101 return 1;
9103 attr.c_oflag |= OPOST;
9104 while(tcsetattr(gl->input_fd, TCSADRAIN, &attr)) {
9105 if(errno != EINTR) {
9106 _err_record_msg(gl->err, "tcsetattr error", END_ERR_MSG);
9107 return 1;
9111 * Invoke the application's callback function.
9113 switch(gl->timer.fn(gl, gl->timer.data)) {
9114 default:
9115 case GLTO_ABORT:
9116 gl_record_status(gl, GLR_TIMEOUT, 0);
9117 waserr = 1;
9118 break;
9119 case GLTO_REFRESH:
9120 gl_queue_redisplay(gl);
9121 break;
9122 case GLTO_CONTINUE:
9123 break;
9126 * Disable conversion of newline characters to carriage-return/linefeed.
9128 attr.c_oflag &= ~(OPOST);
9129 while(tcsetattr(gl->input_fd, TCSADRAIN, &attr)) {
9130 if(errno != EINTR) {
9131 _err_record_msg(gl->err, "tcsetattr error", END_ERR_MSG);
9132 return 1;
9135 return waserr;
9137 #endif /* HAVE_SELECT */
9139 /*.......................................................................
9140 * Switch history groups. History groups represent separate history
9141 * lists recorded within a single history buffer. Different groups
9142 * are distinguished by integer identifiers chosen by the calling
9143 * appplicaton. Initially new_GetLine() sets the group identifier to
9144 * 0. Whenever a new line is appended to the history list, the current
9145 * group identifier is recorded with it, and history lookups only
9146 * consider lines marked with the current group identifier.
9148 * Input:
9149 * gl GetLine * The resource object of gl_get_line().
9150 * id unsigned The new history group identifier.
9151 * Output:
9152 * return int 0 - OK.
9153 * 1 - Error.
9155 int gl_group_history(GetLine *gl, unsigned id)
9157 sigset_t oldset; /* The signals that were blocked on entry to this function */
9158 int status; /* The return status of this function */
9160 * Check the arguments.
9162 if(!gl) {
9163 errno = EINVAL;
9164 return 1;
9167 * Block all signals while we install the new configuration.
9169 if(gl_mask_signals(gl, &oldset))
9170 return 1;
9172 * If the group isn't being changed, do nothing.
9174 if(_glh_get_group(gl->glh) == id) {
9175 status = 0;
9177 * Establish the new group.
9179 } else if(_glh_set_group(gl->glh, id)) {
9180 _err_record_msg(gl->err, _glh_last_error(gl->glh), END_ERR_MSG);
9181 status = 1;
9183 * Prevent history information from the previous group being
9184 * inappropriately used by the next call to gl_get_line().
9186 } else {
9187 gl->preload_history = 0;
9188 gl->last_search = -1;
9189 status = 0;
9192 * Restore the process signal mask.
9194 gl_unmask_signals(gl, &oldset);
9195 return status;
9198 /*.......................................................................
9199 * Display the contents of the history list.
9201 * Input:
9202 * gl GetLine * The resource object of gl_get_line().
9203 * fp FILE * The stdio output stream to write to.
9204 * fmt const char * A format string. This containing characters to be
9205 * written verbatim, plus any of the following
9206 * format directives:
9207 * %D - The date, formatted like 2001-11-20
9208 * %T - The time of day, formatted like 23:59:59
9209 * %N - The sequential entry number of the
9210 * line in the history buffer.
9211 * %G - The number of the history group that
9212 * the line belongs to.
9213 * %% - A literal % character.
9214 * %H - The history line itself.
9215 * Note that a '\n' newline character is not
9216 * appended by default.
9217 * all_groups int If true, display history lines from all
9218 * history groups. Otherwise only display
9219 * those of the current history group.
9220 * max_lines int If max_lines is < 0, all available lines
9221 * are displayed. Otherwise only the most
9222 * recent max_lines lines will be displayed.
9223 * Output:
9224 * return int 0 - OK.
9225 * 1 - Error.
9227 int gl_show_history(GetLine *gl, FILE *fp, const char *fmt, int all_groups,
9228 int max_lines)
9230 sigset_t oldset; /* The signals that were blocked on entry to this function */
9231 int status; /* The return status of this function */
9233 * Check the arguments.
9235 if(!gl || !fp || !fmt) {
9236 if(gl)
9237 _err_record_msg(gl->err, "NULL argument(s)", END_ERR_MSG);
9238 errno = EINVAL;
9239 return 1;
9242 * Block all signals.
9244 if(gl_mask_signals(gl, &oldset))
9245 return 1;
9247 * Display the specified history group(s) while signals are blocked.
9249 status = _glh_show_history(gl->glh, _io_write_stdio, fp, fmt, all_groups,
9250 max_lines) || fflush(fp)==EOF;
9251 if(!status)
9252 _err_record_msg(gl->err, _glh_last_error(gl->glh), END_ERR_MSG);
9254 * Restore the process signal mask.
9256 gl_unmask_signals(gl, &oldset);
9257 return status;
9260 /*.......................................................................
9261 * Update if necessary, and return the current size of the terminal.
9263 * Input:
9264 * gl GetLine * The resource object of gl_get_line().
9265 * def_ncolumn int If the number of columns in the terminal
9266 * can't be determined, substitute this number.
9267 * def_nline int If the number of lines in the terminal can't
9268 * be determined, substitute this number.
9269 * Output:
9270 * return GlTerminalSize The current terminal size.
9272 GlTerminalSize gl_terminal_size(GetLine *gl, int def_ncolumn, int def_nline)
9274 GlTerminalSize size; /* The object to be returned */
9275 sigset_t oldset; /* The signals that were blocked on entry */
9276 /* to this function */
9278 * Block all signals while accessing gl.
9280 gl_mask_signals(gl, &oldset);
9282 * Lookup/configure the terminal size.
9284 _gl_terminal_size(gl, def_ncolumn, def_nline, &size);
9286 * Restore the process signal mask before returning.
9288 gl_unmask_signals(gl, &oldset);
9289 return size;
9292 /*.......................................................................
9293 * This is the private body of the gl_terminal_size() function. It
9294 * assumes that the caller has checked its arguments and blocked the
9295 * delivery of signals.
9297 static void _gl_terminal_size(GetLine *gl, int def_ncolumn, int def_nline,
9298 GlTerminalSize *size)
9300 const char *env; /* The value of an environment variable */
9301 int n; /* A number read from env[] */
9303 * Set the number of lines and columns to non-sensical values so that
9304 * we know later if they have been set.
9306 gl->nline = 0;
9307 gl->ncolumn = 0;
9309 * Are we reading from a terminal?
9311 if(gl->is_term) {
9313 * Ask the terminal directly if possible.
9315 (void) _gl_update_size(gl);
9317 * If gl_update_size() couldn't ask the terminal, it will have
9318 * left gl->nrow and gl->ncolumn unchanged. If these values haven't
9319 * been changed from their initial values of zero, we need to find
9320 * a different method to get the terminal size.
9322 * If the number of lines isn't known yet, first see if the
9323 * LINES environment ariable exists and specifies a believable number.
9324 * If this doesn't work, look up the default size in the terminal
9325 * information database.
9327 if(gl->nline < 1) {
9328 if((env = getenv("LINES")) && (n=atoi(env)) > 0)
9329 gl->nline = n;
9330 #ifdef USE_TERMINFO
9331 else
9332 gl->nline = tigetnum((char *)"lines");
9333 #elif defined(USE_TERMCAP)
9334 else
9335 gl->nline = tgetnum("li");
9336 #endif
9339 * If the number of lines isn't known yet, first see if the COLUMNS
9340 * environment ariable exists and specifies a believable number. If
9341 * this doesn't work, look up the default size in the terminal
9342 * information database.
9344 if(gl->ncolumn < 1) {
9345 if((env = getenv("COLUMNS")) && (n=atoi(env)) > 0)
9346 gl->ncolumn = n;
9347 #ifdef USE_TERMINFO
9348 else
9349 gl->ncolumn = tigetnum((char *)"cols");
9350 #elif defined(USE_TERMCAP)
9351 else
9352 gl->ncolumn = tgetnum("co");
9353 #endif
9357 * If we still haven't been able to acquire reasonable values, substitute
9358 * the default values specified by the caller.
9360 if(gl->nline <= 0)
9361 gl->nline = def_nline;
9362 if(gl->ncolumn <= 0)
9363 gl->ncolumn = def_ncolumn;
9365 * Copy the new size into the return value.
9367 if(size) {
9368 size->nline = gl->nline;
9369 size->ncolumn = gl->ncolumn;
9371 return;
9374 /*.......................................................................
9375 * Resize or delete the history buffer.
9377 * Input:
9378 * gl GetLine * The resource object of gl_get_line().
9379 * bufsize size_t The number of bytes in the history buffer, or 0
9380 * to delete the buffer completely.
9381 * Output:
9382 * return int 0 - OK.
9383 * 1 - Insufficient memory (the previous buffer
9384 * will have been retained). No error message
9385 * will be displayed.
9387 int gl_resize_history(GetLine *gl, size_t bufsize)
9389 sigset_t oldset; /* The signals that were blocked on entry to this function */
9390 int status; /* The return status of this function */
9392 * Check the arguments.
9394 if(!gl)
9395 return 1;
9397 * Block all signals while modifying the contents of gl.
9399 if(gl_mask_signals(gl, &oldset))
9400 return 1;
9402 * Perform the resize while signals are blocked.
9404 status = _glh_resize_history(gl->glh, bufsize);
9405 if(status)
9406 _err_record_msg(gl->err, _glh_last_error(gl->glh), END_ERR_MSG);
9408 * Restore the process signal mask before returning.
9410 gl_unmask_signals(gl, &oldset);
9411 return status;
9414 /*.......................................................................
9415 * Set an upper limit to the number of lines that can be recorded in the
9416 * history list, or remove a previously specified limit.
9418 * Input:
9419 * gl GetLine * The resource object of gl_get_line().
9420 * max_lines int The maximum number of lines to allow, or -1 to
9421 * cancel a previous limit and allow as many lines
9422 * as will fit in the current history buffer size.
9424 void gl_limit_history(GetLine *gl, int max_lines)
9426 if(gl) {
9427 sigset_t oldset; /* The signals that were blocked on entry to this block */
9429 * Temporarily block all signals.
9431 gl_mask_signals(gl, &oldset);
9433 * Apply the limit while signals are blocked.
9435 _glh_limit_history(gl->glh, max_lines);
9437 * Restore the process signal mask before returning.
9439 gl_unmask_signals(gl, &oldset);
9443 /*.......................................................................
9444 * Discard either all historical lines, or just those associated with the
9445 * current history group.
9447 * Input:
9448 * gl GetLine * The resource object of gl_get_line().
9449 * all_groups int If true, clear all of the history. If false,
9450 * clear only the stored lines associated with the
9451 * currently selected history group.
9453 void gl_clear_history(GetLine *gl, int all_groups)
9455 if(gl) {
9456 sigset_t oldset; /* The signals that were blocked on entry to this block */
9458 * Temporarily block all signals.
9460 gl_mask_signals(gl, &oldset);
9462 * Clear the history buffer while signals are blocked.
9464 _glh_clear_history(gl->glh, all_groups);
9466 * Restore the process signal mask before returning.
9468 gl_unmask_signals(gl, &oldset);
9472 /*.......................................................................
9473 * Temporarily enable or disable the gl_get_line() history mechanism.
9475 * Input:
9476 * gl GetLine * The resource object of gl_get_line().
9477 * enable int If true, turn on the history mechanism. If
9478 * false, disable it.
9480 void gl_toggle_history(GetLine *gl, int enable)
9482 if(gl) {
9483 sigset_t oldset; /* The signals that were blocked on entry to this block */
9485 * Temporarily block all signals.
9487 gl_mask_signals(gl, &oldset);
9489 * Change the history recording mode while signals are blocked.
9491 _glh_toggle_history(gl->glh, enable);
9493 * Restore the process signal mask before returning.
9495 gl_unmask_signals(gl, &oldset);
9499 /*.......................................................................
9500 * Lookup a history line by its sequential number of entry in the
9501 * history buffer.
9503 * Input:
9504 * gl GetLine * The resource object of gl_get_line().
9505 * id unsigned long The identification number of the line to
9506 * be returned, where 0 denotes the first line
9507 * that was entered in the history list, and
9508 * each subsequently added line has a number
9509 * one greater than the previous one. For
9510 * the range of lines currently in the list,
9511 * see the gl_range_of_history() function.
9512 * Input/Output:
9513 * line GlHistoryLine * A pointer to the variable in which to
9514 * return the details of the line.
9515 * Output:
9516 * return int 0 - The line is no longer in the history
9517 * list, and *line has not been changed.
9518 * 1 - The requested line can be found in
9519 * *line. Note that line->line is part
9520 * of the history buffer, so a
9521 * private copy should be made if you
9522 * wish to use it after subsequent calls
9523 * to any functions that take *gl as an
9524 * argument.
9526 int gl_lookup_history(GetLine *gl, unsigned long id, GlHistoryLine *line)
9528 sigset_t oldset; /* The signals that were blocked on entry to this function */
9529 int status; /* The return status of this function */
9531 * Check the arguments.
9533 if(!gl)
9534 return 0;
9536 * Block all signals while modifying the contents of gl.
9538 if(gl_mask_signals(gl, &oldset))
9539 return 1;
9541 * Perform the lookup while signals are blocked.
9543 status = _glh_lookup_history(gl->glh, (GlhLineID) id, &line->line,
9544 &line->group, &line->timestamp);
9545 if(status)
9546 _err_record_msg(gl->err, _glh_last_error(gl->glh), END_ERR_MSG);
9548 * Restore the process signal mask before returning.
9550 gl_unmask_signals(gl, &oldset);
9551 return status;
9554 /*.......................................................................
9555 * Query the state of the history list. Note that any of the input/output
9556 * pointers can be specified as NULL.
9558 * Input:
9559 * gl GetLine * The resource object of gl_get_line().
9560 * Input/Output:
9561 * state GlHistoryState * A pointer to the variable in which to record
9562 * the return values.
9564 void gl_state_of_history(GetLine *gl, GlHistoryState *state)
9566 if(gl && state) {
9567 sigset_t oldset; /* The signals that were blocked on entry to this block */
9569 * Temporarily block all signals.
9571 gl_mask_signals(gl, &oldset);
9573 * Lookup the status while signals are blocked.
9575 _glh_state_of_history(gl->glh, &state->enabled, &state->group,
9576 &state->max_lines);
9578 * Restore the process signal mask before returning.
9580 gl_unmask_signals(gl, &oldset);
9584 /*.......................................................................
9585 * Query the number and range of lines in the history buffer.
9587 * Input:
9588 * gl GetLine * The resource object of gl_get_line().
9589 * range GlHistoryRange * A pointer to the variable in which to record
9590 * the return values. If range->nline=0, the
9591 * range of lines will be given as 0-0.
9593 void gl_range_of_history(GetLine *gl, GlHistoryRange *range)
9595 if(gl && range) {
9596 sigset_t oldset; /* The signals that were blocked on entry to this block */
9598 * Temporarily block all signals.
9600 gl_mask_signals(gl, &oldset);
9602 * Lookup the information while signals are blocked.
9604 _glh_range_of_history(gl->glh, &range->oldest, &range->newest,
9605 &range->nlines);
9607 * Restore the process signal mask before returning.
9609 gl_unmask_signals(gl, &oldset);
9613 /*.......................................................................
9614 * Return the size of the history buffer and the amount of the
9615 * buffer that is currently in use.
9617 * Input:
9618 * gl GetLine * The gl_get_line() resource object.
9619 * Input/Output:
9620 * GlHistorySize size * A pointer to the variable in which to return
9621 * the results.
9623 void gl_size_of_history(GetLine *gl, GlHistorySize *size)
9625 if(gl && size) {
9626 sigset_t oldset; /* The signals that were blocked on entry to this block */
9628 * Temporarily block all signals.
9630 gl_mask_signals(gl, &oldset);
9632 * Lookup the information while signals are blocked.
9634 _glh_size_of_history(gl->glh, &size->size, &size->used);
9636 * Restore the process signal mask before returning.
9638 gl_unmask_signals(gl, &oldset);
9642 /*.......................................................................
9643 * This is the action function that lists the contents of the history
9644 * list.
9646 static KT_KEY_FN(gl_list_history)
9649 * Start a new line.
9651 if(gl_start_newline(gl, 1))
9652 return 1;
9654 * List history lines that belong to the current group.
9656 _glh_show_history(gl->glh, gl_write_fn, gl, "%N %T %H\r\n", 0,
9657 count<=1 ? -1 : count);
9659 * Arrange for the input line to be redisplayed.
9661 gl_queue_redisplay(gl);
9662 return 0;
9665 /*.......................................................................
9666 * Specify whether text that users type should be displayed or hidden.
9667 * In the latter case, only the prompt is displayed, and the final
9668 * input line is not archived in the history list.
9670 * Input:
9671 * gl GetLine * The gl_get_line() resource object.
9672 * enable int 0 - Disable echoing.
9673 * 1 - Enable echoing.
9674 * -1 - Just query the mode without changing it.
9675 * Output:
9676 * return int The echoing disposition that was in effect
9677 * before this function was called:
9678 * 0 - Echoing was disabled.
9679 * 1 - Echoing was enabled.
9681 int gl_echo_mode(GetLine *gl, int enable)
9683 if(gl) {
9684 sigset_t oldset; /* The signals that were blocked on entry to this block */
9685 int was_echoing; /* The echoing disposition on entry to this function */
9687 * Temporarily block all signals.
9689 gl_mask_signals(gl, &oldset);
9691 * Install the new disposition while signals are blocked.
9693 was_echoing = gl->echo;
9694 if(enable >= 0)
9695 gl->echo = enable;
9697 * Restore the process signal mask before returning.
9699 gl_unmask_signals(gl, &oldset);
9701 * Return the original echoing disposition.
9703 return was_echoing;
9705 return 1;
9708 /*.......................................................................
9709 * Display the prompt.
9711 * Input:
9712 * gl GetLine * The resource object of gl_get_line().
9713 * Output:
9714 * return int 0 - OK.
9715 * 1 - Error.
9717 static int gl_display_prompt(GetLine *gl)
9719 const char *pptr; /* A pointer into gl->prompt[] */
9720 unsigned old_attr=0; /* The current text display attributes */
9721 unsigned new_attr=0; /* The requested text display attributes */
9723 * Temporarily switch to echoing output characters.
9725 int kept_echo = gl->echo;
9726 gl->echo = 1;
9728 * In case the screen got messed up, send a carriage return to
9729 * put the cursor at the beginning of the current terminal line.
9731 if(gl_print_control_sequence(gl, 1, gl->bol))
9732 return 1;
9734 * Mark the line as partially displayed.
9736 gl->displayed = 1;
9738 * Write the prompt, using the currently selected prompt style.
9740 switch(gl->prompt_style) {
9741 case GL_LITERAL_PROMPT:
9742 if(gl_print_string(gl, gl->prompt, '\0'))
9743 return 1;
9744 break;
9745 case GL_FORMAT_PROMPT:
9746 for(pptr=gl->prompt; *pptr; pptr++) {
9748 * Does the latest character appear to be the start of a directive?
9750 if(*pptr == '%') {
9752 * Check for and act on attribute changing directives.
9754 switch(pptr[1]) {
9756 * Add or remove a text attribute from the new set of attributes.
9758 case 'B': case 'U': case 'S': case 'P': case 'F': case 'V':
9759 case 'b': case 'u': case 's': case 'p': case 'f': case 'v':
9760 switch(*++pptr) {
9761 case 'B': /* Switch to a bold font */
9762 new_attr |= GL_TXT_BOLD;
9763 break;
9764 case 'b': /* Switch to a non-bold font */
9765 new_attr &= ~GL_TXT_BOLD;
9766 break;
9767 case 'U': /* Start underlining */
9768 new_attr |= GL_TXT_UNDERLINE;
9769 break;
9770 case 'u': /* Stop underlining */
9771 new_attr &= ~GL_TXT_UNDERLINE;
9772 break;
9773 case 'S': /* Start highlighting */
9774 new_attr |= GL_TXT_STANDOUT;
9775 break;
9776 case 's': /* Stop highlighting */
9777 new_attr &= ~GL_TXT_STANDOUT;
9778 break;
9779 case 'P': /* Switch to a pale font */
9780 new_attr |= GL_TXT_DIM;
9781 break;
9782 case 'p': /* Switch to a non-pale font */
9783 new_attr &= ~GL_TXT_DIM;
9784 break;
9785 case 'F': /* Switch to a flashing font */
9786 new_attr |= GL_TXT_BLINK;
9787 break;
9788 case 'f': /* Switch to a steady font */
9789 new_attr &= ~GL_TXT_BLINK;
9790 break;
9791 case 'V': /* Switch to reverse video */
9792 new_attr |= GL_TXT_REVERSE;
9793 break;
9794 case 'v': /* Switch out of reverse video */
9795 new_attr &= ~GL_TXT_REVERSE;
9796 break;
9798 continue;
9800 * A literal % is represented by %%. Skip the leading %.
9802 case '%':
9803 pptr++;
9804 break;
9808 * Many terminals, when asked to turn off a single text attribute, turn
9809 * them all off, so the portable way to turn one off individually is to
9810 * explicitly turn them all off, then specify those that we want from
9811 * scratch.
9813 if(old_attr & ~new_attr) {
9814 if(gl_print_control_sequence(gl, 1, gl->text_attr_off))
9815 return 1;
9816 old_attr = 0;
9819 * Install new text attributes?
9821 if(new_attr != old_attr) {
9822 if(new_attr & GL_TXT_BOLD && !(old_attr & GL_TXT_BOLD) &&
9823 gl_print_control_sequence(gl, 1, gl->bold))
9824 return 1;
9825 if(new_attr & GL_TXT_UNDERLINE && !(old_attr & GL_TXT_UNDERLINE) &&
9826 gl_print_control_sequence(gl, 1, gl->underline))
9827 return 1;
9828 if(new_attr & GL_TXT_STANDOUT && !(old_attr & GL_TXT_STANDOUT) &&
9829 gl_print_control_sequence(gl, 1, gl->standout))
9830 return 1;
9831 if(new_attr & GL_TXT_DIM && !(old_attr & GL_TXT_DIM) &&
9832 gl_print_control_sequence(gl, 1, gl->dim))
9833 return 1;
9834 if(new_attr & GL_TXT_REVERSE && !(old_attr & GL_TXT_REVERSE) &&
9835 gl_print_control_sequence(gl, 1, gl->reverse))
9836 return 1;
9837 if(new_attr & GL_TXT_BLINK && !(old_attr & GL_TXT_BLINK) &&
9838 gl_print_control_sequence(gl, 1, gl->blink))
9839 return 1;
9840 old_attr = new_attr;
9843 * Display the latest character.
9845 if(gl_print_char(gl, *pptr, pptr[1]))
9846 return 1;
9849 * Turn off all text attributes now that we have finished drawing
9850 * the prompt.
9852 if(gl_print_control_sequence(gl, 1, gl->text_attr_off))
9853 return 1;
9854 break;
9857 * Restore the original echo mode.
9859 gl->echo = kept_echo;
9861 * The prompt has now been displayed at least once.
9863 gl->prompt_changed = 0;
9864 return 0;
9867 /*.......................................................................
9868 * This function can be called from gl_get_line() callbacks to have
9869 * the prompt changed when they return. It has no effect if gl_get_line()
9870 * is not currently being invoked.
9872 * Input:
9873 * gl GetLine * The resource object of gl_get_line().
9874 * prompt const char * The new prompt.
9876 void gl_replace_prompt(GetLine *gl, const char *prompt)
9878 if(gl) {
9879 sigset_t oldset; /* The signals that were blocked on entry to this block */
9881 * Temporarily block all signals.
9883 gl_mask_signals(gl, &oldset);
9885 * Replace the prompt.
9887 _gl_replace_prompt(gl, prompt);
9889 * Restore the process signal mask before returning.
9891 gl_unmask_signals(gl, &oldset);
9895 /*.......................................................................
9896 * This is the private body of the gl_replace_prompt() function. It
9897 * assumes that the caller has checked its arguments and blocked the
9898 * delivery of signals.
9900 static void _gl_replace_prompt(GetLine *gl, const char *prompt)
9902 size_t size;
9905 * Substitute an empty prompt?
9907 if(!prompt)
9908 prompt = "";
9910 * Gaurd against aliasing between prompt and gl->prompt.
9912 if(gl->prompt != prompt) {
9914 * Get the length of the new prompt string.
9916 size_t slen = strlen(prompt);
9918 * If needed, allocate a new buffer for the prompt string.
9920 size = sizeof(char) * (slen + 1);
9921 if(!gl->prompt || slen > strlen(gl->prompt)) {
9922 char *new_prompt = gl->prompt ? realloc(gl->prompt, size) : malloc(size);
9923 if(!new_prompt)
9924 return;
9925 gl->prompt = new_prompt;
9928 * Make a copy of the new prompt.
9930 strlcpy(gl->prompt, prompt, size);
9933 * Record the statistics of the new prompt.
9935 gl->prompt_len = gl_displayed_prompt_width(gl);
9936 gl->prompt_changed = 1;
9937 gl_queue_redisplay(gl);
9938 return;
9941 /*.......................................................................
9942 * Work out the length of the current prompt on the terminal, according
9943 * to the current prompt formatting style.
9945 * Input:
9946 * gl GetLine * The resource object of this library.
9947 * Output:
9948 * return int The number of displayed characters.
9950 static int gl_displayed_prompt_width(GetLine *gl)
9952 int slen=0; /* The displayed number of characters */
9953 const char *pptr; /* A pointer into prompt[] */
9955 * The length differs according to the prompt display style.
9957 switch(gl->prompt_style) {
9958 case GL_LITERAL_PROMPT:
9959 return gl_displayed_string_width(gl, gl->prompt, -1, 0);
9960 break;
9961 case GL_FORMAT_PROMPT:
9963 * Add up the length of the displayed string, while filtering out
9964 * attribute directives.
9966 for(pptr=gl->prompt; *pptr; pptr++) {
9968 * Does the latest character appear to be the start of a directive?
9970 if(*pptr == '%') {
9972 * Check for and skip attribute changing directives.
9974 switch(pptr[1]) {
9975 case 'B': case 'b': case 'U': case 'u': case 'S': case 's':
9976 pptr++;
9977 continue;
9979 * A literal % is represented by %%. Skip the leading %.
9981 case '%':
9982 pptr++;
9983 break;
9986 slen += gl_displayed_char_width(gl, *pptr, slen);
9988 break;
9990 return slen;
9993 /*.......................................................................
9994 * Specify whether to heed text attribute directives within prompt
9995 * strings.
9997 * Input:
9998 * gl GetLine * The resource object of gl_get_line().
9999 * style GlPromptStyle The style of prompt (see the definition of
10000 * GlPromptStyle in libtecla.h for details).
10002 void gl_prompt_style(GetLine *gl, GlPromptStyle style)
10004 if(gl) {
10005 sigset_t oldset; /* The signals that were blocked on entry to this block */
10007 * Temporarily block all signals.
10009 gl_mask_signals(gl, &oldset);
10011 * Install the new style in gl while signals are blocked.
10013 if(style != gl->prompt_style) {
10014 gl->prompt_style = style;
10015 gl->prompt_len = gl_displayed_prompt_width(gl);
10016 gl->prompt_changed = 1;
10017 gl_queue_redisplay(gl);
10020 * Restore the process signal mask before returning.
10022 gl_unmask_signals(gl, &oldset);
10026 /*.......................................................................
10027 * Tell gl_get_line() how to respond to a given signal. This can be used
10028 * both to override the default responses to signals that gl_get_line()
10029 * normally catches and to add new signals to the list that are to be
10030 * caught.
10032 * Input:
10033 * gl GetLine * The resource object of gl_get_line().
10034 * signo int The number of the signal to be caught.
10035 * flags unsigned A bitwise union of GlSignalFlags enumerators.
10036 * after GlAfterSignal What to do after the application's signal
10037 * handler has been called.
10038 * errno_value int The value to set errno to.
10039 * Output:
10040 * return int 0 - OK.
10041 * 1 - Error.
10043 int gl_trap_signal(GetLine *gl, int signo, unsigned flags,
10044 GlAfterSignal after, int errno_value)
10046 sigset_t oldset; /* The signals that were blocked on entry to this function */
10047 int status; /* The return status of this function */
10049 * Check the arguments.
10051 if(!gl) {
10052 errno = EINVAL;
10053 return 1;
10056 * Block all signals while modifying the contents of gl.
10058 if(gl_mask_signals(gl, &oldset))
10059 return 1;
10061 * Perform the modification while signals are blocked.
10063 status = _gl_trap_signal(gl, signo, flags, after, errno_value);
10065 * Restore the process signal mask before returning.
10067 gl_unmask_signals(gl, &oldset);
10068 return status;
10071 /*.......................................................................
10072 * This is the private body of the gl_trap_signal() function. It
10073 * assumes that the caller has checked its arguments and blocked the
10074 * delivery of signals.
10076 static int _gl_trap_signal(GetLine *gl, int signo, unsigned flags,
10077 GlAfterSignal after, int errno_value)
10079 GlSignalNode *sig;
10081 * Complain if an attempt is made to trap untrappable signals.
10082 * These would otherwise cause errors later in gl_mask_signals().
10084 if(0
10085 #ifdef SIGKILL
10086 || signo==SIGKILL
10087 #endif
10088 #ifdef SIGBLOCK
10089 || signo==SIGBLOCK
10090 #endif
10092 return 1;
10095 * See if the signal has already been registered.
10097 for(sig=gl->sigs; sig && sig->signo != signo; sig = sig->next)
10100 * If the signal hasn't already been registered, allocate a node for
10101 * it.
10103 if(!sig) {
10104 sig = (GlSignalNode *) _new_FreeListNode(gl->sig_mem);
10105 if(!sig)
10106 return 1;
10108 * Add the new node to the head of the list.
10110 sig->next = gl->sigs;
10111 gl->sigs = sig;
10113 * Record the signal number.
10115 sig->signo = signo;
10117 * Create a signal set that includes just this signal.
10119 sigemptyset(&sig->proc_mask);
10120 if(sigaddset(&sig->proc_mask, signo) == -1) {
10121 _err_record_msg(gl->err, "sigaddset error", END_ERR_MSG);
10122 sig = (GlSignalNode *) _del_FreeListNode(gl->sig_mem, sig);
10123 return 1;
10126 * Add the signal to the bit-mask of signals being trapped.
10128 sigaddset(&gl->all_signal_set, signo);
10131 * Record the new signal attributes.
10133 sig->flags = flags;
10134 sig->after = after;
10135 sig->errno_value = errno_value;
10136 return 0;
10139 /*.......................................................................
10140 * Remove a signal from the list of signals that gl_get_line() traps.
10142 * Input:
10143 * gl GetLine * The resource object of gl_get_line().
10144 * signo int The number of the signal to be ignored.
10145 * Output:
10146 * return int 0 - OK.
10147 * 1 - Error.
10149 int gl_ignore_signal(GetLine *gl, int signo)
10151 GlSignalNode *sig; /* The gl->sigs list node of the specified signal */
10152 GlSignalNode *prev; /* The node that precedes sig in the list */
10153 sigset_t oldset; /* The signals that were blocked on entry to this */
10154 /* function. */
10156 * Check the arguments.
10158 if(!gl) {
10159 errno = EINVAL;
10160 return 1;
10163 * Block all signals while modifying the contents of gl.
10165 if(gl_mask_signals(gl, &oldset))
10166 return 1;
10168 * Find the node of the gl->sigs list which records the disposition
10169 * of the specified signal.
10171 for(prev=NULL,sig=gl->sigs; sig && sig->signo != signo;
10172 prev=sig,sig=sig->next)
10174 if(sig) {
10176 * Remove the node from the list.
10178 if(prev)
10179 prev->next = sig->next;
10180 else
10181 gl->sigs = sig->next;
10183 * Return the node to the freelist.
10185 sig = (GlSignalNode *) _del_FreeListNode(gl->sig_mem, sig);
10187 * Remove the signal from the bit-mask union of signals being trapped.
10189 sigdelset(&gl->all_signal_set, signo);
10192 * Restore the process signal mask before returning.
10194 gl_unmask_signals(gl, &oldset);
10195 return 0;
10198 /*.......................................................................
10199 * This function is called when an input line has been completed. It
10200 * appends the specified newline character, terminates the line,
10201 * records the line in the history buffer if appropriate, and positions
10202 * the terminal cursor at the start of the next line.
10204 * Input:
10205 * gl GetLine * The resource object of gl_get_line().
10206 * newline_char int The newline character to add to the end
10207 * of the line.
10208 * Output:
10209 * return int 0 - OK.
10210 * 1 - Error.
10212 static int gl_line_ended(GetLine *gl, int newline_char)
10215 * If the newline character is printable, display it at the end of
10216 * the line, and add it to the input line buffer.
10218 if(isprint((int)(unsigned char) newline_char)) {
10219 if(gl_end_of_line(gl, 1, NULL) || gl_add_char_to_line(gl, newline_char))
10220 return 1;
10221 } else {
10223 * Otherwise just append a newline character to the input line buffer.
10225 newline_char = '\n';
10226 gl_buffer_char(gl, newline_char, gl->ntotal);
10229 * Add the line to the history buffer if it was entered with a
10230 * newline character.
10232 if(gl->echo && gl->automatic_history && newline_char=='\n')
10233 (void) _gl_append_history(gl, gl->line);
10235 * Except when depending on the system-provided line editing, start a new
10236 * line after the end of the line that has just been entered.
10238 if(gl->editor != GL_NO_EDITOR && gl_start_newline(gl, 1))
10239 return 1;
10241 * Record the successful return status.
10243 gl_record_status(gl, GLR_NEWLINE, 0);
10245 * Attempt to flush any pending output.
10247 (void) gl_flush_output(gl);
10249 * The next call to gl_get_line() will write the prompt for a new line
10250 * (or continue the above flush if incomplete), so if we manage to
10251 * flush the terminal now, report that we are waiting to write to the
10252 * terminal.
10254 gl->pending_io = GLP_WRITE;
10255 return 0;
10258 /*.......................................................................
10259 * Return the last signal that was caught by the most recent call to
10260 * gl_get_line(), or -1 if no signals were caught. This is useful if
10261 * gl_get_line() returns errno=EINTR and you need to find out what signal
10262 * caused it to abort.
10264 * Input:
10265 * gl GetLine * The resource object of gl_get_line().
10266 * Output:
10267 * return int The last signal caught by the most recent
10268 * call to gl_get_line(), or -1 if no signals
10269 * were caught.
10271 int gl_last_signal(GetLine *gl)
10273 int signo = -1; /* The requested signal number */
10274 if(gl) {
10275 sigset_t oldset; /* The signals that were blocked on entry to this block */
10277 * Temporarily block all signals.
10279 gl_mask_signals(gl, &oldset);
10281 * Access gl now that signals are blocked.
10283 signo = gl->last_signal;
10285 * Restore the process signal mask before returning.
10287 gl_unmask_signals(gl, &oldset);
10289 return signo;
10292 /*.......................................................................
10293 * Prepare to edit a new line.
10295 * Input:
10296 * gl GetLine * The resource object of this library.
10297 * prompt char * The prompt to prefix the line with, or NULL to
10298 * use the same prompt that was used by the previous
10299 * line.
10300 * start_line char * The initial contents of the input line, or NULL
10301 * if it should start out empty.
10302 * start_pos int If start_line isn't NULL, this specifies the
10303 * index of the character over which the cursor
10304 * should initially be positioned within the line.
10305 * If you just want it to follow the last character
10306 * of the line, send -1.
10307 * Output:
10308 * return int 0 - OK.
10309 * 1 - Error.
10311 static int gl_present_line(GetLine *gl, const char *prompt,
10312 const char *start_line, int start_pos)
10315 * Reset the properties of the line.
10317 gl_reset_input_line(gl);
10319 * Record the new prompt and its displayed width.
10321 if(prompt)
10322 _gl_replace_prompt(gl, prompt);
10324 * Reset the history search pointers.
10326 if(_glh_cancel_search(gl->glh)) {
10327 _err_record_msg(gl->err, _glh_last_error(gl->glh), END_ERR_MSG);
10328 return 1;
10331 * If the previous line was entered via the repeat-history action,
10332 * preload the specified history line.
10334 if(gl->preload_history) {
10335 gl->preload_history = 0;
10336 if(gl->preload_id) {
10337 if(_glh_recall_line(gl->glh, gl->preload_id, gl->line, gl->linelen+1)) {
10338 gl_update_buffer(gl); /* Compute gl->ntotal etc.. */
10339 gl->buff_curpos = gl->ntotal;
10340 } else {
10341 gl_truncate_buffer(gl, 0);
10343 gl->preload_id = 0;
10346 * Present a specified initial line?
10348 } else if(start_line) {
10349 char *cptr; /* A pointer into gl->line[] */
10351 * Measure the length of the starting line.
10353 int start_len = strlen(start_line);
10355 * If the length of the line is greater than the available space,
10356 * truncate it.
10358 if(start_len > gl->linelen)
10359 start_len = gl->linelen;
10361 * Load the line into the buffer.
10363 if(start_line != gl->line)
10364 gl_buffer_string(gl, start_line, start_len, 0);
10366 * Strip off any trailing newline and carriage return characters.
10368 for(cptr=gl->line + gl->ntotal - 1; cptr >= gl->line &&
10369 (*cptr=='\n' || *cptr=='\r'); cptr--,gl->ntotal--)
10371 gl_truncate_buffer(gl, gl->ntotal < 0 ? 0 : gl->ntotal);
10373 * Where should the cursor be placed within the line?
10375 if(start_pos < 0 || start_pos > gl->ntotal) {
10376 if(gl_place_cursor(gl, gl->ntotal))
10377 return 1;
10378 } else {
10379 if(gl_place_cursor(gl, start_pos))
10380 return 1;
10383 * Clear the input line?
10385 } else {
10386 gl_truncate_buffer(gl, 0);
10389 * Arrange for the line to be displayed by gl_flush_output().
10391 gl_queue_redisplay(gl);
10393 * Update the display.
10395 return gl_flush_output(gl);
10398 /*.......................................................................
10399 * Reset all line input parameters for a new input line.
10401 * Input:
10402 * gl GetLine * The line editor resource object.
10404 static void gl_reset_input_line(GetLine *gl)
10406 gl->ntotal = 0;
10407 gl->line[0] = '\0';
10408 gl->buff_curpos = 0;
10409 gl->term_curpos = 0;
10410 gl->term_len = 0;
10411 gl->insert_curpos = 0;
10412 gl->number = -1;
10413 gl->displayed = 0;
10414 gl->endline = 0;
10415 gl->redisplay = 0;
10416 gl->postpone = 0;
10417 gl->nbuf = 0;
10418 gl->nread = 0;
10419 gl->vi.command = 0;
10420 gl->vi.undo.line[0] = '\0';
10421 gl->vi.undo.ntotal = 0;
10422 gl->vi.undo.buff_curpos = 0;
10423 gl->vi.repeat.action.fn = 0;
10424 gl->vi.repeat.action.data = 0;
10425 gl->last_signal = -1;
10428 /*.......................................................................
10429 * Print an informational message to the terminal, after starting a new
10430 * line.
10432 * Input:
10433 * gl GetLine * The line editor resource object.
10434 * ... const char * Zero or more strings to be printed.
10435 * ... void * The last argument must always be GL_END_INFO.
10436 * Output:
10437 * return int 0 - OK.
10438 * 1 - Error.
10440 static int gl_print_info(GetLine *gl, ...)
10442 va_list ap; /* The variable argument list */
10443 const char *s; /* The string being printed */
10444 int waserr = 0; /* True after an error */
10446 * Only display output when echoing is on.
10448 if(gl->echo) {
10450 * Skip to the start of the next empty line before displaying the message.
10452 if(gl_start_newline(gl, 1))
10453 return 1;
10455 * Display the list of provided messages.
10457 va_start(ap, gl);
10458 while(!waserr && (s = va_arg(ap, const char *)) != GL_END_INFO)
10459 waserr = gl_print_raw_string(gl, 1, s, -1);
10460 va_end(ap);
10462 * Start a newline.
10464 waserr = waserr || gl_print_raw_string(gl, 1, "\n\r", -1);
10466 * Arrange for the input line to be redrawn.
10468 gl_queue_redisplay(gl);
10470 return waserr;
10473 /*.......................................................................
10474 * Go to the start of the next empty line, ready to output miscellaneous
10475 * text to the screen.
10477 * Note that when async-signal safety is required, the 'buffered'
10478 * argument must be 0.
10480 * Input:
10481 * gl GetLine * The line editor resource object.
10482 * buffered int If true, used buffered I/O when writing to
10483 * the terminal. Otherwise use async-signal-safe
10484 * unbuffered I/O.
10485 * Output:
10486 * return int 0 - OK.
10487 * 1 - Error.
10489 static int gl_start_newline(GetLine *gl, int buffered)
10491 int waserr = 0; /* True after any I/O error */
10493 * Move the cursor to the start of the terminal line that follows the
10494 * last line of the partially enterred line. In order that this
10495 * function remain async-signal safe when write_fn is signal safe, we
10496 * can't call our normal output functions, since they call tputs(),
10497 * who's signal saftey isn't defined. Fortunately, we can simply use
10498 * \r and \n to move the cursor to the right place.
10500 if(gl->displayed) { /* Is an input line currently displayed? */
10502 * On which terminal lines are the cursor and the last character of the
10503 * input line?
10505 int curs_line = gl->term_curpos / gl->ncolumn;
10506 int last_line = gl->term_len / gl->ncolumn;
10508 * Move the cursor to the start of the line that follows the last
10509 * terminal line that is occupied by the input line.
10511 for( ; curs_line < last_line + 1; curs_line++)
10512 waserr = waserr || gl_print_raw_string(gl, buffered, "\n", 1);
10513 waserr = waserr || gl_print_raw_string(gl, buffered, "\r", 1);
10515 * Mark the line as no longer displayed.
10517 gl_line_erased(gl);
10519 return waserr;
10522 /*.......................................................................
10523 * The callback through which all terminal output is routed.
10524 * This simply appends characters to a queue buffer, which is
10525 * subsequently flushed to the output channel by gl_flush_output().
10527 * Input:
10528 * data void * The pointer to a GetLine line editor resource object
10529 * cast to (void *).
10530 * s const char * The string to be written.
10531 * n int The number of characters to write from s[].
10532 * Output:
10533 * return int The number of characters written. This will always
10534 * be equal to 'n' unless an error occurs.
10536 static GL_WRITE_FN(gl_write_fn)
10538 GetLine *gl = (GetLine *) data;
10539 int ndone = _glq_append_chars(gl->cq, s, n, gl->flush_fn, gl);
10540 if(ndone != n)
10541 _err_record_msg(gl->err, _glq_last_error(gl->cq), END_ERR_MSG);
10542 return ndone;
10545 /*.......................................................................
10546 * Ask gl_get_line() what caused it to return.
10548 * Input:
10549 * gl GetLine * The line editor resource object.
10550 * Output:
10551 * return GlReturnStatus The return status of the last call to
10552 * gl_get_line().
10554 GlReturnStatus gl_return_status(GetLine *gl)
10556 GlReturnStatus rtn_status = GLR_ERROR; /* The requested status */
10557 if(gl) {
10558 sigset_t oldset; /* The signals that were blocked on entry to this block */
10560 * Temporarily block all signals.
10562 gl_mask_signals(gl, &oldset);
10564 * Access gl while signals are blocked.
10566 rtn_status = gl->rtn_status;
10568 * Restore the process signal mask before returning.
10570 gl_unmask_signals(gl, &oldset);
10572 return rtn_status;
10575 /*.......................................................................
10576 * In non-blocking server-I/O mode, this function should be called
10577 * from the application's external event loop to see what type of
10578 * terminal I/O is being waited for by gl_get_line(), and thus what
10579 * direction of I/O to wait for with select() or poll().
10581 * Input:
10582 * gl GetLine * The resource object of gl_get_line().
10583 * Output:
10584 * return GlPendingIO The type of pending I/O being waited for.
10586 GlPendingIO gl_pending_io(GetLine *gl)
10588 GlPendingIO pending_io = GLP_WRITE; /* The requested information */
10589 if(gl) {
10590 sigset_t oldset; /* The signals that were blocked on entry to this block */
10592 * Temporarily block all signals.
10594 gl_mask_signals(gl, &oldset);
10596 * Access gl while signals are blocked.
10598 pending_io = gl->pending_io;
10600 * Restore the process signal mask before returning.
10602 gl_unmask_signals(gl, &oldset);
10604 return pending_io;
10607 /*.......................................................................
10608 * In server mode, this function configures the terminal for non-blocking
10609 * raw terminal I/O. In normal I/O mode it does nothing.
10611 * Callers of this function must be careful to trap all signals that
10612 * terminate or suspend the program, and call gl_normal_io()
10613 * from the corresponding signal handlers in order to restore the
10614 * terminal to its original settings before the program is terminated
10615 * or suspended. They should also trap the SIGCONT signal to detect
10616 * when the program resumes, and ensure that its signal handler
10617 * call gl_raw_io() to redisplay the line and resume editing.
10619 * This function is async signal safe.
10621 * Input:
10622 * gl GetLine * The line editor resource object.
10623 * Output:
10624 * return int 0 - OK.
10625 * 1 - Error.
10627 int gl_raw_io(GetLine *gl)
10629 sigset_t oldset; /* The signals that were blocked on entry to this function */
10630 int status; /* The return status of _gl_raw_io() */
10632 * Check the arguments.
10634 if(!gl) {
10635 errno = EINVAL;
10636 return 1;
10639 * Block all signals.
10641 if(gl_mask_signals(gl, &oldset))
10642 return 1;
10644 * Don't allow applications to switch into raw mode unless in server mode.
10646 if(gl->io_mode != GL_SERVER_MODE) {
10647 _err_record_msg(gl->err, "Can't switch to raw I/O unless in server mode",
10648 END_ERR_MSG);
10649 errno = EPERM;
10650 status = 1;
10651 } else {
10653 * Execute the private body of the function while signals are blocked.
10655 status = _gl_raw_io(gl, 1);
10658 * Restore the process signal mask.
10660 gl_unmask_signals(gl, &oldset);
10661 return status;
10664 /*.......................................................................
10665 * This is the private body of the public function, gl_raw_io().
10666 * It assumes that the caller has checked its arguments and blocked the
10667 * delivery of signals.
10669 * This function is async signal safe.
10671 static int _gl_raw_io(GetLine *gl, int redisplay)
10674 * If we are already in the correct mode, do nothing.
10676 if(gl->raw_mode)
10677 return 0;
10679 * Switch the terminal to raw mode.
10681 if(gl->is_term && gl_raw_terminal_mode(gl))
10682 return 1;
10684 * Switch to non-blocking I/O mode?
10686 if(gl->io_mode==GL_SERVER_MODE &&
10687 (gl_nonblocking_io(gl, gl->input_fd) ||
10688 gl_nonblocking_io(gl, gl->output_fd) ||
10689 (gl->file_fp && gl_nonblocking_io(gl, fileno(gl->file_fp))))) {
10690 if(gl->is_term)
10691 gl_restore_terminal_attributes(gl);
10692 return 1;
10695 * If an input line is being entered, arrange for it to be
10696 * displayed.
10698 if(redisplay) {
10699 gl->postpone = 0;
10700 gl_queue_redisplay(gl);
10702 return 0;
10705 /*.......................................................................
10706 * Restore the terminal to the state that it had when
10707 * gl_raw_io() was last called. After calling
10708 * gl_raw_io(), this function must be called before
10709 * terminating or suspending the program, and before attempting other
10710 * uses of the terminal from within the program. See gl_raw_io()
10711 * for more details.
10713 * Input:
10714 * gl GetLine * The line editor resource object.
10715 * Output:
10716 * return int 0 - OK.
10717 * 1 - Error.
10719 int gl_normal_io(GetLine *gl)
10721 sigset_t oldset; /* The signals that were blocked on entry to this function */
10722 int status; /* The return status of _gl_normal_io() */
10724 * Check the arguments.
10726 if(!gl) {
10727 errno = EINVAL;
10728 return 1;
10731 * Block all signals.
10733 if(gl_mask_signals(gl, &oldset))
10734 return 1;
10736 * Execute the private body of the function while signals are blocked.
10738 status = _gl_normal_io(gl);
10740 * Restore the process signal mask.
10742 gl_unmask_signals(gl, &oldset);
10743 return status;
10746 /*.......................................................................
10747 * This is the private body of the public function, gl_normal_io().
10748 * It assumes that the caller has checked its arguments and blocked the
10749 * delivery of signals.
10751 static int _gl_normal_io(GetLine *gl)
10754 * If we are already in normal mode, do nothing.
10756 if(!gl->raw_mode)
10757 return 0;
10759 * Postpone subsequent redisplays until after _gl_raw_io(gl, 1)
10760 * is next called.
10762 gl->postpone = 1;
10764 * Switch back to blocking I/O. Note that this is essential to do
10765 * here, because when using non-blocking I/O, the terminal output
10766 * buffering code can't always make room for new output without calling
10767 * malloc(), and a call to malloc() would mean that this function
10768 * couldn't safely be called from signal handlers.
10770 if(gl->io_mode==GL_SERVER_MODE &&
10771 (gl_blocking_io(gl, gl->input_fd) ||
10772 gl_blocking_io(gl, gl->output_fd) ||
10773 (gl->file_fp && gl_blocking_io(gl, fileno(gl->file_fp)))))
10774 return 1;
10776 * Move the cursor to the next empty terminal line. Note that
10777 * unbuffered I/O is requested, to ensure that gl_start_newline() be
10778 * async-signal-safe.
10780 if(gl->is_term && gl_start_newline(gl, 0))
10781 return 1;
10783 * Switch the terminal to normal mode.
10785 if(gl->is_term && gl_restore_terminal_attributes(gl)) {
10787 * On error, revert to non-blocking I/O if needed, so that on failure
10788 * we remain in raw mode.
10790 if(gl->io_mode==GL_SERVER_MODE) {
10791 gl_nonblocking_io(gl, gl->input_fd);
10792 gl_nonblocking_io(gl, gl->output_fd);
10793 if(gl->file_fp)
10794 gl_nonblocking_io(gl, fileno(gl->file_fp));
10796 return 1;
10798 return 0;
10801 /*.......................................................................
10802 * This function allows you to install an additional completion
10803 * action, or to change the completion function of an existing
10804 * one. This should be called before the first call to gl_get_line()
10805 * so that the name of the action be defined before the user's
10806 * configuration file is read.
10808 * Input:
10809 * gl GetLine * The resource object of the command-line input
10810 * module.
10811 * data void * This is passed to match_fn() whenever it is
10812 * called. It could, for example, point to a
10813 * symbol table that match_fn() would look up
10814 * matches in.
10815 * match_fn CplMatchFn * The function that will identify the prefix
10816 * to be completed from the input line, and
10817 * report matching symbols.
10818 * list_only int If non-zero, install an action that only lists
10819 * possible completions, rather than attempting
10820 * to perform the completion.
10821 * name const char * The name with which users can refer to the
10822 * binding in tecla configuration files.
10823 * keyseq const char * Either NULL, or a key sequence with which
10824 * to invoke the binding. This should be
10825 * specified in the same manner as key-sequences
10826 * in tecla configuration files (eg. "M-^I").
10827 * Output:
10828 * return int 0 - OK.
10829 * 1 - Error.
10831 int gl_completion_action(GetLine *gl, void *data, CplMatchFn *match_fn,
10832 int list_only, const char *name, const char *keyseq)
10834 sigset_t oldset; /* The signals that were blocked on entry to this function */
10835 int status; /* The return status of _gl_completion_action() */
10837 * Check the arguments.
10839 if(!gl || !name || !match_fn) {
10840 errno = EINVAL;
10841 return 1;
10844 * Block all signals.
10846 if(gl_mask_signals(gl, &oldset))
10847 return 1;
10849 * Install the new action while signals are blocked.
10851 status = _gl_completion_action(gl, data, match_fn, list_only, name, keyseq);
10853 * Restore the process signal mask.
10855 gl_unmask_signals(gl, &oldset);
10856 return status;
10859 /*.......................................................................
10860 * This is the private body of the public function, gl_completion_action().
10861 * It assumes that the caller has checked its arguments and blocked the
10862 * delivery of signals.
10864 static int _gl_completion_action(GetLine *gl, void *data, CplMatchFn *match_fn,
10865 int list_only, const char *name,
10866 const char *keyseq)
10868 KtKeyFn *current_fn; /* An existing action function */
10869 void *current_data; /* The action-function callback data */
10871 * Which action function is desired?
10873 KtKeyFn *action_fn = list_only ? gl_list_completions : gl_complete_word;
10875 * Is there already an action of the specified name?
10877 if(_kt_lookup_action(gl->bindings, name, &current_fn, &current_data) == 0) {
10879 * If the action has the same type as the one being requested,
10880 * simply change the contents of its GlCplCallback callback data.
10882 if(current_fn == action_fn) {
10883 GlCplCallback *cb = (GlCplCallback *) current_data;
10884 cb->fn = match_fn;
10885 cb->data = data;
10886 } else {
10887 errno = EINVAL;
10888 _err_record_msg(gl->err,
10889 "Illegal attempt to change the type of an existing completion action",
10890 END_ERR_MSG);
10891 return 1;
10894 * No existing action has the specified name.
10896 } else {
10898 * Allocate a new GlCplCallback callback object.
10900 GlCplCallback *cb = (GlCplCallback *) _new_FreeListNode(gl->cpl_mem);
10901 if(!cb) {
10902 errno = ENOMEM;
10903 _err_record_msg(gl->err, "Insufficient memory to add completion action",
10904 END_ERR_MSG);
10905 return 1;
10908 * Record the completion callback data.
10910 cb->fn = match_fn;
10911 cb->data = data;
10913 * Attempt to register the new action.
10915 if(_kt_set_action(gl->bindings, name, action_fn, cb)) {
10916 _err_record_msg(gl->err, _kt_last_error(gl->bindings), END_ERR_MSG);
10917 _del_FreeListNode(gl->cpl_mem, (void *) cb);
10918 return 1;
10922 * Bind the action to a given key-sequence?
10924 if(keyseq && _kt_set_keybinding(gl->bindings, KTB_NORM, keyseq, name)) {
10925 _err_record_msg(gl->err, _kt_last_error(gl->bindings), END_ERR_MSG);
10926 return 1;
10928 return 0;
10931 /*.......................................................................
10932 * Register an application-provided function as an action function.
10933 * This should preferably be called before the first call to gl_get_line()
10934 * so that the name of the action becomes defined before the user's
10935 * configuration file is read.
10937 * Input:
10938 * gl GetLine * The resource object of the command-line input
10939 * module.
10940 * data void * Arbitrary application-specific callback
10941 * data to be passed to the callback
10942 * function, fn().
10943 * fn GlActionFn * The application-specific function that
10944 * implements the action. This will be invoked
10945 * whenever the user presses any
10946 * key-sequence which is bound to this action.
10947 * name const char * The name with which users can refer to the
10948 * binding in tecla configuration files.
10949 * keyseq const char * The key sequence with which to invoke
10950 * the binding. This should be specified in the
10951 * same manner as key-sequences in tecla
10952 * configuration files (eg. "M-^I").
10953 * Output:
10954 * return int 0 - OK.
10955 * 1 - Error.
10957 int gl_register_action(GetLine *gl, void *data, GlActionFn *fn,
10958 const char *name, const char *keyseq)
10960 sigset_t oldset; /* The signals that were blocked on entry to this function */
10961 int status; /* The return status of _gl_register_action() */
10963 * Check the arguments.
10965 if(!gl || !name || !fn) {
10966 errno = EINVAL;
10967 return 1;
10970 * Block all signals.
10972 if(gl_mask_signals(gl, &oldset))
10973 return 1;
10975 * Install the new action while signals are blocked.
10977 status = _gl_register_action(gl, data, fn, name, keyseq);
10979 * Restore the process signal mask.
10981 gl_unmask_signals(gl, &oldset);
10982 return status;
10985 /*.......................................................................
10986 * This is the private body of the public function, gl_register_action().
10987 * It assumes that the caller has checked its arguments and blocked the
10988 * delivery of signals.
10990 static int _gl_register_action(GetLine *gl, void *data, GlActionFn *fn,
10991 const char *name, const char *keyseq)
10993 KtKeyFn *current_fn; /* An existing action function */
10994 void *current_data; /* The action-function callback data */
10996 * Get the action function which actually runs the application-provided
10997 * function.
10999 KtKeyFn *action_fn = gl_run_external_action;
11001 * Is there already an action of the specified name?
11003 if(_kt_lookup_action(gl->bindings, name, &current_fn, &current_data) == 0) {
11005 * If the action has the same type as the one being requested,
11006 * simply change the contents of its GlCplCallback callback data.
11008 if(current_fn == action_fn) {
11009 GlExternalAction *a = (GlExternalAction *) current_data;
11010 a->fn = fn;
11011 a->data = data;
11012 } else {
11013 errno = EINVAL;
11014 _err_record_msg(gl->err,
11015 "Illegal attempt to change the type of an existing action",
11016 END_ERR_MSG);
11017 return 1;
11020 * No existing action has the specified name.
11022 } else {
11024 * Allocate a new GlCplCallback callback object.
11026 GlExternalAction *a =
11027 (GlExternalAction *) _new_FreeListNode(gl->ext_act_mem);
11028 if(!a) {
11029 errno = ENOMEM;
11030 _err_record_msg(gl->err, "Insufficient memory to add completion action",
11031 END_ERR_MSG);
11032 return 1;
11035 * Record the completion callback data.
11037 a->fn = fn;
11038 a->data = data;
11040 * Attempt to register the new action.
11042 if(_kt_set_action(gl->bindings, name, action_fn, a)) {
11043 _err_record_msg(gl->err, _kt_last_error(gl->bindings), END_ERR_MSG);
11044 _del_FreeListNode(gl->cpl_mem, (void *) a);
11045 return 1;
11049 * Bind the action to a given key-sequence?
11051 if(keyseq && _kt_set_keybinding(gl->bindings, KTB_NORM, keyseq, name)) {
11052 _err_record_msg(gl->err, _kt_last_error(gl->bindings), END_ERR_MSG);
11053 return 1;
11055 return 0;
11058 /*.......................................................................
11059 * Invoke an action function previously registered by a call to
11060 * gl_register_action().
11062 static KT_KEY_FN(gl_run_external_action)
11064 GlAfterAction status; /* The return value of the action function */
11066 * Get the container of the action function and associated callback data.
11068 GlExternalAction *a = (GlExternalAction *) data;
11070 * Invoke the action function.
11072 status = a->fn(gl, a->data, count, gl->buff_curpos, gl->line);
11074 * If the callback took us out of raw (possibly non-blocking) input
11075 * mode, restore this mode, and queue a redisplay of the input line.
11077 if(_gl_raw_io(gl, 1))
11078 return 1;
11080 * Finally, check to see what the action function wants us to do next.
11082 switch(status) {
11083 default:
11084 case GLA_ABORT:
11085 gl_record_status(gl, GLR_ERROR, errno);
11086 return 1;
11087 break;
11088 case GLA_RETURN:
11089 return gl_newline(gl, 1, NULL);
11090 break;
11091 case GLA_CONTINUE:
11092 break;
11094 return 0;
11097 /*.......................................................................
11098 * In server-I/O mode the terminal is left in raw mode between calls
11099 * to gl_get_line(), so it is necessary for the application to install
11100 * terminal restoring signal handlers for signals that could terminate
11101 * or suspend the process, plus a terminal reconfiguration handler to
11102 * be called when a process resumption signal is received, and finally
11103 * a handler to be called when a terminal-resize signal is received.
11105 * Since there are many signals that by default terminate or suspend
11106 * processes, and different systems support different sub-sets of
11107 * these signals, this function provides a convenient wrapper around
11108 * sigaction() for assigning the specified handlers to all appropriate
11109 * signals. It also arranges that when any one of these signals is
11110 * being handled, all other catchable signals are blocked. This is
11111 * necessary so that the specified signal handlers can safely call
11112 * gl_raw_io(), gl_normal_io() and gl_update_size() without
11113 * reentrancy issues.
11115 * Input:
11116 * term_handler void (*)(int) The signal handler to invoke when
11117 * a process terminating signal is
11118 * received.
11119 * susp_handler void (*)(int) The signal handler to invoke when
11120 * a process suspending signal is
11121 * received.
11122 * cont_handler void (*)(int) The signal handler to invoke when
11123 * a process resumption signal is
11124 * received (ie. SIGCONT).
11125 * size_handler void (*)(int) The signal handler to invoke when
11126 * a terminal-resize signal (ie. SIGWINCH)
11127 * is received.
11128 * Output:
11129 * return int 0 - OK.
11130 * 1 - Error.
11132 int gl_tty_signals(void (*term_handler)(int), void (*susp_handler)(int),
11133 void (*cont_handler)(int), void (*size_handler)(int))
11135 int i;
11137 * Search for signals of the specified classes, and assign the
11138 * associated signal handler to them.
11140 for(i=0; i<sizeof(gl_signal_list)/sizeof(gl_signal_list[0]); i++) {
11141 const struct GlDefSignal *sig = gl_signal_list + i;
11142 if(sig->attr & GLSA_SUSP) {
11143 if(gl_set_tty_signal(sig->signo, term_handler))
11144 return 1;
11145 } else if(sig->attr & GLSA_TERM) {
11146 if(gl_set_tty_signal(sig->signo, susp_handler))
11147 return 1;
11148 } else if(sig->attr & GLSA_CONT) {
11149 if(gl_set_tty_signal(sig->signo, cont_handler))
11150 return 1;
11151 } else if(sig->attr & GLSA_SIZE) {
11152 if(gl_set_tty_signal(sig->signo, size_handler))
11153 return 1;
11156 return 0;
11159 /*.......................................................................
11160 * This is a private function of gl_tty_signals(). It installs a given
11161 * signal handler, and arranges that when that signal handler is being
11162 * invoked other signals are blocked. The latter is important to allow
11163 * functions like gl_normal_io(), gl_raw_io() and gl_update_size()
11164 * to be called from signal handlers.
11166 * Input:
11167 * signo int The signal to be trapped.
11168 * handler void (*)(int) The signal handler to assign to the signal.
11170 static int gl_set_tty_signal(int signo, void (*handler)(int))
11172 SigAction act; /* The signal handler configuation */
11174 * Arrange to block all trappable signals except the one that is being
11175 * assigned (the trapped signal will be blocked automatically by the
11176 * system).
11178 gl_list_trappable_signals(&act.sa_mask);
11179 sigdelset(&act.sa_mask, signo);
11181 * Assign the signal handler.
11183 act.sa_handler = handler;
11185 * There is only one portable signal handling flag, and it isn't
11186 * relevant to us, so don't specify any flags.
11188 act.sa_flags = 0;
11190 * Register the signal handler.
11192 if(sigaction(signo, &act, NULL))
11193 return 1;
11194 return 0;
11197 /*.......................................................................
11198 * Display a left-justified string over multiple terminal lines,
11199 * taking account of the current width of the terminal. Optional
11200 * indentation and an optional prefix string can be specified to be
11201 * displayed at the start of each new terminal line used. Similarly,
11202 * an optional suffix can be specified to be displayed at the end of
11203 * each terminal line. If needed, a single paragraph can be broken
11204 * across multiple calls. Note that literal newlines in the input
11205 * string can be used to force a newline at any point and that you
11206 * should use this feature to explicitly end all paragraphs, including
11207 * at the end of the last string that you write. Note that when a new
11208 * line is started between two words that are separated by spaces,
11209 * those spaces are not output, whereas when a new line is started
11210 * because a newline character was found in the string, only the
11211 * spaces before the newline character are discarded.
11213 * Input:
11214 * gl GetLine * The resource object of gl_get_line().
11215 * indentation int The number of spaces of indentation to write
11216 * at the beginning of each new terminal line.
11217 * prefix const char * An optional prefix string to write after the
11218 * indentation margin at the start of each new
11219 * terminal line. You can specify NULL if no
11220 * prefix is required.
11221 * suffix const char * An optional suffix string to draw at the end
11222 * of the terminal line. Spaces will be added
11223 * where necessary to ensure that the suffix ends
11224 * in the last column of the terminal line. If
11225 * no suffix is desired, specify NULL.
11226 * fill_char int The padding character to use when indenting
11227 * the line or padding up to the suffix.
11228 * def_width int If the terminal width isn't known, such as when
11229 * writing to a pipe or redirecting to a file,
11230 * this number specifies what width to assume.
11231 * start int The number of characters already written to
11232 * the start of the current terminal line. This
11233 * is primarily used to allow individual
11234 * paragraphs to be written over multiple calls
11235 * to this function, but can also be used to
11236 * allow you to start the first line of a
11237 * paragraph with a different prefix or
11238 * indentation than those specified above.
11239 * string const char * The string to be written.
11240 * Output:
11241 * return int On error -1 is returned. Otherwise the
11242 * return value is the terminal column index at
11243 * which the cursor was left after writing the
11244 * final word in the string. Successful return
11245 * values can thus be passed verbatim to the
11246 * 'start' arguments of subsequent calls to
11247 * gl_display_text() to allow the printing of a
11248 * paragraph to be broken across multiple calls
11249 * to gl_display_text().
11251 int gl_display_text(GetLine *gl, int indentation, const char *prefix,
11252 const char *suffix, int fill_char,
11253 int def_width, int start, const char *string)
11255 sigset_t oldset; /* The signals that were blocked on entry to this function */
11256 int status; /* The return status of _gl_completion_action() */
11258 * Check the arguments?
11260 if(!gl || !string) {
11261 errno = EINVAL;
11262 return -1;
11265 * Block all signals.
11267 if(gl_mask_signals(gl, &oldset))
11268 return -1;
11270 * Display the text while signals are blocked.
11272 status = _io_display_text(_io_write_stdio, gl->output_fp, indentation,
11273 prefix, suffix, fill_char,
11274 gl->ncolumn > 0 ? gl->ncolumn : def_width,
11275 start, string);
11277 * Restore the process signal mask.
11279 gl_unmask_signals(gl, &oldset);
11280 return status;
11283 /*.......................................................................
11284 * Block all of the signals that we are currently trapping.
11286 * Input:
11287 * gl GetLine * The resource object of gl_get_line().
11288 * Input/Output:
11289 * oldset sigset_t * The superseded process signal mask
11290 * will be return in *oldset unless oldset is
11291 * NULL.
11292 * Output:
11293 * return int 0 - OK.
11294 * 1 - Error.
11296 static int gl_mask_signals(GetLine *gl, sigset_t *oldset)
11299 * Block all signals in all_signal_set, along with any others that are
11300 * already blocked by the application.
11302 if(sigprocmask(SIG_BLOCK, &gl->all_signal_set, oldset) >= 0) {
11303 gl->signals_masked = 1;
11304 return 0;
11307 * On error attempt to query the current process signal mask, so
11308 * that oldset be the correct process signal mask to restore later
11309 * if the caller of this function ignores the error return value.
11311 if(oldset)
11312 (void) sigprocmask(SIG_SETMASK, NULL, oldset);
11313 gl->signals_masked = 0;
11314 return 1;
11317 /*.......................................................................
11318 * Restore a process signal mask that was previously returned via the
11319 * oldset argument of gl_mask_signals().
11321 * Input:
11322 * gl GetLine * The resource object of gl_get_line().
11323 * Input/Output:
11324 * oldset sigset_t * The process signal mask to be restored.
11325 * Output:
11326 * return int 0 - OK.
11327 * 1 - Error.
11329 static int gl_unmask_signals(GetLine *gl, sigset_t *oldset)
11331 gl->signals_masked = 0;
11332 return sigprocmask(SIG_SETMASK, oldset, NULL) < 0;
11335 /*.......................................................................
11336 * Arrange to temporarily catch the signals marked in gl->use_signal_set.
11338 * Input:
11339 * gl GetLine * The resource object of gl_get_line().
11340 * Output:
11341 * return int 0 - OK.
11342 * 1 - Error.
11344 static int gl_catch_signals(GetLine *gl)
11346 return sigprocmask(SIG_UNBLOCK, &gl->use_signal_set, NULL) < 0;
11349 /*.......................................................................
11350 * Select the I/O mode to be used by gl_get_line().
11352 * Input:
11353 * gl GetLine * The resource object of gl_get_line().
11354 * mode GlIOMode The I/O mode to establish.
11355 * Output:
11356 * return int 0 - OK.
11357 * 1 - Error.
11359 int gl_io_mode(GetLine *gl, GlIOMode mode)
11361 sigset_t oldset; /* The signals that were blocked on entry to this function */
11362 int status; /* The return status of _gl_io_mode() */
11364 * Check the arguments.
11366 if(!gl) {
11367 errno = EINVAL;
11368 return 1;
11371 * Check that the requested mode is known.
11373 switch(mode) {
11374 case GL_NORMAL_MODE:
11375 case GL_SERVER_MODE:
11376 break;
11377 default:
11378 errno = EINVAL;
11379 _err_record_msg(gl->err, "Unknown gl_get_line() I/O mode requested.",
11380 END_ERR_MSG);
11381 return 1;
11384 * Block all signals.
11386 if(gl_mask_signals(gl, &oldset))
11387 return 1;
11389 * Invoke the private body of this function.
11391 status = _gl_io_mode(gl, mode);
11393 * Restore the process signal mask.
11395 gl_unmask_signals(gl, &oldset);
11396 return status;
11399 /*.......................................................................
11400 * This is the private body of the public function, gl_io_mode().
11401 * It assumes that the caller has checked its arguments and blocked the
11402 * delivery of signals.
11404 static int _gl_io_mode(GetLine *gl, GlIOMode mode)
11407 * Are we already in the specified mode?
11409 if(mode == gl->io_mode)
11410 return 0;
11412 * First revert to normal I/O in the current I/O mode.
11414 _gl_normal_io(gl);
11416 * Record the new mode.
11418 gl->io_mode = mode;
11420 * Perform any actions needed by the new mode.
11422 if(mode==GL_SERVER_MODE) {
11423 if(_gl_raw_io(gl, 1))
11424 return 1;
11426 return 0;
11429 /*.......................................................................
11430 * Return extra information (ie. in addition to that provided by errno)
11431 * about the last error to occur in either gl_get_line() or its
11432 * associated public functions.
11434 * Input:
11435 * gl GetLine * The resource object of gl_get_line().
11436 * Input/Output:
11437 * buff char * An optional output buffer. Note that if the
11438 * calling application calls any gl_*()
11439 * functions from signal handlers, it should
11440 * provide a buffer here, so that a copy of
11441 * the latest error message can safely be made
11442 * while signals are blocked.
11443 * n size_t The allocated size of buff[].
11444 * Output:
11445 * return const char * A pointer to the error message. This will
11446 * be the buff argument, unless buff==NULL, in
11447 * which case it will be a pointer to an
11448 * internal error buffer. In the latter case,
11449 * note that the contents of the returned buffer
11450 * will change on subsequent calls to any gl_*()
11451 * functions.
11453 const char *gl_error_message(GetLine *gl, char *buff, size_t n)
11455 if(!gl) {
11456 static const char *msg = "NULL GetLine argument";
11457 if(buff) {
11458 strncpy(buff, msg, n);
11459 buff[n-1] = '\0';
11460 } else {
11461 return msg;
11463 } else if(buff) {
11464 sigset_t oldset; /* The signals that were blocked on entry to this block */
11466 * Temporarily block all signals.
11468 gl_mask_signals(gl, &oldset);
11470 * Copy the error message into the specified buffer.
11472 if(buff && n > 0) {
11473 strncpy(buff, _err_get_msg(gl->err), n);
11474 buff[n-1] = '\0';
11477 * Restore the process signal mask before returning.
11479 gl_unmask_signals(gl, &oldset);
11480 } else {
11481 return _err_get_msg(gl->err);
11483 return buff;
11486 /*.......................................................................
11487 * Return the signal mask used by gl_get_line(). This is the set of
11488 * signals that gl_get_line() is currently configured to trap.
11490 * Input:
11491 * gl GetLine * The resource object of gl_get_line().
11492 * Input/Output:
11493 * set sigset_t * The set of signals will be returned in *set,
11494 * in the form of a signal process mask, as
11495 * used by sigaction(), sigprocmask(),
11496 * sigpending(), sigsuspend(), sigsetjmp() and
11497 * other standard POSIX signal-aware
11498 * functions.
11499 * Output:
11500 * return int 0 - OK.
11501 * 1 - Error (examine errno for reason).
11503 int gl_list_signals(GetLine *gl, sigset_t *set)
11506 * Check the arguments.
11508 if(!gl || !set) {
11509 if(gl)
11510 _err_record_msg(gl->err, "NULL argument(s)", END_ERR_MSG);
11511 errno = EINVAL;
11512 return 1;
11515 * Copy the signal mask into *set.
11517 memcpy(set, &gl->all_signal_set, sizeof(*set));
11518 return 0;
11521 /*.......................................................................
11522 * By default, gl_get_line() doesn't trap signals that are blocked
11523 * when it is called. This default can be changed either on a
11524 * per-signal basis by calling gl_trap_signal(), or on a global basis
11525 * by calling this function. What this function does is add the
11526 * GLS_UNBLOCK_SIG flag to all signals that are currently configured
11527 * to be trapped by gl_get_line(), such that when subsequent calls to
11528 * gl_get_line() wait for I/O, these signals are temporarily
11529 * unblocked. This behavior is useful in non-blocking server-I/O mode,
11530 * where it is used to avoid race conditions related to handling these
11531 * signals externally to gl_get_line(). See the demonstration code in
11532 * demo3.c, or the gl_handle_signal() man page for further
11533 * information.
11535 * Input:
11536 * gl GetLine * The resource object of gl_get_line().
11538 void gl_catch_blocked(GetLine *gl)
11540 sigset_t oldset; /* The process signal mask to restore */
11541 GlSignalNode *sig; /* A signal node in gl->sigs */
11543 * Check the arguments.
11545 if(!gl) {
11546 errno = EINVAL;
11547 return;
11550 * Temporarily block all signals while we modify the contents of gl.
11552 gl_mask_signals(gl, &oldset);
11554 * Add the GLS_UNBLOCK_SIG flag to all configured signals.
11556 for(sig=gl->sigs; sig; sig=sig->next)
11557 sig->flags |= GLS_UNBLOCK_SIG;
11559 * Restore the process signal mask that was superseded by the call
11560 * to gl_mask_signals().
11562 gl_unmask_signals(gl, &oldset);
11563 return;
11566 /*.......................................................................
11567 * Respond to signals who's default effects have important
11568 * consequences to gl_get_line(). This is intended for use in
11569 * non-blocking server mode, where the external event loop is
11570 * responsible for catching signals. Signals that are handled include
11571 * those that by default terminate or suspend the process, and the
11572 * signal that indicates that the terminal size has changed. Note that
11573 * this function is not signal safe and should thus not be called from
11574 * a signal handler itself. See the gl_io_mode() man page for how it
11575 * should be used.
11577 * In the case of signals that by default terminate or suspend
11578 * processes, command-line editing will be suspended, the terminal
11579 * returned to a usable state, then the default disposition of the
11580 * signal restored and the signal resent, in order to suspend or
11581 * terminate the process. If the process subsequently resumes,
11582 * command-line editing is resumed.
11584 * In the case of signals that indicate that the terminal has been
11585 * resized, the new size will be queried, and any input line that is
11586 * being edited will be redrawn to fit the new dimensions of the
11587 * terminal.
11589 * Input:
11590 * signo int The number of the signal to respond to.
11591 * gl GetLine * The first element of an array of 'ngl' GetLine
11592 * objects.
11593 * ngl int The number of elements in the gl[] array. Normally
11594 * this will be one.
11596 void gl_handle_signal(int signo, GetLine *gl, int ngl)
11598 int attr; /* The attributes of the specified signal */
11599 sigset_t all_signals; /* The set of trappable signals */
11600 sigset_t oldset; /* The process signal mask to restore */
11601 int i;
11603 * NULL operation?
11605 if(ngl < 1 || !gl)
11606 return;
11608 * Look up the default attributes of the specified signal.
11610 attr = gl_classify_signal(signo);
11612 * If the signal isn't known, we are done.
11614 if(!attr)
11615 return;
11617 * Temporarily block all signals while we modify the gl objects.
11619 gl_list_trappable_signals(&all_signals);
11620 sigprocmask(SIG_BLOCK, &all_signals, &oldset);
11622 * Suspend or terminate the process?
11624 if(attr & (GLSA_SUSP | GLSA_TERM)) {
11625 gl_suspend_process(signo, gl, ngl);
11627 * Resize the terminal? Note that ioctl() isn't defined as being
11628 * signal safe, so we can't call gl_update_size() here. However,
11629 * gl_get_line() checks for resizes on each call, so simply arrange
11630 * for the application's event loop to call gl_get_line() as soon as
11631 * it becomes possible to write to the terminal. Note that if the
11632 * caller is calling select() or poll when this happens, these functions
11633 * get interrupted, since a signal has been caught.
11635 } else if(attr & GLSA_SIZE) {
11636 for(i=0; i<ngl; i++)
11637 gl[i].pending_io = GLP_WRITE;
11640 * Restore the process signal mask that was superseded by the call
11641 * to gl_mask_signals().
11643 sigprocmask(SIG_SETMASK, &oldset, NULL);
11644 return;
11647 /*.......................................................................
11648 * Respond to an externally caught process suspension or
11649 * termination signal.
11651 * After restoring the terminal to a usable state, suspend or
11652 * terminate the calling process, using the original signal with its
11653 * default disposition restored to do so. If the process subsequently
11654 * resumes, resume editing any input lines that were being entered.
11656 * Input:
11657 * signo int The signal number to suspend the process with. Note
11658 * that the default disposition of this signal will be
11659 * restored before the signal is sent, so provided
11660 * that the default disposition of this signal is to
11661 * either suspend or terminate the application,
11662 * that is what wil happen, regardless of what signal
11663 * handler is currently assigned to this signal.
11664 * gl GetLine * The first element of an array of 'ngl' GetLine objects
11665 * whose terminals should be restored to a sane state
11666 * while the application is suspended.
11667 * ngl int The number of elements in the gl[] array.
11669 static void gl_suspend_process(int signo, GetLine *gl, int ngl)
11671 sigset_t only_signo; /* A signal set containing just signo */
11672 sigset_t oldset; /* The signal mask on entry to this function */
11673 sigset_t all_signals; /* A signal set containing all signals */
11674 struct sigaction old_action; /* The current signal handler */
11675 struct sigaction def_action; /* The default signal handler */
11676 int i;
11678 * Create a signal mask containing the signal that was trapped.
11680 sigemptyset(&only_signo);
11681 sigaddset(&only_signo, signo);
11683 * Temporarily block all signals.
11685 gl_list_trappable_signals(&all_signals);
11686 sigprocmask(SIG_BLOCK, &all_signals, &oldset);
11688 * Restore the terminal to a usable state.
11690 for(i=0; i<ngl; i++) {
11691 GetLine *obj = gl + i;
11692 if(obj->raw_mode) {
11693 _gl_normal_io(obj);
11694 if(!obj->raw_mode) /* Check that gl_normal_io() succeded */
11695 obj->raw_mode = -1; /* Flag raw mode as needing to be restored */
11699 * Restore the system default disposition of the signal that we
11700 * caught. Note that this signal is currently blocked. Note that we
11701 * don't use memcpy() to copy signal sets here, because the signal safety
11702 * of memcpy() is undefined.
11704 def_action.sa_handler = SIG_DFL;
11706 char *orig = (char *) &all_signals;
11707 char *dest = (char *) &def_action.sa_mask;
11708 for(i=0; i<sizeof(sigset_t); i++)
11709 *dest++ = *orig++;
11711 sigaction(signo, &def_action, &old_action);
11713 * Resend the signal, and unblock it so that it gets delivered to
11714 * the application. This will invoke the default action of this signal.
11716 raise(signo);
11717 sigprocmask(SIG_UNBLOCK, &only_signo, NULL);
11719 * If the process resumes again, it will resume here.
11720 * Block the signal again, then restore our signal handler.
11722 sigprocmask(SIG_BLOCK, &only_signo, NULL);
11723 sigaction(signo, &old_action, NULL);
11725 * Resume command-line editing.
11727 for(i=0; i<ngl; i++) {
11728 GetLine *obj = gl + i;
11729 if(obj->raw_mode == -1) { /* Did we flag the need to restore raw mode? */
11730 obj->raw_mode = 0; /* gl_raw_io() does nothing unless raw_mode==0 */
11731 _gl_raw_io(obj, 1);
11735 * Restore the process signal mask to the way it was when this function
11736 * was called.
11738 sigprocmask(SIG_SETMASK, &oldset, NULL);
11739 return;
11742 /*.......................................................................
11743 * Return the information about the default attributes of a given signal.
11744 * The attributes that are returned are as defined by the standards that
11745 * created them, including POSIX, SVR4 and 4.3+BSD, and are taken from a
11746 * table in Richard Steven's book, "Advanced programming in the UNIX
11747 * environment".
11749 * Input:
11750 * signo int The signal to be characterized.
11751 * Output:
11752 * return int A bitwise union of GlSigAttr enumerators, or 0
11753 * if the signal isn't known.
11755 static int gl_classify_signal(int signo)
11757 int i;
11759 * Search for the specified signal in the gl_signal_list[] table.
11761 for(i=0; i<sizeof(gl_signal_list)/sizeof(gl_signal_list[0]); i++) {
11762 const struct GlDefSignal *sig = gl_signal_list + i;
11763 if(sig->signo == signo)
11764 return sig->attr;
11767 * Signal not known.
11769 return 0;
11772 /*.......................................................................
11773 * When in non-blocking server mode, this function can be used to abandon
11774 * the current incompletely entered input line, and prepare to start
11775 * editing a new line on the next call to gl_get_line().
11777 * Input:
11778 * gl GetLine * The line editor resource object.
11780 void gl_abandon_line(GetLine *gl)
11782 sigset_t oldset; /* The process signal mask to restore */
11784 * Check the arguments.
11786 if(!gl) {
11787 errno = EINVAL;
11788 return;
11791 * Temporarily block all signals while we modify the contents of gl.
11793 gl_mask_signals(gl, &oldset);
11795 * Mark the input line as discarded.
11797 _gl_abandon_line(gl);
11799 * Restore the process signal mask that was superseded by the call
11800 * to gl_mask_signals().
11802 gl_unmask_signals(gl, &oldset);
11803 return;
11806 /*.......................................................................
11807 * This is the private body of the gl_abandon_line() function. It
11808 * assumes that the caller has checked its arguments and blocked the
11809 * delivery of signals.
11811 void _gl_abandon_line(GetLine *gl)
11813 gl->endline = 1;
11814 gl->pending_io = GLP_WRITE;
11817 /*.......................................................................
11818 * How many characters are needed to write a number as an octal string?
11820 * Input:
11821 * num unsigned The to be measured.
11822 * Output:
11823 * return int The number of characters needed.
11825 static int gl_octal_width(unsigned num)
11827 int n; /* The number of characters needed to render the number */
11828 for(n=1; num /= 8; n++)
11830 return n;
11833 /*.......................................................................
11834 * Tell gl_get_line() the current terminal size. Note that this is only
11835 * necessary on systems where changes in terminal size aren't reported
11836 * via SIGWINCH.
11838 * Input:
11839 * gl GetLine * The resource object of gl_get_line().
11840 * ncolumn int The number of columns in the terminal.
11841 * nline int The number of lines in the terminal.
11842 * Output:
11843 * return int 0 - OK.
11844 * 1 - Error.
11846 int gl_set_term_size(GetLine *gl, int ncolumn, int nline)
11848 sigset_t oldset; /* The signals that were blocked on entry */
11849 /* to this function */
11850 int status; /* The return status */
11852 * Block all signals while accessing gl.
11854 gl_mask_signals(gl, &oldset);
11856 * Install the new terminal size.
11858 status = _gl_set_term_size(gl, ncolumn, nline);
11860 * Restore the process signal mask before returning.
11862 gl_unmask_signals(gl, &oldset);
11863 return status;
11866 /*.......................................................................
11867 * This is the private body of the gl_set_term_size() function. It
11868 * assumes that the caller has checked its arguments and blocked the
11869 * delivery of signals.
11871 static int _gl_set_term_size(GetLine *gl, int ncolumn, int nline)
11874 * Check the arguments.
11876 if(!gl) {
11877 errno = EINVAL;
11878 return 1;
11881 * Reject non-sensical dimensions.
11883 if(ncolumn <= 0 || nline <= 0) {
11884 _err_record_msg(gl->err, "Invalid terminal size", END_ERR_MSG);
11885 errno = EINVAL;
11886 return 1;
11889 * Install the new dimensions in the terminal driver if possible, so
11890 * that future calls to gl_query_size() get the new value.
11892 #ifdef TIOCSWINSZ
11893 if(gl->is_term) {
11894 struct winsize size;
11895 size.ws_row = nline;
11896 size.ws_col = ncolumn;
11897 size.ws_xpixel = 0;
11898 size.ws_ypixel = 0;
11899 if(ioctl(gl->output_fd, TIOCSWINSZ, &size) == -1) {
11900 _err_record_msg(gl->err, "Can't change terminal size", END_ERR_MSG);
11901 return 1;
11904 #endif
11906 * If an input line is in the process of being edited, redisplay it to
11907 * accomodate the new dimensions, and record the new dimensions in
11908 * gl->nline and gl->ncolumn.
11910 return gl_handle_tty_resize(gl, ncolumn, nline);
11913 /*.......................................................................
11914 * Record a character in the input line buffer at a given position.
11916 * Input:
11917 * gl GetLine * The resource object of gl_get_line().
11918 * c char The character to be recorded.
11919 * bufpos int The index in the buffer at which to record the
11920 * character.
11921 * Output:
11922 * return int 0 - OK.
11923 * 1 - Insufficient room.
11925 static int gl_buffer_char(GetLine *gl, char c, int bufpos)
11928 * Guard against buffer overruns.
11930 if(bufpos >= gl->linelen)
11931 return 1;
11933 * Record the new character.
11935 gl->line[bufpos] = c;
11937 * If the new character was placed beyond the end of the current input
11938 * line, update gl->ntotal to reflect the increased number of characters
11939 * that are in gl->line, and terminate the string.
11941 if(bufpos >= gl->ntotal) {
11942 gl->ntotal = bufpos+1;
11943 gl->line[gl->ntotal] = '\0';
11945 return 0;
11948 /*.......................................................................
11949 * Copy a given string into the input buffer, overwriting the current
11950 * contents.
11952 * Input:
11953 * gl GetLine * The resource object of gl_get_line().
11954 * s const char * The string to be recorded.
11955 * n int The number of characters to be copied from the
11956 * string.
11957 * bufpos int The index in the buffer at which to place the
11958 * the first character of the string.
11959 * Output:
11960 * return int 0 - OK.
11961 * 1 - String truncated to fit.
11963 static int gl_buffer_string(GetLine *gl, const char *s, int n, int bufpos)
11965 int nnew; /* The number of characters actually recorded */
11966 int i;
11968 * How many of the characters will fit within the buffer?
11970 nnew = bufpos + n <= gl->linelen ? n : (gl->linelen - bufpos);
11972 * Record the first nnew characters of s[] in the buffer.
11974 for(i=0; i<nnew; i++)
11975 gl_buffer_char(gl, s[i], bufpos + i);
11977 * Was the string truncated?
11979 return nnew < n;
11982 /*.......................................................................
11983 * Make room in the input buffer for a string to be inserted. This
11984 * involves moving the characters that follow a specified point, towards
11985 * the end of the buffer.
11987 * Input:
11988 * gl GetLine * The resource object of gl_get_line().
11989 * start int The index of the first character to be moved.
11990 * n int The width of the gap.
11991 * Output:
11992 * return int 0 - OK.
11993 * 1 - Insufficient room.
11995 static int gl_make_gap_in_buffer(GetLine *gl, int start, int n)
11998 * Ensure that the buffer has sufficient space.
12000 if(gl->ntotal + n > gl->linelen)
12001 return 1;
12003 * Move everything including and beyond the character at 'start'
12004 * towards the end of the string.
12006 memmove(gl->line + start + n, gl->line + start, gl->ntotal - start + 1);
12008 * Update the recorded size of the line.
12010 gl->ntotal += n;
12011 return 1;
12014 /*.......................................................................
12015 * Remove a given number of characters from the input buffer. This
12016 * involves moving the characters that follow the removed characters to
12017 * where the removed sub-string started in the input buffer.
12019 * Input:
12020 * gl GetLine * The resource object of gl_get_line().
12021 * start int The first character to be removed.
12022 * n int The number of characters to remove.
12024 static void gl_remove_from_buffer(GetLine *gl, int start, int n)
12026 memmove(gl->line + start, gl->line + start + n, gl->ntotal - start - n + 1);
12028 * Update the recorded size of the line.
12030 gl->ntotal -= n;
12033 /*.......................................................................
12034 * Truncate the string in the input line buffer after a given number of
12035 * characters.
12037 * Input:
12038 * gl GetLine * The resource object of gl_get_line().
12039 * n int The new length of the line.
12040 * Output:
12041 * return int 0 - OK.
12042 * 1 - n > gl->linelen.
12044 static int gl_truncate_buffer(GetLine *gl, int n)
12046 if(n > gl->linelen)
12047 return 1;
12048 gl->line[n] = '\0';
12049 gl->ntotal = n;
12050 return 0;
12053 /*.......................................................................
12054 * When the contents of gl->line[] are changed without calling any of the
12055 * gl_ buffer manipulation functions, this function must be called to
12056 * compute the length of this string, and ancillary information.
12058 * Input:
12059 * gl GetLine * The resource object of gl_get_line().
12061 static void gl_update_buffer(GetLine *gl)
12063 int len; /* The length of the line */
12065 * Measure the length of the input line.
12067 for(len=0; len <= gl->linelen && gl->line[len]; len++)
12070 * Just in case the string wasn't correctly terminated, do so here.
12072 gl->line[len] = '\0';
12074 * Record the number of characters that are now in gl->line[].
12076 gl->ntotal = len;
12078 * Ensure that the cursor stays within the bounds of the modified
12079 * input line.
12081 if(gl->buff_curpos > gl->ntotal)
12082 gl->buff_curpos = gl->ntotal;
12084 * Arrange for the input line to be redrawn.
12086 gl_queue_redisplay(gl);
12087 return;
12090 /*.......................................................................
12091 * Erase the displayed input line, including its prompt, and leave the
12092 * cursor where the erased line started. Note that to allow this
12093 * function to be used when responding to a terminal resize, this
12094 * function is designed to work even if the horizontal cursor position
12095 * doesn't match the internally recorded position.
12097 * Input:
12098 * gl GetLine * The resource object of gl_get_line().
12099 * Output:
12100 * return int 0 - OK.
12101 * 1 - Error.
12103 static int gl_erase_line(GetLine *gl)
12106 * Is a line currently displayed?
12108 if(gl->displayed) {
12110 * Relative the the start of the input line, which terminal line of
12111 * the current input line is the cursor currently on?
12113 int cursor_line = gl->term_curpos / gl->ncolumn;
12115 * Move the cursor to the start of the line.
12117 for( ; cursor_line > 0; cursor_line--) {
12118 if(gl_print_control_sequence(gl, 1, gl->up))
12119 return 1;
12121 if(gl_print_control_sequence(gl, 1, gl->bol))
12122 return 1;
12124 * Clear from the start of the line to the end of the terminal.
12126 if(gl_print_control_sequence(gl, gl->nline, gl->clear_eod))
12127 return 1;
12129 * Mark the line as no longer displayed.
12131 gl_line_erased(gl);
12133 return 0;
12136 /*.......................................................................
12137 * Arrange for the input line to be redisplayed by gl_flush_output(),
12138 * as soon as the output queue becomes empty.
12140 * Input:
12141 * gl GetLine * The resource object of gl_get_line().
12143 static void gl_queue_redisplay(GetLine *gl)
12145 gl->redisplay = 1;
12146 gl->pending_io = GLP_WRITE;
12149 /*.......................................................................
12150 * Truncate the displayed input line starting from the current
12151 * terminal cursor position, and leave the cursor at the end of the
12152 * truncated line. The input-line buffer is not affected.
12154 * Input:
12155 * gl GetLine * The resource object of gl_get_line().
12156 * Output:
12157 * return int 0 - OK.
12158 * 1 - Error.
12160 static int gl_truncate_display(GetLine *gl)
12163 * Keep a record of the current terminal cursor position.
12165 int term_curpos = gl->term_curpos;
12167 * First clear from the cursor to the end of the current input line.
12169 if(gl_print_control_sequence(gl, 1, gl->clear_eol))
12170 return 1;
12172 * If there is more than one line displayed, go to the start of the
12173 * next line and clear from there to the end of the display. Note that
12174 * we can't use clear_eod to do the whole job of clearing from the
12175 * current cursor position to the end of the terminal because
12176 * clear_eod is only defined when used at the start of a terminal line
12177 * (eg. with gnome terminals, clear_eod clears from the start of the
12178 * current terminal line, rather than from the current cursor
12179 * position).
12181 if(gl->term_len / gl->ncolumn > gl->term_curpos / gl->ncolumn) {
12182 if(gl_print_control_sequence(gl, 1, gl->down) ||
12183 gl_print_control_sequence(gl, 1, gl->bol) ||
12184 gl_print_control_sequence(gl, gl->nline, gl->clear_eod))
12185 return 1;
12187 * Where is the cursor now?
12189 gl->term_curpos = gl->ncolumn * (term_curpos / gl->ncolumn + 1);
12191 * Restore the cursor position.
12193 gl_set_term_curpos(gl, term_curpos);
12196 * Update the recorded position of the final character.
12198 gl->term_len = gl->term_curpos;
12199 return 0;
12202 /*.......................................................................
12203 * Return the set of all trappable signals.
12205 * Input:
12206 * signals sigset_t * The set of signals will be recorded in
12207 * *signals.
12209 static void gl_list_trappable_signals(sigset_t *signals)
12212 * Start with the set of all signals.
12214 sigfillset(signals);
12216 * Remove un-trappable signals from this set.
12218 #ifdef SIGKILL
12219 sigdelset(signals, SIGKILL);
12220 #endif
12221 #ifdef SIGSTOP
12222 sigdelset(signals, SIGSTOP);
12223 #endif
12226 /*.......................................................................
12227 * Read an input line from a non-interactive input stream.
12229 * Input:
12230 * gl GetLine * The resource object of gl_get_line().
12231 * Output:
12232 * return int 0 - OK
12233 * 1 - Error.
12235 static int gl_read_stream_line(GetLine *gl)
12237 char c = '\0'; /* The latest character read from fp */
12239 * Record the fact that we are about to read input.
12241 gl->pending_io = GLP_READ;
12243 * If we are starting a new line, reset the line-input parameters.
12245 if(gl->endline)
12246 gl_reset_input_line(gl);
12248 * Read one character at a time.
12250 while(gl->ntotal < gl->linelen && c != '\n') {
12252 * Attempt to read one more character.
12254 switch(gl_read_input(gl, &c)) {
12255 case GL_READ_OK:
12256 break;
12257 case GL_READ_EOF: /* Reached end-of-file? */
12259 * If any characters were read before the end-of-file condition,
12260 * interpolate a newline character, so that the caller sees a
12261 * properly terminated line. Otherwise return an end-of-file
12262 * condition.
12264 if(gl->ntotal > 0) {
12265 c = '\n';
12266 } else {
12267 gl_record_status(gl, GLR_EOF, 0);
12268 return 1;
12270 break;
12271 case GL_READ_BLOCKED: /* Input blocked? */
12272 gl_record_status(gl, GLR_BLOCKED, BLOCKED_ERRNO);
12273 return 1;
12274 break;
12275 case GL_READ_ERROR: /* I/O error? */
12276 return 1;
12277 break;
12280 * Append the character to the line buffer.
12282 if(gl_buffer_char(gl, c, gl->ntotal))
12283 return 1;
12286 * Was the end of the input line reached before running out of buffer space?
12288 gl->endline = (c == '\n');
12289 return 0;
12292 /*.......................................................................
12293 * Read a single character from a non-interactive input stream.
12295 * Input:
12296 * gl GetLine * The resource object of gl_get_line().
12297 * Output:
12298 * return int The character, or EOF on error.
12300 static int gl_read_stream_char(GetLine *gl)
12302 char c = '\0'; /* The latest character read from fp */
12303 int retval = EOF; /* The return value of this function */
12305 * Arrange to discard any incomplete input line.
12307 _gl_abandon_line(gl);
12309 * Record the fact that we are about to read input.
12311 gl->pending_io = GLP_READ;
12313 * Attempt to read one more character.
12315 switch(gl_read_input(gl, &c)) {
12316 case GL_READ_OK: /* Success */
12317 retval = c;
12318 break;
12319 case GL_READ_BLOCKED: /* The read blocked */
12320 gl_record_status(gl, GLR_BLOCKED, BLOCKED_ERRNO);
12321 retval = EOF; /* Failure */
12322 break;
12323 case GL_READ_EOF: /* End of file reached */
12324 gl_record_status(gl, GLR_EOF, 0);
12325 retval = EOF; /* Failure */
12326 break;
12327 case GL_READ_ERROR:
12328 retval = EOF; /* Failure */
12329 break;
12331 return retval;
12334 /*.......................................................................
12335 * Bind a key sequence to a given action.
12337 * Input:
12338 * gl GetLine * The resource object of gl_get_line().
12339 * origin GlKeyOrigin The originator of the key binding.
12340 * key const char * The key-sequence to be bound (or unbound).
12341 * action const char * The name of the action to bind the key to,
12342 * or either NULL or "" to unbind the
12343 * key-sequence.
12344 * Output:
12345 * return int 0 - OK
12346 * 1 - Error.
12348 int gl_bind_keyseq(GetLine *gl, GlKeyOrigin origin, const char *keyseq,
12349 const char *action)
12351 KtBinder binder; /* The private internal equivalent of 'origin' */
12353 * Check the arguments.
12355 if(!gl || !keyseq) {
12356 errno = EINVAL;
12357 if(gl)
12358 _err_record_msg(gl->err, "NULL argument(s)", END_ERR_MSG);
12359 return 1;
12362 * An empty action string requests that the key-sequence be unbound.
12363 * This is indicated to _kt_set_keybinding() by passing a NULL action
12364 * string, so convert an empty string to a NULL action pointer.
12366 if(action && *action=='\0')
12367 action = NULL;
12369 * Translate the public originator enumeration to the private equivalent.
12371 binder = origin==GL_USER_KEY ? KTB_USER : KTB_NORM;
12373 * Bind the action to a given key-sequence?
12375 if(keyseq && _kt_set_keybinding(gl->bindings, binder, keyseq, action)) {
12376 _err_record_msg(gl->err, _kt_last_error(gl->bindings), END_ERR_MSG);
12377 return 1;
12379 return 0;
12382 /*.......................................................................
12383 * This is the public wrapper around the gl_clear_termina() function.
12384 * It clears the terminal and leaves the cursor at the home position.
12385 * In server I/O mode, the next call to gl_get_line() will also
12386 * redisplay the current input line.
12388 * Input:
12389 * gl GetLine * The resource object of gl_get_line().
12390 * Output:
12391 * return int 0 - OK.
12392 * 1 - Error.
12394 int gl_erase_terminal(GetLine *gl)
12396 sigset_t oldset; /* The signals that were blocked on entry */
12397 /* to this function */
12398 int status; /* The return status */
12400 * Block all signals while accessing gl.
12402 gl_mask_signals(gl, &oldset);
12404 * Clear the terminal.
12406 status = gl_clear_screen(gl, 1, NULL);
12408 * Attempt to flush the clear-screen control codes to the terminal.
12409 * If this doesn't complete the job, the next call to gl_get_line()
12410 * will.
12412 (void) gl_flush_output(gl);
12414 * Restore the process signal mask before returning.
12416 gl_unmask_signals(gl, &oldset);
12417 return status;
12420 /*.......................................................................
12421 * This function must be called by any function that erases the input
12422 * line.
12424 * Input:
12425 * gl GetLine * The resource object of gl_get_line().
12427 static void gl_line_erased(GetLine *gl)
12429 gl->displayed = 0;
12430 gl->term_curpos = 0;
12431 gl->term_len = 0;
12434 /*.......................................................................
12435 * Append a specified line to the history list.
12437 * Input:
12438 * gl GetLine * The resource object of gl_get_line().
12439 * line const char * The line to be added.
12440 * Output:
12441 * return int 0 - OK.
12442 * 1 - Error.
12444 int gl_append_history(GetLine *gl, const char *line)
12446 sigset_t oldset; /* The signals that were blocked on entry */
12447 /* to this function */
12448 int status; /* The return status */
12450 * Check the arguments.
12452 if(!gl || !line) {
12453 errno = EINVAL;
12454 return 1;
12457 * Block all signals.
12459 if(gl_mask_signals(gl, &oldset))
12460 return 1;
12462 * Execute the private body of the function while signals are blocked.
12464 status = _gl_append_history(gl, line);
12466 * Restore the process signal mask.
12468 gl_unmask_signals(gl, &oldset);
12469 return status;
12472 /*.......................................................................
12473 * This is the private body of the public function, gl_append_history().
12474 * It assumes that the caller has checked its arguments and blocked the
12475 * delivery of signals.
12477 static int _gl_append_history(GetLine *gl, const char *line)
12479 int status =_glh_add_history(gl->glh, line, 0);
12480 if(status)
12481 _err_record_msg(gl->err, _glh_last_error(gl->glh), END_ERR_MSG);
12482 return status;
12485 /*.......................................................................
12486 * Enable or disable the automatic addition of newly entered lines to the
12487 * history list.
12489 * Input:
12490 * gl GetLine * The resource object of gl_get_line().
12491 * enable int If true, subsequently entered lines will
12492 * automatically be added to the history list
12493 * before they are returned to the caller of
12494 * gl_get_line(). If 0, the choice of how and
12495 * when to archive lines in the history list,
12496 * is left up to the calling application, which
12497 * can do so via calls to gl_append_history().
12498 * Output:
12499 * return int 0 - OK.
12500 * 1 - Error.
12502 int gl_automatic_history(GetLine *gl, int enable)
12504 sigset_t oldset; /* The signals that were blocked on entry */
12505 /* to this function */
12507 * Check the arguments.
12509 if(!gl) {
12510 errno = EINVAL;
12511 return 1;
12514 * Block all signals.
12516 if(gl_mask_signals(gl, &oldset))
12517 return 1;
12519 * Execute the private body of the function while signals are blocked.
12521 gl->automatic_history = enable;
12523 * Restore the process signal mask.
12525 gl_unmask_signals(gl, &oldset);
12526 return 0;
12529 /*.......................................................................
12530 * This is a public function that reads a single uninterpretted
12531 * character from the user, without displaying anything.
12533 * Input:
12534 * gl GetLine * A resource object previously returned by
12535 * new_GetLine().
12536 * Output:
12537 * return int The character that was read, or EOF if the read
12538 * had to be aborted (in which case you can call
12539 * gl_return_status() to find out why).
12541 int gl_read_char(GetLine *gl)
12543 int retval; /* The return value of _gl_read_char() */
12545 * This function can be called from application callback functions,
12546 * so check whether signals have already been masked, so that we don't
12547 * do it again, and overwrite gl->old_signal_set.
12549 int was_masked = gl->signals_masked;
12551 * Check the arguments.
12553 if(!gl) {
12554 errno = EINVAL;
12555 return EOF;
12558 * Temporarily block all of the signals that we have been asked to trap.
12560 if(!was_masked && gl_mask_signals(gl, &gl->old_signal_set))
12561 return EOF;
12563 * Perform the character reading task.
12565 retval = _gl_read_char(gl);
12567 * Restore the process signal mask to how it was when this function was
12568 * first called.
12570 if(!was_masked)
12571 gl_unmask_signals(gl, &gl->old_signal_set);
12572 return retval;
12575 /*.......................................................................
12576 * This is the main body of the public function gl_read_char().
12578 static int _gl_read_char(GetLine *gl)
12580 int retval = EOF; /* The return value */
12581 int waserr = 0; /* True if an error occurs */
12582 char c; /* The character read */
12584 * This function can be called from application callback functions,
12585 * so check whether signals have already been overriden, so that we don't
12586 * overwrite the preserved signal handlers with gl_get_line()s. Also
12587 * record whether we are currently in raw I/O mode or not, so that this
12588 * can be left in the same state on leaving this function.
12590 int was_overriden = gl->signals_overriden;
12591 int was_raw = gl->raw_mode;
12593 * Also keep a record of the direction of any I/O that gl_get_line()
12594 * is awaiting, so that we can restore this status on return.
12596 GlPendingIO old_pending_io = gl->pending_io;
12598 * Assume that this call will successfully complete the input operation
12599 * until proven otherwise.
12601 gl_clear_status(gl);
12603 * If this is the first call to this function or gl_get_line(),
12604 * since new_GetLine(), complete any postponed configuration.
12606 if(!gl->configured) {
12607 (void) _gl_configure_getline(gl, NULL, NULL, TECLA_CONFIG_FILE);
12608 gl->configured = 1;
12611 * Before installing our signal handler functions, record the fact
12612 * that there are no pending signals.
12614 gl_pending_signal = -1;
12616 * Temporarily override the signal handlers of the calling program,
12617 * so that we can intercept signals that would leave the terminal
12618 * in a bad state.
12620 if(!was_overriden)
12621 waserr = gl_override_signal_handlers(gl);
12623 * After recording the current terminal settings, switch the terminal
12624 * into raw input mode, without redisplaying any partially entered input
12625 * line.
12627 if(!was_raw)
12628 waserr = waserr || _gl_raw_io(gl, 0);
12630 * Attempt to read the line. This will require more than one attempt if
12631 * either a current temporary input file is opened by gl_get_input_line()
12632 * or the end of a temporary input file is reached by gl_read_stream_line().
12634 while(!waserr) {
12636 * Read a line from a non-interactive stream?
12638 if(gl->file_fp || !gl->is_term) {
12639 retval = gl_read_stream_char(gl);
12640 if(retval != EOF) { /* Success? */
12641 break;
12642 } else if(gl->file_fp) { /* End of temporary input file? */
12643 gl_revert_input(gl);
12644 gl_record_status(gl, GLR_NEWLINE, 0);
12645 } else { /* An error? */
12646 waserr = 1;
12647 break;
12651 * Read from the terminal? Note that the above if() block may have
12652 * changed gl->file_fp, so it is necessary to retest it here, rather
12653 * than using an else statement.
12655 if(!gl->file_fp && gl->is_term) {
12657 * Flush any pending output to the terminal before waiting
12658 * for the user to type a character.
12660 if(_glq_char_count(gl->cq) > 0 && gl_flush_output(gl)) {
12661 retval = EOF;
12663 * Read one character. Don't append it to the key buffer, since
12664 * this would subseuqnely appear as bogus input to the line editor.
12666 } else if(gl_read_terminal(gl, 0, &c) == 0) {
12668 * Record the character for return.
12670 retval = c;
12672 * In this mode, count each character as being a new key-sequence.
12674 gl->keyseq_count++;
12676 * Delete the character that was read, from the key-press buffer.
12678 gl_discard_chars(gl, 1);
12680 if(retval==EOF)
12681 waserr = 1;
12682 else
12683 break;
12687 * If an error occurred, but gl->rtn_status is still set to
12688 * GLR_NEWLINE, change the status to GLR_ERROR. Otherwise
12689 * leave it at whatever specific value was assigned by the function
12690 * that aborted input. This means that only functions that trap
12691 * non-generic errors have to remember to update gl->rtn_status
12692 * themselves.
12694 if(waserr && gl->rtn_status == GLR_NEWLINE)
12695 gl_record_status(gl, GLR_ERROR, errno);
12697 * Restore terminal settings, if they were changed by this function.
12699 if(!was_raw && gl->io_mode != GL_SERVER_MODE)
12700 _gl_normal_io(gl);
12702 * Restore the signal handlers, if they were overriden by this function.
12704 if(!was_overriden)
12705 gl_restore_signal_handlers(gl);
12707 * If this function gets aborted early, the errno value associated
12708 * with the event that caused this to happen is recorded in
12709 * gl->rtn_errno. Since errno may have been overwritten by cleanup
12710 * functions after this, restore its value to the value that it had
12711 * when the error condition occured, so that the caller can examine it
12712 * to find out what happened.
12714 errno = gl->rtn_errno;
12716 * Error conditions are signalled to the caller, by setting the returned
12717 * character to EOF.
12719 if(gl->rtn_status != GLR_NEWLINE)
12720 retval = EOF;
12722 * Restore the indication of what direction of I/O gl_get_line()
12723 * was awaiting before this call.
12725 gl->pending_io = old_pending_io;
12727 * Return the acquired character.
12729 return retval;
12732 /*.......................................................................
12733 * Reset the GetLine completion status. This function should be called
12734 * at the start of gl_get_line(), gl_read_char() and gl_query_char()
12735 * to discard the completion status and non-zero errno value of any
12736 * preceding calls to these functions.
12738 * Input:
12739 * gl GetLine * The resource object of this module.
12741 static void gl_clear_status(GetLine *gl)
12743 gl_record_status(gl, GLR_NEWLINE, 0);
12746 /*.......................................................................
12747 * When an error or other event causes gl_get_line() to return, this
12748 * function should be called to record information about what
12749 * happened, including the value of errno and the value that
12750 * gl_return_status() should return.
12752 * Input:
12753 * gl GetLine * The resource object of this module.
12754 * rtn_status GlReturnStatus The completion status. To clear a
12755 * previous abnormal completion status,
12756 * specify GLR_NEWLINE (this is what
12757 * gl_clear_status() does).
12758 * rtn_errno int The associated value of errno.
12760 static void gl_record_status(GetLine *gl, GlReturnStatus rtn_status,
12761 int rtn_errno)
12764 * If rtn_status==GLR_NEWLINE, then this resets the completion status, so we
12765 * should always heed this. Otherwise, only record the first abnormal
12766 * condition that occurs after such a reset.
12768 if(rtn_status == GLR_NEWLINE || gl->rtn_status == GLR_NEWLINE) {
12769 gl->rtn_status = rtn_status;
12770 gl->rtn_errno = rtn_errno;