2 * Copyright (c) 2000, 2001, 2002, 2003, 2004 by Martin C. Shepherd.
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.
38 #pragma ident "%Z%%M% %I% %E% SMI"
55 #include <sys/ioctl.h>
57 #ifdef HAVE_SYS_SELECT_H
58 #include <sys/select.h>
61 #include <sys/types.h>
65 * Handle the different sources of terminal control string and size
66 * information. Note that if no terminal information database is available,
67 * ANSI VT100 control sequences are used.
69 #if defined(USE_TERMINFO) || defined(USE_TERMCAP)
71 * Include curses.h or ncurses/curses.h depending on which is available.
75 #elif defined(HAVE_NCURSES_CURSES_H)
76 #include <ncurses/curses.h>
79 * Include term.h where available.
81 #if defined(HAVE_TERM_H)
83 #elif defined(HAVE_NCURSES_TERM_H)
84 #include <ncurses/term.h>
87 * When using termcap, include termcap.h on systems that have it.
88 * Otherwise assume that all prototypes are provided by curses.h.
90 #if defined(USE_TERMCAP) && defined(HAVE_TERMCAP_H)
95 * Under Solaris default Curses the output function that tputs takes is
96 * declared to have a char argument. On all other systems and on Solaris
97 * X/Open Curses (Issue 4, Version 2) it expects an int argument (using
98 * c89 or options -I /usr/xpg4/include -L /usr/xpg4/lib -R /usr/xpg4/lib
99 * selects XPG4v2 Curses on Solaris 2.6 and later).
101 * Similarly, under Mac OS X, the return value of the tputs output
102 * function is declared as void, whereas it is declared as int on
105 #if defined __sun && defined __SVR4 && !defined _XOPEN_CURSES
106 typedef int TputsRetType
;
107 typedef char TputsArgType
; /* int tputs(char c, FILE *fp) */
108 #define TPUTS_RETURNS_VALUE 1
109 #elif defined(__APPLE__) && defined(__MACH__)
110 typedef void TputsRetType
;
111 typedef int TputsArgType
; /* void tputs(int c, FILE *fp) */
112 #define TPUTS_RETURNS_VALUE 0
114 typedef int TputsRetType
;
115 typedef int TputsArgType
; /* int tputs(int c, FILE *fp) */
116 #define TPUTS_RETURNS_VALUE 1
120 * Use the above specifications to prototype our tputs callback function.
122 static TputsRetType
gl_tputs_putchar(TputsArgType c
);
124 #endif /* defined(USE_TERMINFO) || defined(USE_TERMCAP) */
127 * If the library is being compiled without filesystem access facilities,
128 * ensure that none of the action functions that normally do access the
129 * filesystem are bound by default, and that it they do get bound, that
130 * they don't do anything.
132 #if WITHOUT_FILE_SYSTEM
133 #define HIDE_FILE_SYSTEM
144 * Provide typedefs for standard POSIX structures.
146 typedef struct sigaction SigAction
;
147 typedef struct termios Termios
;
150 * Which flag is used to select non-blocking I/O with fcntl()?
152 #undef NON_BLOCKING_FLAG
153 #if defined(O_NONBLOCK)
154 #define NON_BLOCKING_FLAG (O_NONBLOCK)
155 #elif defined(O_NDELAY)
156 #define NON_BLOCKING_FLAG (O_NDELAY)
160 * What value should we give errno if I/O blocks when it shouldn't.
164 #define BLOCKED_ERRNO (EAGAIN)
165 #elif defined(EWOULDBLOCK)
166 #define BLOCKED_ERRNO (EWOULDBLOCK)
168 #define BLOCKED_ERRNO (EIO)
170 #define BLOCKED_ERRNO 0
176 #ifndef WITHOUT_FILE_SYSTEM
177 #include "pathutil.h"
179 #include "libtecla.h"
184 #include "freelist.h"
185 #include "stringrp.h"
186 #include "chrqueue.h"
187 #include "cplmatch.h"
188 #ifndef WITHOUT_FILE_SYSTEM
194 * Enumerate the available editing styles.
197 GL_EMACS_MODE
, /* Emacs style editing */
198 GL_VI_MODE
, /* Vi style editing */
199 GL_NO_EDITOR
/* Fall back to the basic OS-provided editing */
203 * Set the largest key-sequence that can be handled.
205 #define GL_KEY_MAX 64
208 * In vi mode, the following datatype is used to implement the
209 * undo command. It records a copy of the input line from before
210 * the command-mode action which edited the input line.
213 char *line
; /* A historical copy of the input line */
214 int buff_curpos
; /* The historical location of the cursor in */
215 /* line[] when the line was modified. */
216 int ntotal
; /* The number of characters in line[] */
217 int saved
; /* True once a line has been saved after the */
218 /* last call to gl_interpret_char(). */
222 * In vi mode, the following datatype is used to record information
223 * needed by the vi-repeat-change command.
226 KtAction action
; /* The last action function that made a */
227 /* change to the line. */
228 int count
; /* The repeat count that was passed to the */
230 int input_curpos
; /* Whenever vi command mode is entered, the */
231 /* the position at which it was first left */
232 /* is recorded here. */
233 int command_curpos
; /* Whenever vi command mode is entered, the */
234 /* the location of the cursor is recorded */
236 char input_char
; /* Commands that call gl_read_terminal() */
237 /* record the character here, so that it can */
238 /* used on repeating the function. */
239 int saved
; /* True if a function has been saved since the */
240 /* last call to gl_interpret_char(). */
241 int active
; /* True while a function is being repeated. */
245 * The following datatype is used to encapsulate information specific
249 ViUndo undo
; /* Information needed to implement the vi */
251 ViRepeat repeat
; /* Information needed to implement the vi */
252 /* repeat command. */
253 int command
; /* True in vi command-mode */
254 int find_forward
; /* True if the last character search was in the */
255 /* forward direction. */
256 int find_onto
; /* True if the last character search left the */
257 /* on top of the located character, as opposed */
258 /* to just before or after it. */
259 char find_char
; /* The last character sought, or '\0' if no */
260 /* searches have been performed yet. */
265 * Define a type for recording a file-descriptor callback and its associated
269 GlFdEventFn
*fn
; /* The callback function */
270 void *data
; /* Anonymous data to pass to the callback function */
274 * A list of nodes of the following type is used to record file-activity
275 * event handlers, but only on systems that have the select() system call.
277 typedef struct GlFdNode GlFdNode
;
279 GlFdNode
*next
; /* The next in the list of nodes */
280 int fd
; /* The file descriptor being watched */
281 GlFdHandler rd
; /* The callback to call when fd is readable */
282 GlFdHandler wr
; /* The callback to call when fd is writable */
283 GlFdHandler ur
; /* The callback to call when fd has urgent data */
287 * Set the number of the above structures to allocate every time that
288 * the freelist of GlFdNode's becomes exhausted.
290 #define GLFD_FREELIST_BLOCKING 10
293 static int gl_call_fd_handler(GetLine
*gl
, GlFdHandler
*gfh
, int fd
,
296 static int gl_call_timeout_handler(GetLine
*gl
);
301 * Each signal that gl_get_line() traps is described by a list node
302 * of the following type.
304 typedef struct GlSignalNode GlSignalNode
;
305 struct GlSignalNode
{
306 GlSignalNode
*next
; /* The next signal in the list */
307 int signo
; /* The number of the signal */
308 sigset_t proc_mask
; /* A process mask which only includes signo */
309 SigAction original
; /* The signal disposition of the calling program */
310 /* for this signal. */
311 unsigned flags
; /* A bitwise union of GlSignalFlags enumerators */
312 GlAfterSignal after
; /* What to do after the signal has been handled */
313 int errno_value
; /* What to set errno to */
317 * Set the number of the above structures to allocate every time that
318 * the freelist of GlSignalNode's becomes exhausted.
320 #define GLS_FREELIST_BLOCKING 30
323 * Completion handlers and their callback data are recorded in
324 * nodes of the following type.
326 typedef struct GlCplCallback GlCplCallback
;
327 struct GlCplCallback
{
328 CplMatchFn
*fn
; /* The completion callback function */
329 void *data
; /* Arbitrary callback data */
333 * The following function is used as the default completion handler when
334 * the filesystem is to be hidden. It simply reports no completions.
336 #ifdef HIDE_FILE_SYSTEM
337 static CPL_MATCH_FN(gl_no_completions
);
341 * Specify how many GlCplCallback nodes are added to the GlCplCallback freelist
342 * whenever it becomes exhausted.
344 #define GL_CPL_FREELIST_BLOCKING 10
347 * External action functions and their callback data are recorded in
348 * nodes of the following type.
350 typedef struct GlExternalAction GlExternalAction
;
351 struct GlExternalAction
{
352 GlActionFn
*fn
; /* The function which implements the action */
353 void *data
; /* Arbitrary callback data */
357 * Specify how many GlExternalAction nodes are added to the
358 * GlExternalAction freelist whenever it becomes exhausted.
360 #define GL_EXT_ACT_FREELIST_BLOCKING 10
363 * Define the contents of the GetLine object.
364 * Note that the typedef for this object can be found in libtecla.h.
367 ErrMsg
*err
; /* The error-reporting buffer */
368 GlHistory
*glh
; /* The line-history buffer */
369 WordCompletion
*cpl
; /* String completion resource object */
370 GlCplCallback cplfn
; /* The completion callback */
371 #ifndef WITHOUT_FILE_SYSTEM
372 ExpandFile
*ef
; /* ~user/, $envvar and wildcard expansion */
373 /* resource object. */
375 StringGroup
*capmem
; /* Memory for recording terminal capability */
377 GlCharQueue
*cq
; /* The terminal output character queue */
378 int input_fd
; /* The file descriptor to read on */
379 int output_fd
; /* The file descriptor to write to */
380 FILE *input_fp
; /* A stream wrapper around input_fd */
381 FILE *output_fp
; /* A stream wrapper around output_fd */
382 FILE *file_fp
; /* When input is being temporarily taken from */
383 /* a file, this is its file-pointer. Otherwise */
385 char *term
; /* The terminal type specified on the last call */
386 /* to gl_change_terminal(). */
387 int is_term
; /* True if stdin is a terminal */
388 GlWriteFn
*flush_fn
; /* The function to call to write to the terminal */
389 GlIOMode io_mode
; /* The I/O mode established by gl_io_mode() */
390 int raw_mode
; /* True while the terminal is in raw mode */
391 GlPendingIO pending_io
; /* The type of I/O that is currently pending */
392 GlReturnStatus rtn_status
; /* The reason why gl_get_line() returned */
393 int rtn_errno
; /* THe value of errno associated with rtn_status */
394 size_t linelen
; /* The max number of characters per line */
395 char *line
; /* A line-input buffer of allocated size */
396 /* linelen+2. The extra 2 characters are */
397 /* reserved for "\n\0". */
398 char *cutbuf
; /* A cut-buffer of the same size as line[] */
399 char *prompt
; /* The current prompt string */
400 int prompt_len
; /* The length of the prompt string */
401 int prompt_changed
; /* True after a callback changes the prompt */
402 int prompt_style
; /* How the prompt string is displayed */
403 FreeList
*cpl_mem
; /* Memory for GlCplCallback objects */
404 FreeList
*ext_act_mem
; /* Memory for GlExternalAction objects */
405 FreeList
*sig_mem
; /* Memory for nodes of the signal list */
406 GlSignalNode
*sigs
; /* The head of the list of signals */
407 int signals_masked
; /* True between calls to gl_mask_signals() and */
408 /* gl_unmask_signals() */
409 int signals_overriden
; /* True between calls to gl_override_signals() */
410 /* and gl_restore_signals() */
411 sigset_t all_signal_set
; /* The set of all signals that we are trapping */
412 sigset_t old_signal_set
; /* The set of blocked signals on entry to */
414 sigset_t use_signal_set
; /* The subset of all_signal_set to unblock */
415 /* while waiting for key-strokes */
416 Termios oldattr
; /* Saved terminal attributes. */
417 KeyTab
*bindings
; /* A table of key-bindings */
418 int ntotal
; /* The number of characters in gl->line[] */
419 int buff_curpos
; /* The cursor position within gl->line[] */
420 int term_curpos
; /* The cursor position on the terminal */
421 int term_len
; /* The number of terminal characters used to */
422 /* display the current input line. */
423 int buff_mark
; /* A marker location in the buffer */
424 int insert_curpos
; /* The cursor position at start of insert */
425 int insert
; /* True in insert mode */
426 int number
; /* If >= 0, a numeric argument is being read */
427 int endline
; /* True to tell gl_get_input_line() to return */
428 /* the current contents of gl->line[] */
429 int displayed
; /* True if an input line is currently displayed */
430 int redisplay
; /* If true, the input line will be redrawn */
431 /* either after the current action function */
432 /* returns, or when gl_get_input_line() */
433 /* is next called. */
434 int postpone
; /* _gl_normal_io() sets this flag, to */
435 /* postpone any redisplays until */
436 /* is next called, to resume line editing. */
437 char keybuf
[GL_KEY_MAX
+1]; /* A buffer of currently unprocessed key presses */
438 int nbuf
; /* The number of characters in keybuf[] */
439 int nread
; /* The number of characters read from keybuf[] */
440 KtAction current_action
; /* The action function that is being invoked */
441 int current_count
; /* The repeat count passed to */
442 /* current_acction.fn() */
443 GlhLineID preload_id
; /* When not zero, this should be the ID of a */
444 /* line in the history buffer for potential */
446 int preload_history
; /* If true, preload the above history line when */
447 /* gl_get_input_line() is next called. */
448 long keyseq_count
; /* The number of key sequences entered by the */
449 /* the user since new_GetLine() was called. */
450 long last_search
; /* The value of keyseq_count during the last */
451 /* history search operation. */
452 GlEditor editor
; /* The style of editing, (eg. vi or emacs) */
453 int silence_bell
; /* True if gl_ring_bell() should do nothing. */
454 int automatic_history
; /* True to automatically archive entered lines */
455 /* in the history list. */
456 ViMode vi
; /* Parameters used when editing in vi mode */
457 const char *left
; /* The string that moves the cursor 1 character */
459 const char *right
; /* The string that moves the cursor 1 character */
461 const char *up
; /* The string that moves the cursor 1 character */
463 const char *down
; /* The string that moves the cursor 1 character */
465 const char *home
; /* The string that moves the cursor home */
466 const char *bol
; /* Move cursor to beginning of line */
467 const char *clear_eol
; /* The string that clears from the cursor to */
468 /* the end of the line. */
469 const char *clear_eod
; /* The string that clears from the cursor to */
470 /* the end of the display. */
471 const char *u_arrow
; /* The string returned by the up-arrow key */
472 const char *d_arrow
; /* The string returned by the down-arrow key */
473 const char *l_arrow
; /* The string returned by the left-arrow key */
474 const char *r_arrow
; /* The string returned by the right-arrow key */
475 const char *sound_bell
; /* The string needed to ring the terminal bell */
476 const char *bold
; /* Switch to the bold font */
477 const char *underline
; /* Underline subsequent characters */
478 const char *standout
; /* Turn on standout mode */
479 const char *dim
; /* Switch to a dim font */
480 const char *reverse
; /* Turn on reverse video */
481 const char *blink
; /* Switch to a blinking font */
482 const char *text_attr_off
; /* Turn off all text attributes */
483 int nline
; /* The height of the terminal in lines */
484 int ncolumn
; /* The width of the terminal in columns */
486 char *tgetent_buf
; /* The buffer that is used by tgetent() to */
487 /* store a terminal description. */
488 char *tgetstr_buf
; /* The buffer that is used by tgetstr() to */
489 /* store terminal capabilities. */
492 const char *left_n
; /* The parameter string that moves the cursor */
493 /* n characters left. */
494 const char *right_n
; /* The parameter string that moves the cursor */
495 /* n characters right. */
497 char *app_file
; /* The pathname of the application-specific */
498 /* .teclarc configuration file, or NULL. */
499 char *user_file
; /* The pathname of the user-specific */
500 /* .teclarc configuration file, or NULL. */
501 int configured
; /* True as soon as any teclarc configuration */
502 /* file has been read. */
503 int echo
; /* True to display the line as it is being */
504 /* entered. If 0, only the prompt will be */
505 /* displayed, and the line will not be */
506 /* archived in the history list. */
507 int last_signal
; /* The last signal that was caught by */
508 /* the last call to gl_get_line(), or -1 */
509 /* if no signal has been caught yet. */
511 FreeList
*fd_node_mem
; /* A freelist of GlFdNode structures */
512 GlFdNode
*fd_nodes
; /* The list of fd event descriptions */
513 fd_set rfds
; /* The set of fds to watch for readability */
514 fd_set wfds
; /* The set of fds to watch for writability */
515 fd_set ufds
; /* The set of fds to watch for urgent data */
516 int max_fd
; /* The maximum file-descriptor being watched */
517 struct { /* Inactivity timeout related data */
518 struct timeval dt
; /* The inactivity timeout when timer.fn() */
520 GlTimeoutFn
*fn
; /* The application callback to call when */
521 /* the inactivity timer expires, or 0 if */
522 /* timeouts are not required. */
523 void *data
; /* Application provided data to be passed to */
530 * Define the max amount of space needed to store a termcap terminal
531 * description. Unfortunately this has to be done by guesswork, so
532 * there is the potential for buffer overflows if we guess too small.
533 * Fortunately termcap has been replaced by terminfo on most
534 * platforms, and with terminfo this isn't an issue. The value that I
535 * am using here is the conventional value, as recommended by certain
539 #define TERMCAP_BUF_SIZE 2048
543 * Set the size of the string segments used to store terminal capability
546 #define CAPMEM_SEGMENT_SIZE 512
549 * If no terminal size information is available, substitute the
550 * following vt100 default sizes.
552 #define GL_DEF_NLINE 24
553 #define GL_DEF_NCOLUMN 80
556 * Enumerate the attributes needed to classify different types of
557 * signals. These attributes reflect the standard default
558 * characteristics of these signals (according to Richard Steven's
559 * Advanced Programming in the UNIX Environment). Note that these values
560 * are all powers of 2, so that they can be combined in a bitwise union.
563 GLSA_TERM
=1, /* A signal that terminates processes */
564 GLSA_SUSP
=2, /* A signal that suspends processes */
565 GLSA_CONT
=4, /* A signal that is sent when suspended processes resume */
566 GLSA_IGN
=8, /* A signal that is ignored */
567 GLSA_CORE
=16, /* A signal that generates a core dump */
568 GLSA_HARD
=32, /* A signal generated by a hardware exception */
569 GLSA_SIZE
=64 /* A signal indicating terminal size changes */
573 * List the signals that we need to catch. In general these are
574 * those that by default terminate or suspend the process, since
575 * in such cases we need to restore terminal settings.
577 static const struct GlDefSignal
{
578 int signo
; /* The number of the signal */
579 unsigned flags
; /* A bitwise union of GlSignalFlags enumerators */
580 GlAfterSignal after
; /* What to do after the signal has been delivered */
581 int attr
; /* The default attributes of this signal, expressed */
582 /* as a bitwise union of GlSigAttr enumerators */
583 int errno_value
; /* What to set errno to */
584 } gl_signal_list
[] = {
585 {SIGABRT
, GLS_SUSPEND_INPUT
, GLS_ABORT
, GLSA_TERM
|GLSA_CORE
, EINTR
},
586 {SIGALRM
, GLS_RESTORE_ENV
, GLS_CONTINUE
, GLSA_TERM
, 0},
587 {SIGCONT
, GLS_RESTORE_ENV
, GLS_CONTINUE
, GLSA_CONT
|GLSA_IGN
, 0},
590 {SIGHUP
, GLS_SUSPEND_INPUT
, GLS_ABORT
, GLSA_TERM
, ENOTTY
},
592 {SIGHUP
, GLS_SUSPEND_INPUT
, GLS_ABORT
, GLSA_TERM
, EINTR
},
595 {SIGINT
, GLS_SUSPEND_INPUT
, GLS_ABORT
, GLSA_TERM
, EINTR
},
598 {SIGPIPE
, GLS_SUSPEND_INPUT
, GLS_ABORT
, GLSA_TERM
, EPIPE
},
600 {SIGPIPE
, GLS_SUSPEND_INPUT
, GLS_ABORT
, GLSA_TERM
, EINTR
},
604 {SIGPOLL
, GLS_SUSPEND_INPUT
, GLS_ABORT
, GLSA_TERM
, EINTR
},
607 {SIGPWR
, GLS_RESTORE_ENV
, GLS_CONTINUE
, GLSA_IGN
, 0},
610 {SIGQUIT
, GLS_SUSPEND_INPUT
, GLS_ABORT
, GLSA_TERM
|GLSA_CORE
, EINTR
},
612 {SIGTERM
, GLS_SUSPEND_INPUT
, GLS_ABORT
, GLSA_TERM
, EINTR
},
614 {SIGTSTP
, GLS_SUSPEND_INPUT
, GLS_CONTINUE
, GLSA_SUSP
, 0},
617 {SIGTTIN
, GLS_SUSPEND_INPUT
, GLS_CONTINUE
, GLSA_SUSP
, 0},
620 {SIGTTOU
, GLS_SUSPEND_INPUT
, GLS_CONTINUE
, GLSA_SUSP
, 0},
623 {SIGUSR1
, GLS_RESTORE_ENV
, GLS_CONTINUE
, GLSA_TERM
, 0},
626 {SIGUSR2
, GLS_RESTORE_ENV
, GLS_CONTINUE
, GLSA_TERM
, 0},
629 {SIGVTALRM
, GLS_RESTORE_ENV
, GLS_CONTINUE
, GLSA_TERM
, 0},
632 {SIGWINCH
, GLS_RESTORE_ENV
, GLS_CONTINUE
, GLSA_SIZE
|GLSA_IGN
, 0},
635 {SIGXCPU
, GLS_RESTORE_ENV
, GLS_CONTINUE
, GLSA_TERM
|GLSA_CORE
, 0},
638 {SIGXFSZ
, GLS_RESTORE_ENV
, GLS_CONTINUE
, GLSA_TERM
|GLSA_CORE
, 0},
643 * Define file-scope variables for use in signal handlers.
645 static volatile sig_atomic_t gl_pending_signal
= -1;
646 static sigjmp_buf gl_setjmp_buffer
;
648 static void gl_signal_handler(int signo
);
650 static int gl_check_caught_signal(GetLine
*gl
);
653 * Respond to an externally caught process suspension or
654 * termination signal.
656 static void gl_suspend_process(int signo
, GetLine
*gl
, int ngl
);
658 /* Return the default attributes of a given signal */
660 static int gl_classify_signal(int signo
);
663 * Unfortunately both terminfo and termcap require one to use the tputs()
664 * function to output terminal control characters, and this function
665 * doesn't allow one to specify a file stream. As a result, the following
666 * file-scope variable is used to pass the current output file stream.
667 * This is bad, but there doesn't seem to be any alternative.
669 static GetLine
*tputs_gl
= NULL
;
672 * Define a tab to be a string of 8 spaces.
677 * Lookup the current size of the terminal.
679 static void gl_query_size(GetLine
*gl
, int *ncolumn
, int *nline
);
682 * Getline calls this to temporarily override certain signal handlers
683 * of the calling program.
685 static int gl_override_signal_handlers(GetLine
*gl
);
688 * Getline calls this to restore the signal handlers of the calling
691 static int gl_restore_signal_handlers(GetLine
*gl
);
694 * Temporarily block the delivery of all signals that gl_get_line()
695 * is currently configured to trap.
697 static int gl_mask_signals(GetLine
*gl
, sigset_t
*oldset
);
700 * Restore the process signal mask that was overriden by a previous
701 * call to gl_mask_signals().
703 static int gl_unmask_signals(GetLine
*gl
, sigset_t
*oldset
);
706 * Unblock the signals that gl_get_line() has been configured to catch.
708 static int gl_catch_signals(GetLine
*gl
);
711 * Return the set of all trappable signals.
713 static void gl_list_trappable_signals(sigset_t
*signals
);
716 * Put the terminal into raw input mode, after saving the original
717 * terminal attributes in gl->oldattr.
719 static int gl_raw_terminal_mode(GetLine
*gl
);
722 * Restore the terminal attributes from gl->oldattr.
724 static int gl_restore_terminal_attributes(GetLine
*gl
);
727 * Switch to non-blocking I/O if possible.
729 static int gl_nonblocking_io(GetLine
*gl
, int fd
);
732 * Switch to blocking I/O if possible.
734 static int gl_blocking_io(GetLine
*gl
, int fd
);
737 * Read a line from the user in raw mode.
739 static int gl_get_input_line(GetLine
*gl
, const char *prompt
,
740 const char *start_line
, int start_pos
);
743 * Query the user for a single character.
745 static int gl_get_query_char(GetLine
*gl
, const char *prompt
, int defchar
);
748 * Read input from a non-interactive input stream.
750 static int gl_read_stream_line(GetLine
*gl
);
753 * Read a single character from a non-interactive input stream.
755 static int gl_read_stream_char(GetLine
*gl
);
758 * Prepare to edit a new line.
760 static int gl_present_line(GetLine
*gl
, const char *prompt
,
761 const char *start_line
, int start_pos
);
764 * Reset all line input parameters for a new input line.
766 static void gl_reset_input_line(GetLine
*gl
);
769 * Handle the receipt of the potential start of a new key-sequence from
772 static int gl_interpret_char(GetLine
*gl
, char c
);
775 * Bind a single control or meta character to an action.
777 static int gl_bind_control_char(GetLine
*gl
, KtBinder binder
,
778 char c
, const char *action
);
781 * Set up terminal-specific key bindings.
783 static int gl_bind_terminal_keys(GetLine
*gl
);
786 * Lookup terminal control string and size information.
788 static int gl_control_strings(GetLine
*gl
, const char *term
);
791 * Wrappers around the terminfo and termcap functions that lookup
792 * strings in the terminal information databases.
795 static const char *gl_tigetstr(GetLine
*gl
, const char *name
);
796 #elif defined(USE_TERMCAP)
797 static const char *gl_tgetstr(GetLine
*gl
, const char *name
, char **bufptr
);
801 * Output a binary string directly to the terminal.
803 static int gl_print_raw_string(GetLine
*gl
, int buffered
,
804 const char *string
, int n
);
807 * Print an informational message, starting and finishing on new lines.
808 * After the list of strings to be printed, the last argument MUST be
811 static int gl_print_info(GetLine
*gl
, ...);
812 #define GL_END_INFO ((const char *)0)
815 * Start a newline and place the cursor at its start.
817 static int gl_start_newline(GetLine
*gl
, int buffered
);
820 * Output a terminal control sequence.
822 static int gl_print_control_sequence(GetLine
*gl
, int nline
,
826 * Output a character or string to the terminal after converting tabs
827 * to spaces and control characters to a caret followed by the modified
830 static int gl_print_char(GetLine
*gl
, char c
, char pad
);
831 static int gl_print_string(GetLine
*gl
, const char *string
, char pad
);
834 * Delete nc characters starting from the one under the cursor.
835 * Optionally copy the deleted characters to the cut buffer.
837 static int gl_delete_chars(GetLine
*gl
, int nc
, int cut
);
840 * Add a character to the line buffer at the current cursor position,
841 * inserting or overwriting according the current mode.
843 static int gl_add_char_to_line(GetLine
*gl
, char c
);
846 * Insert/append a string to the line buffer and terminal at the current
849 static int gl_add_string_to_line(GetLine
*gl
, const char *s
);
852 * Record a new character in the input-line buffer.
854 static int gl_buffer_char(GetLine
*gl
, char c
, int bufpos
);
857 * Record a string in the input-line buffer.
859 static int gl_buffer_string(GetLine
*gl
, const char *s
, int n
, int bufpos
);
862 * Make way to insert a string in the input-line buffer.
864 static int gl_make_gap_in_buffer(GetLine
*gl
, int start
, int n
);
867 * Remove characters from the input-line buffer, and move any characters
868 * that followed them to the start of the vacated space.
870 static void gl_remove_from_buffer(GetLine
*gl
, int start
, int n
);
873 * Terminate the input-line buffer after a specified number of characters.
875 static int gl_truncate_buffer(GetLine
*gl
, int n
);
878 * Delete the displayed part of the input line that follows the current
879 * terminal cursor position.
881 static int gl_truncate_display(GetLine
*gl
);
884 * Accomodate changes to the contents of the input line buffer
885 * that weren't made by the above gl_*buffer functions.
887 static void gl_update_buffer(GetLine
*gl
);
890 * Read a single character from the terminal.
892 static int gl_read_terminal(GetLine
*gl
, int keep
, char *c
);
895 * Discard processed characters from the key-press lookahead buffer.
897 static void gl_discard_chars(GetLine
*gl
, int nused
);
900 * Move the terminal cursor n positions to the left or right.
902 static int gl_terminal_move_cursor(GetLine
*gl
, int n
);
905 * Move the terminal cursor to a given position.
907 static int gl_set_term_curpos(GetLine
*gl
, int term_curpos
);
910 * Set the position of the cursor both in the line input buffer and on the
913 static int gl_place_cursor(GetLine
*gl
, int buff_curpos
);
916 * How many characters are needed to write a number as an octal string?
918 static int gl_octal_width(unsigned num
);
921 * Return the number of spaces needed to display a tab character at
922 * a given location of the terminal.
924 static int gl_displayed_tab_width(GetLine
*gl
, int term_curpos
);
927 * Return the number of terminal characters needed to display a
928 * given raw character.
930 static int gl_displayed_char_width(GetLine
*gl
, char c
, int term_curpos
);
933 * Return the number of terminal characters needed to display a
936 static int gl_displayed_string_width(GetLine
*gl
, const char *string
, int nc
,
940 * Return non-zero if 'c' is to be considered part of a word.
942 static int gl_is_word_char(int c
);
945 * Read a tecla configuration file.
947 static int _gl_read_config_file(GetLine
*gl
, const char *filename
, KtBinder who
);
950 * Read a tecla configuration string.
952 static int _gl_read_config_string(GetLine
*gl
, const char *buffer
, KtBinder who
);
955 * Define the callback function used by _gl_parse_config_line() to
956 * read the next character of a configuration stream.
958 #define GLC_GETC_FN(fn) int (fn)(void *stream)
959 typedef GLC_GETC_FN(GlcGetcFn
);
961 static GLC_GETC_FN(glc_file_getc
); /* Read from a file */
962 static GLC_GETC_FN(glc_buff_getc
); /* Read from a string */
965 * Parse a single configuration command line.
967 static int _gl_parse_config_line(GetLine
*gl
, void *stream
, GlcGetcFn
*getc_fn
,
968 const char *origin
, KtBinder who
, int *lineno
);
969 static int gl_report_config_error(GetLine
*gl
, const char *origin
, int lineno
,
973 * Bind the actual arrow key bindings to match those of the symbolic
974 * arrow-key bindings.
976 static int _gl_bind_arrow_keys(GetLine
*gl
);
979 * Copy the binding of the specified symbolic arrow-key binding to
980 * the terminal specific, and default arrow-key key-sequences.
982 static int _gl_rebind_arrow_key(GetLine
*gl
, const char *name
,
983 const char *term_seq
,
984 const char *def_seq1
,
985 const char *def_seq2
);
988 * After the gl_read_from_file() action has been used to tell gl_get_line()
989 * to temporarily read input from a file, gl_revert_input() arranges
990 * for input to be reverted to the input stream last registered with
991 * gl_change_terminal().
993 static void gl_revert_input(GetLine
*gl
);
996 * Flush unwritten characters to the terminal.
998 static int gl_flush_output(GetLine
*gl
);
1001 * The callback through which all terminal output is routed.
1002 * This simply appends characters to a queue buffer, which is
1003 * subsequently flushed to the output channel by gl_flush_output().
1005 static GL_WRITE_FN(gl_write_fn
);
1008 * The callback function which the output character queue object
1009 * calls to transfer characters to the output channel.
1011 static GL_WRITE_FN(gl_flush_terminal
);
1014 * Enumerate the possible return statuses of gl_read_input().
1017 GL_READ_OK
, /* A character was read successfully */
1018 GL_READ_ERROR
, /* A read-error occurred */
1019 GL_READ_BLOCKED
, /* The read would have blocked the caller */
1020 GL_READ_EOF
/* The end of the current input file was reached */
1023 static GlReadStatus
gl_read_input(GetLine
*gl
, char *c
);
1025 * Private functions of gl_read_input().
1027 static int gl_event_handler(GetLine
*gl
, int fd
);
1028 static int gl_read_unmasked(GetLine
*gl
, int fd
, char *c
);
1032 * A private function of gl_tty_signals().
1034 static int gl_set_tty_signal(int signo
, void (*handler
)(int));
1037 * Change the editor style being emulated.
1039 static int gl_change_editor(GetLine
*gl
, GlEditor editor
);
1042 * Searching in a given direction, return the index of a given (or
1043 * read) character in the input line, or the character that precedes
1044 * it in the specified search direction. Return -1 if not found.
1046 static int gl_find_char(GetLine
*gl
, int count
, int forward
, int onto
, char c
);
1049 * Return the buffer index of the nth word ending after the cursor.
1051 static int gl_nth_word_end_forward(GetLine
*gl
, int n
);
1054 * Return the buffer index of the nth word start after the cursor.
1056 static int gl_nth_word_start_forward(GetLine
*gl
, int n
);
1059 * Return the buffer index of the nth word start before the cursor.
1061 static int gl_nth_word_start_backward(GetLine
*gl
, int n
);
1064 * When called when vi command mode is enabled, this function saves the
1065 * current line and cursor position for potential restoration later
1066 * by the vi undo command.
1068 static void gl_save_for_undo(GetLine
*gl
);
1071 * If in vi mode, switch to vi command mode.
1073 static void gl_vi_command_mode(GetLine
*gl
);
1076 * In vi mode this is used to delete up to or onto a given or read
1077 * character in the input line. Also switch to insert mode if requested
1078 * after the deletion.
1080 static int gl_delete_find(GetLine
*gl
, int count
, char c
, int forward
,
1081 int onto
, int change
);
1084 * Copy the characters between the cursor and the count'th instance of
1085 * a specified (or read) character in the input line, into the cut buffer.
1087 static int gl_copy_find(GetLine
*gl
, int count
, char c
, int forward
, int onto
);
1090 * Return the line index of the parenthesis that either matches the one under
1091 * the cursor, or not over a parenthesis character, the index of the next
1092 * close parenthesis. Return -1 if not found.
1094 static int gl_index_of_matching_paren(GetLine
*gl
);
1097 * Replace a malloc'd string (or NULL), with another malloc'd copy of
1098 * a string (or NULL).
1100 static int gl_record_string(char **sptr
, const char *string
);
1103 * Enumerate text display attributes as powers of two, suitable for
1104 * use in a bit-mask.
1107 GL_TXT_STANDOUT
=1, /* Display text highlighted */
1108 GL_TXT_UNDERLINE
=2, /* Display text underlined */
1109 GL_TXT_REVERSE
=4, /* Display text with reverse video */
1110 GL_TXT_BLINK
=8, /* Display blinking text */
1111 GL_TXT_DIM
=16, /* Display text in a dim font */
1112 GL_TXT_BOLD
=32 /* Display text using a bold font */
1116 * Display the prompt regardless of the current visibility mode.
1118 static int gl_display_prompt(GetLine
*gl
);
1121 * Return the number of characters used by the prompt on the terminal.
1123 static int gl_displayed_prompt_width(GetLine
*gl
);
1126 * Prepare to return the current input line to the caller of gl_get_line().
1128 static int gl_line_ended(GetLine
*gl
, int newline_char
);
1131 * Arrange for the input line to be redisplayed when the current contents
1132 * of the output queue have been flushed.
1134 static void gl_queue_redisplay(GetLine
*gl
);
1137 * Erase the displayed representation of the input line, without
1138 * touching the buffered copy.
1140 static int gl_erase_line(GetLine
*gl
);
1143 * This function is called whenever the input line has been erased.
1145 static void gl_line_erased(GetLine
*gl
);
1148 * Arrange for the current input line to be discarded.
1150 void _gl_abandon_line(GetLine
*gl
);
1153 * The following are private internally callable versions of pertinent
1154 * public functions. Unlike their public wrapper functions, they don't
1155 * block signals while running, and assume that their arguments are valid.
1156 * They are designed to be called from places where signals are already
1157 * blocked, and where simple sanity checks have already been applied to
1160 static char *_gl_get_line(GetLine
*gl
, const char *prompt
,
1161 const char *start_line
, int start_pos
);
1162 static int _gl_query_char(GetLine
*gl
, const char *prompt
, char defchar
);
1163 static int _gl_read_char(GetLine
*gl
);
1164 static int _gl_update_size(GetLine
*gl
);
1166 * Redraw the current input line to account for a change in the terminal
1167 * size. Also install the new size in gl.
1169 static int gl_handle_tty_resize(GetLine
*gl
, int ncolumn
, int nline
);
1171 static int _gl_change_terminal(GetLine
*gl
, FILE *input_fp
, FILE *output_fp
,
1173 static int _gl_configure_getline(GetLine
*gl
, const char *app_string
,
1174 const char *app_file
, const char *user_file
);
1175 static int _gl_save_history(GetLine
*gl
, const char *filename
,
1176 const char *comment
, int max_lines
);
1177 static int _gl_load_history(GetLine
*gl
, const char *filename
,
1178 const char *comment
);
1179 static int _gl_watch_fd(GetLine
*gl
, int fd
, GlFdEvent event
,
1180 GlFdEventFn
*callback
, void *data
);
1181 static void _gl_terminal_size(GetLine
*gl
, int def_ncolumn
, int def_nline
,
1182 GlTerminalSize
*size
);
1183 static void _gl_replace_prompt(GetLine
*gl
, const char *prompt
);
1184 static int _gl_trap_signal(GetLine
*gl
, int signo
, unsigned flags
,
1185 GlAfterSignal after
, int errno_value
);
1186 static int _gl_raw_io(GetLine
*gl
, int redisplay
);
1187 static int _gl_normal_io(GetLine
*gl
);
1188 static int _gl_completion_action(GetLine
*gl
, void *data
, CplMatchFn
*match_fn
,
1189 int list_only
, const char *name
,
1190 const char *keyseq
);
1191 static int _gl_register_action(GetLine
*gl
, void *data
, GlActionFn
*fn
,
1192 const char *name
, const char *keyseq
);
1193 static int _gl_io_mode(GetLine
*gl
, GlIOMode mode
);
1194 static int _gl_set_term_size(GetLine
*gl
, int ncolumn
, int nline
);
1195 static int _gl_append_history(GetLine
*gl
, const char *line
);
1198 * Reset the completion status and associated errno value in
1199 * gl->rtn_status and gl->rtn_errno.
1201 static void gl_clear_status(GetLine
*gl
);
1204 * Record a completion status, unless a previous abnormal completion
1205 * status has already been recorded for the current call.
1207 static void gl_record_status(GetLine
*gl
, GlReturnStatus rtn_status
,
1211 * Set the maximum length of a line in a user's tecla configuration
1212 * file (not counting comments).
1214 #define GL_CONF_BUFLEN 100
1217 * Set the maximum number of arguments supported by individual commands
1218 * in tecla configuration files.
1220 #define GL_CONF_MAXARG 10
1223 * Prototype the available action functions.
1225 static KT_KEY_FN(gl_user_interrupt
);
1226 static KT_KEY_FN(gl_abort
);
1227 static KT_KEY_FN(gl_suspend
);
1228 static KT_KEY_FN(gl_stop_output
);
1229 static KT_KEY_FN(gl_start_output
);
1230 static KT_KEY_FN(gl_literal_next
);
1231 static KT_KEY_FN(gl_cursor_left
);
1232 static KT_KEY_FN(gl_cursor_right
);
1233 static KT_KEY_FN(gl_insert_mode
);
1234 static KT_KEY_FN(gl_beginning_of_line
);
1235 static KT_KEY_FN(gl_end_of_line
);
1236 static KT_KEY_FN(gl_delete_line
);
1237 static KT_KEY_FN(gl_kill_line
);
1238 static KT_KEY_FN(gl_forward_word
);
1239 static KT_KEY_FN(gl_backward_word
);
1240 static KT_KEY_FN(gl_forward_delete_char
);
1241 static KT_KEY_FN(gl_backward_delete_char
);
1242 static KT_KEY_FN(gl_forward_delete_word
);
1243 static KT_KEY_FN(gl_backward_delete_word
);
1244 static KT_KEY_FN(gl_delete_refind
);
1245 static KT_KEY_FN(gl_delete_invert_refind
);
1246 static KT_KEY_FN(gl_delete_to_column
);
1247 static KT_KEY_FN(gl_delete_to_parenthesis
);
1248 static KT_KEY_FN(gl_forward_delete_find
);
1249 static KT_KEY_FN(gl_backward_delete_find
);
1250 static KT_KEY_FN(gl_forward_delete_to
);
1251 static KT_KEY_FN(gl_backward_delete_to
);
1252 static KT_KEY_FN(gl_upcase_word
);
1253 static KT_KEY_FN(gl_downcase_word
);
1254 static KT_KEY_FN(gl_capitalize_word
);
1255 static KT_KEY_FN(gl_redisplay
);
1256 static KT_KEY_FN(gl_clear_screen
);
1257 static KT_KEY_FN(gl_transpose_chars
);
1258 static KT_KEY_FN(gl_set_mark
);
1259 static KT_KEY_FN(gl_exchange_point_and_mark
);
1260 static KT_KEY_FN(gl_kill_region
);
1261 static KT_KEY_FN(gl_copy_region_as_kill
);
1262 static KT_KEY_FN(gl_yank
);
1263 static KT_KEY_FN(gl_up_history
);
1264 static KT_KEY_FN(gl_down_history
);
1265 static KT_KEY_FN(gl_history_search_backward
);
1266 static KT_KEY_FN(gl_history_re_search_backward
);
1267 static KT_KEY_FN(gl_history_search_forward
);
1268 static KT_KEY_FN(gl_history_re_search_forward
);
1269 static KT_KEY_FN(gl_complete_word
);
1270 #ifndef HIDE_FILE_SYSTEM
1271 static KT_KEY_FN(gl_expand_filename
);
1272 static KT_KEY_FN(gl_read_from_file
);
1273 static KT_KEY_FN(gl_read_init_files
);
1274 static KT_KEY_FN(gl_list_glob
);
1276 static KT_KEY_FN(gl_del_char_or_list_or_eof
);
1277 static KT_KEY_FN(gl_list_or_eof
);
1278 static KT_KEY_FN(gl_beginning_of_history
);
1279 static KT_KEY_FN(gl_end_of_history
);
1280 static KT_KEY_FN(gl_digit_argument
);
1281 static KT_KEY_FN(gl_newline
);
1282 static KT_KEY_FN(gl_repeat_history
);
1283 static KT_KEY_FN(gl_vi_insert
);
1284 static KT_KEY_FN(gl_vi_overwrite
);
1285 static KT_KEY_FN(gl_change_case
);
1286 static KT_KEY_FN(gl_vi_insert_at_bol
);
1287 static KT_KEY_FN(gl_vi_append_at_eol
);
1288 static KT_KEY_FN(gl_vi_append
);
1289 static KT_KEY_FN(gl_backward_kill_line
);
1290 static KT_KEY_FN(gl_goto_column
);
1291 static KT_KEY_FN(gl_forward_to_word
);
1292 static KT_KEY_FN(gl_vi_replace_char
);
1293 static KT_KEY_FN(gl_vi_change_rest_of_line
);
1294 static KT_KEY_FN(gl_vi_change_line
);
1295 static KT_KEY_FN(gl_vi_change_to_bol
);
1296 static KT_KEY_FN(gl_vi_change_refind
);
1297 static KT_KEY_FN(gl_vi_change_invert_refind
);
1298 static KT_KEY_FN(gl_vi_change_to_column
);
1299 static KT_KEY_FN(gl_vi_change_to_parenthesis
);
1300 static KT_KEY_FN(gl_vi_forward_change_word
);
1301 static KT_KEY_FN(gl_vi_backward_change_word
);
1302 static KT_KEY_FN(gl_vi_forward_change_find
);
1303 static KT_KEY_FN(gl_vi_backward_change_find
);
1304 static KT_KEY_FN(gl_vi_forward_change_to
);
1305 static KT_KEY_FN(gl_vi_backward_change_to
);
1306 static KT_KEY_FN(gl_vi_forward_change_char
);
1307 static KT_KEY_FN(gl_vi_backward_change_char
);
1308 static KT_KEY_FN(gl_forward_copy_char
);
1309 static KT_KEY_FN(gl_backward_copy_char
);
1310 static KT_KEY_FN(gl_forward_find_char
);
1311 static KT_KEY_FN(gl_backward_find_char
);
1312 static KT_KEY_FN(gl_forward_to_char
);
1313 static KT_KEY_FN(gl_backward_to_char
);
1314 static KT_KEY_FN(gl_repeat_find_char
);
1315 static KT_KEY_FN(gl_invert_refind_char
);
1316 static KT_KEY_FN(gl_append_yank
);
1317 static KT_KEY_FN(gl_backward_copy_word
);
1318 static KT_KEY_FN(gl_forward_copy_word
);
1319 static KT_KEY_FN(gl_copy_to_bol
);
1320 static KT_KEY_FN(gl_copy_refind
);
1321 static KT_KEY_FN(gl_copy_invert_refind
);
1322 static KT_KEY_FN(gl_copy_to_column
);
1323 static KT_KEY_FN(gl_copy_to_parenthesis
);
1324 static KT_KEY_FN(gl_copy_rest_of_line
);
1325 static KT_KEY_FN(gl_copy_line
);
1326 static KT_KEY_FN(gl_backward_copy_find
);
1327 static KT_KEY_FN(gl_forward_copy_find
);
1328 static KT_KEY_FN(gl_backward_copy_to
);
1329 static KT_KEY_FN(gl_forward_copy_to
);
1330 static KT_KEY_FN(gl_vi_undo
);
1331 static KT_KEY_FN(gl_emacs_editing_mode
);
1332 static KT_KEY_FN(gl_vi_editing_mode
);
1333 static KT_KEY_FN(gl_ring_bell
);
1334 static KT_KEY_FN(gl_vi_repeat_change
);
1335 static KT_KEY_FN(gl_find_parenthesis
);
1336 static KT_KEY_FN(gl_list_history
);
1337 static KT_KEY_FN(gl_list_completions
);
1338 static KT_KEY_FN(gl_run_external_action
);
1341 * Name the available action functions.
1343 static const struct {const char *name
; KT_KEY_FN(*fn
);} gl_actions
[] = {
1344 {"user-interrupt", gl_user_interrupt
},
1345 {"abort", gl_abort
},
1346 {"suspend", gl_suspend
},
1347 {"stop-output", gl_stop_output
},
1348 {"start-output", gl_start_output
},
1349 {"literal-next", gl_literal_next
},
1350 {"cursor-right", gl_cursor_right
},
1351 {"cursor-left", gl_cursor_left
},
1352 {"insert-mode", gl_insert_mode
},
1353 {"beginning-of-line", gl_beginning_of_line
},
1354 {"end-of-line", gl_end_of_line
},
1355 {"delete-line", gl_delete_line
},
1356 {"kill-line", gl_kill_line
},
1357 {"forward-word", gl_forward_word
},
1358 {"backward-word", gl_backward_word
},
1359 {"forward-delete-char", gl_forward_delete_char
},
1360 {"backward-delete-char", gl_backward_delete_char
},
1361 {"forward-delete-word", gl_forward_delete_word
},
1362 {"backward-delete-word", gl_backward_delete_word
},
1363 {"delete-refind", gl_delete_refind
},
1364 {"delete-invert-refind", gl_delete_invert_refind
},
1365 {"delete-to-column", gl_delete_to_column
},
1366 {"delete-to-parenthesis", gl_delete_to_parenthesis
},
1367 {"forward-delete-find", gl_forward_delete_find
},
1368 {"backward-delete-find", gl_backward_delete_find
},
1369 {"forward-delete-to", gl_forward_delete_to
},
1370 {"backward-delete-to", gl_backward_delete_to
},
1371 {"upcase-word", gl_upcase_word
},
1372 {"downcase-word", gl_downcase_word
},
1373 {"capitalize-word", gl_capitalize_word
},
1374 {"redisplay", gl_redisplay
},
1375 {"clear-screen", gl_clear_screen
},
1376 {"transpose-chars", gl_transpose_chars
},
1377 {"set-mark", gl_set_mark
},
1378 {"exchange-point-and-mark", gl_exchange_point_and_mark
},
1379 {"kill-region", gl_kill_region
},
1380 {"copy-region-as-kill", gl_copy_region_as_kill
},
1382 {"up-history", gl_up_history
},
1383 {"down-history", gl_down_history
},
1384 {"history-search-backward", gl_history_search_backward
},
1385 {"history-re-search-backward", gl_history_re_search_backward
},
1386 {"history-search-forward", gl_history_search_forward
},
1387 {"history-re-search-forward", gl_history_re_search_forward
},
1388 {"complete-word", gl_complete_word
},
1389 #ifndef HIDE_FILE_SYSTEM
1390 {"expand-filename", gl_expand_filename
},
1391 {"read-from-file", gl_read_from_file
},
1392 {"read-init-files", gl_read_init_files
},
1393 {"list-glob", gl_list_glob
},
1395 {"del-char-or-list-or-eof", gl_del_char_or_list_or_eof
},
1396 {"beginning-of-history", gl_beginning_of_history
},
1397 {"end-of-history", gl_end_of_history
},
1398 {"digit-argument", gl_digit_argument
},
1399 {"newline", gl_newline
},
1400 {"repeat-history", gl_repeat_history
},
1401 {"vi-insert", gl_vi_insert
},
1402 {"vi-overwrite", gl_vi_overwrite
},
1403 {"vi-insert-at-bol", gl_vi_insert_at_bol
},
1404 {"vi-append-at-eol", gl_vi_append_at_eol
},
1405 {"vi-append", gl_vi_append
},
1406 {"change-case", gl_change_case
},
1407 {"backward-kill-line", gl_backward_kill_line
},
1408 {"goto-column", gl_goto_column
},
1409 {"forward-to-word", gl_forward_to_word
},
1410 {"vi-replace-char", gl_vi_replace_char
},
1411 {"vi-change-rest-of-line", gl_vi_change_rest_of_line
},
1412 {"vi-change-line", gl_vi_change_line
},
1413 {"vi-change-to-bol", gl_vi_change_to_bol
},
1414 {"vi-change-refind", gl_vi_change_refind
},
1415 {"vi-change-invert-refind", gl_vi_change_invert_refind
},
1416 {"vi-change-to-column", gl_vi_change_to_column
},
1417 {"vi-change-to-parenthesis", gl_vi_change_to_parenthesis
},
1418 {"forward-copy-char", gl_forward_copy_char
},
1419 {"backward-copy-char", gl_backward_copy_char
},
1420 {"forward-find-char", gl_forward_find_char
},
1421 {"backward-find-char", gl_backward_find_char
},
1422 {"forward-to-char", gl_forward_to_char
},
1423 {"backward-to-char", gl_backward_to_char
},
1424 {"repeat-find-char", gl_repeat_find_char
},
1425 {"invert-refind-char", gl_invert_refind_char
},
1426 {"append-yank", gl_append_yank
},
1427 {"backward-copy-word", gl_backward_copy_word
},
1428 {"forward-copy-word", gl_forward_copy_word
},
1429 {"copy-to-bol", gl_copy_to_bol
},
1430 {"copy-refind", gl_copy_refind
},
1431 {"copy-invert-refind", gl_copy_invert_refind
},
1432 {"copy-to-column", gl_copy_to_column
},
1433 {"copy-to-parenthesis", gl_copy_to_parenthesis
},
1434 {"copy-rest-of-line", gl_copy_rest_of_line
},
1435 {"copy-line", gl_copy_line
},
1436 {"backward-copy-find", gl_backward_copy_find
},
1437 {"forward-copy-find", gl_forward_copy_find
},
1438 {"backward-copy-to", gl_backward_copy_to
},
1439 {"forward-copy-to", gl_forward_copy_to
},
1440 {"list-or-eof", gl_list_or_eof
},
1441 {"vi-undo", gl_vi_undo
},
1442 {"vi-backward-change-word", gl_vi_backward_change_word
},
1443 {"vi-forward-change-word", gl_vi_forward_change_word
},
1444 {"vi-backward-change-find", gl_vi_backward_change_find
},
1445 {"vi-forward-change-find", gl_vi_forward_change_find
},
1446 {"vi-backward-change-to", gl_vi_backward_change_to
},
1447 {"vi-forward-change-to", gl_vi_forward_change_to
},
1448 {"vi-backward-change-char", gl_vi_backward_change_char
},
1449 {"vi-forward-change-char", gl_vi_forward_change_char
},
1450 {"emacs-mode", gl_emacs_editing_mode
},
1451 {"vi-mode", gl_vi_editing_mode
},
1452 {"ring-bell", gl_ring_bell
},
1453 {"vi-repeat-change", gl_vi_repeat_change
},
1454 {"find-parenthesis", gl_find_parenthesis
},
1455 {"list-history", gl_list_history
},
1459 * Define the default key-bindings in emacs mode.
1461 static const KtKeyBinding gl_emacs_bindings
[] = {
1462 {"right", "cursor-right"},
1463 {"^F", "cursor-right"},
1464 {"left", "cursor-left"},
1465 {"^B", "cursor-left"},
1466 {"M-i", "insert-mode"},
1467 {"M-I", "insert-mode"},
1468 {"^A", "beginning-of-line"},
1469 {"^E", "end-of-line"},
1470 {"^U", "delete-line"},
1471 {"^K", "kill-line"},
1472 {"M-f", "forward-word"},
1473 {"M-F", "forward-word"},
1474 {"M-b", "backward-word"},
1475 {"M-B", "backward-word"},
1476 {"^D", "del-char-or-list-or-eof"},
1477 {"^H", "backward-delete-char"},
1478 {"^?", "backward-delete-char"},
1479 {"M-d", "forward-delete-word"},
1480 {"M-D", "forward-delete-word"},
1481 {"M-^H", "backward-delete-word"},
1482 {"M-^?", "backward-delete-word"},
1483 {"M-u", "upcase-word"},
1484 {"M-U", "upcase-word"},
1485 {"M-l", "downcase-word"},
1486 {"M-L", "downcase-word"},
1487 {"M-c", "capitalize-word"},
1488 {"M-C", "capitalize-word"},
1489 {"^R", "redisplay"},
1490 {"^L", "clear-screen"},
1491 {"^T", "transpose-chars"},
1493 {"^X^X", "exchange-point-and-mark"},
1494 {"^W", "kill-region"},
1495 {"M-w", "copy-region-as-kill"},
1496 {"M-W", "copy-region-as-kill"},
1498 {"^P", "up-history"},
1499 {"up", "up-history"},
1500 {"^N", "down-history"},
1501 {"down", "down-history"},
1502 {"M-p", "history-search-backward"},
1503 {"M-P", "history-search-backward"},
1504 {"M-n", "history-search-forward"},
1505 {"M-N", "history-search-forward"},
1506 {"\t", "complete-word"},
1507 #ifndef HIDE_FILE_SYSTEM
1508 {"^X*", "expand-filename"},
1509 {"^X^F", "read-from-file"},
1510 {"^X^R", "read-init-files"},
1511 {"^Xg", "list-glob"},
1512 {"^XG", "list-glob"},
1514 {"^Xh", "list-history"},
1515 {"^XH", "list-history"},
1516 {"M-<", "beginning-of-history"},
1517 {"M->", "end-of-history"},
1518 {"M-0", "digit-argument"},
1519 {"M-1", "digit-argument"},
1520 {"M-2", "digit-argument"},
1521 {"M-3", "digit-argument"},
1522 {"M-4", "digit-argument"},
1523 {"M-5", "digit-argument"},
1524 {"M-6", "digit-argument"},
1525 {"M-7", "digit-argument"},
1526 {"M-8", "digit-argument"},
1527 {"M-9", "digit-argument"},
1530 {"M-o", "repeat-history"},
1531 {"M-C-v", "vi-mode"},
1535 * Define the default key-bindings in vi mode. Note that in vi-mode
1536 * meta-key bindings are command-mode bindings. For example M-i first
1537 * switches to command mode if not already in that mode, then moves
1538 * the cursor one position right, as in vi.
1540 static const KtKeyBinding gl_vi_bindings
[] = {
1541 {"^D", "list-or-eof"},
1542 #ifndef HIDE_FILE_SYSTEM
1543 {"^G", "list-glob"},
1545 {"^H", "backward-delete-char"},
1546 {"\t", "complete-word"},
1549 {"^L", "clear-screen"},
1550 {"^N", "down-history"},
1551 {"^P", "up-history"},
1552 {"^R", "redisplay"},
1553 {"^U", "backward-kill-line"},
1554 {"^W", "backward-delete-word"},
1555 #ifndef HIDE_FILE_SYSTEM
1556 {"^X^F", "read-from-file"},
1557 {"^X^R", "read-init-files"},
1558 {"^X*", "expand-filename"},
1560 {"^?", "backward-delete-char"},
1561 {"M- ", "cursor-right"},
1562 {"M-$", "end-of-line"},
1563 #ifndef HIDE_FILE_SYSTEM
1564 {"M-*", "expand-filename"},
1566 {"M-+", "down-history"},
1567 {"M--", "up-history"},
1568 {"M-<", "beginning-of-history"},
1569 {"M->", "end-of-history"},
1570 {"M-^", "beginning-of-line"},
1571 {"M-;", "repeat-find-char"},
1572 {"M-,", "invert-refind-char"},
1573 {"M-|", "goto-column"},
1574 {"M-~", "change-case"},
1575 {"M-.", "vi-repeat-change"},
1576 {"M-%", "find-parenthesis"},
1577 {"M-0", "digit-argument"},
1578 {"M-1", "digit-argument"},
1579 {"M-2", "digit-argument"},
1580 {"M-3", "digit-argument"},
1581 {"M-4", "digit-argument"},
1582 {"M-5", "digit-argument"},
1583 {"M-6", "digit-argument"},
1584 {"M-7", "digit-argument"},
1585 {"M-8", "digit-argument"},
1586 {"M-9", "digit-argument"},
1587 {"M-a", "vi-append"},
1588 {"M-A", "vi-append-at-eol"},
1589 {"M-b", "backward-word"},
1590 {"M-B", "backward-word"},
1591 {"M-C", "vi-change-rest-of-line"},
1592 {"M-cb", "vi-backward-change-word"},
1593 {"M-cB", "vi-backward-change-word"},
1594 {"M-cc", "vi-change-line"},
1595 {"M-ce", "vi-forward-change-word"},
1596 {"M-cE", "vi-forward-change-word"},
1597 {"M-cw", "vi-forward-change-word"},
1598 {"M-cW", "vi-forward-change-word"},
1599 {"M-cF", "vi-backward-change-find"},
1600 {"M-cf", "vi-forward-change-find"},
1601 {"M-cT", "vi-backward-change-to"},
1602 {"M-ct", "vi-forward-change-to"},
1603 {"M-c;", "vi-change-refind"},
1604 {"M-c,", "vi-change-invert-refind"},
1605 {"M-ch", "vi-backward-change-char"},
1606 {"M-c^H", "vi-backward-change-char"},
1607 {"M-c^?", "vi-backward-change-char"},
1608 {"M-cl", "vi-forward-change-char"},
1609 {"M-c ", "vi-forward-change-char"},
1610 {"M-c^", "vi-change-to-bol"},
1611 {"M-c0", "vi-change-to-bol"},
1612 {"M-c$", "vi-change-rest-of-line"},
1613 {"M-c|", "vi-change-to-column"},
1614 {"M-c%", "vi-change-to-parenthesis"},
1615 {"M-dh", "backward-delete-char"},
1616 {"M-d^H", "backward-delete-char"},
1617 {"M-d^?", "backward-delete-char"},
1618 {"M-dl", "forward-delete-char"},
1619 {"M-d ", "forward-delete-char"},
1620 {"M-dd", "delete-line"},
1621 {"M-db", "backward-delete-word"},
1622 {"M-dB", "backward-delete-word"},
1623 {"M-de", "forward-delete-word"},
1624 {"M-dE", "forward-delete-word"},
1625 {"M-dw", "forward-delete-word"},
1626 {"M-dW", "forward-delete-word"},
1627 {"M-dF", "backward-delete-find"},
1628 {"M-df", "forward-delete-find"},
1629 {"M-dT", "backward-delete-to"},
1630 {"M-dt", "forward-delete-to"},
1631 {"M-d;", "delete-refind"},
1632 {"M-d,", "delete-invert-refind"},
1633 {"M-d^", "backward-kill-line"},
1634 {"M-d0", "backward-kill-line"},
1635 {"M-d$", "kill-line"},
1636 {"M-D", "kill-line"},
1637 {"M-d|", "delete-to-column"},
1638 {"M-d%", "delete-to-parenthesis"},
1639 {"M-e", "forward-word"},
1640 {"M-E", "forward-word"},
1641 {"M-f", "forward-find-char"},
1642 {"M-F", "backward-find-char"},
1643 {"M--", "up-history"},
1644 {"M-h", "cursor-left"},
1645 {"M-H", "beginning-of-history"},
1646 {"M-i", "vi-insert"},
1647 {"M-I", "vi-insert-at-bol"},
1648 {"M-j", "down-history"},
1649 {"M-J", "history-search-forward"},
1650 {"M-k", "up-history"},
1651 {"M-K", "history-search-backward"},
1652 {"M-l", "cursor-right"},
1653 {"M-L", "end-of-history"},
1654 {"M-n", "history-re-search-forward"},
1655 {"M-N", "history-re-search-backward"},
1656 {"M-p", "append-yank"},
1658 {"M-r", "vi-replace-char"},
1659 {"M-R", "vi-overwrite"},
1660 {"M-s", "vi-forward-change-char"},
1661 {"M-S", "vi-change-line"},
1662 {"M-t", "forward-to-char"},
1663 {"M-T", "backward-to-char"},
1665 {"M-w", "forward-to-word"},
1666 {"M-W", "forward-to-word"},
1667 {"M-x", "forward-delete-char"},
1668 {"M-X", "backward-delete-char"},
1669 {"M-yh", "backward-copy-char"},
1670 {"M-y^H", "backward-copy-char"},
1671 {"M-y^?", "backward-copy-char"},
1672 {"M-yl", "forward-copy-char"},
1673 {"M-y ", "forward-copy-char"},
1674 {"M-ye", "forward-copy-word"},
1675 {"M-yE", "forward-copy-word"},
1676 {"M-yw", "forward-copy-word"},
1677 {"M-yW", "forward-copy-word"},
1678 {"M-yb", "backward-copy-word"},
1679 {"M-yB", "backward-copy-word"},
1680 {"M-yf", "forward-copy-find"},
1681 {"M-yF", "backward-copy-find"},
1682 {"M-yt", "forward-copy-to"},
1683 {"M-yT", "backward-copy-to"},
1684 {"M-y;", "copy-refind"},
1685 {"M-y,", "copy-invert-refind"},
1686 {"M-y^", "copy-to-bol"},
1687 {"M-y0", "copy-to-bol"},
1688 {"M-y$", "copy-rest-of-line"},
1689 {"M-yy", "copy-line"},
1690 {"M-Y", "copy-line"},
1691 {"M-y|", "copy-to-column"},
1692 {"M-y%", "copy-to-parenthesis"},
1693 {"M-^E", "emacs-mode"},
1694 {"M-^H", "cursor-left"},
1695 {"M-^?", "cursor-left"},
1696 {"M-^L", "clear-screen"},
1697 {"M-^N", "down-history"},
1698 {"M-^P", "up-history"},
1699 {"M-^R", "redisplay"},
1700 {"M-^D", "list-or-eof"},
1701 {"M-\r", "newline"},
1702 {"M-\t", "complete-word"},
1703 {"M-\n", "newline"},
1704 #ifndef HIDE_FILE_SYSTEM
1705 {"M-^X^R", "read-init-files"},
1707 {"M-^Xh", "list-history"},
1708 {"M-^XH", "list-history"},
1709 {"down", "down-history"},
1710 {"up", "up-history"},
1711 {"left", "cursor-left"},
1712 {"right", "cursor-right"},
1715 /*.......................................................................
1716 * Create a new GetLine object.
1719 * linelen size_t The maximum line length to allow for.
1720 * histlen size_t The number of bytes to allocate for recording
1721 * a circular buffer of history lines.
1723 * return GetLine * The new object, or NULL on error.
1725 GetLine
*new_GetLine(size_t linelen
, size_t histlen
)
1727 GetLine
*gl
; /* The object to be returned */
1730 * Check the arguments.
1737 * Allocate the container.
1739 gl
= (GetLine
*) malloc(sizeof(GetLine
));
1745 * Before attempting any operation that might fail, initialize the
1746 * container at least up to the point at which it can safely be passed
1752 #ifndef HIDE_FILE_SYSTEM
1753 gl
->cplfn
.fn
= cpl_file_completions
;
1755 gl
->cplfn
.fn
= gl_no_completions
;
1757 gl
->cplfn
.data
= NULL
;
1758 #ifndef WITHOUT_FILE_SYSTEM
1765 gl
->input_fp
= NULL
;
1766 gl
->output_fp
= NULL
;
1770 gl
->flush_fn
= gl_flush_terminal
;
1771 gl
->io_mode
= GL_NORMAL_MODE
;
1773 gl
->pending_io
= GLP_WRITE
; /* We will start by writing the prompt */
1774 gl_clear_status(gl
);
1775 gl
->linelen
= linelen
;
1780 gl
->prompt_changed
= 0;
1781 gl
->prompt_style
= GL_LITERAL_PROMPT
;
1783 gl
->ext_act_mem
= NULL
;
1786 gl
->signals_masked
= 0;
1787 gl
->signals_overriden
= 0;
1788 sigemptyset(&gl
->all_signal_set
);
1789 sigemptyset(&gl
->old_signal_set
);
1790 sigemptyset(&gl
->use_signal_set
);
1791 gl
->bindings
= NULL
;
1793 gl
->buff_curpos
= 0;
1794 gl
->term_curpos
= 0;
1797 gl
->insert_curpos
= 0;
1807 gl
->current_action
.fn
= 0;
1808 gl
->current_action
.data
= NULL
;
1809 gl
->current_count
= 0;
1811 gl
->preload_history
= 0;
1812 gl
->keyseq_count
= 0;
1813 gl
->last_search
= -1;
1814 gl
->editor
= GL_EMACS_MODE
;
1815 gl
->silence_bell
= 0;
1816 gl
->automatic_history
= 1;
1817 gl
->vi
.undo
.line
= NULL
;
1818 gl
->vi
.undo
.buff_curpos
= 0;
1819 gl
->vi
.undo
.ntotal
= 0;
1820 gl
->vi
.undo
.saved
= 0;
1821 gl
->vi
.repeat
.action
.fn
= 0;
1822 gl
->vi
.repeat
.action
.data
= 0;
1823 gl
->vi
.repeat
.count
= 0;
1824 gl
->vi
.repeat
.input_curpos
= 0;
1825 gl
->vi
.repeat
.command_curpos
= 0;
1826 gl
->vi
.repeat
.input_char
= '\0';
1827 gl
->vi
.repeat
.saved
= 0;
1828 gl
->vi
.repeat
.active
= 0;
1830 gl
->vi
.find_forward
= 0;
1831 gl
->vi
.find_onto
= 0;
1832 gl
->vi
.find_char
= '\0';
1839 gl
->clear_eol
= NULL
;
1840 gl
->clear_eod
= NULL
;
1845 gl
->sound_bell
= NULL
;
1847 gl
->underline
= NULL
;
1848 gl
->standout
= NULL
;
1852 gl
->text_attr_off
= NULL
;
1858 #elif defined(USE_TERMCAP)
1859 gl
->tgetent_buf
= NULL
;
1860 gl
->tgetstr_buf
= NULL
;
1862 gl
->app_file
= NULL
;
1863 gl
->user_file
= NULL
;
1866 gl
->last_signal
= -1;
1868 gl
->fd_node_mem
= NULL
;
1869 gl
->fd_nodes
= NULL
;
1874 gl
->timer
.dt
.tv_sec
= 0;
1875 gl
->timer
.dt
.tv_usec
= 0;
1877 gl
->timer
.data
= NULL
;
1880 * Allocate an error reporting buffer.
1882 gl
->err
= _new_ErrMsg();
1884 return del_GetLine(gl
);
1886 * Allocate the history buffer.
1888 gl
->glh
= _new_GlHistory(histlen
);
1890 return del_GetLine(gl
);
1892 * Allocate the resource object for file-completion.
1894 gl
->cpl
= new_WordCompletion();
1896 return del_GetLine(gl
);
1898 * Allocate the resource object for file-completion.
1900 #ifndef WITHOUT_FILE_SYSTEM
1901 gl
->ef
= new_ExpandFile();
1903 return del_GetLine(gl
);
1906 * Allocate a string-segment memory allocator for use in storing terminal
1907 * capablity strings.
1909 gl
->capmem
= _new_StringGroup(CAPMEM_SEGMENT_SIZE
);
1911 return del_GetLine(gl
);
1913 * Allocate the character queue that is used to buffer terminal output.
1915 gl
->cq
= _new_GlCharQueue();
1917 return del_GetLine(gl
);
1919 * Allocate a line buffer, leaving 2 extra characters for the terminating
1920 * '\n' and '\0' characters
1922 gl
->line
= (char *) malloc(linelen
+ 2);
1925 return del_GetLine(gl
);
1928 * Start with an empty input line.
1930 gl_truncate_buffer(gl
, 0);
1932 * Allocate a cut buffer.
1934 gl
->cutbuf
= (char *) malloc(linelen
+ 2);
1937 return del_GetLine(gl
);
1939 gl
->cutbuf
[0] = '\0';
1941 * Allocate an initial empty prompt.
1943 _gl_replace_prompt(gl
, NULL
);
1946 return del_GetLine(gl
);
1949 * Allocate a vi undo buffer.
1951 gl
->vi
.undo
.line
= (char *) malloc(linelen
+ 2);
1952 if(!gl
->vi
.undo
.line
) {
1954 return del_GetLine(gl
);
1956 gl
->vi
.undo
.line
[0] = '\0';
1958 * Allocate a freelist from which to allocate nodes for the list
1959 * of completion functions.
1961 gl
->cpl_mem
= _new_FreeList(sizeof(GlCplCallback
), GL_CPL_FREELIST_BLOCKING
);
1963 return del_GetLine(gl
);
1965 * Allocate a freelist from which to allocate nodes for the list
1966 * of external action functions.
1968 gl
->ext_act_mem
= _new_FreeList(sizeof(GlExternalAction
),
1969 GL_EXT_ACT_FREELIST_BLOCKING
);
1970 if(!gl
->ext_act_mem
)
1971 return del_GetLine(gl
);
1973 * Allocate a freelist from which to allocate nodes for the list
1976 gl
->sig_mem
= _new_FreeList(sizeof(GlSignalNode
), GLS_FREELIST_BLOCKING
);
1978 return del_GetLine(gl
);
1980 * Install initial dispositions for the default list of signals that
1981 * gl_get_line() traps.
1983 for(i
=0; i
<sizeof(gl_signal_list
)/sizeof(gl_signal_list
[0]); i
++) {
1984 const struct GlDefSignal
*sig
= gl_signal_list
+ i
;
1985 if(_gl_trap_signal(gl
, sig
->signo
, sig
->flags
, sig
->after
,
1987 return del_GetLine(gl
);
1990 * Allocate an empty table of key bindings.
1992 gl
->bindings
= _new_KeyTab();
1994 return del_GetLine(gl
);
1996 * Define the available actions that can be bound to key sequences.
1998 for(i
=0; i
<sizeof(gl_actions
)/sizeof(gl_actions
[0]); i
++) {
1999 if(_kt_set_action(gl
->bindings
, gl_actions
[i
].name
, gl_actions
[i
].fn
, NULL
))
2000 return del_GetLine(gl
);
2003 * Set up the default bindings.
2005 if(gl_change_editor(gl
, gl
->editor
))
2006 return del_GetLine(gl
);
2008 * Allocate termcap buffers.
2011 gl
->tgetent_buf
= (char *) malloc(TERMCAP_BUF_SIZE
);
2012 gl
->tgetstr_buf
= (char *) malloc(TERMCAP_BUF_SIZE
);
2013 if(!gl
->tgetent_buf
|| !gl
->tgetstr_buf
) {
2015 return del_GetLine(gl
);
2019 * Set up for I/O assuming stdin and stdout.
2021 if(_gl_change_terminal(gl
, stdin
, stdout
, getenv("TERM")))
2022 return del_GetLine(gl
);
2024 * Create a freelist for use in allocating GlFdNode list nodes.
2027 gl
->fd_node_mem
= _new_FreeList(sizeof(GlFdNode
), GLFD_FREELIST_BLOCKING
);
2028 if(!gl
->fd_node_mem
)
2029 return del_GetLine(gl
);
2032 * We are done for now.
2037 /*.......................................................................
2038 * Delete a GetLine object.
2041 * gl GetLine * The object to be deleted.
2043 * return GetLine * The deleted object (always NULL).
2045 GetLine
*del_GetLine(GetLine
*gl
)
2049 * If the terminal is in raw server mode, reset it.
2053 * Deallocate all objects contained by gl.
2055 gl
->err
= _del_ErrMsg(gl
->err
);
2056 gl
->glh
= _del_GlHistory(gl
->glh
);
2057 gl
->cpl
= del_WordCompletion(gl
->cpl
);
2058 #ifndef WITHOUT_FILE_SYSTEM
2059 gl
->ef
= del_ExpandFile(gl
->ef
);
2061 gl
->capmem
= _del_StringGroup(gl
->capmem
);
2062 gl
->cq
= _del_GlCharQueue(gl
->cq
);
2064 fclose(gl
->file_fp
);
2073 gl
->cpl_mem
= _del_FreeList(gl
->cpl_mem
, 1);
2074 gl
->ext_act_mem
= _del_FreeList(gl
->ext_act_mem
, 1);
2075 gl
->sig_mem
= _del_FreeList(gl
->sig_mem
, 1);
2076 gl
->sigs
= NULL
; /* Already freed by freeing sig_mem */
2077 gl
->bindings
= _del_KeyTab(gl
->bindings
);
2078 if(gl
->vi
.undo
.line
)
2079 free(gl
->vi
.undo
.line
);
2082 free(gl
->tgetent_buf
);
2084 free(gl
->tgetstr_buf
);
2089 free(gl
->user_file
);
2091 gl
->fd_node_mem
= _del_FreeList(gl
->fd_node_mem
, 1);
2092 gl
->fd_nodes
= NULL
; /* Already freed by freeing gl->fd_node_mem */
2095 * Delete the now empty container.
2102 /*.......................................................................
2103 * Bind a control or meta character to an action.
2106 * gl GetLine * The resource object of this program.
2107 * binder KtBinder The source of the binding.
2108 * c char The control or meta character.
2109 * If this is '\0', the call is ignored.
2110 * action const char * The action name to bind the key to.
2112 * return int 0 - OK.
2115 static int gl_bind_control_char(GetLine
*gl
, KtBinder binder
, char c
,
2120 * Quietly reject binding to the NUL control character, since this
2121 * is an ambiguous prefix of all bindings.
2126 * Making sure not to bind characters which aren't either control or
2129 if(IS_CTRL_CHAR(c
) || IS_META_CHAR(c
)) {
2136 * Install the binding.
2138 if(_kt_set_keybinding(gl
->bindings
, binder
, keyseq
, action
)) {
2139 _err_record_msg(gl
->err
, _kt_last_error(gl
->bindings
), END_ERR_MSG
);
2145 /*.......................................................................
2146 * Read a line from the user.
2149 * gl GetLine * A resource object returned by new_GetLine().
2150 * prompt char * The prompt to prefix the line with.
2151 * start_line char * The initial contents of the input line, or NULL
2152 * if it should start out empty.
2153 * start_pos int If start_line isn't NULL, this specifies the
2154 * index of the character over which the cursor
2155 * should initially be positioned within the line.
2156 * If you just want it to follow the last character
2157 * of the line, send -1.
2159 * return char * An internal buffer containing the input line, or
2160 * NULL at the end of input. If the line fitted in
2161 * the buffer there will be a '\n' newline character
2162 * before the terminating '\0'. If it was truncated
2163 * there will be no newline character, and the remains
2164 * of the line should be retrieved via further calls
2167 char *gl_get_line(GetLine
*gl
, const char *prompt
,
2168 const char *start_line
, int start_pos
)
2170 char *retval
; /* The return value of _gl_get_line() */
2172 * Check the arguments.
2179 * Temporarily block all of the signals that we have been asked to trap.
2181 if(gl_mask_signals(gl
, &gl
->old_signal_set
))
2184 * Perform the command-line editing task.
2186 retval
= _gl_get_line(gl
, prompt
, start_line
, start_pos
);
2188 * Restore the process signal mask to how it was when this function was
2191 gl_unmask_signals(gl
, &gl
->old_signal_set
);
2196 /*.......................................................................
2197 * This is the main body of the public function gl_get_line().
2199 static char *_gl_get_line(GetLine
*gl
, const char *prompt
,
2200 const char *start_line
, int start_pos
)
2202 int waserr
= 0; /* True if an error occurs */
2204 * Assume that this call will successfully complete the input
2205 * line until proven otherwise.
2207 gl_clear_status(gl
);
2209 * If this is the first call to this function since new_GetLine(),
2210 * complete any postponed configuration.
2212 if(!gl
->configured
) {
2213 (void) _gl_configure_getline(gl
, NULL
, NULL
, TECLA_CONFIG_FILE
);
2217 * Before installing our signal handler functions, record the fact
2218 * that there are no pending signals.
2220 gl_pending_signal
= -1;
2222 * Temporarily override the signal handlers of the calling program,
2223 * so that we can intercept signals that would leave the terminal
2226 waserr
= gl_override_signal_handlers(gl
);
2228 * After recording the current terminal settings, switch the terminal
2229 * into raw input mode.
2231 waserr
= waserr
|| _gl_raw_io(gl
, 1);
2233 * Attempt to read the line. This will require more than one attempt if
2234 * either a current temporary input file is opened by gl_get_input_line()
2235 * or the end of a temporary input file is reached by gl_read_stream_line().
2239 * Read a line from a non-interactive stream?
2241 if(gl
->file_fp
|| !gl
->is_term
) {
2242 if(gl_read_stream_line(gl
)==0) {
2244 } else if(gl
->file_fp
) {
2245 gl_revert_input(gl
);
2246 gl_record_status(gl
, GLR_NEWLINE
, 0);
2253 * Read from the terminal? Note that the above if() block may have
2254 * changed gl->file_fp, so it is necessary to retest it here, rather
2255 * than using an else statement.
2257 if(!gl
->file_fp
&& gl
->is_term
) {
2258 if(gl_get_input_line(gl
, prompt
, start_line
, start_pos
))
2265 * If an error occurred, but gl->rtn_status is still set to
2266 * GLR_NEWLINE, change the status to GLR_ERROR. Otherwise
2267 * leave it at whatever specific value was assigned by the function
2268 * that aborted input. This means that only functions that trap
2269 * non-generic errors have to remember to update gl->rtn_status
2272 if(waserr
&& gl
->rtn_status
== GLR_NEWLINE
)
2273 gl_record_status(gl
, GLR_ERROR
, errno
);
2275 * Restore terminal settings.
2277 if(gl
->io_mode
!= GL_SERVER_MODE
)
2280 * Restore the signal handlers.
2282 gl_restore_signal_handlers(gl
);
2284 * If gl_get_line() gets aborted early, the errno value associated
2285 * with the event that caused this to happen is recorded in
2286 * gl->rtn_errno. Since errno may have been overwritten by cleanup
2287 * functions after this, restore its value to the value that it had
2288 * when the error condition occured, so that the caller can examine it
2289 * to find out what happened.
2291 errno
= gl
->rtn_errno
;
2293 * Check the completion status to see how to return.
2295 switch(gl
->rtn_status
) {
2296 case GLR_NEWLINE
: /* Success */
2298 case GLR_BLOCKED
: /* These events abort the current input line, */
2299 case GLR_SIGNAL
: /* when in normal blocking I/O mode, but only */
2300 case GLR_TIMEOUT
: /* temporarily pause line editing when in */
2301 case GLR_FDABORT
: /* non-blocking server I/O mode. */
2302 if(gl
->io_mode
!= GL_SERVER_MODE
)
2303 _gl_abandon_line(gl
);
2305 case GLR_ERROR
: /* Unrecoverable errors abort the input line, */
2306 case GLR_EOF
: /* regardless of the I/O mode. */
2308 _gl_abandon_line(gl
);
2313 /*.......................................................................
2314 * Read a single character from the user.
2317 * gl GetLine * A resource object returned by new_GetLine().
2318 * prompt char * The prompt to prefix the line with, or NULL if
2319 * no prompt is required.
2320 * defchar char The character to substitute if the
2321 * user simply hits return, or '\n' if you don't
2322 * need to substitute anything.
2324 * return int The character that was read, or EOF if the read
2325 * had to be aborted (in which case you can call
2326 * gl_return_status() to find out why).
2328 int gl_query_char(GetLine
*gl
, const char *prompt
, char defchar
)
2330 int retval
; /* The return value of _gl_query_char() */
2332 * Check the arguments.
2339 * Temporarily block all of the signals that we have been asked to trap.
2341 if(gl_mask_signals(gl
, &gl
->old_signal_set
))
2344 * Perform the character reading task.
2346 retval
= _gl_query_char(gl
, prompt
, defchar
);
2348 * Restore the process signal mask to how it was when this function was
2351 gl_unmask_signals(gl
, &gl
->old_signal_set
);
2355 /*.......................................................................
2356 * This is the main body of the public function gl_query_char().
2358 static int _gl_query_char(GetLine
*gl
, const char *prompt
, char defchar
)
2360 int c
= EOF
; /* The character to be returned */
2361 int waserr
= 0; /* True if an error occurs */
2363 * Assume that this call will successfully complete the input operation
2364 * until proven otherwise.
2366 gl_clear_status(gl
);
2368 * If this is the first call to this function or gl_get_line(),
2369 * since new_GetLine(), complete any postponed configuration.
2371 if(!gl
->configured
) {
2372 (void) _gl_configure_getline(gl
, NULL
, NULL
, TECLA_CONFIG_FILE
);
2376 * Before installing our signal handler functions, record the fact
2377 * that there are no pending signals.
2379 gl_pending_signal
= -1;
2381 * Temporarily override the signal handlers of the calling program,
2382 * so that we can intercept signals that would leave the terminal
2385 waserr
= gl_override_signal_handlers(gl
);
2387 * After recording the current terminal settings, switch the terminal
2388 * into raw input mode without redisplaying any partially entered
2391 waserr
= waserr
|| _gl_raw_io(gl
, 0);
2393 * Attempt to read the line. This will require more than one attempt if
2394 * either a current temporary input file is opened by gl_get_input_line()
2395 * or the end of a temporary input file is reached by gl_read_stream_line().
2399 * Read a line from a non-interactive stream?
2401 if(gl
->file_fp
|| !gl
->is_term
) {
2402 c
= gl_read_stream_char(gl
);
2403 if(c
!= EOF
) { /* Success? */
2404 if(c
=='\n') c
= defchar
;
2406 } else if(gl
->file_fp
) { /* End of temporary input file? */
2407 gl_revert_input(gl
);
2408 gl_record_status(gl
, GLR_NEWLINE
, 0);
2409 } else { /* An error? */
2415 * Read from the terminal? Note that the above if() block may have
2416 * changed gl->file_fp, so it is necessary to retest it here, rather
2417 * than using an else statement.
2419 if(!gl
->file_fp
&& gl
->is_term
) {
2420 c
= gl_get_query_char(gl
, prompt
, defchar
);
2428 * If an error occurred, but gl->rtn_status is still set to
2429 * GLR_NEWLINE, change the status to GLR_ERROR. Otherwise
2430 * leave it at whatever specific value was assigned by the function
2431 * that aborted input. This means that only functions that trap
2432 * non-generic errors have to remember to update gl->rtn_status
2435 if(waserr
&& gl
->rtn_status
== GLR_NEWLINE
)
2436 gl_record_status(gl
, GLR_ERROR
, errno
);
2438 * Restore terminal settings.
2440 if(gl
->io_mode
!= GL_SERVER_MODE
)
2443 * Restore the signal handlers.
2445 gl_restore_signal_handlers(gl
);
2447 * If this function gets aborted early, the errno value associated
2448 * with the event that caused this to happen is recorded in
2449 * gl->rtn_errno. Since errno may have been overwritten by cleanup
2450 * functions after this, restore its value to the value that it had
2451 * when the error condition occured, so that the caller can examine it
2452 * to find out what happened.
2454 errno
= gl
->rtn_errno
;
2456 * Error conditions are signalled to the caller, by setting the returned
2459 if(gl
->rtn_status
!= GLR_NEWLINE
)
2462 * In this mode, every character that is read is a completed
2463 * transaction, just like reading a completed input line, so prepare
2464 * for the next input line or character.
2466 _gl_abandon_line(gl
);
2468 * Return the acquired character.
2473 /*.......................................................................
2474 * Record of the signal handlers of the calling program, so that they
2475 * can be restored later.
2478 * gl GetLine * The resource object of this library.
2480 * return int 0 - OK.
2483 static int gl_override_signal_handlers(GetLine
*gl
)
2485 GlSignalNode
*sig
; /* A node in the list of signals to be caught */
2487 * Set up our signal handler.
2490 act
.sa_handler
= gl_signal_handler
;
2491 memcpy(&act
.sa_mask
, &gl
->all_signal_set
, sizeof(sigset_t
));
2494 * Get the subset of the signals that we are supposed to trap that
2495 * should actually be trapped.
2497 sigemptyset(&gl
->use_signal_set
);
2498 for(sig
=gl
->sigs
; sig
; sig
=sig
->next
) {
2500 * Trap this signal? If it is blocked by the calling program and we
2501 * haven't been told to unblock it, don't arrange to trap this signal.
2503 if(sig
->flags
& GLS_UNBLOCK_SIG
||
2504 !sigismember(&gl
->old_signal_set
, sig
->signo
)) {
2505 if(sigaddset(&gl
->use_signal_set
, sig
->signo
) == -1) {
2506 _err_record_msg(gl
->err
, "sigaddset error", END_ERR_MSG
);
2512 * Override the actions of the signals that we are trapping.
2514 for(sig
=gl
->sigs
; sig
; sig
=sig
->next
) {
2515 if(sigismember(&gl
->use_signal_set
, sig
->signo
)) {
2516 sigdelset(&act
.sa_mask
, sig
->signo
);
2517 if(sigaction(sig
->signo
, &act
, &sig
->original
)) {
2518 _err_record_msg(gl
->err
, "sigaction error", END_ERR_MSG
);
2521 sigaddset(&act
.sa_mask
, sig
->signo
);
2525 * Record the fact that the application's signal handlers have now
2528 gl
->signals_overriden
= 1;
2530 * Just in case a SIGWINCH signal was sent to the process while our
2531 * SIGWINCH signal handler wasn't in place, check to see if the terminal
2532 * size needs updating.
2534 if(_gl_update_size(gl
))
2539 /*.......................................................................
2540 * Restore the signal handlers of the calling program.
2543 * gl GetLine * The resource object of this library.
2545 * return int 0 - OK.
2548 static int gl_restore_signal_handlers(GetLine
*gl
)
2550 GlSignalNode
*sig
; /* A node in the list of signals to be caught */
2552 * Restore application signal handlers that were overriden
2553 * by gl_override_signal_handlers().
2555 for(sig
=gl
->sigs
; sig
; sig
=sig
->next
) {
2556 if(sigismember(&gl
->use_signal_set
, sig
->signo
) &&
2557 sigaction(sig
->signo
, &sig
->original
, NULL
)) {
2558 _err_record_msg(gl
->err
, "sigaction error", END_ERR_MSG
);
2563 * Record the fact that the application's signal handlers have now
2566 gl
->signals_overriden
= 0;
2570 /*.......................................................................
2571 * This signal handler simply records the fact that a given signal was
2572 * caught in the file-scope gl_pending_signal variable.
2574 static void gl_signal_handler(int signo
)
2576 gl_pending_signal
= signo
;
2577 siglongjmp(gl_setjmp_buffer
, 1);
2580 /*.......................................................................
2581 * Switch the terminal into raw mode after storing the previous terminal
2582 * settings in gl->attributes.
2585 * gl GetLine * The resource object of this program.
2587 * return int 0 - OK.
2590 static int gl_raw_terminal_mode(GetLine
*gl
)
2592 Termios newattr
; /* The new terminal attributes */
2594 * If the terminal is already in raw mode, do nothing.
2599 * Record the current terminal attributes.
2601 if(tcgetattr(gl
->input_fd
, &gl
->oldattr
)) {
2602 _err_record_msg(gl
->err
, "tcgetattr error", END_ERR_MSG
);
2606 * This function shouldn't do anything but record the current terminal
2607 * attritubes if editing has been disabled.
2609 if(gl
->editor
== GL_NO_EDITOR
)
2612 * Modify the existing attributes.
2614 newattr
= gl
->oldattr
;
2616 * Turn off local echo, canonical input mode and extended input processing.
2618 newattr
.c_lflag
&= ~(ECHO
| ICANON
| IEXTEN
);
2620 * Don't translate carriage return to newline, turn off input parity
2621 * checking, don't strip off 8th bit, turn off output flow control.
2623 newattr
.c_iflag
&= ~(ICRNL
| INPCK
| ISTRIP
);
2625 * Clear size bits, turn off parity checking, and allow 8-bit characters.
2627 newattr
.c_cflag
&= ~(CSIZE
| PARENB
);
2628 newattr
.c_cflag
|= CS8
;
2630 * Turn off output processing.
2632 newattr
.c_oflag
&= ~(OPOST
);
2634 * Request one byte at a time, without waiting.
2636 newattr
.c_cc
[VMIN
] = gl
->io_mode
==GL_SERVER_MODE
? 0:1;
2637 newattr
.c_cc
[VTIME
] = 0;
2639 * Install the new terminal modes.
2641 while(tcsetattr(gl
->input_fd
, TCSADRAIN
, &newattr
)) {
2642 if(errno
!= EINTR
) {
2643 _err_record_msg(gl
->err
, "tcsetattr error", END_ERR_MSG
);
2648 * Record the new terminal mode.
2654 /*.......................................................................
2655 * Restore the terminal attributes recorded in gl->oldattr.
2658 * gl GetLine * The resource object of this library.
2660 * return int 0 - OK.
2663 static int gl_restore_terminal_attributes(GetLine
*gl
)
2667 * If not in raw mode, do nothing.
2672 * Before changing the terminal attributes, make sure that all output
2673 * has been passed to the terminal.
2675 if(gl_flush_output(gl
))
2678 * Reset the terminal attributes to the values that they had on
2679 * entry to gl_get_line().
2681 while(tcsetattr(gl
->input_fd
, TCSADRAIN
, &gl
->oldattr
)) {
2682 if(errno
!= EINTR
) {
2683 _err_record_msg(gl
->err
, "tcsetattr error", END_ERR_MSG
);
2689 * Record the new terminal mode.
2695 /*.......................................................................
2696 * Switch the terminal file descriptor to use non-blocking I/O.
2699 * gl GetLine * The resource object of gl_get_line().
2700 * fd int The file descriptor to make non-blocking.
2702 static int gl_nonblocking_io(GetLine
*gl
, int fd
)
2704 int fcntl_flags
; /* The new file-descriptor control flags */
2706 * Is non-blocking I/O supported on this system? Note that even
2707 * without non-blocking I/O, the terminal will probably still act as
2708 * though it was non-blocking, because we also set the terminal
2709 * attributes to return immediately if no input is available and we
2710 * use select() to wait to be able to write. If select() also isn't
2711 * available, then input will probably remain fine, but output could
2712 * block, depending on the behaviour of the terminal driver.
2714 #if defined(NON_BLOCKING_FLAG)
2716 * Query the current file-control flags, and add the
2717 * non-blocking I/O flag.
2719 fcntl_flags
= fcntl(fd
, F_GETFL
) | NON_BLOCKING_FLAG
;
2721 * Install the new control flags.
2723 if(fcntl(fd
, F_SETFL
, fcntl_flags
) == -1) {
2724 _err_record_msg(gl
->err
, "fcntl error", END_ERR_MSG
);
2731 /*.......................................................................
2732 * Switch to blocking terminal I/O.
2735 * gl GetLine * The resource object of gl_get_line().
2736 * fd int The file descriptor to make blocking.
2738 static int gl_blocking_io(GetLine
*gl
, int fd
)
2740 int fcntl_flags
; /* The new file-descriptor control flags */
2742 * Is non-blocking I/O implemented on this system?
2744 #if defined(NON_BLOCKING_FLAG)
2746 * Query the current file control flags and remove the non-blocking
2749 fcntl_flags
= fcntl(fd
, F_GETFL
) & ~NON_BLOCKING_FLAG
;
2751 * Install the modified control flags.
2753 if(fcntl(fd
, F_SETFL
, fcntl_flags
) == -1) {
2754 _err_record_msg(gl
->err
, "fcntl error", END_ERR_MSG
);
2761 /*.......................................................................
2762 * Read a new input line from the user.
2765 * gl GetLine * The resource object of this library.
2766 * prompt char * The prompt to prefix the line with, or NULL to
2767 * use the same prompt that was used by the previous
2769 * start_line char * The initial contents of the input line, or NULL
2770 * if it should start out empty.
2771 * start_pos int If start_line isn't NULL, this specifies the
2772 * index of the character over which the cursor
2773 * should initially be positioned within the line.
2774 * If you just want it to follow the last character
2775 * of the line, send -1.
2777 * return int 0 - OK.
2780 static int gl_get_input_line(GetLine
*gl
, const char *prompt
,
2781 const char *start_line
, int start_pos
)
2783 char c
; /* The character being read */
2785 * Flush any pending output to the terminal.
2787 if(_glq_char_count(gl
->cq
) > 0 && gl_flush_output(gl
))
2790 * Are we starting a new line?
2794 * Delete any incompletely enterred line.
2796 if(gl_erase_line(gl
))
2799 * Display the new line to be edited.
2801 if(gl_present_line(gl
, prompt
, start_line
, start_pos
))
2805 * Read one character at a time.
2807 while(gl_read_terminal(gl
, 1, &c
) == 0) {
2809 * Increment the count of the number of key sequences entered.
2813 * Interpret the character either as the start of a new key-sequence,
2814 * as a continuation of a repeat count, or as a printable character
2815 * to be added to the line.
2817 if(gl_interpret_char(gl
, c
))
2820 * If we just ran an action function which temporarily asked for
2821 * input to be taken from a file, abort this call.
2826 * Has the line been completed?
2829 return gl_line_ended(gl
, c
);
2832 * To get here, gl_read_terminal() must have returned non-zero. See
2833 * whether a signal was caught that requested that the current line
2837 return gl_line_ended(gl
, '\n');
2839 * If I/O blocked while attempting to get the latest character
2840 * of the key sequence, rewind the key buffer to allow interpretation of
2841 * the current key sequence to be restarted on the next call to this
2844 if(gl
->rtn_status
== GLR_BLOCKED
&& gl
->pending_io
== GLP_READ
)
2849 /*.......................................................................
2850 * This is the private function of gl_query_char() that handles
2851 * prompting the user, reading a character from the terminal, and
2852 * displaying what the user entered.
2855 * gl GetLine * The resource object of this library.
2856 * prompt char * The prompt to prefix the line with.
2857 * defchar char The character to substitute if the
2858 * user simply hits return, or '\n' if you don't
2859 * need to substitute anything.
2861 * return int The character that was read, or EOF if something
2862 * prevented a character from being read.
2864 static int gl_get_query_char(GetLine
*gl
, const char *prompt
, int defchar
)
2866 char c
; /* The character being read */
2867 int retval
; /* The return value of this function */
2869 * Flush any pending output to the terminal.
2871 if(_glq_char_count(gl
->cq
) > 0 && gl_flush_output(gl
))
2874 * Delete any incompletely entered line.
2876 if(gl_erase_line(gl
))
2879 * Reset the line input parameters and display the prompt, if any.
2881 if(gl_present_line(gl
, prompt
, NULL
, 0))
2884 * Read one character.
2886 if(gl_read_terminal(gl
, 1, &c
) == 0) {
2888 * In this mode, count each character as being a new key-sequence.
2892 * Delete the character that was read, from the key-press buffer.
2894 gl_discard_chars(gl
, gl
->nread
);
2896 * Convert carriage returns to newlines.
2901 * If the user just hit return, subsitute the default character.
2906 * Display the entered character to the right of the prompt.
2909 if(gl_end_of_line(gl
, 1, NULL
)==0)
2910 gl_print_char(gl
, c
, ' ');
2913 * Record the return character, and mark the call as successful.
2916 gl_record_status(gl
, GLR_NEWLINE
, 0);
2918 * Was a signal caught whose disposition is to cause the current input
2919 * line to be returned? If so return a newline character.
2921 } else if(gl
->endline
) {
2923 gl_record_status(gl
, GLR_NEWLINE
, 0);
2930 if(gl_start_newline(gl
, 1))
2933 * Attempt to flush any pending output.
2935 (void) gl_flush_output(gl
);
2937 * Return either the character that was read, or EOF if an error occurred.
2942 /*.......................................................................
2943 * Add a character to the line buffer at the current cursor position,
2944 * inserting or overwriting according the current mode.
2947 * gl GetLine * The resource object of this library.
2948 * c char The character to be added.
2950 * return int 0 - OK.
2951 * 1 - Insufficient room.
2953 static int gl_add_char_to_line(GetLine
*gl
, char c
)
2956 * Keep a record of the current cursor position.
2958 int buff_curpos
= gl
->buff_curpos
;
2959 int term_curpos
= gl
->term_curpos
;
2961 * Work out the displayed width of the new character.
2963 int width
= gl_displayed_char_width(gl
, c
, term_curpos
);
2965 * If we are in insert mode, or at the end of the line,
2966 * check that we can accomodate a new character in the buffer.
2967 * If not, simply return, leaving it up to the calling program
2968 * to check for the absence of a newline character.
2970 if((gl
->insert
|| buff_curpos
>= gl
->ntotal
) && gl
->ntotal
>= gl
->linelen
)
2973 * Are we adding characters to the line (ie. inserting or appending)?
2975 if(gl
->insert
|| buff_curpos
>= gl
->ntotal
) {
2977 * If inserting, make room for the new character.
2979 if(buff_curpos
< gl
->ntotal
)
2980 gl_make_gap_in_buffer(gl
, buff_curpos
, 1);
2982 * Copy the character into the buffer.
2984 gl_buffer_char(gl
, c
, buff_curpos
);
2987 * Redraw the line from the cursor position to the end of the line,
2988 * and move the cursor to just after the added character.
2990 if(gl_print_string(gl
, gl
->line
+ buff_curpos
, '\0') ||
2991 gl_set_term_curpos(gl
, term_curpos
+ width
))
2994 * Are we overwriting an existing character?
2998 * Get the width of the character being overwritten.
3000 int old_width
= gl_displayed_char_width(gl
, gl
->line
[buff_curpos
],
3003 * Overwrite the character in the buffer.
3005 gl_buffer_char(gl
, c
, buff_curpos
);
3007 * If we are replacing with a narrower character, we need to
3008 * redraw the terminal string to the end of the line, then
3009 * overwrite the trailing old_width - width characters
3012 if(old_width
> width
) {
3013 if(gl_print_string(gl
, gl
->line
+ buff_curpos
, '\0'))
3016 * Clear to the end of the terminal.
3018 if(gl_truncate_display(gl
))
3021 * Move the cursor to the end of the new character.
3023 if(gl_set_term_curpos(gl
, term_curpos
+ width
))
3027 * If we are replacing with a wider character, then we will be
3028 * inserting new characters, and thus extending the line.
3030 } else if(width
> old_width
) {
3032 * Redraw the line from the cursor position to the end of the line,
3033 * and move the cursor to just after the added character.
3035 if(gl_print_string(gl
, gl
->line
+ buff_curpos
, '\0') ||
3036 gl_set_term_curpos(gl
, term_curpos
+ width
))
3040 * The original and replacement characters have the same width,
3041 * so simply overwrite.
3045 * Copy the character into the buffer.
3047 gl_buffer_char(gl
, c
, buff_curpos
);
3050 * Overwrite the original character.
3052 if(gl_print_char(gl
, c
, gl
->line
[gl
->buff_curpos
]))
3059 /*.......................................................................
3060 * Insert/append a string to the line buffer and terminal at the current
3064 * gl GetLine * The resource object of this library.
3065 * s char * The string to be added.
3067 * return int 0 - OK.
3068 * 1 - Insufficient room.
3070 static int gl_add_string_to_line(GetLine
*gl
, const char *s
)
3072 int buff_slen
; /* The length of the string being added to line[] */
3073 int term_slen
; /* The length of the string being written to the terminal */
3074 int buff_curpos
; /* The original value of gl->buff_curpos */
3075 int term_curpos
; /* The original value of gl->term_curpos */
3077 * Keep a record of the current cursor position.
3079 buff_curpos
= gl
->buff_curpos
;
3080 term_curpos
= gl
->term_curpos
;
3082 * How long is the string to be added?
3084 buff_slen
= strlen(s
);
3085 term_slen
= gl_displayed_string_width(gl
, s
, buff_slen
, term_curpos
);
3087 * Check that we can accomodate the string in the buffer.
3088 * If not, simply return, leaving it up to the calling program
3089 * to check for the absence of a newline character.
3091 if(gl
->ntotal
+ buff_slen
> gl
->linelen
)
3094 * Move the characters that follow the cursor in the buffer by
3095 * buff_slen characters to the right.
3097 if(gl
->ntotal
> gl
->buff_curpos
)
3098 gl_make_gap_in_buffer(gl
, gl
->buff_curpos
, buff_slen
);
3100 * Copy the string into the buffer.
3102 gl_buffer_string(gl
, s
, buff_slen
, gl
->buff_curpos
);
3103 gl
->buff_curpos
+= buff_slen
;
3105 * Write the modified part of the line to the terminal, then move
3106 * the terminal cursor to the end of the displayed input string.
3108 if(gl_print_string(gl
, gl
->line
+ buff_curpos
, '\0') ||
3109 gl_set_term_curpos(gl
, term_curpos
+ term_slen
))
3114 /*.......................................................................
3115 * Read a single character from the terminal.
3118 * gl GetLine * The resource object of this library.
3119 * keep int If true, the returned character will be kept in
3120 * the input buffer, for potential replays. It should
3121 * subsequently be removed from the buffer when the
3122 * key sequence that it belongs to has been fully
3123 * processed, by calling gl_discard_chars().
3125 * c char * The character that is read, is assigned to *c.
3127 * return int 0 - OK.
3128 * 1 - Either an I/O error occurred, or a signal was
3129 * caught who's disposition is to abort gl_get_line()
3130 * or to have gl_get_line() return the current line
3131 * as though the user had pressed return. In the
3132 * latter case gl->endline will be non-zero.
3134 static int gl_read_terminal(GetLine
*gl
, int keep
, char *c
)
3137 * Before waiting for a new character to be input, flush unwritten
3138 * characters to the terminal.
3140 if(gl_flush_output(gl
))
3143 * Record the fact that we are about to read from the terminal.
3145 gl
->pending_io
= GLP_READ
;
3147 * If there is already an unread character in the buffer,
3150 if(gl
->nread
< gl
->nbuf
) {
3151 *c
= gl
->keybuf
[gl
->nread
];
3153 * Retain the character in the key buffer, but mark it as having been read?
3158 * Completely remove the character from the key buffer?
3161 memmove(gl
->keybuf
+ gl
->nread
, gl
->keybuf
+ gl
->nread
+ 1,
3162 gl
->nbuf
- gl
->nread
- 1);
3167 * Make sure that there is space in the key buffer for one more character.
3168 * This should always be true if gl_interpret_char() is called for each
3169 * new character added, since it will clear the buffer once it has recognized
3170 * or rejected a key sequence.
3172 if(gl
->nbuf
+ 1 > GL_KEY_MAX
) {
3173 gl_print_info(gl
, "gl_read_terminal: Buffer overflow avoided.",
3179 * Read one character from the terminal.
3181 switch(gl_read_input(gl
, c
)) {
3184 case GL_READ_BLOCKED
:
3185 gl_record_status(gl
, GLR_BLOCKED
, BLOCKED_ERRNO
);
3193 * Append the character to the key buffer?
3196 gl
->keybuf
[gl
->nbuf
] = *c
;
3197 gl
->nread
= ++gl
->nbuf
;
3202 /*.......................................................................
3203 * Read one or more keypresses from the terminal of an input stream.
3206 * gl GetLine * The resource object of this module.
3207 * c char * The character that was read is assigned to *c.
3209 * return GlReadStatus The completion status of the read operation.
3211 static GlReadStatus
gl_read_input(GetLine
*gl
, char *c
)
3214 * We may have to repeat the read if window change signals are received.
3218 * Which file descriptor should we read from? Mark this volatile, so
3219 * that siglongjmp() can't clobber it.
3221 volatile int fd
= gl
->file_fp
? fileno(gl
->file_fp
) : gl
->input_fd
;
3223 * If the endline flag becomes set, don't wait for another character.
3226 return GL_READ_ERROR
;
3228 * Since the code in this function can block, trap signals.
3230 if(sigsetjmp(gl_setjmp_buffer
, 1)==0) {
3232 * Handle the different I/O modes.
3234 switch(gl
->io_mode
) {
3236 * In normal I/O mode, we call the event handler before attempting
3237 * to read, since read() blocks.
3239 case GL_NORMAL_MODE
:
3240 if(gl_event_handler(gl
, fd
))
3241 return GL_READ_ERROR
;
3242 return gl_read_unmasked(gl
, fd
, c
); /* Read one character */
3245 * In non-blocking server I/O mode, we attempt to read a character,
3246 * and only if this fails, call the event handler to wait for a any
3247 * user-configured timeout and any other user-configured events. In
3248 * addition, we turn off the fcntl() non-blocking flag when reading
3249 * from the terminal, to work around a bug in Solaris. We can do this
3250 * without causing the read() to block, because when in non-blocking
3251 * server-I/O mode, gl_raw_io() sets the VMIN terminal attribute to 0,
3252 * which tells the terminal driver to return immediately if no
3253 * characters are available to be read.
3255 case GL_SERVER_MODE
:
3257 GlReadStatus status
; /* The return status */
3258 if(isatty(fd
)) /* If we reading from a terminal, */
3259 gl_blocking_io(gl
, fd
); /* switch to blocking I/O */
3260 status
= gl_read_unmasked(gl
, fd
, c
); /* Try reading */
3261 if(status
== GL_READ_BLOCKED
) { /* Nothing readable yet */
3262 if(gl_event_handler(gl
, fd
)) /* Wait for input */
3263 status
= GL_READ_ERROR
;
3265 status
= gl_read_unmasked(gl
, fd
, c
); /* Try reading again */
3267 gl_nonblocking_io(gl
, fd
); /* Restore non-blocking I/O */
3274 * To get here, one of the signals that we are trapping must have
3275 * been received. Note that by using sigsetjmp() instead of setjmp()
3276 * the signal mask that was blocking these signals will have been
3277 * reinstated, so we can be sure that no more of these signals will
3278 * be received until we explicitly unblock them again.
3280 * First, if non-blocking I/O was temporarily disabled, reinstate it.
3282 if(gl
->io_mode
== GL_SERVER_MODE
)
3283 gl_nonblocking_io(gl
, fd
);
3285 * Now respond to the signal that was caught.
3287 if(gl_check_caught_signal(gl
))
3288 return GL_READ_ERROR
;
3292 /*.......................................................................
3293 * This is a private function of gl_read_input(), which unblocks signals
3294 * temporarily while it reads a single character from the specified file
3298 * gl GetLine * The resource object of this module.
3299 * fd int The file descriptor to read from.
3300 * c char * The character that was read is assigned to *c.
3302 * return GlReadStatus The completion status of the read.
3304 static int gl_read_unmasked(GetLine
*gl
, int fd
, char *c
)
3306 int nread
; /* The return value of read() */
3308 * Unblock the signals that we are trapping, while waiting for I/O.
3310 gl_catch_signals(gl
);
3312 * Attempt to read one character from the terminal, restarting the read
3313 * if any signals that we aren't trapping, are received.
3317 nread
= read(fd
, c
, 1);
3318 } while(nread
< 0 && errno
==EINTR
);
3320 * Block all of the signals that we are trapping.
3322 gl_mask_signals(gl
, NULL
);
3324 * Check the completion status of the read.
3330 return (isatty(fd
) || errno
!= 0) ? GL_READ_BLOCKED
: GL_READ_EOF
;
3332 return GL_READ_ERROR
;
3336 /*.......................................................................
3337 * Remove a specified number of characters from the start of the
3338 * key-press lookahead buffer, gl->keybuf[], and arrange for the next
3339 * read to start from the character at the start of the shifted buffer.
3342 * gl GetLine * The resource object of this module.
3343 * nused int The number of characters to discard from the start
3346 static void gl_discard_chars(GetLine
*gl
, int nused
)
3348 int nkeep
= gl
->nbuf
- nused
;
3350 memmove(gl
->keybuf
, gl
->keybuf
+ nused
, nkeep
);
3354 gl
->nbuf
= gl
->nread
= 0;
3358 /*.......................................................................
3359 * This function is called to handle signals caught between calls to
3360 * sigsetjmp() and siglongjmp().
3363 * gl GetLine * The resource object of this library.
3365 * return int 0 - Signal handled internally.
3366 * 1 - Signal requires gl_get_line() to abort.
3368 static int gl_check_caught_signal(GetLine
*gl
)
3370 GlSignalNode
*sig
; /* The signal disposition */
3371 SigAction keep_action
; /* The signal disposition of tecla signal handlers */
3372 unsigned flags
; /* The signal processing flags to use */
3373 int signo
; /* The signal to be handled */
3375 * Was no signal caught?
3377 if(gl_pending_signal
== -1)
3380 * Get the signal to be handled.
3382 signo
= gl_pending_signal
;
3384 * Mark the signal as handled. Note that at this point, all of
3385 * the signals that we are trapping are blocked from delivery.
3387 gl_pending_signal
= -1;
3389 * Record the signal that was caught, so that the user can query it later.
3391 gl
->last_signal
= signo
;
3393 * In non-blocking server mode, the application is responsible for
3394 * responding to terminal signals, and we don't want gl_get_line()s
3395 * normal signal handling to clash with this, so whenever a signal
3396 * is caught, we arrange for gl_get_line() to abort and requeue the
3397 * signal while signals are still blocked. If the application
3398 * had the signal unblocked when gl_get_line() was called, the signal
3399 * will be delivered again as soon as gl_get_line() restores the
3400 * process signal mask, just before returning to the application.
3401 * Note that the caller of this function should set gl->pending_io
3402 * to the appropriate choice of GLP_READ and GLP_WRITE, before returning.
3404 if(gl
->io_mode
==GL_SERVER_MODE
) {
3405 gl_record_status(gl
, GLR_SIGNAL
, EINTR
);
3410 * Lookup the requested disposition of this signal.
3412 for(sig
=gl
->sigs
; sig
&& sig
->signo
!= signo
; sig
=sig
->next
)
3417 * Get the signal response flags for this signal.
3421 * Did we receive a terminal size signal?
3424 if(signo
== SIGWINCH
&& _gl_update_size(gl
))
3428 * Start a fresh line?
3430 if(flags
& GLS_RESTORE_LINE
) {
3431 if(gl_start_newline(gl
, 0))
3435 * Restore terminal settings to how they were before gl_get_line() was
3438 if(flags
& GLS_RESTORE_TTY
)
3439 gl_restore_terminal_attributes(gl
);
3441 * Restore signal handlers to how they were before gl_get_line() was
3442 * called? If this hasn't been requested, only reinstate the signal
3443 * handler of the signal that we are handling.
3445 if(flags
& GLS_RESTORE_SIG
) {
3446 gl_restore_signal_handlers(gl
);
3447 gl_unmask_signals(gl
, &gl
->old_signal_set
);
3449 (void) sigaction(sig
->signo
, &sig
->original
, &keep_action
);
3450 (void) sigprocmask(SIG_UNBLOCK
, &sig
->proc_mask
, NULL
);
3453 * Forward the signal to the application's signal handler.
3455 if(!(flags
& GLS_DONT_FORWARD
))
3458 * Reinstate our signal handlers.
3460 if(flags
& GLS_RESTORE_SIG
) {
3461 gl_mask_signals(gl
, NULL
);
3462 gl_override_signal_handlers(gl
);
3464 (void) sigaction(sig
->signo
, &keep_action
, NULL
);
3465 (void) sigprocmask(SIG_BLOCK
, &sig
->proc_mask
, NULL
);
3468 * Do we need to reinstate our terminal settings?
3470 if(flags
& GLS_RESTORE_TTY
)
3471 gl_raw_terminal_mode(gl
);
3475 if(flags
& GLS_REDRAW_LINE
)
3476 gl_queue_redisplay(gl
);
3480 switch(sig
->after
) {
3482 gl_newline(gl
, 1, NULL
);
3483 return gl_flush_output(gl
);
3486 gl_record_status(gl
, GLR_SIGNAL
, sig
->errno_value
);
3490 return gl_flush_output(gl
);
3496 /*.......................................................................
3497 * Get pertinent terminal control strings and the initial terminal size.
3500 * gl GetLine * The resource object of this library.
3501 * term char * The type of the terminal.
3503 * return int 0 - OK.
3506 static int gl_control_strings(GetLine
*gl
, const char *term
)
3508 int bad_term
= 0; /* True if term is unusable */
3510 * Discard any existing control strings from a previous terminal.
3518 gl
->clear_eol
= NULL
;
3519 gl
->clear_eod
= NULL
;
3524 gl
->sound_bell
= NULL
;
3526 gl
->underline
= NULL
;
3527 gl
->standout
= NULL
;
3531 gl
->text_attr_off
= NULL
;
3539 * If possible lookup the information in a terminal information
3545 if(!term
|| setupterm((char *)term
, gl
->input_fd
, &errret
) == ERR
) {
3548 _clr_StringGroup(gl
->capmem
);
3549 gl
->left
= gl_tigetstr(gl
, "cub1");
3550 gl
->right
= gl_tigetstr(gl
, "cuf1");
3551 gl
->up
= gl_tigetstr(gl
, "cuu1");
3552 gl
->down
= gl_tigetstr(gl
, "cud1");
3553 gl
->home
= gl_tigetstr(gl
, "home");
3554 gl
->clear_eol
= gl_tigetstr(gl
, "el");
3555 gl
->clear_eod
= gl_tigetstr(gl
, "ed");
3556 gl
->u_arrow
= gl_tigetstr(gl
, "kcuu1");
3557 gl
->d_arrow
= gl_tigetstr(gl
, "kcud1");
3558 gl
->l_arrow
= gl_tigetstr(gl
, "kcub1");
3559 gl
->r_arrow
= gl_tigetstr(gl
, "kcuf1");
3560 gl
->left_n
= gl_tigetstr(gl
, "cub");
3561 gl
->right_n
= gl_tigetstr(gl
, "cuf");
3562 gl
->sound_bell
= gl_tigetstr(gl
, "bel");
3563 gl
->bold
= gl_tigetstr(gl
, "bold");
3564 gl
->underline
= gl_tigetstr(gl
, "smul");
3565 gl
->standout
= gl_tigetstr(gl
, "smso");
3566 gl
->dim
= gl_tigetstr(gl
, "dim");
3567 gl
->reverse
= gl_tigetstr(gl
, "rev");
3568 gl
->blink
= gl_tigetstr(gl
, "blink");
3569 gl
->text_attr_off
= gl_tigetstr(gl
, "sgr0");
3572 #elif defined(USE_TERMCAP)
3573 if(!term
|| tgetent(gl
->tgetent_buf
, (char *)term
) < 0) {
3576 char *tgetstr_buf_ptr
= gl
->tgetstr_buf
;
3577 _clr_StringGroup(gl
->capmem
);
3578 gl
->left
= gl_tgetstr(gl
, "le", &tgetstr_buf_ptr
);
3579 gl
->right
= gl_tgetstr(gl
, "nd", &tgetstr_buf_ptr
);
3580 gl
->up
= gl_tgetstr(gl
, "up", &tgetstr_buf_ptr
);
3581 gl
->down
= gl_tgetstr(gl
, "do", &tgetstr_buf_ptr
);
3582 gl
->home
= gl_tgetstr(gl
, "ho", &tgetstr_buf_ptr
);
3583 gl
->clear_eol
= gl_tgetstr(gl
, "ce", &tgetstr_buf_ptr
);
3584 gl
->clear_eod
= gl_tgetstr(gl
, "cd", &tgetstr_buf_ptr
);
3585 gl
->u_arrow
= gl_tgetstr(gl
, "ku", &tgetstr_buf_ptr
);
3586 gl
->d_arrow
= gl_tgetstr(gl
, "kd", &tgetstr_buf_ptr
);
3587 gl
->l_arrow
= gl_tgetstr(gl
, "kl", &tgetstr_buf_ptr
);
3588 gl
->r_arrow
= gl_tgetstr(gl
, "kr", &tgetstr_buf_ptr
);
3589 gl
->sound_bell
= gl_tgetstr(gl
, "bl", &tgetstr_buf_ptr
);
3590 gl
->bold
= gl_tgetstr(gl
, "md", &tgetstr_buf_ptr
);
3591 gl
->underline
= gl_tgetstr(gl
, "us", &tgetstr_buf_ptr
);
3592 gl
->standout
= gl_tgetstr(gl
, "so", &tgetstr_buf_ptr
);
3593 gl
->dim
= gl_tgetstr(gl
, "mh", &tgetstr_buf_ptr
);
3594 gl
->reverse
= gl_tgetstr(gl
, "mr", &tgetstr_buf_ptr
);
3595 gl
->blink
= gl_tgetstr(gl
, "mb", &tgetstr_buf_ptr
);
3596 gl
->text_attr_off
= gl_tgetstr(gl
, "me", &tgetstr_buf_ptr
);
3600 * Report term being unusable.
3603 gl_print_info(gl
, "Bad terminal type: \"", term
? term
: "(null)",
3604 "\". Will assume vt100.", GL_END_INFO
);
3607 * Fill in missing information with ANSI VT100 strings.
3610 gl
->left
= "\b"; /* ^H */
3612 gl
->right
= GL_ESC_STR
"[C";
3614 gl
->up
= GL_ESC_STR
"[A";
3618 gl
->home
= GL_ESC_STR
"[H";
3622 gl
->clear_eol
= GL_ESC_STR
"[K";
3624 gl
->clear_eod
= GL_ESC_STR
"[J";
3626 gl
->u_arrow
= GL_ESC_STR
"[A";
3628 gl
->d_arrow
= GL_ESC_STR
"[B";
3630 gl
->l_arrow
= GL_ESC_STR
"[D";
3632 gl
->r_arrow
= GL_ESC_STR
"[C";
3634 gl
->sound_bell
= "\a";
3636 gl
->bold
= GL_ESC_STR
"[1m";
3638 gl
->underline
= GL_ESC_STR
"[4m";
3640 gl
->standout
= GL_ESC_STR
"[1;7m";
3642 gl
->dim
= ""; /* Not available */
3644 gl
->reverse
= GL_ESC_STR
"[7m";
3646 gl
->blink
= GL_ESC_STR
"[5m";
3647 if(!gl
->text_attr_off
)
3648 gl
->text_attr_off
= GL_ESC_STR
"[m";
3650 * Find out the current terminal size.
3652 (void) _gl_terminal_size(gl
, GL_DEF_NCOLUMN
, GL_DEF_NLINE
, NULL
);
3657 /*.......................................................................
3658 * This is a private function of gl_control_strings() used to look up
3659 * a termninal capability string from the terminfo database and make
3660 * a private copy of it.
3663 * gl GetLine * The resource object of gl_get_line().
3664 * name const char * The name of the terminfo string to look up.
3666 * return const char * The local copy of the capability, or NULL
3669 static const char *gl_tigetstr(GetLine
*gl
, const char *name
)
3671 const char *value
= tigetstr((char *)name
);
3672 if(!value
|| value
== (char *) -1)
3674 return _sg_store_string(gl
->capmem
, value
, 0);
3676 #elif defined(USE_TERMCAP)
3677 /*.......................................................................
3678 * This is a private function of gl_control_strings() used to look up
3679 * a termninal capability string from the termcap database and make
3680 * a private copy of it. Note that some emulations of tgetstr(), such
3681 * as that used by Solaris, ignores the buffer pointer that is past to
3682 * it, so we can't assume that a private copy has been made that won't
3683 * be trashed by another call to gl_control_strings() by another
3684 * GetLine object. So we make what may be a redundant private copy
3685 * of the string in gl->capmem.
3688 * gl GetLine * The resource object of gl_get_line().
3689 * name const char * The name of the terminfo string to look up.
3691 * bufptr char ** On input *bufptr points to the location in
3692 * gl->tgetstr_buf at which to record the
3693 * capability string. On output *bufptr is
3694 * incremented over the stored string.
3696 * return const char * The local copy of the capability, or NULL
3699 static const char *gl_tgetstr(GetLine
*gl
, const char *name
, char **bufptr
)
3701 const char *value
= tgetstr((char *)name
, bufptr
);
3702 if(!value
|| value
== (char *) -1)
3704 return _sg_store_string(gl
->capmem
, value
, 0);
3708 /*.......................................................................
3709 * This is an action function that implements a user interrupt (eg. ^C).
3711 static KT_KEY_FN(gl_user_interrupt
)
3717 /*.......................................................................
3718 * This is an action function that implements the abort signal.
3720 static KT_KEY_FN(gl_abort
)
3726 /*.......................................................................
3727 * This is an action function that sends a suspend signal (eg. ^Z) to the
3728 * the parent process.
3730 static KT_KEY_FN(gl_suspend
)
3736 /*.......................................................................
3737 * This is an action function that halts output to the terminal.
3739 static KT_KEY_FN(gl_stop_output
)
3741 tcflow(gl
->output_fd
, TCOOFF
);
3745 /*.......................................................................
3746 * This is an action function that resumes halted terminal output.
3748 static KT_KEY_FN(gl_start_output
)
3750 tcflow(gl
->output_fd
, TCOON
);
3754 /*.......................................................................
3755 * This is an action function that allows the next character to be accepted
3756 * without any interpretation as a special character.
3758 static KT_KEY_FN(gl_literal_next
)
3760 char c
; /* The character to be added to the line */
3763 * Get the character to be inserted literally.
3765 if(gl_read_terminal(gl
, 1, &c
))
3768 * Add the character to the line 'count' times.
3770 for(i
=0; i
<count
; i
++)
3771 gl_add_char_to_line(gl
, c
);
3775 /*.......................................................................
3776 * Return the width of a tab character at a given position when
3777 * displayed at a given position on the terminal. This is needed
3778 * because the width of tab characters depends on where they are,
3779 * relative to the preceding tab stops.
3782 * gl GetLine * The resource object of this library.
3783 * term_curpos int The destination terminal location of the character.
3785 * return int The number of terminal charaters needed.
3787 static int gl_displayed_tab_width(GetLine
*gl
, int term_curpos
)
3789 return TAB_WIDTH
- ((term_curpos
% gl
->ncolumn
) % TAB_WIDTH
);
3792 /*.......................................................................
3793 * Return the number of characters needed to display a given character
3794 * on the screen. Tab characters require eight spaces, and control
3795 * characters are represented by a caret followed by the modified
3799 * gl GetLine * The resource object of this library.
3800 * c char The character to be displayed.
3801 * term_curpos int The destination terminal location of the character.
3802 * This is needed because the width of tab characters
3803 * depends on where they are, relative to the
3804 * preceding tab stops.
3806 * return int The number of terminal charaters needed.
3808 static int gl_displayed_char_width(GetLine
*gl
, char c
, int term_curpos
)
3811 return gl_displayed_tab_width(gl
, term_curpos
);
3814 if(!isprint((int)(unsigned char) c
))
3815 return gl_octal_width((int)(unsigned char)c
) + 1;
3820 /*.......................................................................
3821 * Work out the length of given string of characters on the terminal.
3824 * gl GetLine * The resource object of this library.
3825 * string char * The string to be measured.
3826 * nc int The number of characters to be measured, or -1
3827 * to measure the whole string.
3828 * term_curpos int The destination terminal location of the character.
3829 * This is needed because the width of tab characters
3830 * depends on where they are, relative to the
3831 * preceding tab stops.
3833 * return int The number of displayed characters.
3835 static int gl_displayed_string_width(GetLine
*gl
, const char *string
, int nc
,
3838 int slen
= 0; /* The displayed number of characters */
3841 * How many characters are to be measured?
3844 nc
= strlen(string
);
3846 * Add up the length of the displayed string.
3849 slen
+= gl_displayed_char_width(gl
, string
[i
], term_curpos
+ slen
);
3853 /*.......................................................................
3854 * Write a string verbatim to the current terminal or output stream.
3856 * Note that when async-signal safety is required, the 'buffered'
3857 * argument must be 0, and n must not be -1.
3860 * gl GetLine * The resource object of the gl_get_line().
3861 * buffered int If true, used buffered I/O when writing to
3862 * the terminal. Otherwise use async-signal-safe
3864 * string const char * The string to be written (this need not be
3865 * '\0' terminated unless n<0).
3866 * n int The number of characters to write from the
3867 * prefix of string[], or -1 to request that
3868 * gl_print_raw_string() use strlen() to figure
3871 * return int 0 - OK.
3874 static int gl_print_raw_string(GetLine
*gl
, int buffered
,
3875 const char *string
, int n
)
3877 GlWriteFn
*write_fn
= buffered
? gl_write_fn
: gl
->flush_fn
;
3879 * Only display output when echoing is turned on.
3882 int ndone
= 0; /* The number of characters written so far */
3884 * When using un-buffered I/O, flush pending output first.
3887 if(gl_flush_output(gl
))
3891 * If no length has been provided, measure the length of the string.
3898 if(write_fn(gl
, string
+ ndone
, n
-ndone
) != n
)
3904 /*.......................................................................
3905 * Output a terminal control sequence. When using terminfo,
3906 * this must be a sequence returned by tgetstr() or tigetstr()
3910 * gl GetLine * The resource object of this library.
3911 * nline int The number of lines affected by the operation,
3912 * or 1 if not relevant.
3913 * string char * The control sequence to be sent.
3915 * return int 0 - OK.
3918 static int gl_print_control_sequence(GetLine
*gl
, int nline
, const char *string
)
3920 int waserr
= 0; /* True if an error occurs */
3922 * Only write characters to the terminal when echoing is enabled.
3925 #if defined(USE_TERMINFO) || defined(USE_TERMCAP)
3928 tputs((char *)string
, nline
, gl_tputs_putchar
);
3929 waserr
= errno
!= 0;
3931 waserr
= gl_print_raw_string(gl
, 1, string
, -1);
3937 #if defined(USE_TERMINFO) || defined(USE_TERMCAP)
3938 /*.......................................................................
3939 * The following callback function is called by tputs() to output a raw
3940 * control character to the terminal.
3942 static TputsRetType
gl_tputs_putchar(TputsArgType c
)
3945 #if TPUTS_RETURNS_VALUE
3946 return gl_print_raw_string(tputs_gl
, 1, &ch
, 1);
3948 (void) gl_print_raw_string(tputs_gl
, 1, &ch
, 1);
3953 /*.......................................................................
3954 * Move the terminal cursor n characters to the left or right.
3957 * gl GetLine * The resource object of this program.
3958 * n int number of positions to the right (> 0) or left (< 0).
3960 * return int 0 - OK.
3963 static int gl_terminal_move_cursor(GetLine
*gl
, int n
)
3965 int cur_row
, cur_col
; /* The current terminal row and column index of */
3966 /* the cursor wrt the start of the input line. */
3967 int new_row
, new_col
; /* The target terminal row and column index of */
3968 /* the cursor wrt the start of the input line. */
3970 * Do nothing if the input line isn't currently displayed. In this
3971 * case, the cursor will be moved to the right place when the line
3972 * is next redisplayed.
3977 * How far can we move left?
3979 if(gl
->term_curpos
+ n
< 0)
3980 n
= gl
->term_curpos
;
3982 * Break down the current and target cursor locations into rows and columns.
3984 cur_row
= gl
->term_curpos
/ gl
->ncolumn
;
3985 cur_col
= gl
->term_curpos
% gl
->ncolumn
;
3986 new_row
= (gl
->term_curpos
+ n
) / gl
->ncolumn
;
3987 new_col
= (gl
->term_curpos
+ n
) % gl
->ncolumn
;
3989 * Move down to the next line.
3991 for(; cur_row
< new_row
; cur_row
++) {
3992 if(gl_print_control_sequence(gl
, 1, gl
->down
))
3996 * Move up to the previous line.
3998 for(; cur_row
> new_row
; cur_row
--) {
3999 if(gl_print_control_sequence(gl
, 1, gl
->up
))
4003 * Move to the right within the target line?
4005 if(cur_col
< new_col
) {
4008 * Use a parameterized control sequence if it generates less control
4009 * characters (guess based on ANSI terminal termcap entry).
4011 if(gl
->right_n
!= NULL
&& new_col
- cur_col
> 1) {
4012 if(gl_print_control_sequence(gl
, 1, tparm((char *)gl
->right_n
,
4013 (long)(new_col
- cur_col
), 0l, 0l, 0l, 0l, 0l, 0l, 0l, 0l)))
4018 for(; cur_col
< new_col
; cur_col
++) {
4019 if(gl_print_control_sequence(gl
, 1, gl
->right
))
4024 * Move to the left within the target line?
4026 } else if(cur_col
> new_col
) {
4029 * Use a parameterized control sequence if it generates less control
4030 * characters (guess based on ANSI terminal termcap entry).
4032 if(gl
->left_n
!= NULL
&& cur_col
- new_col
> 3) {
4033 if(gl_print_control_sequence(gl
, 1, tparm((char *)gl
->left_n
,
4034 (long)(cur_col
- new_col
), 0l, 0l, 0l, 0l, 0l, 0l, 0l, 0l)))
4039 for(; cur_col
> new_col
; cur_col
--) {
4040 if(gl_print_control_sequence(gl
, 1, gl
->left
))
4046 * Update the recorded position of the terminal cursor.
4048 gl
->term_curpos
+= n
;
4052 /*.......................................................................
4053 * Write a character to the terminal after expanding tabs and control
4054 * characters to their multi-character representations.
4057 * gl GetLine * The resource object of this program.
4058 * c char The character to be output.
4059 * pad char Many terminals have the irritating feature that
4060 * when one writes a character in the last column of
4061 * of the terminal, the cursor isn't wrapped to the
4062 * start of the next line until one more character
4063 * is written. Some terminals don't do this, so
4064 * after such a write, we don't know where the
4065 * terminal is unless we output an extra character.
4066 * This argument specifies the character to write.
4067 * If at the end of the input line send '\0' or a
4068 * space, and a space will be written. Otherwise,
4069 * pass the next character in the input line
4070 * following the one being written.
4072 * return int 0 - OK.
4074 static int gl_print_char(GetLine
*gl
, char c
, char pad
)
4076 char string
[TAB_WIDTH
+ 4]; /* A work area for composing compound strings */
4077 int nchar
; /* The number of terminal characters */
4080 * Check for special characters.
4084 * How many spaces do we need to represent a tab at the current terminal
4087 nchar
= gl_displayed_tab_width(gl
, gl
->term_curpos
);
4089 * Compose the tab string.
4091 for(i
=0; i
<nchar
; i
++)
4093 } else if(IS_CTRL_CHAR(c
)) {
4095 string
[1] = CTRL_TO_CHAR(c
);
4097 } else if(!isprint((int)(unsigned char) c
)) {
4098 snprintf(string
, sizeof(string
), "\\%o", (int)(unsigned char)c
);
4099 nchar
= strlen(string
);
4105 * Terminate the string.
4107 string
[nchar
] = '\0';
4109 * Write the string to the terminal.
4111 if(gl_print_raw_string(gl
, 1, string
, -1))
4114 * Except for one exception to be described in a moment, the cursor should
4115 * now have been positioned after the character that was just output.
4117 gl
->term_curpos
+= nchar
;
4119 * Keep a record of the number of characters in the terminal version
4120 * of the input line.
4122 if(gl
->term_curpos
> gl
->term_len
)
4123 gl
->term_len
= gl
->term_curpos
;
4125 * If the new character ended exactly at the end of a line,
4126 * most terminals won't move the cursor onto the next line until we
4127 * have written a character on the next line, so append an extra
4128 * space then move the cursor back.
4130 if(gl
->term_curpos
% gl
->ncolumn
== 0) {
4131 int term_curpos
= gl
->term_curpos
;
4132 if(gl_print_char(gl
, pad
? pad
: ' ', ' ') ||
4133 gl_set_term_curpos(gl
, term_curpos
))
4139 /*.......................................................................
4140 * Write a string to the terminal after expanding tabs and control
4141 * characters to their multi-character representations.
4144 * gl GetLine * The resource object of this program.
4145 * string char * The string to be output.
4146 * pad char Many terminals have the irritating feature that
4147 * when one writes a character in the last column of
4148 * of the terminal, the cursor isn't wrapped to the
4149 * start of the next line until one more character
4150 * is written. Some terminals don't do this, so
4151 * after such a write, we don't know where the
4152 * terminal is unless we output an extra character.
4153 * This argument specifies the character to write.
4154 * If at the end of the input line send '\0' or a
4155 * space, and a space will be written. Otherwise,
4156 * pass the next character in the input line
4157 * following the one being written.
4159 * return int 0 - OK.
4161 static int gl_print_string(GetLine
*gl
, const char *string
, char pad
)
4163 const char *cptr
; /* A pointer into string[] */
4164 for(cptr
=string
; *cptr
; cptr
++) {
4165 char nextc
= cptr
[1];
4166 if(gl_print_char(gl
, *cptr
, nextc
? nextc
: pad
))
4172 /*.......................................................................
4173 * Move the terminal cursor position.
4176 * gl GetLine * The resource object of this library.
4177 * term_curpos int The destination terminal cursor position.
4179 * return int 0 - OK.
4182 static int gl_set_term_curpos(GetLine
*gl
, int term_curpos
)
4184 return gl_terminal_move_cursor(gl
, term_curpos
- gl
->term_curpos
);
4187 /*.......................................................................
4188 * This is an action function that moves the buffer cursor one character
4189 * left, and updates the terminal cursor to match.
4191 static KT_KEY_FN(gl_cursor_left
)
4193 return gl_place_cursor(gl
, gl
->buff_curpos
- count
);
4196 /*.......................................................................
4197 * This is an action function that moves the buffer cursor one character
4198 * right, and updates the terminal cursor to match.
4200 static KT_KEY_FN(gl_cursor_right
)
4202 return gl_place_cursor(gl
, gl
->buff_curpos
+ count
);
4205 /*.......................................................................
4206 * This is an action function that toggles between overwrite and insert
4209 static KT_KEY_FN(gl_insert_mode
)
4211 gl
->insert
= !gl
->insert
;
4215 /*.......................................................................
4216 * This is an action function which moves the cursor to the beginning of
4219 static KT_KEY_FN(gl_beginning_of_line
)
4221 return gl_place_cursor(gl
, 0);
4224 /*.......................................................................
4225 * This is an action function which moves the cursor to the end of
4228 static KT_KEY_FN(gl_end_of_line
)
4230 return gl_place_cursor(gl
, gl
->ntotal
);
4233 /*.......................................................................
4234 * This is an action function which deletes the entire contents of the
4237 static KT_KEY_FN(gl_delete_line
)
4240 * If in vi command mode, preserve the current line for potential
4243 gl_save_for_undo(gl
);
4245 * Copy the contents of the line to the cut buffer.
4247 strlcpy(gl
->cutbuf
, gl
->line
, gl
->linelen
);
4251 gl_truncate_buffer(gl
, 0);
4253 * Move the terminal cursor to just after the prompt.
4255 if(gl_place_cursor(gl
, 0))
4258 * Clear from the end of the prompt to the end of the terminal.
4260 if(gl_truncate_display(gl
))
4265 /*.......................................................................
4266 * This is an action function which deletes all characters between the
4267 * current cursor position and the end of the line.
4269 static KT_KEY_FN(gl_kill_line
)
4272 * If in vi command mode, preserve the current line for potential
4275 gl_save_for_undo(gl
);
4277 * Copy the part of the line that is about to be deleted to the cut buffer.
4279 strlcpy(gl
->cutbuf
, gl
->line
+ gl
->buff_curpos
, gl
->linelen
);
4281 * Terminate the buffered line at the current cursor position.
4283 gl_truncate_buffer(gl
, gl
->buff_curpos
);
4285 * Clear the part of the line that follows the cursor.
4287 if(gl_truncate_display(gl
))
4290 * Explicitly reset the cursor position to allow vi command mode
4291 * constraints on its position to be set.
4293 return gl_place_cursor(gl
, gl
->buff_curpos
);
4296 /*.......................................................................
4297 * This is an action function which deletes all characters between the
4298 * start of the line and the current cursor position.
4300 static KT_KEY_FN(gl_backward_kill_line
)
4303 * How many characters are to be deleted from before the cursor?
4305 int nc
= gl
->buff_curpos
- gl
->insert_curpos
;
4309 * Move the cursor to the start of the line, or in vi input mode,
4310 * the start of the sub-line at which insertion started, and delete
4311 * up to the old cursor position.
4313 return gl_place_cursor(gl
, gl
->insert_curpos
) ||
4314 gl_delete_chars(gl
, nc
, gl
->editor
== GL_EMACS_MODE
|| gl
->vi
.command
);
4317 /*.......................................................................
4318 * This is an action function which moves the cursor forward by a word.
4320 static KT_KEY_FN(gl_forward_word
)
4322 return gl_place_cursor(gl
, gl_nth_word_end_forward(gl
, count
) +
4323 (gl
->editor
==GL_EMACS_MODE
));
4326 /*.......................................................................
4327 * This is an action function which moves the cursor forward to the start
4330 static KT_KEY_FN(gl_forward_to_word
)
4332 return gl_place_cursor(gl
, gl_nth_word_start_forward(gl
, count
));
4335 /*.......................................................................
4336 * This is an action function which moves the cursor backward by a word.
4338 static KT_KEY_FN(gl_backward_word
)
4340 return gl_place_cursor(gl
, gl_nth_word_start_backward(gl
, count
));
4343 /*.......................................................................
4344 * Delete one or more characters, starting with the one under the cursor.
4347 * gl GetLine * The resource object of this library.
4348 * nc int The number of characters to delete.
4349 * cut int If true, copy the characters to the cut buffer.
4351 * return int 0 - OK.
4354 static int gl_delete_chars(GetLine
*gl
, int nc
, int cut
)
4357 * If in vi command mode, preserve the current line for potential
4360 gl_save_for_undo(gl
);
4362 * If there are fewer than nc characters following the cursor, limit
4363 * nc to the number available.
4365 if(gl
->buff_curpos
+ nc
> gl
->ntotal
)
4366 nc
= gl
->ntotal
- gl
->buff_curpos
;
4368 * Copy the about to be deleted region to the cut buffer.
4371 memcpy(gl
->cutbuf
, gl
->line
+ gl
->buff_curpos
, nc
);
4372 gl
->cutbuf
[nc
] = '\0';
4375 * Nothing to delete?
4380 * In vi overwrite mode, restore any previously overwritten characters
4381 * from the undo buffer.
4383 if(gl
->editor
== GL_VI_MODE
&& !gl
->vi
.command
&& !gl
->insert
) {
4385 * How many of the characters being deleted can be restored from the
4388 int nrestore
= gl
->buff_curpos
+ nc
<= gl
->vi
.undo
.ntotal
?
4389 nc
: gl
->vi
.undo
.ntotal
- gl
->buff_curpos
;
4391 * Restore any available characters.
4394 gl_buffer_string(gl
, gl
->vi
.undo
.line
+ gl
->buff_curpos
, nrestore
,
4398 * If their were insufficient characters in the undo buffer, then this
4399 * implies that we are deleting from the end of the line, so we need
4400 * to terminate the line either where the undo buffer ran out, or if
4401 * we are deleting from beyond the end of the undo buffer, at the current
4404 if(nc
!= nrestore
) {
4405 gl_truncate_buffer(gl
, (gl
->vi
.undo
.ntotal
> gl
->buff_curpos
) ?
4406 gl
->vi
.undo
.ntotal
: gl
->buff_curpos
);
4410 * Copy the remaining part of the line back over the deleted characters.
4412 gl_remove_from_buffer(gl
, gl
->buff_curpos
, nc
);
4415 * Redraw the remaining characters following the cursor.
4417 if(gl_print_string(gl
, gl
->line
+ gl
->buff_curpos
, '\0'))
4420 * Clear to the end of the terminal.
4422 if(gl_truncate_display(gl
))
4425 * Place the cursor at the start of where the deletion was performed.
4427 return gl_place_cursor(gl
, gl
->buff_curpos
);
4430 /*.......................................................................
4431 * This is an action function which deletes character(s) under the
4432 * cursor without moving the cursor.
4434 static KT_KEY_FN(gl_forward_delete_char
)
4437 * Delete 'count' characters.
4439 return gl_delete_chars(gl
, count
, gl
->vi
.command
);
4442 /*.......................................................................
4443 * This is an action function which deletes character(s) under the
4444 * cursor and moves the cursor back one character.
4446 static KT_KEY_FN(gl_backward_delete_char
)
4449 * Restrict the deletion count to the number of characters that
4450 * precede the insertion point.
4452 if(count
> gl
->buff_curpos
- gl
->insert_curpos
)
4453 count
= gl
->buff_curpos
- gl
->insert_curpos
;
4455 * If in vi command mode, preserve the current line for potential
4458 gl_save_for_undo(gl
);
4459 return gl_cursor_left(gl
, count
, NULL
) ||
4460 gl_delete_chars(gl
, count
, gl
->vi
.command
);
4463 /*.......................................................................
4464 * Starting from the cursor position delete to the specified column.
4466 static KT_KEY_FN(gl_delete_to_column
)
4468 if (--count
>= gl
->buff_curpos
)
4469 return gl_forward_delete_char(gl
, count
- gl
->buff_curpos
, NULL
);
4471 return gl_backward_delete_char(gl
, gl
->buff_curpos
- count
, NULL
);
4474 /*.......................................................................
4475 * Starting from the cursor position delete characters to a matching
4478 static KT_KEY_FN(gl_delete_to_parenthesis
)
4480 int curpos
= gl_index_of_matching_paren(gl
);
4482 gl_save_for_undo(gl
);
4483 if(curpos
>= gl
->buff_curpos
)
4484 return gl_forward_delete_char(gl
, curpos
- gl
->buff_curpos
+ 1, NULL
);
4486 return gl_backward_delete_char(gl
, ++gl
->buff_curpos
- curpos
+ 1, NULL
);
4491 /*.......................................................................
4492 * This is an action function which deletes from the cursor to the end
4493 * of the word that the cursor is either in or precedes.
4495 static KT_KEY_FN(gl_forward_delete_word
)
4498 * If in vi command mode, preserve the current line for potential
4501 gl_save_for_undo(gl
);
4503 * In emacs mode delete to the end of the word. In vi mode delete to the
4504 * start of the net word.
4506 if(gl
->editor
== GL_EMACS_MODE
) {
4507 return gl_delete_chars(gl
,
4508 gl_nth_word_end_forward(gl
,count
) - gl
->buff_curpos
+ 1, 1);
4510 return gl_delete_chars(gl
,
4511 gl_nth_word_start_forward(gl
,count
) - gl
->buff_curpos
,
4516 /*.......................................................................
4517 * This is an action function which deletes the word that precedes the
4520 static KT_KEY_FN(gl_backward_delete_word
)
4523 * Keep a record of the current cursor position.
4525 int buff_curpos
= gl
->buff_curpos
;
4527 * If in vi command mode, preserve the current line for potential
4530 gl_save_for_undo(gl
);
4532 * Move back 'count' words.
4534 if(gl_backward_word(gl
, count
, NULL
))
4537 * Delete from the new cursor position to the original one.
4539 return gl_delete_chars(gl
, buff_curpos
- gl
->buff_curpos
,
4540 gl
->editor
== GL_EMACS_MODE
|| gl
->vi
.command
);
4543 /*.......................................................................
4544 * Searching in a given direction, delete to the count'th
4545 * instance of a specified or queried character, in the input line.
4548 * gl GetLine * The getline resource object.
4549 * count int The number of times to search.
4550 * c char The character to be searched for, or '\0' if
4551 * the character should be read from the user.
4552 * forward int True if searching forward.
4553 * onto int True if the search should end on top of the
4554 * character, false if the search should stop
4555 * one character before the character in the
4556 * specified search direction.
4557 * change int If true, this function is being called upon
4558 * to do a vi change command, in which case the
4559 * user will be left in insert mode after the
4562 * return int 0 - OK.
4565 static int gl_delete_find(GetLine
*gl
, int count
, char c
, int forward
,
4566 int onto
, int change
)
4569 * Search for the character, and abort the deletion if not found.
4571 int pos
= gl_find_char(gl
, count
, forward
, onto
, c
);
4575 * If in vi command mode, preserve the current line for potential
4578 gl_save_for_undo(gl
);
4580 * Allow the cursor to be at the end of the line if this is a change
4586 * Delete the appropriate span of characters.
4589 if(gl_delete_chars(gl
, pos
- gl
->buff_curpos
+ 1, 1))
4592 int buff_curpos
= gl
->buff_curpos
;
4593 if(gl_place_cursor(gl
, pos
) ||
4594 gl_delete_chars(gl
, buff_curpos
- gl
->buff_curpos
, 1))
4598 * If this is a change operation, switch the insert mode.
4600 if(change
&& gl_vi_insert(gl
, 0, NULL
))
4605 /*.......................................................................
4606 * This is an action function which deletes forward from the cursor up to and
4607 * including a specified character.
4609 static KT_KEY_FN(gl_forward_delete_find
)
4611 return gl_delete_find(gl
, count
, '\0', 1, 1, 0);
4614 /*.......................................................................
4615 * This is an action function which deletes backward from the cursor back to
4616 * and including a specified character.
4618 static KT_KEY_FN(gl_backward_delete_find
)
4620 return gl_delete_find(gl
, count
, '\0', 0, 1, 0);
4623 /*.......................................................................
4624 * This is an action function which deletes forward from the cursor up to but
4625 * not including a specified character.
4627 static KT_KEY_FN(gl_forward_delete_to
)
4629 return gl_delete_find(gl
, count
, '\0', 1, 0, 0);
4632 /*.......................................................................
4633 * This is an action function which deletes backward from the cursor back to
4634 * but not including a specified character.
4636 static KT_KEY_FN(gl_backward_delete_to
)
4638 return gl_delete_find(gl
, count
, '\0', 0, 0, 0);
4641 /*.......................................................................
4642 * This is an action function which deletes to a character specified by a
4645 static KT_KEY_FN(gl_delete_refind
)
4647 return gl_delete_find(gl
, count
, gl
->vi
.find_char
, gl
->vi
.find_forward
,
4648 gl
->vi
.find_onto
, 0);
4651 /*.......................................................................
4652 * This is an action function which deletes to a character specified by a
4653 * previous search, but in the opposite direction.
4655 static KT_KEY_FN(gl_delete_invert_refind
)
4657 return gl_delete_find(gl
, count
, gl
->vi
.find_char
,
4658 !gl
->vi
.find_forward
, gl
->vi
.find_onto
, 0);
4661 /*.......................................................................
4662 * This is an action function which converts the characters in the word
4663 * following the cursor to upper case.
4665 static KT_KEY_FN(gl_upcase_word
)
4668 * Locate the count'th word ending after the cursor.
4670 int last
= gl_nth_word_end_forward(gl
, count
);
4672 * If in vi command mode, preserve the current line for potential
4675 gl_save_for_undo(gl
);
4677 * Upcase characters from the current cursor position to 'last'.
4679 while(gl
->buff_curpos
<= last
) {
4680 char *cptr
= gl
->line
+ gl
->buff_curpos
;
4682 * Convert the character to upper case?
4684 if(islower((int)(unsigned char) *cptr
))
4685 gl_buffer_char(gl
, toupper((int) *cptr
), gl
->buff_curpos
);
4688 * Write the possibly modified character back. Note that for non-modified
4689 * characters we want to do this as well, so as to advance the cursor.
4691 if(gl_print_char(gl
, *cptr
, cptr
[1]))
4694 return gl_place_cursor(gl
, gl
->buff_curpos
); /* bounds check */
4697 /*.......................................................................
4698 * This is an action function which converts the characters in the word
4699 * following the cursor to lower case.
4701 static KT_KEY_FN(gl_downcase_word
)
4704 * Locate the count'th word ending after the cursor.
4706 int last
= gl_nth_word_end_forward(gl
, count
);
4708 * If in vi command mode, preserve the current line for potential
4711 gl_save_for_undo(gl
);
4713 * Upcase characters from the current cursor position to 'last'.
4715 while(gl
->buff_curpos
<= last
) {
4716 char *cptr
= gl
->line
+ gl
->buff_curpos
;
4718 * Convert the character to upper case?
4720 if(isupper((int)(unsigned char) *cptr
))
4721 gl_buffer_char(gl
, tolower((int) *cptr
), gl
->buff_curpos
);
4724 * Write the possibly modified character back. Note that for non-modified
4725 * characters we want to do this as well, so as to advance the cursor.
4727 if(gl_print_char(gl
, *cptr
, cptr
[1]))
4730 return gl_place_cursor(gl
, gl
->buff_curpos
); /* bounds check */
4733 /*.......................................................................
4734 * This is an action function which converts the first character of the
4735 * following word to upper case, in order to capitalize the word, and
4736 * leaves the cursor at the end of the word.
4738 static KT_KEY_FN(gl_capitalize_word
)
4740 char *cptr
; /* &gl->line[gl->buff_curpos] */
4741 int first
; /* True for the first letter of the word */
4744 * Keep a record of the current insert mode and the cursor position.
4746 int insert
= gl
->insert
;
4748 * If in vi command mode, preserve the current line for potential
4751 gl_save_for_undo(gl
);
4753 * We want to overwrite the modified word.
4757 * Capitalize 'count' words.
4759 for(i
=0; i
<count
&& gl
->buff_curpos
< gl
->ntotal
; i
++) {
4760 int pos
= gl
->buff_curpos
;
4762 * If we are not already within a word, skip to the start of the word.
4764 for(cptr
= gl
->line
+ pos
; pos
<gl
->ntotal
&& !gl_is_word_char((int) *cptr
);
4768 * Move the cursor to the new position.
4770 if(gl_place_cursor(gl
, pos
))
4773 * While searching for the end of the word, change lower case letters
4776 for(first
=1; gl
->buff_curpos
<gl
->ntotal
&& gl_is_word_char((int) *cptr
);
4777 gl
->buff_curpos
++, cptr
++) {
4779 * Convert the character to upper case?
4782 if(islower((int)(unsigned char) *cptr
))
4783 gl_buffer_char(gl
, toupper((int) *cptr
), cptr
- gl
->line
);
4785 if(isupper((int)(unsigned char) *cptr
))
4786 gl_buffer_char(gl
, tolower((int) *cptr
), cptr
- gl
->line
);
4790 * Write the possibly modified character back. Note that for non-modified
4791 * characters we want to do this as well, so as to advance the cursor.
4793 if(gl_print_char(gl
, *cptr
, cptr
[1]))
4798 * Restore the insertion mode.
4800 gl
->insert
= insert
;
4801 return gl_place_cursor(gl
, gl
->buff_curpos
); /* bounds check */
4804 /*.......................................................................
4805 * This is an action function which redraws the current line.
4807 static KT_KEY_FN(gl_redisplay
)
4810 * Keep a record of the current cursor position.
4812 int buff_curpos
= gl
->buff_curpos
;
4814 * Do nothing if there is no line to be redisplayed.
4819 * Erase the current input line.
4821 if(gl_erase_line(gl
))
4824 * Display the current prompt.
4826 if(gl_display_prompt(gl
))
4829 * Render the part of the line that the user has typed in so far.
4831 if(gl_print_string(gl
, gl
->line
, '\0'))
4834 * Restore the cursor position.
4836 if(gl_place_cursor(gl
, buff_curpos
))
4839 * Mark the redisplay operation as having been completed.
4843 * Flush the redisplayed line to the terminal.
4845 return gl_flush_output(gl
);
4848 /*.......................................................................
4849 * This is an action function which clears the display and redraws the
4850 * input line from the home position.
4852 static KT_KEY_FN(gl_clear_screen
)
4855 * Home the cursor and clear from there to the end of the display.
4857 if(gl_print_control_sequence(gl
, gl
->nline
, gl
->home
) ||
4858 gl_print_control_sequence(gl
, gl
->nline
, gl
->clear_eod
))
4861 * The input line is no longer displayed.
4865 * Arrange for the input line to be redisplayed.
4867 gl_queue_redisplay(gl
);
4871 /*.......................................................................
4872 * This is an action function which swaps the character under the cursor
4873 * with the character to the left of the cursor.
4875 static KT_KEY_FN(gl_transpose_chars
)
4877 char from
[3]; /* The original string of 2 characters */
4878 char swap
[3]; /* The swapped string of two characters */
4880 * If we are at the beginning or end of the line, there aren't two
4881 * characters to swap.
4883 if(gl
->buff_curpos
< 1 || gl
->buff_curpos
>= gl
->ntotal
)
4886 * If in vi command mode, preserve the current line for potential
4889 gl_save_for_undo(gl
);
4891 * Get the original and swapped strings of the two characters.
4893 from
[0] = gl
->line
[gl
->buff_curpos
- 1];
4894 from
[1] = gl
->line
[gl
->buff_curpos
];
4896 swap
[0] = gl
->line
[gl
->buff_curpos
];
4897 swap
[1] = gl
->line
[gl
->buff_curpos
- 1];
4900 * Move the cursor to the start of the two characters.
4902 if(gl_place_cursor(gl
, gl
->buff_curpos
-1))
4905 * Swap the two characters in the buffer.
4907 gl_buffer_char(gl
, swap
[0], gl
->buff_curpos
);
4908 gl_buffer_char(gl
, swap
[1], gl
->buff_curpos
+1);
4910 * If the sum of the displayed width of the two characters
4911 * in their current and final positions is the same, swapping can
4912 * be done by just overwriting with the two swapped characters.
4914 if(gl_displayed_string_width(gl
, from
, -1, gl
->term_curpos
) ==
4915 gl_displayed_string_width(gl
, swap
, -1, gl
->term_curpos
)) {
4916 int insert
= gl
->insert
;
4918 if(gl_print_char(gl
, swap
[0], swap
[1]) ||
4919 gl_print_char(gl
, swap
[1], gl
->line
[gl
->buff_curpos
+2]))
4921 gl
->insert
= insert
;
4923 * If the swapped substring has a different displayed size, we need to
4924 * redraw everything after the first of the characters.
4927 if(gl_print_string(gl
, gl
->line
+ gl
->buff_curpos
, '\0') ||
4928 gl_truncate_display(gl
))
4932 * Advance the cursor to the character after the swapped pair.
4934 return gl_place_cursor(gl
, gl
->buff_curpos
+ 2);
4937 /*.......................................................................
4938 * This is an action function which sets a mark at the current cursor
4941 static KT_KEY_FN(gl_set_mark
)
4943 gl
->buff_mark
= gl
->buff_curpos
;
4947 /*.......................................................................
4948 * This is an action function which swaps the mark location for the
4951 static KT_KEY_FN(gl_exchange_point_and_mark
)
4954 * Get the old mark position, and limit to the extent of the input
4957 int old_mark
= gl
->buff_mark
<= gl
->ntotal
? gl
->buff_mark
: gl
->ntotal
;
4959 * Make the current cursor position the new mark.
4961 gl
->buff_mark
= gl
->buff_curpos
;
4963 * Move the cursor to the old mark position.
4965 return gl_place_cursor(gl
, old_mark
);
4968 /*.......................................................................
4969 * This is an action function which deletes the characters between the
4970 * mark and the cursor, recording them in gl->cutbuf for later pasting.
4972 static KT_KEY_FN(gl_kill_region
)
4975 * If in vi command mode, preserve the current line for potential
4978 gl_save_for_undo(gl
);
4980 * Limit the mark to be within the line.
4982 if(gl
->buff_mark
> gl
->ntotal
)
4983 gl
->buff_mark
= gl
->ntotal
;
4985 * If there are no characters between the cursor and the mark, simply clear
4988 if(gl
->buff_mark
== gl
->buff_curpos
) {
4989 gl
->cutbuf
[0] = '\0';
4993 * If the mark is before the cursor, swap the cursor and the mark.
4995 if(gl
->buff_mark
< gl
->buff_curpos
&& gl_exchange_point_and_mark(gl
,1,NULL
))
4998 * Delete the characters.
5000 if(gl_delete_chars(gl
, gl
->buff_mark
- gl
->buff_curpos
, 1))
5003 * Make the mark the same as the cursor position.
5005 gl
->buff_mark
= gl
->buff_curpos
;
5009 /*.......................................................................
5010 * This is an action function which records the characters between the
5011 * mark and the cursor, in gl->cutbuf for later pasting.
5013 static KT_KEY_FN(gl_copy_region_as_kill
)
5015 int ca
, cb
; /* The indexes of the first and last characters in the region */
5016 int mark
; /* The position of the mark */
5018 * Get the position of the mark, limiting it to lie within the line.
5020 mark
= gl
->buff_mark
> gl
->ntotal
? gl
->ntotal
: gl
->buff_mark
;
5022 * If there are no characters between the cursor and the mark, clear
5025 if(mark
== gl
->buff_curpos
) {
5026 gl
->cutbuf
[0] = '\0';
5030 * Get the line indexes of the first and last characters in the region.
5032 if(mark
< gl
->buff_curpos
) {
5034 cb
= gl
->buff_curpos
- 1;
5036 ca
= gl
->buff_curpos
;
5040 * Copy the region to the cut buffer.
5042 memcpy(gl
->cutbuf
, gl
->line
+ ca
, cb
+ 1 - ca
);
5043 gl
->cutbuf
[cb
+ 1 - ca
] = '\0';
5047 /*.......................................................................
5048 * This is an action function which inserts the contents of the cut
5049 * buffer at the current cursor location.
5051 static KT_KEY_FN(gl_yank
)
5055 * Set the mark at the current location.
5057 gl
->buff_mark
= gl
->buff_curpos
;
5059 * Do nothing else if the cut buffer is empty.
5061 if(gl
->cutbuf
[0] == '\0')
5062 return gl_ring_bell(gl
, 1, NULL
);
5064 * If in vi command mode, preserve the current line for potential
5067 gl_save_for_undo(gl
);
5069 * Insert the string count times.
5071 for(i
=0; i
<count
; i
++) {
5072 if(gl_add_string_to_line(gl
, gl
->cutbuf
))
5076 * gl_add_string_to_line() leaves the cursor after the last character that
5077 * was pasted, whereas vi leaves the cursor over the last character pasted.
5079 if(gl
->editor
== GL_VI_MODE
&& gl_cursor_left(gl
, 1, NULL
))
5084 /*.......................................................................
5085 * This is an action function which inserts the contents of the cut
5086 * buffer one character beyond the current cursor location.
5088 static KT_KEY_FN(gl_append_yank
)
5090 int was_command
= gl
->vi
.command
;
5093 * If the cut buffer is empty, ring the terminal bell.
5095 if(gl
->cutbuf
[0] == '\0')
5096 return gl_ring_bell(gl
, 1, NULL
);
5098 * Set the mark at the current location + 1.
5100 gl
->buff_mark
= gl
->buff_curpos
+ 1;
5102 * If in vi command mode, preserve the current line for potential
5105 gl_save_for_undo(gl
);
5107 * Arrange to paste the text in insert mode after the current character.
5109 if(gl_vi_append(gl
, 0, NULL
))
5112 * Insert the string count times.
5114 for(i
=0; i
<count
; i
++) {
5115 if(gl_add_string_to_line(gl
, gl
->cutbuf
))
5119 * Switch back to command mode if necessary.
5122 gl_vi_command_mode(gl
);
5126 /*.......................................................................
5127 * Attempt to ask the terminal for its current size. On systems that
5128 * don't support the TIOCWINSZ ioctl() for querying the terminal size,
5129 * the current values of gl->ncolumn and gl->nrow are returned.
5132 * gl GetLine * The resource object of gl_get_line().
5134 * ncolumn int * The number of columns will be assigned to *ncolumn.
5135 * nline int * The number of lines will be assigned to *nline.
5137 static void gl_query_size(GetLine
*gl
, int *ncolumn
, int *nline
)
5141 * Query the new terminal window size. Ignore invalid responses.
5143 struct winsize size
;
5144 if(ioctl(gl
->output_fd
, TIOCGWINSZ
, &size
) == 0 &&
5145 size
.ws_row
> 0 && size
.ws_col
> 0) {
5146 *ncolumn
= size
.ws_col
;
5147 *nline
= size
.ws_row
;
5152 * Return the existing values.
5154 *ncolumn
= gl
->ncolumn
;
5159 /*.......................................................................
5160 * Query the size of the terminal, and if it has changed, redraw the
5161 * current input line accordingly.
5164 * gl GetLine * The resource object of gl_get_line().
5166 * return int 0 - OK.
5169 static int _gl_update_size(GetLine
*gl
)
5171 int ncolumn
, nline
; /* The new size of the terminal */
5173 * Query the new terminal window size.
5175 gl_query_size(gl
, &ncolumn
, &nline
);
5177 * Update gl and the displayed line to fit the new dimensions.
5179 return gl_handle_tty_resize(gl
, ncolumn
, nline
);
5182 /*.......................................................................
5183 * Redraw the current input line to account for a change in the terminal
5184 * size. Also install the new size in gl.
5187 * gl GetLine * The resource object of gl_get_line().
5188 * ncolumn int The new number of columns.
5189 * nline int The new number of lines.
5191 * return int 0 - OK.
5194 static int gl_handle_tty_resize(GetLine
*gl
, int ncolumn
, int nline
)
5197 * If the input device isn't a terminal, just record the new size.
5201 gl
->ncolumn
= ncolumn
;
5203 * Has the size actually changed?
5205 } else if(ncolumn
!= gl
->ncolumn
|| nline
!= gl
->nline
) {
5207 * If we are currently editing a line, erase it.
5209 if(gl_erase_line(gl
))
5212 * Update the recorded window size.
5215 gl
->ncolumn
= ncolumn
;
5217 * Arrange for the input line to be redrawn before the next character
5218 * is read from the terminal.
5220 gl_queue_redisplay(gl
);
5225 /*.......................................................................
5226 * This is the action function that recalls the previous line in the
5229 static KT_KEY_FN(gl_up_history
)
5232 * In vi mode, switch to command mode, since the user is very
5233 * likely to want to move around newly recalled lines.
5235 gl_vi_command_mode(gl
);
5237 * Forget any previous recall session.
5241 * Record the key sequence number of this search action.
5243 gl
->last_search
= gl
->keyseq_count
;
5245 * We don't want a search prefix for this function.
5247 if(_glh_search_prefix(gl
->glh
, gl
->line
, 0)) {
5248 _err_record_msg(gl
->err
, _glh_last_error(gl
->glh
), END_ERR_MSG
);
5252 * Recall the count'th next older line in the history list. If the first one
5253 * fails we can return since nothing has changed, otherwise we must continue
5254 * and update the line state.
5256 if(_glh_find_backwards(gl
->glh
, gl
->line
, gl
->linelen
+1) == NULL
)
5258 while(--count
&& _glh_find_backwards(gl
->glh
, gl
->line
, gl
->linelen
+1))
5261 * Accomodate the new contents of gl->line[].
5263 gl_update_buffer(gl
);
5265 * Arrange to have the cursor placed at the end of the new line.
5267 gl
->buff_curpos
= gl
->ntotal
;
5269 * Erase and display the new line.
5271 gl_queue_redisplay(gl
);
5275 /*.......................................................................
5276 * This is the action function that recalls the next line in the
5279 static KT_KEY_FN(gl_down_history
)
5282 * In vi mode, switch to command mode, since the user is very
5283 * likely to want to move around newly recalled lines.
5285 gl_vi_command_mode(gl
);
5287 * Record the key sequence number of this search action.
5289 gl
->last_search
= gl
->keyseq_count
;
5291 * If no search is currently in progress continue a previous recall
5292 * session from a previous entered line if possible.
5294 if(_glh_line_id(gl
->glh
, 0) == 0 && gl
->preload_id
) {
5295 _glh_recall_line(gl
->glh
, gl
->preload_id
, gl
->line
, gl
->linelen
+1);
5299 * We don't want a search prefix for this function.
5301 if(_glh_search_prefix(gl
->glh
, gl
->line
, 0)) {
5302 _err_record_msg(gl
->err
, _glh_last_error(gl
->glh
), END_ERR_MSG
);
5306 * Recall the count'th next newer line in the history list. If the first one
5307 * fails we can return since nothing has changed otherwise we must continue
5308 * and update the line state.
5310 if(_glh_find_forwards(gl
->glh
, gl
->line
, gl
->linelen
+1) == NULL
)
5312 while(--count
&& _glh_find_forwards(gl
->glh
, gl
->line
, gl
->linelen
+1))
5316 * Accomodate the new contents of gl->line[].
5318 gl_update_buffer(gl
);
5320 * Arrange to have the cursor placed at the end of the new line.
5322 gl
->buff_curpos
= gl
->ntotal
;
5324 * Erase and display the new line.
5326 gl_queue_redisplay(gl
);
5330 /*.......................................................................
5331 * This is the action function that recalls the previous line in the
5332 * history buffer whos prefix matches the characters that currently
5333 * precede the cursor. By setting count=-1, this can be used internally
5334 * to force searching for the prefix used in the last search.
5336 static KT_KEY_FN(gl_history_search_backward
)
5339 * In vi mode, switch to command mode, since the user is very
5340 * likely to want to move around newly recalled lines.
5342 gl_vi_command_mode(gl
);
5344 * Forget any previous recall session.
5348 * Record the key sequence number of this search action.
5350 gl
->last_search
= gl
->keyseq_count
;
5352 * If a prefix search isn't already in progress, replace the search
5353 * prefix to the string that precedes the cursor. In vi command mode
5354 * include the character that is under the cursor in the string. If
5355 * count<0 keep the previous search prefix regardless, so as to force
5356 * a repeat search even if the last command wasn't a history command.
5358 if(count
>= 0 && !_glh_search_active(gl
->glh
) &&
5359 _glh_search_prefix(gl
->glh
, gl
->line
, gl
->buff_curpos
+
5360 (gl
->editor
==GL_VI_MODE
&& gl
->ntotal
>0))) {
5361 _err_record_msg(gl
->err
, _glh_last_error(gl
->glh
), END_ERR_MSG
);
5365 * Search backwards for a match to the part of the line which precedes the
5368 if(_glh_find_backwards(gl
->glh
, gl
->line
, gl
->linelen
+1) == NULL
)
5371 * Accomodate the new contents of gl->line[].
5373 gl_update_buffer(gl
);
5375 * Arrange to have the cursor placed at the end of the new line.
5377 gl
->buff_curpos
= gl
->ntotal
;
5379 * Erase and display the new line.
5381 gl_queue_redisplay(gl
);
5385 /*.......................................................................
5386 * This is the action function that recalls the previous line in the
5387 * history buffer who's prefix matches that specified in an earlier call
5388 * to gl_history_search_backward() or gl_history_search_forward().
5390 static KT_KEY_FN(gl_history_re_search_backward
)
5392 return gl_history_search_backward(gl
, -1, NULL
);
5395 /*.......................................................................
5396 * This is the action function that recalls the next line in the
5397 * history buffer who's prefix matches that specified in the earlier call
5398 * to gl_history_search_backward) which started the history search.
5399 * By setting count=-1, this can be used internally to force searching
5400 * for the prefix used in the last search.
5402 static KT_KEY_FN(gl_history_search_forward
)
5405 * In vi mode, switch to command mode, since the user is very
5406 * likely to want to move around newly recalled lines.
5408 gl_vi_command_mode(gl
);
5410 * Record the key sequence number of this search action.
5412 gl
->last_search
= gl
->keyseq_count
;
5414 * If a prefix search isn't already in progress, replace the search
5415 * prefix to the string that precedes the cursor. In vi command mode
5416 * include the character that is under the cursor in the string. If
5417 * count<0 keep the previous search prefix regardless, so as to force
5418 * a repeat search even if the last command wasn't a history command.
5420 if(count
>= 0 && !_glh_search_active(gl
->glh
) &&
5421 _glh_search_prefix(gl
->glh
, gl
->line
, gl
->buff_curpos
+
5422 (gl
->editor
==GL_VI_MODE
&& gl
->ntotal
>0))) {
5423 _err_record_msg(gl
->err
, _glh_last_error(gl
->glh
), END_ERR_MSG
);
5427 * Search forwards for the next matching line.
5429 if(_glh_find_forwards(gl
->glh
, gl
->line
, gl
->linelen
+1) == NULL
)
5432 * Accomodate the new contents of gl->line[].
5434 gl_update_buffer(gl
);
5436 * Arrange for the cursor to be placed at the end of the new line.
5438 gl
->buff_curpos
= gl
->ntotal
;
5440 * Erase and display the new line.
5442 gl_queue_redisplay(gl
);
5446 /*.......................................................................
5447 * This is the action function that recalls the next line in the
5448 * history buffer who's prefix matches that specified in an earlier call
5449 * to gl_history_search_backward() or gl_history_search_forward().
5451 static KT_KEY_FN(gl_history_re_search_forward
)
5453 return gl_history_search_forward(gl
, -1, NULL
);
5456 #ifdef HIDE_FILE_SYSTEM
5457 /*.......................................................................
5458 * The following function is used as the default completion handler when
5459 * the filesystem is to be hidden. It simply reports no completions.
5461 static CPL_MATCH_FN(gl_no_completions
)
5467 /*.......................................................................
5468 * This is the tab completion function that completes the filename that
5469 * precedes the cursor position. Its callback data argument must be a
5470 * pointer to a GlCplCallback containing the completion callback function
5471 * and its callback data, or NULL to use the builtin filename completer.
5473 static KT_KEY_FN(gl_complete_word
)
5475 CplMatches
*matches
; /* The possible completions */
5476 int suffix_len
; /* The length of the completion extension */
5477 int cont_len
; /* The length of any continuation suffix */
5478 int nextra
; /* The number of characters being added to the */
5479 /* total length of the line. */
5480 int buff_pos
; /* The buffer index at which the completion is */
5481 /* to be inserted. */
5482 int waserr
= 0; /* True after errors */
5484 * Get the container of the completion callback and its callback data.
5486 GlCplCallback
*cb
= data
? (GlCplCallback
*) data
: &gl
->cplfn
;
5488 * In vi command mode, switch to append mode so that the character under
5489 * the cursor is included in the completion (otherwise people can't
5490 * complete at the end of the line).
5492 if(gl
->vi
.command
&& gl_vi_append(gl
, 0, NULL
))
5495 * Get the cursor position at which the completion is to be inserted.
5497 buff_pos
= gl
->buff_curpos
;
5499 * Perform the completion.
5501 matches
= cpl_complete_word(gl
->cpl
, gl
->line
, gl
->buff_curpos
, cb
->data
,
5504 * No matching completions?
5507 waserr
= gl_print_info(gl
, cpl_last_error(gl
->cpl
), GL_END_INFO
);
5509 * Are there any completions?
5511 } else if(matches
->nmatch
>= 1) {
5513 * If there any ambiguous matches, report them, starting on a new line.
5515 if(matches
->nmatch
> 1 && gl
->echo
) {
5516 if(_gl_normal_io(gl
) ||
5517 _cpl_output_completions(matches
, gl_write_fn
, gl
, gl
->ncolumn
))
5521 * Get the length of the suffix and any continuation suffix to add to it.
5523 suffix_len
= strlen(matches
->suffix
);
5524 cont_len
= strlen(matches
->cont_suffix
);
5526 * If there is an unambiguous match, and the continuation suffix ends in
5527 * a newline, strip that newline and arrange to have getline return
5528 * after this action function returns.
5530 if(matches
->nmatch
==1 && cont_len
> 0 &&
5531 matches
->cont_suffix
[cont_len
- 1] == '\n') {
5533 if(gl_newline(gl
, 1, NULL
))
5537 * Work out the number of characters that are to be added.
5539 nextra
= suffix_len
+ cont_len
;
5541 * Is there anything to be added?
5543 if(!waserr
&& nextra
) {
5545 * Will there be space for the expansion in the line buffer?
5547 if(gl
->ntotal
+ nextra
< gl
->linelen
) {
5549 * Make room to insert the filename extension.
5551 gl_make_gap_in_buffer(gl
, gl
->buff_curpos
, nextra
);
5553 * Insert the filename extension.
5555 gl_buffer_string(gl
, matches
->suffix
, suffix_len
, gl
->buff_curpos
);
5557 * Add the terminating characters.
5559 gl_buffer_string(gl
, matches
->cont_suffix
, cont_len
,
5560 gl
->buff_curpos
+ suffix_len
);
5562 * Place the cursor position at the end of the completion.
5564 gl
->buff_curpos
+= nextra
;
5566 * If we don't have to redisplay the whole line, redisplay the part
5567 * of the line which follows the original cursor position, and place
5568 * the cursor at the end of the completion.
5571 if(gl_truncate_display(gl
) ||
5572 gl_print_string(gl
, gl
->line
+ buff_pos
, '\0') ||
5573 gl_place_cursor(gl
, gl
->buff_curpos
))
5577 (void) gl_print_info(gl
,
5578 "Insufficient room in line for file completion.",
5585 * If any output had to be written to the terminal, then editing will
5586 * have been suspended, make sure that we are back in raw line editing
5587 * mode before returning.
5589 if(_gl_raw_io(gl
, 1))
5594 #ifndef HIDE_FILE_SYSTEM
5595 /*.......................................................................
5596 * This is the function that expands the filename that precedes the
5597 * cursor position. It expands ~user/ expressions, $envvar expressions,
5600 static KT_KEY_FN(gl_expand_filename
)
5602 char *start_path
; /* The pointer to the start of the pathname in */
5604 FileExpansion
*result
; /* The results of the filename expansion */
5605 int pathlen
; /* The length of the pathname being expanded */
5606 int length
; /* The number of characters needed to display the */
5607 /* expanded files. */
5608 int nextra
; /* The number of characters to be added */
5611 * In vi command mode, switch to append mode so that the character under
5612 * the cursor is included in the completion (otherwise people can't
5613 * complete at the end of the line).
5615 if(gl
->vi
.command
&& gl_vi_append(gl
, 0, NULL
))
5618 * Locate the start of the filename that precedes the cursor position.
5620 start_path
= _pu_start_of_path(gl
->line
, gl
->buff_curpos
);
5624 * Get the length of the string that is to be expanded.
5626 pathlen
= gl
->buff_curpos
- (start_path
- gl
->line
);
5628 * Attempt to expand it.
5630 result
= ef_expand_file(gl
->ef
, start_path
, pathlen
);
5632 * If there was an error, report the error on a new line.
5635 return gl_print_info(gl
, ef_last_error(gl
->ef
), GL_END_INFO
);
5637 * If no files matched, report this as well.
5639 if(result
->nfile
== 0 || !result
->exists
)
5640 return gl_print_info(gl
, "No files match.", GL_END_INFO
);
5642 * If in vi command mode, preserve the current line for potential use by
5645 gl_save_for_undo(gl
);
5647 * Work out how much space we will need to display all of the matching
5648 * filenames, taking account of the space that we need to place between
5649 * them, and the number of additional '\' characters needed to escape
5650 * spaces, tabs and backslash characters in the individual filenames.
5653 for(i
=0; i
<result
->nfile
; i
++) {
5654 char *file
= result
->files
[i
];
5658 case ' ': case '\t': case '\\': case '*': case '?': case '[':
5659 length
++; /* Count extra backslash characters */
5661 length
++; /* Count the character itself */
5663 length
++; /* Count the space that follows each filename */
5666 * Work out the number of characters that are to be added.
5668 nextra
= length
- pathlen
;
5670 * Will there be space for the expansion in the line buffer?
5672 if(gl
->ntotal
+ nextra
>= gl
->linelen
) {
5673 return gl_print_info(gl
, "Insufficient room in line for file expansion.",
5677 * Do we need to move the part of the line that followed the unexpanded
5681 gl_make_gap_in_buffer(gl
, gl
->buff_curpos
, nextra
);
5682 } else if(nextra
< 0) {
5683 gl
->buff_curpos
+= nextra
;
5684 gl_remove_from_buffer(gl
, gl
->buff_curpos
, -nextra
);
5687 * Insert the filenames, separated by spaces, and with internal spaces,
5688 * tabs and backslashes escaped with backslashes.
5690 for(i
=0,j
=start_path
- gl
->line
; i
<result
->nfile
; i
++) {
5691 char *file
= result
->files
[i
];
5695 case ' ': case '\t': case '\\': case '*': case '?': case '[':
5696 gl_buffer_char(gl
, '\\', j
++);
5698 gl_buffer_char(gl
, c
, j
++);
5700 gl_buffer_char(gl
, ' ', j
++);
5704 * Redisplay the part of the line which follows the start of
5705 * the original filename.
5707 if(gl_place_cursor(gl
, start_path
- gl
->line
) ||
5708 gl_truncate_display(gl
) ||
5709 gl_print_string(gl
, start_path
, start_path
[length
]))
5712 * Move the cursor to the end of the expansion.
5714 return gl_place_cursor(gl
, (start_path
- gl
->line
) + length
);
5718 #ifndef HIDE_FILE_SYSTEM
5719 /*.......................................................................
5720 * This is the action function that lists glob expansions of the
5721 * filename that precedes the cursor position. It expands ~user/
5722 * expressions, $envvar expressions, and wildcards.
5724 static KT_KEY_FN(gl_list_glob
)
5726 char *start_path
; /* The pointer to the start of the pathname in */
5728 FileExpansion
*result
; /* The results of the filename expansion */
5729 int pathlen
; /* The length of the pathname being expanded */
5731 * Locate the start of the filename that precedes the cursor position.
5733 start_path
= _pu_start_of_path(gl
->line
, gl
->buff_curpos
);
5737 * Get the length of the string that is to be expanded.
5739 pathlen
= gl
->buff_curpos
- (start_path
- gl
->line
);
5741 * Attempt to expand it.
5743 result
= ef_expand_file(gl
->ef
, start_path
, pathlen
);
5745 * If there was an error, report it.
5748 return gl_print_info(gl
, ef_last_error(gl
->ef
), GL_END_INFO
);
5750 * If no files matched, report this as well.
5752 } else if(result
->nfile
== 0 || !result
->exists
) {
5753 return gl_print_info(gl
, "No files match.", GL_END_INFO
);
5755 * List the matching expansions.
5757 } else if(gl
->echo
) {
5758 if(gl_start_newline(gl
, 1) ||
5759 _ef_output_expansions(result
, gl_write_fn
, gl
, gl
->ncolumn
))
5761 gl_queue_redisplay(gl
);
5767 /*.......................................................................
5768 * Return non-zero if a character should be considered a part of a word.
5771 * c int The character to be tested.
5773 * return int True if the character should be considered part of a word.
5775 static int gl_is_word_char(int c
)
5777 return isalnum((int)(unsigned char)c
) || strchr(GL_WORD_CHARS
, c
) != NULL
;
5780 /*.......................................................................
5781 * Override the builtin file-completion callback that is bound to the
5782 * "complete_word" action function.
5785 * gl GetLine * The resource object of the command-line input
5787 * data void * This is passed to match_fn() whenever it is
5788 * called. It could, for example, point to a
5789 * symbol table where match_fn() could look
5790 * for possible completions.
5791 * match_fn CplMatchFn * The function that will identify the prefix
5792 * to be completed from the input line, and
5793 * report matching symbols.
5795 * return int 0 - OK.
5798 int gl_customize_completion(GetLine
*gl
, void *data
, CplMatchFn
*match_fn
)
5800 sigset_t oldset
; /* The signals that were blocked on entry to this function */
5802 * Check the arguments.
5804 if(!gl
|| !match_fn
) {
5806 _err_record_msg(gl
->err
, "NULL argument", END_ERR_MSG
);
5811 * Temporarily block all signals.
5813 gl_mask_signals(gl
, &oldset
);
5815 * Record the new completion function and its callback data.
5817 gl
->cplfn
.fn
= match_fn
;
5818 gl
->cplfn
.data
= data
;
5820 * Restore the process signal mask before returning.
5822 gl_unmask_signals(gl
, &oldset
);
5826 /*.......................................................................
5827 * Change the terminal (or stream) that getline interacts with.
5830 * gl GetLine * The resource object of the command-line input
5832 * input_fp FILE * The stdio stream to read from.
5833 * output_fp FILE * The stdio stream to write to.
5834 * term char * The terminal type. This can be NULL if
5835 * either or both of input_fp and output_fp don't
5836 * refer to a terminal. Otherwise it should refer
5837 * to an entry in the terminal information database.
5839 * return int 0 - OK.
5842 int gl_change_terminal(GetLine
*gl
, FILE *input_fp
, FILE *output_fp
,
5845 sigset_t oldset
; /* The signals that were blocked on entry to this function */
5846 int status
; /* The return status of _gl_change_terminal() */
5848 * Check the arguments.
5855 * Block all signals.
5857 if(gl_mask_signals(gl
, &oldset
))
5860 * Execute the private body of the function while signals are blocked.
5862 status
= _gl_change_terminal(gl
, input_fp
, output_fp
, term
);
5864 * Restore the process signal mask.
5866 gl_unmask_signals(gl
, &oldset
);
5870 /*.......................................................................
5871 * This is the private body of the gl_change_terminal() function. It
5872 * assumes that the caller has checked its arguments and blocked the
5873 * delivery of signals.
5875 static int _gl_change_terminal(GetLine
*gl
, FILE *input_fp
, FILE *output_fp
,
5878 int is_term
= 0; /* True if both input_fd and output_fd are associated */
5879 /* with a terminal. */
5881 * Require that input_fp and output_fp both be valid.
5883 if(!input_fp
|| !output_fp
) {
5884 gl_print_info(gl
, "Can't change terminal. Bad input/output stream(s).",
5889 * Are we displacing an existing terminal (as opposed to setting the
5890 * initial terminal)?
5892 if(gl
->input_fd
>= 0) {
5894 * Make sure to leave the previous terminal in a usable state.
5896 if(_gl_normal_io(gl
))
5899 * Remove the displaced terminal from the list of fds to watch.
5902 FD_CLR(gl
->input_fd
, &gl
->rfds
);
5906 * Record the file descriptors and streams.
5908 gl
->input_fp
= input_fp
;
5909 gl
->input_fd
= fileno(input_fp
);
5910 gl
->output_fp
= output_fp
;
5911 gl
->output_fd
= fileno(output_fp
);
5913 * If needed, expand the record of the maximum file-descriptor that might
5914 * need to be monitored with select().
5917 if(gl
->input_fd
> gl
->max_fd
)
5918 gl
->max_fd
= gl
->input_fd
;
5921 * Disable terminal interaction until we have enough info to interact
5922 * with the terminal.
5926 * For terminal editing, we need both output_fd and input_fd to refer to
5927 * a terminal. While we can't verify that they both point to the same
5928 * terminal, we can verify that they point to terminals.
5930 is_term
= isatty(gl
->input_fd
) && isatty(gl
->output_fd
);
5932 * If we are interacting with a terminal and no terminal type has been
5933 * specified, treat it as a generic ANSI terminal.
5935 if(is_term
&& !term
)
5938 * Make a copy of the terminal type string.
5940 if(term
!= gl
->term
) {
5942 * Delete any old terminal type string.
5949 * Make a copy of the new terminal-type string, if any.
5952 size_t termsz
= strlen(term
)+1;
5954 gl
->term
= (char *) malloc(termsz
);
5956 strlcpy(gl
->term
, term
, termsz
);
5960 * Clear any terminal-specific key bindings that were taken from the
5961 * settings of the last terminal.
5963 _kt_clear_bindings(gl
->bindings
, KTB_TERM
);
5965 * If we have a terminal install new bindings for it.
5969 * Get the current settings of the terminal.
5971 if(tcgetattr(gl
->input_fd
, &gl
->oldattr
)) {
5972 _err_record_msg(gl
->err
, "tcgetattr error", END_ERR_MSG
);
5976 * If we don't set this now, gl_control_strings() won't know
5977 * that it is talking to a terminal.
5981 * Lookup the terminal control string and size information.
5983 if(gl_control_strings(gl
, term
)) {
5988 * Bind terminal-specific keys.
5990 if(gl_bind_terminal_keys(gl
))
5994 * Assume that the caller has given us a terminal in a sane state.
5996 gl
->io_mode
= GL_NORMAL_MODE
;
5998 * Switch into the currently configured I/O mode.
6000 if(_gl_io_mode(gl
, gl
->io_mode
))
6005 /*.......................................................................
6006 * Set up terminal-specific key bindings.
6009 * gl GetLine * The resource object of the command-line input
6012 * return int 0 - OK.
6015 static int gl_bind_terminal_keys(GetLine
*gl
)
6018 * Install key-bindings for the special terminal characters.
6020 if(gl_bind_control_char(gl
, KTB_TERM
, gl
->oldattr
.c_cc
[VINTR
],
6021 "user-interrupt") ||
6022 gl_bind_control_char(gl
, KTB_TERM
, gl
->oldattr
.c_cc
[VQUIT
], "abort") ||
6023 gl_bind_control_char(gl
, KTB_TERM
, gl
->oldattr
.c_cc
[VSUSP
], "suspend"))
6026 * In vi-mode, arrange for the above characters to be seen in command
6029 if(gl
->editor
== GL_VI_MODE
) {
6030 if(gl_bind_control_char(gl
, KTB_TERM
, MAKE_META(gl
->oldattr
.c_cc
[VINTR
]),
6031 "user-interrupt") ||
6032 gl_bind_control_char(gl
, KTB_TERM
, MAKE_META(gl
->oldattr
.c_cc
[VQUIT
]),
6034 gl_bind_control_char(gl
, KTB_TERM
, MAKE_META(gl
->oldattr
.c_cc
[VSUSP
]),
6039 * Non-universal special keys.
6042 if(gl_bind_control_char(gl
, KTB_TERM
, gl
->oldattr
.c_cc
[VLNEXT
],
6046 if(_kt_set_keybinding(gl
->bindings
, KTB_TERM
, "^V", "literal-next")) {
6047 _err_record_msg(gl
->err
, _kt_last_error(gl
->bindings
), END_ERR_MSG
);
6052 * Bind action functions to the terminal-specific arrow keys
6053 * looked up by gl_control_strings().
6055 if(_gl_bind_arrow_keys(gl
))
6060 /*.......................................................................
6061 * This function is normally bound to control-D. When it is invoked within
6062 * a line it deletes the character which follows the cursor. When invoked
6063 * at the end of the line it lists possible file completions, and when
6064 * invoked on an empty line it causes gl_get_line() to return EOF. This
6065 * function emulates the one that is normally bound to control-D by tcsh.
6067 static KT_KEY_FN(gl_del_char_or_list_or_eof
)
6070 * If we have an empty line arrange to return EOF.
6072 if(gl
->ntotal
< 1) {
6073 gl_record_status(gl
, GLR_EOF
, 0);
6076 * If we are at the end of the line list possible completions.
6078 } else if(gl
->buff_curpos
>= gl
->ntotal
) {
6079 return gl_list_completions(gl
, 1, NULL
);
6081 * Within the line delete the character that follows the cursor.
6085 * If in vi command mode, first preserve the current line for potential use
6088 gl_save_for_undo(gl
);
6090 * Delete 'count' characters.
6092 return gl_forward_delete_char(gl
, count
, NULL
);
6096 /*.......................................................................
6097 * This function is normally bound to control-D in vi mode. When it is
6098 * invoked within a line it lists possible file completions, and when
6099 * invoked on an empty line it causes gl_get_line() to return EOF. This
6100 * function emulates the one that is normally bound to control-D by tcsh.
6102 static KT_KEY_FN(gl_list_or_eof
)
6105 * If we have an empty line arrange to return EOF.
6107 if(gl
->ntotal
< 1) {
6108 gl_record_status(gl
, GLR_EOF
, 0);
6111 * Otherwise list possible completions.
6114 return gl_list_completions(gl
, 1, NULL
);
6118 /*.......................................................................
6119 * List possible completions of the word that precedes the cursor. The
6120 * callback data argument must either be NULL to select the default
6121 * file completion callback, or be a GlCplCallback object containing the
6122 * completion callback function to call.
6124 static KT_KEY_FN(gl_list_completions
)
6126 int waserr
= 0; /* True after errors */
6128 * Get the container of the completion callback and its callback data.
6130 GlCplCallback
*cb
= data
? (GlCplCallback
*) data
: &gl
->cplfn
;
6132 * Get the list of possible completions.
6134 CplMatches
*matches
= cpl_complete_word(gl
->cpl
, gl
->line
, gl
->buff_curpos
,
6137 * No matching completions?
6140 waserr
= gl_print_info(gl
, cpl_last_error(gl
->cpl
), GL_END_INFO
);
6144 } else if(matches
->nmatch
> 0 && gl
->echo
) {
6145 if(_gl_normal_io(gl
) ||
6146 _cpl_output_completions(matches
, gl_write_fn
, gl
, gl
->ncolumn
))
6150 * If any output had to be written to the terminal, then editing will
6151 * have been suspended, make sure that we are back in raw line editing
6152 * mode before returning.
6154 if(_gl_raw_io(gl
, 1))
6159 /*.......................................................................
6160 * Where the user has used the symbolic arrow-key names to specify
6161 * arrow key bindings, bind the specified action functions to the default
6162 * and terminal specific arrow key sequences.
6165 * gl GetLine * The getline resource object.
6167 * return int 0 - OK.
6170 static int _gl_bind_arrow_keys(GetLine
*gl
)
6173 * Process each of the arrow keys.
6175 if(_gl_rebind_arrow_key(gl
, "up", gl
->u_arrow
, "^[[A", "^[OA") ||
6176 _gl_rebind_arrow_key(gl
, "down", gl
->d_arrow
, "^[[B", "^[OB") ||
6177 _gl_rebind_arrow_key(gl
, "left", gl
->l_arrow
, "^[[D", "^[OD") ||
6178 _gl_rebind_arrow_key(gl
, "right", gl
->r_arrow
, "^[[C", "^[OC"))
6183 /*.......................................................................
6184 * Lookup the action function of a symbolic arrow-key binding, and bind
6185 * it to the terminal-specific and default arrow-key sequences. Note that
6186 * we don't trust the terminal-specified key sequences to be correct.
6187 * The main reason for this is that on some machines the xterm terminfo
6188 * entry is for hardware X-terminals, rather than xterm terminal emulators
6189 * and the two terminal types emit different character sequences when the
6190 * their cursor keys are pressed. As a result we also supply a couple
6191 * of default key sequences.
6194 * gl GetLine * The resource object of gl_get_line().
6195 * name char * The symbolic name of the arrow key.
6196 * term_seq char * The terminal-specific arrow-key sequence.
6197 * def_seq1 char * The first default arrow-key sequence.
6198 * def_seq2 char * The second arrow-key sequence.
6200 * return int 0 - OK.
6203 static int _gl_rebind_arrow_key(GetLine
*gl
, const char *name
,
6204 const char *term_seq
, const char *def_seq1
,
6205 const char *def_seq2
)
6207 KeySym
*keysym
; /* The binding-table entry matching the arrow-key name */
6208 int nsym
; /* The number of ambiguous matches */
6210 * Lookup the key binding for the symbolic name of the arrow key. This
6211 * will either be the default action, or a user provided one.
6213 if(_kt_lookup_keybinding(gl
->bindings
, name
, strlen(name
), &keysym
, &nsym
)
6214 == KT_EXACT_MATCH
) {
6216 * Get the action function.
6218 KtAction
*action
= keysym
->actions
+ keysym
->binder
;
6219 KtKeyFn
*fn
= action
->fn
;
6220 void *data
= action
->data
;
6222 * Bind this to each of the specified key sequences.
6225 _kt_set_keyfn(gl
->bindings
, KTB_TERM
, term_seq
, fn
, data
)) ||
6227 _kt_set_keyfn(gl
->bindings
, KTB_NORM
, def_seq1
, fn
, data
)) ||
6229 _kt_set_keyfn(gl
->bindings
, KTB_NORM
, def_seq2
, fn
, data
))) {
6230 _err_record_msg(gl
->err
, _kt_last_error(gl
->bindings
), END_ERR_MSG
);
6237 /*.......................................................................
6238 * Read getline configuration information from a given file.
6241 * gl GetLine * The getline resource object.
6242 * filename const char * The name of the file to read configuration
6243 * information from. The contents of this file
6244 * are as described in the gl_get_line(3) man
6245 * page for the default ~/.teclarc configuration
6247 * who KtBinder Who bindings are to be installed for.
6249 * return int 0 - OK.
6250 * 1 - Irrecoverable error.
6252 static int _gl_read_config_file(GetLine
*gl
, const char *filename
, KtBinder who
)
6255 * If filesystem access is to be excluded, configuration files can't
6258 #ifdef WITHOUT_FILE_SYSTEM
6259 _err_record_msg(gl
->err
,
6260 "Can't read configuration files without filesystem access",
6265 FileExpansion
*expansion
; /* The expansion of the filename */
6266 FILE *fp
; /* The opened file */
6267 int waserr
= 0; /* True if an error occurred while reading */
6268 int lineno
= 1; /* The line number being processed */
6270 * Check the arguments.
6272 if(!gl
|| !filename
) {
6274 _err_record_msg(gl
->err
, "NULL argument(s)", END_ERR_MSG
);
6279 * Expand the filename.
6281 expansion
= ef_expand_file(gl
->ef
, filename
, -1);
6283 gl_print_info(gl
, "Unable to expand ", filename
, " (",
6284 ef_last_error(gl
->ef
), ").", GL_END_INFO
);
6288 * Attempt to open the file.
6290 fp
= fopen(expansion
->files
[0], "r");
6292 * It isn't an error for there to be no configuration file.
6297 * Parse the contents of the file.
6299 while(!waserr
&& !feof(fp
))
6300 waserr
= _gl_parse_config_line(gl
, fp
, glc_file_getc
, filename
, who
,
6303 * Bind action functions to the terminal-specific arrow keys.
6305 if(_gl_bind_arrow_keys(gl
))
6315 /*.......................................................................
6316 * Read GetLine configuration information from a string. The contents of
6317 * the string are the same as those described in the gl_get_line(3)
6318 * man page for the contents of the ~/.teclarc configuration file.
6320 static int _gl_read_config_string(GetLine
*gl
, const char *buffer
, KtBinder who
)
6322 const char *bptr
; /* A pointer into buffer[] */
6323 int waserr
= 0; /* True if an error occurred while reading */
6324 int lineno
= 1; /* The line number being processed */
6326 * Check the arguments.
6328 if(!gl
|| !buffer
) {
6330 _err_record_msg(gl
->err
, "NULL argument(s)", END_ERR_MSG
);
6335 * Get a pointer to the start of the buffer.
6339 * Parse the contents of the buffer.
6341 while(!waserr
&& *bptr
)
6342 waserr
= _gl_parse_config_line(gl
, &bptr
, glc_buff_getc
, "", who
, &lineno
);
6344 * Bind action functions to the terminal-specific arrow keys.
6346 if(_gl_bind_arrow_keys(gl
))
6351 /*.......................................................................
6352 * Parse the next line of a getline configuration file.
6355 * gl GetLine * The getline resource object.
6356 * stream void * The pointer representing the stream to be read
6358 * getc_fn GlcGetcFn * A callback function which when called with
6359 * 'stream' as its argument, returns the next
6360 * unread character from the stream.
6361 * origin const char * The name of the entity being read (eg. a
6363 * who KtBinder Who bindings are to be installed for.
6365 * lineno int * The line number being processed is to be
6366 * maintained in *lineno.
6368 * return int 0 - OK.
6369 * 1 - Irrecoverable error.
6371 static int _gl_parse_config_line(GetLine
*gl
, void *stream
, GlcGetcFn
*getc_fn
,
6372 const char *origin
, KtBinder who
, int *lineno
)
6374 char buffer
[GL_CONF_BUFLEN
+1]; /* The input line buffer */
6375 char *argv
[GL_CONF_MAXARG
]; /* The argument list */
6376 int argc
= 0; /* The number of arguments in argv[] */
6377 int c
; /* A character from the file */
6378 int escaped
= 0; /* True if the next character is escaped */
6381 * Skip spaces and tabs.
6383 do c
= getc_fn(stream
); while(c
==' ' || c
=='\t');
6385 * Comments extend to the end of the line.
6388 do c
= getc_fn(stream
); while(c
!= '\n' && c
!= EOF
);
6390 * Ignore empty lines.
6392 if(c
=='\n' || c
==EOF
) {
6397 * Record the buffer location of the start of the first argument.
6399 argv
[argc
] = buffer
;
6401 * Read the rest of the line, stopping early if a comment is seen, or
6402 * the buffer overflows, and replacing sequences of spaces with a
6403 * '\0', and recording the thus terminated string as an argument.
6406 while(i
<GL_CONF_BUFLEN
) {
6408 * Did we hit the end of the latest argument?
6410 if(c
==EOF
|| (!escaped
&& (c
==' ' || c
=='\n' || c
=='\t' || c
=='#'))) {
6412 * Terminate the argument.
6417 * Skip spaces and tabs.
6419 while(c
==' ' || c
=='\t')
6420 c
= getc_fn(stream
);
6422 * If we hit the end of the line, or the start of a comment, exit the loop.
6424 if(c
==EOF
|| c
=='\n' || c
=='#')
6427 * Start recording the next argument.
6429 if(argc
>= GL_CONF_MAXARG
) {
6430 gl_report_config_error(gl
, origin
, *lineno
, "Too many arguments.");
6431 do c
= getc_fn(stream
); while(c
!='\n' && c
!=EOF
); /* Skip past eol */
6434 argv
[argc
] = buffer
+ i
;
6436 * The next character was preceded by spaces, so it isn't escaped.
6441 * If we hit an unescaped backslash, this means that we should arrange
6442 * to treat the next character like a simple alphabetical character.
6444 if(c
=='\\' && !escaped
) {
6447 * Splice lines where the newline is escaped.
6449 } else if(c
=='\n' && escaped
) {
6452 * Record a normal character, preserving any preceding backslash.
6457 if(i
>=GL_CONF_BUFLEN
)
6463 * Get the next character.
6465 c
= getc_fn(stream
);
6469 * Did the buffer overflow?
6471 if(i
>=GL_CONF_BUFLEN
) {
6472 gl_report_config_error(gl
, origin
, *lineno
, "Line too long.");
6476 * The first argument should be a command name.
6478 if(strcmp(argv
[0], "bind") == 0) {
6479 const char *action
= NULL
; /* A NULL action removes a keybinding */
6480 const char *keyseq
= NULL
;
6484 case 2: /* Note the intentional fallthrough */
6487 * Attempt to record the new keybinding.
6489 if(_kt_set_keybinding(gl
->bindings
, who
, keyseq
, action
)) {
6490 gl_report_config_error(gl
, origin
, *lineno
,
6491 _kt_last_error(gl
->bindings
));
6495 gl_report_config_error(gl
, origin
, *lineno
, "Wrong number of arguments.");
6497 } else if(strcmp(argv
[0], "edit-mode") == 0) {
6498 if(argc
== 2 && strcmp(argv
[1], "emacs") == 0) {
6499 gl_change_editor(gl
, GL_EMACS_MODE
);
6500 } else if(argc
== 2 && strcmp(argv
[1], "vi") == 0) {
6501 gl_change_editor(gl
, GL_VI_MODE
);
6502 } else if(argc
== 2 && strcmp(argv
[1], "none") == 0) {
6503 gl_change_editor(gl
, GL_NO_EDITOR
);
6505 gl_report_config_error(gl
, origin
, *lineno
,
6506 "The argument of editor should be vi or emacs.");
6508 } else if(strcmp(argv
[0], "nobeep") == 0) {
6509 gl
->silence_bell
= 1;
6511 gl_report_config_error(gl
, origin
, *lineno
, "Unknown command name.");
6514 * Skip any trailing comment.
6516 while(c
!= '\n' && c
!= EOF
)
6517 c
= getc_fn(stream
);
6522 /*.......................................................................
6523 * This is a private function of _gl_parse_config_line() which prints
6524 * out an error message about the contents of the line, prefixed by the
6525 * name of the origin of the line and its line number.
6528 * gl GetLine * The resource object of gl_get_line().
6529 * origin const char * The name of the entity being read (eg. a
6531 * lineno int The line number at which the error occurred.
6532 * errmsg const char * The error message.
6534 * return int 0 - OK.
6537 static int gl_report_config_error(GetLine
*gl
, const char *origin
, int lineno
,
6540 char lnum
[20]; /* A buffer in which to render a single integer */
6542 * Convert the line number into a string.
6544 snprintf(lnum
, sizeof(lnum
), "%d", lineno
);
6546 * Have the string printed on the terminal.
6548 return gl_print_info(gl
, origin
, ":", lnum
, ": ", errmsg
, GL_END_INFO
);
6551 /*.......................................................................
6552 * This is the _gl_parse_config_line() callback function which reads the
6553 * next character from a configuration file.
6555 static GLC_GETC_FN(glc_file_getc
)
6557 return fgetc((FILE *) stream
);
6560 /*.......................................................................
6561 * This is the _gl_parse_config_line() callback function which reads the
6562 * next character from a buffer. Its stream argument is a pointer to a
6563 * variable which is, in turn, a pointer into the buffer being read from.
6565 static GLC_GETC_FN(glc_buff_getc
)
6567 const char **lptr
= (char const **) stream
;
6568 return **lptr
? *(*lptr
)++ : EOF
;
6571 #ifndef HIDE_FILE_SYSTEM
6572 /*.......................................................................
6573 * When this action is triggered, it arranges to temporarily read command
6574 * lines from the regular file whos name precedes the cursor.
6575 * The current line is first discarded.
6577 static KT_KEY_FN(gl_read_from_file
)
6579 char *start_path
; /* The pointer to the start of the pathname in */
6581 FileExpansion
*result
; /* The results of the filename expansion */
6582 int pathlen
; /* The length of the pathname being expanded */
6584 * Locate the start of the filename that precedes the cursor position.
6586 start_path
= _pu_start_of_path(gl
->line
, gl
->buff_curpos
);
6590 * Get the length of the pathname string.
6592 pathlen
= gl
->buff_curpos
- (start_path
- gl
->line
);
6594 * Attempt to expand the pathname.
6596 result
= ef_expand_file(gl
->ef
, start_path
, pathlen
);
6598 * If there was an error, report the error on a new line.
6601 return gl_print_info(gl
, ef_last_error(gl
->ef
), GL_END_INFO
);
6603 * If no files matched, report this as well.
6605 } else if(result
->nfile
== 0 || !result
->exists
) {
6606 return gl_print_info(gl
, "No files match.", GL_END_INFO
);
6608 * Complain if more than one file matches.
6610 } else if(result
->nfile
> 1) {
6611 return gl_print_info(gl
, "More than one file matches.", GL_END_INFO
);
6613 * Disallow input from anything but normal files. In principle we could
6614 * also support input from named pipes. Terminal files would be a problem
6615 * since we wouldn't know the terminal type, and other types of files
6616 * might cause the library to lock up.
6618 } else if(!_pu_path_is_file(result
->files
[0])) {
6619 return gl_print_info(gl
, "Not a normal file.", GL_END_INFO
);
6622 * Attempt to open and install the specified file for reading.
6624 gl
->file_fp
= fopen(result
->files
[0], "r");
6626 return gl_print_info(gl
, "Unable to open: ", result
->files
[0],
6630 * If needed, expand the record of the maximum file-descriptor that might
6631 * need to be monitored with select().
6634 if(fileno(gl
->file_fp
) > gl
->max_fd
)
6635 gl
->max_fd
= fileno(gl
->file_fp
);
6638 * Is non-blocking I/O needed?
6640 if(gl
->raw_mode
&& gl
->io_mode
==GL_SERVER_MODE
&&
6641 gl_nonblocking_io(gl
, fileno(gl
->file_fp
))) {
6642 gl_revert_input(gl
);
6643 return gl_print_info(gl
, "Can't read file %s with non-blocking I/O",
6647 * Inform the user what is happening.
6649 if(gl_print_info(gl
, "<Taking input from ", result
->files
[0], ">",
6657 /*.......................................................................
6658 * Close any temporary file that is being used for input.
6661 * gl GetLine * The getline resource object.
6663 static void gl_revert_input(GetLine
*gl
)
6666 fclose(gl
->file_fp
);
6671 /*.......................................................................
6672 * This is the action function that recalls the oldest line in the
6675 static KT_KEY_FN(gl_beginning_of_history
)
6678 * In vi mode, switch to command mode, since the user is very
6679 * likely to want to move around newly recalled lines.
6681 gl_vi_command_mode(gl
);
6683 * Forget any previous recall session.
6687 * Record the key sequence number of this search action.
6689 gl
->last_search
= gl
->keyseq_count
;
6691 * Recall the next oldest line in the history list.
6693 if(_glh_oldest_line(gl
->glh
, gl
->line
, gl
->linelen
+1) == NULL
)
6696 * Accomodate the new contents of gl->line[].
6698 gl_update_buffer(gl
);
6700 * Arrange to have the cursor placed at the end of the new line.
6702 gl
->buff_curpos
= gl
->ntotal
;
6704 * Erase and display the new line.
6706 gl_queue_redisplay(gl
);
6710 /*.......................................................................
6711 * If a history session is currently in progress, this action function
6712 * recalls the line that was being edited when the session started. If
6713 * no history session is in progress, it does nothing.
6715 static KT_KEY_FN(gl_end_of_history
)
6718 * In vi mode, switch to command mode, since the user is very
6719 * likely to want to move around newly recalled lines.
6721 gl_vi_command_mode(gl
);
6723 * Forget any previous recall session.
6727 * Record the key sequence number of this search action.
6729 gl
->last_search
= gl
->keyseq_count
;
6731 * Recall the next oldest line in the history list.
6733 if(_glh_current_line(gl
->glh
, gl
->line
, gl
->linelen
+1) == NULL
)
6736 * Accomodate the new contents of gl->line[].
6738 gl_update_buffer(gl
);
6740 * Arrange to have the cursor placed at the end of the new line.
6742 gl
->buff_curpos
= gl
->ntotal
;
6744 * Erase and display the new line.
6746 gl_queue_redisplay(gl
);
6750 /*.......................................................................
6751 * This action function is treated specially, in that its count argument
6752 * is set to the end keystroke of the keysequence that activated it.
6753 * It accumulates a numeric argument, adding one digit on each call in
6754 * which the last keystroke was a numeric digit.
6756 static KT_KEY_FN(gl_digit_argument
)
6759 * Was the last keystroke a digit?
6761 int is_digit
= isdigit((int)(unsigned char) count
);
6763 * In vi command mode, a lone '0' means goto-start-of-line.
6765 if(gl
->vi
.command
&& gl
->number
< 0 && count
== '0')
6766 return gl_beginning_of_line(gl
, count
, NULL
);
6768 * Are we starting to accumulate a new number?
6770 if(gl
->number
< 0 || !is_digit
)
6773 * Was the last keystroke a digit?
6777 * Read the numeric value of the digit, without assuming ASCII.
6780 char s
[2]; s
[0] = count
; s
[1] = '\0';
6783 * Append the new digit.
6785 gl
->number
= gl
->number
* 10 + n
;
6790 /*.......................................................................
6791 * The newline action function sets gl->endline to tell
6792 * gl_get_input_line() that the line is now complete.
6794 static KT_KEY_FN(gl_newline
)
6796 GlhLineID id
; /* The last history line recalled while entering this line */
6798 * Flag the line as ended.
6802 * Record the next position in the history buffer, for potential
6803 * recall by an action function on the next call to gl_get_line().
6805 id
= _glh_line_id(gl
->glh
, 1);
6807 gl
->preload_id
= id
;
6811 /*.......................................................................
6812 * The 'repeat' action function sets gl->endline to tell
6813 * gl_get_input_line() that the line is now complete, and records the
6814 * ID of the next history line in gl->preload_id so that the next call
6815 * to gl_get_input_line() will preload the line with that history line.
6817 static KT_KEY_FN(gl_repeat_history
)
6820 gl
->preload_id
= _glh_line_id(gl
->glh
, 1);
6821 gl
->preload_history
= 1;
6825 /*.......................................................................
6826 * Flush unwritten characters to the terminal.
6829 * gl GetLine * The getline resource object.
6831 * return int 0 - OK.
6832 * 1 - Either an error occured, or the output
6833 * blocked and non-blocking I/O is being used.
6834 * See gl->rtn_status for details.
6836 static int gl_flush_output(GetLine
*gl
)
6839 * Record the fact that we are about to write to the terminal.
6841 gl
->pending_io
= GLP_WRITE
;
6843 * Attempt to flush the output to the terminal.
6846 switch(_glq_flush_queue(gl
->cq
, gl
->flush_fn
, gl
)) {
6847 case GLQ_FLUSH_DONE
:
6848 return gl
->redisplay
&& !gl
->postpone
&& gl_redisplay(gl
, 1, NULL
);
6850 case GLQ_FLUSH_AGAIN
: /* Output blocked */
6851 gl_record_status(gl
, GLR_BLOCKED
, BLOCKED_ERRNO
);
6854 default: /* Abort the line if an error occurs */
6855 gl_record_status(gl
, errno
==EINTR
? GLR_SIGNAL
: GLR_ERROR
, errno
);
6861 /*.......................................................................
6862 * This is the callback which _glq_flush_queue() uses to write buffered
6863 * characters to the terminal.
6865 static GL_WRITE_FN(gl_flush_terminal
)
6867 int ndone
= 0; /* The number of characters written so far */
6869 * Get the line-editor resource object.
6871 GetLine
*gl
= (GetLine
*) data
;
6873 * Transfer the latest array of characters to stdio.
6876 int nnew
= write(gl
->output_fd
, s
, n
-ndone
);
6878 * If the write was successful, add to the recorded number of bytes
6879 * that have now been written.
6884 * If a signal interrupted the call, restart the write(), since all of
6885 * the signals that gl_get_line() has been told to watch for are
6886 * currently blocked.
6888 } else if(errno
== EINTR
) {
6891 * If we managed to write something before an I/O error occurred, or
6892 * output blocked before anything was written, report the number of
6893 * bytes that were successfully written before this happened.
6899 #if defined(EWOULDBLOCK)
6900 || errno
==EWOULDBLOCK
6906 * To get here, an error must have occurred before anything new could
6914 * To get here, we must have successfully written the number of
6915 * bytes that was specified.
6920 /*.......................................................................
6921 * Change the style of editing to emulate a given editor.
6924 * gl GetLine * The getline resource object.
6925 * editor GlEditor The type of editor to emulate.
6927 * return int 0 - OK.
6930 static int gl_change_editor(GetLine
*gl
, GlEditor editor
)
6933 * Install the default key-bindings of the requested editor.
6937 _kt_clear_bindings(gl
->bindings
, KTB_NORM
);
6938 _kt_clear_bindings(gl
->bindings
, KTB_TERM
);
6939 (void) _kt_add_bindings(gl
->bindings
, KTB_NORM
, gl_emacs_bindings
,
6940 sizeof(gl_emacs_bindings
)/sizeof(gl_emacs_bindings
[0]));
6943 _kt_clear_bindings(gl
->bindings
, KTB_NORM
);
6944 _kt_clear_bindings(gl
->bindings
, KTB_TERM
);
6945 (void) _kt_add_bindings(gl
->bindings
, KTB_NORM
, gl_vi_bindings
,
6946 sizeof(gl_vi_bindings
)/sizeof(gl_vi_bindings
[0]));
6951 _err_record_msg(gl
->err
, "Unknown editor", END_ERR_MSG
);
6956 * Record the new editing mode.
6958 gl
->editor
= editor
;
6959 gl
->vi
.command
= 0; /* Start in input mode */
6960 gl
->insert_curpos
= 0;
6962 * Reinstate terminal-specific bindings.
6964 if(gl
->editor
!= GL_NO_EDITOR
&& gl
->input_fp
)
6965 (void) gl_bind_terminal_keys(gl
);
6969 /*.......................................................................
6970 * This is an action function that switches to editing using emacs bindings
6972 static KT_KEY_FN(gl_emacs_editing_mode
)
6974 return gl_change_editor(gl
, GL_EMACS_MODE
);
6977 /*.......................................................................
6978 * This is an action function that switches to editing using vi bindings
6980 static KT_KEY_FN(gl_vi_editing_mode
)
6982 return gl_change_editor(gl
, GL_VI_MODE
);
6985 /*.......................................................................
6986 * This is the action function that switches to insert mode.
6988 static KT_KEY_FN(gl_vi_insert
)
6991 * If in vi command mode, preserve the current line for potential
6994 gl_save_for_undo(gl
);
6996 * Switch to vi insert mode.
7000 gl
->insert_curpos
= gl
->buff_curpos
;
7004 /*.......................................................................
7005 * This is an action function that switches to overwrite mode.
7007 static KT_KEY_FN(gl_vi_overwrite
)
7010 * If in vi command mode, preserve the current line for potential
7013 gl_save_for_undo(gl
);
7015 * Switch to vi overwrite mode.
7019 gl
->insert_curpos
= gl
->buff_curpos
;
7023 /*.......................................................................
7024 * This action function toggles the case of the character under the
7027 static KT_KEY_FN(gl_change_case
)
7031 * Keep a record of the current insert mode and the cursor position.
7033 int insert
= gl
->insert
;
7035 * If in vi command mode, preserve the current line for potential
7038 gl_save_for_undo(gl
);
7040 * We want to overwrite the modified word.
7044 * Toggle the case of 'count' characters.
7046 for(i
=0; i
<count
&& gl
->buff_curpos
< gl
->ntotal
; i
++) {
7047 char *cptr
= gl
->line
+ gl
->buff_curpos
++;
7049 * Convert the character to upper case?
7051 if(islower((int)(unsigned char) *cptr
))
7052 gl_buffer_char(gl
, toupper((int) *cptr
), cptr
- gl
->line
);
7053 else if(isupper((int)(unsigned char) *cptr
))
7054 gl_buffer_char(gl
, tolower((int) *cptr
), cptr
- gl
->line
);
7056 * Write the possibly modified character back. Note that for non-modified
7057 * characters we want to do this as well, so as to advance the cursor.
7059 if(gl_print_char(gl
, *cptr
, cptr
[1]))
7063 * Restore the insertion mode.
7065 gl
->insert
= insert
;
7066 return gl_place_cursor(gl
, gl
->buff_curpos
); /* bounds check */
7069 /*.......................................................................
7070 * This is the action function which implements the vi-style action which
7071 * moves the cursor to the start of the line, then switches to insert mode.
7073 static KT_KEY_FN(gl_vi_insert_at_bol
)
7075 gl_save_for_undo(gl
);
7076 return gl_beginning_of_line(gl
, 0, NULL
) ||
7077 gl_vi_insert(gl
, 0, NULL
);
7081 /*.......................................................................
7082 * This is the action function which implements the vi-style action which
7083 * moves the cursor to the end of the line, then switches to insert mode
7084 * to allow text to be appended to the line.
7086 static KT_KEY_FN(gl_vi_append_at_eol
)
7088 gl_save_for_undo(gl
);
7089 gl
->vi
.command
= 0; /* Allow cursor at EOL */
7090 return gl_end_of_line(gl
, 0, NULL
) ||
7091 gl_vi_insert(gl
, 0, NULL
);
7094 /*.......................................................................
7095 * This is the action function which implements the vi-style action which
7096 * moves the cursor to right one then switches to insert mode, thus
7097 * allowing text to be appended after the next character.
7099 static KT_KEY_FN(gl_vi_append
)
7101 gl_save_for_undo(gl
);
7102 gl
->vi
.command
= 0; /* Allow cursor at EOL */
7103 return gl_cursor_right(gl
, 1, NULL
) ||
7104 gl_vi_insert(gl
, 0, NULL
);
7107 /*.......................................................................
7108 * This action function moves the cursor to the column specified by the
7109 * numeric argument. Column indexes start at 1.
7111 static KT_KEY_FN(gl_goto_column
)
7113 return gl_place_cursor(gl
, count
- 1);
7116 /*.......................................................................
7117 * Starting with the character under the cursor, replace 'count'
7118 * characters with the next character that the user types.
7120 static KT_KEY_FN(gl_vi_replace_char
)
7122 char c
; /* The replacement character */
7125 * Keep a record of the current insert mode.
7127 int insert
= gl
->insert
;
7129 * Get the replacement character.
7131 if(gl
->vi
.repeat
.active
) {
7132 c
= gl
->vi
.repeat
.input_char
;
7134 if(gl_read_terminal(gl
, 1, &c
))
7136 gl
->vi
.repeat
.input_char
= c
;
7139 * Are there 'count' characters to be replaced?
7141 if(gl
->ntotal
- gl
->buff_curpos
>= count
) {
7143 * If in vi command mode, preserve the current line for potential
7146 gl_save_for_undo(gl
);
7148 * Temporarily switch to overwrite mode.
7152 * Overwrite the current character plus count-1 subsequent characters
7153 * with the replacement character.
7155 for(i
=0; i
<count
; i
++)
7156 gl_add_char_to_line(gl
, c
);
7158 * Restore the original insert/overwrite mode.
7160 gl
->insert
= insert
;
7162 return gl_place_cursor(gl
, gl
->buff_curpos
); /* bounds check */
7165 /*.......................................................................
7166 * This is an action function which changes all characters between the
7167 * current cursor position and the end of the line.
7169 static KT_KEY_FN(gl_vi_change_rest_of_line
)
7171 gl_save_for_undo(gl
);
7172 gl
->vi
.command
= 0; /* Allow cursor at EOL */
7173 return gl_kill_line(gl
, count
, NULL
) || gl_vi_insert(gl
, 0, NULL
);
7176 /*.......................................................................
7177 * This is an action function which changes all characters between the
7178 * start of the line and the current cursor position.
7180 static KT_KEY_FN(gl_vi_change_to_bol
)
7182 return gl_backward_kill_line(gl
,count
,NULL
) || gl_vi_insert(gl
,0,NULL
);
7185 /*.......................................................................
7186 * This is an action function which deletes the entire contents of the
7187 * current line and switches to insert mode.
7189 static KT_KEY_FN(gl_vi_change_line
)
7191 return gl_delete_line(gl
,count
,NULL
) || gl_vi_insert(gl
,0,NULL
);
7194 /*.......................................................................
7195 * Starting from the cursor position and looking towards the end of the
7196 * line, copy 'count' characters to the cut buffer.
7198 static KT_KEY_FN(gl_forward_copy_char
)
7201 * Limit the count to the number of characters available.
7203 if(gl
->buff_curpos
+ count
>= gl
->ntotal
)
7204 count
= gl
->ntotal
- gl
->buff_curpos
;
7208 * Copy the characters to the cut buffer.
7210 memcpy(gl
->cutbuf
, gl
->line
+ gl
->buff_curpos
, count
);
7211 gl
->cutbuf
[count
] = '\0';
7215 /*.......................................................................
7216 * Starting from the character before the cursor position and looking
7217 * backwards towards the start of the line, copy 'count' characters to
7220 static KT_KEY_FN(gl_backward_copy_char
)
7223 * Limit the count to the number of characters available.
7225 if(count
> gl
->buff_curpos
)
7226 count
= gl
->buff_curpos
;
7229 gl_place_cursor(gl
, gl
->buff_curpos
- count
);
7231 * Copy the characters to the cut buffer.
7233 memcpy(gl
->cutbuf
, gl
->line
+ gl
->buff_curpos
, count
);
7234 gl
->cutbuf
[count
] = '\0';
7238 /*.......................................................................
7239 * Starting from the cursor position copy to the specified column into the
7242 static KT_KEY_FN(gl_copy_to_column
)
7244 if (--count
>= gl
->buff_curpos
)
7245 return gl_forward_copy_char(gl
, count
- gl
->buff_curpos
, NULL
);
7247 return gl_backward_copy_char(gl
, gl
->buff_curpos
- count
, NULL
);
7250 /*.......................................................................
7251 * Starting from the cursor position copy characters up to a matching
7252 * parenthesis into the cut buffer.
7254 static KT_KEY_FN(gl_copy_to_parenthesis
)
7256 int curpos
= gl_index_of_matching_paren(gl
);
7258 gl_save_for_undo(gl
);
7259 if(curpos
>= gl
->buff_curpos
)
7260 return gl_forward_copy_char(gl
, curpos
- gl
->buff_curpos
+ 1, NULL
);
7262 return gl_backward_copy_char(gl
, ++gl
->buff_curpos
- curpos
+ 1, NULL
);
7267 /*.......................................................................
7268 * Starting from the cursor position copy the rest of the line into the
7271 static KT_KEY_FN(gl_copy_rest_of_line
)
7274 * Copy the characters to the cut buffer.
7276 memcpy(gl
->cutbuf
, gl
->line
+ gl
->buff_curpos
, gl
->ntotal
- gl
->buff_curpos
);
7277 gl
->cutbuf
[gl
->ntotal
- gl
->buff_curpos
] = '\0';
7281 /*.......................................................................
7282 * Copy from the beginning of the line to the cursor position into the
7285 static KT_KEY_FN(gl_copy_to_bol
)
7288 * Copy the characters to the cut buffer.
7290 memcpy(gl
->cutbuf
, gl
->line
, gl
->buff_curpos
);
7291 gl
->cutbuf
[gl
->buff_curpos
] = '\0';
7292 gl_place_cursor(gl
, 0);
7296 /*.......................................................................
7297 * Copy the entire line into the cut buffer.
7299 static KT_KEY_FN(gl_copy_line
)
7302 * Copy the characters to the cut buffer.
7304 memcpy(gl
->cutbuf
, gl
->line
, gl
->ntotal
);
7305 gl
->cutbuf
[gl
->ntotal
] = '\0';
7309 /*.......................................................................
7310 * Search forwards for the next character that the user enters.
7312 static KT_KEY_FN(gl_forward_find_char
)
7314 int pos
= gl_find_char(gl
, count
, 1, 1, '\0');
7315 return pos
>= 0 && gl_place_cursor(gl
, pos
);
7318 /*.......................................................................
7319 * Search backwards for the next character that the user enters.
7321 static KT_KEY_FN(gl_backward_find_char
)
7323 int pos
= gl_find_char(gl
, count
, 0, 1, '\0');
7324 return pos
>= 0 && gl_place_cursor(gl
, pos
);
7327 /*.......................................................................
7328 * Search forwards for the next character that the user enters. Move up to,
7329 * but not onto, the found character.
7331 static KT_KEY_FN(gl_forward_to_char
)
7333 int pos
= gl_find_char(gl
, count
, 1, 0, '\0');
7334 return pos
>= 0 && gl_place_cursor(gl
, pos
);
7337 /*.......................................................................
7338 * Search backwards for the next character that the user enters. Move back to,
7339 * but not onto, the found character.
7341 static KT_KEY_FN(gl_backward_to_char
)
7343 int pos
= gl_find_char(gl
, count
, 0, 0, '\0');
7344 return pos
>= 0 && gl_place_cursor(gl
, pos
);
7347 /*.......................................................................
7348 * Searching in a given direction, return the index of a given (or
7349 * read) character in the input line, or the character that precedes
7350 * it in the specified search direction. Return -1 if not found.
7353 * gl GetLine * The getline resource object.
7354 * count int The number of times to search.
7355 * forward int True if searching forward.
7356 * onto int True if the search should end on top of the
7357 * character, false if the search should stop
7358 * one character before the character in the
7359 * specified search direction.
7360 * c char The character to be sought, or '\0' if the
7361 * character should be read from the user.
7363 * return int The index of the character in gl->line[], or
7366 static int gl_find_char(GetLine
*gl
, int count
, int forward
, int onto
, char c
)
7368 int pos
; /* The index reached in searching the input line */
7371 * Get a character from the user?
7375 * If we are in the process of repeating a previous change command, substitute
7376 * the last find character.
7378 if(gl
->vi
.repeat
.active
) {
7379 c
= gl
->vi
.find_char
;
7381 if(gl_read_terminal(gl
, 1, &c
))
7384 * Record the details of the new search, for use by repeat finds.
7386 gl
->vi
.find_forward
= forward
;
7387 gl
->vi
.find_onto
= onto
;
7388 gl
->vi
.find_char
= c
;
7392 * Which direction should we search?
7396 * Search forwards 'count' times for the character, starting with the
7397 * character that follows the cursor.
7399 for(i
=0, pos
=gl
->buff_curpos
; i
<count
&& pos
< gl
->ntotal
; i
++) {
7401 * Advance past the last match (or past the current cursor position
7402 * on the first search).
7406 * Search for the next instance of c.
7408 for( ; pos
<gl
->ntotal
&& c
!=gl
->line
[pos
]; pos
++)
7412 * If the character was found and we have been requested to return the
7413 * position of the character that precedes the desired character, then
7414 * we have gone one character too far.
7416 if(!onto
&& pos
<gl
->ntotal
)
7420 * Search backwards 'count' times for the character, starting with the
7421 * character that precedes the cursor.
7423 for(i
=0, pos
=gl
->buff_curpos
; i
<count
&& pos
>= gl
->insert_curpos
; i
++) {
7425 * Step back one from the last match (or from the current cursor
7426 * position on the first search).
7430 * Search for the next instance of c.
7432 for( ; pos
>=gl
->insert_curpos
&& c
!=gl
->line
[pos
]; pos
--)
7436 * If the character was found and we have been requested to return the
7437 * position of the character that precedes the desired character, then
7438 * we have gone one character too far.
7440 if(!onto
&& pos
>=gl
->insert_curpos
)
7444 * If found, return the cursor position of the count'th match.
7445 * Otherwise ring the terminal bell.
7447 if(pos
>= gl
->insert_curpos
&& pos
< gl
->ntotal
) {
7450 (void) gl_ring_bell(gl
, 1, NULL
);
7455 /*.......................................................................
7456 * Repeat the last character search in the same direction as the last
7459 static KT_KEY_FN(gl_repeat_find_char
)
7461 int pos
= gl
->vi
.find_char
?
7462 gl_find_char(gl
, count
, gl
->vi
.find_forward
, gl
->vi
.find_onto
,
7463 gl
->vi
.find_char
) : -1;
7464 return pos
>= 0 && gl_place_cursor(gl
, pos
);
7467 /*.......................................................................
7468 * Repeat the last character search in the opposite direction as the last
7471 static KT_KEY_FN(gl_invert_refind_char
)
7473 int pos
= gl
->vi
.find_char
?
7474 gl_find_char(gl
, count
, !gl
->vi
.find_forward
, gl
->vi
.find_onto
,
7475 gl
->vi
.find_char
) : -1;
7476 return pos
>= 0 && gl_place_cursor(gl
, pos
);
7479 /*.......................................................................
7480 * Search forward from the current position of the cursor for 'count'
7481 * word endings, returning the index of the last one found, or the end of
7482 * the line if there were less than 'count' words.
7485 * gl GetLine * The getline resource object.
7486 * n int The number of word boundaries to search for.
7488 * return int The buffer index of the located position.
7490 static int gl_nth_word_end_forward(GetLine
*gl
, int n
)
7492 int bufpos
; /* The buffer index being checked. */
7495 * In order to guarantee forward motion to the next word ending,
7496 * we need to start from one position to the right of the cursor
7497 * position, since this may already be at the end of a word.
7499 bufpos
= gl
->buff_curpos
+ 1;
7501 * If we are at the end of the line, return the index of the last
7502 * real character on the line. Note that this will be -1 if the line
7505 if(bufpos
>= gl
->ntotal
)
7506 return gl
->ntotal
- 1;
7508 * Search 'n' times, unless the end of the input line is reached first.
7510 for(i
=0; i
<n
&& bufpos
<gl
->ntotal
; i
++) {
7512 * If we are not already within a word, skip to the start of the next word.
7514 for( ; bufpos
<gl
->ntotal
&& !gl_is_word_char((int)gl
->line
[bufpos
]);
7518 * Find the end of the next word.
7520 for( ; bufpos
<gl
->ntotal
&& gl_is_word_char((int)gl
->line
[bufpos
]);
7525 * We will have overshot.
7527 return bufpos
> 0 ? bufpos
-1 : bufpos
;
7530 /*.......................................................................
7531 * Search forward from the current position of the cursor for 'count'
7532 * word starts, returning the index of the last one found, or the end of
7533 * the line if there were less than 'count' words.
7536 * gl GetLine * The getline resource object.
7537 * n int The number of word boundaries to search for.
7539 * return int The buffer index of the located position.
7541 static int gl_nth_word_start_forward(GetLine
*gl
, int n
)
7543 int bufpos
; /* The buffer index being checked. */
7546 * Get the current cursor position.
7548 bufpos
= gl
->buff_curpos
;
7550 * Search 'n' times, unless the end of the input line is reached first.
7552 for(i
=0; i
<n
&& bufpos
<gl
->ntotal
; i
++) {
7554 * Find the end of the current word.
7556 for( ; bufpos
<gl
->ntotal
&& gl_is_word_char((int)gl
->line
[bufpos
]);
7560 * Skip to the start of the next word.
7562 for( ; bufpos
<gl
->ntotal
&& !gl_is_word_char((int)gl
->line
[bufpos
]);
7569 /*.......................................................................
7570 * Search backward from the current position of the cursor for 'count'
7571 * word starts, returning the index of the last one found, or the start
7572 * of the line if there were less than 'count' words.
7575 * gl GetLine * The getline resource object.
7576 * n int The number of word boundaries to search for.
7578 * return int The buffer index of the located position.
7580 static int gl_nth_word_start_backward(GetLine
*gl
, int n
)
7582 int bufpos
; /* The buffer index being checked. */
7585 * Get the current cursor position.
7587 bufpos
= gl
->buff_curpos
;
7589 * Search 'n' times, unless the beginning of the input line (or vi insertion
7590 * point) is reached first.
7592 for(i
=0; i
<n
&& bufpos
> gl
->insert_curpos
; i
++) {
7594 * Starting one character back from the last search, so as not to keep
7595 * settling on the same word-start, search backwards until finding a
7598 while(--bufpos
>= gl
->insert_curpos
&&
7599 !gl_is_word_char((int)gl
->line
[bufpos
]))
7602 * Find the start of the word.
7604 while(--bufpos
>= gl
->insert_curpos
&&
7605 gl_is_word_char((int)gl
->line
[bufpos
]))
7608 * We will have gone one character too far.
7612 return bufpos
>= gl
->insert_curpos
? bufpos
: gl
->insert_curpos
;
7615 /*.......................................................................
7616 * Copy one or more words into the cut buffer without moving the cursor
7619 static KT_KEY_FN(gl_forward_copy_word
)
7622 * Find the location of the count'th start or end of a word
7623 * after the cursor, depending on whether in emacs or vi mode.
7625 int next
= gl
->editor
== GL_EMACS_MODE
?
7626 gl_nth_word_end_forward(gl
, count
) :
7627 gl_nth_word_start_forward(gl
, count
);
7629 * How many characters are to be copied into the cut buffer?
7631 int n
= next
- gl
->buff_curpos
;
7633 * Copy the specified segment and terminate the string.
7635 memcpy(gl
->cutbuf
, gl
->line
+ gl
->buff_curpos
, n
);
7636 gl
->cutbuf
[n
] = '\0';
7640 /*.......................................................................
7641 * Copy one or more words preceding the cursor into the cut buffer,
7642 * without moving the cursor or deleting text.
7644 static KT_KEY_FN(gl_backward_copy_word
)
7647 * Find the location of the count'th start of word before the cursor.
7649 int next
= gl_nth_word_start_backward(gl
, count
);
7651 * How many characters are to be copied into the cut buffer?
7653 int n
= gl
->buff_curpos
- next
;
7654 gl_place_cursor(gl
, next
);
7656 * Copy the specified segment and terminate the string.
7658 memcpy(gl
->cutbuf
, gl
->line
+ next
, n
);
7659 gl
->cutbuf
[n
] = '\0';
7663 /*.......................................................................
7664 * Copy the characters between the cursor and the count'th instance of
7665 * a specified character in the input line, into the cut buffer.
7668 * gl GetLine * The getline resource object.
7669 * count int The number of times to search.
7670 * c char The character to be searched for, or '\0' if
7671 * the character should be read from the user.
7672 * forward int True if searching forward.
7673 * onto int True if the search should end on top of the
7674 * character, false if the search should stop
7675 * one character before the character in the
7676 * specified search direction.
7678 * return int 0 - OK.
7682 static int gl_copy_find(GetLine
*gl
, int count
, char c
, int forward
, int onto
)
7684 int n
; /* The number of characters in the cut buffer */
7686 * Search for the character, and abort the operation if not found.
7688 int pos
= gl_find_char(gl
, count
, forward
, onto
, c
);
7692 * Copy the specified segment.
7695 n
= pos
+ 1 - gl
->buff_curpos
;
7696 memcpy(gl
->cutbuf
, gl
->line
+ gl
->buff_curpos
, n
);
7698 n
= gl
->buff_curpos
- pos
;
7699 memcpy(gl
->cutbuf
, gl
->line
+ pos
, n
);
7700 if(gl
->editor
== GL_VI_MODE
)
7701 gl_place_cursor(gl
, pos
);
7704 * Terminate the copy.
7706 gl
->cutbuf
[n
] = '\0';
7710 /*.......................................................................
7711 * Copy a section up to and including a specified character into the cut
7712 * buffer without moving the cursor or deleting text.
7714 static KT_KEY_FN(gl_forward_copy_find
)
7716 return gl_copy_find(gl
, count
, '\0', 1, 1);
7719 /*.......................................................................
7720 * Copy a section back to and including a specified character into the cut
7721 * buffer without moving the cursor or deleting text.
7723 static KT_KEY_FN(gl_backward_copy_find
)
7725 return gl_copy_find(gl
, count
, '\0', 0, 1);
7728 /*.......................................................................
7729 * Copy a section up to and not including a specified character into the cut
7730 * buffer without moving the cursor or deleting text.
7732 static KT_KEY_FN(gl_forward_copy_to
)
7734 return gl_copy_find(gl
, count
, '\0', 1, 0);
7737 /*.......................................................................
7738 * Copy a section back to and not including a specified character into the cut
7739 * buffer without moving the cursor or deleting text.
7741 static KT_KEY_FN(gl_backward_copy_to
)
7743 return gl_copy_find(gl
, count
, '\0', 0, 0);
7746 /*.......................................................................
7747 * Copy to a character specified in a previous search into the cut
7748 * buffer without moving the cursor or deleting text.
7750 static KT_KEY_FN(gl_copy_refind
)
7752 return gl_copy_find(gl
, count
, gl
->vi
.find_char
, gl
->vi
.find_forward
,
7756 /*.......................................................................
7757 * Copy to a character specified in a previous search, but in the opposite
7758 * direction, into the cut buffer without moving the cursor or deleting text.
7760 static KT_KEY_FN(gl_copy_invert_refind
)
7762 return gl_copy_find(gl
, count
, gl
->vi
.find_char
, !gl
->vi
.find_forward
,
7766 /*.......................................................................
7767 * Set the position of the cursor in the line input buffer and the
7771 * gl GetLine * The getline resource object.
7772 * buff_curpos int The new buffer cursor position.
7774 * return int 0 - OK.
7777 static int gl_place_cursor(GetLine
*gl
, int buff_curpos
)
7780 * Don't allow the cursor position to go out of the bounds of the input
7783 if(buff_curpos
>= gl
->ntotal
)
7784 buff_curpos
= gl
->vi
.command
? gl
->ntotal
-1 : gl
->ntotal
;
7788 * Record the new buffer position.
7790 gl
->buff_curpos
= buff_curpos
;
7792 * Move the terminal cursor to the corresponding character.
7794 return gl_set_term_curpos(gl
, gl
->prompt_len
+
7795 gl_displayed_string_width(gl
, gl
->line
, buff_curpos
, gl
->prompt_len
));
7798 /*.......................................................................
7799 * In vi command mode, this function saves the current line to the
7800 * historical buffer needed by the undo command. In emacs mode it does
7801 * nothing. In order to allow action functions to call other action
7802 * functions, gl_interpret_char() sets gl->vi.undo.saved to 0 before
7803 * invoking an action, and thereafter once any call to this function
7804 * has set it to 1, further calls are ignored.
7807 * gl GetLine * The getline resource object.
7809 static void gl_save_for_undo(GetLine
*gl
)
7811 if(gl
->vi
.command
&& !gl
->vi
.undo
.saved
) {
7812 strlcpy(gl
->vi
.undo
.line
, gl
->line
, gl
->linelen
);
7813 gl
->vi
.undo
.buff_curpos
= gl
->buff_curpos
;
7814 gl
->vi
.undo
.ntotal
= gl
->ntotal
;
7815 gl
->vi
.undo
.saved
= 1;
7817 if(gl
->vi
.command
&& !gl
->vi
.repeat
.saved
&&
7818 gl
->current_action
.fn
!= gl_vi_repeat_change
) {
7819 gl
->vi
.repeat
.action
= gl
->current_action
;
7820 gl
->vi
.repeat
.count
= gl
->current_count
;
7821 gl
->vi
.repeat
.saved
= 1;
7826 /*.......................................................................
7827 * In vi mode, restore the line to the way it was before the last command
7828 * mode operation, storing the current line in the buffer so that the
7829 * undo operation itself can subsequently be undone.
7831 static KT_KEY_FN(gl_vi_undo
)
7834 * Get pointers into the two lines.
7836 char *undo_ptr
= gl
->vi
.undo
.line
;
7837 char *line_ptr
= gl
->line
;
7839 * Swap the characters of the two buffers up to the length of the shortest
7842 while(*undo_ptr
&& *line_ptr
) {
7844 *undo_ptr
++ = *line_ptr
;
7848 * Copy the rest directly.
7850 if(gl
->ntotal
> gl
->vi
.undo
.ntotal
) {
7851 strlcpy(undo_ptr
, line_ptr
, gl
->linelen
);
7854 strlcpy(line_ptr
, undo_ptr
, gl
->linelen
);
7858 * Record the length of the stored string.
7860 gl
->vi
.undo
.ntotal
= gl
->ntotal
;
7862 * Accomodate the new contents of gl->line[].
7864 gl_update_buffer(gl
);
7866 * Set both cursor positions to the leftmost of the saved and current
7867 * cursor positions to emulate what vi does.
7869 if(gl
->buff_curpos
< gl
->vi
.undo
.buff_curpos
)
7870 gl
->vi
.undo
.buff_curpos
= gl
->buff_curpos
;
7872 gl
->buff_curpos
= gl
->vi
.undo
.buff_curpos
;
7874 * Since we have bipassed calling gl_save_for_undo(), record repeat
7875 * information inline.
7877 gl
->vi
.repeat
.action
.fn
= gl_vi_undo
;
7878 gl
->vi
.repeat
.action
.data
= NULL
;
7879 gl
->vi
.repeat
.count
= 1;
7881 * Display the restored line.
7883 gl_queue_redisplay(gl
);
7887 /*.......................................................................
7888 * Delete the following word and leave the user in vi insert mode.
7890 static KT_KEY_FN(gl_vi_forward_change_word
)
7892 gl_save_for_undo(gl
);
7893 gl
->vi
.command
= 0; /* Allow cursor at EOL */
7894 return gl_forward_delete_word(gl
, count
, NULL
) || gl_vi_insert(gl
, 0, NULL
);
7897 /*.......................................................................
7898 * Delete the preceding word and leave the user in vi insert mode.
7900 static KT_KEY_FN(gl_vi_backward_change_word
)
7902 return gl_backward_delete_word(gl
, count
, NULL
) || gl_vi_insert(gl
, 0, NULL
);
7905 /*.......................................................................
7906 * Delete the following section and leave the user in vi insert mode.
7908 static KT_KEY_FN(gl_vi_forward_change_find
)
7910 return gl_delete_find(gl
, count
, '\0', 1, 1, 1);
7913 /*.......................................................................
7914 * Delete the preceding section and leave the user in vi insert mode.
7916 static KT_KEY_FN(gl_vi_backward_change_find
)
7918 return gl_delete_find(gl
, count
, '\0', 0, 1, 1);
7921 /*.......................................................................
7922 * Delete the following section and leave the user in vi insert mode.
7924 static KT_KEY_FN(gl_vi_forward_change_to
)
7926 return gl_delete_find(gl
, count
, '\0', 1, 0, 1);
7929 /*.......................................................................
7930 * Delete the preceding section and leave the user in vi insert mode.
7932 static KT_KEY_FN(gl_vi_backward_change_to
)
7934 return gl_delete_find(gl
, count
, '\0', 0, 0, 1);
7937 /*.......................................................................
7938 * Delete to a character specified by a previous search and leave the user
7939 * in vi insert mode.
7941 static KT_KEY_FN(gl_vi_change_refind
)
7943 return gl_delete_find(gl
, count
, gl
->vi
.find_char
, gl
->vi
.find_forward
,
7944 gl
->vi
.find_onto
, 1);
7947 /*.......................................................................
7948 * Delete to a character specified by a previous search, but in the opposite
7949 * direction, and leave the user in vi insert mode.
7951 static KT_KEY_FN(gl_vi_change_invert_refind
)
7953 return gl_delete_find(gl
, count
, gl
->vi
.find_char
, !gl
->vi
.find_forward
,
7954 gl
->vi
.find_onto
, 1);
7957 /*.......................................................................
7958 * Delete the following character and leave the user in vi insert mode.
7960 static KT_KEY_FN(gl_vi_forward_change_char
)
7962 gl_save_for_undo(gl
);
7963 gl
->vi
.command
= 0; /* Allow cursor at EOL */
7964 return gl_delete_chars(gl
, count
, 1) || gl_vi_insert(gl
, 0, NULL
);
7967 /*.......................................................................
7968 * Delete the preceding character and leave the user in vi insert mode.
7970 static KT_KEY_FN(gl_vi_backward_change_char
)
7972 return gl_backward_delete_char(gl
, count
, NULL
) || gl_vi_insert(gl
, 0, NULL
);
7975 /*.......................................................................
7976 * Starting from the cursor position change characters to the specified column.
7978 static KT_KEY_FN(gl_vi_change_to_column
)
7980 if (--count
>= gl
->buff_curpos
)
7981 return gl_vi_forward_change_char(gl
, count
- gl
->buff_curpos
, NULL
);
7983 return gl_vi_backward_change_char(gl
, gl
->buff_curpos
- count
, NULL
);
7986 /*.......................................................................
7987 * Starting from the cursor position change characters to a matching
7990 static KT_KEY_FN(gl_vi_change_to_parenthesis
)
7992 int curpos
= gl_index_of_matching_paren(gl
);
7994 gl_save_for_undo(gl
);
7995 if(curpos
>= gl
->buff_curpos
)
7996 return gl_vi_forward_change_char(gl
, curpos
- gl
->buff_curpos
+ 1, NULL
);
7998 return gl_vi_backward_change_char(gl
, ++gl
->buff_curpos
- curpos
+ 1,
8004 /*.......................................................................
8005 * If in vi mode, switch to vi command mode.
8008 * gl GetLine * The getline resource object.
8010 static void gl_vi_command_mode(GetLine
*gl
)
8012 if(gl
->editor
== GL_VI_MODE
&& !gl
->vi
.command
) {
8015 gl
->vi
.repeat
.input_curpos
= gl
->insert_curpos
;
8016 gl
->vi
.repeat
.command_curpos
= gl
->buff_curpos
;
8017 gl
->insert_curpos
= 0; /* unrestrict left motion boundary */
8018 gl_cursor_left(gl
, 1, NULL
); /* Vi moves 1 left on entering command mode */
8022 /*.......................................................................
8023 * This is an action function which rings the terminal bell.
8025 static KT_KEY_FN(gl_ring_bell
)
8027 return gl
->silence_bell
? 0 :
8028 gl_print_control_sequence(gl
, 1, gl
->sound_bell
);
8031 /*.......................................................................
8032 * This is the action function which implements the vi-repeat-change
8035 static KT_KEY_FN(gl_vi_repeat_change
)
8037 int status
; /* The return status of the repeated action function */
8040 * Nothing to repeat?
8042 if(!gl
->vi
.repeat
.action
.fn
)
8043 return gl_ring_bell(gl
, 1, NULL
);
8045 * Provide a way for action functions to know whether they are being
8048 gl
->vi
.repeat
.active
= 1;
8050 * Re-run the recorded function.
8052 status
= gl
->vi
.repeat
.action
.fn(gl
, gl
->vi
.repeat
.count
,
8053 gl
->vi
.repeat
.action
.data
);
8055 * Mark the repeat as completed.
8057 gl
->vi
.repeat
.active
= 0;
8059 * Is we are repeating a function that has just switched to input
8060 * mode to allow the user to type, re-enter the text that the user
8061 * previously entered.
8063 if(status
==0 && !gl
->vi
.command
) {
8065 * Make sure that the current line has been saved.
8067 gl_save_for_undo(gl
);
8069 * Repeat a previous insertion or overwrite?
8071 if(gl
->vi
.repeat
.input_curpos
>= 0 &&
8072 gl
->vi
.repeat
.input_curpos
<= gl
->vi
.repeat
.command_curpos
&&
8073 gl
->vi
.repeat
.command_curpos
<= gl
->vi
.undo
.ntotal
) {
8075 * Using the current line which is saved in the undo buffer, plus
8076 * the range of characters therein, as recorded by gl_vi_command_mode(),
8077 * add the characters that the user previously entered, to the input
8080 for(i
=gl
->vi
.repeat
.input_curpos
; i
<gl
->vi
.repeat
.command_curpos
; i
++) {
8081 if(gl_add_char_to_line(gl
, gl
->vi
.undo
.line
[i
]))
8086 * Switch back to command mode, now that the insertion has been repeated.
8088 gl_vi_command_mode(gl
);
8093 /*.......................................................................
8094 * If the cursor is currently over a parenthesis character, return the
8095 * index of its matching parenthesis. If not currently over a parenthesis
8096 * character, return the next close parenthesis character to the right of
8097 * the cursor. If the respective parenthesis character isn't found,
8098 * ring the terminal bell and return -1.
8101 * gl GetLine * The getline resource object.
8103 * return int Either the index of the matching parenthesis,
8104 * or -1 if not found.
8106 static int gl_index_of_matching_paren(GetLine
*gl
)
8110 * List the recognized parentheses, and their matches.
8112 const char *o_paren
= "([{";
8113 const char *c_paren
= ")]}";
8116 * Get the character that is currently under the cursor.
8118 char c
= gl
->line
[gl
->buff_curpos
];
8120 * If the character under the cursor is an open parenthesis, look forward
8121 * for the matching close parenthesis.
8123 if((cptr
=strchr(o_paren
, c
))) {
8124 char match
= c_paren
[cptr
- o_paren
];
8125 int matches_needed
= 1;
8126 for(i
=gl
->buff_curpos
+1; i
<gl
->ntotal
; i
++) {
8127 if(gl
->line
[i
] == c
)
8129 else if(gl
->line
[i
] == match
&& --matches_needed
==0)
8133 * If the character under the cursor is an close parenthesis, look forward
8134 * for the matching open parenthesis.
8136 } else if((cptr
=strchr(c_paren
, c
))) {
8137 char match
= o_paren
[cptr
- c_paren
];
8138 int matches_needed
= 1;
8139 for(i
=gl
->buff_curpos
-1; i
>=0; i
--) {
8140 if(gl
->line
[i
] == c
)
8142 else if(gl
->line
[i
] == match
&& --matches_needed
==0)
8146 * If not currently over a parenthesis character, search forwards for
8147 * the first close parenthesis (this is what the vi % binding does).
8150 for(i
=gl
->buff_curpos
+1; i
<gl
->ntotal
; i
++)
8151 if(strchr(c_paren
, gl
->line
[i
]) != NULL
)
8157 (void) gl_ring_bell(gl
, 1, NULL
);
8161 /*.......................................................................
8162 * If the cursor is currently over a parenthesis character, this action
8163 * function moves the cursor to its matching parenthesis.
8165 static KT_KEY_FN(gl_find_parenthesis
)
8167 int curpos
= gl_index_of_matching_paren(gl
);
8169 return gl_place_cursor(gl
, curpos
);
8173 /*.......................................................................
8174 * Handle the receipt of the potential start of a new key-sequence from
8178 * gl GetLine * The resource object of this library.
8179 * first_char char The first character of the sequence.
8181 * return int 0 - OK.
8184 static int gl_interpret_char(GetLine
*gl
, char first_char
)
8186 char keyseq
[GL_KEY_MAX
+1]; /* A special key sequence being read */
8187 int nkey
=0; /* The number of characters in the key sequence */
8188 int count
; /* The repeat count of an action function */
8189 int ret
; /* The return value of an action function */
8192 * Get the first character.
8194 char c
= first_char
;
8196 * If editing is disabled, just add newly entered characters to the
8197 * input line buffer, and watch for the end of the line.
8199 if(gl
->editor
== GL_NO_EDITOR
) {
8200 gl_discard_chars(gl
, 1);
8201 if(gl
->ntotal
>= gl
->linelen
)
8203 if(c
== '\n' || c
== '\r')
8204 return gl_newline(gl
, 1, NULL
);
8205 gl_buffer_char(gl
, c
, gl
->ntotal
);
8209 * If the user is in the process of specifying a repeat count and the
8210 * new character is a digit, increment the repeat count accordingly.
8212 if(gl
->number
>= 0 && isdigit((int)(unsigned char) c
)) {
8213 gl_discard_chars(gl
, 1);
8214 return gl_digit_argument(gl
, c
, NULL
);
8216 * In vi command mode, all key-sequences entered need to be
8217 * either implicitly or explicitly prefixed with an escape character.
8219 } else if(gl
->vi
.command
&& c
!= GL_ESC_CHAR
) {
8220 keyseq
[nkey
++] = GL_ESC_CHAR
;
8222 * If the first character of the sequence is a printable character,
8223 * then to avoid confusion with the special "up", "down", "left"
8224 * or "right" cursor key bindings, we need to prefix the
8225 * printable character with a backslash escape before looking it up.
8227 } else if(!IS_META_CHAR(c
) && !IS_CTRL_CHAR(c
)) {
8228 keyseq
[nkey
++] = '\\';
8231 * Compose a potentially multiple key-sequence in gl->keyseq.
8233 while(nkey
< GL_KEY_MAX
) {
8234 KtAction
*action
; /* An action function */
8235 KeySym
*keysym
; /* The symbol-table entry of a key-sequence */
8236 int nsym
; /* The number of ambiguously matching key-sequences */
8238 * If the character is an unprintable meta character, split it
8239 * into two characters, an escape character and the character
8240 * that was modified by the meta key.
8242 if(IS_META_CHAR(c
)) {
8243 keyseq
[nkey
++] = GL_ESC_CHAR
;
8244 c
= META_TO_CHAR(c
);
8248 * Append the latest character to the key sequence.
8252 * When doing vi-style editing, an escape at the beginning of any binding
8253 * switches to command mode.
8255 if(keyseq
[0] == GL_ESC_CHAR
&& !gl
->vi
.command
)
8256 gl_vi_command_mode(gl
);
8258 * Lookup the key sequence.
8260 switch(_kt_lookup_keybinding(gl
->bindings
, keyseq
, nkey
, &keysym
, &nsym
)) {
8261 case KT_EXACT_MATCH
:
8263 * Get the matching action function.
8265 action
= keysym
->actions
+ keysym
->binder
;
8267 * Get the repeat count, passing the last keystroke if executing the
8268 * digit-argument action.
8270 if(action
->fn
== gl_digit_argument
) {
8273 count
= gl
->number
>= 0 ? gl
->number
: 1;
8276 * Record the function that is being invoked.
8278 gl
->current_action
= *action
;
8279 gl
->current_count
= count
;
8281 * Mark the current line as not yet preserved for use by the vi undo command.
8283 gl
->vi
.undo
.saved
= 0;
8284 gl
->vi
.repeat
.saved
= 0;
8286 * Execute the action function. Note the action function can tell
8287 * whether the provided repeat count was defaulted or specified
8288 * explicitly by looking at whether gl->number is -1 or not. If
8289 * it is negative, then no repeat count was specified by the user.
8291 ret
= action
->fn(gl
, count
, action
->data
);
8293 * In server mode, the action will return immediately if it tries to
8294 * read input from the terminal, and no input is currently available.
8295 * If this happens, abort. Note that gl_get_input_line() will rewind
8296 * the read-ahead buffer to allow the next call to redo the function
8299 if(gl
->rtn_status
== GLR_BLOCKED
&& gl
->pending_io
==GLP_READ
)
8302 * Discard the now processed characters from the key sequence buffer.
8304 gl_discard_chars(gl
, gl
->nread
);
8306 * If the latest action function wasn't a history action, cancel any
8307 * current history search.
8309 if(gl
->last_search
!= gl
->keyseq_count
)
8310 _glh_cancel_search(gl
->glh
);
8312 * Reset the repeat count after running action functions.
8314 if(action
->fn
!= gl_digit_argument
)
8318 case KT_AMBIG_MATCH
: /* Ambiguous match - so read the next character */
8319 if(gl_read_terminal(gl
, 1, &c
))
8324 * If the first character looked like it might be a prefix of a key-sequence
8325 * but it turned out not to be, ring the bell to tell the user that it
8326 * wasn't recognised.
8328 if(keyseq
[0] != '\\' && keyseq
[0] != '\t') {
8329 gl_ring_bell(gl
, 1, NULL
);
8332 * The user typed a single printable character that doesn't match
8333 * the start of any keysequence, so add it to the line in accordance
8334 * with the current repeat count.
8336 count
= gl
->number
>= 0 ? gl
->number
: 1;
8337 for(i
=0; i
<count
; i
++)
8338 gl_add_char_to_line(gl
, first_char
);
8341 gl_discard_chars(gl
, 1);
8342 _glh_cancel_search(gl
->glh
);
8346 gl_ring_bell(gl
, 1, NULL
);
8347 gl_discard_chars(gl
, gl
->nread
);
8348 _glh_cancel_search(gl
->glh
);
8354 * If the key sequence was too long to match, ring the bell, then
8355 * discard the first character, so that the next attempt to match a
8356 * key-sequence continues with the next key press. In practice this
8357 * shouldn't happen, since one isn't allowed to bind action functions
8358 * to keysequences that are longer than GL_KEY_MAX.
8360 gl_ring_bell(gl
, 1, NULL
);
8361 gl_discard_chars(gl
, 1);
8365 /*.......................................................................
8366 * Configure the application and/or user-specific behavior of
8369 * Note that calling this function between calling new_GetLine() and
8370 * the first call to gl_get_line(), disables the otherwise automatic
8371 * reading of ~/.teclarc on the first call to gl_get_line().
8374 * gl GetLine * The resource object of this library.
8375 * app_string const char * Either NULL, or a string containing one
8376 * or more .teclarc command lines, separated
8377 * by newline characters. This can be used to
8378 * establish an application-specific
8379 * configuration, without the need for an external
8380 * file. This is particularly useful in embedded
8381 * environments where there is no filesystem.
8382 * app_file const char * Either NULL, or the pathname of an
8383 * application-specific .teclarc file. The
8384 * contents of this file, if provided, are
8385 * read after the contents of app_string[].
8386 * user_file const char * Either NULL, or the pathname of a
8387 * user-specific .teclarc file. Except in
8388 * embedded applications, this should
8389 * usually be "~/.teclarc".
8391 * return int 0 - OK.
8392 * 1 - Bad argument(s).
8394 int gl_configure_getline(GetLine
*gl
, const char *app_string
,
8395 const char *app_file
, const char *user_file
)
8397 sigset_t oldset
; /* The signals that were blocked on entry to this function */
8398 int status
; /* The return status of _gl_configure_getline() */
8400 * Check the arguments.
8407 * Block all signals.
8409 if(gl_mask_signals(gl
, &oldset
))
8412 * Execute the private body of the function while signals are blocked.
8414 status
= _gl_configure_getline(gl
, app_string
, app_file
, user_file
);
8416 * Restore the process signal mask.
8418 gl_unmask_signals(gl
, &oldset
);
8422 /*.......................................................................
8423 * This is the private body of the gl_configure_getline() function. It
8424 * assumes that the caller has checked its arguments and blocked the
8425 * delivery of signals.
8427 static int _gl_configure_getline(GetLine
*gl
, const char *app_string
,
8428 const char *app_file
, const char *user_file
)
8431 * Mark getline as having been explicitly configured.
8435 * Start by parsing the configuration string, if provided.
8438 (void) _gl_read_config_string(gl
, app_string
, KTB_NORM
);
8440 * Now parse the application-specific configuration file, if provided.
8443 (void) _gl_read_config_file(gl
, app_file
, KTB_NORM
);
8445 * Finally, parse the user-specific configuration file, if provided.
8448 (void) _gl_read_config_file(gl
, user_file
, KTB_USER
);
8450 * Record the names of the configuration files to allow them to
8451 * be re-read if requested at a later time.
8453 if(gl_record_string(&gl
->app_file
, app_file
) ||
8454 gl_record_string(&gl
->user_file
, user_file
)) {
8456 _err_record_msg(gl
->err
,
8457 "Insufficient memory to record tecla configuration file names",
8464 /*.......................................................................
8465 * Replace a malloc'd string (or NULL), with another malloc'd copy of
8466 * a string (or NULL).
8469 * sptr char ** On input if *sptr!=NULL, *sptr will be
8470 * free'd and *sptr will be set to NULL. Then,
8471 * on output, if string!=NULL a malloc'd copy
8472 * of this string will be assigned to *sptr.
8473 * string const char * The string to be copied, or NULL to simply
8474 * discard any existing string.
8476 * return int 0 - OK.
8477 * 1 - Malloc failure (no error message is generated).
8479 static int gl_record_string(char **sptr
, const char *string
)
8482 * If the original string is the same string, don't do anything.
8484 if(*sptr
== string
|| (*sptr
&& string
&& strcmp(*sptr
, string
)==0))
8487 * Discard any existing cached string.
8494 * Allocate memory for a copy of the specified string.
8497 size_t ssz
= strlen(string
) + 1;
8498 *sptr
= (char *) malloc(ssz
);
8504 strlcpy(*sptr
, string
, ssz
);
8509 #ifndef HIDE_FILE_SYSTEM
8510 /*.......................................................................
8511 * Re-read any application-specific and user-specific files previously
8512 * specified via the gl_configure_getline() function.
8514 static KT_KEY_FN(gl_read_init_files
)
8516 return _gl_configure_getline(gl
, NULL
, gl
->app_file
, gl
->user_file
);
8520 /*.......................................................................
8521 * Save the contents of the history buffer to a given new file.
8524 * gl GetLine * The resource object of this library.
8525 * filename const char * The name of the new file to write to.
8526 * comment const char * Extra information such as timestamps will
8527 * be recorded on a line started with this
8528 * string, the idea being that the file can
8529 * double as a command file. Specify "" if
8531 * max_lines int The maximum number of lines to save, or -1
8532 * to save all of the lines in the history
8535 * return int 0 - OK.
8538 int gl_save_history(GetLine
*gl
, const char *filename
, const char *comment
,
8541 sigset_t oldset
; /* The signals that were blocked on entry to this function */
8542 int status
; /* The return status of _gl_save_history() */
8544 * Check the arguments.
8546 if(!gl
|| !filename
|| !comment
) {
8548 _err_record_msg(gl
->err
, "NULL argument(s)", END_ERR_MSG
);
8553 * Block all signals.
8555 if(gl_mask_signals(gl
, &oldset
))
8558 * Execute the private body of the function while signals are blocked.
8560 status
= _gl_save_history(gl
, filename
, comment
, max_lines
);
8562 * Restore the process signal mask.
8564 gl_unmask_signals(gl
, &oldset
);
8568 /*.......................................................................
8569 * This is the private body of the gl_save_history() function. It
8570 * assumes that the caller has checked its arguments and blocked the
8571 * delivery of signals.
8573 static int _gl_save_history(GetLine
*gl
, const char *filename
,
8574 const char *comment
, int max_lines
)
8577 * If filesystem access is to be excluded, then history files can't
8580 #ifdef WITHOUT_FILE_SYSTEM
8581 _err_record_msg(gl
->err
, "Can't save history without filesystem access",
8586 FileExpansion
*expansion
; /* The expansion of the filename */
8588 * Expand the filename.
8590 expansion
= ef_expand_file(gl
->ef
, filename
, -1);
8592 gl_print_info(gl
, "Unable to expand ", filename
, " (",
8593 ef_last_error(gl
->ef
), ").", GL_END_INFO
);
8597 * Attempt to save to the specified file.
8599 if(_glh_save_history(gl
->glh
, expansion
->files
[0], comment
, max_lines
)) {
8600 _err_record_msg(gl
->err
, _glh_last_error(gl
->glh
), END_ERR_MSG
);
8607 /*.......................................................................
8608 * Restore the contents of the history buffer from a given new file.
8611 * gl GetLine * The resource object of this library.
8612 * filename const char * The name of the new file to write to.
8613 * comment const char * This must be the same string that was
8614 * passed to gl_save_history() when the file
8617 * return int 0 - OK.
8620 int gl_load_history(GetLine
*gl
, const char *filename
, const char *comment
)
8622 sigset_t oldset
; /* The signals that were blocked on entry to this function */
8623 int status
; /* The return status of _gl_load_history() */
8625 * Check the arguments.
8627 if(!gl
|| !filename
|| !comment
) {
8629 _err_record_msg(gl
->err
, "NULL argument(s)", END_ERR_MSG
);
8634 * Block all signals.
8636 if(gl_mask_signals(gl
, &oldset
))
8639 * Execute the private body of the function while signals are blocked.
8641 status
= _gl_load_history(gl
, filename
, comment
);
8643 * Restore the process signal mask.
8645 gl_unmask_signals(gl
, &oldset
);
8649 /*.......................................................................
8650 * This is the private body of the gl_load_history() function. It
8651 * assumes that the caller has checked its arguments and blocked the
8652 * delivery of signals.
8654 static int _gl_load_history(GetLine
*gl
, const char *filename
,
8655 const char *comment
)
8658 * If filesystem access is to be excluded, then history files can't
8661 #ifdef WITHOUT_FILE_SYSTEM
8662 _err_record_msg(gl
->err
, "Can't load history without filesystem access",
8667 FileExpansion
*expansion
; /* The expansion of the filename */
8669 * Expand the filename.
8671 expansion
= ef_expand_file(gl
->ef
, filename
, -1);
8673 gl_print_info(gl
, "Unable to expand ", filename
, " (",
8674 ef_last_error(gl
->ef
), ").", GL_END_INFO
);
8678 * Attempt to load from the specified file.
8680 if(_glh_load_history(gl
->glh
, expansion
->files
[0], comment
,
8681 gl
->cutbuf
, gl
->linelen
+1)) {
8682 _err_record_msg(gl
->err
, _glh_last_error(gl
->glh
), END_ERR_MSG
);
8683 gl
->cutbuf
[0] = '\0';
8686 gl
->cutbuf
[0] = '\0';
8691 /*.......................................................................
8692 * Where possible, register a function and associated data to be called
8693 * whenever a specified event is seen on a file descriptor.
8696 * gl GetLine * The resource object of the command-line input
8698 * fd int The file descriptor to watch.
8699 * event GlFdEvent The type of activity to watch for.
8700 * callback GlFdEventFn * The function to call when the specified
8701 * event occurs. Setting this to 0 removes
8702 * any existing callback.
8703 * data void * A pointer to arbitrary data to pass to the
8704 * callback function.
8706 * return int 0 - OK.
8707 * 1 - Either gl==NULL, or this facility isn't
8708 * available on the the host system
8709 * (ie. select() isn't available). No
8710 * error message is generated in the latter
8713 int gl_watch_fd(GetLine
*gl
, int fd
, GlFdEvent event
,
8714 GlFdEventFn
*callback
, void *data
)
8716 sigset_t oldset
; /* The signals that were blocked on entry to this function */
8717 int status
; /* The return status of _gl_watch_fd() */
8719 * Check the arguments.
8726 _err_record_msg(gl
->err
, "Error: fd < 0", END_ERR_MSG
);
8731 * Block all signals.
8733 if(gl_mask_signals(gl
, &oldset
))
8736 * Execute the private body of the function while signals are blocked.
8738 status
= _gl_watch_fd(gl
, fd
, event
, callback
, data
);
8740 * Restore the process signal mask.
8742 gl_unmask_signals(gl
, &oldset
);
8746 /*.......................................................................
8747 * This is the private body of the gl_watch_fd() function. It
8748 * assumes that the caller has checked its arguments and blocked the
8749 * delivery of signals.
8751 static int _gl_watch_fd(GetLine
*gl
, int fd
, GlFdEvent event
,
8752 GlFdEventFn
*callback
, void *data
)
8753 #if !defined(HAVE_SELECT)
8754 {return 1;} /* The facility isn't supported on this system */
8757 GlFdNode
*prev
; /* The node that precedes 'node' in gl->fd_nodes */
8758 GlFdNode
*node
; /* The file-descriptor node being checked */
8760 * Search the list of already registered fd activity nodes for the specified
8763 for(prev
=NULL
,node
=gl
->fd_nodes
; node
&& node
->fd
!= fd
;
8764 prev
=node
, node
=node
->next
)
8767 * Hasn't a node been allocated for this fd yet?
8771 * If there is no callback to record, just ignore the call.
8776 * Allocate the new node.
8778 node
= (GlFdNode
*) _new_FreeListNode(gl
->fd_node_mem
);
8781 _err_record_msg(gl
->err
, "Insufficient memory", END_ERR_MSG
);
8785 * Prepend the node to the list.
8787 node
->next
= gl
->fd_nodes
;
8788 gl
->fd_nodes
= node
;
8790 * Initialize the node.
8794 node
->rd
.data
= NULL
;
8795 node
->ur
= node
->wr
= node
->rd
;
8798 * Record the new callback.
8802 node
->rd
.fn
= callback
;
8803 node
->rd
.data
= data
;
8805 FD_SET(fd
, &gl
->rfds
);
8807 FD_CLR(fd
, &gl
->rfds
);
8810 node
->wr
.fn
= callback
;
8811 node
->wr
.data
= data
;
8813 FD_SET(fd
, &gl
->wfds
);
8815 FD_CLR(fd
, &gl
->wfds
);
8818 node
->ur
.fn
= callback
;
8819 node
->ur
.data
= data
;
8821 FD_SET(fd
, &gl
->ufds
);
8823 FD_CLR(fd
, &gl
->ufds
);
8827 * Keep a record of the largest file descriptor being watched.
8832 * If we are deleting an existing callback, also delete the parent
8833 * activity node if no callbacks are registered to the fd anymore.
8836 if(!node
->rd
.fn
&& !node
->wr
.fn
&& !node
->ur
.fn
) {
8838 prev
->next
= node
->next
;
8840 gl
->fd_nodes
= node
->next
;
8841 node
= (GlFdNode
*) _del_FreeListNode(gl
->fd_node_mem
, node
);
8848 /*.......................................................................
8849 * On systems with the select() system call, the gl_inactivity_timeout()
8850 * function provides the option of setting (or cancelling) an
8851 * inactivity timeout. Inactivity, in this case, refers both to
8852 * terminal input received from the user, and to I/O on any file
8853 * descriptors registered by calls to gl_watch_fd(). If at any time,
8854 * no activity is seen for the requested time period, the specified
8855 * timeout callback function is called. On returning, this callback
8856 * returns a code which tells gl_get_line() what to do next. Note that
8857 * each call to gl_inactivity_timeout() replaces any previously installed
8858 * timeout callback, and that specifying a callback of 0, turns off
8859 * inactivity timing.
8861 * Beware that although the timeout argument includes a nano-second
8862 * component, few computer clocks presently have resolutions finer
8863 * than a few milliseconds, so asking for less than a few milliseconds
8864 * is equivalent to zero on a lot of systems.
8867 * gl GetLine * The resource object of the command-line input
8869 * callback GlTimeoutFn * The function to call when the inactivity
8870 * timeout is exceeded. To turn off
8871 * inactivity timeouts altogether, send 0.
8872 * data void * A pointer to arbitrary data to pass to the
8873 * callback function.
8874 * sec unsigned long The number of whole seconds in the timeout.
8875 * nsec unsigned long The fractional number of seconds in the
8876 * timeout, expressed in nano-seconds (see
8877 * the caveat above).
8879 * return int 0 - OK.
8880 * 1 - Either gl==NULL, or this facility isn't
8881 * available on the the host system
8882 * (ie. select() isn't available). No
8883 * error message is generated in the latter
8886 int gl_inactivity_timeout(GetLine
*gl
, GlTimeoutFn
*timeout_fn
, void *data
,
8887 unsigned long sec
, unsigned long nsec
)
8888 #if !defined(HAVE_SELECT)
8889 {return 1;} /* The facility isn't supported on this system */
8892 sigset_t oldset
; /* The signals that were blocked on entry to this function */
8894 * Check the arguments.
8901 * Block all signals.
8903 if(gl_mask_signals(gl
, &oldset
))
8906 * Install a new timeout?
8909 gl
->timer
.dt
.tv_sec
= sec
;
8910 gl
->timer
.dt
.tv_usec
= nsec
/ 1000;
8911 gl
->timer
.fn
= timeout_fn
;
8912 gl
->timer
.data
= data
;
8915 gl
->timer
.data
= NULL
;
8918 * Restore the process signal mask.
8920 gl_unmask_signals(gl
, &oldset
);
8925 /*.......................................................................
8926 * When select() is available, this is a private function of
8927 * gl_read_input() which responds to file-descriptor events registered by
8928 * the caller. Note that it assumes that it is being called from within
8929 * gl_read_input()'s sigsetjump() clause.
8932 * gl GetLine * The resource object of this module.
8933 * fd int The file descriptor to be watched for user input.
8935 * return int 0 - OK.
8936 * 1 - An error occurred.
8938 static int gl_event_handler(GetLine
*gl
, int fd
)
8940 #if !defined(HAVE_SELECT)
8944 * Set up a zero-second timeout.
8946 struct timeval zero
;
8947 zero
.tv_sec
= zero
.tv_usec
= 0;
8949 * If at any time no external callbacks remain, quit the loop return,
8950 * so that we can simply wait in read(). This is designed as an
8951 * optimization for when no callbacks have been registered on entry to
8952 * this function, but since callbacks can delete themselves, it can
8955 while(gl
->fd_nodes
|| gl
->timer
.fn
) {
8956 int nready
; /* The number of file descriptors that are ready for I/O */
8958 * Get the set of descriptors to be watched.
8960 fd_set rfds
= gl
->rfds
;
8961 fd_set wfds
= gl
->wfds
;
8962 fd_set ufds
= gl
->ufds
;
8964 * Get the appropriate timeout.
8966 struct timeval dt
= gl
->timer
.fn
? gl
->timer
.dt
: zero
;
8968 * Add the specified user-input file descriptor to the set that is to
8973 * Unblock the signals that we are watching, while select is blocked
8976 gl_catch_signals(gl
);
8978 * Wait for activity on any of the file descriptors.
8980 nready
= select(gl
->max_fd
+1, &rfds
, &wfds
, &ufds
,
8981 (gl
->timer
.fn
|| gl
->io_mode
==GL_SERVER_MODE
) ? &dt
: NULL
);
8983 * We don't want to do a longjmp in the middle of a callback that
8984 * might be modifying global or heap data, so block all the signals
8985 * that we are trapping before executing callback functions. Note that
8986 * the caller will unblock them again when it needs to, so there is
8987 * no need to undo this before returning.
8989 gl_mask_signals(gl
, NULL
);
8991 * If select() returns but none of the file descriptors are reported
8992 * to have activity, then select() timed out.
8996 * Note that in non-blocking server mode, the inactivity timer is used
8997 * to allow I/O to block for a specified amount of time, so in this
8998 * mode we return the postponed blocked status when an abort is
9001 if(gl_call_timeout_handler(gl
)) {
9003 } else if(gl
->io_mode
== GL_SERVER_MODE
) {
9004 gl_record_status(gl
, GLR_BLOCKED
, BLOCKED_ERRNO
);
9008 * If nready < 0, this means an error occurred.
9010 } else if(nready
< 0) {
9011 if(errno
!= EINTR
) {
9012 gl_record_status(gl
, GLR_ERROR
, errno
);
9016 * If the user-input file descriptor has data available, return.
9018 } else if(FD_ISSET(fd
, &rfds
)) {
9021 * Check for activity on any of the file descriptors registered by the
9022 * calling application, and call the associated callback functions.
9025 GlFdNode
*node
; /* The fd event node being checked */
9027 * Search the list for the file descriptor that caused select() to return.
9029 for(node
=gl
->fd_nodes
; node
; node
=node
->next
) {
9031 * Is there urgent out of band data waiting to be read on fd?
9033 if(node
->ur
.fn
&& FD_ISSET(node
->fd
, &ufds
)) {
9034 if(gl_call_fd_handler(gl
, &node
->ur
, node
->fd
, GLFD_URGENT
))
9036 break; /* The callback may have changed the list of nodes */
9038 * Is the fd readable?
9040 } else if(node
->rd
.fn
&& FD_ISSET(node
->fd
, &rfds
)) {
9041 if(gl_call_fd_handler(gl
, &node
->rd
, node
->fd
, GLFD_READ
))
9043 break; /* The callback may have changed the list of nodes */
9045 * Is the fd writable?
9047 } else if(node
->wr
.fn
&& FD_ISSET(node
->fd
, &wfds
)) {
9048 if(gl_call_fd_handler(gl
, &node
->wr
, node
->fd
, GLFD_WRITE
))
9050 break; /* The callback may have changed the list of nodes */
9055 * Just in case the above event handlers asked for the input line to
9056 * be redrawn, flush any pending output.
9058 if(gl_flush_output(gl
))
9065 #if defined(HAVE_SELECT)
9066 /*.......................................................................
9067 * This is a private function of gl_event_handler(), used to call a
9068 * file-descriptor callback.
9071 * gl GetLine * The resource object of gl_get_line().
9072 * gfh GlFdHandler * The I/O handler.
9073 * fd int The file-descriptor being reported.
9074 * event GlFdEvent The I/O event being reported.
9076 * return int 0 - OK.
9079 static int gl_call_fd_handler(GetLine
*gl
, GlFdHandler
*gfh
, int fd
,
9082 Termios attr
; /* The terminal attributes */
9083 int waserr
= 0; /* True after any error */
9085 * Re-enable conversion of newline characters to carriage-return/linefeed,
9086 * so that the callback can write to the terminal without having to do
9089 if(tcgetattr(gl
->input_fd
, &attr
)) {
9090 _err_record_msg(gl
->err
, "tcgetattr error", END_ERR_MSG
);
9093 attr
.c_oflag
|= OPOST
;
9094 while(tcsetattr(gl
->input_fd
, TCSADRAIN
, &attr
)) {
9095 if(errno
!= EINTR
) {
9096 _err_record_msg(gl
->err
, "tcsetattr error", END_ERR_MSG
);
9101 * Invoke the application's callback function.
9103 switch(gfh
->fn(gl
, gfh
->data
, fd
, event
)) {
9106 gl_record_status(gl
, GLR_FDABORT
, 0);
9110 gl_queue_redisplay(gl
);
9116 * Disable conversion of newline characters to carriage-return/linefeed.
9118 attr
.c_oflag
&= ~(OPOST
);
9119 while(tcsetattr(gl
->input_fd
, TCSADRAIN
, &attr
)) {
9120 if(errno
!= EINTR
) {
9121 _err_record_msg(gl
->err
, "tcsetattr error", END_ERR_MSG
);
9128 /*.......................................................................
9129 * This is a private function of gl_event_handler(), used to call a
9130 * inactivity timer callbacks.
9133 * gl GetLine * The resource object of gl_get_line().
9135 * return int 0 - OK.
9138 static int gl_call_timeout_handler(GetLine
*gl
)
9140 Termios attr
; /* The terminal attributes */
9141 int waserr
= 0; /* True after any error */
9143 * Make sure that there is an inactivity timeout callback.
9148 * Re-enable conversion of newline characters to carriage-return/linefeed,
9149 * so that the callback can write to the terminal without having to do
9152 if(tcgetattr(gl
->input_fd
, &attr
)) {
9153 _err_record_msg(gl
->err
, "tcgetattr error", END_ERR_MSG
);
9156 attr
.c_oflag
|= OPOST
;
9157 while(tcsetattr(gl
->input_fd
, TCSADRAIN
, &attr
)) {
9158 if(errno
!= EINTR
) {
9159 _err_record_msg(gl
->err
, "tcsetattr error", END_ERR_MSG
);
9164 * Invoke the application's callback function.
9166 switch(gl
->timer
.fn(gl
, gl
->timer
.data
)) {
9169 gl_record_status(gl
, GLR_TIMEOUT
, 0);
9173 gl_queue_redisplay(gl
);
9179 * Disable conversion of newline characters to carriage-return/linefeed.
9181 attr
.c_oflag
&= ~(OPOST
);
9182 while(tcsetattr(gl
->input_fd
, TCSADRAIN
, &attr
)) {
9183 if(errno
!= EINTR
) {
9184 _err_record_msg(gl
->err
, "tcsetattr error", END_ERR_MSG
);
9190 #endif /* HAVE_SELECT */
9192 /*.......................................................................
9193 * Switch history groups. History groups represent separate history
9194 * lists recorded within a single history buffer. Different groups
9195 * are distinguished by integer identifiers chosen by the calling
9196 * appplicaton. Initially new_GetLine() sets the group identifier to
9197 * 0. Whenever a new line is appended to the history list, the current
9198 * group identifier is recorded with it, and history lookups only
9199 * consider lines marked with the current group identifier.
9202 * gl GetLine * The resource object of gl_get_line().
9203 * id unsigned The new history group identifier.
9205 * return int 0 - OK.
9208 int gl_group_history(GetLine
*gl
, unsigned id
)
9210 sigset_t oldset
; /* The signals that were blocked on entry to this function */
9211 int status
; /* The return status of this function */
9213 * Check the arguments.
9220 * Block all signals while we install the new configuration.
9222 if(gl_mask_signals(gl
, &oldset
))
9225 * If the group isn't being changed, do nothing.
9227 if(_glh_get_group(gl
->glh
) == id
) {
9230 * Establish the new group.
9232 } else if(_glh_set_group(gl
->glh
, id
)) {
9233 _err_record_msg(gl
->err
, _glh_last_error(gl
->glh
), END_ERR_MSG
);
9236 * Prevent history information from the previous group being
9237 * inappropriately used by the next call to gl_get_line().
9240 gl
->preload_history
= 0;
9241 gl
->last_search
= -1;
9245 * Restore the process signal mask.
9247 gl_unmask_signals(gl
, &oldset
);
9251 /*.......................................................................
9252 * Display the contents of the history list.
9255 * gl GetLine * The resource object of gl_get_line().
9256 * fp FILE * The stdio output stream to write to.
9257 * fmt const char * A format string. This containing characters to be
9258 * written verbatim, plus any of the following
9259 * format directives:
9260 * %D - The date, formatted like 2001-11-20
9261 * %T - The time of day, formatted like 23:59:59
9262 * %N - The sequential entry number of the
9263 * line in the history buffer.
9264 * %G - The number of the history group that
9265 * the line belongs to.
9266 * %% - A literal % character.
9267 * %H - The history line itself.
9268 * Note that a '\n' newline character is not
9269 * appended by default.
9270 * all_groups int If true, display history lines from all
9271 * history groups. Otherwise only display
9272 * those of the current history group.
9273 * max_lines int If max_lines is < 0, all available lines
9274 * are displayed. Otherwise only the most
9275 * recent max_lines lines will be displayed.
9277 * return int 0 - OK.
9280 int gl_show_history(GetLine
*gl
, FILE *fp
, const char *fmt
, int all_groups
,
9283 sigset_t oldset
; /* The signals that were blocked on entry to this function */
9284 int status
; /* The return status of this function */
9286 * Check the arguments.
9288 if(!gl
|| !fp
|| !fmt
) {
9290 _err_record_msg(gl
->err
, "NULL argument(s)", END_ERR_MSG
);
9295 * Block all signals.
9297 if(gl_mask_signals(gl
, &oldset
))
9300 * Display the specified history group(s) while signals are blocked.
9302 status
= _glh_show_history(gl
->glh
, _io_write_stdio
, fp
, fmt
, all_groups
,
9303 max_lines
) || fflush(fp
)==EOF
;
9305 _err_record_msg(gl
->err
, _glh_last_error(gl
->glh
), END_ERR_MSG
);
9307 * Restore the process signal mask.
9309 gl_unmask_signals(gl
, &oldset
);
9313 /*.......................................................................
9314 * Update if necessary, and return the current size of the terminal.
9317 * gl GetLine * The resource object of gl_get_line().
9318 * def_ncolumn int If the number of columns in the terminal
9319 * can't be determined, substitute this number.
9320 * def_nline int If the number of lines in the terminal can't
9321 * be determined, substitute this number.
9323 * return GlTerminalSize The current terminal size.
9325 GlTerminalSize
gl_terminal_size(GetLine
*gl
, int def_ncolumn
, int def_nline
)
9327 GlTerminalSize size
; /* The object to be returned */
9328 sigset_t oldset
; /* The signals that were blocked on entry */
9329 /* to this function */
9331 * Block all signals while accessing gl.
9333 gl_mask_signals(gl
, &oldset
);
9335 * Lookup/configure the terminal size.
9337 _gl_terminal_size(gl
, def_ncolumn
, def_nline
, &size
);
9339 * Restore the process signal mask before returning.
9341 gl_unmask_signals(gl
, &oldset
);
9345 /*.......................................................................
9346 * This is the private body of the gl_terminal_size() function. It
9347 * assumes that the caller has checked its arguments and blocked the
9348 * delivery of signals.
9350 static void _gl_terminal_size(GetLine
*gl
, int def_ncolumn
, int def_nline
,
9351 GlTerminalSize
*size
)
9353 const char *env
; /* The value of an environment variable */
9354 int n
; /* A number read from env[] */
9356 * Set the number of lines and columns to non-sensical values so that
9357 * we know later if they have been set.
9362 * Are we reading from a terminal?
9366 * Ask the terminal directly if possible.
9368 (void) _gl_update_size(gl
);
9370 * If gl_update_size() couldn't ask the terminal, it will have
9371 * left gl->nrow and gl->ncolumn unchanged. If these values haven't
9372 * been changed from their initial values of zero, we need to find
9373 * a different method to get the terminal size.
9375 * If the number of lines isn't known yet, first see if the
9376 * LINES environment ariable exists and specifies a believable number.
9377 * If this doesn't work, look up the default size in the terminal
9378 * information database.
9381 if((env
= getenv("LINES")) && (n
=atoi(env
)) > 0)
9385 gl
->nline
= tigetnum((char *)"lines");
9386 #elif defined(USE_TERMCAP)
9388 gl
->nline
= tgetnum("li");
9392 * If the number of lines isn't known yet, first see if the COLUMNS
9393 * environment ariable exists and specifies a believable number. If
9394 * this doesn't work, look up the default size in the terminal
9395 * information database.
9397 if(gl
->ncolumn
< 1) {
9398 if((env
= getenv("COLUMNS")) && (n
=atoi(env
)) > 0)
9402 gl
->ncolumn
= tigetnum((char *)"cols");
9403 #elif defined(USE_TERMCAP)
9405 gl
->ncolumn
= tgetnum("co");
9410 * If we still haven't been able to acquire reasonable values, substitute
9411 * the default values specified by the caller.
9414 gl
->nline
= def_nline
;
9415 if(gl
->ncolumn
<= 0)
9416 gl
->ncolumn
= def_ncolumn
;
9418 * Copy the new size into the return value.
9421 size
->nline
= gl
->nline
;
9422 size
->ncolumn
= gl
->ncolumn
;
9427 /*.......................................................................
9428 * Resize or delete the history buffer.
9431 * gl GetLine * The resource object of gl_get_line().
9432 * bufsize size_t The number of bytes in the history buffer, or 0
9433 * to delete the buffer completely.
9435 * return int 0 - OK.
9436 * 1 - Insufficient memory (the previous buffer
9437 * will have been retained). No error message
9438 * will be displayed.
9440 int gl_resize_history(GetLine
*gl
, size_t bufsize
)
9442 sigset_t oldset
; /* The signals that were blocked on entry to this function */
9443 int status
; /* The return status of this function */
9445 * Check the arguments.
9450 * Block all signals while modifying the contents of gl.
9452 if(gl_mask_signals(gl
, &oldset
))
9455 * Perform the resize while signals are blocked.
9457 status
= _glh_resize_history(gl
->glh
, bufsize
);
9459 _err_record_msg(gl
->err
, _glh_last_error(gl
->glh
), END_ERR_MSG
);
9461 * Restore the process signal mask before returning.
9463 gl_unmask_signals(gl
, &oldset
);
9467 /*.......................................................................
9468 * Set an upper limit to the number of lines that can be recorded in the
9469 * history list, or remove a previously specified limit.
9472 * gl GetLine * The resource object of gl_get_line().
9473 * max_lines int The maximum number of lines to allow, or -1 to
9474 * cancel a previous limit and allow as many lines
9475 * as will fit in the current history buffer size.
9477 void gl_limit_history(GetLine
*gl
, int max_lines
)
9480 sigset_t oldset
; /* The signals that were blocked on entry to this block */
9482 * Temporarily block all signals.
9484 gl_mask_signals(gl
, &oldset
);
9486 * Apply the limit while signals are blocked.
9488 _glh_limit_history(gl
->glh
, max_lines
);
9490 * Restore the process signal mask before returning.
9492 gl_unmask_signals(gl
, &oldset
);
9496 /*.......................................................................
9497 * Discard either all historical lines, or just those associated with the
9498 * current history group.
9501 * gl GetLine * The resource object of gl_get_line().
9502 * all_groups int If true, clear all of the history. If false,
9503 * clear only the stored lines associated with the
9504 * currently selected history group.
9506 void gl_clear_history(GetLine
*gl
, int all_groups
)
9509 sigset_t oldset
; /* The signals that were blocked on entry to this block */
9511 * Temporarily block all signals.
9513 gl_mask_signals(gl
, &oldset
);
9515 * Clear the history buffer while signals are blocked.
9517 _glh_clear_history(gl
->glh
, all_groups
);
9519 * Restore the process signal mask before returning.
9521 gl_unmask_signals(gl
, &oldset
);
9525 /*.......................................................................
9526 * Temporarily enable or disable the gl_get_line() history mechanism.
9529 * gl GetLine * The resource object of gl_get_line().
9530 * enable int If true, turn on the history mechanism. If
9531 * false, disable it.
9533 void gl_toggle_history(GetLine
*gl
, int enable
)
9536 sigset_t oldset
; /* The signals that were blocked on entry to this block */
9538 * Temporarily block all signals.
9540 gl_mask_signals(gl
, &oldset
);
9542 * Change the history recording mode while signals are blocked.
9544 _glh_toggle_history(gl
->glh
, enable
);
9546 * Restore the process signal mask before returning.
9548 gl_unmask_signals(gl
, &oldset
);
9552 /*.......................................................................
9553 * Lookup a history line by its sequential number of entry in the
9557 * gl GetLine * The resource object of gl_get_line().
9558 * id unsigned long The identification number of the line to
9559 * be returned, where 0 denotes the first line
9560 * that was entered in the history list, and
9561 * each subsequently added line has a number
9562 * one greater than the previous one. For
9563 * the range of lines currently in the list,
9564 * see the gl_range_of_history() function.
9566 * line GlHistoryLine * A pointer to the variable in which to
9567 * return the details of the line.
9569 * return int 0 - The line is no longer in the history
9570 * list, and *line has not been changed.
9571 * 1 - The requested line can be found in
9572 * *line. Note that line->line is part
9573 * of the history buffer, so a
9574 * private copy should be made if you
9575 * wish to use it after subsequent calls
9576 * to any functions that take *gl as an
9579 int gl_lookup_history(GetLine
*gl
, unsigned long id
, GlHistoryLine
*line
)
9581 sigset_t oldset
; /* The signals that were blocked on entry to this function */
9582 int status
; /* The return status of this function */
9584 * Check the arguments.
9589 * Block all signals while modifying the contents of gl.
9591 if(gl_mask_signals(gl
, &oldset
))
9594 * Perform the lookup while signals are blocked.
9596 status
= _glh_lookup_history(gl
->glh
, (GlhLineID
) id
, &line
->line
,
9597 &line
->group
, &line
->timestamp
);
9599 _err_record_msg(gl
->err
, _glh_last_error(gl
->glh
), END_ERR_MSG
);
9601 * Restore the process signal mask before returning.
9603 gl_unmask_signals(gl
, &oldset
);
9607 /*.......................................................................
9608 * Query the state of the history list. Note that any of the input/output
9609 * pointers can be specified as NULL.
9612 * gl GetLine * The resource object of gl_get_line().
9614 * state GlHistoryState * A pointer to the variable in which to record
9615 * the return values.
9617 void gl_state_of_history(GetLine
*gl
, GlHistoryState
*state
)
9620 sigset_t oldset
; /* The signals that were blocked on entry to this block */
9622 * Temporarily block all signals.
9624 gl_mask_signals(gl
, &oldset
);
9626 * Lookup the status while signals are blocked.
9628 _glh_state_of_history(gl
->glh
, &state
->enabled
, &state
->group
,
9631 * Restore the process signal mask before returning.
9633 gl_unmask_signals(gl
, &oldset
);
9637 /*.......................................................................
9638 * Query the number and range of lines in the history buffer.
9641 * gl GetLine * The resource object of gl_get_line().
9642 * range GlHistoryRange * A pointer to the variable in which to record
9643 * the return values. If range->nline=0, the
9644 * range of lines will be given as 0-0.
9646 void gl_range_of_history(GetLine
*gl
, GlHistoryRange
*range
)
9649 sigset_t oldset
; /* The signals that were blocked on entry to this block */
9651 * Temporarily block all signals.
9653 gl_mask_signals(gl
, &oldset
);
9655 * Lookup the information while signals are blocked.
9657 _glh_range_of_history(gl
->glh
, &range
->oldest
, &range
->newest
,
9660 * Restore the process signal mask before returning.
9662 gl_unmask_signals(gl
, &oldset
);
9666 /*.......................................................................
9667 * Return the size of the history buffer and the amount of the
9668 * buffer that is currently in use.
9671 * gl GetLine * The gl_get_line() resource object.
9673 * GlHistorySize size * A pointer to the variable in which to return
9676 void gl_size_of_history(GetLine
*gl
, GlHistorySize
*size
)
9679 sigset_t oldset
; /* The signals that were blocked on entry to this block */
9681 * Temporarily block all signals.
9683 gl_mask_signals(gl
, &oldset
);
9685 * Lookup the information while signals are blocked.
9687 _glh_size_of_history(gl
->glh
, &size
->size
, &size
->used
);
9689 * Restore the process signal mask before returning.
9691 gl_unmask_signals(gl
, &oldset
);
9695 /*.......................................................................
9696 * This is the action function that lists the contents of the history
9699 static KT_KEY_FN(gl_list_history
)
9704 if(gl_start_newline(gl
, 1))
9707 * List history lines that belong to the current group.
9709 _glh_show_history(gl
->glh
, gl_write_fn
, gl
, "%N %T %H\r\n", 0,
9710 count
<=1 ? -1 : count
);
9712 * Arrange for the input line to be redisplayed.
9714 gl_queue_redisplay(gl
);
9718 /*.......................................................................
9719 * Specify whether text that users type should be displayed or hidden.
9720 * In the latter case, only the prompt is displayed, and the final
9721 * input line is not archived in the history list.
9724 * gl GetLine * The gl_get_line() resource object.
9725 * enable int 0 - Disable echoing.
9726 * 1 - Enable echoing.
9727 * -1 - Just query the mode without changing it.
9729 * return int The echoing disposition that was in effect
9730 * before this function was called:
9731 * 0 - Echoing was disabled.
9732 * 1 - Echoing was enabled.
9734 int gl_echo_mode(GetLine
*gl
, int enable
)
9737 sigset_t oldset
; /* The signals that were blocked on entry to this block */
9738 int was_echoing
; /* The echoing disposition on entry to this function */
9740 * Temporarily block all signals.
9742 gl_mask_signals(gl
, &oldset
);
9744 * Install the new disposition while signals are blocked.
9746 was_echoing
= gl
->echo
;
9750 * Restore the process signal mask before returning.
9752 gl_unmask_signals(gl
, &oldset
);
9754 * Return the original echoing disposition.
9761 /*.......................................................................
9762 * Display the prompt.
9765 * gl GetLine * The resource object of gl_get_line().
9767 * return int 0 - OK.
9770 static int gl_display_prompt(GetLine
*gl
)
9772 const char *pptr
; /* A pointer into gl->prompt[] */
9773 unsigned old_attr
=0; /* The current text display attributes */
9774 unsigned new_attr
=0; /* The requested text display attributes */
9776 * Temporarily switch to echoing output characters.
9778 int kept_echo
= gl
->echo
;
9781 * In case the screen got messed up, send a carriage return to
9782 * put the cursor at the beginning of the current terminal line.
9784 if(gl_print_control_sequence(gl
, 1, gl
->bol
))
9787 * Mark the line as partially displayed.
9791 * Write the prompt, using the currently selected prompt style.
9793 switch(gl
->prompt_style
) {
9794 case GL_LITERAL_PROMPT
:
9795 if(gl_print_string(gl
, gl
->prompt
, '\0'))
9798 case GL_FORMAT_PROMPT
:
9799 for(pptr
=gl
->prompt
; *pptr
; pptr
++) {
9801 * Does the latest character appear to be the start of a directive?
9805 * Check for and act on attribute changing directives.
9809 * Add or remove a text attribute from the new set of attributes.
9811 case 'B': case 'U': case 'S': case 'P': case 'F': case 'V':
9812 case 'b': case 'u': case 's': case 'p': case 'f': case 'v':
9814 case 'B': /* Switch to a bold font */
9815 new_attr
|= GL_TXT_BOLD
;
9817 case 'b': /* Switch to a non-bold font */
9818 new_attr
&= ~GL_TXT_BOLD
;
9820 case 'U': /* Start underlining */
9821 new_attr
|= GL_TXT_UNDERLINE
;
9823 case 'u': /* Stop underlining */
9824 new_attr
&= ~GL_TXT_UNDERLINE
;
9826 case 'S': /* Start highlighting */
9827 new_attr
|= GL_TXT_STANDOUT
;
9829 case 's': /* Stop highlighting */
9830 new_attr
&= ~GL_TXT_STANDOUT
;
9832 case 'P': /* Switch to a pale font */
9833 new_attr
|= GL_TXT_DIM
;
9835 case 'p': /* Switch to a non-pale font */
9836 new_attr
&= ~GL_TXT_DIM
;
9838 case 'F': /* Switch to a flashing font */
9839 new_attr
|= GL_TXT_BLINK
;
9841 case 'f': /* Switch to a steady font */
9842 new_attr
&= ~GL_TXT_BLINK
;
9844 case 'V': /* Switch to reverse video */
9845 new_attr
|= GL_TXT_REVERSE
;
9847 case 'v': /* Switch out of reverse video */
9848 new_attr
&= ~GL_TXT_REVERSE
;
9853 * A literal % is represented by %%. Skip the leading %.
9861 * Many terminals, when asked to turn off a single text attribute, turn
9862 * them all off, so the portable way to turn one off individually is to
9863 * explicitly turn them all off, then specify those that we want from
9866 if(old_attr
& ~new_attr
) {
9867 if(gl_print_control_sequence(gl
, 1, gl
->text_attr_off
))
9872 * Install new text attributes?
9874 if(new_attr
!= old_attr
) {
9875 if(new_attr
& GL_TXT_BOLD
&& !(old_attr
& GL_TXT_BOLD
) &&
9876 gl_print_control_sequence(gl
, 1, gl
->bold
))
9878 if(new_attr
& GL_TXT_UNDERLINE
&& !(old_attr
& GL_TXT_UNDERLINE
) &&
9879 gl_print_control_sequence(gl
, 1, gl
->underline
))
9881 if(new_attr
& GL_TXT_STANDOUT
&& !(old_attr
& GL_TXT_STANDOUT
) &&
9882 gl_print_control_sequence(gl
, 1, gl
->standout
))
9884 if(new_attr
& GL_TXT_DIM
&& !(old_attr
& GL_TXT_DIM
) &&
9885 gl_print_control_sequence(gl
, 1, gl
->dim
))
9887 if(new_attr
& GL_TXT_REVERSE
&& !(old_attr
& GL_TXT_REVERSE
) &&
9888 gl_print_control_sequence(gl
, 1, gl
->reverse
))
9890 if(new_attr
& GL_TXT_BLINK
&& !(old_attr
& GL_TXT_BLINK
) &&
9891 gl_print_control_sequence(gl
, 1, gl
->blink
))
9893 old_attr
= new_attr
;
9896 * Display the latest character.
9898 if(gl_print_char(gl
, *pptr
, pptr
[1]))
9902 * Turn off all text attributes now that we have finished drawing
9905 if(gl_print_control_sequence(gl
, 1, gl
->text_attr_off
))
9910 * Restore the original echo mode.
9912 gl
->echo
= kept_echo
;
9914 * The prompt has now been displayed at least once.
9916 gl
->prompt_changed
= 0;
9920 /*.......................................................................
9921 * This function can be called from gl_get_line() callbacks to have
9922 * the prompt changed when they return. It has no effect if gl_get_line()
9923 * is not currently being invoked.
9926 * gl GetLine * The resource object of gl_get_line().
9927 * prompt const char * The new prompt.
9929 void gl_replace_prompt(GetLine
*gl
, const char *prompt
)
9932 sigset_t oldset
; /* The signals that were blocked on entry to this block */
9934 * Temporarily block all signals.
9936 gl_mask_signals(gl
, &oldset
);
9938 * Replace the prompt.
9940 _gl_replace_prompt(gl
, prompt
);
9942 * Restore the process signal mask before returning.
9944 gl_unmask_signals(gl
, &oldset
);
9948 /*.......................................................................
9949 * This is the private body of the gl_replace_prompt() function. It
9950 * assumes that the caller has checked its arguments and blocked the
9951 * delivery of signals.
9953 static void _gl_replace_prompt(GetLine
*gl
, const char *prompt
)
9958 * Substitute an empty prompt?
9963 * Gaurd against aliasing between prompt and gl->prompt.
9965 if(gl
->prompt
!= prompt
) {
9967 * Get the length of the new prompt string.
9969 size_t slen
= strlen(prompt
);
9971 * If needed, allocate a new buffer for the prompt string.
9973 size
= sizeof(char) * (slen
+ 1);
9974 if(!gl
->prompt
|| slen
> strlen(gl
->prompt
)) {
9975 char *new_prompt
= gl
->prompt
? realloc(gl
->prompt
, size
) : malloc(size
);
9978 gl
->prompt
= new_prompt
;
9981 * Make a copy of the new prompt.
9983 strlcpy(gl
->prompt
, prompt
, size
);
9986 * Record the statistics of the new prompt.
9988 gl
->prompt_len
= gl_displayed_prompt_width(gl
);
9989 gl
->prompt_changed
= 1;
9990 gl_queue_redisplay(gl
);
9994 /*.......................................................................
9995 * Work out the length of the current prompt on the terminal, according
9996 * to the current prompt formatting style.
9999 * gl GetLine * The resource object of this library.
10001 * return int The number of displayed characters.
10003 static int gl_displayed_prompt_width(GetLine
*gl
)
10005 int slen
=0; /* The displayed number of characters */
10006 const char *pptr
; /* A pointer into prompt[] */
10008 * The length differs according to the prompt display style.
10010 switch(gl
->prompt_style
) {
10011 case GL_LITERAL_PROMPT
:
10012 return gl_displayed_string_width(gl
, gl
->prompt
, -1, 0);
10014 case GL_FORMAT_PROMPT
:
10016 * Add up the length of the displayed string, while filtering out
10017 * attribute directives.
10019 for(pptr
=gl
->prompt
; *pptr
; pptr
++) {
10021 * Does the latest character appear to be the start of a directive?
10025 * Check for and skip attribute changing directives.
10028 case 'B': case 'b': case 'U': case 'u': case 'S': case 's':
10032 * A literal % is represented by %%. Skip the leading %.
10039 slen
+= gl_displayed_char_width(gl
, *pptr
, slen
);
10046 /*.......................................................................
10047 * Specify whether to heed text attribute directives within prompt
10051 * gl GetLine * The resource object of gl_get_line().
10052 * style GlPromptStyle The style of prompt (see the definition of
10053 * GlPromptStyle in libtecla.h for details).
10055 void gl_prompt_style(GetLine
*gl
, GlPromptStyle style
)
10058 sigset_t oldset
; /* The signals that were blocked on entry to this block */
10060 * Temporarily block all signals.
10062 gl_mask_signals(gl
, &oldset
);
10064 * Install the new style in gl while signals are blocked.
10066 if(style
!= gl
->prompt_style
) {
10067 gl
->prompt_style
= style
;
10068 gl
->prompt_len
= gl_displayed_prompt_width(gl
);
10069 gl
->prompt_changed
= 1;
10070 gl_queue_redisplay(gl
);
10073 * Restore the process signal mask before returning.
10075 gl_unmask_signals(gl
, &oldset
);
10079 /*.......................................................................
10080 * Tell gl_get_line() how to respond to a given signal. This can be used
10081 * both to override the default responses to signals that gl_get_line()
10082 * normally catches and to add new signals to the list that are to be
10086 * gl GetLine * The resource object of gl_get_line().
10087 * signo int The number of the signal to be caught.
10088 * flags unsigned A bitwise union of GlSignalFlags enumerators.
10089 * after GlAfterSignal What to do after the application's signal
10090 * handler has been called.
10091 * errno_value int The value to set errno to.
10093 * return int 0 - OK.
10096 int gl_trap_signal(GetLine
*gl
, int signo
, unsigned flags
,
10097 GlAfterSignal after
, int errno_value
)
10099 sigset_t oldset
; /* The signals that were blocked on entry to this function */
10100 int status
; /* The return status of this function */
10102 * Check the arguments.
10109 * Block all signals while modifying the contents of gl.
10111 if(gl_mask_signals(gl
, &oldset
))
10114 * Perform the modification while signals are blocked.
10116 status
= _gl_trap_signal(gl
, signo
, flags
, after
, errno_value
);
10118 * Restore the process signal mask before returning.
10120 gl_unmask_signals(gl
, &oldset
);
10124 /*.......................................................................
10125 * This is the private body of the gl_trap_signal() function. It
10126 * assumes that the caller has checked its arguments and blocked the
10127 * delivery of signals.
10129 static int _gl_trap_signal(GetLine
*gl
, int signo
, unsigned flags
,
10130 GlAfterSignal after
, int errno_value
)
10134 * Complain if an attempt is made to trap untrappable signals.
10135 * These would otherwise cause errors later in gl_mask_signals().
10148 * See if the signal has already been registered.
10150 for(sig
=gl
->sigs
; sig
&& sig
->signo
!= signo
; sig
= sig
->next
)
10153 * If the signal hasn't already been registered, allocate a node for
10157 sig
= (GlSignalNode
*) _new_FreeListNode(gl
->sig_mem
);
10161 * Add the new node to the head of the list.
10163 sig
->next
= gl
->sigs
;
10166 * Record the signal number.
10168 sig
->signo
= signo
;
10170 * Create a signal set that includes just this signal.
10172 sigemptyset(&sig
->proc_mask
);
10173 if(sigaddset(&sig
->proc_mask
, signo
) == -1) {
10174 _err_record_msg(gl
->err
, "sigaddset error", END_ERR_MSG
);
10175 sig
= (GlSignalNode
*) _del_FreeListNode(gl
->sig_mem
, sig
);
10179 * Add the signal to the bit-mask of signals being trapped.
10181 sigaddset(&gl
->all_signal_set
, signo
);
10184 * Record the new signal attributes.
10186 sig
->flags
= flags
;
10187 sig
->after
= after
;
10188 sig
->errno_value
= errno_value
;
10192 /*.......................................................................
10193 * Remove a signal from the list of signals that gl_get_line() traps.
10196 * gl GetLine * The resource object of gl_get_line().
10197 * signo int The number of the signal to be ignored.
10199 * return int 0 - OK.
10202 int gl_ignore_signal(GetLine
*gl
, int signo
)
10204 GlSignalNode
*sig
; /* The gl->sigs list node of the specified signal */
10205 GlSignalNode
*prev
; /* The node that precedes sig in the list */
10206 sigset_t oldset
; /* The signals that were blocked on entry to this */
10209 * Check the arguments.
10216 * Block all signals while modifying the contents of gl.
10218 if(gl_mask_signals(gl
, &oldset
))
10221 * Find the node of the gl->sigs list which records the disposition
10222 * of the specified signal.
10224 for(prev
=NULL
,sig
=gl
->sigs
; sig
&& sig
->signo
!= signo
;
10225 prev
=sig
,sig
=sig
->next
)
10229 * Remove the node from the list.
10232 prev
->next
= sig
->next
;
10234 gl
->sigs
= sig
->next
;
10236 * Return the node to the freelist.
10238 sig
= (GlSignalNode
*) _del_FreeListNode(gl
->sig_mem
, sig
);
10240 * Remove the signal from the bit-mask union of signals being trapped.
10242 sigdelset(&gl
->all_signal_set
, signo
);
10245 * Restore the process signal mask before returning.
10247 gl_unmask_signals(gl
, &oldset
);
10251 /*.......................................................................
10252 * This function is called when an input line has been completed. It
10253 * appends the specified newline character, terminates the line,
10254 * records the line in the history buffer if appropriate, and positions
10255 * the terminal cursor at the start of the next line.
10258 * gl GetLine * The resource object of gl_get_line().
10259 * newline_char int The newline character to add to the end
10262 * return int 0 - OK.
10265 static int gl_line_ended(GetLine
*gl
, int newline_char
)
10268 * If the newline character is printable, display it at the end of
10269 * the line, and add it to the input line buffer.
10271 if(isprint((int)(unsigned char) newline_char
)) {
10272 if(gl_end_of_line(gl
, 1, NULL
) || gl_add_char_to_line(gl
, newline_char
))
10276 * Otherwise just append a newline character to the input line buffer.
10278 newline_char
= '\n';
10279 gl_buffer_char(gl
, newline_char
, gl
->ntotal
);
10282 * Add the line to the history buffer if it was entered with a
10283 * newline character.
10285 if(gl
->echo
&& gl
->automatic_history
&& newline_char
=='\n')
10286 (void) _gl_append_history(gl
, gl
->line
);
10288 * Except when depending on the system-provided line editing, start a new
10289 * line after the end of the line that has just been entered.
10291 if(gl
->editor
!= GL_NO_EDITOR
&& gl_start_newline(gl
, 1))
10294 * Record the successful return status.
10296 gl_record_status(gl
, GLR_NEWLINE
, 0);
10298 * Attempt to flush any pending output.
10300 (void) gl_flush_output(gl
);
10302 * The next call to gl_get_line() will write the prompt for a new line
10303 * (or continue the above flush if incomplete), so if we manage to
10304 * flush the terminal now, report that we are waiting to write to the
10307 gl
->pending_io
= GLP_WRITE
;
10311 /*.......................................................................
10312 * Return the last signal that was caught by the most recent call to
10313 * gl_get_line(), or -1 if no signals were caught. This is useful if
10314 * gl_get_line() returns errno=EINTR and you need to find out what signal
10315 * caused it to abort.
10318 * gl GetLine * The resource object of gl_get_line().
10320 * return int The last signal caught by the most recent
10321 * call to gl_get_line(), or -1 if no signals
10324 int gl_last_signal(GetLine
*gl
)
10326 int signo
= -1; /* The requested signal number */
10328 sigset_t oldset
; /* The signals that were blocked on entry to this block */
10330 * Temporarily block all signals.
10332 gl_mask_signals(gl
, &oldset
);
10334 * Access gl now that signals are blocked.
10336 signo
= gl
->last_signal
;
10338 * Restore the process signal mask before returning.
10340 gl_unmask_signals(gl
, &oldset
);
10345 /*.......................................................................
10346 * Prepare to edit a new line.
10349 * gl GetLine * The resource object of this library.
10350 * prompt char * The prompt to prefix the line with, or NULL to
10351 * use the same prompt that was used by the previous
10353 * start_line char * The initial contents of the input line, or NULL
10354 * if it should start out empty.
10355 * start_pos int If start_line isn't NULL, this specifies the
10356 * index of the character over which the cursor
10357 * should initially be positioned within the line.
10358 * If you just want it to follow the last character
10359 * of the line, send -1.
10361 * return int 0 - OK.
10364 static int gl_present_line(GetLine
*gl
, const char *prompt
,
10365 const char *start_line
, int start_pos
)
10368 * Reset the properties of the line.
10370 gl_reset_input_line(gl
);
10372 * Record the new prompt and its displayed width.
10375 _gl_replace_prompt(gl
, prompt
);
10377 * Reset the history search pointers.
10379 if(_glh_cancel_search(gl
->glh
)) {
10380 _err_record_msg(gl
->err
, _glh_last_error(gl
->glh
), END_ERR_MSG
);
10384 * If the previous line was entered via the repeat-history action,
10385 * preload the specified history line.
10387 if(gl
->preload_history
) {
10388 gl
->preload_history
= 0;
10389 if(gl
->preload_id
) {
10390 if(_glh_recall_line(gl
->glh
, gl
->preload_id
, gl
->line
, gl
->linelen
+1)) {
10391 gl_update_buffer(gl
); /* Compute gl->ntotal etc.. */
10392 gl
->buff_curpos
= gl
->ntotal
;
10394 gl_truncate_buffer(gl
, 0);
10396 gl
->preload_id
= 0;
10399 * Present a specified initial line?
10401 } else if(start_line
) {
10402 char *cptr
; /* A pointer into gl->line[] */
10404 * Measure the length of the starting line.
10406 int start_len
= strlen(start_line
);
10408 * If the length of the line is greater than the available space,
10411 if(start_len
> gl
->linelen
)
10412 start_len
= gl
->linelen
;
10414 * Load the line into the buffer.
10416 if(start_line
!= gl
->line
)
10417 gl_buffer_string(gl
, start_line
, start_len
, 0);
10419 * Strip off any trailing newline and carriage return characters.
10421 for(cptr
=gl
->line
+ gl
->ntotal
- 1; cptr
>= gl
->line
&&
10422 (*cptr
=='\n' || *cptr
=='\r'); cptr
--,gl
->ntotal
--)
10424 gl_truncate_buffer(gl
, gl
->ntotal
< 0 ? 0 : gl
->ntotal
);
10426 * Where should the cursor be placed within the line?
10428 if(start_pos
< 0 || start_pos
> gl
->ntotal
) {
10429 if(gl_place_cursor(gl
, gl
->ntotal
))
10432 if(gl_place_cursor(gl
, start_pos
))
10436 * Clear the input line?
10439 gl_truncate_buffer(gl
, 0);
10442 * Arrange for the line to be displayed by gl_flush_output().
10444 gl_queue_redisplay(gl
);
10446 * Update the display.
10448 return gl_flush_output(gl
);
10451 /*.......................................................................
10452 * Reset all line input parameters for a new input line.
10455 * gl GetLine * The line editor resource object.
10457 static void gl_reset_input_line(GetLine
*gl
)
10460 gl
->line
[0] = '\0';
10461 gl
->buff_curpos
= 0;
10462 gl
->term_curpos
= 0;
10464 gl
->insert_curpos
= 0;
10472 gl
->vi
.command
= 0;
10473 gl
->vi
.undo
.line
[0] = '\0';
10474 gl
->vi
.undo
.ntotal
= 0;
10475 gl
->vi
.undo
.buff_curpos
= 0;
10476 gl
->vi
.repeat
.action
.fn
= 0;
10477 gl
->vi
.repeat
.action
.data
= 0;
10478 gl
->last_signal
= -1;
10481 /*.......................................................................
10482 * Print an informational message to the terminal, after starting a new
10486 * gl GetLine * The line editor resource object.
10487 * ... const char * Zero or more strings to be printed.
10488 * ... void * The last argument must always be GL_END_INFO.
10490 * return int 0 - OK.
10493 static int gl_print_info(GetLine
*gl
, ...)
10495 va_list ap
; /* The variable argument list */
10496 const char *s
; /* The string being printed */
10497 int waserr
= 0; /* True after an error */
10499 * Only display output when echoing is on.
10503 * Skip to the start of the next empty line before displaying the message.
10505 if(gl_start_newline(gl
, 1))
10508 * Display the list of provided messages.
10511 while(!waserr
&& (s
= va_arg(ap
, const char *)) != GL_END_INFO
)
10512 waserr
= gl_print_raw_string(gl
, 1, s
, -1);
10517 waserr
= waserr
|| gl_print_raw_string(gl
, 1, "\n\r", -1);
10519 * Arrange for the input line to be redrawn.
10521 gl_queue_redisplay(gl
);
10526 /*.......................................................................
10527 * Go to the start of the next empty line, ready to output miscellaneous
10528 * text to the screen.
10530 * Note that when async-signal safety is required, the 'buffered'
10531 * argument must be 0.
10534 * gl GetLine * The line editor resource object.
10535 * buffered int If true, used buffered I/O when writing to
10536 * the terminal. Otherwise use async-signal-safe
10539 * return int 0 - OK.
10542 static int gl_start_newline(GetLine
*gl
, int buffered
)
10544 int waserr
= 0; /* True after any I/O error */
10546 * Move the cursor to the start of the terminal line that follows the
10547 * last line of the partially enterred line. In order that this
10548 * function remain async-signal safe when write_fn is signal safe, we
10549 * can't call our normal output functions, since they call tputs(),
10550 * who's signal saftey isn't defined. Fortunately, we can simply use
10551 * \r and \n to move the cursor to the right place.
10553 if(gl
->displayed
) { /* Is an input line currently displayed? */
10555 * On which terminal lines are the cursor and the last character of the
10558 int curs_line
= gl
->term_curpos
/ gl
->ncolumn
;
10559 int last_line
= gl
->term_len
/ gl
->ncolumn
;
10561 * Move the cursor to the start of the line that follows the last
10562 * terminal line that is occupied by the input line.
10564 for( ; curs_line
< last_line
+ 1; curs_line
++)
10565 waserr
= waserr
|| gl_print_raw_string(gl
, buffered
, "\n", 1);
10566 waserr
= waserr
|| gl_print_raw_string(gl
, buffered
, "\r", 1);
10568 * Mark the line as no longer displayed.
10570 gl_line_erased(gl
);
10575 /*.......................................................................
10576 * The callback through which all terminal output is routed.
10577 * This simply appends characters to a queue buffer, which is
10578 * subsequently flushed to the output channel by gl_flush_output().
10581 * data void * The pointer to a GetLine line editor resource object
10582 * cast to (void *).
10583 * s const char * The string to be written.
10584 * n int The number of characters to write from s[].
10586 * return int The number of characters written. This will always
10587 * be equal to 'n' unless an error occurs.
10589 static GL_WRITE_FN(gl_write_fn
)
10591 GetLine
*gl
= (GetLine
*) data
;
10592 int ndone
= _glq_append_chars(gl
->cq
, s
, n
, gl
->flush_fn
, gl
);
10594 _err_record_msg(gl
->err
, _glq_last_error(gl
->cq
), END_ERR_MSG
);
10598 /*.......................................................................
10599 * Ask gl_get_line() what caused it to return.
10602 * gl GetLine * The line editor resource object.
10604 * return GlReturnStatus The return status of the last call to
10607 GlReturnStatus
gl_return_status(GetLine
*gl
)
10609 GlReturnStatus rtn_status
= GLR_ERROR
; /* The requested status */
10611 sigset_t oldset
; /* The signals that were blocked on entry to this block */
10613 * Temporarily block all signals.
10615 gl_mask_signals(gl
, &oldset
);
10617 * Access gl while signals are blocked.
10619 rtn_status
= gl
->rtn_status
;
10621 * Restore the process signal mask before returning.
10623 gl_unmask_signals(gl
, &oldset
);
10628 /*.......................................................................
10629 * In non-blocking server-I/O mode, this function should be called
10630 * from the application's external event loop to see what type of
10631 * terminal I/O is being waited for by gl_get_line(), and thus what
10632 * direction of I/O to wait for with select() or poll().
10635 * gl GetLine * The resource object of gl_get_line().
10637 * return GlPendingIO The type of pending I/O being waited for.
10639 GlPendingIO
gl_pending_io(GetLine
*gl
)
10641 GlPendingIO pending_io
= GLP_WRITE
; /* The requested information */
10643 sigset_t oldset
; /* The signals that were blocked on entry to this block */
10645 * Temporarily block all signals.
10647 gl_mask_signals(gl
, &oldset
);
10649 * Access gl while signals are blocked.
10651 pending_io
= gl
->pending_io
;
10653 * Restore the process signal mask before returning.
10655 gl_unmask_signals(gl
, &oldset
);
10660 /*.......................................................................
10661 * In server mode, this function configures the terminal for non-blocking
10662 * raw terminal I/O. In normal I/O mode it does nothing.
10664 * Callers of this function must be careful to trap all signals that
10665 * terminate or suspend the program, and call gl_normal_io()
10666 * from the corresponding signal handlers in order to restore the
10667 * terminal to its original settings before the program is terminated
10668 * or suspended. They should also trap the SIGCONT signal to detect
10669 * when the program resumes, and ensure that its signal handler
10670 * call gl_raw_io() to redisplay the line and resume editing.
10672 * This function is async signal safe.
10675 * gl GetLine * The line editor resource object.
10677 * return int 0 - OK.
10680 int gl_raw_io(GetLine
*gl
)
10682 sigset_t oldset
; /* The signals that were blocked on entry to this function */
10683 int status
; /* The return status of _gl_raw_io() */
10685 * Check the arguments.
10692 * Block all signals.
10694 if(gl_mask_signals(gl
, &oldset
))
10697 * Don't allow applications to switch into raw mode unless in server mode.
10699 if(gl
->io_mode
!= GL_SERVER_MODE
) {
10700 _err_record_msg(gl
->err
, "Can't switch to raw I/O unless in server mode",
10706 * Execute the private body of the function while signals are blocked.
10708 status
= _gl_raw_io(gl
, 1);
10711 * Restore the process signal mask.
10713 gl_unmask_signals(gl
, &oldset
);
10717 /*.......................................................................
10718 * This is the private body of the public function, gl_raw_io().
10719 * It assumes that the caller has checked its arguments and blocked the
10720 * delivery of signals.
10722 * This function is async signal safe.
10724 static int _gl_raw_io(GetLine
*gl
, int redisplay
)
10727 * If we are already in the correct mode, do nothing.
10732 * Switch the terminal to raw mode.
10734 if(gl
->is_term
&& gl_raw_terminal_mode(gl
))
10737 * Switch to non-blocking I/O mode?
10739 if(gl
->io_mode
==GL_SERVER_MODE
&&
10740 (gl_nonblocking_io(gl
, gl
->input_fd
) ||
10741 gl_nonblocking_io(gl
, gl
->output_fd
) ||
10742 (gl
->file_fp
&& gl_nonblocking_io(gl
, fileno(gl
->file_fp
))))) {
10744 gl_restore_terminal_attributes(gl
);
10748 * If an input line is being entered, arrange for it to be
10753 gl_queue_redisplay(gl
);
10758 /*.......................................................................
10759 * Restore the terminal to the state that it had when
10760 * gl_raw_io() was last called. After calling
10761 * gl_raw_io(), this function must be called before
10762 * terminating or suspending the program, and before attempting other
10763 * uses of the terminal from within the program. See gl_raw_io()
10764 * for more details.
10767 * gl GetLine * The line editor resource object.
10769 * return int 0 - OK.
10772 int gl_normal_io(GetLine
*gl
)
10774 sigset_t oldset
; /* The signals that were blocked on entry to this function */
10775 int status
; /* The return status of _gl_normal_io() */
10777 * Check the arguments.
10784 * Block all signals.
10786 if(gl_mask_signals(gl
, &oldset
))
10789 * Execute the private body of the function while signals are blocked.
10791 status
= _gl_normal_io(gl
);
10793 * Restore the process signal mask.
10795 gl_unmask_signals(gl
, &oldset
);
10799 /*.......................................................................
10800 * This is the private body of the public function, gl_normal_io().
10801 * It assumes that the caller has checked its arguments and blocked the
10802 * delivery of signals.
10804 static int _gl_normal_io(GetLine
*gl
)
10807 * If we are already in normal mode, do nothing.
10812 * Postpone subsequent redisplays until after _gl_raw_io(gl, 1)
10817 * Switch back to blocking I/O. Note that this is essential to do
10818 * here, because when using non-blocking I/O, the terminal output
10819 * buffering code can't always make room for new output without calling
10820 * malloc(), and a call to malloc() would mean that this function
10821 * couldn't safely be called from signal handlers.
10823 if(gl
->io_mode
==GL_SERVER_MODE
&&
10824 (gl_blocking_io(gl
, gl
->input_fd
) ||
10825 gl_blocking_io(gl
, gl
->output_fd
) ||
10826 (gl
->file_fp
&& gl_blocking_io(gl
, fileno(gl
->file_fp
)))))
10829 * Move the cursor to the next empty terminal line. Note that
10830 * unbuffered I/O is requested, to ensure that gl_start_newline() be
10831 * async-signal-safe.
10833 if(gl
->is_term
&& gl_start_newline(gl
, 0))
10836 * Switch the terminal to normal mode.
10838 if(gl
->is_term
&& gl_restore_terminal_attributes(gl
)) {
10840 * On error, revert to non-blocking I/O if needed, so that on failure
10841 * we remain in raw mode.
10843 if(gl
->io_mode
==GL_SERVER_MODE
) {
10844 gl_nonblocking_io(gl
, gl
->input_fd
);
10845 gl_nonblocking_io(gl
, gl
->output_fd
);
10847 gl_nonblocking_io(gl
, fileno(gl
->file_fp
));
10854 /*.......................................................................
10855 * This function allows you to install an additional completion
10856 * action, or to change the completion function of an existing
10857 * one. This should be called before the first call to gl_get_line()
10858 * so that the name of the action be defined before the user's
10859 * configuration file is read.
10862 * gl GetLine * The resource object of the command-line input
10864 * data void * This is passed to match_fn() whenever it is
10865 * called. It could, for example, point to a
10866 * symbol table that match_fn() would look up
10868 * match_fn CplMatchFn * The function that will identify the prefix
10869 * to be completed from the input line, and
10870 * report matching symbols.
10871 * list_only int If non-zero, install an action that only lists
10872 * possible completions, rather than attempting
10873 * to perform the completion.
10874 * name const char * The name with which users can refer to the
10875 * binding in tecla configuration files.
10876 * keyseq const char * Either NULL, or a key sequence with which
10877 * to invoke the binding. This should be
10878 * specified in the same manner as key-sequences
10879 * in tecla configuration files (eg. "M-^I").
10881 * return int 0 - OK.
10884 int gl_completion_action(GetLine
*gl
, void *data
, CplMatchFn
*match_fn
,
10885 int list_only
, const char *name
, const char *keyseq
)
10887 sigset_t oldset
; /* The signals that were blocked on entry to this function */
10888 int status
; /* The return status of _gl_completion_action() */
10890 * Check the arguments.
10892 if(!gl
|| !name
|| !match_fn
) {
10897 * Block all signals.
10899 if(gl_mask_signals(gl
, &oldset
))
10902 * Install the new action while signals are blocked.
10904 status
= _gl_completion_action(gl
, data
, match_fn
, list_only
, name
, keyseq
);
10906 * Restore the process signal mask.
10908 gl_unmask_signals(gl
, &oldset
);
10912 /*.......................................................................
10913 * This is the private body of the public function, gl_completion_action().
10914 * It assumes that the caller has checked its arguments and blocked the
10915 * delivery of signals.
10917 static int _gl_completion_action(GetLine
*gl
, void *data
, CplMatchFn
*match_fn
,
10918 int list_only
, const char *name
,
10919 const char *keyseq
)
10921 KtKeyFn
*current_fn
; /* An existing action function */
10922 void *current_data
; /* The action-function callback data */
10924 * Which action function is desired?
10926 KtKeyFn
*action_fn
= list_only
? gl_list_completions
: gl_complete_word
;
10928 * Is there already an action of the specified name?
10930 if(_kt_lookup_action(gl
->bindings
, name
, ¤t_fn
, ¤t_data
) == 0) {
10932 * If the action has the same type as the one being requested,
10933 * simply change the contents of its GlCplCallback callback data.
10935 if(current_fn
== action_fn
) {
10936 GlCplCallback
*cb
= (GlCplCallback
*) current_data
;
10941 _err_record_msg(gl
->err
,
10942 "Illegal attempt to change the type of an existing completion action",
10947 * No existing action has the specified name.
10951 * Allocate a new GlCplCallback callback object.
10953 GlCplCallback
*cb
= (GlCplCallback
*) _new_FreeListNode(gl
->cpl_mem
);
10956 _err_record_msg(gl
->err
, "Insufficient memory to add completion action",
10961 * Record the completion callback data.
10966 * Attempt to register the new action.
10968 if(_kt_set_action(gl
->bindings
, name
, action_fn
, cb
)) {
10969 _err_record_msg(gl
->err
, _kt_last_error(gl
->bindings
), END_ERR_MSG
);
10970 _del_FreeListNode(gl
->cpl_mem
, (void *) cb
);
10975 * Bind the action to a given key-sequence?
10977 if(keyseq
&& _kt_set_keybinding(gl
->bindings
, KTB_NORM
, keyseq
, name
)) {
10978 _err_record_msg(gl
->err
, _kt_last_error(gl
->bindings
), END_ERR_MSG
);
10984 /*.......................................................................
10985 * Register an application-provided function as an action function.
10986 * This should preferably be called before the first call to gl_get_line()
10987 * so that the name of the action becomes defined before the user's
10988 * configuration file is read.
10991 * gl GetLine * The resource object of the command-line input
10993 * data void * Arbitrary application-specific callback
10994 * data to be passed to the callback
10996 * fn GlActionFn * The application-specific function that
10997 * implements the action. This will be invoked
10998 * whenever the user presses any
10999 * key-sequence which is bound to this action.
11000 * name const char * The name with which users can refer to the
11001 * binding in tecla configuration files.
11002 * keyseq const char * The key sequence with which to invoke
11003 * the binding. This should be specified in the
11004 * same manner as key-sequences in tecla
11005 * configuration files (eg. "M-^I").
11007 * return int 0 - OK.
11010 int gl_register_action(GetLine
*gl
, void *data
, GlActionFn
*fn
,
11011 const char *name
, const char *keyseq
)
11013 sigset_t oldset
; /* The signals that were blocked on entry to this function */
11014 int status
; /* The return status of _gl_register_action() */
11016 * Check the arguments.
11018 if(!gl
|| !name
|| !fn
) {
11023 * Block all signals.
11025 if(gl_mask_signals(gl
, &oldset
))
11028 * Install the new action while signals are blocked.
11030 status
= _gl_register_action(gl
, data
, fn
, name
, keyseq
);
11032 * Restore the process signal mask.
11034 gl_unmask_signals(gl
, &oldset
);
11038 /*.......................................................................
11039 * This is the private body of the public function, gl_register_action().
11040 * It assumes that the caller has checked its arguments and blocked the
11041 * delivery of signals.
11043 static int _gl_register_action(GetLine
*gl
, void *data
, GlActionFn
*fn
,
11044 const char *name
, const char *keyseq
)
11046 KtKeyFn
*current_fn
; /* An existing action function */
11047 void *current_data
; /* The action-function callback data */
11049 * Get the action function which actually runs the application-provided
11052 KtKeyFn
*action_fn
= gl_run_external_action
;
11054 * Is there already an action of the specified name?
11056 if(_kt_lookup_action(gl
->bindings
, name
, ¤t_fn
, ¤t_data
) == 0) {
11058 * If the action has the same type as the one being requested,
11059 * simply change the contents of its GlCplCallback callback data.
11061 if(current_fn
== action_fn
) {
11062 GlExternalAction
*a
= (GlExternalAction
*) current_data
;
11067 _err_record_msg(gl
->err
,
11068 "Illegal attempt to change the type of an existing action",
11073 * No existing action has the specified name.
11077 * Allocate a new GlCplCallback callback object.
11079 GlExternalAction
*a
=
11080 (GlExternalAction
*) _new_FreeListNode(gl
->ext_act_mem
);
11083 _err_record_msg(gl
->err
, "Insufficient memory to add completion action",
11088 * Record the completion callback data.
11093 * Attempt to register the new action.
11095 if(_kt_set_action(gl
->bindings
, name
, action_fn
, a
)) {
11096 _err_record_msg(gl
->err
, _kt_last_error(gl
->bindings
), END_ERR_MSG
);
11097 _del_FreeListNode(gl
->cpl_mem
, (void *) a
);
11102 * Bind the action to a given key-sequence?
11104 if(keyseq
&& _kt_set_keybinding(gl
->bindings
, KTB_NORM
, keyseq
, name
)) {
11105 _err_record_msg(gl
->err
, _kt_last_error(gl
->bindings
), END_ERR_MSG
);
11111 /*.......................................................................
11112 * Invoke an action function previously registered by a call to
11113 * gl_register_action().
11115 static KT_KEY_FN(gl_run_external_action
)
11117 GlAfterAction status
; /* The return value of the action function */
11119 * Get the container of the action function and associated callback data.
11121 GlExternalAction
*a
= (GlExternalAction
*) data
;
11123 * Invoke the action function.
11125 status
= a
->fn(gl
, a
->data
, count
, gl
->buff_curpos
, gl
->line
);
11127 * If the callback took us out of raw (possibly non-blocking) input
11128 * mode, restore this mode, and queue a redisplay of the input line.
11130 if(_gl_raw_io(gl
, 1))
11133 * Finally, check to see what the action function wants us to do next.
11138 gl_record_status(gl
, GLR_ERROR
, errno
);
11142 return gl_newline(gl
, 1, NULL
);
11150 /*.......................................................................
11151 * In server-I/O mode the terminal is left in raw mode between calls
11152 * to gl_get_line(), so it is necessary for the application to install
11153 * terminal restoring signal handlers for signals that could terminate
11154 * or suspend the process, plus a terminal reconfiguration handler to
11155 * be called when a process resumption signal is received, and finally
11156 * a handler to be called when a terminal-resize signal is received.
11158 * Since there are many signals that by default terminate or suspend
11159 * processes, and different systems support different sub-sets of
11160 * these signals, this function provides a convenient wrapper around
11161 * sigaction() for assigning the specified handlers to all appropriate
11162 * signals. It also arranges that when any one of these signals is
11163 * being handled, all other catchable signals are blocked. This is
11164 * necessary so that the specified signal handlers can safely call
11165 * gl_raw_io(), gl_normal_io() and gl_update_size() without
11166 * reentrancy issues.
11169 * term_handler void (*)(int) The signal handler to invoke when
11170 * a process terminating signal is
11172 * susp_handler void (*)(int) The signal handler to invoke when
11173 * a process suspending signal is
11175 * cont_handler void (*)(int) The signal handler to invoke when
11176 * a process resumption signal is
11177 * received (ie. SIGCONT).
11178 * size_handler void (*)(int) The signal handler to invoke when
11179 * a terminal-resize signal (ie. SIGWINCH)
11182 * return int 0 - OK.
11185 int gl_tty_signals(void (*term_handler
)(int), void (*susp_handler
)(int),
11186 void (*cont_handler
)(int), void (*size_handler
)(int))
11190 * Search for signals of the specified classes, and assign the
11191 * associated signal handler to them.
11193 for(i
=0; i
<sizeof(gl_signal_list
)/sizeof(gl_signal_list
[0]); i
++) {
11194 const struct GlDefSignal
*sig
= gl_signal_list
+ i
;
11195 if(sig
->attr
& GLSA_SUSP
) {
11196 if(gl_set_tty_signal(sig
->signo
, term_handler
))
11198 } else if(sig
->attr
& GLSA_TERM
) {
11199 if(gl_set_tty_signal(sig
->signo
, susp_handler
))
11201 } else if(sig
->attr
& GLSA_CONT
) {
11202 if(gl_set_tty_signal(sig
->signo
, cont_handler
))
11204 } else if(sig
->attr
& GLSA_SIZE
) {
11205 if(gl_set_tty_signal(sig
->signo
, size_handler
))
11212 /*.......................................................................
11213 * This is a private function of gl_tty_signals(). It installs a given
11214 * signal handler, and arranges that when that signal handler is being
11215 * invoked other signals are blocked. The latter is important to allow
11216 * functions like gl_normal_io(), gl_raw_io() and gl_update_size()
11217 * to be called from signal handlers.
11220 * signo int The signal to be trapped.
11221 * handler void (*)(int) The signal handler to assign to the signal.
11223 static int gl_set_tty_signal(int signo
, void (*handler
)(int))
11225 SigAction act
; /* The signal handler configuation */
11227 * Arrange to block all trappable signals except the one that is being
11228 * assigned (the trapped signal will be blocked automatically by the
11231 gl_list_trappable_signals(&act
.sa_mask
);
11232 sigdelset(&act
.sa_mask
, signo
);
11234 * Assign the signal handler.
11236 act
.sa_handler
= handler
;
11238 * There is only one portable signal handling flag, and it isn't
11239 * relevant to us, so don't specify any flags.
11243 * Register the signal handler.
11245 if(sigaction(signo
, &act
, NULL
))
11250 /*.......................................................................
11251 * Display a left-justified string over multiple terminal lines,
11252 * taking account of the current width of the terminal. Optional
11253 * indentation and an optional prefix string can be specified to be
11254 * displayed at the start of each new terminal line used. Similarly,
11255 * an optional suffix can be specified to be displayed at the end of
11256 * each terminal line. If needed, a single paragraph can be broken
11257 * across multiple calls. Note that literal newlines in the input
11258 * string can be used to force a newline at any point and that you
11259 * should use this feature to explicitly end all paragraphs, including
11260 * at the end of the last string that you write. Note that when a new
11261 * line is started between two words that are separated by spaces,
11262 * those spaces are not output, whereas when a new line is started
11263 * because a newline character was found in the string, only the
11264 * spaces before the newline character are discarded.
11267 * gl GetLine * The resource object of gl_get_line().
11268 * indentation int The number of spaces of indentation to write
11269 * at the beginning of each new terminal line.
11270 * prefix const char * An optional prefix string to write after the
11271 * indentation margin at the start of each new
11272 * terminal line. You can specify NULL if no
11273 * prefix is required.
11274 * suffix const char * An optional suffix string to draw at the end
11275 * of the terminal line. Spaces will be added
11276 * where necessary to ensure that the suffix ends
11277 * in the last column of the terminal line. If
11278 * no suffix is desired, specify NULL.
11279 * fill_char int The padding character to use when indenting
11280 * the line or padding up to the suffix.
11281 * def_width int If the terminal width isn't known, such as when
11282 * writing to a pipe or redirecting to a file,
11283 * this number specifies what width to assume.
11284 * start int The number of characters already written to
11285 * the start of the current terminal line. This
11286 * is primarily used to allow individual
11287 * paragraphs to be written over multiple calls
11288 * to this function, but can also be used to
11289 * allow you to start the first line of a
11290 * paragraph with a different prefix or
11291 * indentation than those specified above.
11292 * string const char * The string to be written.
11294 * return int On error -1 is returned. Otherwise the
11295 * return value is the terminal column index at
11296 * which the cursor was left after writing the
11297 * final word in the string. Successful return
11298 * values can thus be passed verbatim to the
11299 * 'start' arguments of subsequent calls to
11300 * gl_display_text() to allow the printing of a
11301 * paragraph to be broken across multiple calls
11302 * to gl_display_text().
11304 int gl_display_text(GetLine
*gl
, int indentation
, const char *prefix
,
11305 const char *suffix
, int fill_char
,
11306 int def_width
, int start
, const char *string
)
11308 sigset_t oldset
; /* The signals that were blocked on entry to this function */
11309 int status
; /* The return status of _gl_completion_action() */
11311 * Check the arguments?
11313 if(!gl
|| !string
) {
11318 * Block all signals.
11320 if(gl_mask_signals(gl
, &oldset
))
11323 * Display the text while signals are blocked.
11325 status
= _io_display_text(_io_write_stdio
, gl
->output_fp
, indentation
,
11326 prefix
, suffix
, fill_char
,
11327 gl
->ncolumn
> 0 ? gl
->ncolumn
: def_width
,
11330 * Restore the process signal mask.
11332 gl_unmask_signals(gl
, &oldset
);
11336 /*.......................................................................
11337 * Block all of the signals that we are currently trapping.
11340 * gl GetLine * The resource object of gl_get_line().
11342 * oldset sigset_t * The superseded process signal mask
11343 * will be return in *oldset unless oldset is
11346 * return int 0 - OK.
11349 static int gl_mask_signals(GetLine
*gl
, sigset_t
*oldset
)
11352 * Block all signals in all_signal_set, along with any others that are
11353 * already blocked by the application.
11355 if(sigprocmask(SIG_BLOCK
, &gl
->all_signal_set
, oldset
) >= 0) {
11356 gl
->signals_masked
= 1;
11360 * On error attempt to query the current process signal mask, so
11361 * that oldset be the correct process signal mask to restore later
11362 * if the caller of this function ignores the error return value.
11365 (void) sigprocmask(SIG_SETMASK
, NULL
, oldset
);
11366 gl
->signals_masked
= 0;
11370 /*.......................................................................
11371 * Restore a process signal mask that was previously returned via the
11372 * oldset argument of gl_mask_signals().
11375 * gl GetLine * The resource object of gl_get_line().
11377 * oldset sigset_t * The process signal mask to be restored.
11379 * return int 0 - OK.
11382 static int gl_unmask_signals(GetLine
*gl
, sigset_t
*oldset
)
11384 gl
->signals_masked
= 0;
11385 return sigprocmask(SIG_SETMASK
, oldset
, NULL
) < 0;
11388 /*.......................................................................
11389 * Arrange to temporarily catch the signals marked in gl->use_signal_set.
11392 * gl GetLine * The resource object of gl_get_line().
11394 * return int 0 - OK.
11397 static int gl_catch_signals(GetLine
*gl
)
11399 return sigprocmask(SIG_UNBLOCK
, &gl
->use_signal_set
, NULL
) < 0;
11402 /*.......................................................................
11403 * Select the I/O mode to be used by gl_get_line().
11406 * gl GetLine * The resource object of gl_get_line().
11407 * mode GlIOMode The I/O mode to establish.
11409 * return int 0 - OK.
11412 int gl_io_mode(GetLine
*gl
, GlIOMode mode
)
11414 sigset_t oldset
; /* The signals that were blocked on entry to this function */
11415 int status
; /* The return status of _gl_io_mode() */
11417 * Check the arguments.
11424 * Check that the requested mode is known.
11427 case GL_NORMAL_MODE
:
11428 case GL_SERVER_MODE
:
11432 _err_record_msg(gl
->err
, "Unknown gl_get_line() I/O mode requested.",
11437 * Block all signals.
11439 if(gl_mask_signals(gl
, &oldset
))
11442 * Invoke the private body of this function.
11444 status
= _gl_io_mode(gl
, mode
);
11446 * Restore the process signal mask.
11448 gl_unmask_signals(gl
, &oldset
);
11452 /*.......................................................................
11453 * This is the private body of the public function, gl_io_mode().
11454 * It assumes that the caller has checked its arguments and blocked the
11455 * delivery of signals.
11457 static int _gl_io_mode(GetLine
*gl
, GlIOMode mode
)
11460 * Are we already in the specified mode?
11462 if(mode
== gl
->io_mode
)
11465 * First revert to normal I/O in the current I/O mode.
11469 * Record the new mode.
11471 gl
->io_mode
= mode
;
11473 * Perform any actions needed by the new mode.
11475 if(mode
==GL_SERVER_MODE
) {
11476 if(_gl_raw_io(gl
, 1))
11482 /*.......................................................................
11483 * Return extra information (ie. in addition to that provided by errno)
11484 * about the last error to occur in either gl_get_line() or its
11485 * associated public functions.
11488 * gl GetLine * The resource object of gl_get_line().
11490 * buff char * An optional output buffer. Note that if the
11491 * calling application calls any gl_*()
11492 * functions from signal handlers, it should
11493 * provide a buffer here, so that a copy of
11494 * the latest error message can safely be made
11495 * while signals are blocked.
11496 * n size_t The allocated size of buff[].
11498 * return const char * A pointer to the error message. This will
11499 * be the buff argument, unless buff==NULL, in
11500 * which case it will be a pointer to an
11501 * internal error buffer. In the latter case,
11502 * note that the contents of the returned buffer
11503 * will change on subsequent calls to any gl_*()
11506 const char *gl_error_message(GetLine
*gl
, char *buff
, size_t n
)
11509 static const char *msg
= "NULL GetLine argument";
11511 strncpy(buff
, msg
, n
);
11517 sigset_t oldset
; /* The signals that were blocked on entry to this block */
11519 * Temporarily block all signals.
11521 gl_mask_signals(gl
, &oldset
);
11523 * Copy the error message into the specified buffer.
11525 if(buff
&& n
> 0) {
11526 strncpy(buff
, _err_get_msg(gl
->err
), n
);
11530 * Restore the process signal mask before returning.
11532 gl_unmask_signals(gl
, &oldset
);
11534 return _err_get_msg(gl
->err
);
11539 /*.......................................................................
11540 * Return the signal mask used by gl_get_line(). This is the set of
11541 * signals that gl_get_line() is currently configured to trap.
11544 * gl GetLine * The resource object of gl_get_line().
11546 * set sigset_t * The set of signals will be returned in *set,
11547 * in the form of a signal process mask, as
11548 * used by sigaction(), sigprocmask(),
11549 * sigpending(), sigsuspend(), sigsetjmp() and
11550 * other standard POSIX signal-aware
11553 * return int 0 - OK.
11554 * 1 - Error (examine errno for reason).
11556 int gl_list_signals(GetLine
*gl
, sigset_t
*set
)
11559 * Check the arguments.
11563 _err_record_msg(gl
->err
, "NULL argument(s)", END_ERR_MSG
);
11568 * Copy the signal mask into *set.
11570 memcpy(set
, &gl
->all_signal_set
, sizeof(*set
));
11574 /*.......................................................................
11575 * By default, gl_get_line() doesn't trap signals that are blocked
11576 * when it is called. This default can be changed either on a
11577 * per-signal basis by calling gl_trap_signal(), or on a global basis
11578 * by calling this function. What this function does is add the
11579 * GLS_UNBLOCK_SIG flag to all signals that are currently configured
11580 * to be trapped by gl_get_line(), such that when subsequent calls to
11581 * gl_get_line() wait for I/O, these signals are temporarily
11582 * unblocked. This behavior is useful in non-blocking server-I/O mode,
11583 * where it is used to avoid race conditions related to handling these
11584 * signals externally to gl_get_line(). See the demonstration code in
11585 * demo3.c, or the gl_handle_signal() man page for further
11589 * gl GetLine * The resource object of gl_get_line().
11591 void gl_catch_blocked(GetLine
*gl
)
11593 sigset_t oldset
; /* The process signal mask to restore */
11594 GlSignalNode
*sig
; /* A signal node in gl->sigs */
11596 * Check the arguments.
11603 * Temporarily block all signals while we modify the contents of gl.
11605 gl_mask_signals(gl
, &oldset
);
11607 * Add the GLS_UNBLOCK_SIG flag to all configured signals.
11609 for(sig
=gl
->sigs
; sig
; sig
=sig
->next
)
11610 sig
->flags
|= GLS_UNBLOCK_SIG
;
11612 * Restore the process signal mask that was superseded by the call
11613 * to gl_mask_signals().
11615 gl_unmask_signals(gl
, &oldset
);
11619 /*.......................................................................
11620 * Respond to signals who's default effects have important
11621 * consequences to gl_get_line(). This is intended for use in
11622 * non-blocking server mode, where the external event loop is
11623 * responsible for catching signals. Signals that are handled include
11624 * those that by default terminate or suspend the process, and the
11625 * signal that indicates that the terminal size has changed. Note that
11626 * this function is not signal safe and should thus not be called from
11627 * a signal handler itself. See the gl_io_mode() man page for how it
11630 * In the case of signals that by default terminate or suspend
11631 * processes, command-line editing will be suspended, the terminal
11632 * returned to a usable state, then the default disposition of the
11633 * signal restored and the signal resent, in order to suspend or
11634 * terminate the process. If the process subsequently resumes,
11635 * command-line editing is resumed.
11637 * In the case of signals that indicate that the terminal has been
11638 * resized, the new size will be queried, and any input line that is
11639 * being edited will be redrawn to fit the new dimensions of the
11643 * signo int The number of the signal to respond to.
11644 * gl GetLine * The first element of an array of 'ngl' GetLine
11646 * ngl int The number of elements in the gl[] array. Normally
11647 * this will be one.
11649 void gl_handle_signal(int signo
, GetLine
*gl
, int ngl
)
11651 int attr
; /* The attributes of the specified signal */
11652 sigset_t all_signals
; /* The set of trappable signals */
11653 sigset_t oldset
; /* The process signal mask to restore */
11661 * Look up the default attributes of the specified signal.
11663 attr
= gl_classify_signal(signo
);
11665 * If the signal isn't known, we are done.
11670 * Temporarily block all signals while we modify the gl objects.
11672 gl_list_trappable_signals(&all_signals
);
11673 sigprocmask(SIG_BLOCK
, &all_signals
, &oldset
);
11675 * Suspend or terminate the process?
11677 if(attr
& (GLSA_SUSP
| GLSA_TERM
)) {
11678 gl_suspend_process(signo
, gl
, ngl
);
11680 * Resize the terminal? Note that ioctl() isn't defined as being
11681 * signal safe, so we can't call gl_update_size() here. However,
11682 * gl_get_line() checks for resizes on each call, so simply arrange
11683 * for the application's event loop to call gl_get_line() as soon as
11684 * it becomes possible to write to the terminal. Note that if the
11685 * caller is calling select() or poll when this happens, these functions
11686 * get interrupted, since a signal has been caught.
11688 } else if(attr
& GLSA_SIZE
) {
11689 for(i
=0; i
<ngl
; i
++)
11690 gl
[i
].pending_io
= GLP_WRITE
;
11693 * Restore the process signal mask that was superseded by the call
11694 * to gl_mask_signals().
11696 sigprocmask(SIG_SETMASK
, &oldset
, NULL
);
11700 /*.......................................................................
11701 * Respond to an externally caught process suspension or
11702 * termination signal.
11704 * After restoring the terminal to a usable state, suspend or
11705 * terminate the calling process, using the original signal with its
11706 * default disposition restored to do so. If the process subsequently
11707 * resumes, resume editing any input lines that were being entered.
11710 * signo int The signal number to suspend the process with. Note
11711 * that the default disposition of this signal will be
11712 * restored before the signal is sent, so provided
11713 * that the default disposition of this signal is to
11714 * either suspend or terminate the application,
11715 * that is what wil happen, regardless of what signal
11716 * handler is currently assigned to this signal.
11717 * gl GetLine * The first element of an array of 'ngl' GetLine objects
11718 * whose terminals should be restored to a sane state
11719 * while the application is suspended.
11720 * ngl int The number of elements in the gl[] array.
11722 static void gl_suspend_process(int signo
, GetLine
*gl
, int ngl
)
11724 sigset_t only_signo
; /* A signal set containing just signo */
11725 sigset_t oldset
; /* The signal mask on entry to this function */
11726 sigset_t all_signals
; /* A signal set containing all signals */
11727 struct sigaction old_action
; /* The current signal handler */
11728 struct sigaction def_action
; /* The default signal handler */
11731 * Create a signal mask containing the signal that was trapped.
11733 sigemptyset(&only_signo
);
11734 sigaddset(&only_signo
, signo
);
11736 * Temporarily block all signals.
11738 gl_list_trappable_signals(&all_signals
);
11739 sigprocmask(SIG_BLOCK
, &all_signals
, &oldset
);
11741 * Restore the terminal to a usable state.
11743 for(i
=0; i
<ngl
; i
++) {
11744 GetLine
*obj
= gl
+ i
;
11745 if(obj
->raw_mode
) {
11746 _gl_normal_io(obj
);
11747 if(!obj
->raw_mode
) /* Check that gl_normal_io() succeded */
11748 obj
->raw_mode
= -1; /* Flag raw mode as needing to be restored */
11752 * Restore the system default disposition of the signal that we
11753 * caught. Note that this signal is currently blocked. Note that we
11754 * don't use memcpy() to copy signal sets here, because the signal safety
11755 * of memcpy() is undefined.
11757 def_action
.sa_handler
= SIG_DFL
;
11759 char *orig
= (char *) &all_signals
;
11760 char *dest
= (char *) &def_action
.sa_mask
;
11761 for(i
=0; i
<sizeof(sigset_t
); i
++)
11764 sigaction(signo
, &def_action
, &old_action
);
11766 * Resend the signal, and unblock it so that it gets delivered to
11767 * the application. This will invoke the default action of this signal.
11770 sigprocmask(SIG_UNBLOCK
, &only_signo
, NULL
);
11772 * If the process resumes again, it will resume here.
11773 * Block the signal again, then restore our signal handler.
11775 sigprocmask(SIG_BLOCK
, &only_signo
, NULL
);
11776 sigaction(signo
, &old_action
, NULL
);
11778 * Resume command-line editing.
11780 for(i
=0; i
<ngl
; i
++) {
11781 GetLine
*obj
= gl
+ i
;
11782 if(obj
->raw_mode
== -1) { /* Did we flag the need to restore raw mode? */
11783 obj
->raw_mode
= 0; /* gl_raw_io() does nothing unless raw_mode==0 */
11784 _gl_raw_io(obj
, 1);
11788 * Restore the process signal mask to the way it was when this function
11791 sigprocmask(SIG_SETMASK
, &oldset
, NULL
);
11795 /*.......................................................................
11796 * Return the information about the default attributes of a given signal.
11797 * The attributes that are returned are as defined by the standards that
11798 * created them, including POSIX, SVR4 and 4.3+BSD, and are taken from a
11799 * table in Richard Steven's book, "Advanced programming in the UNIX
11803 * signo int The signal to be characterized.
11805 * return int A bitwise union of GlSigAttr enumerators, or 0
11806 * if the signal isn't known.
11808 static int gl_classify_signal(int signo
)
11812 * Search for the specified signal in the gl_signal_list[] table.
11814 for(i
=0; i
<sizeof(gl_signal_list
)/sizeof(gl_signal_list
[0]); i
++) {
11815 const struct GlDefSignal
*sig
= gl_signal_list
+ i
;
11816 if(sig
->signo
== signo
)
11820 * Signal not known.
11825 /*.......................................................................
11826 * When in non-blocking server mode, this function can be used to abandon
11827 * the current incompletely entered input line, and prepare to start
11828 * editing a new line on the next call to gl_get_line().
11831 * gl GetLine * The line editor resource object.
11833 void gl_abandon_line(GetLine
*gl
)
11835 sigset_t oldset
; /* The process signal mask to restore */
11837 * Check the arguments.
11844 * Temporarily block all signals while we modify the contents of gl.
11846 gl_mask_signals(gl
, &oldset
);
11848 * Mark the input line as discarded.
11850 _gl_abandon_line(gl
);
11852 * Restore the process signal mask that was superseded by the call
11853 * to gl_mask_signals().
11855 gl_unmask_signals(gl
, &oldset
);
11859 /*.......................................................................
11860 * This is the private body of the gl_abandon_line() function. It
11861 * assumes that the caller has checked its arguments and blocked the
11862 * delivery of signals.
11864 void _gl_abandon_line(GetLine
*gl
)
11867 gl
->pending_io
= GLP_WRITE
;
11870 /*.......................................................................
11871 * How many characters are needed to write a number as an octal string?
11874 * num unsigned The to be measured.
11876 * return int The number of characters needed.
11878 static int gl_octal_width(unsigned num
)
11880 int n
; /* The number of characters needed to render the number */
11881 for(n
=1; num
/= 8; n
++)
11886 /*.......................................................................
11887 * Tell gl_get_line() the current terminal size. Note that this is only
11888 * necessary on systems where changes in terminal size aren't reported
11892 * gl GetLine * The resource object of gl_get_line().
11893 * ncolumn int The number of columns in the terminal.
11894 * nline int The number of lines in the terminal.
11896 * return int 0 - OK.
11899 int gl_set_term_size(GetLine
*gl
, int ncolumn
, int nline
)
11901 sigset_t oldset
; /* The signals that were blocked on entry */
11902 /* to this function */
11903 int status
; /* The return status */
11905 * Block all signals while accessing gl.
11907 gl_mask_signals(gl
, &oldset
);
11909 * Install the new terminal size.
11911 status
= _gl_set_term_size(gl
, ncolumn
, nline
);
11913 * Restore the process signal mask before returning.
11915 gl_unmask_signals(gl
, &oldset
);
11919 /*.......................................................................
11920 * This is the private body of the gl_set_term_size() function. It
11921 * assumes that the caller has checked its arguments and blocked the
11922 * delivery of signals.
11924 static int _gl_set_term_size(GetLine
*gl
, int ncolumn
, int nline
)
11927 * Check the arguments.
11934 * Reject non-sensical dimensions.
11936 if(ncolumn
<= 0 || nline
<= 0) {
11937 _err_record_msg(gl
->err
, "Invalid terminal size", END_ERR_MSG
);
11942 * Install the new dimensions in the terminal driver if possible, so
11943 * that future calls to gl_query_size() get the new value.
11947 struct winsize size
;
11948 size
.ws_row
= nline
;
11949 size
.ws_col
= ncolumn
;
11950 size
.ws_xpixel
= 0;
11951 size
.ws_ypixel
= 0;
11952 if(ioctl(gl
->output_fd
, TIOCSWINSZ
, &size
) == -1) {
11953 _err_record_msg(gl
->err
, "Can't change terminal size", END_ERR_MSG
);
11959 * If an input line is in the process of being edited, redisplay it to
11960 * accomodate the new dimensions, and record the new dimensions in
11961 * gl->nline and gl->ncolumn.
11963 return gl_handle_tty_resize(gl
, ncolumn
, nline
);
11966 /*.......................................................................
11967 * Record a character in the input line buffer at a given position.
11970 * gl GetLine * The resource object of gl_get_line().
11971 * c char The character to be recorded.
11972 * bufpos int The index in the buffer at which to record the
11975 * return int 0 - OK.
11976 * 1 - Insufficient room.
11978 static int gl_buffer_char(GetLine
*gl
, char c
, int bufpos
)
11981 * Guard against buffer overruns.
11983 if(bufpos
>= gl
->linelen
)
11986 * Record the new character.
11988 gl
->line
[bufpos
] = c
;
11990 * If the new character was placed beyond the end of the current input
11991 * line, update gl->ntotal to reflect the increased number of characters
11992 * that are in gl->line, and terminate the string.
11994 if(bufpos
>= gl
->ntotal
) {
11995 gl
->ntotal
= bufpos
+1;
11996 gl
->line
[gl
->ntotal
] = '\0';
12001 /*.......................................................................
12002 * Copy a given string into the input buffer, overwriting the current
12006 * gl GetLine * The resource object of gl_get_line().
12007 * s const char * The string to be recorded.
12008 * n int The number of characters to be copied from the
12010 * bufpos int The index in the buffer at which to place the
12011 * the first character of the string.
12013 * return int 0 - OK.
12014 * 1 - String truncated to fit.
12016 static int gl_buffer_string(GetLine
*gl
, const char *s
, int n
, int bufpos
)
12018 int nnew
; /* The number of characters actually recorded */
12021 * How many of the characters will fit within the buffer?
12023 nnew
= bufpos
+ n
<= gl
->linelen
? n
: (gl
->linelen
- bufpos
);
12025 * Record the first nnew characters of s[] in the buffer.
12027 for(i
=0; i
<nnew
; i
++)
12028 gl_buffer_char(gl
, s
[i
], bufpos
+ i
);
12030 * Was the string truncated?
12035 /*.......................................................................
12036 * Make room in the input buffer for a string to be inserted. This
12037 * involves moving the characters that follow a specified point, towards
12038 * the end of the buffer.
12041 * gl GetLine * The resource object of gl_get_line().
12042 * start int The index of the first character to be moved.
12043 * n int The width of the gap.
12045 * return int 0 - OK.
12046 * 1 - Insufficient room.
12048 static int gl_make_gap_in_buffer(GetLine
*gl
, int start
, int n
)
12051 * Ensure that the buffer has sufficient space.
12053 if(gl
->ntotal
+ n
> gl
->linelen
)
12056 * Move everything including and beyond the character at 'start'
12057 * towards the end of the string.
12059 memmove(gl
->line
+ start
+ n
, gl
->line
+ start
, gl
->ntotal
- start
+ 1);
12061 * Update the recorded size of the line.
12067 /*.......................................................................
12068 * Remove a given number of characters from the input buffer. This
12069 * involves moving the characters that follow the removed characters to
12070 * where the removed sub-string started in the input buffer.
12073 * gl GetLine * The resource object of gl_get_line().
12074 * start int The first character to be removed.
12075 * n int The number of characters to remove.
12077 static void gl_remove_from_buffer(GetLine
*gl
, int start
, int n
)
12079 memmove(gl
->line
+ start
, gl
->line
+ start
+ n
, gl
->ntotal
- start
- n
+ 1);
12081 * Update the recorded size of the line.
12086 /*.......................................................................
12087 * Truncate the string in the input line buffer after a given number of
12091 * gl GetLine * The resource object of gl_get_line().
12092 * n int The new length of the line.
12094 * return int 0 - OK.
12095 * 1 - n > gl->linelen.
12097 static int gl_truncate_buffer(GetLine
*gl
, int n
)
12099 if(n
> gl
->linelen
)
12101 gl
->line
[n
] = '\0';
12106 /*.......................................................................
12107 * When the contents of gl->line[] are changed without calling any of the
12108 * gl_ buffer manipulation functions, this function must be called to
12109 * compute the length of this string, and ancillary information.
12112 * gl GetLine * The resource object of gl_get_line().
12114 static void gl_update_buffer(GetLine
*gl
)
12116 int len
; /* The length of the line */
12118 * Measure the length of the input line.
12120 for(len
=0; len
<= gl
->linelen
&& gl
->line
[len
]; len
++)
12123 * Just in case the string wasn't correctly terminated, do so here.
12125 gl
->line
[len
] = '\0';
12127 * Record the number of characters that are now in gl->line[].
12131 * Ensure that the cursor stays within the bounds of the modified
12134 if(gl
->buff_curpos
> gl
->ntotal
)
12135 gl
->buff_curpos
= gl
->ntotal
;
12137 * Arrange for the input line to be redrawn.
12139 gl_queue_redisplay(gl
);
12143 /*.......................................................................
12144 * Erase the displayed input line, including its prompt, and leave the
12145 * cursor where the erased line started. Note that to allow this
12146 * function to be used when responding to a terminal resize, this
12147 * function is designed to work even if the horizontal cursor position
12148 * doesn't match the internally recorded position.
12151 * gl GetLine * The resource object of gl_get_line().
12153 * return int 0 - OK.
12156 static int gl_erase_line(GetLine
*gl
)
12159 * Is a line currently displayed?
12161 if(gl
->displayed
) {
12163 * Relative the the start of the input line, which terminal line of
12164 * the current input line is the cursor currently on?
12166 int cursor_line
= gl
->term_curpos
/ gl
->ncolumn
;
12168 * Move the cursor to the start of the line.
12170 for( ; cursor_line
> 0; cursor_line
--) {
12171 if(gl_print_control_sequence(gl
, 1, gl
->up
))
12174 if(gl_print_control_sequence(gl
, 1, gl
->bol
))
12177 * Clear from the start of the line to the end of the terminal.
12179 if(gl_print_control_sequence(gl
, gl
->nline
, gl
->clear_eod
))
12182 * Mark the line as no longer displayed.
12184 gl_line_erased(gl
);
12189 /*.......................................................................
12190 * Arrange for the input line to be redisplayed by gl_flush_output(),
12191 * as soon as the output queue becomes empty.
12194 * gl GetLine * The resource object of gl_get_line().
12196 static void gl_queue_redisplay(GetLine
*gl
)
12199 gl
->pending_io
= GLP_WRITE
;
12202 /*.......................................................................
12203 * Truncate the displayed input line starting from the current
12204 * terminal cursor position, and leave the cursor at the end of the
12205 * truncated line. The input-line buffer is not affected.
12208 * gl GetLine * The resource object of gl_get_line().
12210 * return int 0 - OK.
12213 static int gl_truncate_display(GetLine
*gl
)
12216 * Keep a record of the current terminal cursor position.
12218 int term_curpos
= gl
->term_curpos
;
12220 * First clear from the cursor to the end of the current input line.
12222 if(gl_print_control_sequence(gl
, 1, gl
->clear_eol
))
12225 * If there is more than one line displayed, go to the start of the
12226 * next line and clear from there to the end of the display. Note that
12227 * we can't use clear_eod to do the whole job of clearing from the
12228 * current cursor position to the end of the terminal because
12229 * clear_eod is only defined when used at the start of a terminal line
12230 * (eg. with gnome terminals, clear_eod clears from the start of the
12231 * current terminal line, rather than from the current cursor
12234 if(gl
->term_len
/ gl
->ncolumn
> gl
->term_curpos
/ gl
->ncolumn
) {
12235 if(gl_print_control_sequence(gl
, 1, gl
->down
) ||
12236 gl_print_control_sequence(gl
, 1, gl
->bol
) ||
12237 gl_print_control_sequence(gl
, gl
->nline
, gl
->clear_eod
))
12240 * Where is the cursor now?
12242 gl
->term_curpos
= gl
->ncolumn
* (term_curpos
/ gl
->ncolumn
+ 1);
12244 * Restore the cursor position.
12246 gl_set_term_curpos(gl
, term_curpos
);
12249 * Update the recorded position of the final character.
12251 gl
->term_len
= gl
->term_curpos
;
12255 /*.......................................................................
12256 * Return the set of all trappable signals.
12259 * signals sigset_t * The set of signals will be recorded in
12262 static void gl_list_trappable_signals(sigset_t
*signals
)
12265 * Start with the set of all signals.
12267 sigfillset(signals
);
12269 * Remove un-trappable signals from this set.
12272 sigdelset(signals
, SIGKILL
);
12275 sigdelset(signals
, SIGSTOP
);
12279 /*.......................................................................
12280 * Read an input line from a non-interactive input stream.
12283 * gl GetLine * The resource object of gl_get_line().
12285 * return int 0 - OK
12288 static int gl_read_stream_line(GetLine
*gl
)
12290 char c
= '\0'; /* The latest character read from fp */
12292 * Record the fact that we are about to read input.
12294 gl
->pending_io
= GLP_READ
;
12296 * If we are starting a new line, reset the line-input parameters.
12299 gl_reset_input_line(gl
);
12301 * Read one character at a time.
12303 while(gl
->ntotal
< gl
->linelen
&& c
!= '\n') {
12305 * Attempt to read one more character.
12307 switch(gl_read_input(gl
, &c
)) {
12310 case GL_READ_EOF
: /* Reached end-of-file? */
12312 * If any characters were read before the end-of-file condition,
12313 * interpolate a newline character, so that the caller sees a
12314 * properly terminated line. Otherwise return an end-of-file
12317 if(gl
->ntotal
> 0) {
12320 gl_record_status(gl
, GLR_EOF
, 0);
12324 case GL_READ_BLOCKED
: /* Input blocked? */
12325 gl_record_status(gl
, GLR_BLOCKED
, BLOCKED_ERRNO
);
12328 case GL_READ_ERROR
: /* I/O error? */
12333 * Append the character to the line buffer.
12335 if(gl_buffer_char(gl
, c
, gl
->ntotal
))
12339 * Was the end of the input line reached before running out of buffer space?
12341 gl
->endline
= (c
== '\n');
12345 /*.......................................................................
12346 * Read a single character from a non-interactive input stream.
12349 * gl GetLine * The resource object of gl_get_line().
12351 * return int The character, or EOF on error.
12353 static int gl_read_stream_char(GetLine
*gl
)
12355 char c
= '\0'; /* The latest character read from fp */
12356 int retval
= EOF
; /* The return value of this function */
12358 * Arrange to discard any incomplete input line.
12360 _gl_abandon_line(gl
);
12362 * Record the fact that we are about to read input.
12364 gl
->pending_io
= GLP_READ
;
12366 * Attempt to read one more character.
12368 switch(gl_read_input(gl
, &c
)) {
12369 case GL_READ_OK
: /* Success */
12372 case GL_READ_BLOCKED
: /* The read blocked */
12373 gl_record_status(gl
, GLR_BLOCKED
, BLOCKED_ERRNO
);
12374 retval
= EOF
; /* Failure */
12376 case GL_READ_EOF
: /* End of file reached */
12377 gl_record_status(gl
, GLR_EOF
, 0);
12378 retval
= EOF
; /* Failure */
12380 case GL_READ_ERROR
:
12381 retval
= EOF
; /* Failure */
12387 /*.......................................................................
12388 * Bind a key sequence to a given action.
12391 * gl GetLine * The resource object of gl_get_line().
12392 * origin GlKeyOrigin The originator of the key binding.
12393 * key const char * The key-sequence to be bound (or unbound).
12394 * action const char * The name of the action to bind the key to,
12395 * or either NULL or "" to unbind the
12398 * return int 0 - OK
12401 int gl_bind_keyseq(GetLine
*gl
, GlKeyOrigin origin
, const char *keyseq
,
12402 const char *action
)
12404 KtBinder binder
; /* The private internal equivalent of 'origin' */
12406 * Check the arguments.
12408 if(!gl
|| !keyseq
) {
12411 _err_record_msg(gl
->err
, "NULL argument(s)", END_ERR_MSG
);
12415 * An empty action string requests that the key-sequence be unbound.
12416 * This is indicated to _kt_set_keybinding() by passing a NULL action
12417 * string, so convert an empty string to a NULL action pointer.
12419 if(action
&& *action
=='\0')
12422 * Translate the public originator enumeration to the private equivalent.
12424 binder
= origin
==GL_USER_KEY
? KTB_USER
: KTB_NORM
;
12426 * Bind the action to a given key-sequence?
12428 if(keyseq
&& _kt_set_keybinding(gl
->bindings
, binder
, keyseq
, action
)) {
12429 _err_record_msg(gl
->err
, _kt_last_error(gl
->bindings
), END_ERR_MSG
);
12435 /*.......................................................................
12436 * This is the public wrapper around the gl_clear_termina() function.
12437 * It clears the terminal and leaves the cursor at the home position.
12438 * In server I/O mode, the next call to gl_get_line() will also
12439 * redisplay the current input line.
12442 * gl GetLine * The resource object of gl_get_line().
12444 * return int 0 - OK.
12447 int gl_erase_terminal(GetLine
*gl
)
12449 sigset_t oldset
; /* The signals that were blocked on entry */
12450 /* to this function */
12451 int status
; /* The return status */
12453 * Block all signals while accessing gl.
12455 gl_mask_signals(gl
, &oldset
);
12457 * Clear the terminal.
12459 status
= gl_clear_screen(gl
, 1, NULL
);
12461 * Attempt to flush the clear-screen control codes to the terminal.
12462 * If this doesn't complete the job, the next call to gl_get_line()
12465 (void) gl_flush_output(gl
);
12467 * Restore the process signal mask before returning.
12469 gl_unmask_signals(gl
, &oldset
);
12473 /*.......................................................................
12474 * This function must be called by any function that erases the input
12478 * gl GetLine * The resource object of gl_get_line().
12480 static void gl_line_erased(GetLine
*gl
)
12483 gl
->term_curpos
= 0;
12487 /*.......................................................................
12488 * Append a specified line to the history list.
12491 * gl GetLine * The resource object of gl_get_line().
12492 * line const char * The line to be added.
12494 * return int 0 - OK.
12497 int gl_append_history(GetLine
*gl
, const char *line
)
12499 sigset_t oldset
; /* The signals that were blocked on entry */
12500 /* to this function */
12501 int status
; /* The return status */
12503 * Check the arguments.
12510 * Block all signals.
12512 if(gl_mask_signals(gl
, &oldset
))
12515 * Execute the private body of the function while signals are blocked.
12517 status
= _gl_append_history(gl
, line
);
12519 * Restore the process signal mask.
12521 gl_unmask_signals(gl
, &oldset
);
12525 /*.......................................................................
12526 * This is the private body of the public function, gl_append_history().
12527 * It assumes that the caller has checked its arguments and blocked the
12528 * delivery of signals.
12530 static int _gl_append_history(GetLine
*gl
, const char *line
)
12532 int status
=_glh_add_history(gl
->glh
, line
, 0);
12534 _err_record_msg(gl
->err
, _glh_last_error(gl
->glh
), END_ERR_MSG
);
12538 /*.......................................................................
12539 * Enable or disable the automatic addition of newly entered lines to the
12543 * gl GetLine * The resource object of gl_get_line().
12544 * enable int If true, subsequently entered lines will
12545 * automatically be added to the history list
12546 * before they are returned to the caller of
12547 * gl_get_line(). If 0, the choice of how and
12548 * when to archive lines in the history list,
12549 * is left up to the calling application, which
12550 * can do so via calls to gl_append_history().
12552 * return int 0 - OK.
12555 int gl_automatic_history(GetLine
*gl
, int enable
)
12557 sigset_t oldset
; /* The signals that were blocked on entry */
12558 /* to this function */
12560 * Check the arguments.
12567 * Block all signals.
12569 if(gl_mask_signals(gl
, &oldset
))
12572 * Execute the private body of the function while signals are blocked.
12574 gl
->automatic_history
= enable
;
12576 * Restore the process signal mask.
12578 gl_unmask_signals(gl
, &oldset
);
12582 /*.......................................................................
12583 * This is a public function that reads a single uninterpretted
12584 * character from the user, without displaying anything.
12587 * gl GetLine * A resource object previously returned by
12590 * return int The character that was read, or EOF if the read
12591 * had to be aborted (in which case you can call
12592 * gl_return_status() to find out why).
12594 int gl_read_char(GetLine
*gl
)
12596 int retval
; /* The return value of _gl_read_char() */
12598 * This function can be called from application callback functions,
12599 * so check whether signals have already been masked, so that we don't
12600 * do it again, and overwrite gl->old_signal_set.
12602 int was_masked
= gl
->signals_masked
;
12604 * Check the arguments.
12611 * Temporarily block all of the signals that we have been asked to trap.
12613 if(!was_masked
&& gl_mask_signals(gl
, &gl
->old_signal_set
))
12616 * Perform the character reading task.
12618 retval
= _gl_read_char(gl
);
12620 * Restore the process signal mask to how it was when this function was
12624 gl_unmask_signals(gl
, &gl
->old_signal_set
);
12628 /*.......................................................................
12629 * This is the main body of the public function gl_read_char().
12631 static int _gl_read_char(GetLine
*gl
)
12633 int retval
= EOF
; /* The return value */
12634 int waserr
= 0; /* True if an error occurs */
12635 char c
; /* The character read */
12637 * This function can be called from application callback functions,
12638 * so check whether signals have already been overriden, so that we don't
12639 * overwrite the preserved signal handlers with gl_get_line()s. Also
12640 * record whether we are currently in raw I/O mode or not, so that this
12641 * can be left in the same state on leaving this function.
12643 int was_overriden
= gl
->signals_overriden
;
12644 int was_raw
= gl
->raw_mode
;
12646 * Also keep a record of the direction of any I/O that gl_get_line()
12647 * is awaiting, so that we can restore this status on return.
12649 GlPendingIO old_pending_io
= gl
->pending_io
;
12651 * Assume that this call will successfully complete the input operation
12652 * until proven otherwise.
12654 gl_clear_status(gl
);
12656 * If this is the first call to this function or gl_get_line(),
12657 * since new_GetLine(), complete any postponed configuration.
12659 if(!gl
->configured
) {
12660 (void) _gl_configure_getline(gl
, NULL
, NULL
, TECLA_CONFIG_FILE
);
12661 gl
->configured
= 1;
12664 * Before installing our signal handler functions, record the fact
12665 * that there are no pending signals.
12667 gl_pending_signal
= -1;
12669 * Temporarily override the signal handlers of the calling program,
12670 * so that we can intercept signals that would leave the terminal
12674 waserr
= gl_override_signal_handlers(gl
);
12676 * After recording the current terminal settings, switch the terminal
12677 * into raw input mode, without redisplaying any partially entered input
12681 waserr
= waserr
|| _gl_raw_io(gl
, 0);
12683 * Attempt to read the line. This will require more than one attempt if
12684 * either a current temporary input file is opened by gl_get_input_line()
12685 * or the end of a temporary input file is reached by gl_read_stream_line().
12689 * Read a line from a non-interactive stream?
12691 if(gl
->file_fp
|| !gl
->is_term
) {
12692 retval
= gl_read_stream_char(gl
);
12693 if(retval
!= EOF
) { /* Success? */
12695 } else if(gl
->file_fp
) { /* End of temporary input file? */
12696 gl_revert_input(gl
);
12697 gl_record_status(gl
, GLR_NEWLINE
, 0);
12698 } else { /* An error? */
12704 * Read from the terminal? Note that the above if() block may have
12705 * changed gl->file_fp, so it is necessary to retest it here, rather
12706 * than using an else statement.
12708 if(!gl
->file_fp
&& gl
->is_term
) {
12710 * Flush any pending output to the terminal before waiting
12711 * for the user to type a character.
12713 if(_glq_char_count(gl
->cq
) > 0 && gl_flush_output(gl
)) {
12716 * Read one character. Don't append it to the key buffer, since
12717 * this would subseuqnely appear as bogus input to the line editor.
12719 } else if(gl_read_terminal(gl
, 0, &c
) == 0) {
12721 * Record the character for return.
12725 * In this mode, count each character as being a new key-sequence.
12727 gl
->keyseq_count
++;
12729 * Delete the character that was read, from the key-press buffer.
12731 gl_discard_chars(gl
, 1);
12740 * If an error occurred, but gl->rtn_status is still set to
12741 * GLR_NEWLINE, change the status to GLR_ERROR. Otherwise
12742 * leave it at whatever specific value was assigned by the function
12743 * that aborted input. This means that only functions that trap
12744 * non-generic errors have to remember to update gl->rtn_status
12747 if(waserr
&& gl
->rtn_status
== GLR_NEWLINE
)
12748 gl_record_status(gl
, GLR_ERROR
, errno
);
12750 * Restore terminal settings, if they were changed by this function.
12752 if(!was_raw
&& gl
->io_mode
!= GL_SERVER_MODE
)
12755 * Restore the signal handlers, if they were overriden by this function.
12758 gl_restore_signal_handlers(gl
);
12760 * If this function gets aborted early, the errno value associated
12761 * with the event that caused this to happen is recorded in
12762 * gl->rtn_errno. Since errno may have been overwritten by cleanup
12763 * functions after this, restore its value to the value that it had
12764 * when the error condition occured, so that the caller can examine it
12765 * to find out what happened.
12767 errno
= gl
->rtn_errno
;
12769 * Error conditions are signalled to the caller, by setting the returned
12770 * character to EOF.
12772 if(gl
->rtn_status
!= GLR_NEWLINE
)
12775 * Restore the indication of what direction of I/O gl_get_line()
12776 * was awaiting before this call.
12778 gl
->pending_io
= old_pending_io
;
12780 * Return the acquired character.
12785 /*.......................................................................
12786 * Reset the GetLine completion status. This function should be called
12787 * at the start of gl_get_line(), gl_read_char() and gl_query_char()
12788 * to discard the completion status and non-zero errno value of any
12789 * preceding calls to these functions.
12792 * gl GetLine * The resource object of this module.
12794 static void gl_clear_status(GetLine
*gl
)
12796 gl_record_status(gl
, GLR_NEWLINE
, 0);
12799 /*.......................................................................
12800 * When an error or other event causes gl_get_line() to return, this
12801 * function should be called to record information about what
12802 * happened, including the value of errno and the value that
12803 * gl_return_status() should return.
12806 * gl GetLine * The resource object of this module.
12807 * rtn_status GlReturnStatus The completion status. To clear a
12808 * previous abnormal completion status,
12809 * specify GLR_NEWLINE (this is what
12810 * gl_clear_status() does).
12811 * rtn_errno int The associated value of errno.
12813 static void gl_record_status(GetLine
*gl
, GlReturnStatus rtn_status
,
12817 * If rtn_status==GLR_NEWLINE, then this resets the completion status, so we
12818 * should always heed this. Otherwise, only record the first abnormal
12819 * condition that occurs after such a reset.
12821 if(rtn_status
== GLR_NEWLINE
|| gl
->rtn_status
== GLR_NEWLINE
) {
12822 gl
->rtn_status
= rtn_status
;
12823 gl
->rtn_errno
= rtn_errno
;