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.
53 #include <sys/ioctl.h>
55 #ifdef HAVE_SYS_SELECT_H
56 #include <sys/select.h>
59 #include <sys/types.h>
65 * When using termcap, include termcap.h on systems that have it.
66 * Otherwise assume that all prototypes are provided by curses.h.
68 #if defined(USE_TERMCAP) && defined(HAVE_TERMCAP_H)
72 typedef int TputsRetType
;
73 typedef int TputsArgType
; /* int tputs(int c, FILE *fp) */
74 #define TPUTS_RETURNS_VALUE 1
77 * Use the above specifications to prototype our tputs callback function.
79 static TputsRetType
gl_tputs_putchar(TputsArgType c
);
83 * If the library is being compiled without filesystem access facilities,
84 * ensure that none of the action functions that normally do access the
85 * filesystem are bound by default, and that it they do get bound, that
86 * they don't do anything.
88 #if WITHOUT_FILE_SYSTEM
89 #define HIDE_FILE_SYSTEM
100 * Provide typedefs for standard POSIX structures.
102 typedef struct sigaction SigAction
;
103 typedef struct termios Termios
;
106 * Which flag is used to select non-blocking I/O with fcntl()?
108 #undef NON_BLOCKING_FLAG
109 #if defined(O_NONBLOCK)
110 #define NON_BLOCKING_FLAG (O_NONBLOCK)
111 #elif defined(O_NDELAY)
112 #define NON_BLOCKING_FLAG (O_NDELAY)
116 * What value should we give errno if I/O blocks when it shouldn't.
120 #define BLOCKED_ERRNO (EAGAIN)
121 #elif defined(EWOULDBLOCK)
122 #define BLOCKED_ERRNO (EWOULDBLOCK)
124 #define BLOCKED_ERRNO (EIO)
126 #define BLOCKED_ERRNO 0
132 #ifndef WITHOUT_FILE_SYSTEM
133 #include "pathutil.h"
135 #include "libtecla.h"
140 #include "freelist.h"
141 #include "stringrp.h"
142 #include "chrqueue.h"
143 #include "cplmatch.h"
144 #ifndef WITHOUT_FILE_SYSTEM
150 * Enumerate the available editing styles.
153 GL_EMACS_MODE
, /* Emacs style editing */
154 GL_VI_MODE
, /* Vi style editing */
155 GL_NO_EDITOR
/* Fall back to the basic OS-provided editing */
159 * Set the largest key-sequence that can be handled.
161 #define GL_KEY_MAX 64
164 * In vi mode, the following datatype is used to implement the
165 * undo command. It records a copy of the input line from before
166 * the command-mode action which edited the input line.
169 char *line
; /* A historical copy of the input line */
170 int buff_curpos
; /* The historical location of the cursor in */
171 /* line[] when the line was modified. */
172 int ntotal
; /* The number of characters in line[] */
173 int saved
; /* True once a line has been saved after the */
174 /* last call to gl_interpret_char(). */
178 * In vi mode, the following datatype is used to record information
179 * needed by the vi-repeat-change command.
182 KtAction action
; /* The last action function that made a */
183 /* change to the line. */
184 int count
; /* The repeat count that was passed to the */
186 int input_curpos
; /* Whenever vi command mode is entered, the */
187 /* the position at which it was first left */
188 /* is recorded here. */
189 int command_curpos
; /* Whenever vi command mode is entered, the */
190 /* the location of the cursor is recorded */
192 char input_char
; /* Commands that call gl_read_terminal() */
193 /* record the character here, so that it can */
194 /* used on repeating the function. */
195 int saved
; /* True if a function has been saved since the */
196 /* last call to gl_interpret_char(). */
197 int active
; /* True while a function is being repeated. */
201 * The following datatype is used to encapsulate information specific
205 ViUndo undo
; /* Information needed to implement the vi */
207 ViRepeat repeat
; /* Information needed to implement the vi */
208 /* repeat command. */
209 int command
; /* True in vi command-mode */
210 int find_forward
; /* True if the last character search was in the */
211 /* forward direction. */
212 int find_onto
; /* True if the last character search left the */
213 /* on top of the located character, as opposed */
214 /* to just before or after it. */
215 char find_char
; /* The last character sought, or '\0' if no */
216 /* searches have been performed yet. */
221 * Define a type for recording a file-descriptor callback and its associated
225 GlFdEventFn
*fn
; /* The callback function */
226 void *data
; /* Anonymous data to pass to the callback function */
230 * A list of nodes of the following type is used to record file-activity
231 * event handlers, but only on systems that have the select() system call.
233 typedef struct GlFdNode GlFdNode
;
235 GlFdNode
*next
; /* The next in the list of nodes */
236 int fd
; /* The file descriptor being watched */
237 GlFdHandler rd
; /* The callback to call when fd is readable */
238 GlFdHandler wr
; /* The callback to call when fd is writable */
239 GlFdHandler ur
; /* The callback to call when fd has urgent data */
243 * Set the number of the above structures to allocate every time that
244 * the freelist of GlFdNode's becomes exhausted.
246 #define GLFD_FREELIST_BLOCKING 10
249 static int gl_call_fd_handler(GetLine
*gl
, GlFdHandler
*gfh
, int fd
,
252 static int gl_call_timeout_handler(GetLine
*gl
);
257 * Each signal that gl_get_line() traps is described by a list node
258 * of the following type.
260 typedef struct GlSignalNode GlSignalNode
;
261 struct GlSignalNode
{
262 GlSignalNode
*next
; /* The next signal in the list */
263 int signo
; /* The number of the signal */
264 sigset_t proc_mask
; /* A process mask which only includes signo */
265 SigAction original
; /* The signal disposition of the calling program */
266 /* for this signal. */
267 unsigned flags
; /* A bitwise union of GlSignalFlags enumerators */
268 GlAfterSignal after
; /* What to do after the signal has been handled */
269 int errno_value
; /* What to set errno to */
273 * Set the number of the above structures to allocate every time that
274 * the freelist of GlSignalNode's becomes exhausted.
276 #define GLS_FREELIST_BLOCKING 30
279 * Completion handlers and their callback data are recorded in
280 * nodes of the following type.
282 typedef struct GlCplCallback GlCplCallback
;
283 struct GlCplCallback
{
284 CplMatchFn
*fn
; /* The completion callback function */
285 void *data
; /* Arbitrary callback data */
289 * The following function is used as the default completion handler when
290 * the filesystem is to be hidden. It simply reports no completions.
292 #ifdef HIDE_FILE_SYSTEM
293 static CPL_MATCH_FN(gl_no_completions
);
297 * Specify how many GlCplCallback nodes are added to the GlCplCallback freelist
298 * whenever it becomes exhausted.
300 #define GL_CPL_FREELIST_BLOCKING 10
303 * External action functions and their callback data are recorded in
304 * nodes of the following type.
306 typedef struct GlExternalAction GlExternalAction
;
307 struct GlExternalAction
{
308 GlActionFn
*fn
; /* The function which implements the action */
309 void *data
; /* Arbitrary callback data */
313 * Specify how many GlExternalAction nodes are added to the
314 * GlExternalAction freelist whenever it becomes exhausted.
316 #define GL_EXT_ACT_FREELIST_BLOCKING 10
319 * Define the contents of the GetLine object.
320 * Note that the typedef for this object can be found in libtecla.h.
323 ErrMsg
*err
; /* The error-reporting buffer */
324 GlHistory
*glh
; /* The line-history buffer */
325 WordCompletion
*cpl
; /* String completion resource object */
326 GlCplCallback cplfn
; /* The completion callback */
327 #ifndef WITHOUT_FILE_SYSTEM
328 ExpandFile
*ef
; /* ~user/, $envvar and wildcard expansion */
329 /* resource object. */
331 StringGroup
*capmem
; /* Memory for recording terminal capability */
333 GlCharQueue
*cq
; /* The terminal output character queue */
334 int input_fd
; /* The file descriptor to read on */
335 int output_fd
; /* The file descriptor to write to */
336 FILE *input_fp
; /* A stream wrapper around input_fd */
337 FILE *output_fp
; /* A stream wrapper around output_fd */
338 FILE *file_fp
; /* When input is being temporarily taken from */
339 /* a file, this is its file-pointer. Otherwise */
341 char *term
; /* The terminal type specified on the last call */
342 /* to gl_change_terminal(). */
343 int is_term
; /* True if stdin is a terminal */
344 GlWriteFn
*flush_fn
; /* The function to call to write to the terminal */
345 GlIOMode io_mode
; /* The I/O mode established by gl_io_mode() */
346 int raw_mode
; /* True while the terminal is in raw mode */
347 GlPendingIO pending_io
; /* The type of I/O that is currently pending */
348 GlReturnStatus rtn_status
; /* The reason why gl_get_line() returned */
349 int rtn_errno
; /* THe value of errno associated with rtn_status */
350 size_t linelen
; /* The max number of characters per line */
351 char *line
; /* A line-input buffer of allocated size */
352 /* linelen+2. The extra 2 characters are */
353 /* reserved for "\n\0". */
354 char *cutbuf
; /* A cut-buffer of the same size as line[] */
355 char *prompt
; /* The current prompt string */
356 int prompt_len
; /* The length of the prompt string */
357 int prompt_changed
; /* True after a callback changes the prompt */
358 int prompt_style
; /* How the prompt string is displayed */
359 FreeList
*cpl_mem
; /* Memory for GlCplCallback objects */
360 FreeList
*ext_act_mem
; /* Memory for GlExternalAction objects */
361 FreeList
*sig_mem
; /* Memory for nodes of the signal list */
362 GlSignalNode
*sigs
; /* The head of the list of signals */
363 int signals_masked
; /* True between calls to gl_mask_signals() and */
364 /* gl_unmask_signals() */
365 int signals_overriden
; /* True between calls to gl_override_signals() */
366 /* and gl_restore_signals() */
367 sigset_t all_signal_set
; /* The set of all signals that we are trapping */
368 sigset_t old_signal_set
; /* The set of blocked signals on entry to */
370 sigset_t use_signal_set
; /* The subset of all_signal_set to unblock */
371 /* while waiting for key-strokes */
372 Termios oldattr
; /* Saved terminal attributes. */
373 KeyTab
*bindings
; /* A table of key-bindings */
374 int ntotal
; /* The number of characters in gl->line[] */
375 int buff_curpos
; /* The cursor position within gl->line[] */
376 int term_curpos
; /* The cursor position on the terminal */
377 int term_len
; /* The number of terminal characters used to */
378 /* display the current input line. */
379 int buff_mark
; /* A marker location in the buffer */
380 int insert_curpos
; /* The cursor position at start of insert */
381 int insert
; /* True in insert mode */
382 int number
; /* If >= 0, a numeric argument is being read */
383 int endline
; /* True to tell gl_get_input_line() to return */
384 /* the current contents of gl->line[] */
385 int displayed
; /* True if an input line is currently displayed */
386 int redisplay
; /* If true, the input line will be redrawn */
387 /* either after the current action function */
388 /* returns, or when gl_get_input_line() */
389 /* is next called. */
390 int postpone
; /* _gl_normal_io() sets this flag, to */
391 /* postpone any redisplays until */
392 /* is next called, to resume line editing. */
393 char keybuf
[GL_KEY_MAX
+1]; /* A buffer of currently unprocessed key presses */
394 int nbuf
; /* The number of characters in keybuf[] */
395 int nread
; /* The number of characters read from keybuf[] */
396 KtAction current_action
; /* The action function that is being invoked */
397 int current_count
; /* The repeat count passed to */
398 /* current_acction.fn() */
399 GlhLineID preload_id
; /* When not zero, this should be the ID of a */
400 /* line in the history buffer for potential */
402 int preload_history
; /* If true, preload the above history line when */
403 /* gl_get_input_line() is next called. */
404 long keyseq_count
; /* The number of key sequences entered by the */
405 /* the user since new_GetLine() was called. */
406 long last_search
; /* The value of keyseq_count during the last */
407 /* history search operation. */
408 GlEditor editor
; /* The style of editing, (eg. vi or emacs) */
409 int silence_bell
; /* True if gl_ring_bell() should do nothing. */
410 int automatic_history
; /* True to automatically archive entered lines */
411 /* in the history list. */
412 ViMode vi
; /* Parameters used when editing in vi mode */
413 const char *left
; /* The string that moves the cursor 1 character */
415 const char *right
; /* The string that moves the cursor 1 character */
417 const char *up
; /* The string that moves the cursor 1 character */
419 const char *down
; /* The string that moves the cursor 1 character */
421 const char *home
; /* The string that moves the cursor home */
422 const char *bol
; /* Move cursor to beginning of line */
423 const char *clear_eol
; /* The string that clears from the cursor to */
424 /* the end of the line. */
425 const char *clear_eod
; /* The string that clears from the cursor to */
426 /* the end of the display. */
427 const char *u_arrow
; /* The string returned by the up-arrow key */
428 const char *d_arrow
; /* The string returned by the down-arrow key */
429 const char *l_arrow
; /* The string returned by the left-arrow key */
430 const char *r_arrow
; /* The string returned by the right-arrow key */
431 const char *sound_bell
; /* The string needed to ring the terminal bell */
432 const char *bold
; /* Switch to the bold font */
433 const char *underline
; /* Underline subsequent characters */
434 const char *standout
; /* Turn on standout mode */
435 const char *dim
; /* Switch to a dim font */
436 const char *reverse
; /* Turn on reverse video */
437 const char *blink
; /* Switch to a blinking font */
438 const char *text_attr_off
; /* Turn off all text attributes */
439 int nline
; /* The height of the terminal in lines */
440 int ncolumn
; /* The width of the terminal in columns */
442 char *tgetent_buf
; /* The buffer that is used by tgetent() to */
443 /* store a terminal description. */
444 char *tgetstr_buf
; /* The buffer that is used by tgetstr() to */
445 /* store terminal capabilities. */
448 const char *left_n
; /* The parameter string that moves the cursor */
449 /* n characters left. */
450 const char *right_n
; /* The parameter string that moves the cursor */
451 /* n characters right. */
453 char *app_file
; /* The pathname of the application-specific */
454 /* .teclarc configuration file, or NULL. */
455 char *user_file
; /* The pathname of the user-specific */
456 /* .teclarc configuration file, or NULL. */
457 int configured
; /* True as soon as any teclarc configuration */
458 /* file has been read. */
459 int echo
; /* True to display the line as it is being */
460 /* entered. If 0, only the prompt will be */
461 /* displayed, and the line will not be */
462 /* archived in the history list. */
463 int last_signal
; /* The last signal that was caught by */
464 /* the last call to gl_get_line(), or -1 */
465 /* if no signal has been caught yet. */
467 FreeList
*fd_node_mem
; /* A freelist of GlFdNode structures */
468 GlFdNode
*fd_nodes
; /* The list of fd event descriptions */
469 fd_set rfds
; /* The set of fds to watch for readability */
470 fd_set wfds
; /* The set of fds to watch for writability */
471 fd_set ufds
; /* The set of fds to watch for urgent data */
472 int max_fd
; /* The maximum file-descriptor being watched */
473 struct { /* Inactivity timeout related data */
474 struct timeval dt
; /* The inactivity timeout when timer.fn() */
476 GlTimeoutFn
*fn
; /* The application callback to call when */
477 /* the inactivity timer expires, or 0 if */
478 /* timeouts are not required. */
479 void *data
; /* Application provided data to be passed to */
486 * Define the max amount of space needed to store a termcap terminal
487 * description. Unfortunately this has to be done by guesswork, so
488 * there is the potential for buffer overflows if we guess too small.
489 * Fortunately termcap has been replaced by terminfo on most
490 * platforms, and with terminfo this isn't an issue. The value that I
491 * am using here is the conventional value, as recommended by certain
495 #define TERMCAP_BUF_SIZE 2048
499 * Set the size of the string segments used to store terminal capability
502 #define CAPMEM_SEGMENT_SIZE 512
505 * If no terminal size information is available, substitute the
506 * following vt100 default sizes.
508 #define GL_DEF_NLINE 24
509 #define GL_DEF_NCOLUMN 80
512 * Enumerate the attributes needed to classify different types of
513 * signals. These attributes reflect the standard default
514 * characteristics of these signals (according to Richard Steven's
515 * Advanced Programming in the UNIX Environment). Note that these values
516 * are all powers of 2, so that they can be combined in a bitwise union.
519 GLSA_TERM
=1, /* A signal that terminates processes */
520 GLSA_SUSP
=2, /* A signal that suspends processes */
521 GLSA_CONT
=4, /* A signal that is sent when suspended processes resume */
522 GLSA_IGN
=8, /* A signal that is ignored */
523 GLSA_CORE
=16, /* A signal that generates a core dump */
524 GLSA_HARD
=32, /* A signal generated by a hardware exception */
525 GLSA_SIZE
=64 /* A signal indicating terminal size changes */
529 * List the signals that we need to catch. In general these are
530 * those that by default terminate or suspend the process, since
531 * in such cases we need to restore terminal settings.
533 static const struct GlDefSignal
{
534 int signo
; /* The number of the signal */
535 unsigned flags
; /* A bitwise union of GlSignalFlags enumerators */
536 GlAfterSignal after
; /* What to do after the signal has been delivered */
537 int attr
; /* The default attributes of this signal, expressed */
538 /* as a bitwise union of GlSigAttr enumerators */
539 int errno_value
; /* What to set errno to */
540 } gl_signal_list
[] = {
541 {SIGABRT
, GLS_SUSPEND_INPUT
, GLS_ABORT
, GLSA_TERM
|GLSA_CORE
, EINTR
},
542 {SIGALRM
, GLS_RESTORE_ENV
, GLS_CONTINUE
, GLSA_TERM
, 0},
543 {SIGCONT
, GLS_RESTORE_ENV
, GLS_CONTINUE
, GLSA_CONT
|GLSA_IGN
, 0},
546 {SIGHUP
, GLS_SUSPEND_INPUT
, GLS_ABORT
, GLSA_TERM
, ENOTTY
},
548 {SIGHUP
, GLS_SUSPEND_INPUT
, GLS_ABORT
, GLSA_TERM
, EINTR
},
551 {SIGINT
, GLS_SUSPEND_INPUT
, GLS_ABORT
, GLSA_TERM
, EINTR
},
554 {SIGPIPE
, GLS_SUSPEND_INPUT
, GLS_ABORT
, GLSA_TERM
, EPIPE
},
556 {SIGPIPE
, GLS_SUSPEND_INPUT
, GLS_ABORT
, GLSA_TERM
, EINTR
},
560 {SIGPOLL
, GLS_SUSPEND_INPUT
, GLS_ABORT
, GLSA_TERM
, EINTR
},
563 {SIGPWR
, GLS_RESTORE_ENV
, GLS_CONTINUE
, GLSA_IGN
, 0},
566 {SIGQUIT
, GLS_SUSPEND_INPUT
, GLS_ABORT
, GLSA_TERM
|GLSA_CORE
, EINTR
},
568 {SIGTERM
, GLS_SUSPEND_INPUT
, GLS_ABORT
, GLSA_TERM
, EINTR
},
570 {SIGTSTP
, GLS_SUSPEND_INPUT
, GLS_CONTINUE
, GLSA_SUSP
, 0},
573 {SIGTTIN
, GLS_SUSPEND_INPUT
, GLS_CONTINUE
, GLSA_SUSP
, 0},
576 {SIGTTOU
, GLS_SUSPEND_INPUT
, GLS_CONTINUE
, GLSA_SUSP
, 0},
579 {SIGUSR1
, GLS_RESTORE_ENV
, GLS_CONTINUE
, GLSA_TERM
, 0},
582 {SIGUSR2
, GLS_RESTORE_ENV
, GLS_CONTINUE
, GLSA_TERM
, 0},
585 {SIGVTALRM
, GLS_RESTORE_ENV
, GLS_CONTINUE
, GLSA_TERM
, 0},
588 {SIGWINCH
, GLS_RESTORE_ENV
, GLS_CONTINUE
, GLSA_SIZE
|GLSA_IGN
, 0},
591 {SIGXCPU
, GLS_RESTORE_ENV
, GLS_CONTINUE
, GLSA_TERM
|GLSA_CORE
, 0},
594 {SIGXFSZ
, GLS_RESTORE_ENV
, GLS_CONTINUE
, GLSA_TERM
|GLSA_CORE
, 0},
599 * Define file-scope variables for use in signal handlers.
601 static volatile sig_atomic_t gl_pending_signal
= -1;
602 static sigjmp_buf gl_setjmp_buffer
;
604 static void gl_signal_handler(int signo
);
606 static int gl_check_caught_signal(GetLine
*gl
);
609 * Respond to an externally caught process suspension or
610 * termination signal.
612 static void gl_suspend_process(int signo
, GetLine
*gl
, int ngl
);
614 /* Return the default attributes of a given signal */
616 static int gl_classify_signal(int signo
);
619 * Unfortunately both terminfo and termcap require one to use the tputs()
620 * function to output terminal control characters, and this function
621 * doesn't allow one to specify a file stream. As a result, the following
622 * file-scope variable is used to pass the current output file stream.
623 * This is bad, but there doesn't seem to be any alternative.
625 static GetLine
*tputs_gl
= NULL
;
628 * Define a tab to be a string of 8 spaces.
633 * Lookup the current size of the terminal.
635 static void gl_query_size(GetLine
*gl
, int *ncolumn
, int *nline
);
638 * Getline calls this to temporarily override certain signal handlers
639 * of the calling program.
641 static int gl_override_signal_handlers(GetLine
*gl
);
644 * Getline calls this to restore the signal handlers of the calling
647 static int gl_restore_signal_handlers(GetLine
*gl
);
650 * Temporarily block the delivery of all signals that gl_get_line()
651 * is currently configured to trap.
653 static int gl_mask_signals(GetLine
*gl
, sigset_t
*oldset
);
656 * Restore the process signal mask that was overriden by a previous
657 * call to gl_mask_signals().
659 static int gl_unmask_signals(GetLine
*gl
, sigset_t
*oldset
);
662 * Unblock the signals that gl_get_line() has been configured to catch.
664 static int gl_catch_signals(GetLine
*gl
);
667 * Return the set of all trappable signals.
669 static void gl_list_trappable_signals(sigset_t
*signals
);
672 * Put the terminal into raw input mode, after saving the original
673 * terminal attributes in gl->oldattr.
675 static int gl_raw_terminal_mode(GetLine
*gl
);
678 * Restore the terminal attributes from gl->oldattr.
680 static int gl_restore_terminal_attributes(GetLine
*gl
);
683 * Switch to non-blocking I/O if possible.
685 static int gl_nonblocking_io(GetLine
*gl
, int fd
);
688 * Switch to blocking I/O if possible.
690 static int gl_blocking_io(GetLine
*gl
, int fd
);
693 * Read a line from the user in raw mode.
695 static int gl_get_input_line(GetLine
*gl
, const char *prompt
,
696 const char *start_line
, int start_pos
);
699 * Query the user for a single character.
701 static int gl_get_query_char(GetLine
*gl
, const char *prompt
, int defchar
);
704 * Read input from a non-interactive input stream.
706 static int gl_read_stream_line(GetLine
*gl
);
709 * Read a single character from a non-interactive input stream.
711 static int gl_read_stream_char(GetLine
*gl
);
714 * Prepare to edit a new line.
716 static int gl_present_line(GetLine
*gl
, const char *prompt
,
717 const char *start_line
, int start_pos
);
720 * Reset all line input parameters for a new input line.
722 static void gl_reset_input_line(GetLine
*gl
);
725 * Handle the receipt of the potential start of a new key-sequence from
728 static int gl_interpret_char(GetLine
*gl
, char c
);
731 * Bind a single control or meta character to an action.
733 static int gl_bind_control_char(GetLine
*gl
, KtBinder binder
,
734 char c
, const char *action
);
737 * Set up terminal-specific key bindings.
739 static int gl_bind_terminal_keys(GetLine
*gl
);
742 * Lookup terminal control string and size information.
744 static int gl_control_strings(GetLine
*gl
, const char *term
);
747 * Wrappers around the terminfo and termcap functions that lookup
748 * strings in the terminal information databases.
751 static const char *gl_tigetstr(GetLine
*gl
, const char *name
);
752 #elif defined(USE_TERMCAP)
753 static const char *gl_tgetstr(GetLine
*gl
, const char *name
, char **bufptr
);
757 * Output a binary string directly to the terminal.
759 static int gl_print_raw_string(GetLine
*gl
, int buffered
,
760 const char *string
, int n
);
763 * Print an informational message, starting and finishing on new lines.
764 * After the list of strings to be printed, the last argument MUST be
767 static int gl_print_info(GetLine
*gl
, ...);
768 #define GL_END_INFO ((const char *)0)
771 * Start a newline and place the cursor at its start.
773 static int gl_start_newline(GetLine
*gl
, int buffered
);
776 * Output a terminal control sequence.
778 static int gl_print_control_sequence(GetLine
*gl
, int nline
,
782 * Output a character or string to the terminal after converting tabs
783 * to spaces and control characters to a caret followed by the modified
786 static int gl_print_char(GetLine
*gl
, char c
, char pad
);
787 static int gl_print_string(GetLine
*gl
, const char *string
, char pad
);
790 * Delete nc characters starting from the one under the cursor.
791 * Optionally copy the deleted characters to the cut buffer.
793 static int gl_delete_chars(GetLine
*gl
, int nc
, int cut
);
796 * Add a character to the line buffer at the current cursor position,
797 * inserting or overwriting according the current mode.
799 static int gl_add_char_to_line(GetLine
*gl
, char c
);
802 * Insert/append a string to the line buffer and terminal at the current
805 static int gl_add_string_to_line(GetLine
*gl
, const char *s
);
808 * Record a new character in the input-line buffer.
810 static int gl_buffer_char(GetLine
*gl
, char c
, int bufpos
);
813 * Record a string in the input-line buffer.
815 static int gl_buffer_string(GetLine
*gl
, const char *s
, int n
, int bufpos
);
818 * Make way to insert a string in the input-line buffer.
820 static int gl_make_gap_in_buffer(GetLine
*gl
, int start
, int n
);
823 * Remove characters from the input-line buffer, and move any characters
824 * that followed them to the start of the vacated space.
826 static void gl_remove_from_buffer(GetLine
*gl
, int start
, int n
);
829 * Terminate the input-line buffer after a specified number of characters.
831 static int gl_truncate_buffer(GetLine
*gl
, int n
);
834 * Delete the displayed part of the input line that follows the current
835 * terminal cursor position.
837 static int gl_truncate_display(GetLine
*gl
);
840 * Accomodate changes to the contents of the input line buffer
841 * that weren't made by the above gl_*buffer functions.
843 static void gl_update_buffer(GetLine
*gl
);
846 * Read a single character from the terminal.
848 static int gl_read_terminal(GetLine
*gl
, int keep
, char *c
);
851 * Discard processed characters from the key-press lookahead buffer.
853 static void gl_discard_chars(GetLine
*gl
, int nused
);
856 * Move the terminal cursor n positions to the left or right.
858 static int gl_terminal_move_cursor(GetLine
*gl
, int n
);
861 * Move the terminal cursor to a given position.
863 static int gl_set_term_curpos(GetLine
*gl
, int term_curpos
);
866 * Set the position of the cursor both in the line input buffer and on the
869 static int gl_place_cursor(GetLine
*gl
, int buff_curpos
);
872 * How many characters are needed to write a number as an octal string?
874 static int gl_octal_width(unsigned num
);
877 * Return the number of spaces needed to display a tab character at
878 * a given location of the terminal.
880 static int gl_displayed_tab_width(GetLine
*gl
, int term_curpos
);
883 * Return the number of terminal characters needed to display a
884 * given raw character.
886 static int gl_displayed_char_width(GetLine
*gl
, char c
, int term_curpos
);
889 * Return the number of terminal characters needed to display a
892 static int gl_displayed_string_width(GetLine
*gl
, const char *string
, int nc
,
896 * Return non-zero if 'c' is to be considered part of a word.
898 static int gl_is_word_char(int c
);
901 * Read a tecla configuration file.
903 static int _gl_read_config_file(GetLine
*gl
, const char *filename
, KtBinder who
);
906 * Read a tecla configuration string.
908 static int _gl_read_config_string(GetLine
*gl
, const char *buffer
, KtBinder who
);
911 * Define the callback function used by _gl_parse_config_line() to
912 * read the next character of a configuration stream.
914 #define GLC_GETC_FN(fn) int (fn)(void *stream)
915 typedef GLC_GETC_FN(GlcGetcFn
);
917 static GLC_GETC_FN(glc_file_getc
); /* Read from a file */
918 static GLC_GETC_FN(glc_buff_getc
); /* Read from a string */
921 * Parse a single configuration command line.
923 static int _gl_parse_config_line(GetLine
*gl
, void *stream
, GlcGetcFn
*getc_fn
,
924 const char *origin
, KtBinder who
, int *lineno
);
925 static int gl_report_config_error(GetLine
*gl
, const char *origin
, int lineno
,
929 * Bind the actual arrow key bindings to match those of the symbolic
930 * arrow-key bindings.
932 static int _gl_bind_arrow_keys(GetLine
*gl
);
935 * Copy the binding of the specified symbolic arrow-key binding to
936 * the terminal specific, and default arrow-key key-sequences.
938 static int _gl_rebind_arrow_key(GetLine
*gl
, const char *name
,
939 const char *term_seq
,
940 const char *def_seq1
,
941 const char *def_seq2
);
944 * After the gl_read_from_file() action has been used to tell gl_get_line()
945 * to temporarily read input from a file, gl_revert_input() arranges
946 * for input to be reverted to the input stream last registered with
947 * gl_change_terminal().
949 static void gl_revert_input(GetLine
*gl
);
952 * Flush unwritten characters to the terminal.
954 static int gl_flush_output(GetLine
*gl
);
957 * The callback through which all terminal output is routed.
958 * This simply appends characters to a queue buffer, which is
959 * subsequently flushed to the output channel by gl_flush_output().
961 static GL_WRITE_FN(gl_write_fn
);
964 * The callback function which the output character queue object
965 * calls to transfer characters to the output channel.
967 static GL_WRITE_FN(gl_flush_terminal
);
970 * Enumerate the possible return statuses of gl_read_input().
973 GL_READ_OK
, /* A character was read successfully */
974 GL_READ_ERROR
, /* A read-error occurred */
975 GL_READ_BLOCKED
, /* The read would have blocked the caller */
976 GL_READ_EOF
/* The end of the current input file was reached */
979 static GlReadStatus
gl_read_input(GetLine
*gl
, char *c
);
981 * Private functions of gl_read_input().
983 static int gl_event_handler(GetLine
*gl
, int fd
);
984 static int gl_read_unmasked(GetLine
*gl
, int fd
, char *c
);
988 * A private function of gl_tty_signals().
990 static int gl_set_tty_signal(int signo
, void (*handler
)(int));
993 * Change the editor style being emulated.
995 static int gl_change_editor(GetLine
*gl
, GlEditor editor
);
998 * Searching in a given direction, return the index of a given (or
999 * read) character in the input line, or the character that precedes
1000 * it in the specified search direction. Return -1 if not found.
1002 static int gl_find_char(GetLine
*gl
, int count
, int forward
, int onto
, char c
);
1005 * Return the buffer index of the nth word ending after the cursor.
1007 static int gl_nth_word_end_forward(GetLine
*gl
, int n
);
1010 * Return the buffer index of the nth word start after the cursor.
1012 static int gl_nth_word_start_forward(GetLine
*gl
, int n
);
1015 * Return the buffer index of the nth word start before the cursor.
1017 static int gl_nth_word_start_backward(GetLine
*gl
, int n
);
1020 * When called when vi command mode is enabled, this function saves the
1021 * current line and cursor position for potential restoration later
1022 * by the vi undo command.
1024 static void gl_save_for_undo(GetLine
*gl
);
1027 * If in vi mode, switch to vi command mode.
1029 static void gl_vi_command_mode(GetLine
*gl
);
1032 * In vi mode this is used to delete up to or onto a given or read
1033 * character in the input line. Also switch to insert mode if requested
1034 * after the deletion.
1036 static int gl_delete_find(GetLine
*gl
, int count
, char c
, int forward
,
1037 int onto
, int change
);
1040 * Copy the characters between the cursor and the count'th instance of
1041 * a specified (or read) character in the input line, into the cut buffer.
1043 static int gl_copy_find(GetLine
*gl
, int count
, char c
, int forward
, int onto
);
1046 * Return the line index of the parenthesis that either matches the one under
1047 * the cursor, or not over a parenthesis character, the index of the next
1048 * close parenthesis. Return -1 if not found.
1050 static int gl_index_of_matching_paren(GetLine
*gl
);
1053 * Replace a malloc'd string (or NULL), with another malloc'd copy of
1054 * a string (or NULL).
1056 static int gl_record_string(char **sptr
, const char *string
);
1059 * Enumerate text display attributes as powers of two, suitable for
1060 * use in a bit-mask.
1063 GL_TXT_STANDOUT
=1, /* Display text highlighted */
1064 GL_TXT_UNDERLINE
=2, /* Display text underlined */
1065 GL_TXT_REVERSE
=4, /* Display text with reverse video */
1066 GL_TXT_BLINK
=8, /* Display blinking text */
1067 GL_TXT_DIM
=16, /* Display text in a dim font */
1068 GL_TXT_BOLD
=32 /* Display text using a bold font */
1072 * Display the prompt regardless of the current visibility mode.
1074 static int gl_display_prompt(GetLine
*gl
);
1077 * Return the number of characters used by the prompt on the terminal.
1079 static int gl_displayed_prompt_width(GetLine
*gl
);
1082 * Prepare to return the current input line to the caller of gl_get_line().
1084 static int gl_line_ended(GetLine
*gl
, int newline_char
);
1087 * Arrange for the input line to be redisplayed when the current contents
1088 * of the output queue have been flushed.
1090 static void gl_queue_redisplay(GetLine
*gl
);
1093 * Erase the displayed representation of the input line, without
1094 * touching the buffered copy.
1096 static int gl_erase_line(GetLine
*gl
);
1099 * This function is called whenever the input line has been erased.
1101 static void gl_line_erased(GetLine
*gl
);
1104 * Arrange for the current input line to be discarded.
1106 void _gl_abandon_line(GetLine
*gl
);
1109 * The following are private internally callable versions of pertinent
1110 * public functions. Unlike their public wrapper functions, they don't
1111 * block signals while running, and assume that their arguments are valid.
1112 * They are designed to be called from places where signals are already
1113 * blocked, and where simple sanity checks have already been applied to
1116 static char *_gl_get_line(GetLine
*gl
, const char *prompt
,
1117 const char *start_line
, int start_pos
);
1118 static int _gl_query_char(GetLine
*gl
, const char *prompt
, char defchar
);
1119 static int _gl_read_char(GetLine
*gl
);
1120 static int _gl_update_size(GetLine
*gl
);
1122 * Redraw the current input line to account for a change in the terminal
1123 * size. Also install the new size in gl.
1125 static int gl_handle_tty_resize(GetLine
*gl
, int ncolumn
, int nline
);
1127 static int _gl_change_terminal(GetLine
*gl
, FILE *input_fp
, FILE *output_fp
,
1129 static int _gl_configure_getline(GetLine
*gl
, const char *app_string
,
1130 const char *app_file
, const char *user_file
);
1131 static int _gl_save_history(GetLine
*gl
, const char *filename
,
1132 const char *comment
, int max_lines
);
1133 static int _gl_load_history(GetLine
*gl
, const char *filename
,
1134 const char *comment
);
1135 static int _gl_watch_fd(GetLine
*gl
, int fd
, GlFdEvent event
,
1136 GlFdEventFn
*callback
, void *data
);
1137 static void _gl_terminal_size(GetLine
*gl
, int def_ncolumn
, int def_nline
,
1138 GlTerminalSize
*size
);
1139 static void _gl_replace_prompt(GetLine
*gl
, const char *prompt
);
1140 static int _gl_trap_signal(GetLine
*gl
, int signo
, unsigned flags
,
1141 GlAfterSignal after
, int errno_value
);
1142 static int _gl_raw_io(GetLine
*gl
, int redisplay
);
1143 static int _gl_normal_io(GetLine
*gl
);
1144 static int _gl_completion_action(GetLine
*gl
, void *data
, CplMatchFn
*match_fn
,
1145 int list_only
, const char *name
,
1146 const char *keyseq
);
1147 static int _gl_register_action(GetLine
*gl
, void *data
, GlActionFn
*fn
,
1148 const char *name
, const char *keyseq
);
1149 static int _gl_io_mode(GetLine
*gl
, GlIOMode mode
);
1150 static int _gl_set_term_size(GetLine
*gl
, int ncolumn
, int nline
);
1151 static int _gl_append_history(GetLine
*gl
, const char *line
);
1154 * Reset the completion status and associated errno value in
1155 * gl->rtn_status and gl->rtn_errno.
1157 static void gl_clear_status(GetLine
*gl
);
1160 * Record a completion status, unless a previous abnormal completion
1161 * status has already been recorded for the current call.
1163 static void gl_record_status(GetLine
*gl
, GlReturnStatus rtn_status
,
1167 * Set the maximum length of a line in a user's tecla configuration
1168 * file (not counting comments).
1170 #define GL_CONF_BUFLEN 100
1173 * Set the maximum number of arguments supported by individual commands
1174 * in tecla configuration files.
1176 #define GL_CONF_MAXARG 10
1179 * Prototype the available action functions.
1181 static KT_KEY_FN(gl_user_interrupt
);
1182 static KT_KEY_FN(gl_abort
);
1183 static KT_KEY_FN(gl_suspend
);
1184 static KT_KEY_FN(gl_stop_output
);
1185 static KT_KEY_FN(gl_start_output
);
1186 static KT_KEY_FN(gl_literal_next
);
1187 static KT_KEY_FN(gl_cursor_left
);
1188 static KT_KEY_FN(gl_cursor_right
);
1189 static KT_KEY_FN(gl_insert_mode
);
1190 static KT_KEY_FN(gl_beginning_of_line
);
1191 static KT_KEY_FN(gl_end_of_line
);
1192 static KT_KEY_FN(gl_delete_line
);
1193 static KT_KEY_FN(gl_kill_line
);
1194 static KT_KEY_FN(gl_forward_word
);
1195 static KT_KEY_FN(gl_backward_word
);
1196 static KT_KEY_FN(gl_forward_delete_char
);
1197 static KT_KEY_FN(gl_backward_delete_char
);
1198 static KT_KEY_FN(gl_forward_delete_word
);
1199 static KT_KEY_FN(gl_backward_delete_word
);
1200 static KT_KEY_FN(gl_delete_refind
);
1201 static KT_KEY_FN(gl_delete_invert_refind
);
1202 static KT_KEY_FN(gl_delete_to_column
);
1203 static KT_KEY_FN(gl_delete_to_parenthesis
);
1204 static KT_KEY_FN(gl_forward_delete_find
);
1205 static KT_KEY_FN(gl_backward_delete_find
);
1206 static KT_KEY_FN(gl_forward_delete_to
);
1207 static KT_KEY_FN(gl_backward_delete_to
);
1208 static KT_KEY_FN(gl_upcase_word
);
1209 static KT_KEY_FN(gl_downcase_word
);
1210 static KT_KEY_FN(gl_capitalize_word
);
1211 static KT_KEY_FN(gl_redisplay
);
1212 static KT_KEY_FN(gl_clear_screen
);
1213 static KT_KEY_FN(gl_transpose_chars
);
1214 static KT_KEY_FN(gl_set_mark
);
1215 static KT_KEY_FN(gl_exchange_point_and_mark
);
1216 static KT_KEY_FN(gl_kill_region
);
1217 static KT_KEY_FN(gl_copy_region_as_kill
);
1218 static KT_KEY_FN(gl_yank
);
1219 static KT_KEY_FN(gl_up_history
);
1220 static KT_KEY_FN(gl_down_history
);
1221 static KT_KEY_FN(gl_history_search_backward
);
1222 static KT_KEY_FN(gl_history_re_search_backward
);
1223 static KT_KEY_FN(gl_history_search_forward
);
1224 static KT_KEY_FN(gl_history_re_search_forward
);
1225 static KT_KEY_FN(gl_complete_word
);
1226 #ifndef HIDE_FILE_SYSTEM
1227 static KT_KEY_FN(gl_expand_filename
);
1228 static KT_KEY_FN(gl_read_from_file
);
1229 static KT_KEY_FN(gl_read_init_files
);
1230 static KT_KEY_FN(gl_list_glob
);
1232 static KT_KEY_FN(gl_del_char_or_list_or_eof
);
1233 static KT_KEY_FN(gl_list_or_eof
);
1234 static KT_KEY_FN(gl_beginning_of_history
);
1235 static KT_KEY_FN(gl_end_of_history
);
1236 static KT_KEY_FN(gl_digit_argument
);
1237 static KT_KEY_FN(gl_newline
);
1238 static KT_KEY_FN(gl_repeat_history
);
1239 static KT_KEY_FN(gl_vi_insert
);
1240 static KT_KEY_FN(gl_vi_overwrite
);
1241 static KT_KEY_FN(gl_change_case
);
1242 static KT_KEY_FN(gl_vi_insert_at_bol
);
1243 static KT_KEY_FN(gl_vi_append_at_eol
);
1244 static KT_KEY_FN(gl_vi_append
);
1245 static KT_KEY_FN(gl_backward_kill_line
);
1246 static KT_KEY_FN(gl_goto_column
);
1247 static KT_KEY_FN(gl_forward_to_word
);
1248 static KT_KEY_FN(gl_vi_replace_char
);
1249 static KT_KEY_FN(gl_vi_change_rest_of_line
);
1250 static KT_KEY_FN(gl_vi_change_line
);
1251 static KT_KEY_FN(gl_vi_change_to_bol
);
1252 static KT_KEY_FN(gl_vi_change_refind
);
1253 static KT_KEY_FN(gl_vi_change_invert_refind
);
1254 static KT_KEY_FN(gl_vi_change_to_column
);
1255 static KT_KEY_FN(gl_vi_change_to_parenthesis
);
1256 static KT_KEY_FN(gl_vi_forward_change_word
);
1257 static KT_KEY_FN(gl_vi_backward_change_word
);
1258 static KT_KEY_FN(gl_vi_forward_change_find
);
1259 static KT_KEY_FN(gl_vi_backward_change_find
);
1260 static KT_KEY_FN(gl_vi_forward_change_to
);
1261 static KT_KEY_FN(gl_vi_backward_change_to
);
1262 static KT_KEY_FN(gl_vi_forward_change_char
);
1263 static KT_KEY_FN(gl_vi_backward_change_char
);
1264 static KT_KEY_FN(gl_forward_copy_char
);
1265 static KT_KEY_FN(gl_backward_copy_char
);
1266 static KT_KEY_FN(gl_forward_find_char
);
1267 static KT_KEY_FN(gl_backward_find_char
);
1268 static KT_KEY_FN(gl_forward_to_char
);
1269 static KT_KEY_FN(gl_backward_to_char
);
1270 static KT_KEY_FN(gl_repeat_find_char
);
1271 static KT_KEY_FN(gl_invert_refind_char
);
1272 static KT_KEY_FN(gl_append_yank
);
1273 static KT_KEY_FN(gl_backward_copy_word
);
1274 static KT_KEY_FN(gl_forward_copy_word
);
1275 static KT_KEY_FN(gl_copy_to_bol
);
1276 static KT_KEY_FN(gl_copy_refind
);
1277 static KT_KEY_FN(gl_copy_invert_refind
);
1278 static KT_KEY_FN(gl_copy_to_column
);
1279 static KT_KEY_FN(gl_copy_to_parenthesis
);
1280 static KT_KEY_FN(gl_copy_rest_of_line
);
1281 static KT_KEY_FN(gl_copy_line
);
1282 static KT_KEY_FN(gl_backward_copy_find
);
1283 static KT_KEY_FN(gl_forward_copy_find
);
1284 static KT_KEY_FN(gl_backward_copy_to
);
1285 static KT_KEY_FN(gl_forward_copy_to
);
1286 static KT_KEY_FN(gl_vi_undo
);
1287 static KT_KEY_FN(gl_emacs_editing_mode
);
1288 static KT_KEY_FN(gl_vi_editing_mode
);
1289 static KT_KEY_FN(gl_ring_bell
);
1290 static KT_KEY_FN(gl_vi_repeat_change
);
1291 static KT_KEY_FN(gl_find_parenthesis
);
1292 static KT_KEY_FN(gl_list_history
);
1293 static KT_KEY_FN(gl_list_completions
);
1294 static KT_KEY_FN(gl_run_external_action
);
1297 * Name the available action functions.
1299 static const struct {const char *name
; KT_KEY_FN(*fn
);} gl_actions
[] = {
1300 {"user-interrupt", gl_user_interrupt
},
1301 {"abort", gl_abort
},
1302 {"suspend", gl_suspend
},
1303 {"stop-output", gl_stop_output
},
1304 {"start-output", gl_start_output
},
1305 {"literal-next", gl_literal_next
},
1306 {"cursor-right", gl_cursor_right
},
1307 {"cursor-left", gl_cursor_left
},
1308 {"insert-mode", gl_insert_mode
},
1309 {"beginning-of-line", gl_beginning_of_line
},
1310 {"end-of-line", gl_end_of_line
},
1311 {"delete-line", gl_delete_line
},
1312 {"kill-line", gl_kill_line
},
1313 {"forward-word", gl_forward_word
},
1314 {"backward-word", gl_backward_word
},
1315 {"forward-delete-char", gl_forward_delete_char
},
1316 {"backward-delete-char", gl_backward_delete_char
},
1317 {"forward-delete-word", gl_forward_delete_word
},
1318 {"backward-delete-word", gl_backward_delete_word
},
1319 {"delete-refind", gl_delete_refind
},
1320 {"delete-invert-refind", gl_delete_invert_refind
},
1321 {"delete-to-column", gl_delete_to_column
},
1322 {"delete-to-parenthesis", gl_delete_to_parenthesis
},
1323 {"forward-delete-find", gl_forward_delete_find
},
1324 {"backward-delete-find", gl_backward_delete_find
},
1325 {"forward-delete-to", gl_forward_delete_to
},
1326 {"backward-delete-to", gl_backward_delete_to
},
1327 {"upcase-word", gl_upcase_word
},
1328 {"downcase-word", gl_downcase_word
},
1329 {"capitalize-word", gl_capitalize_word
},
1330 {"redisplay", gl_redisplay
},
1331 {"clear-screen", gl_clear_screen
},
1332 {"transpose-chars", gl_transpose_chars
},
1333 {"set-mark", gl_set_mark
},
1334 {"exchange-point-and-mark", gl_exchange_point_and_mark
},
1335 {"kill-region", gl_kill_region
},
1336 {"copy-region-as-kill", gl_copy_region_as_kill
},
1338 {"up-history", gl_up_history
},
1339 {"down-history", gl_down_history
},
1340 {"history-search-backward", gl_history_search_backward
},
1341 {"history-re-search-backward", gl_history_re_search_backward
},
1342 {"history-search-forward", gl_history_search_forward
},
1343 {"history-re-search-forward", gl_history_re_search_forward
},
1344 {"complete-word", gl_complete_word
},
1345 #ifndef HIDE_FILE_SYSTEM
1346 {"expand-filename", gl_expand_filename
},
1347 {"read-from-file", gl_read_from_file
},
1348 {"read-init-files", gl_read_init_files
},
1349 {"list-glob", gl_list_glob
},
1351 {"del-char-or-list-or-eof", gl_del_char_or_list_or_eof
},
1352 {"beginning-of-history", gl_beginning_of_history
},
1353 {"end-of-history", gl_end_of_history
},
1354 {"digit-argument", gl_digit_argument
},
1355 {"newline", gl_newline
},
1356 {"repeat-history", gl_repeat_history
},
1357 {"vi-insert", gl_vi_insert
},
1358 {"vi-overwrite", gl_vi_overwrite
},
1359 {"vi-insert-at-bol", gl_vi_insert_at_bol
},
1360 {"vi-append-at-eol", gl_vi_append_at_eol
},
1361 {"vi-append", gl_vi_append
},
1362 {"change-case", gl_change_case
},
1363 {"backward-kill-line", gl_backward_kill_line
},
1364 {"goto-column", gl_goto_column
},
1365 {"forward-to-word", gl_forward_to_word
},
1366 {"vi-replace-char", gl_vi_replace_char
},
1367 {"vi-change-rest-of-line", gl_vi_change_rest_of_line
},
1368 {"vi-change-line", gl_vi_change_line
},
1369 {"vi-change-to-bol", gl_vi_change_to_bol
},
1370 {"vi-change-refind", gl_vi_change_refind
},
1371 {"vi-change-invert-refind", gl_vi_change_invert_refind
},
1372 {"vi-change-to-column", gl_vi_change_to_column
},
1373 {"vi-change-to-parenthesis", gl_vi_change_to_parenthesis
},
1374 {"forward-copy-char", gl_forward_copy_char
},
1375 {"backward-copy-char", gl_backward_copy_char
},
1376 {"forward-find-char", gl_forward_find_char
},
1377 {"backward-find-char", gl_backward_find_char
},
1378 {"forward-to-char", gl_forward_to_char
},
1379 {"backward-to-char", gl_backward_to_char
},
1380 {"repeat-find-char", gl_repeat_find_char
},
1381 {"invert-refind-char", gl_invert_refind_char
},
1382 {"append-yank", gl_append_yank
},
1383 {"backward-copy-word", gl_backward_copy_word
},
1384 {"forward-copy-word", gl_forward_copy_word
},
1385 {"copy-to-bol", gl_copy_to_bol
},
1386 {"copy-refind", gl_copy_refind
},
1387 {"copy-invert-refind", gl_copy_invert_refind
},
1388 {"copy-to-column", gl_copy_to_column
},
1389 {"copy-to-parenthesis", gl_copy_to_parenthesis
},
1390 {"copy-rest-of-line", gl_copy_rest_of_line
},
1391 {"copy-line", gl_copy_line
},
1392 {"backward-copy-find", gl_backward_copy_find
},
1393 {"forward-copy-find", gl_forward_copy_find
},
1394 {"backward-copy-to", gl_backward_copy_to
},
1395 {"forward-copy-to", gl_forward_copy_to
},
1396 {"list-or-eof", gl_list_or_eof
},
1397 {"vi-undo", gl_vi_undo
},
1398 {"vi-backward-change-word", gl_vi_backward_change_word
},
1399 {"vi-forward-change-word", gl_vi_forward_change_word
},
1400 {"vi-backward-change-find", gl_vi_backward_change_find
},
1401 {"vi-forward-change-find", gl_vi_forward_change_find
},
1402 {"vi-backward-change-to", gl_vi_backward_change_to
},
1403 {"vi-forward-change-to", gl_vi_forward_change_to
},
1404 {"vi-backward-change-char", gl_vi_backward_change_char
},
1405 {"vi-forward-change-char", gl_vi_forward_change_char
},
1406 {"emacs-mode", gl_emacs_editing_mode
},
1407 {"vi-mode", gl_vi_editing_mode
},
1408 {"ring-bell", gl_ring_bell
},
1409 {"vi-repeat-change", gl_vi_repeat_change
},
1410 {"find-parenthesis", gl_find_parenthesis
},
1411 {"list-history", gl_list_history
},
1415 * Define the default key-bindings in emacs mode.
1417 static const KtKeyBinding gl_emacs_bindings
[] = {
1418 {"right", "cursor-right"},
1419 {"^F", "cursor-right"},
1420 {"left", "cursor-left"},
1421 {"^B", "cursor-left"},
1422 {"M-i", "insert-mode"},
1423 {"M-I", "insert-mode"},
1424 {"^A", "beginning-of-line"},
1425 {"^E", "end-of-line"},
1426 {"^U", "delete-line"},
1427 {"^K", "kill-line"},
1428 {"M-f", "forward-word"},
1429 {"M-F", "forward-word"},
1430 {"M-b", "backward-word"},
1431 {"M-B", "backward-word"},
1432 {"^D", "del-char-or-list-or-eof"},
1433 {"^H", "backward-delete-char"},
1434 {"^?", "backward-delete-char"},
1435 {"M-d", "forward-delete-word"},
1436 {"M-D", "forward-delete-word"},
1437 {"M-^H", "backward-delete-word"},
1438 {"M-^?", "backward-delete-word"},
1439 {"M-u", "upcase-word"},
1440 {"M-U", "upcase-word"},
1441 {"M-l", "downcase-word"},
1442 {"M-L", "downcase-word"},
1443 {"M-c", "capitalize-word"},
1444 {"M-C", "capitalize-word"},
1445 {"^R", "redisplay"},
1446 {"^L", "clear-screen"},
1447 {"^T", "transpose-chars"},
1449 {"^X^X", "exchange-point-and-mark"},
1450 {"^W", "kill-region"},
1451 {"M-w", "copy-region-as-kill"},
1452 {"M-W", "copy-region-as-kill"},
1454 {"^P", "up-history"},
1455 {"up", "up-history"},
1456 {"^N", "down-history"},
1457 {"down", "down-history"},
1458 {"M-p", "history-search-backward"},
1459 {"M-P", "history-search-backward"},
1460 {"M-n", "history-search-forward"},
1461 {"M-N", "history-search-forward"},
1462 {"\t", "complete-word"},
1463 #ifndef HIDE_FILE_SYSTEM
1464 {"^X*", "expand-filename"},
1465 {"^X^F", "read-from-file"},
1466 {"^X^R", "read-init-files"},
1467 {"^Xg", "list-glob"},
1468 {"^XG", "list-glob"},
1470 {"^Xh", "list-history"},
1471 {"^XH", "list-history"},
1472 {"M-<", "beginning-of-history"},
1473 {"M->", "end-of-history"},
1474 {"M-0", "digit-argument"},
1475 {"M-1", "digit-argument"},
1476 {"M-2", "digit-argument"},
1477 {"M-3", "digit-argument"},
1478 {"M-4", "digit-argument"},
1479 {"M-5", "digit-argument"},
1480 {"M-6", "digit-argument"},
1481 {"M-7", "digit-argument"},
1482 {"M-8", "digit-argument"},
1483 {"M-9", "digit-argument"},
1486 {"M-o", "repeat-history"},
1487 {"M-C-v", "vi-mode"},
1491 * Define the default key-bindings in vi mode. Note that in vi-mode
1492 * meta-key bindings are command-mode bindings. For example M-i first
1493 * switches to command mode if not already in that mode, then moves
1494 * the cursor one position right, as in vi.
1496 static const KtKeyBinding gl_vi_bindings
[] = {
1497 {"^D", "list-or-eof"},
1498 #ifndef HIDE_FILE_SYSTEM
1499 {"^G", "list-glob"},
1501 {"^H", "backward-delete-char"},
1502 {"\t", "complete-word"},
1505 {"^L", "clear-screen"},
1506 {"^N", "down-history"},
1507 {"^P", "up-history"},
1508 {"^R", "redisplay"},
1509 {"^U", "backward-kill-line"},
1510 {"^W", "backward-delete-word"},
1511 #ifndef HIDE_FILE_SYSTEM
1512 {"^X^F", "read-from-file"},
1513 {"^X^R", "read-init-files"},
1514 {"^X*", "expand-filename"},
1516 {"^?", "backward-delete-char"},
1517 {"M- ", "cursor-right"},
1518 {"M-$", "end-of-line"},
1519 #ifndef HIDE_FILE_SYSTEM
1520 {"M-*", "expand-filename"},
1522 {"M-+", "down-history"},
1523 {"M--", "up-history"},
1524 {"M-<", "beginning-of-history"},
1525 {"M->", "end-of-history"},
1526 {"M-^", "beginning-of-line"},
1527 {"M-;", "repeat-find-char"},
1528 {"M-,", "invert-refind-char"},
1529 {"M-|", "goto-column"},
1530 {"M-~", "change-case"},
1531 {"M-.", "vi-repeat-change"},
1532 {"M-%", "find-parenthesis"},
1533 {"M-0", "digit-argument"},
1534 {"M-1", "digit-argument"},
1535 {"M-2", "digit-argument"},
1536 {"M-3", "digit-argument"},
1537 {"M-4", "digit-argument"},
1538 {"M-5", "digit-argument"},
1539 {"M-6", "digit-argument"},
1540 {"M-7", "digit-argument"},
1541 {"M-8", "digit-argument"},
1542 {"M-9", "digit-argument"},
1543 {"M-a", "vi-append"},
1544 {"M-A", "vi-append-at-eol"},
1545 {"M-b", "backward-word"},
1546 {"M-B", "backward-word"},
1547 {"M-C", "vi-change-rest-of-line"},
1548 {"M-cb", "vi-backward-change-word"},
1549 {"M-cB", "vi-backward-change-word"},
1550 {"M-cc", "vi-change-line"},
1551 {"M-ce", "vi-forward-change-word"},
1552 {"M-cE", "vi-forward-change-word"},
1553 {"M-cw", "vi-forward-change-word"},
1554 {"M-cW", "vi-forward-change-word"},
1555 {"M-cF", "vi-backward-change-find"},
1556 {"M-cf", "vi-forward-change-find"},
1557 {"M-cT", "vi-backward-change-to"},
1558 {"M-ct", "vi-forward-change-to"},
1559 {"M-c;", "vi-change-refind"},
1560 {"M-c,", "vi-change-invert-refind"},
1561 {"M-ch", "vi-backward-change-char"},
1562 {"M-c^H", "vi-backward-change-char"},
1563 {"M-c^?", "vi-backward-change-char"},
1564 {"M-cl", "vi-forward-change-char"},
1565 {"M-c ", "vi-forward-change-char"},
1566 {"M-c^", "vi-change-to-bol"},
1567 {"M-c0", "vi-change-to-bol"},
1568 {"M-c$", "vi-change-rest-of-line"},
1569 {"M-c|", "vi-change-to-column"},
1570 {"M-c%", "vi-change-to-parenthesis"},
1571 {"M-dh", "backward-delete-char"},
1572 {"M-d^H", "backward-delete-char"},
1573 {"M-d^?", "backward-delete-char"},
1574 {"M-dl", "forward-delete-char"},
1575 {"M-d ", "forward-delete-char"},
1576 {"M-dd", "delete-line"},
1577 {"M-db", "backward-delete-word"},
1578 {"M-dB", "backward-delete-word"},
1579 {"M-de", "forward-delete-word"},
1580 {"M-dE", "forward-delete-word"},
1581 {"M-dw", "forward-delete-word"},
1582 {"M-dW", "forward-delete-word"},
1583 {"M-dF", "backward-delete-find"},
1584 {"M-df", "forward-delete-find"},
1585 {"M-dT", "backward-delete-to"},
1586 {"M-dt", "forward-delete-to"},
1587 {"M-d;", "delete-refind"},
1588 {"M-d,", "delete-invert-refind"},
1589 {"M-d^", "backward-kill-line"},
1590 {"M-d0", "backward-kill-line"},
1591 {"M-d$", "kill-line"},
1592 {"M-D", "kill-line"},
1593 {"M-d|", "delete-to-column"},
1594 {"M-d%", "delete-to-parenthesis"},
1595 {"M-e", "forward-word"},
1596 {"M-E", "forward-word"},
1597 {"M-f", "forward-find-char"},
1598 {"M-F", "backward-find-char"},
1599 {"M--", "up-history"},
1600 {"M-h", "cursor-left"},
1601 {"M-H", "beginning-of-history"},
1602 {"M-i", "vi-insert"},
1603 {"M-I", "vi-insert-at-bol"},
1604 {"M-j", "down-history"},
1605 {"M-J", "history-search-forward"},
1606 {"M-k", "up-history"},
1607 {"M-K", "history-search-backward"},
1608 {"M-l", "cursor-right"},
1609 {"M-L", "end-of-history"},
1610 {"M-n", "history-re-search-forward"},
1611 {"M-N", "history-re-search-backward"},
1612 {"M-p", "append-yank"},
1614 {"M-r", "vi-replace-char"},
1615 {"M-R", "vi-overwrite"},
1616 {"M-s", "vi-forward-change-char"},
1617 {"M-S", "vi-change-line"},
1618 {"M-t", "forward-to-char"},
1619 {"M-T", "backward-to-char"},
1621 {"M-w", "forward-to-word"},
1622 {"M-W", "forward-to-word"},
1623 {"M-x", "forward-delete-char"},
1624 {"M-X", "backward-delete-char"},
1625 {"M-yh", "backward-copy-char"},
1626 {"M-y^H", "backward-copy-char"},
1627 {"M-y^?", "backward-copy-char"},
1628 {"M-yl", "forward-copy-char"},
1629 {"M-y ", "forward-copy-char"},
1630 {"M-ye", "forward-copy-word"},
1631 {"M-yE", "forward-copy-word"},
1632 {"M-yw", "forward-copy-word"},
1633 {"M-yW", "forward-copy-word"},
1634 {"M-yb", "backward-copy-word"},
1635 {"M-yB", "backward-copy-word"},
1636 {"M-yf", "forward-copy-find"},
1637 {"M-yF", "backward-copy-find"},
1638 {"M-yt", "forward-copy-to"},
1639 {"M-yT", "backward-copy-to"},
1640 {"M-y;", "copy-refind"},
1641 {"M-y,", "copy-invert-refind"},
1642 {"M-y^", "copy-to-bol"},
1643 {"M-y0", "copy-to-bol"},
1644 {"M-y$", "copy-rest-of-line"},
1645 {"M-yy", "copy-line"},
1646 {"M-Y", "copy-line"},
1647 {"M-y|", "copy-to-column"},
1648 {"M-y%", "copy-to-parenthesis"},
1649 {"M-^E", "emacs-mode"},
1650 {"M-^H", "cursor-left"},
1651 {"M-^?", "cursor-left"},
1652 {"M-^L", "clear-screen"},
1653 {"M-^N", "down-history"},
1654 {"M-^P", "up-history"},
1655 {"M-^R", "redisplay"},
1656 {"M-^D", "list-or-eof"},
1657 {"M-\r", "newline"},
1658 {"M-\t", "complete-word"},
1659 {"M-\n", "newline"},
1660 #ifndef HIDE_FILE_SYSTEM
1661 {"M-^X^R", "read-init-files"},
1663 {"M-^Xh", "list-history"},
1664 {"M-^XH", "list-history"},
1665 {"down", "down-history"},
1666 {"up", "up-history"},
1667 {"left", "cursor-left"},
1668 {"right", "cursor-right"},
1671 /*.......................................................................
1672 * Create a new GetLine object.
1675 * linelen size_t The maximum line length to allow for.
1676 * histlen size_t The number of bytes to allocate for recording
1677 * a circular buffer of history lines.
1679 * return GetLine * The new object, or NULL on error.
1681 GetLine
*new_GetLine(size_t linelen
, size_t histlen
)
1683 GetLine
*gl
; /* The object to be returned */
1686 * Check the arguments.
1693 * Allocate the container.
1695 gl
= (GetLine
*) malloc(sizeof(GetLine
));
1701 * Before attempting any operation that might fail, initialize the
1702 * container at least up to the point at which it can safely be passed
1708 #ifndef HIDE_FILE_SYSTEM
1709 gl
->cplfn
.fn
= cpl_file_completions
;
1711 gl
->cplfn
.fn
= gl_no_completions
;
1713 gl
->cplfn
.data
= NULL
;
1714 #ifndef WITHOUT_FILE_SYSTEM
1721 gl
->input_fp
= NULL
;
1722 gl
->output_fp
= NULL
;
1726 gl
->flush_fn
= gl_flush_terminal
;
1727 gl
->io_mode
= GL_NORMAL_MODE
;
1729 gl
->pending_io
= GLP_WRITE
; /* We will start by writing the prompt */
1730 gl_clear_status(gl
);
1731 gl
->linelen
= linelen
;
1736 gl
->prompt_changed
= 0;
1737 gl
->prompt_style
= GL_LITERAL_PROMPT
;
1739 gl
->ext_act_mem
= NULL
;
1742 gl
->signals_masked
= 0;
1743 gl
->signals_overriden
= 0;
1744 sigemptyset(&gl
->all_signal_set
);
1745 sigemptyset(&gl
->old_signal_set
);
1746 sigemptyset(&gl
->use_signal_set
);
1747 gl
->bindings
= NULL
;
1749 gl
->buff_curpos
= 0;
1750 gl
->term_curpos
= 0;
1753 gl
->insert_curpos
= 0;
1763 gl
->current_action
.fn
= 0;
1764 gl
->current_action
.data
= NULL
;
1765 gl
->current_count
= 0;
1767 gl
->preload_history
= 0;
1768 gl
->keyseq_count
= 0;
1769 gl
->last_search
= -1;
1770 gl
->editor
= GL_EMACS_MODE
;
1771 gl
->silence_bell
= 0;
1772 gl
->automatic_history
= 1;
1773 gl
->vi
.undo
.line
= NULL
;
1774 gl
->vi
.undo
.buff_curpos
= 0;
1775 gl
->vi
.undo
.ntotal
= 0;
1776 gl
->vi
.undo
.saved
= 0;
1777 gl
->vi
.repeat
.action
.fn
= 0;
1778 gl
->vi
.repeat
.action
.data
= 0;
1779 gl
->vi
.repeat
.count
= 0;
1780 gl
->vi
.repeat
.input_curpos
= 0;
1781 gl
->vi
.repeat
.command_curpos
= 0;
1782 gl
->vi
.repeat
.input_char
= '\0';
1783 gl
->vi
.repeat
.saved
= 0;
1784 gl
->vi
.repeat
.active
= 0;
1786 gl
->vi
.find_forward
= 0;
1787 gl
->vi
.find_onto
= 0;
1788 gl
->vi
.find_char
= '\0';
1795 gl
->clear_eol
= NULL
;
1796 gl
->clear_eod
= NULL
;
1801 gl
->sound_bell
= NULL
;
1803 gl
->underline
= NULL
;
1804 gl
->standout
= NULL
;
1808 gl
->text_attr_off
= NULL
;
1814 #elif defined(USE_TERMCAP)
1815 gl
->tgetent_buf
= NULL
;
1816 gl
->tgetstr_buf
= NULL
;
1818 gl
->app_file
= NULL
;
1819 gl
->user_file
= NULL
;
1822 gl
->last_signal
= -1;
1824 gl
->fd_node_mem
= NULL
;
1825 gl
->fd_nodes
= NULL
;
1830 gl
->timer
.dt
.tv_sec
= 0;
1831 gl
->timer
.dt
.tv_usec
= 0;
1833 gl
->timer
.data
= NULL
;
1836 * Allocate an error reporting buffer.
1838 gl
->err
= _new_ErrMsg();
1840 return del_GetLine(gl
);
1842 * Allocate the history buffer.
1844 gl
->glh
= _new_GlHistory(histlen
);
1846 return del_GetLine(gl
);
1848 * Allocate the resource object for file-completion.
1850 gl
->cpl
= new_WordCompletion();
1852 return del_GetLine(gl
);
1854 * Allocate the resource object for file-completion.
1856 #ifndef WITHOUT_FILE_SYSTEM
1857 gl
->ef
= new_ExpandFile();
1859 return del_GetLine(gl
);
1862 * Allocate a string-segment memory allocator for use in storing terminal
1863 * capablity strings.
1865 gl
->capmem
= _new_StringGroup(CAPMEM_SEGMENT_SIZE
);
1867 return del_GetLine(gl
);
1869 * Allocate the character queue that is used to buffer terminal output.
1871 gl
->cq
= _new_GlCharQueue();
1873 return del_GetLine(gl
);
1875 * Allocate a line buffer, leaving 2 extra characters for the terminating
1876 * '\n' and '\0' characters
1878 gl
->line
= (char *) malloc(linelen
+ 2);
1881 return del_GetLine(gl
);
1884 * Start with an empty input line.
1886 gl_truncate_buffer(gl
, 0);
1888 * Allocate a cut buffer.
1890 gl
->cutbuf
= (char *) malloc(linelen
+ 2);
1893 return del_GetLine(gl
);
1895 gl
->cutbuf
[0] = '\0';
1897 * Allocate an initial empty prompt.
1899 _gl_replace_prompt(gl
, NULL
);
1902 return del_GetLine(gl
);
1905 * Allocate a vi undo buffer.
1907 gl
->vi
.undo
.line
= (char *) malloc(linelen
+ 2);
1908 if(!gl
->vi
.undo
.line
) {
1910 return del_GetLine(gl
);
1912 gl
->vi
.undo
.line
[0] = '\0';
1914 * Allocate a freelist from which to allocate nodes for the list
1915 * of completion functions.
1917 gl
->cpl_mem
= _new_FreeList(sizeof(GlCplCallback
), GL_CPL_FREELIST_BLOCKING
);
1919 return del_GetLine(gl
);
1921 * Allocate a freelist from which to allocate nodes for the list
1922 * of external action functions.
1924 gl
->ext_act_mem
= _new_FreeList(sizeof(GlExternalAction
),
1925 GL_EXT_ACT_FREELIST_BLOCKING
);
1926 if(!gl
->ext_act_mem
)
1927 return del_GetLine(gl
);
1929 * Allocate a freelist from which to allocate nodes for the list
1932 gl
->sig_mem
= _new_FreeList(sizeof(GlSignalNode
), GLS_FREELIST_BLOCKING
);
1934 return del_GetLine(gl
);
1936 * Install initial dispositions for the default list of signals that
1937 * gl_get_line() traps.
1939 for(i
=0; i
<sizeof(gl_signal_list
)/sizeof(gl_signal_list
[0]); i
++) {
1940 const struct GlDefSignal
*sig
= gl_signal_list
+ i
;
1941 if(_gl_trap_signal(gl
, sig
->signo
, sig
->flags
, sig
->after
,
1943 return del_GetLine(gl
);
1946 * Allocate an empty table of key bindings.
1948 gl
->bindings
= _new_KeyTab();
1950 return del_GetLine(gl
);
1952 * Define the available actions that can be bound to key sequences.
1954 for(i
=0; i
<sizeof(gl_actions
)/sizeof(gl_actions
[0]); i
++) {
1955 if(_kt_set_action(gl
->bindings
, gl_actions
[i
].name
, gl_actions
[i
].fn
, NULL
))
1956 return del_GetLine(gl
);
1959 * Set up the default bindings.
1961 if(gl_change_editor(gl
, gl
->editor
))
1962 return del_GetLine(gl
);
1964 * Allocate termcap buffers.
1967 gl
->tgetent_buf
= (char *) malloc(TERMCAP_BUF_SIZE
);
1968 gl
->tgetstr_buf
= (char *) malloc(TERMCAP_BUF_SIZE
);
1969 if(!gl
->tgetent_buf
|| !gl
->tgetstr_buf
) {
1971 return del_GetLine(gl
);
1975 * Set up for I/O assuming stdin and stdout.
1977 if(_gl_change_terminal(gl
, stdin
, stdout
, getenv("TERM")))
1978 return del_GetLine(gl
);
1980 * Create a freelist for use in allocating GlFdNode list nodes.
1983 gl
->fd_node_mem
= _new_FreeList(sizeof(GlFdNode
), GLFD_FREELIST_BLOCKING
);
1984 if(!gl
->fd_node_mem
)
1985 return del_GetLine(gl
);
1988 * We are done for now.
1993 /*.......................................................................
1994 * Delete a GetLine object.
1997 * gl GetLine * The object to be deleted.
1999 * return GetLine * The deleted object (always NULL).
2001 GetLine
*del_GetLine(GetLine
*gl
)
2005 * If the terminal is in raw server mode, reset it.
2009 * Deallocate all objects contained by gl.
2011 gl
->err
= _del_ErrMsg(gl
->err
);
2012 gl
->glh
= _del_GlHistory(gl
->glh
);
2013 gl
->cpl
= del_WordCompletion(gl
->cpl
);
2014 #ifndef WITHOUT_FILE_SYSTEM
2015 gl
->ef
= del_ExpandFile(gl
->ef
);
2017 gl
->capmem
= _del_StringGroup(gl
->capmem
);
2018 gl
->cq
= _del_GlCharQueue(gl
->cq
);
2020 fclose(gl
->file_fp
);
2025 gl
->cpl_mem
= _del_FreeList(gl
->cpl_mem
, 1);
2026 gl
->ext_act_mem
= _del_FreeList(gl
->ext_act_mem
, 1);
2027 gl
->sig_mem
= _del_FreeList(gl
->sig_mem
, 1);
2028 gl
->sigs
= NULL
; /* Already freed by freeing sig_mem */
2029 gl
->bindings
= _del_KeyTab(gl
->bindings
);
2030 free(gl
->vi
.undo
.line
);
2032 free(gl
->tgetent_buf
);
2033 free(gl
->tgetstr_buf
);
2036 free(gl
->user_file
);
2038 gl
->fd_node_mem
= _del_FreeList(gl
->fd_node_mem
, 1);
2039 gl
->fd_nodes
= NULL
; /* Already freed by freeing gl->fd_node_mem */
2042 * Delete the now empty container.
2049 /*.......................................................................
2050 * Bind a control or meta character to an action.
2053 * gl GetLine * The resource object of this program.
2054 * binder KtBinder The source of the binding.
2055 * c char The control or meta character.
2056 * If this is '\0', the call is ignored.
2057 * action const char * The action name to bind the key to.
2059 * return int 0 - OK.
2062 static int gl_bind_control_char(GetLine
*gl
, KtBinder binder
, char c
,
2067 * Quietly reject binding to the NUL control character, since this
2068 * is an ambiguous prefix of all bindings.
2073 * Making sure not to bind characters which aren't either control or
2076 if(IS_CTRL_CHAR(c
) || IS_META_CHAR(c
)) {
2083 * Install the binding.
2085 if(_kt_set_keybinding(gl
->bindings
, binder
, keyseq
, action
)) {
2086 _err_record_msg(gl
->err
, _kt_last_error(gl
->bindings
), END_ERR_MSG
);
2092 /*.......................................................................
2093 * Read a line from the user.
2096 * gl GetLine * A resource object returned by new_GetLine().
2097 * prompt char * The prompt to prefix the line with.
2098 * start_line char * The initial contents of the input line, or NULL
2099 * if it should start out empty.
2100 * start_pos int If start_line isn't NULL, this specifies the
2101 * index of the character over which the cursor
2102 * should initially be positioned within the line.
2103 * If you just want it to follow the last character
2104 * of the line, send -1.
2106 * return char * An internal buffer containing the input line, or
2107 * NULL at the end of input. If the line fitted in
2108 * the buffer there will be a '\n' newline character
2109 * before the terminating '\0'. If it was truncated
2110 * there will be no newline character, and the remains
2111 * of the line should be retrieved via further calls
2114 char *gl_get_line(GetLine
*gl
, const char *prompt
,
2115 const char *start_line
, int start_pos
)
2117 char *retval
; /* The return value of _gl_get_line() */
2119 * Check the arguments.
2126 * Temporarily block all of the signals that we have been asked to trap.
2128 if(gl_mask_signals(gl
, &gl
->old_signal_set
))
2131 * Perform the command-line editing task.
2133 retval
= _gl_get_line(gl
, prompt
, start_line
, start_pos
);
2135 * Restore the process signal mask to how it was when this function was
2138 gl_unmask_signals(gl
, &gl
->old_signal_set
);
2143 /*.......................................................................
2144 * This is the main body of the public function gl_get_line().
2146 static char *_gl_get_line(GetLine
*gl
, const char *prompt
,
2147 const char *start_line
, int start_pos
)
2149 int waserr
= 0; /* True if an error occurs */
2151 * Assume that this call will successfully complete the input
2152 * line until proven otherwise.
2154 gl_clear_status(gl
);
2156 * If this is the first call to this function since new_GetLine(),
2157 * complete any postponed configuration.
2159 if(!gl
->configured
) {
2160 (void) _gl_configure_getline(gl
, NULL
, NULL
, TECLA_CONFIG_FILE
);
2164 * Before installing our signal handler functions, record the fact
2165 * that there are no pending signals.
2167 gl_pending_signal
= -1;
2169 * Temporarily override the signal handlers of the calling program,
2170 * so that we can intercept signals that would leave the terminal
2173 waserr
= gl_override_signal_handlers(gl
);
2175 * After recording the current terminal settings, switch the terminal
2176 * into raw input mode.
2178 waserr
= waserr
|| _gl_raw_io(gl
, 1);
2180 * Attempt to read the line. This will require more than one attempt if
2181 * either a current temporary input file is opened by gl_get_input_line()
2182 * or the end of a temporary input file is reached by gl_read_stream_line().
2186 * Read a line from a non-interactive stream?
2188 if(gl
->file_fp
|| !gl
->is_term
) {
2189 if(gl_read_stream_line(gl
)==0) {
2191 } else if(gl
->file_fp
) {
2192 gl_revert_input(gl
);
2193 gl_record_status(gl
, GLR_NEWLINE
, 0);
2200 * Read from the terminal? Note that the above if() block may have
2201 * changed gl->file_fp, so it is necessary to retest it here, rather
2202 * than using an else statement.
2204 if(!gl
->file_fp
&& gl
->is_term
) {
2205 if(gl_get_input_line(gl
, prompt
, start_line
, start_pos
))
2212 * If an error occurred, but gl->rtn_status is still set to
2213 * GLR_NEWLINE, change the status to GLR_ERROR. Otherwise
2214 * leave it at whatever specific value was assigned by the function
2215 * that aborted input. This means that only functions that trap
2216 * non-generic errors have to remember to update gl->rtn_status
2219 if(waserr
&& gl
->rtn_status
== GLR_NEWLINE
)
2220 gl_record_status(gl
, GLR_ERROR
, errno
);
2222 * Restore terminal settings.
2224 if(gl
->io_mode
!= GL_SERVER_MODE
)
2227 * Restore the signal handlers.
2229 gl_restore_signal_handlers(gl
);
2231 * If gl_get_line() gets aborted early, the errno value associated
2232 * with the event that caused this to happen is recorded in
2233 * gl->rtn_errno. Since errno may have been overwritten by cleanup
2234 * functions after this, restore its value to the value that it had
2235 * when the error condition occured, so that the caller can examine it
2236 * to find out what happened.
2238 errno
= gl
->rtn_errno
;
2240 * Check the completion status to see how to return.
2242 switch(gl
->rtn_status
) {
2243 case GLR_NEWLINE
: /* Success */
2245 case GLR_BLOCKED
: /* These events abort the current input line, */
2246 case GLR_SIGNAL
: /* when in normal blocking I/O mode, but only */
2247 case GLR_TIMEOUT
: /* temporarily pause line editing when in */
2248 case GLR_FDABORT
: /* non-blocking server I/O mode. */
2249 if(gl
->io_mode
!= GL_SERVER_MODE
)
2250 _gl_abandon_line(gl
);
2252 case GLR_ERROR
: /* Unrecoverable errors abort the input line, */
2253 case GLR_EOF
: /* regardless of the I/O mode. */
2255 _gl_abandon_line(gl
);
2260 /*.......................................................................
2261 * Read a single character from the user.
2264 * gl GetLine * A resource object returned by new_GetLine().
2265 * prompt char * The prompt to prefix the line with, or NULL if
2266 * no prompt is required.
2267 * defchar char The character to substitute if the
2268 * user simply hits return, or '\n' if you don't
2269 * need to substitute anything.
2271 * return int The character that was read, or EOF if the read
2272 * had to be aborted (in which case you can call
2273 * gl_return_status() to find out why).
2275 int gl_query_char(GetLine
*gl
, const char *prompt
, char defchar
)
2277 int retval
; /* The return value of _gl_query_char() */
2279 * Check the arguments.
2286 * Temporarily block all of the signals that we have been asked to trap.
2288 if(gl_mask_signals(gl
, &gl
->old_signal_set
))
2291 * Perform the character reading task.
2293 retval
= _gl_query_char(gl
, prompt
, defchar
);
2295 * Restore the process signal mask to how it was when this function was
2298 gl_unmask_signals(gl
, &gl
->old_signal_set
);
2302 /*.......................................................................
2303 * This is the main body of the public function gl_query_char().
2305 static int _gl_query_char(GetLine
*gl
, const char *prompt
, char defchar
)
2307 int c
= EOF
; /* The character to be returned */
2308 int waserr
= 0; /* True if an error occurs */
2310 * Assume that this call will successfully complete the input operation
2311 * until proven otherwise.
2313 gl_clear_status(gl
);
2315 * If this is the first call to this function or gl_get_line(),
2316 * since new_GetLine(), complete any postponed configuration.
2318 if(!gl
->configured
) {
2319 (void) _gl_configure_getline(gl
, NULL
, NULL
, TECLA_CONFIG_FILE
);
2323 * Before installing our signal handler functions, record the fact
2324 * that there are no pending signals.
2326 gl_pending_signal
= -1;
2328 * Temporarily override the signal handlers of the calling program,
2329 * so that we can intercept signals that would leave the terminal
2332 waserr
= gl_override_signal_handlers(gl
);
2334 * After recording the current terminal settings, switch the terminal
2335 * into raw input mode without redisplaying any partially entered
2338 waserr
= waserr
|| _gl_raw_io(gl
, 0);
2340 * Attempt to read the line. This will require more than one attempt if
2341 * either a current temporary input file is opened by gl_get_input_line()
2342 * or the end of a temporary input file is reached by gl_read_stream_line().
2346 * Read a line from a non-interactive stream?
2348 if(gl
->file_fp
|| !gl
->is_term
) {
2349 c
= gl_read_stream_char(gl
);
2350 if(c
!= EOF
) { /* Success? */
2351 if(c
=='\n') c
= defchar
;
2353 } else if(gl
->file_fp
) { /* End of temporary input file? */
2354 gl_revert_input(gl
);
2355 gl_record_status(gl
, GLR_NEWLINE
, 0);
2356 } else { /* An error? */
2362 * Read from the terminal? Note that the above if() block may have
2363 * changed gl->file_fp, so it is necessary to retest it here, rather
2364 * than using an else statement.
2366 if(!gl
->file_fp
&& gl
->is_term
) {
2367 c
= gl_get_query_char(gl
, prompt
, defchar
);
2375 * If an error occurred, but gl->rtn_status is still set to
2376 * GLR_NEWLINE, change the status to GLR_ERROR. Otherwise
2377 * leave it at whatever specific value was assigned by the function
2378 * that aborted input. This means that only functions that trap
2379 * non-generic errors have to remember to update gl->rtn_status
2382 if(waserr
&& gl
->rtn_status
== GLR_NEWLINE
)
2383 gl_record_status(gl
, GLR_ERROR
, errno
);
2385 * Restore terminal settings.
2387 if(gl
->io_mode
!= GL_SERVER_MODE
)
2390 * Restore the signal handlers.
2392 gl_restore_signal_handlers(gl
);
2394 * If this function gets aborted early, the errno value associated
2395 * with the event that caused this to happen is recorded in
2396 * gl->rtn_errno. Since errno may have been overwritten by cleanup
2397 * functions after this, restore its value to the value that it had
2398 * when the error condition occured, so that the caller can examine it
2399 * to find out what happened.
2401 errno
= gl
->rtn_errno
;
2403 * Error conditions are signalled to the caller, by setting the returned
2406 if(gl
->rtn_status
!= GLR_NEWLINE
)
2409 * In this mode, every character that is read is a completed
2410 * transaction, just like reading a completed input line, so prepare
2411 * for the next input line or character.
2413 _gl_abandon_line(gl
);
2415 * Return the acquired character.
2420 /*.......................................................................
2421 * Record of the signal handlers of the calling program, so that they
2422 * can be restored later.
2425 * gl GetLine * The resource object of this library.
2427 * return int 0 - OK.
2430 static int gl_override_signal_handlers(GetLine
*gl
)
2432 GlSignalNode
*sig
; /* A node in the list of signals to be caught */
2434 * Set up our signal handler.
2437 act
.sa_handler
= gl_signal_handler
;
2438 memcpy(&act
.sa_mask
, &gl
->all_signal_set
, sizeof(sigset_t
));
2441 * Get the subset of the signals that we are supposed to trap that
2442 * should actually be trapped.
2444 sigemptyset(&gl
->use_signal_set
);
2445 for(sig
=gl
->sigs
; sig
; sig
=sig
->next
) {
2447 * Trap this signal? If it is blocked by the calling program and we
2448 * haven't been told to unblock it, don't arrange to trap this signal.
2450 if(sig
->flags
& GLS_UNBLOCK_SIG
||
2451 !sigismember(&gl
->old_signal_set
, sig
->signo
)) {
2452 if(sigaddset(&gl
->use_signal_set
, sig
->signo
) == -1) {
2453 _err_record_msg(gl
->err
, "sigaddset error", END_ERR_MSG
);
2459 * Override the actions of the signals that we are trapping.
2461 for(sig
=gl
->sigs
; sig
; sig
=sig
->next
) {
2462 if(sigismember(&gl
->use_signal_set
, sig
->signo
)) {
2463 sigdelset(&act
.sa_mask
, sig
->signo
);
2464 if(sigaction(sig
->signo
, &act
, &sig
->original
)) {
2465 _err_record_msg(gl
->err
, "sigaction error", END_ERR_MSG
);
2468 sigaddset(&act
.sa_mask
, sig
->signo
);
2472 * Record the fact that the application's signal handlers have now
2475 gl
->signals_overriden
= 1;
2477 * Just in case a SIGWINCH signal was sent to the process while our
2478 * SIGWINCH signal handler wasn't in place, check to see if the terminal
2479 * size needs updating.
2481 if(_gl_update_size(gl
))
2486 /*.......................................................................
2487 * Restore the signal handlers of the calling program.
2490 * gl GetLine * The resource object of this library.
2492 * return int 0 - OK.
2495 static int gl_restore_signal_handlers(GetLine
*gl
)
2497 GlSignalNode
*sig
; /* A node in the list of signals to be caught */
2499 * Restore application signal handlers that were overriden
2500 * by gl_override_signal_handlers().
2502 for(sig
=gl
->sigs
; sig
; sig
=sig
->next
) {
2503 if(sigismember(&gl
->use_signal_set
, sig
->signo
) &&
2504 sigaction(sig
->signo
, &sig
->original
, NULL
)) {
2505 _err_record_msg(gl
->err
, "sigaction error", END_ERR_MSG
);
2510 * Record the fact that the application's signal handlers have now
2513 gl
->signals_overriden
= 0;
2517 /*.......................................................................
2518 * This signal handler simply records the fact that a given signal was
2519 * caught in the file-scope gl_pending_signal variable.
2521 static void gl_signal_handler(int signo
)
2523 gl_pending_signal
= signo
;
2524 siglongjmp(gl_setjmp_buffer
, 1);
2527 /*.......................................................................
2528 * Switch the terminal into raw mode after storing the previous terminal
2529 * settings in gl->attributes.
2532 * gl GetLine * The resource object of this program.
2534 * return int 0 - OK.
2537 static int gl_raw_terminal_mode(GetLine
*gl
)
2539 Termios newattr
; /* The new terminal attributes */
2541 * If the terminal is already in raw mode, do nothing.
2546 * Record the current terminal attributes.
2548 if(tcgetattr(gl
->input_fd
, &gl
->oldattr
)) {
2549 _err_record_msg(gl
->err
, "tcgetattr error", END_ERR_MSG
);
2553 * This function shouldn't do anything but record the current terminal
2554 * attritubes if editing has been disabled.
2556 if(gl
->editor
== GL_NO_EDITOR
)
2559 * Modify the existing attributes.
2561 newattr
= gl
->oldattr
;
2563 * Turn off local echo, canonical input mode and extended input processing.
2565 newattr
.c_lflag
&= ~(ECHO
| ICANON
| IEXTEN
);
2567 * Don't translate carriage return to newline, turn off input parity
2568 * checking, don't strip off 8th bit, turn off output flow control.
2570 newattr
.c_iflag
&= ~(ICRNL
| INPCK
| ISTRIP
);
2572 * Clear size bits, turn off parity checking, and allow 8-bit characters.
2574 newattr
.c_cflag
&= ~(CSIZE
| PARENB
);
2575 newattr
.c_cflag
|= CS8
;
2577 * Turn off output processing.
2579 newattr
.c_oflag
&= ~(OPOST
);
2581 * Request one byte at a time, without waiting.
2583 newattr
.c_cc
[VMIN
] = gl
->io_mode
==GL_SERVER_MODE
? 0:1;
2584 newattr
.c_cc
[VTIME
] = 0;
2586 * Install the new terminal modes.
2588 while(tcsetattr(gl
->input_fd
, TCSADRAIN
, &newattr
)) {
2589 if(errno
!= EINTR
) {
2590 _err_record_msg(gl
->err
, "tcsetattr error", END_ERR_MSG
);
2595 * Record the new terminal mode.
2601 /*.......................................................................
2602 * Restore the terminal attributes recorded in gl->oldattr.
2605 * gl GetLine * The resource object of this library.
2607 * return int 0 - OK.
2610 static int gl_restore_terminal_attributes(GetLine
*gl
)
2614 * If not in raw mode, do nothing.
2619 * Before changing the terminal attributes, make sure that all output
2620 * has been passed to the terminal.
2622 if(gl_flush_output(gl
))
2625 * Reset the terminal attributes to the values that they had on
2626 * entry to gl_get_line().
2628 while(tcsetattr(gl
->input_fd
, TCSADRAIN
, &gl
->oldattr
)) {
2629 if(errno
!= EINTR
) {
2630 _err_record_msg(gl
->err
, "tcsetattr error", END_ERR_MSG
);
2636 * Record the new terminal mode.
2642 /*.......................................................................
2643 * Switch the terminal file descriptor to use non-blocking I/O.
2646 * gl GetLine * The resource object of gl_get_line().
2647 * fd int The file descriptor to make non-blocking.
2649 static int gl_nonblocking_io(GetLine
*gl
, int fd
)
2651 int fcntl_flags
; /* The new file-descriptor control flags */
2653 * Is non-blocking I/O supported on this system? Note that even
2654 * without non-blocking I/O, the terminal will probably still act as
2655 * though it was non-blocking, because we also set the terminal
2656 * attributes to return immediately if no input is available and we
2657 * use select() to wait to be able to write. If select() also isn't
2658 * available, then input will probably remain fine, but output could
2659 * block, depending on the behaviour of the terminal driver.
2661 #if defined(NON_BLOCKING_FLAG)
2663 * Query the current file-control flags, and add the
2664 * non-blocking I/O flag.
2666 fcntl_flags
= fcntl(fd
, F_GETFL
) | NON_BLOCKING_FLAG
;
2668 * Install the new control flags.
2670 if(fcntl(fd
, F_SETFL
, fcntl_flags
) == -1) {
2671 _err_record_msg(gl
->err
, "fcntl error", END_ERR_MSG
);
2678 /*.......................................................................
2679 * Switch to blocking terminal I/O.
2682 * gl GetLine * The resource object of gl_get_line().
2683 * fd int The file descriptor to make blocking.
2685 static int gl_blocking_io(GetLine
*gl
, int fd
)
2687 int fcntl_flags
; /* The new file-descriptor control flags */
2689 * Is non-blocking I/O implemented on this system?
2691 #if defined(NON_BLOCKING_FLAG)
2693 * Query the current file control flags and remove the non-blocking
2696 fcntl_flags
= fcntl(fd
, F_GETFL
) & ~NON_BLOCKING_FLAG
;
2698 * Install the modified control flags.
2700 if(fcntl(fd
, F_SETFL
, fcntl_flags
) == -1) {
2701 _err_record_msg(gl
->err
, "fcntl error", END_ERR_MSG
);
2708 /*.......................................................................
2709 * Read a new input line from the user.
2712 * gl GetLine * The resource object of this library.
2713 * prompt char * The prompt to prefix the line with, or NULL to
2714 * use the same prompt that was used by the previous
2716 * start_line char * The initial contents of the input line, or NULL
2717 * if it should start out empty.
2718 * start_pos int If start_line isn't NULL, this specifies the
2719 * index of the character over which the cursor
2720 * should initially be positioned within the line.
2721 * If you just want it to follow the last character
2722 * of the line, send -1.
2724 * return int 0 - OK.
2727 static int gl_get_input_line(GetLine
*gl
, const char *prompt
,
2728 const char *start_line
, int start_pos
)
2730 char c
; /* The character being read */
2732 * Flush any pending output to the terminal.
2734 if(_glq_char_count(gl
->cq
) > 0 && gl_flush_output(gl
))
2737 * Are we starting a new line?
2741 * Delete any incompletely enterred line.
2743 if(gl_erase_line(gl
))
2746 * Display the new line to be edited.
2748 if(gl_present_line(gl
, prompt
, start_line
, start_pos
))
2752 * Read one character at a time.
2754 while(gl_read_terminal(gl
, 1, &c
) == 0) {
2756 * Increment the count of the number of key sequences entered.
2760 * Interpret the character either as the start of a new key-sequence,
2761 * as a continuation of a repeat count, or as a printable character
2762 * to be added to the line.
2764 if(gl_interpret_char(gl
, c
))
2767 * If we just ran an action function which temporarily asked for
2768 * input to be taken from a file, abort this call.
2773 * Has the line been completed?
2776 return gl_line_ended(gl
, c
);
2779 * To get here, gl_read_terminal() must have returned non-zero. See
2780 * whether a signal was caught that requested that the current line
2784 return gl_line_ended(gl
, '\n');
2786 * If I/O blocked while attempting to get the latest character
2787 * of the key sequence, rewind the key buffer to allow interpretation of
2788 * the current key sequence to be restarted on the next call to this
2791 if(gl
->rtn_status
== GLR_BLOCKED
&& gl
->pending_io
== GLP_READ
)
2796 /*.......................................................................
2797 * This is the private function of gl_query_char() that handles
2798 * prompting the user, reading a character from the terminal, and
2799 * displaying what the user entered.
2802 * gl GetLine * The resource object of this library.
2803 * prompt char * The prompt to prefix the line with.
2804 * defchar char The character to substitute if the
2805 * user simply hits return, or '\n' if you don't
2806 * need to substitute anything.
2808 * return int The character that was read, or EOF if something
2809 * prevented a character from being read.
2811 static int gl_get_query_char(GetLine
*gl
, const char *prompt
, int defchar
)
2813 char c
; /* The character being read */
2814 int retval
; /* The return value of this function */
2816 * Flush any pending output to the terminal.
2818 if(_glq_char_count(gl
->cq
) > 0 && gl_flush_output(gl
))
2821 * Delete any incompletely entered line.
2823 if(gl_erase_line(gl
))
2826 * Reset the line input parameters and display the prompt, if any.
2828 if(gl_present_line(gl
, prompt
, NULL
, 0))
2831 * Read one character.
2833 if(gl_read_terminal(gl
, 1, &c
) == 0) {
2835 * In this mode, count each character as being a new key-sequence.
2839 * Delete the character that was read, from the key-press buffer.
2841 gl_discard_chars(gl
, gl
->nread
);
2843 * Convert carriage returns to newlines.
2848 * If the user just hit return, subsitute the default character.
2853 * Display the entered character to the right of the prompt.
2856 if(gl_end_of_line(gl
, 1, NULL
)==0)
2857 gl_print_char(gl
, c
, ' ');
2860 * Record the return character, and mark the call as successful.
2863 gl_record_status(gl
, GLR_NEWLINE
, 0);
2865 * Was a signal caught whose disposition is to cause the current input
2866 * line to be returned? If so return a newline character.
2868 } else if(gl
->endline
) {
2870 gl_record_status(gl
, GLR_NEWLINE
, 0);
2877 if(gl_start_newline(gl
, 1))
2880 * Attempt to flush any pending output.
2882 (void) gl_flush_output(gl
);
2884 * Return either the character that was read, or EOF if an error occurred.
2889 /*.......................................................................
2890 * Add a character to the line buffer at the current cursor position,
2891 * inserting or overwriting according the current mode.
2894 * gl GetLine * The resource object of this library.
2895 * c char The character to be added.
2897 * return int 0 - OK.
2898 * 1 - Insufficient room.
2900 static int gl_add_char_to_line(GetLine
*gl
, char c
)
2903 * Keep a record of the current cursor position.
2905 int buff_curpos
= gl
->buff_curpos
;
2906 int term_curpos
= gl
->term_curpos
;
2908 * Work out the displayed width of the new character.
2910 int width
= gl_displayed_char_width(gl
, c
, term_curpos
);
2912 * If we are in insert mode, or at the end of the line,
2913 * check that we can accomodate a new character in the buffer.
2914 * If not, simply return, leaving it up to the calling program
2915 * to check for the absence of a newline character.
2917 if((gl
->insert
|| buff_curpos
>= gl
->ntotal
) && gl
->ntotal
>= gl
->linelen
)
2920 * Are we adding characters to the line (ie. inserting or appending)?
2922 if(gl
->insert
|| buff_curpos
>= gl
->ntotal
) {
2924 * If inserting, make room for the new character.
2926 if(buff_curpos
< gl
->ntotal
)
2927 gl_make_gap_in_buffer(gl
, buff_curpos
, 1);
2929 * Copy the character into the buffer.
2931 gl_buffer_char(gl
, c
, buff_curpos
);
2934 * Redraw the line from the cursor position to the end of the line,
2935 * and move the cursor to just after the added character.
2937 if(gl_print_string(gl
, gl
->line
+ buff_curpos
, '\0') ||
2938 gl_set_term_curpos(gl
, term_curpos
+ width
))
2941 * Are we overwriting an existing character?
2945 * Get the width of the character being overwritten.
2947 int old_width
= gl_displayed_char_width(gl
, gl
->line
[buff_curpos
],
2950 * Overwrite the character in the buffer.
2952 gl_buffer_char(gl
, c
, buff_curpos
);
2954 * If we are replacing with a narrower character, we need to
2955 * redraw the terminal string to the end of the line, then
2956 * overwrite the trailing old_width - width characters
2959 if(old_width
> width
) {
2960 if(gl_print_string(gl
, gl
->line
+ buff_curpos
, '\0'))
2963 * Clear to the end of the terminal.
2965 if(gl_truncate_display(gl
))
2968 * Move the cursor to the end of the new character.
2970 if(gl_set_term_curpos(gl
, term_curpos
+ width
))
2974 * If we are replacing with a wider character, then we will be
2975 * inserting new characters, and thus extending the line.
2977 } else if(width
> old_width
) {
2979 * Redraw the line from the cursor position to the end of the line,
2980 * and move the cursor to just after the added character.
2982 if(gl_print_string(gl
, gl
->line
+ buff_curpos
, '\0') ||
2983 gl_set_term_curpos(gl
, term_curpos
+ width
))
2987 * The original and replacement characters have the same width,
2988 * so simply overwrite.
2992 * Copy the character into the buffer.
2994 gl_buffer_char(gl
, c
, buff_curpos
);
2997 * Overwrite the original character.
2999 if(gl_print_char(gl
, c
, gl
->line
[gl
->buff_curpos
]))
3006 /*.......................................................................
3007 * Insert/append a string to the line buffer and terminal at the current
3011 * gl GetLine * The resource object of this library.
3012 * s char * The string to be added.
3014 * return int 0 - OK.
3015 * 1 - Insufficient room.
3017 static int gl_add_string_to_line(GetLine
*gl
, const char *s
)
3019 int buff_slen
; /* The length of the string being added to line[] */
3020 int term_slen
; /* The length of the string being written to the terminal */
3021 int buff_curpos
; /* The original value of gl->buff_curpos */
3022 int term_curpos
; /* The original value of gl->term_curpos */
3024 * Keep a record of the current cursor position.
3026 buff_curpos
= gl
->buff_curpos
;
3027 term_curpos
= gl
->term_curpos
;
3029 * How long is the string to be added?
3031 buff_slen
= strlen(s
);
3032 term_slen
= gl_displayed_string_width(gl
, s
, buff_slen
, term_curpos
);
3034 * Check that we can accomodate the string in the buffer.
3035 * If not, simply return, leaving it up to the calling program
3036 * to check for the absence of a newline character.
3038 if(gl
->ntotal
+ buff_slen
> gl
->linelen
)
3041 * Move the characters that follow the cursor in the buffer by
3042 * buff_slen characters to the right.
3044 if(gl
->ntotal
> gl
->buff_curpos
)
3045 gl_make_gap_in_buffer(gl
, gl
->buff_curpos
, buff_slen
);
3047 * Copy the string into the buffer.
3049 gl_buffer_string(gl
, s
, buff_slen
, gl
->buff_curpos
);
3050 gl
->buff_curpos
+= buff_slen
;
3052 * Write the modified part of the line to the terminal, then move
3053 * the terminal cursor to the end of the displayed input string.
3055 if(gl_print_string(gl
, gl
->line
+ buff_curpos
, '\0') ||
3056 gl_set_term_curpos(gl
, term_curpos
+ term_slen
))
3061 /*.......................................................................
3062 * Read a single character from the terminal.
3065 * gl GetLine * The resource object of this library.
3066 * keep int If true, the returned character will be kept in
3067 * the input buffer, for potential replays. It should
3068 * subsequently be removed from the buffer when the
3069 * key sequence that it belongs to has been fully
3070 * processed, by calling gl_discard_chars().
3072 * c char * The character that is read, is assigned to *c.
3074 * return int 0 - OK.
3075 * 1 - Either an I/O error occurred, or a signal was
3076 * caught who's disposition is to abort gl_get_line()
3077 * or to have gl_get_line() return the current line
3078 * as though the user had pressed return. In the
3079 * latter case gl->endline will be non-zero.
3081 static int gl_read_terminal(GetLine
*gl
, int keep
, char *c
)
3084 * Before waiting for a new character to be input, flush unwritten
3085 * characters to the terminal.
3087 if(gl_flush_output(gl
))
3090 * Record the fact that we are about to read from the terminal.
3092 gl
->pending_io
= GLP_READ
;
3094 * If there is already an unread character in the buffer,
3097 if(gl
->nread
< gl
->nbuf
) {
3098 *c
= gl
->keybuf
[gl
->nread
];
3100 * Retain the character in the key buffer, but mark it as having been read?
3105 * Completely remove the character from the key buffer?
3108 memmove(gl
->keybuf
+ gl
->nread
, gl
->keybuf
+ gl
->nread
+ 1,
3109 gl
->nbuf
- gl
->nread
- 1);
3114 * Make sure that there is space in the key buffer for one more character.
3115 * This should always be true if gl_interpret_char() is called for each
3116 * new character added, since it will clear the buffer once it has recognized
3117 * or rejected a key sequence.
3119 if(gl
->nbuf
+ 1 > GL_KEY_MAX
) {
3120 gl_print_info(gl
, "gl_read_terminal: Buffer overflow avoided.",
3126 * Read one character from the terminal.
3128 switch(gl_read_input(gl
, c
)) {
3131 case GL_READ_BLOCKED
:
3132 gl_record_status(gl
, GLR_BLOCKED
, BLOCKED_ERRNO
);
3140 * Append the character to the key buffer?
3143 gl
->keybuf
[gl
->nbuf
] = *c
;
3144 gl
->nread
= ++gl
->nbuf
;
3149 /*.......................................................................
3150 * Read one or more keypresses from the terminal of an input stream.
3153 * gl GetLine * The resource object of this module.
3154 * c char * The character that was read is assigned to *c.
3156 * return GlReadStatus The completion status of the read operation.
3158 static GlReadStatus
gl_read_input(GetLine
*gl
, char *c
)
3161 * We may have to repeat the read if window change signals are received.
3165 * Which file descriptor should we read from? Mark this volatile, so
3166 * that siglongjmp() can't clobber it.
3168 volatile int fd
= gl
->file_fp
? fileno(gl
->file_fp
) : gl
->input_fd
;
3170 * If the endline flag becomes set, don't wait for another character.
3173 return GL_READ_ERROR
;
3175 * Since the code in this function can block, trap signals.
3177 if(sigsetjmp(gl_setjmp_buffer
, 1)==0) {
3179 * Handle the different I/O modes.
3181 switch(gl
->io_mode
) {
3183 * In normal I/O mode, we call the event handler before attempting
3184 * to read, since read() blocks.
3186 case GL_NORMAL_MODE
:
3187 if(gl_event_handler(gl
, fd
))
3188 return GL_READ_ERROR
;
3189 return gl_read_unmasked(gl
, fd
, c
); /* Read one character */
3192 * In non-blocking server I/O mode, we attempt to read a character,
3193 * and only if this fails, call the event handler to wait for a any
3194 * user-configured timeout and any other user-configured events. In
3195 * addition, we turn off the fcntl() non-blocking flag when reading
3196 * from the terminal, to work around a bug in Solaris. We can do this
3197 * without causing the read() to block, because when in non-blocking
3198 * server-I/O mode, gl_raw_io() sets the VMIN terminal attribute to 0,
3199 * which tells the terminal driver to return immediately if no
3200 * characters are available to be read.
3202 case GL_SERVER_MODE
:
3204 GlReadStatus status
; /* The return status */
3205 if(isatty(fd
)) /* If we reading from a terminal, */
3206 gl_blocking_io(gl
, fd
); /* switch to blocking I/O */
3207 status
= gl_read_unmasked(gl
, fd
, c
); /* Try reading */
3208 if(status
== GL_READ_BLOCKED
) { /* Nothing readable yet */
3209 if(gl_event_handler(gl
, fd
)) /* Wait for input */
3210 status
= GL_READ_ERROR
;
3212 status
= gl_read_unmasked(gl
, fd
, c
); /* Try reading again */
3214 gl_nonblocking_io(gl
, fd
); /* Restore non-blocking I/O */
3221 * To get here, one of the signals that we are trapping must have
3222 * been received. Note that by using sigsetjmp() instead of setjmp()
3223 * the signal mask that was blocking these signals will have been
3224 * reinstated, so we can be sure that no more of these signals will
3225 * be received until we explicitly unblock them again.
3227 * First, if non-blocking I/O was temporarily disabled, reinstate it.
3229 if(gl
->io_mode
== GL_SERVER_MODE
)
3230 gl_nonblocking_io(gl
, fd
);
3232 * Now respond to the signal that was caught.
3234 if(gl_check_caught_signal(gl
))
3235 return GL_READ_ERROR
;
3239 /*.......................................................................
3240 * This is a private function of gl_read_input(), which unblocks signals
3241 * temporarily while it reads a single character from the specified file
3245 * gl GetLine * The resource object of this module.
3246 * fd int The file descriptor to read from.
3247 * c char * The character that was read is assigned to *c.
3249 * return GlReadStatus The completion status of the read.
3251 static int gl_read_unmasked(GetLine
*gl
, int fd
, char *c
)
3253 int nread
; /* The return value of read() */
3255 * Unblock the signals that we are trapping, while waiting for I/O.
3257 gl_catch_signals(gl
);
3259 * Attempt to read one character from the terminal, restarting the read
3260 * if any signals that we aren't trapping, are received.
3264 nread
= read(fd
, c
, 1);
3265 } while(nread
< 0 && errno
==EINTR
);
3267 * Block all of the signals that we are trapping.
3269 gl_mask_signals(gl
, NULL
);
3271 * Check the completion status of the read.
3277 return (isatty(fd
) || errno
!= 0) ? GL_READ_BLOCKED
: GL_READ_EOF
;
3279 return GL_READ_ERROR
;
3283 /*.......................................................................
3284 * Remove a specified number of characters from the start of the
3285 * key-press lookahead buffer, gl->keybuf[], and arrange for the next
3286 * read to start from the character at the start of the shifted buffer.
3289 * gl GetLine * The resource object of this module.
3290 * nused int The number of characters to discard from the start
3293 static void gl_discard_chars(GetLine
*gl
, int nused
)
3295 int nkeep
= gl
->nbuf
- nused
;
3297 memmove(gl
->keybuf
, gl
->keybuf
+ nused
, nkeep
);
3301 gl
->nbuf
= gl
->nread
= 0;
3305 /*.......................................................................
3306 * This function is called to handle signals caught between calls to
3307 * sigsetjmp() and siglongjmp().
3310 * gl GetLine * The resource object of this library.
3312 * return int 0 - Signal handled internally.
3313 * 1 - Signal requires gl_get_line() to abort.
3315 static int gl_check_caught_signal(GetLine
*gl
)
3317 GlSignalNode
*sig
; /* The signal disposition */
3318 SigAction keep_action
; /* The signal disposition of tecla signal handlers */
3319 unsigned flags
; /* The signal processing flags to use */
3320 int signo
; /* The signal to be handled */
3322 * Was no signal caught?
3324 if(gl_pending_signal
== -1)
3327 * Get the signal to be handled.
3329 signo
= gl_pending_signal
;
3331 * Mark the signal as handled. Note that at this point, all of
3332 * the signals that we are trapping are blocked from delivery.
3334 gl_pending_signal
= -1;
3336 * Record the signal that was caught, so that the user can query it later.
3338 gl
->last_signal
= signo
;
3340 * In non-blocking server mode, the application is responsible for
3341 * responding to terminal signals, and we don't want gl_get_line()s
3342 * normal signal handling to clash with this, so whenever a signal
3343 * is caught, we arrange for gl_get_line() to abort and requeue the
3344 * signal while signals are still blocked. If the application
3345 * had the signal unblocked when gl_get_line() was called, the signal
3346 * will be delivered again as soon as gl_get_line() restores the
3347 * process signal mask, just before returning to the application.
3348 * Note that the caller of this function should set gl->pending_io
3349 * to the appropriate choice of GLP_READ and GLP_WRITE, before returning.
3351 if(gl
->io_mode
==GL_SERVER_MODE
) {
3352 gl_record_status(gl
, GLR_SIGNAL
, EINTR
);
3357 * Lookup the requested disposition of this signal.
3359 for(sig
=gl
->sigs
; sig
&& sig
->signo
!= signo
; sig
=sig
->next
)
3364 * Get the signal response flags for this signal.
3368 * Did we receive a terminal size signal?
3371 if(signo
== SIGWINCH
&& _gl_update_size(gl
))
3375 * Start a fresh line?
3377 if(flags
& GLS_RESTORE_LINE
) {
3378 if(gl_start_newline(gl
, 0))
3382 * Restore terminal settings to how they were before gl_get_line() was
3385 if(flags
& GLS_RESTORE_TTY
)
3386 gl_restore_terminal_attributes(gl
);
3388 * Restore signal handlers to how they were before gl_get_line() was
3389 * called? If this hasn't been requested, only reinstate the signal
3390 * handler of the signal that we are handling.
3392 if(flags
& GLS_RESTORE_SIG
) {
3393 gl_restore_signal_handlers(gl
);
3394 gl_unmask_signals(gl
, &gl
->old_signal_set
);
3396 (void) sigaction(sig
->signo
, &sig
->original
, &keep_action
);
3397 (void) sigprocmask(SIG_UNBLOCK
, &sig
->proc_mask
, NULL
);
3400 * Forward the signal to the application's signal handler.
3402 if(!(flags
& GLS_DONT_FORWARD
))
3405 * Reinstate our signal handlers.
3407 if(flags
& GLS_RESTORE_SIG
) {
3408 gl_mask_signals(gl
, NULL
);
3409 gl_override_signal_handlers(gl
);
3411 (void) sigaction(sig
->signo
, &keep_action
, NULL
);
3412 (void) sigprocmask(SIG_BLOCK
, &sig
->proc_mask
, NULL
);
3415 * Do we need to reinstate our terminal settings?
3417 if(flags
& GLS_RESTORE_TTY
)
3418 gl_raw_terminal_mode(gl
);
3422 if(flags
& GLS_REDRAW_LINE
)
3423 gl_queue_redisplay(gl
);
3427 switch(sig
->after
) {
3429 gl_newline(gl
, 1, NULL
);
3430 return gl_flush_output(gl
);
3433 gl_record_status(gl
, GLR_SIGNAL
, sig
->errno_value
);
3437 return gl_flush_output(gl
);
3443 /*.......................................................................
3444 * Get pertinent terminal control strings and the initial terminal size.
3447 * gl GetLine * The resource object of this library.
3448 * term char * The type of the terminal.
3450 * return int 0 - OK.
3453 static int gl_control_strings(GetLine
*gl
, const char *term
)
3455 int bad_term
= 0; /* True if term is unusable */
3457 * Discard any existing control strings from a previous terminal.
3465 gl
->clear_eol
= NULL
;
3466 gl
->clear_eod
= NULL
;
3471 gl
->sound_bell
= NULL
;
3473 gl
->underline
= NULL
;
3474 gl
->standout
= NULL
;
3478 gl
->text_attr_off
= NULL
;
3486 * If possible lookup the information in a terminal information
3492 if(!term
|| setupterm((char *)term
, gl
->input_fd
, &errret
) == ERR
) {
3495 _clr_StringGroup(gl
->capmem
);
3496 gl
->left
= gl_tigetstr(gl
, "cub1");
3497 gl
->right
= gl_tigetstr(gl
, "cuf1");
3498 gl
->up
= gl_tigetstr(gl
, "cuu1");
3499 gl
->down
= gl_tigetstr(gl
, "cud1");
3500 gl
->home
= gl_tigetstr(gl
, "home");
3501 gl
->clear_eol
= gl_tigetstr(gl
, "el");
3502 gl
->clear_eod
= gl_tigetstr(gl
, "ed");
3503 gl
->u_arrow
= gl_tigetstr(gl
, "kcuu1");
3504 gl
->d_arrow
= gl_tigetstr(gl
, "kcud1");
3505 gl
->l_arrow
= gl_tigetstr(gl
, "kcub1");
3506 gl
->r_arrow
= gl_tigetstr(gl
, "kcuf1");
3507 gl
->left_n
= gl_tigetstr(gl
, "cub");
3508 gl
->right_n
= gl_tigetstr(gl
, "cuf");
3509 gl
->sound_bell
= gl_tigetstr(gl
, "bel");
3510 gl
->bold
= gl_tigetstr(gl
, "bold");
3511 gl
->underline
= gl_tigetstr(gl
, "smul");
3512 gl
->standout
= gl_tigetstr(gl
, "smso");
3513 gl
->dim
= gl_tigetstr(gl
, "dim");
3514 gl
->reverse
= gl_tigetstr(gl
, "rev");
3515 gl
->blink
= gl_tigetstr(gl
, "blink");
3516 gl
->text_attr_off
= gl_tigetstr(gl
, "sgr0");
3519 #elif defined(USE_TERMCAP)
3520 if(!term
|| tgetent(gl
->tgetent_buf
, (char *)term
) < 0) {
3523 char *tgetstr_buf_ptr
= gl
->tgetstr_buf
;
3524 _clr_StringGroup(gl
->capmem
);
3525 gl
->left
= gl_tgetstr(gl
, "le", &tgetstr_buf_ptr
);
3526 gl
->right
= gl_tgetstr(gl
, "nd", &tgetstr_buf_ptr
);
3527 gl
->up
= gl_tgetstr(gl
, "up", &tgetstr_buf_ptr
);
3528 gl
->down
= gl_tgetstr(gl
, "do", &tgetstr_buf_ptr
);
3529 gl
->home
= gl_tgetstr(gl
, "ho", &tgetstr_buf_ptr
);
3530 gl
->clear_eol
= gl_tgetstr(gl
, "ce", &tgetstr_buf_ptr
);
3531 gl
->clear_eod
= gl_tgetstr(gl
, "cd", &tgetstr_buf_ptr
);
3532 gl
->u_arrow
= gl_tgetstr(gl
, "ku", &tgetstr_buf_ptr
);
3533 gl
->d_arrow
= gl_tgetstr(gl
, "kd", &tgetstr_buf_ptr
);
3534 gl
->l_arrow
= gl_tgetstr(gl
, "kl", &tgetstr_buf_ptr
);
3535 gl
->r_arrow
= gl_tgetstr(gl
, "kr", &tgetstr_buf_ptr
);
3536 gl
->sound_bell
= gl_tgetstr(gl
, "bl", &tgetstr_buf_ptr
);
3537 gl
->bold
= gl_tgetstr(gl
, "md", &tgetstr_buf_ptr
);
3538 gl
->underline
= gl_tgetstr(gl
, "us", &tgetstr_buf_ptr
);
3539 gl
->standout
= gl_tgetstr(gl
, "so", &tgetstr_buf_ptr
);
3540 gl
->dim
= gl_tgetstr(gl
, "mh", &tgetstr_buf_ptr
);
3541 gl
->reverse
= gl_tgetstr(gl
, "mr", &tgetstr_buf_ptr
);
3542 gl
->blink
= gl_tgetstr(gl
, "mb", &tgetstr_buf_ptr
);
3543 gl
->text_attr_off
= gl_tgetstr(gl
, "me", &tgetstr_buf_ptr
);
3547 * Report term being unusable.
3550 gl_print_info(gl
, "Bad terminal type: \"", term
? term
: "(null)",
3551 "\". Will assume vt100.", GL_END_INFO
);
3554 * Fill in missing information with ANSI VT100 strings.
3557 gl
->left
= "\b"; /* ^H */
3559 gl
->right
= GL_ESC_STR
"[C";
3561 gl
->up
= GL_ESC_STR
"[A";
3565 gl
->home
= GL_ESC_STR
"[H";
3569 gl
->clear_eol
= GL_ESC_STR
"[K";
3571 gl
->clear_eod
= GL_ESC_STR
"[J";
3573 gl
->u_arrow
= GL_ESC_STR
"[A";
3575 gl
->d_arrow
= GL_ESC_STR
"[B";
3577 gl
->l_arrow
= GL_ESC_STR
"[D";
3579 gl
->r_arrow
= GL_ESC_STR
"[C";
3581 gl
->sound_bell
= "\a";
3583 gl
->bold
= GL_ESC_STR
"[1m";
3585 gl
->underline
= GL_ESC_STR
"[4m";
3587 gl
->standout
= GL_ESC_STR
"[1;7m";
3589 gl
->dim
= ""; /* Not available */
3591 gl
->reverse
= GL_ESC_STR
"[7m";
3593 gl
->blink
= GL_ESC_STR
"[5m";
3594 if(!gl
->text_attr_off
)
3595 gl
->text_attr_off
= GL_ESC_STR
"[m";
3597 * Find out the current terminal size.
3599 (void) _gl_terminal_size(gl
, GL_DEF_NCOLUMN
, GL_DEF_NLINE
, NULL
);
3604 /*.......................................................................
3605 * This is a private function of gl_control_strings() used to look up
3606 * a termninal capability string from the terminfo database and make
3607 * a private copy of it.
3610 * gl GetLine * The resource object of gl_get_line().
3611 * name const char * The name of the terminfo string to look up.
3613 * return const char * The local copy of the capability, or NULL
3616 static const char *gl_tigetstr(GetLine
*gl
, const char *name
)
3618 const char *value
= tigetstr((char *)name
);
3619 if(!value
|| value
== (char *) -1)
3621 return _sg_store_string(gl
->capmem
, value
, 0);
3623 #elif defined(USE_TERMCAP)
3624 /*.......................................................................
3625 * This is a private function of gl_control_strings() used to look up
3626 * a termninal capability string from the termcap database and make
3627 * a private copy of it. Note that some emulations of tgetstr(), such
3628 * as that used by Solaris, ignores the buffer pointer that is past to
3629 * it, so we can't assume that a private copy has been made that won't
3630 * be trashed by another call to gl_control_strings() by another
3631 * GetLine object. So we make what may be a redundant private copy
3632 * of the string in gl->capmem.
3635 * gl GetLine * The resource object of gl_get_line().
3636 * name const char * The name of the terminfo string to look up.
3638 * bufptr char ** On input *bufptr points to the location in
3639 * gl->tgetstr_buf at which to record the
3640 * capability string. On output *bufptr is
3641 * incremented over the stored string.
3643 * return const char * The local copy of the capability, or NULL
3646 static const char *gl_tgetstr(GetLine
*gl
, const char *name
, char **bufptr
)
3648 const char *value
= tgetstr((char *)name
, bufptr
);
3649 if(!value
|| value
== (char *) -1)
3651 return _sg_store_string(gl
->capmem
, value
, 0);
3655 /*.......................................................................
3656 * This is an action function that implements a user interrupt (eg. ^C).
3658 static KT_KEY_FN(gl_user_interrupt
)
3664 /*.......................................................................
3665 * This is an action function that implements the abort signal.
3667 static KT_KEY_FN(gl_abort
)
3673 /*.......................................................................
3674 * This is an action function that sends a suspend signal (eg. ^Z) to the
3675 * the parent process.
3677 static KT_KEY_FN(gl_suspend
)
3683 /*.......................................................................
3684 * This is an action function that halts output to the terminal.
3686 static KT_KEY_FN(gl_stop_output
)
3688 tcflow(gl
->output_fd
, TCOOFF
);
3692 /*.......................................................................
3693 * This is an action function that resumes halted terminal output.
3695 static KT_KEY_FN(gl_start_output
)
3697 tcflow(gl
->output_fd
, TCOON
);
3701 /*.......................................................................
3702 * This is an action function that allows the next character to be accepted
3703 * without any interpretation as a special character.
3705 static KT_KEY_FN(gl_literal_next
)
3707 char c
; /* The character to be added to the line */
3710 * Get the character to be inserted literally.
3712 if(gl_read_terminal(gl
, 1, &c
))
3715 * Add the character to the line 'count' times.
3717 for(i
=0; i
<count
; i
++)
3718 gl_add_char_to_line(gl
, c
);
3722 /*.......................................................................
3723 * Return the width of a tab character at a given position when
3724 * displayed at a given position on the terminal. This is needed
3725 * because the width of tab characters depends on where they are,
3726 * relative to the preceding tab stops.
3729 * gl GetLine * The resource object of this library.
3730 * term_curpos int The destination terminal location of the character.
3732 * return int The number of terminal charaters needed.
3734 static int gl_displayed_tab_width(GetLine
*gl
, int term_curpos
)
3736 return TAB_WIDTH
- ((term_curpos
% gl
->ncolumn
) % TAB_WIDTH
);
3739 /*.......................................................................
3740 * Return the number of characters needed to display a given character
3741 * on the screen. Tab characters require eight spaces, and control
3742 * characters are represented by a caret followed by the modified
3746 * gl GetLine * The resource object of this library.
3747 * c char The character to be displayed.
3748 * term_curpos int The destination terminal location of the character.
3749 * This is needed because the width of tab characters
3750 * depends on where they are, relative to the
3751 * preceding tab stops.
3753 * return int The number of terminal charaters needed.
3755 static int gl_displayed_char_width(GetLine
*gl
, char c
, int term_curpos
)
3758 return gl_displayed_tab_width(gl
, term_curpos
);
3761 if(!isprint((int)(unsigned char) c
))
3762 return gl_octal_width((int)(unsigned char)c
) + 1;
3767 /*.......................................................................
3768 * Work out the length of given string of characters on the terminal.
3771 * gl GetLine * The resource object of this library.
3772 * string char * The string to be measured.
3773 * nc int The number of characters to be measured, or -1
3774 * to measure the whole string.
3775 * term_curpos int The destination terminal location of the character.
3776 * This is needed because the width of tab characters
3777 * depends on where they are, relative to the
3778 * preceding tab stops.
3780 * return int The number of displayed characters.
3782 static int gl_displayed_string_width(GetLine
*gl
, const char *string
, int nc
,
3785 int slen
= 0; /* The displayed number of characters */
3788 * How many characters are to be measured?
3791 nc
= strlen(string
);
3793 * Add up the length of the displayed string.
3796 slen
+= gl_displayed_char_width(gl
, string
[i
], term_curpos
+ slen
);
3800 /*.......................................................................
3801 * Write a string verbatim to the current terminal or output stream.
3803 * Note that when async-signal safety is required, the 'buffered'
3804 * argument must be 0, and n must not be -1.
3807 * gl GetLine * The resource object of the gl_get_line().
3808 * buffered int If true, used buffered I/O when writing to
3809 * the terminal. Otherwise use async-signal-safe
3811 * string const char * The string to be written (this need not be
3812 * '\0' terminated unless n<0).
3813 * n int The number of characters to write from the
3814 * prefix of string[], or -1 to request that
3815 * gl_print_raw_string() use strlen() to figure
3818 * return int 0 - OK.
3821 static int gl_print_raw_string(GetLine
*gl
, int buffered
,
3822 const char *string
, int n
)
3824 GlWriteFn
*write_fn
= buffered
? gl_write_fn
: gl
->flush_fn
;
3826 * Only display output when echoing is turned on.
3829 int ndone
= 0; /* The number of characters written so far */
3831 * When using un-buffered I/O, flush pending output first.
3834 if(gl_flush_output(gl
))
3838 * If no length has been provided, measure the length of the string.
3845 if(write_fn(gl
, string
+ ndone
, n
-ndone
) != n
)
3851 /*.......................................................................
3852 * Output a terminal control sequence. When using terminfo,
3853 * this must be a sequence returned by tgetstr() or tigetstr()
3857 * gl GetLine * The resource object of this library.
3858 * nline int The number of lines affected by the operation,
3859 * or 1 if not relevant.
3860 * string char * The control sequence to be sent.
3862 * return int 0 - OK.
3865 static int gl_print_control_sequence(GetLine
*gl
, int nline
, const char *string
)
3867 int waserr
= 0; /* True if an error occurs */
3869 * Only write characters to the terminal when echoing is enabled.
3872 #if defined(USE_TERMINFO) || defined(USE_TERMCAP)
3875 tputs((char *)string
, nline
, gl_tputs_putchar
);
3876 waserr
= errno
!= 0;
3878 waserr
= gl_print_raw_string(gl
, 1, string
, -1);
3884 #if defined(USE_TERMINFO) || defined(USE_TERMCAP)
3885 /*.......................................................................
3886 * The following callback function is called by tputs() to output a raw
3887 * control character to the terminal.
3889 static TputsRetType
gl_tputs_putchar(TputsArgType c
)
3892 #if TPUTS_RETURNS_VALUE
3893 return gl_print_raw_string(tputs_gl
, 1, &ch
, 1);
3895 (void) gl_print_raw_string(tputs_gl
, 1, &ch
, 1);
3900 /*.......................................................................
3901 * Move the terminal cursor n characters to the left or right.
3904 * gl GetLine * The resource object of this program.
3905 * n int number of positions to the right (> 0) or left (< 0).
3907 * return int 0 - OK.
3910 static int gl_terminal_move_cursor(GetLine
*gl
, int n
)
3912 int cur_row
, cur_col
; /* The current terminal row and column index of */
3913 /* the cursor wrt the start of the input line. */
3914 int new_row
, new_col
; /* The target terminal row and column index of */
3915 /* the cursor wrt the start of the input line. */
3917 * Do nothing if the input line isn't currently displayed. In this
3918 * case, the cursor will be moved to the right place when the line
3919 * is next redisplayed.
3924 * How far can we move left?
3926 if(gl
->term_curpos
+ n
< 0)
3927 n
= gl
->term_curpos
;
3929 * Break down the current and target cursor locations into rows and columns.
3931 cur_row
= gl
->term_curpos
/ gl
->ncolumn
;
3932 cur_col
= gl
->term_curpos
% gl
->ncolumn
;
3933 new_row
= (gl
->term_curpos
+ n
) / gl
->ncolumn
;
3934 new_col
= (gl
->term_curpos
+ n
) % gl
->ncolumn
;
3936 * Move down to the next line.
3938 for(; cur_row
< new_row
; cur_row
++) {
3939 if(gl_print_control_sequence(gl
, 1, gl
->down
))
3943 * Move up to the previous line.
3945 for(; cur_row
> new_row
; cur_row
--) {
3946 if(gl_print_control_sequence(gl
, 1, gl
->up
))
3950 * Move to the right within the target line?
3952 if(cur_col
< new_col
) {
3955 * Use a parameterized control sequence if it generates less control
3956 * characters (guess based on ANSI terminal termcap entry).
3958 if(gl
->right_n
!= NULL
&& new_col
- cur_col
> 1) {
3959 if(gl_print_control_sequence(gl
, 1, tparm((char *)gl
->right_n
,
3960 (long)(new_col
- cur_col
), 0l, 0l, 0l, 0l, 0l, 0l, 0l, 0l)))
3965 for(; cur_col
< new_col
; cur_col
++) {
3966 if(gl_print_control_sequence(gl
, 1, gl
->right
))
3971 * Move to the left within the target line?
3973 } else if(cur_col
> new_col
) {
3976 * Use a parameterized control sequence if it generates less control
3977 * characters (guess based on ANSI terminal termcap entry).
3979 if(gl
->left_n
!= NULL
&& cur_col
- new_col
> 3) {
3980 if(gl_print_control_sequence(gl
, 1, tparm((char *)gl
->left_n
,
3981 (long)(cur_col
- new_col
), 0l, 0l, 0l, 0l, 0l, 0l, 0l, 0l)))
3986 for(; cur_col
> new_col
; cur_col
--) {
3987 if(gl_print_control_sequence(gl
, 1, gl
->left
))
3993 * Update the recorded position of the terminal cursor.
3995 gl
->term_curpos
+= n
;
3999 /*.......................................................................
4000 * Write a character to the terminal after expanding tabs and control
4001 * characters to their multi-character representations.
4004 * gl GetLine * The resource object of this program.
4005 * c char The character to be output.
4006 * pad char Many terminals have the irritating feature that
4007 * when one writes a character in the last column of
4008 * of the terminal, the cursor isn't wrapped to the
4009 * start of the next line until one more character
4010 * is written. Some terminals don't do this, so
4011 * after such a write, we don't know where the
4012 * terminal is unless we output an extra character.
4013 * This argument specifies the character to write.
4014 * If at the end of the input line send '\0' or a
4015 * space, and a space will be written. Otherwise,
4016 * pass the next character in the input line
4017 * following the one being written.
4019 * return int 0 - OK.
4021 static int gl_print_char(GetLine
*gl
, char c
, char pad
)
4023 char string
[TAB_WIDTH
+ 4]; /* A work area for composing compound strings */
4024 int nchar
; /* The number of terminal characters */
4027 * Check for special characters.
4031 * How many spaces do we need to represent a tab at the current terminal
4034 nchar
= gl_displayed_tab_width(gl
, gl
->term_curpos
);
4036 * Compose the tab string.
4038 for(i
=0; i
<nchar
; i
++)
4040 } else if(IS_CTRL_CHAR(c
)) {
4042 string
[1] = CTRL_TO_CHAR(c
);
4044 } else if(!isprint((int)(unsigned char) c
)) {
4045 snprintf(string
, sizeof(string
), "\\%o", (int)(unsigned char)c
);
4046 nchar
= strlen(string
);
4052 * Terminate the string.
4054 string
[nchar
] = '\0';
4056 * Write the string to the terminal.
4058 if(gl_print_raw_string(gl
, 1, string
, -1))
4061 * Except for one exception to be described in a moment, the cursor should
4062 * now have been positioned after the character that was just output.
4064 gl
->term_curpos
+= nchar
;
4066 * Keep a record of the number of characters in the terminal version
4067 * of the input line.
4069 if(gl
->term_curpos
> gl
->term_len
)
4070 gl
->term_len
= gl
->term_curpos
;
4072 * If the new character ended exactly at the end of a line,
4073 * most terminals won't move the cursor onto the next line until we
4074 * have written a character on the next line, so append an extra
4075 * space then move the cursor back.
4077 if(gl
->term_curpos
% gl
->ncolumn
== 0) {
4078 int term_curpos
= gl
->term_curpos
;
4079 if(gl_print_char(gl
, pad
? pad
: ' ', ' ') ||
4080 gl_set_term_curpos(gl
, term_curpos
))
4086 /*.......................................................................
4087 * Write a string to the terminal after expanding tabs and control
4088 * characters to their multi-character representations.
4091 * gl GetLine * The resource object of this program.
4092 * string char * The string to be output.
4093 * pad char Many terminals have the irritating feature that
4094 * when one writes a character in the last column of
4095 * of the terminal, the cursor isn't wrapped to the
4096 * start of the next line until one more character
4097 * is written. Some terminals don't do this, so
4098 * after such a write, we don't know where the
4099 * terminal is unless we output an extra character.
4100 * This argument specifies the character to write.
4101 * If at the end of the input line send '\0' or a
4102 * space, and a space will be written. Otherwise,
4103 * pass the next character in the input line
4104 * following the one being written.
4106 * return int 0 - OK.
4108 static int gl_print_string(GetLine
*gl
, const char *string
, char pad
)
4110 const char *cptr
; /* A pointer into string[] */
4111 for(cptr
=string
; *cptr
; cptr
++) {
4112 char nextc
= cptr
[1];
4113 if(gl_print_char(gl
, *cptr
, nextc
? nextc
: pad
))
4119 /*.......................................................................
4120 * Move the terminal cursor position.
4123 * gl GetLine * The resource object of this library.
4124 * term_curpos int The destination terminal cursor position.
4126 * return int 0 - OK.
4129 static int gl_set_term_curpos(GetLine
*gl
, int term_curpos
)
4131 return gl_terminal_move_cursor(gl
, term_curpos
- gl
->term_curpos
);
4134 /*.......................................................................
4135 * This is an action function that moves the buffer cursor one character
4136 * left, and updates the terminal cursor to match.
4138 static KT_KEY_FN(gl_cursor_left
)
4140 return gl_place_cursor(gl
, gl
->buff_curpos
- count
);
4143 /*.......................................................................
4144 * This is an action function that moves the buffer cursor one character
4145 * right, and updates the terminal cursor to match.
4147 static KT_KEY_FN(gl_cursor_right
)
4149 return gl_place_cursor(gl
, gl
->buff_curpos
+ count
);
4152 /*.......................................................................
4153 * This is an action function that toggles between overwrite and insert
4156 static KT_KEY_FN(gl_insert_mode
)
4158 gl
->insert
= !gl
->insert
;
4162 /*.......................................................................
4163 * This is an action function which moves the cursor to the beginning of
4166 static KT_KEY_FN(gl_beginning_of_line
)
4168 return gl_place_cursor(gl
, 0);
4171 /*.......................................................................
4172 * This is an action function which moves the cursor to the end of
4175 static KT_KEY_FN(gl_end_of_line
)
4177 return gl_place_cursor(gl
, gl
->ntotal
);
4180 /*.......................................................................
4181 * This is an action function which deletes the entire contents of the
4184 static KT_KEY_FN(gl_delete_line
)
4187 * If in vi command mode, preserve the current line for potential
4190 gl_save_for_undo(gl
);
4192 * Copy the contents of the line to the cut buffer.
4194 strlcpy(gl
->cutbuf
, gl
->line
, gl
->linelen
);
4198 gl_truncate_buffer(gl
, 0);
4200 * Move the terminal cursor to just after the prompt.
4202 if(gl_place_cursor(gl
, 0))
4205 * Clear from the end of the prompt to the end of the terminal.
4207 if(gl_truncate_display(gl
))
4212 /*.......................................................................
4213 * This is an action function which deletes all characters between the
4214 * current cursor position and the end of the line.
4216 static KT_KEY_FN(gl_kill_line
)
4219 * If in vi command mode, preserve the current line for potential
4222 gl_save_for_undo(gl
);
4224 * Copy the part of the line that is about to be deleted to the cut buffer.
4226 strlcpy(gl
->cutbuf
, gl
->line
+ gl
->buff_curpos
, gl
->linelen
);
4228 * Terminate the buffered line at the current cursor position.
4230 gl_truncate_buffer(gl
, gl
->buff_curpos
);
4232 * Clear the part of the line that follows the cursor.
4234 if(gl_truncate_display(gl
))
4237 * Explicitly reset the cursor position to allow vi command mode
4238 * constraints on its position to be set.
4240 return gl_place_cursor(gl
, gl
->buff_curpos
);
4243 /*.......................................................................
4244 * This is an action function which deletes all characters between the
4245 * start of the line and the current cursor position.
4247 static KT_KEY_FN(gl_backward_kill_line
)
4250 * How many characters are to be deleted from before the cursor?
4252 int nc
= gl
->buff_curpos
- gl
->insert_curpos
;
4256 * Move the cursor to the start of the line, or in vi input mode,
4257 * the start of the sub-line at which insertion started, and delete
4258 * up to the old cursor position.
4260 return gl_place_cursor(gl
, gl
->insert_curpos
) ||
4261 gl_delete_chars(gl
, nc
, gl
->editor
== GL_EMACS_MODE
|| gl
->vi
.command
);
4264 /*.......................................................................
4265 * This is an action function which moves the cursor forward by a word.
4267 static KT_KEY_FN(gl_forward_word
)
4269 return gl_place_cursor(gl
, gl_nth_word_end_forward(gl
, count
) +
4270 (gl
->editor
==GL_EMACS_MODE
));
4273 /*.......................................................................
4274 * This is an action function which moves the cursor forward to the start
4277 static KT_KEY_FN(gl_forward_to_word
)
4279 return gl_place_cursor(gl
, gl_nth_word_start_forward(gl
, count
));
4282 /*.......................................................................
4283 * This is an action function which moves the cursor backward by a word.
4285 static KT_KEY_FN(gl_backward_word
)
4287 return gl_place_cursor(gl
, gl_nth_word_start_backward(gl
, count
));
4290 /*.......................................................................
4291 * Delete one or more characters, starting with the one under the cursor.
4294 * gl GetLine * The resource object of this library.
4295 * nc int The number of characters to delete.
4296 * cut int If true, copy the characters to the cut buffer.
4298 * return int 0 - OK.
4301 static int gl_delete_chars(GetLine
*gl
, int nc
, int cut
)
4304 * If in vi command mode, preserve the current line for potential
4307 gl_save_for_undo(gl
);
4309 * If there are fewer than nc characters following the cursor, limit
4310 * nc to the number available.
4312 if(gl
->buff_curpos
+ nc
> gl
->ntotal
)
4313 nc
= gl
->ntotal
- gl
->buff_curpos
;
4315 * Copy the about to be deleted region to the cut buffer.
4318 memcpy(gl
->cutbuf
, gl
->line
+ gl
->buff_curpos
, nc
);
4319 gl
->cutbuf
[nc
] = '\0';
4322 * Nothing to delete?
4327 * In vi overwrite mode, restore any previously overwritten characters
4328 * from the undo buffer.
4330 if(gl
->editor
== GL_VI_MODE
&& !gl
->vi
.command
&& !gl
->insert
) {
4332 * How many of the characters being deleted can be restored from the
4335 int nrestore
= gl
->buff_curpos
+ nc
<= gl
->vi
.undo
.ntotal
?
4336 nc
: gl
->vi
.undo
.ntotal
- gl
->buff_curpos
;
4338 * Restore any available characters.
4341 gl_buffer_string(gl
, gl
->vi
.undo
.line
+ gl
->buff_curpos
, nrestore
,
4345 * If their were insufficient characters in the undo buffer, then this
4346 * implies that we are deleting from the end of the line, so we need
4347 * to terminate the line either where the undo buffer ran out, or if
4348 * we are deleting from beyond the end of the undo buffer, at the current
4351 if(nc
!= nrestore
) {
4352 gl_truncate_buffer(gl
, (gl
->vi
.undo
.ntotal
> gl
->buff_curpos
) ?
4353 gl
->vi
.undo
.ntotal
: gl
->buff_curpos
);
4357 * Copy the remaining part of the line back over the deleted characters.
4359 gl_remove_from_buffer(gl
, gl
->buff_curpos
, nc
);
4362 * Redraw the remaining characters following the cursor.
4364 if(gl_print_string(gl
, gl
->line
+ gl
->buff_curpos
, '\0'))
4367 * Clear to the end of the terminal.
4369 if(gl_truncate_display(gl
))
4372 * Place the cursor at the start of where the deletion was performed.
4374 return gl_place_cursor(gl
, gl
->buff_curpos
);
4377 /*.......................................................................
4378 * This is an action function which deletes character(s) under the
4379 * cursor without moving the cursor.
4381 static KT_KEY_FN(gl_forward_delete_char
)
4384 * Delete 'count' characters.
4386 return gl_delete_chars(gl
, count
, gl
->vi
.command
);
4389 /*.......................................................................
4390 * This is an action function which deletes character(s) under the
4391 * cursor and moves the cursor back one character.
4393 static KT_KEY_FN(gl_backward_delete_char
)
4396 * Restrict the deletion count to the number of characters that
4397 * precede the insertion point.
4399 if(count
> gl
->buff_curpos
- gl
->insert_curpos
)
4400 count
= gl
->buff_curpos
- gl
->insert_curpos
;
4402 * If in vi command mode, preserve the current line for potential
4405 gl_save_for_undo(gl
);
4406 return gl_cursor_left(gl
, count
, NULL
) ||
4407 gl_delete_chars(gl
, count
, gl
->vi
.command
);
4410 /*.......................................................................
4411 * Starting from the cursor position delete to the specified column.
4413 static KT_KEY_FN(gl_delete_to_column
)
4415 if (--count
>= gl
->buff_curpos
)
4416 return gl_forward_delete_char(gl
, count
- gl
->buff_curpos
, NULL
);
4418 return gl_backward_delete_char(gl
, gl
->buff_curpos
- count
, NULL
);
4421 /*.......................................................................
4422 * Starting from the cursor position delete characters to a matching
4425 static KT_KEY_FN(gl_delete_to_parenthesis
)
4427 int curpos
= gl_index_of_matching_paren(gl
);
4429 gl_save_for_undo(gl
);
4430 if(curpos
>= gl
->buff_curpos
)
4431 return gl_forward_delete_char(gl
, curpos
- gl
->buff_curpos
+ 1, NULL
);
4433 return gl_backward_delete_char(gl
, ++gl
->buff_curpos
- curpos
+ 1, NULL
);
4438 /*.......................................................................
4439 * This is an action function which deletes from the cursor to the end
4440 * of the word that the cursor is either in or precedes.
4442 static KT_KEY_FN(gl_forward_delete_word
)
4445 * If in vi command mode, preserve the current line for potential
4448 gl_save_for_undo(gl
);
4450 * In emacs mode delete to the end of the word. In vi mode delete to the
4451 * start of the net word.
4453 if(gl
->editor
== GL_EMACS_MODE
) {
4454 return gl_delete_chars(gl
,
4455 gl_nth_word_end_forward(gl
,count
) - gl
->buff_curpos
+ 1, 1);
4457 return gl_delete_chars(gl
,
4458 gl_nth_word_start_forward(gl
,count
) - gl
->buff_curpos
,
4463 /*.......................................................................
4464 * This is an action function which deletes the word that precedes the
4467 static KT_KEY_FN(gl_backward_delete_word
)
4470 * Keep a record of the current cursor position.
4472 int buff_curpos
= gl
->buff_curpos
;
4474 * If in vi command mode, preserve the current line for potential
4477 gl_save_for_undo(gl
);
4479 * Move back 'count' words.
4481 if(gl_backward_word(gl
, count
, NULL
))
4484 * Delete from the new cursor position to the original one.
4486 return gl_delete_chars(gl
, buff_curpos
- gl
->buff_curpos
,
4487 gl
->editor
== GL_EMACS_MODE
|| gl
->vi
.command
);
4490 /*.......................................................................
4491 * Searching in a given direction, delete to the count'th
4492 * instance of a specified or queried character, in the input line.
4495 * gl GetLine * The getline resource object.
4496 * count int The number of times to search.
4497 * c char The character to be searched for, or '\0' if
4498 * the character should be read from the user.
4499 * forward int True if searching forward.
4500 * onto int True if the search should end on top of the
4501 * character, false if the search should stop
4502 * one character before the character in the
4503 * specified search direction.
4504 * change int If true, this function is being called upon
4505 * to do a vi change command, in which case the
4506 * user will be left in insert mode after the
4509 * return int 0 - OK.
4512 static int gl_delete_find(GetLine
*gl
, int count
, char c
, int forward
,
4513 int onto
, int change
)
4516 * Search for the character, and abort the deletion if not found.
4518 int pos
= gl_find_char(gl
, count
, forward
, onto
, c
);
4522 * If in vi command mode, preserve the current line for potential
4525 gl_save_for_undo(gl
);
4527 * Allow the cursor to be at the end of the line if this is a change
4533 * Delete the appropriate span of characters.
4536 if(gl_delete_chars(gl
, pos
- gl
->buff_curpos
+ 1, 1))
4539 int buff_curpos
= gl
->buff_curpos
;
4540 if(gl_place_cursor(gl
, pos
) ||
4541 gl_delete_chars(gl
, buff_curpos
- gl
->buff_curpos
, 1))
4545 * If this is a change operation, switch the insert mode.
4547 if(change
&& gl_vi_insert(gl
, 0, NULL
))
4552 /*.......................................................................
4553 * This is an action function which deletes forward from the cursor up to and
4554 * including a specified character.
4556 static KT_KEY_FN(gl_forward_delete_find
)
4558 return gl_delete_find(gl
, count
, '\0', 1, 1, 0);
4561 /*.......................................................................
4562 * This is an action function which deletes backward from the cursor back to
4563 * and including a specified character.
4565 static KT_KEY_FN(gl_backward_delete_find
)
4567 return gl_delete_find(gl
, count
, '\0', 0, 1, 0);
4570 /*.......................................................................
4571 * This is an action function which deletes forward from the cursor up to but
4572 * not including a specified character.
4574 static KT_KEY_FN(gl_forward_delete_to
)
4576 return gl_delete_find(gl
, count
, '\0', 1, 0, 0);
4579 /*.......................................................................
4580 * This is an action function which deletes backward from the cursor back to
4581 * but not including a specified character.
4583 static KT_KEY_FN(gl_backward_delete_to
)
4585 return gl_delete_find(gl
, count
, '\0', 0, 0, 0);
4588 /*.......................................................................
4589 * This is an action function which deletes to a character specified by a
4592 static KT_KEY_FN(gl_delete_refind
)
4594 return gl_delete_find(gl
, count
, gl
->vi
.find_char
, gl
->vi
.find_forward
,
4595 gl
->vi
.find_onto
, 0);
4598 /*.......................................................................
4599 * This is an action function which deletes to a character specified by a
4600 * previous search, but in the opposite direction.
4602 static KT_KEY_FN(gl_delete_invert_refind
)
4604 return gl_delete_find(gl
, count
, gl
->vi
.find_char
,
4605 !gl
->vi
.find_forward
, gl
->vi
.find_onto
, 0);
4608 /*.......................................................................
4609 * This is an action function which converts the characters in the word
4610 * following the cursor to upper case.
4612 static KT_KEY_FN(gl_upcase_word
)
4615 * Locate the count'th word ending after the cursor.
4617 int last
= gl_nth_word_end_forward(gl
, count
);
4619 * If in vi command mode, preserve the current line for potential
4622 gl_save_for_undo(gl
);
4624 * Upcase characters from the current cursor position to 'last'.
4626 while(gl
->buff_curpos
<= last
) {
4627 char *cptr
= gl
->line
+ gl
->buff_curpos
;
4629 * Convert the character to upper case?
4631 if(islower((int)(unsigned char) *cptr
))
4632 gl_buffer_char(gl
, toupper((int) *cptr
), gl
->buff_curpos
);
4635 * Write the possibly modified character back. Note that for non-modified
4636 * characters we want to do this as well, so as to advance the cursor.
4638 if(gl_print_char(gl
, *cptr
, cptr
[1]))
4641 return gl_place_cursor(gl
, gl
->buff_curpos
); /* bounds check */
4644 /*.......................................................................
4645 * This is an action function which converts the characters in the word
4646 * following the cursor to lower case.
4648 static KT_KEY_FN(gl_downcase_word
)
4651 * Locate the count'th word ending after the cursor.
4653 int last
= gl_nth_word_end_forward(gl
, count
);
4655 * If in vi command mode, preserve the current line for potential
4658 gl_save_for_undo(gl
);
4660 * Upcase characters from the current cursor position to 'last'.
4662 while(gl
->buff_curpos
<= last
) {
4663 char *cptr
= gl
->line
+ gl
->buff_curpos
;
4665 * Convert the character to upper case?
4667 if(isupper((int)(unsigned char) *cptr
))
4668 gl_buffer_char(gl
, tolower((int) *cptr
), gl
->buff_curpos
);
4671 * Write the possibly modified character back. Note that for non-modified
4672 * characters we want to do this as well, so as to advance the cursor.
4674 if(gl_print_char(gl
, *cptr
, cptr
[1]))
4677 return gl_place_cursor(gl
, gl
->buff_curpos
); /* bounds check */
4680 /*.......................................................................
4681 * This is an action function which converts the first character of the
4682 * following word to upper case, in order to capitalize the word, and
4683 * leaves the cursor at the end of the word.
4685 static KT_KEY_FN(gl_capitalize_word
)
4687 char *cptr
; /* &gl->line[gl->buff_curpos] */
4688 int first
; /* True for the first letter of the word */
4691 * Keep a record of the current insert mode and the cursor position.
4693 int insert
= gl
->insert
;
4695 * If in vi command mode, preserve the current line for potential
4698 gl_save_for_undo(gl
);
4700 * We want to overwrite the modified word.
4704 * Capitalize 'count' words.
4706 for(i
=0; i
<count
&& gl
->buff_curpos
< gl
->ntotal
; i
++) {
4707 int pos
= gl
->buff_curpos
;
4709 * If we are not already within a word, skip to the start of the word.
4711 for(cptr
= gl
->line
+ pos
; pos
<gl
->ntotal
&& !gl_is_word_char((int) *cptr
);
4715 * Move the cursor to the new position.
4717 if(gl_place_cursor(gl
, pos
))
4720 * While searching for the end of the word, change lower case letters
4723 for(first
=1; gl
->buff_curpos
<gl
->ntotal
&& gl_is_word_char((int) *cptr
);
4724 gl
->buff_curpos
++, cptr
++) {
4726 * Convert the character to upper case?
4729 if(islower((int)(unsigned char) *cptr
))
4730 gl_buffer_char(gl
, toupper((int) *cptr
), cptr
- gl
->line
);
4732 if(isupper((int)(unsigned char) *cptr
))
4733 gl_buffer_char(gl
, tolower((int) *cptr
), cptr
- gl
->line
);
4737 * Write the possibly modified character back. Note that for non-modified
4738 * characters we want to do this as well, so as to advance the cursor.
4740 if(gl_print_char(gl
, *cptr
, cptr
[1]))
4745 * Restore the insertion mode.
4747 gl
->insert
= insert
;
4748 return gl_place_cursor(gl
, gl
->buff_curpos
); /* bounds check */
4751 /*.......................................................................
4752 * This is an action function which redraws the current line.
4754 static KT_KEY_FN(gl_redisplay
)
4757 * Keep a record of the current cursor position.
4759 int buff_curpos
= gl
->buff_curpos
;
4761 * Do nothing if there is no line to be redisplayed.
4766 * Erase the current input line.
4768 if(gl_erase_line(gl
))
4771 * Display the current prompt.
4773 if(gl_display_prompt(gl
))
4776 * Render the part of the line that the user has typed in so far.
4778 if(gl_print_string(gl
, gl
->line
, '\0'))
4781 * Restore the cursor position.
4783 if(gl_place_cursor(gl
, buff_curpos
))
4786 * Mark the redisplay operation as having been completed.
4790 * Flush the redisplayed line to the terminal.
4792 return gl_flush_output(gl
);
4795 /*.......................................................................
4796 * This is an action function which clears the display and redraws the
4797 * input line from the home position.
4799 static KT_KEY_FN(gl_clear_screen
)
4802 * Home the cursor and clear from there to the end of the display.
4804 if(gl_print_control_sequence(gl
, gl
->nline
, gl
->home
) ||
4805 gl_print_control_sequence(gl
, gl
->nline
, gl
->clear_eod
))
4808 * The input line is no longer displayed.
4812 * Arrange for the input line to be redisplayed.
4814 gl_queue_redisplay(gl
);
4818 /*.......................................................................
4819 * This is an action function which swaps the character under the cursor
4820 * with the character to the left of the cursor.
4822 static KT_KEY_FN(gl_transpose_chars
)
4824 char from
[3]; /* The original string of 2 characters */
4825 char swap
[3]; /* The swapped string of two characters */
4827 * If we are at the beginning or end of the line, there aren't two
4828 * characters to swap.
4830 if(gl
->buff_curpos
< 1 || gl
->buff_curpos
>= gl
->ntotal
)
4833 * If in vi command mode, preserve the current line for potential
4836 gl_save_for_undo(gl
);
4838 * Get the original and swapped strings of the two characters.
4840 from
[0] = gl
->line
[gl
->buff_curpos
- 1];
4841 from
[1] = gl
->line
[gl
->buff_curpos
];
4843 swap
[0] = gl
->line
[gl
->buff_curpos
];
4844 swap
[1] = gl
->line
[gl
->buff_curpos
- 1];
4847 * Move the cursor to the start of the two characters.
4849 if(gl_place_cursor(gl
, gl
->buff_curpos
-1))
4852 * Swap the two characters in the buffer.
4854 gl_buffer_char(gl
, swap
[0], gl
->buff_curpos
);
4855 gl_buffer_char(gl
, swap
[1], gl
->buff_curpos
+1);
4857 * If the sum of the displayed width of the two characters
4858 * in their current and final positions is the same, swapping can
4859 * be done by just overwriting with the two swapped characters.
4861 if(gl_displayed_string_width(gl
, from
, -1, gl
->term_curpos
) ==
4862 gl_displayed_string_width(gl
, swap
, -1, gl
->term_curpos
)) {
4863 int insert
= gl
->insert
;
4865 if(gl_print_char(gl
, swap
[0], swap
[1]) ||
4866 gl_print_char(gl
, swap
[1], gl
->line
[gl
->buff_curpos
+2]))
4868 gl
->insert
= insert
;
4870 * If the swapped substring has a different displayed size, we need to
4871 * redraw everything after the first of the characters.
4874 if(gl_print_string(gl
, gl
->line
+ gl
->buff_curpos
, '\0') ||
4875 gl_truncate_display(gl
))
4879 * Advance the cursor to the character after the swapped pair.
4881 return gl_place_cursor(gl
, gl
->buff_curpos
+ 2);
4884 /*.......................................................................
4885 * This is an action function which sets a mark at the current cursor
4888 static KT_KEY_FN(gl_set_mark
)
4890 gl
->buff_mark
= gl
->buff_curpos
;
4894 /*.......................................................................
4895 * This is an action function which swaps the mark location for the
4898 static KT_KEY_FN(gl_exchange_point_and_mark
)
4901 * Get the old mark position, and limit to the extent of the input
4904 int old_mark
= gl
->buff_mark
<= gl
->ntotal
? gl
->buff_mark
: gl
->ntotal
;
4906 * Make the current cursor position the new mark.
4908 gl
->buff_mark
= gl
->buff_curpos
;
4910 * Move the cursor to the old mark position.
4912 return gl_place_cursor(gl
, old_mark
);
4915 /*.......................................................................
4916 * This is an action function which deletes the characters between the
4917 * mark and the cursor, recording them in gl->cutbuf for later pasting.
4919 static KT_KEY_FN(gl_kill_region
)
4922 * If in vi command mode, preserve the current line for potential
4925 gl_save_for_undo(gl
);
4927 * Limit the mark to be within the line.
4929 if(gl
->buff_mark
> gl
->ntotal
)
4930 gl
->buff_mark
= gl
->ntotal
;
4932 * If there are no characters between the cursor and the mark, simply clear
4935 if(gl
->buff_mark
== gl
->buff_curpos
) {
4936 gl
->cutbuf
[0] = '\0';
4940 * If the mark is before the cursor, swap the cursor and the mark.
4942 if(gl
->buff_mark
< gl
->buff_curpos
&& gl_exchange_point_and_mark(gl
,1,NULL
))
4945 * Delete the characters.
4947 if(gl_delete_chars(gl
, gl
->buff_mark
- gl
->buff_curpos
, 1))
4950 * Make the mark the same as the cursor position.
4952 gl
->buff_mark
= gl
->buff_curpos
;
4956 /*.......................................................................
4957 * This is an action function which records the characters between the
4958 * mark and the cursor, in gl->cutbuf for later pasting.
4960 static KT_KEY_FN(gl_copy_region_as_kill
)
4962 int ca
, cb
; /* The indexes of the first and last characters in the region */
4963 int mark
; /* The position of the mark */
4965 * Get the position of the mark, limiting it to lie within the line.
4967 mark
= gl
->buff_mark
> gl
->ntotal
? gl
->ntotal
: gl
->buff_mark
;
4969 * If there are no characters between the cursor and the mark, clear
4972 if(mark
== gl
->buff_curpos
) {
4973 gl
->cutbuf
[0] = '\0';
4977 * Get the line indexes of the first and last characters in the region.
4979 if(mark
< gl
->buff_curpos
) {
4981 cb
= gl
->buff_curpos
- 1;
4983 ca
= gl
->buff_curpos
;
4987 * Copy the region to the cut buffer.
4989 memcpy(gl
->cutbuf
, gl
->line
+ ca
, cb
+ 1 - ca
);
4990 gl
->cutbuf
[cb
+ 1 - ca
] = '\0';
4994 /*.......................................................................
4995 * This is an action function which inserts the contents of the cut
4996 * buffer at the current cursor location.
4998 static KT_KEY_FN(gl_yank
)
5002 * Set the mark at the current location.
5004 gl
->buff_mark
= gl
->buff_curpos
;
5006 * Do nothing else if the cut buffer is empty.
5008 if(gl
->cutbuf
[0] == '\0')
5009 return gl_ring_bell(gl
, 1, NULL
);
5011 * If in vi command mode, preserve the current line for potential
5014 gl_save_for_undo(gl
);
5016 * Insert the string count times.
5018 for(i
=0; i
<count
; i
++) {
5019 if(gl_add_string_to_line(gl
, gl
->cutbuf
))
5023 * gl_add_string_to_line() leaves the cursor after the last character that
5024 * was pasted, whereas vi leaves the cursor over the last character pasted.
5026 if(gl
->editor
== GL_VI_MODE
&& gl_cursor_left(gl
, 1, NULL
))
5031 /*.......................................................................
5032 * This is an action function which inserts the contents of the cut
5033 * buffer one character beyond the current cursor location.
5035 static KT_KEY_FN(gl_append_yank
)
5037 int was_command
= gl
->vi
.command
;
5040 * If the cut buffer is empty, ring the terminal bell.
5042 if(gl
->cutbuf
[0] == '\0')
5043 return gl_ring_bell(gl
, 1, NULL
);
5045 * Set the mark at the current location + 1.
5047 gl
->buff_mark
= gl
->buff_curpos
+ 1;
5049 * If in vi command mode, preserve the current line for potential
5052 gl_save_for_undo(gl
);
5054 * Arrange to paste the text in insert mode after the current character.
5056 if(gl_vi_append(gl
, 0, NULL
))
5059 * Insert the string count times.
5061 for(i
=0; i
<count
; i
++) {
5062 if(gl_add_string_to_line(gl
, gl
->cutbuf
))
5066 * Switch back to command mode if necessary.
5069 gl_vi_command_mode(gl
);
5073 /*.......................................................................
5074 * Attempt to ask the terminal for its current size. On systems that
5075 * don't support the TIOCWINSZ ioctl() for querying the terminal size,
5076 * the current values of gl->ncolumn and gl->nrow are returned.
5079 * gl GetLine * The resource object of gl_get_line().
5081 * ncolumn int * The number of columns will be assigned to *ncolumn.
5082 * nline int * The number of lines will be assigned to *nline.
5084 static void gl_query_size(GetLine
*gl
, int *ncolumn
, int *nline
)
5088 * Query the new terminal window size. Ignore invalid responses.
5090 struct winsize size
;
5091 if(ioctl(gl
->output_fd
, TIOCGWINSZ
, &size
) == 0 &&
5092 size
.ws_row
> 0 && size
.ws_col
> 0) {
5093 *ncolumn
= size
.ws_col
;
5094 *nline
= size
.ws_row
;
5099 * Return the existing values.
5101 *ncolumn
= gl
->ncolumn
;
5106 /*.......................................................................
5107 * Query the size of the terminal, and if it has changed, redraw the
5108 * current input line accordingly.
5111 * gl GetLine * The resource object of gl_get_line().
5113 * return int 0 - OK.
5116 static int _gl_update_size(GetLine
*gl
)
5118 int ncolumn
, nline
; /* The new size of the terminal */
5120 * Query the new terminal window size.
5122 gl_query_size(gl
, &ncolumn
, &nline
);
5124 * Update gl and the displayed line to fit the new dimensions.
5126 return gl_handle_tty_resize(gl
, ncolumn
, nline
);
5129 /*.......................................................................
5130 * Redraw the current input line to account for a change in the terminal
5131 * size. Also install the new size in gl.
5134 * gl GetLine * The resource object of gl_get_line().
5135 * ncolumn int The new number of columns.
5136 * nline int The new number of lines.
5138 * return int 0 - OK.
5141 static int gl_handle_tty_resize(GetLine
*gl
, int ncolumn
, int nline
)
5144 * If the input device isn't a terminal, just record the new size.
5148 gl
->ncolumn
= ncolumn
;
5150 * Has the size actually changed?
5152 } else if(ncolumn
!= gl
->ncolumn
|| nline
!= gl
->nline
) {
5154 * If we are currently editing a line, erase it.
5156 if(gl_erase_line(gl
))
5159 * Update the recorded window size.
5162 gl
->ncolumn
= ncolumn
;
5164 * Arrange for the input line to be redrawn before the next character
5165 * is read from the terminal.
5167 gl_queue_redisplay(gl
);
5172 /*.......................................................................
5173 * This is the action function that recalls the previous line in the
5176 static KT_KEY_FN(gl_up_history
)
5179 * In vi mode, switch to command mode, since the user is very
5180 * likely to want to move around newly recalled lines.
5182 gl_vi_command_mode(gl
);
5184 * Forget any previous recall session.
5188 * Record the key sequence number of this search action.
5190 gl
->last_search
= gl
->keyseq_count
;
5192 * We don't want a search prefix for this function.
5194 if(_glh_search_prefix(gl
->glh
, gl
->line
, 0)) {
5195 _err_record_msg(gl
->err
, _glh_last_error(gl
->glh
), END_ERR_MSG
);
5199 * Recall the count'th next older line in the history list. If the first one
5200 * fails we can return since nothing has changed, otherwise we must continue
5201 * and update the line state.
5203 if(_glh_find_backwards(gl
->glh
, gl
->line
, gl
->linelen
+1) == NULL
)
5205 while(--count
&& _glh_find_backwards(gl
->glh
, gl
->line
, gl
->linelen
+1))
5208 * Accomodate the new contents of gl->line[].
5210 gl_update_buffer(gl
);
5212 * Arrange to have the cursor placed at the end of the new line.
5214 gl
->buff_curpos
= gl
->ntotal
;
5216 * Erase and display the new line.
5218 gl_queue_redisplay(gl
);
5222 /*.......................................................................
5223 * This is the action function that recalls the next line in the
5226 static KT_KEY_FN(gl_down_history
)
5229 * In vi mode, switch to command mode, since the user is very
5230 * likely to want to move around newly recalled lines.
5232 gl_vi_command_mode(gl
);
5234 * Record the key sequence number of this search action.
5236 gl
->last_search
= gl
->keyseq_count
;
5238 * If no search is currently in progress continue a previous recall
5239 * session from a previous entered line if possible.
5241 if(_glh_line_id(gl
->glh
, 0) == 0 && gl
->preload_id
) {
5242 _glh_recall_line(gl
->glh
, gl
->preload_id
, gl
->line
, gl
->linelen
+1);
5246 * We don't want a search prefix for this function.
5248 if(_glh_search_prefix(gl
->glh
, gl
->line
, 0)) {
5249 _err_record_msg(gl
->err
, _glh_last_error(gl
->glh
), END_ERR_MSG
);
5253 * Recall the count'th next newer line in the history list. If the first one
5254 * fails we can return since nothing has changed otherwise we must continue
5255 * and update the line state.
5257 if(_glh_find_forwards(gl
->glh
, gl
->line
, gl
->linelen
+1) == NULL
)
5259 while(--count
&& _glh_find_forwards(gl
->glh
, gl
->line
, gl
->linelen
+1))
5263 * Accomodate the new contents of gl->line[].
5265 gl_update_buffer(gl
);
5267 * Arrange to have the cursor placed at the end of the new line.
5269 gl
->buff_curpos
= gl
->ntotal
;
5271 * Erase and display the new line.
5273 gl_queue_redisplay(gl
);
5277 /*.......................................................................
5278 * This is the action function that recalls the previous line in the
5279 * history buffer whos prefix matches the characters that currently
5280 * precede the cursor. By setting count=-1, this can be used internally
5281 * to force searching for the prefix used in the last search.
5283 static KT_KEY_FN(gl_history_search_backward
)
5286 * In vi mode, switch to command mode, since the user is very
5287 * likely to want to move around newly recalled lines.
5289 gl_vi_command_mode(gl
);
5291 * Forget any previous recall session.
5295 * Record the key sequence number of this search action.
5297 gl
->last_search
= gl
->keyseq_count
;
5299 * If a prefix search isn't already in progress, replace the search
5300 * prefix to the string that precedes the cursor. In vi command mode
5301 * include the character that is under the cursor in the string. If
5302 * count<0 keep the previous search prefix regardless, so as to force
5303 * a repeat search even if the last command wasn't a history command.
5305 if(count
>= 0 && !_glh_search_active(gl
->glh
) &&
5306 _glh_search_prefix(gl
->glh
, gl
->line
, gl
->buff_curpos
+
5307 (gl
->editor
==GL_VI_MODE
&& gl
->ntotal
>0))) {
5308 _err_record_msg(gl
->err
, _glh_last_error(gl
->glh
), END_ERR_MSG
);
5312 * Search backwards for a match to the part of the line which precedes the
5315 if(_glh_find_backwards(gl
->glh
, gl
->line
, gl
->linelen
+1) == NULL
)
5318 * Accomodate the new contents of gl->line[].
5320 gl_update_buffer(gl
);
5322 * Arrange to have the cursor placed at the end of the new line.
5324 gl
->buff_curpos
= gl
->ntotal
;
5326 * Erase and display the new line.
5328 gl_queue_redisplay(gl
);
5332 /*.......................................................................
5333 * This is the action function that recalls the previous line in the
5334 * history buffer who's prefix matches that specified in an earlier call
5335 * to gl_history_search_backward() or gl_history_search_forward().
5337 static KT_KEY_FN(gl_history_re_search_backward
)
5339 return gl_history_search_backward(gl
, -1, NULL
);
5342 /*.......................................................................
5343 * This is the action function that recalls the next line in the
5344 * history buffer who's prefix matches that specified in the earlier call
5345 * to gl_history_search_backward) which started the history search.
5346 * By setting count=-1, this can be used internally to force searching
5347 * for the prefix used in the last search.
5349 static KT_KEY_FN(gl_history_search_forward
)
5352 * In vi mode, switch to command mode, since the user is very
5353 * likely to want to move around newly recalled lines.
5355 gl_vi_command_mode(gl
);
5357 * Record the key sequence number of this search action.
5359 gl
->last_search
= gl
->keyseq_count
;
5361 * If a prefix search isn't already in progress, replace the search
5362 * prefix to the string that precedes the cursor. In vi command mode
5363 * include the character that is under the cursor in the string. If
5364 * count<0 keep the previous search prefix regardless, so as to force
5365 * a repeat search even if the last command wasn't a history command.
5367 if(count
>= 0 && !_glh_search_active(gl
->glh
) &&
5368 _glh_search_prefix(gl
->glh
, gl
->line
, gl
->buff_curpos
+
5369 (gl
->editor
==GL_VI_MODE
&& gl
->ntotal
>0))) {
5370 _err_record_msg(gl
->err
, _glh_last_error(gl
->glh
), END_ERR_MSG
);
5374 * Search forwards for the next matching line.
5376 if(_glh_find_forwards(gl
->glh
, gl
->line
, gl
->linelen
+1) == NULL
)
5379 * Accomodate the new contents of gl->line[].
5381 gl_update_buffer(gl
);
5383 * Arrange for the cursor to be placed at the end of the new line.
5385 gl
->buff_curpos
= gl
->ntotal
;
5387 * Erase and display the new line.
5389 gl_queue_redisplay(gl
);
5393 /*.......................................................................
5394 * This is the action function that recalls the next line in the
5395 * history buffer who's prefix matches that specified in an earlier call
5396 * to gl_history_search_backward() or gl_history_search_forward().
5398 static KT_KEY_FN(gl_history_re_search_forward
)
5400 return gl_history_search_forward(gl
, -1, NULL
);
5403 #ifdef HIDE_FILE_SYSTEM
5404 /*.......................................................................
5405 * The following function is used as the default completion handler when
5406 * the filesystem is to be hidden. It simply reports no completions.
5408 static CPL_MATCH_FN(gl_no_completions
)
5414 /*.......................................................................
5415 * This is the tab completion function that completes the filename that
5416 * precedes the cursor position. Its callback data argument must be a
5417 * pointer to a GlCplCallback containing the completion callback function
5418 * and its callback data, or NULL to use the builtin filename completer.
5420 static KT_KEY_FN(gl_complete_word
)
5422 CplMatches
*matches
; /* The possible completions */
5423 int suffix_len
; /* The length of the completion extension */
5424 int cont_len
; /* The length of any continuation suffix */
5425 int nextra
; /* The number of characters being added to the */
5426 /* total length of the line. */
5427 int buff_pos
; /* The buffer index at which the completion is */
5428 /* to be inserted. */
5429 int waserr
= 0; /* True after errors */
5431 * Get the container of the completion callback and its callback data.
5433 GlCplCallback
*cb
= data
? (GlCplCallback
*) data
: &gl
->cplfn
;
5435 * In vi command mode, switch to append mode so that the character under
5436 * the cursor is included in the completion (otherwise people can't
5437 * complete at the end of the line).
5439 if(gl
->vi
.command
&& gl_vi_append(gl
, 0, NULL
))
5442 * Get the cursor position at which the completion is to be inserted.
5444 buff_pos
= gl
->buff_curpos
;
5446 * Perform the completion.
5448 matches
= cpl_complete_word(gl
->cpl
, gl
->line
, gl
->buff_curpos
, cb
->data
,
5451 * No matching completions?
5454 waserr
= gl_print_info(gl
, cpl_last_error(gl
->cpl
), GL_END_INFO
);
5456 * Are there any completions?
5458 } else if(matches
->nmatch
>= 1) {
5460 * If there any ambiguous matches, report them, starting on a new line.
5462 if(matches
->nmatch
> 1 && gl
->echo
) {
5463 if(_gl_normal_io(gl
) ||
5464 _cpl_output_completions(matches
, gl_write_fn
, gl
, gl
->ncolumn
))
5468 * Get the length of the suffix and any continuation suffix to add to it.
5470 suffix_len
= strlen(matches
->suffix
);
5471 cont_len
= strlen(matches
->cont_suffix
);
5473 * If there is an unambiguous match, and the continuation suffix ends in
5474 * a newline, strip that newline and arrange to have getline return
5475 * after this action function returns.
5477 if(matches
->nmatch
==1 && cont_len
> 0 &&
5478 matches
->cont_suffix
[cont_len
- 1] == '\n') {
5480 if(gl_newline(gl
, 1, NULL
))
5484 * Work out the number of characters that are to be added.
5486 nextra
= suffix_len
+ cont_len
;
5488 * Is there anything to be added?
5490 if(!waserr
&& nextra
) {
5492 * Will there be space for the expansion in the line buffer?
5494 if(gl
->ntotal
+ nextra
< gl
->linelen
) {
5496 * Make room to insert the filename extension.
5498 gl_make_gap_in_buffer(gl
, gl
->buff_curpos
, nextra
);
5500 * Insert the filename extension.
5502 gl_buffer_string(gl
, matches
->suffix
, suffix_len
, gl
->buff_curpos
);
5504 * Add the terminating characters.
5506 gl_buffer_string(gl
, matches
->cont_suffix
, cont_len
,
5507 gl
->buff_curpos
+ suffix_len
);
5509 * Place the cursor position at the end of the completion.
5511 gl
->buff_curpos
+= nextra
;
5513 * If we don't have to redisplay the whole line, redisplay the part
5514 * of the line which follows the original cursor position, and place
5515 * the cursor at the end of the completion.
5518 if(gl_truncate_display(gl
) ||
5519 gl_print_string(gl
, gl
->line
+ buff_pos
, '\0') ||
5520 gl_place_cursor(gl
, gl
->buff_curpos
))
5524 (void) gl_print_info(gl
,
5525 "Insufficient room in line for file completion.",
5532 * If any output had to be written to the terminal, then editing will
5533 * have been suspended, make sure that we are back in raw line editing
5534 * mode before returning.
5536 if(_gl_raw_io(gl
, 1))
5541 #ifndef HIDE_FILE_SYSTEM
5542 /*.......................................................................
5543 * This is the function that expands the filename that precedes the
5544 * cursor position. It expands ~user/ expressions, $envvar expressions,
5547 static KT_KEY_FN(gl_expand_filename
)
5549 char *start_path
; /* The pointer to the start of the pathname in */
5551 FileExpansion
*result
; /* The results of the filename expansion */
5552 int pathlen
; /* The length of the pathname being expanded */
5553 int length
; /* The number of characters needed to display the */
5554 /* expanded files. */
5555 int nextra
; /* The number of characters to be added */
5558 * In vi command mode, switch to append mode so that the character under
5559 * the cursor is included in the completion (otherwise people can't
5560 * complete at the end of the line).
5562 if(gl
->vi
.command
&& gl_vi_append(gl
, 0, NULL
))
5565 * Locate the start of the filename that precedes the cursor position.
5567 start_path
= _pu_start_of_path(gl
->line
, gl
->buff_curpos
);
5571 * Get the length of the string that is to be expanded.
5573 pathlen
= gl
->buff_curpos
- (start_path
- gl
->line
);
5575 * Attempt to expand it.
5577 result
= ef_expand_file(gl
->ef
, start_path
, pathlen
);
5579 * If there was an error, report the error on a new line.
5582 return gl_print_info(gl
, ef_last_error(gl
->ef
), GL_END_INFO
);
5584 * If no files matched, report this as well.
5586 if(result
->nfile
== 0 || !result
->exists
)
5587 return gl_print_info(gl
, "No files match.", GL_END_INFO
);
5589 * If in vi command mode, preserve the current line for potential use by
5592 gl_save_for_undo(gl
);
5594 * Work out how much space we will need to display all of the matching
5595 * filenames, taking account of the space that we need to place between
5596 * them, and the number of additional '\' characters needed to escape
5597 * spaces, tabs and backslash characters in the individual filenames.
5600 for(i
=0; i
<result
->nfile
; i
++) {
5601 char *file
= result
->files
[i
];
5605 case ' ': case '\t': case '\\': case '*': case '?': case '[':
5606 length
++; /* Count extra backslash characters */
5608 length
++; /* Count the character itself */
5610 length
++; /* Count the space that follows each filename */
5613 * Work out the number of characters that are to be added.
5615 nextra
= length
- pathlen
;
5617 * Will there be space for the expansion in the line buffer?
5619 if(gl
->ntotal
+ nextra
>= gl
->linelen
) {
5620 return gl_print_info(gl
, "Insufficient room in line for file expansion.",
5624 * Do we need to move the part of the line that followed the unexpanded
5628 gl_make_gap_in_buffer(gl
, gl
->buff_curpos
, nextra
);
5629 } else if(nextra
< 0) {
5630 gl
->buff_curpos
+= nextra
;
5631 gl_remove_from_buffer(gl
, gl
->buff_curpos
, -nextra
);
5634 * Insert the filenames, separated by spaces, and with internal spaces,
5635 * tabs and backslashes escaped with backslashes.
5637 for(i
=0,j
=start_path
- gl
->line
; i
<result
->nfile
; i
++) {
5638 char *file
= result
->files
[i
];
5642 case ' ': case '\t': case '\\': case '*': case '?': case '[':
5643 gl_buffer_char(gl
, '\\', j
++);
5645 gl_buffer_char(gl
, c
, j
++);
5647 gl_buffer_char(gl
, ' ', j
++);
5651 * Redisplay the part of the line which follows the start of
5652 * the original filename.
5654 if(gl_place_cursor(gl
, start_path
- gl
->line
) ||
5655 gl_truncate_display(gl
) ||
5656 gl_print_string(gl
, start_path
, start_path
[length
]))
5659 * Move the cursor to the end of the expansion.
5661 return gl_place_cursor(gl
, (start_path
- gl
->line
) + length
);
5665 #ifndef HIDE_FILE_SYSTEM
5666 /*.......................................................................
5667 * This is the action function that lists glob expansions of the
5668 * filename that precedes the cursor position. It expands ~user/
5669 * expressions, $envvar expressions, and wildcards.
5671 static KT_KEY_FN(gl_list_glob
)
5673 char *start_path
; /* The pointer to the start of the pathname in */
5675 FileExpansion
*result
; /* The results of the filename expansion */
5676 int pathlen
; /* The length of the pathname being expanded */
5678 * Locate the start of the filename that precedes the cursor position.
5680 start_path
= _pu_start_of_path(gl
->line
, gl
->buff_curpos
);
5684 * Get the length of the string that is to be expanded.
5686 pathlen
= gl
->buff_curpos
- (start_path
- gl
->line
);
5688 * Attempt to expand it.
5690 result
= ef_expand_file(gl
->ef
, start_path
, pathlen
);
5692 * If there was an error, report it.
5695 return gl_print_info(gl
, ef_last_error(gl
->ef
), GL_END_INFO
);
5697 * If no files matched, report this as well.
5699 } else if(result
->nfile
== 0 || !result
->exists
) {
5700 return gl_print_info(gl
, "No files match.", GL_END_INFO
);
5702 * List the matching expansions.
5704 } else if(gl
->echo
) {
5705 if(gl_start_newline(gl
, 1) ||
5706 _ef_output_expansions(result
, gl_write_fn
, gl
, gl
->ncolumn
))
5708 gl_queue_redisplay(gl
);
5714 /*.......................................................................
5715 * Return non-zero if a character should be considered a part of a word.
5718 * c int The character to be tested.
5720 * return int True if the character should be considered part of a word.
5722 static int gl_is_word_char(int c
)
5724 return isalnum((int)(unsigned char)c
) || strchr(GL_WORD_CHARS
, c
) != NULL
;
5727 /*.......................................................................
5728 * Override the builtin file-completion callback that is bound to the
5729 * "complete_word" action function.
5732 * gl GetLine * The resource object of the command-line input
5734 * data void * This is passed to match_fn() whenever it is
5735 * called. It could, for example, point to a
5736 * symbol table where match_fn() could look
5737 * for possible completions.
5738 * match_fn CplMatchFn * The function that will identify the prefix
5739 * to be completed from the input line, and
5740 * report matching symbols.
5742 * return int 0 - OK.
5745 int gl_customize_completion(GetLine
*gl
, void *data
, CplMatchFn
*match_fn
)
5747 sigset_t oldset
; /* The signals that were blocked on entry to this function */
5749 * Check the arguments.
5751 if(!gl
|| !match_fn
) {
5753 _err_record_msg(gl
->err
, "NULL argument", END_ERR_MSG
);
5758 * Temporarily block all signals.
5760 gl_mask_signals(gl
, &oldset
);
5762 * Record the new completion function and its callback data.
5764 gl
->cplfn
.fn
= match_fn
;
5765 gl
->cplfn
.data
= data
;
5767 * Restore the process signal mask before returning.
5769 gl_unmask_signals(gl
, &oldset
);
5773 /*.......................................................................
5774 * Change the terminal (or stream) that getline interacts with.
5777 * gl GetLine * The resource object of the command-line input
5779 * input_fp FILE * The stdio stream to read from.
5780 * output_fp FILE * The stdio stream to write to.
5781 * term char * The terminal type. This can be NULL if
5782 * either or both of input_fp and output_fp don't
5783 * refer to a terminal. Otherwise it should refer
5784 * to an entry in the terminal information database.
5786 * return int 0 - OK.
5789 int gl_change_terminal(GetLine
*gl
, FILE *input_fp
, FILE *output_fp
,
5792 sigset_t oldset
; /* The signals that were blocked on entry to this function */
5793 int status
; /* The return status of _gl_change_terminal() */
5795 * Check the arguments.
5802 * Block all signals.
5804 if(gl_mask_signals(gl
, &oldset
))
5807 * Execute the private body of the function while signals are blocked.
5809 status
= _gl_change_terminal(gl
, input_fp
, output_fp
, term
);
5811 * Restore the process signal mask.
5813 gl_unmask_signals(gl
, &oldset
);
5817 /*.......................................................................
5818 * This is the private body of the gl_change_terminal() function. It
5819 * assumes that the caller has checked its arguments and blocked the
5820 * delivery of signals.
5822 static int _gl_change_terminal(GetLine
*gl
, FILE *input_fp
, FILE *output_fp
,
5825 int is_term
= 0; /* True if both input_fd and output_fd are associated */
5826 /* with a terminal. */
5828 * Require that input_fp and output_fp both be valid.
5830 if(!input_fp
|| !output_fp
) {
5831 gl_print_info(gl
, "Can't change terminal. Bad input/output stream(s).",
5836 * Are we displacing an existing terminal (as opposed to setting the
5837 * initial terminal)?
5839 if(gl
->input_fd
>= 0) {
5841 * Make sure to leave the previous terminal in a usable state.
5843 if(_gl_normal_io(gl
))
5846 * Remove the displaced terminal from the list of fds to watch.
5849 FD_CLR(gl
->input_fd
, &gl
->rfds
);
5853 * Record the file descriptors and streams.
5855 gl
->input_fp
= input_fp
;
5856 gl
->input_fd
= fileno(input_fp
);
5857 gl
->output_fp
= output_fp
;
5858 gl
->output_fd
= fileno(output_fp
);
5860 * If needed, expand the record of the maximum file-descriptor that might
5861 * need to be monitored with select().
5864 if(gl
->input_fd
> gl
->max_fd
)
5865 gl
->max_fd
= gl
->input_fd
;
5868 * Disable terminal interaction until we have enough info to interact
5869 * with the terminal.
5873 * For terminal editing, we need both output_fd and input_fd to refer to
5874 * a terminal. While we can't verify that they both point to the same
5875 * terminal, we can verify that they point to terminals.
5877 is_term
= isatty(gl
->input_fd
) && isatty(gl
->output_fd
);
5879 * If we are interacting with a terminal and no terminal type has been
5880 * specified, treat it as a generic ANSI terminal.
5882 if(is_term
&& !term
)
5885 * Make a copy of the terminal type string.
5887 if(term
!= gl
->term
) {
5889 * Delete any old terminal type string.
5896 * Make a copy of the new terminal-type string, if any.
5899 size_t termsz
= strlen(term
)+1;
5901 gl
->term
= (char *) malloc(termsz
);
5903 strlcpy(gl
->term
, term
, termsz
);
5907 * Clear any terminal-specific key bindings that were taken from the
5908 * settings of the last terminal.
5910 _kt_clear_bindings(gl
->bindings
, KTB_TERM
);
5912 * If we have a terminal install new bindings for it.
5916 * Get the current settings of the terminal.
5918 if(tcgetattr(gl
->input_fd
, &gl
->oldattr
)) {
5919 _err_record_msg(gl
->err
, "tcgetattr error", END_ERR_MSG
);
5923 * If we don't set this now, gl_control_strings() won't know
5924 * that it is talking to a terminal.
5928 * Lookup the terminal control string and size information.
5930 if(gl_control_strings(gl
, term
)) {
5935 * Bind terminal-specific keys.
5937 if(gl_bind_terminal_keys(gl
))
5941 * Assume that the caller has given us a terminal in a sane state.
5943 gl
->io_mode
= GL_NORMAL_MODE
;
5945 * Switch into the currently configured I/O mode.
5947 if(_gl_io_mode(gl
, gl
->io_mode
))
5952 /*.......................................................................
5953 * Set up terminal-specific key bindings.
5956 * gl GetLine * The resource object of the command-line input
5959 * return int 0 - OK.
5962 static int gl_bind_terminal_keys(GetLine
*gl
)
5965 * Install key-bindings for the special terminal characters.
5967 if(gl_bind_control_char(gl
, KTB_TERM
, gl
->oldattr
.c_cc
[VINTR
],
5968 "user-interrupt") ||
5969 gl_bind_control_char(gl
, KTB_TERM
, gl
->oldattr
.c_cc
[VQUIT
], "abort") ||
5970 gl_bind_control_char(gl
, KTB_TERM
, gl
->oldattr
.c_cc
[VSUSP
], "suspend"))
5973 * In vi-mode, arrange for the above characters to be seen in command
5976 if(gl
->editor
== GL_VI_MODE
) {
5977 if(gl_bind_control_char(gl
, KTB_TERM
, MAKE_META(gl
->oldattr
.c_cc
[VINTR
]),
5978 "user-interrupt") ||
5979 gl_bind_control_char(gl
, KTB_TERM
, MAKE_META(gl
->oldattr
.c_cc
[VQUIT
]),
5981 gl_bind_control_char(gl
, KTB_TERM
, MAKE_META(gl
->oldattr
.c_cc
[VSUSP
]),
5986 * Non-universal special keys.
5989 if(gl_bind_control_char(gl
, KTB_TERM
, gl
->oldattr
.c_cc
[VLNEXT
],
5993 if(_kt_set_keybinding(gl
->bindings
, KTB_TERM
, "^V", "literal-next")) {
5994 _err_record_msg(gl
->err
, _kt_last_error(gl
->bindings
), END_ERR_MSG
);
5999 * Bind action functions to the terminal-specific arrow keys
6000 * looked up by gl_control_strings().
6002 if(_gl_bind_arrow_keys(gl
))
6007 /*.......................................................................
6008 * This function is normally bound to control-D. When it is invoked within
6009 * a line it deletes the character which follows the cursor. When invoked
6010 * at the end of the line it lists possible file completions, and when
6011 * invoked on an empty line it causes gl_get_line() to return EOF. This
6012 * function emulates the one that is normally bound to control-D by tcsh.
6014 static KT_KEY_FN(gl_del_char_or_list_or_eof
)
6017 * If we have an empty line arrange to return EOF.
6019 if(gl
->ntotal
< 1) {
6020 gl_record_status(gl
, GLR_EOF
, 0);
6023 * If we are at the end of the line list possible completions.
6025 } else if(gl
->buff_curpos
>= gl
->ntotal
) {
6026 return gl_list_completions(gl
, 1, NULL
);
6028 * Within the line delete the character that follows the cursor.
6032 * If in vi command mode, first preserve the current line for potential use
6035 gl_save_for_undo(gl
);
6037 * Delete 'count' characters.
6039 return gl_forward_delete_char(gl
, count
, NULL
);
6043 /*.......................................................................
6044 * This function is normally bound to control-D in vi mode. When it is
6045 * invoked within a line it lists possible file completions, and when
6046 * invoked on an empty line it causes gl_get_line() to return EOF. This
6047 * function emulates the one that is normally bound to control-D by tcsh.
6049 static KT_KEY_FN(gl_list_or_eof
)
6052 * If we have an empty line arrange to return EOF.
6054 if(gl
->ntotal
< 1) {
6055 gl_record_status(gl
, GLR_EOF
, 0);
6058 * Otherwise list possible completions.
6061 return gl_list_completions(gl
, 1, NULL
);
6065 /*.......................................................................
6066 * List possible completions of the word that precedes the cursor. The
6067 * callback data argument must either be NULL to select the default
6068 * file completion callback, or be a GlCplCallback object containing the
6069 * completion callback function to call.
6071 static KT_KEY_FN(gl_list_completions
)
6073 int waserr
= 0; /* True after errors */
6075 * Get the container of the completion callback and its callback data.
6077 GlCplCallback
*cb
= data
? (GlCplCallback
*) data
: &gl
->cplfn
;
6079 * Get the list of possible completions.
6081 CplMatches
*matches
= cpl_complete_word(gl
->cpl
, gl
->line
, gl
->buff_curpos
,
6084 * No matching completions?
6087 waserr
= gl_print_info(gl
, cpl_last_error(gl
->cpl
), GL_END_INFO
);
6091 } else if(matches
->nmatch
> 0 && gl
->echo
) {
6092 if(_gl_normal_io(gl
) ||
6093 _cpl_output_completions(matches
, gl_write_fn
, gl
, gl
->ncolumn
))
6097 * If any output had to be written to the terminal, then editing will
6098 * have been suspended, make sure that we are back in raw line editing
6099 * mode before returning.
6101 if(_gl_raw_io(gl
, 1))
6106 /*.......................................................................
6107 * Where the user has used the symbolic arrow-key names to specify
6108 * arrow key bindings, bind the specified action functions to the default
6109 * and terminal specific arrow key sequences.
6112 * gl GetLine * The getline resource object.
6114 * return int 0 - OK.
6117 static int _gl_bind_arrow_keys(GetLine
*gl
)
6120 * Process each of the arrow keys.
6122 if(_gl_rebind_arrow_key(gl
, "up", gl
->u_arrow
, "^[[A", "^[OA") ||
6123 _gl_rebind_arrow_key(gl
, "down", gl
->d_arrow
, "^[[B", "^[OB") ||
6124 _gl_rebind_arrow_key(gl
, "left", gl
->l_arrow
, "^[[D", "^[OD") ||
6125 _gl_rebind_arrow_key(gl
, "right", gl
->r_arrow
, "^[[C", "^[OC"))
6130 /*.......................................................................
6131 * Lookup the action function of a symbolic arrow-key binding, and bind
6132 * it to the terminal-specific and default arrow-key sequences. Note that
6133 * we don't trust the terminal-specified key sequences to be correct.
6134 * The main reason for this is that on some machines the xterm terminfo
6135 * entry is for hardware X-terminals, rather than xterm terminal emulators
6136 * and the two terminal types emit different character sequences when the
6137 * their cursor keys are pressed. As a result we also supply a couple
6138 * of default key sequences.
6141 * gl GetLine * The resource object of gl_get_line().
6142 * name char * The symbolic name of the arrow key.
6143 * term_seq char * The terminal-specific arrow-key sequence.
6144 * def_seq1 char * The first default arrow-key sequence.
6145 * def_seq2 char * The second arrow-key sequence.
6147 * return int 0 - OK.
6150 static int _gl_rebind_arrow_key(GetLine
*gl
, const char *name
,
6151 const char *term_seq
, const char *def_seq1
,
6152 const char *def_seq2
)
6154 KeySym
*keysym
; /* The binding-table entry matching the arrow-key name */
6155 int nsym
; /* The number of ambiguous matches */
6157 * Lookup the key binding for the symbolic name of the arrow key. This
6158 * will either be the default action, or a user provided one.
6160 if(_kt_lookup_keybinding(gl
->bindings
, name
, strlen(name
), &keysym
, &nsym
)
6161 == KT_EXACT_MATCH
) {
6163 * Get the action function.
6165 KtAction
*action
= keysym
->actions
+ keysym
->binder
;
6166 KtKeyFn
*fn
= action
->fn
;
6167 void *data
= action
->data
;
6169 * Bind this to each of the specified key sequences.
6172 _kt_set_keyfn(gl
->bindings
, KTB_TERM
, term_seq
, fn
, data
)) ||
6174 _kt_set_keyfn(gl
->bindings
, KTB_NORM
, def_seq1
, fn
, data
)) ||
6176 _kt_set_keyfn(gl
->bindings
, KTB_NORM
, def_seq2
, fn
, data
))) {
6177 _err_record_msg(gl
->err
, _kt_last_error(gl
->bindings
), END_ERR_MSG
);
6184 /*.......................................................................
6185 * Read getline configuration information from a given file.
6188 * gl GetLine * The getline resource object.
6189 * filename const char * The name of the file to read configuration
6190 * information from. The contents of this file
6191 * are as described in the gl_get_line(3) man
6192 * page for the default ~/.teclarc configuration
6194 * who KtBinder Who bindings are to be installed for.
6196 * return int 0 - OK.
6197 * 1 - Irrecoverable error.
6199 static int _gl_read_config_file(GetLine
*gl
, const char *filename
, KtBinder who
)
6202 * If filesystem access is to be excluded, configuration files can't
6205 #ifdef WITHOUT_FILE_SYSTEM
6206 _err_record_msg(gl
->err
,
6207 "Can't read configuration files without filesystem access",
6212 FileExpansion
*expansion
; /* The expansion of the filename */
6213 FILE *fp
; /* The opened file */
6214 int waserr
= 0; /* True if an error occurred while reading */
6215 int lineno
= 1; /* The line number being processed */
6217 * Check the arguments.
6219 if(!gl
|| !filename
) {
6221 _err_record_msg(gl
->err
, "NULL argument(s)", END_ERR_MSG
);
6226 * Expand the filename.
6228 expansion
= ef_expand_file(gl
->ef
, filename
, -1);
6230 gl_print_info(gl
, "Unable to expand ", filename
, " (",
6231 ef_last_error(gl
->ef
), ").", GL_END_INFO
);
6235 * Attempt to open the file.
6237 fp
= fopen(expansion
->files
[0], "r");
6239 * It isn't an error for there to be no configuration file.
6244 * Parse the contents of the file.
6246 while(!waserr
&& !feof(fp
))
6247 waserr
= _gl_parse_config_line(gl
, fp
, glc_file_getc
, filename
, who
,
6250 * Bind action functions to the terminal-specific arrow keys.
6252 if(_gl_bind_arrow_keys(gl
))
6262 /*.......................................................................
6263 * Read GetLine configuration information from a string. The contents of
6264 * the string are the same as those described in the gl_get_line(3)
6265 * man page for the contents of the ~/.teclarc configuration file.
6267 static int _gl_read_config_string(GetLine
*gl
, const char *buffer
, KtBinder who
)
6269 const char *bptr
; /* A pointer into buffer[] */
6270 int waserr
= 0; /* True if an error occurred while reading */
6271 int lineno
= 1; /* The line number being processed */
6273 * Check the arguments.
6275 if(!gl
|| !buffer
) {
6277 _err_record_msg(gl
->err
, "NULL argument(s)", END_ERR_MSG
);
6282 * Get a pointer to the start of the buffer.
6286 * Parse the contents of the buffer.
6288 while(!waserr
&& *bptr
)
6289 waserr
= _gl_parse_config_line(gl
, &bptr
, glc_buff_getc
, "", who
, &lineno
);
6291 * Bind action functions to the terminal-specific arrow keys.
6293 if(_gl_bind_arrow_keys(gl
))
6298 /*.......................................................................
6299 * Parse the next line of a getline configuration file.
6302 * gl GetLine * The getline resource object.
6303 * stream void * The pointer representing the stream to be read
6305 * getc_fn GlcGetcFn * A callback function which when called with
6306 * 'stream' as its argument, returns the next
6307 * unread character from the stream.
6308 * origin const char * The name of the entity being read (eg. a
6310 * who KtBinder Who bindings are to be installed for.
6312 * lineno int * The line number being processed is to be
6313 * maintained in *lineno.
6315 * return int 0 - OK.
6316 * 1 - Irrecoverable error.
6318 static int _gl_parse_config_line(GetLine
*gl
, void *stream
, GlcGetcFn
*getc_fn
,
6319 const char *origin
, KtBinder who
, int *lineno
)
6321 char buffer
[GL_CONF_BUFLEN
+1]; /* The input line buffer */
6322 char *argv
[GL_CONF_MAXARG
]; /* The argument list */
6323 int argc
= 0; /* The number of arguments in argv[] */
6324 int c
; /* A character from the file */
6325 int escaped
= 0; /* True if the next character is escaped */
6328 * Skip spaces and tabs.
6330 do c
= getc_fn(stream
); while(c
==' ' || c
=='\t');
6332 * Comments extend to the end of the line.
6335 do c
= getc_fn(stream
); while(c
!= '\n' && c
!= EOF
);
6337 * Ignore empty lines.
6339 if(c
=='\n' || c
==EOF
) {
6344 * Record the buffer location of the start of the first argument.
6346 argv
[argc
] = buffer
;
6348 * Read the rest of the line, stopping early if a comment is seen, or
6349 * the buffer overflows, and replacing sequences of spaces with a
6350 * '\0', and recording the thus terminated string as an argument.
6353 while(i
<GL_CONF_BUFLEN
) {
6355 * Did we hit the end of the latest argument?
6357 if(c
==EOF
|| (!escaped
&& (c
==' ' || c
=='\n' || c
=='\t' || c
=='#'))) {
6359 * Terminate the argument.
6364 * Skip spaces and tabs.
6366 while(c
==' ' || c
=='\t')
6367 c
= getc_fn(stream
);
6369 * If we hit the end of the line, or the start of a comment, exit the loop.
6371 if(c
==EOF
|| c
=='\n' || c
=='#')
6374 * Start recording the next argument.
6376 if(argc
>= GL_CONF_MAXARG
) {
6377 gl_report_config_error(gl
, origin
, *lineno
, "Too many arguments.");
6378 do c
= getc_fn(stream
); while(c
!='\n' && c
!=EOF
); /* Skip past eol */
6381 argv
[argc
] = buffer
+ i
;
6383 * The next character was preceded by spaces, so it isn't escaped.
6388 * If we hit an unescaped backslash, this means that we should arrange
6389 * to treat the next character like a simple alphabetical character.
6391 if(c
=='\\' && !escaped
) {
6394 * Splice lines where the newline is escaped.
6396 } else if(c
=='\n' && escaped
) {
6399 * Record a normal character, preserving any preceding backslash.
6404 if(i
>=GL_CONF_BUFLEN
)
6410 * Get the next character.
6412 c
= getc_fn(stream
);
6416 * Did the buffer overflow?
6418 if(i
>=GL_CONF_BUFLEN
) {
6419 gl_report_config_error(gl
, origin
, *lineno
, "Line too long.");
6423 * The first argument should be a command name.
6425 if(strcmp(argv
[0], "bind") == 0) {
6426 const char *action
= NULL
; /* A NULL action removes a keybinding */
6427 const char *keyseq
= NULL
;
6432 case 2: /* Note the intentional fallthrough */
6435 * Attempt to record the new keybinding.
6437 if(_kt_set_keybinding(gl
->bindings
, who
, keyseq
, action
)) {
6438 gl_report_config_error(gl
, origin
, *lineno
,
6439 _kt_last_error(gl
->bindings
));
6443 gl_report_config_error(gl
, origin
, *lineno
, "Wrong number of arguments.");
6445 } else if(strcmp(argv
[0], "edit-mode") == 0) {
6446 if(argc
== 2 && strcmp(argv
[1], "emacs") == 0) {
6447 gl_change_editor(gl
, GL_EMACS_MODE
);
6448 } else if(argc
== 2 && strcmp(argv
[1], "vi") == 0) {
6449 gl_change_editor(gl
, GL_VI_MODE
);
6450 } else if(argc
== 2 && strcmp(argv
[1], "none") == 0) {
6451 gl_change_editor(gl
, GL_NO_EDITOR
);
6453 gl_report_config_error(gl
, origin
, *lineno
,
6454 "The argument of editor should be vi or emacs.");
6456 } else if(strcmp(argv
[0], "nobeep") == 0) {
6457 gl
->silence_bell
= 1;
6459 gl_report_config_error(gl
, origin
, *lineno
, "Unknown command name.");
6462 * Skip any trailing comment.
6464 while(c
!= '\n' && c
!= EOF
)
6465 c
= getc_fn(stream
);
6470 /*.......................................................................
6471 * This is a private function of _gl_parse_config_line() which prints
6472 * out an error message about the contents of the line, prefixed by the
6473 * name of the origin of the line and its line number.
6476 * gl GetLine * The resource object of gl_get_line().
6477 * origin const char * The name of the entity being read (eg. a
6479 * lineno int The line number at which the error occurred.
6480 * errmsg const char * The error message.
6482 * return int 0 - OK.
6485 static int gl_report_config_error(GetLine
*gl
, const char *origin
, int lineno
,
6488 char lnum
[20]; /* A buffer in which to render a single integer */
6490 * Convert the line number into a string.
6492 snprintf(lnum
, sizeof(lnum
), "%d", lineno
);
6494 * Have the string printed on the terminal.
6496 return gl_print_info(gl
, origin
, ":", lnum
, ": ", errmsg
, GL_END_INFO
);
6499 /*.......................................................................
6500 * This is the _gl_parse_config_line() callback function which reads the
6501 * next character from a configuration file.
6503 static GLC_GETC_FN(glc_file_getc
)
6505 return fgetc((FILE *) stream
);
6508 /*.......................................................................
6509 * This is the _gl_parse_config_line() callback function which reads the
6510 * next character from a buffer. Its stream argument is a pointer to a
6511 * variable which is, in turn, a pointer into the buffer being read from.
6513 static GLC_GETC_FN(glc_buff_getc
)
6515 const char **lptr
= (char const **) stream
;
6516 return **lptr
? *(*lptr
)++ : EOF
;
6519 #ifndef HIDE_FILE_SYSTEM
6520 /*.......................................................................
6521 * When this action is triggered, it arranges to temporarily read command
6522 * lines from the regular file whos name precedes the cursor.
6523 * The current line is first discarded.
6525 static KT_KEY_FN(gl_read_from_file
)
6527 char *start_path
; /* The pointer to the start of the pathname in */
6529 FileExpansion
*result
; /* The results of the filename expansion */
6530 int pathlen
; /* The length of the pathname being expanded */
6532 * Locate the start of the filename that precedes the cursor position.
6534 start_path
= _pu_start_of_path(gl
->line
, gl
->buff_curpos
);
6538 * Get the length of the pathname string.
6540 pathlen
= gl
->buff_curpos
- (start_path
- gl
->line
);
6542 * Attempt to expand the pathname.
6544 result
= ef_expand_file(gl
->ef
, start_path
, pathlen
);
6546 * If there was an error, report the error on a new line.
6549 return gl_print_info(gl
, ef_last_error(gl
->ef
), GL_END_INFO
);
6551 * If no files matched, report this as well.
6553 } else if(result
->nfile
== 0 || !result
->exists
) {
6554 return gl_print_info(gl
, "No files match.", GL_END_INFO
);
6556 * Complain if more than one file matches.
6558 } else if(result
->nfile
> 1) {
6559 return gl_print_info(gl
, "More than one file matches.", GL_END_INFO
);
6561 * Disallow input from anything but normal files. In principle we could
6562 * also support input from named pipes. Terminal files would be a problem
6563 * since we wouldn't know the terminal type, and other types of files
6564 * might cause the library to lock up.
6566 } else if(!_pu_path_is_file(result
->files
[0])) {
6567 return gl_print_info(gl
, "Not a normal file.", GL_END_INFO
);
6570 * Attempt to open and install the specified file for reading.
6572 gl
->file_fp
= fopen(result
->files
[0], "r");
6574 return gl_print_info(gl
, "Unable to open: ", result
->files
[0],
6578 * If needed, expand the record of the maximum file-descriptor that might
6579 * need to be monitored with select().
6582 if(fileno(gl
->file_fp
) > gl
->max_fd
)
6583 gl
->max_fd
= fileno(gl
->file_fp
);
6586 * Is non-blocking I/O needed?
6588 if(gl
->raw_mode
&& gl
->io_mode
==GL_SERVER_MODE
&&
6589 gl_nonblocking_io(gl
, fileno(gl
->file_fp
))) {
6590 gl_revert_input(gl
);
6591 return gl_print_info(gl
, "Can't read file %s with non-blocking I/O",
6595 * Inform the user what is happening.
6597 if(gl_print_info(gl
, "<Taking input from ", result
->files
[0], ">",
6605 /*.......................................................................
6606 * Close any temporary file that is being used for input.
6609 * gl GetLine * The getline resource object.
6611 static void gl_revert_input(GetLine
*gl
)
6614 fclose(gl
->file_fp
);
6619 /*.......................................................................
6620 * This is the action function that recalls the oldest line in the
6623 static KT_KEY_FN(gl_beginning_of_history
)
6626 * In vi mode, switch to command mode, since the user is very
6627 * likely to want to move around newly recalled lines.
6629 gl_vi_command_mode(gl
);
6631 * Forget any previous recall session.
6635 * Record the key sequence number of this search action.
6637 gl
->last_search
= gl
->keyseq_count
;
6639 * Recall the next oldest line in the history list.
6641 if(_glh_oldest_line(gl
->glh
, gl
->line
, gl
->linelen
+1) == NULL
)
6644 * Accomodate the new contents of gl->line[].
6646 gl_update_buffer(gl
);
6648 * Arrange to have the cursor placed at the end of the new line.
6650 gl
->buff_curpos
= gl
->ntotal
;
6652 * Erase and display the new line.
6654 gl_queue_redisplay(gl
);
6658 /*.......................................................................
6659 * If a history session is currently in progress, this action function
6660 * recalls the line that was being edited when the session started. If
6661 * no history session is in progress, it does nothing.
6663 static KT_KEY_FN(gl_end_of_history
)
6666 * In vi mode, switch to command mode, since the user is very
6667 * likely to want to move around newly recalled lines.
6669 gl_vi_command_mode(gl
);
6671 * Forget any previous recall session.
6675 * Record the key sequence number of this search action.
6677 gl
->last_search
= gl
->keyseq_count
;
6679 * Recall the next oldest line in the history list.
6681 if(_glh_current_line(gl
->glh
, gl
->line
, gl
->linelen
+1) == NULL
)
6684 * Accomodate the new contents of gl->line[].
6686 gl_update_buffer(gl
);
6688 * Arrange to have the cursor placed at the end of the new line.
6690 gl
->buff_curpos
= gl
->ntotal
;
6692 * Erase and display the new line.
6694 gl_queue_redisplay(gl
);
6698 /*.......................................................................
6699 * This action function is treated specially, in that its count argument
6700 * is set to the end keystroke of the keysequence that activated it.
6701 * It accumulates a numeric argument, adding one digit on each call in
6702 * which the last keystroke was a numeric digit.
6704 static KT_KEY_FN(gl_digit_argument
)
6707 * Was the last keystroke a digit?
6709 int is_digit
= isdigit((int)(unsigned char) count
);
6711 * In vi command mode, a lone '0' means goto-start-of-line.
6713 if(gl
->vi
.command
&& gl
->number
< 0 && count
== '0')
6714 return gl_beginning_of_line(gl
, count
, NULL
);
6716 * Are we starting to accumulate a new number?
6718 if(gl
->number
< 0 || !is_digit
)
6721 * Was the last keystroke a digit?
6725 * Read the numeric value of the digit, without assuming ASCII.
6728 char s
[2]; s
[0] = count
; s
[1] = '\0';
6731 * Append the new digit.
6733 gl
->number
= gl
->number
* 10 + n
;
6738 /*.......................................................................
6739 * The newline action function sets gl->endline to tell
6740 * gl_get_input_line() that the line is now complete.
6742 static KT_KEY_FN(gl_newline
)
6744 GlhLineID id
; /* The last history line recalled while entering this line */
6746 * Flag the line as ended.
6750 * Record the next position in the history buffer, for potential
6751 * recall by an action function on the next call to gl_get_line().
6753 id
= _glh_line_id(gl
->glh
, 1);
6755 gl
->preload_id
= id
;
6759 /*.......................................................................
6760 * The 'repeat' action function sets gl->endline to tell
6761 * gl_get_input_line() that the line is now complete, and records the
6762 * ID of the next history line in gl->preload_id so that the next call
6763 * to gl_get_input_line() will preload the line with that history line.
6765 static KT_KEY_FN(gl_repeat_history
)
6768 gl
->preload_id
= _glh_line_id(gl
->glh
, 1);
6769 gl
->preload_history
= 1;
6773 /*.......................................................................
6774 * Flush unwritten characters to the terminal.
6777 * gl GetLine * The getline resource object.
6779 * return int 0 - OK.
6780 * 1 - Either an error occured, or the output
6781 * blocked and non-blocking I/O is being used.
6782 * See gl->rtn_status for details.
6784 static int gl_flush_output(GetLine
*gl
)
6787 * Record the fact that we are about to write to the terminal.
6789 gl
->pending_io
= GLP_WRITE
;
6791 * Attempt to flush the output to the terminal.
6794 switch(_glq_flush_queue(gl
->cq
, gl
->flush_fn
, gl
)) {
6795 case GLQ_FLUSH_DONE
:
6796 return gl
->redisplay
&& !gl
->postpone
&& gl_redisplay(gl
, 1, NULL
);
6798 case GLQ_FLUSH_AGAIN
: /* Output blocked */
6799 gl_record_status(gl
, GLR_BLOCKED
, BLOCKED_ERRNO
);
6802 default: /* Abort the line if an error occurs */
6803 gl_record_status(gl
, errno
==EINTR
? GLR_SIGNAL
: GLR_ERROR
, errno
);
6809 /*.......................................................................
6810 * This is the callback which _glq_flush_queue() uses to write buffered
6811 * characters to the terminal.
6813 static GL_WRITE_FN(gl_flush_terminal
)
6815 int ndone
= 0; /* The number of characters written so far */
6817 * Get the line-editor resource object.
6819 GetLine
*gl
= (GetLine
*) data
;
6821 * Transfer the latest array of characters to stdio.
6824 int nnew
= write(gl
->output_fd
, s
, n
-ndone
);
6826 * If the write was successful, add to the recorded number of bytes
6827 * that have now been written.
6832 * If a signal interrupted the call, restart the write(), since all of
6833 * the signals that gl_get_line() has been told to watch for are
6834 * currently blocked.
6836 } else if(errno
== EINTR
) {
6839 * If we managed to write something before an I/O error occurred, or
6840 * output blocked before anything was written, report the number of
6841 * bytes that were successfully written before this happened.
6847 #if defined(EWOULDBLOCK)
6848 || errno
==EWOULDBLOCK
6854 * To get here, an error must have occurred before anything new could
6862 * To get here, we must have successfully written the number of
6863 * bytes that was specified.
6868 /*.......................................................................
6869 * Change the style of editing to emulate a given editor.
6872 * gl GetLine * The getline resource object.
6873 * editor GlEditor The type of editor to emulate.
6875 * return int 0 - OK.
6878 static int gl_change_editor(GetLine
*gl
, GlEditor editor
)
6881 * Install the default key-bindings of the requested editor.
6885 _kt_clear_bindings(gl
->bindings
, KTB_NORM
);
6886 _kt_clear_bindings(gl
->bindings
, KTB_TERM
);
6887 (void) _kt_add_bindings(gl
->bindings
, KTB_NORM
, gl_emacs_bindings
,
6888 sizeof(gl_emacs_bindings
)/sizeof(gl_emacs_bindings
[0]));
6891 _kt_clear_bindings(gl
->bindings
, KTB_NORM
);
6892 _kt_clear_bindings(gl
->bindings
, KTB_TERM
);
6893 (void) _kt_add_bindings(gl
->bindings
, KTB_NORM
, gl_vi_bindings
,
6894 sizeof(gl_vi_bindings
)/sizeof(gl_vi_bindings
[0]));
6899 _err_record_msg(gl
->err
, "Unknown editor", END_ERR_MSG
);
6904 * Record the new editing mode.
6906 gl
->editor
= editor
;
6907 gl
->vi
.command
= 0; /* Start in input mode */
6908 gl
->insert_curpos
= 0;
6910 * Reinstate terminal-specific bindings.
6912 if(gl
->editor
!= GL_NO_EDITOR
&& gl
->input_fp
)
6913 (void) gl_bind_terminal_keys(gl
);
6917 /*.......................................................................
6918 * This is an action function that switches to editing using emacs bindings
6920 static KT_KEY_FN(gl_emacs_editing_mode
)
6922 return gl_change_editor(gl
, GL_EMACS_MODE
);
6925 /*.......................................................................
6926 * This is an action function that switches to editing using vi bindings
6928 static KT_KEY_FN(gl_vi_editing_mode
)
6930 return gl_change_editor(gl
, GL_VI_MODE
);
6933 /*.......................................................................
6934 * This is the action function that switches to insert mode.
6936 static KT_KEY_FN(gl_vi_insert
)
6939 * If in vi command mode, preserve the current line for potential
6942 gl_save_for_undo(gl
);
6944 * Switch to vi insert mode.
6948 gl
->insert_curpos
= gl
->buff_curpos
;
6952 /*.......................................................................
6953 * This is an action function that switches to overwrite mode.
6955 static KT_KEY_FN(gl_vi_overwrite
)
6958 * If in vi command mode, preserve the current line for potential
6961 gl_save_for_undo(gl
);
6963 * Switch to vi overwrite mode.
6967 gl
->insert_curpos
= gl
->buff_curpos
;
6971 /*.......................................................................
6972 * This action function toggles the case of the character under the
6975 static KT_KEY_FN(gl_change_case
)
6979 * Keep a record of the current insert mode and the cursor position.
6981 int insert
= gl
->insert
;
6983 * If in vi command mode, preserve the current line for potential
6986 gl_save_for_undo(gl
);
6988 * We want to overwrite the modified word.
6992 * Toggle the case of 'count' characters.
6994 for(i
=0; i
<count
&& gl
->buff_curpos
< gl
->ntotal
; i
++) {
6995 char *cptr
= gl
->line
+ gl
->buff_curpos
++;
6997 * Convert the character to upper case?
6999 if(islower((int)(unsigned char) *cptr
))
7000 gl_buffer_char(gl
, toupper((int) *cptr
), cptr
- gl
->line
);
7001 else if(isupper((int)(unsigned char) *cptr
))
7002 gl_buffer_char(gl
, tolower((int) *cptr
), cptr
- gl
->line
);
7004 * Write the possibly modified character back. Note that for non-modified
7005 * characters we want to do this as well, so as to advance the cursor.
7007 if(gl_print_char(gl
, *cptr
, cptr
[1]))
7011 * Restore the insertion mode.
7013 gl
->insert
= insert
;
7014 return gl_place_cursor(gl
, gl
->buff_curpos
); /* bounds check */
7017 /*.......................................................................
7018 * This is the action function which implements the vi-style action which
7019 * moves the cursor to the start of the line, then switches to insert mode.
7021 static KT_KEY_FN(gl_vi_insert_at_bol
)
7023 gl_save_for_undo(gl
);
7024 return gl_beginning_of_line(gl
, 0, NULL
) ||
7025 gl_vi_insert(gl
, 0, NULL
);
7029 /*.......................................................................
7030 * This is the action function which implements the vi-style action which
7031 * moves the cursor to the end of the line, then switches to insert mode
7032 * to allow text to be appended to the line.
7034 static KT_KEY_FN(gl_vi_append_at_eol
)
7036 gl_save_for_undo(gl
);
7037 gl
->vi
.command
= 0; /* Allow cursor at EOL */
7038 return gl_end_of_line(gl
, 0, NULL
) ||
7039 gl_vi_insert(gl
, 0, NULL
);
7042 /*.......................................................................
7043 * This is the action function which implements the vi-style action which
7044 * moves the cursor to right one then switches to insert mode, thus
7045 * allowing text to be appended after the next character.
7047 static KT_KEY_FN(gl_vi_append
)
7049 gl_save_for_undo(gl
);
7050 gl
->vi
.command
= 0; /* Allow cursor at EOL */
7051 return gl_cursor_right(gl
, 1, NULL
) ||
7052 gl_vi_insert(gl
, 0, NULL
);
7055 /*.......................................................................
7056 * This action function moves the cursor to the column specified by the
7057 * numeric argument. Column indexes start at 1.
7059 static KT_KEY_FN(gl_goto_column
)
7061 return gl_place_cursor(gl
, count
- 1);
7064 /*.......................................................................
7065 * Starting with the character under the cursor, replace 'count'
7066 * characters with the next character that the user types.
7068 static KT_KEY_FN(gl_vi_replace_char
)
7070 char c
; /* The replacement character */
7073 * Keep a record of the current insert mode.
7075 int insert
= gl
->insert
;
7077 * Get the replacement character.
7079 if(gl
->vi
.repeat
.active
) {
7080 c
= gl
->vi
.repeat
.input_char
;
7082 if(gl_read_terminal(gl
, 1, &c
))
7084 gl
->vi
.repeat
.input_char
= c
;
7087 * Are there 'count' characters to be replaced?
7089 if(gl
->ntotal
- gl
->buff_curpos
>= count
) {
7091 * If in vi command mode, preserve the current line for potential
7094 gl_save_for_undo(gl
);
7096 * Temporarily switch to overwrite mode.
7100 * Overwrite the current character plus count-1 subsequent characters
7101 * with the replacement character.
7103 for(i
=0; i
<count
; i
++)
7104 gl_add_char_to_line(gl
, c
);
7106 * Restore the original insert/overwrite mode.
7108 gl
->insert
= insert
;
7110 return gl_place_cursor(gl
, gl
->buff_curpos
); /* bounds check */
7113 /*.......................................................................
7114 * This is an action function which changes all characters between the
7115 * current cursor position and the end of the line.
7117 static KT_KEY_FN(gl_vi_change_rest_of_line
)
7119 gl_save_for_undo(gl
);
7120 gl
->vi
.command
= 0; /* Allow cursor at EOL */
7121 return gl_kill_line(gl
, count
, NULL
) || gl_vi_insert(gl
, 0, NULL
);
7124 /*.......................................................................
7125 * This is an action function which changes all characters between the
7126 * start of the line and the current cursor position.
7128 static KT_KEY_FN(gl_vi_change_to_bol
)
7130 return gl_backward_kill_line(gl
,count
,NULL
) || gl_vi_insert(gl
,0,NULL
);
7133 /*.......................................................................
7134 * This is an action function which deletes the entire contents of the
7135 * current line and switches to insert mode.
7137 static KT_KEY_FN(gl_vi_change_line
)
7139 return gl_delete_line(gl
,count
,NULL
) || gl_vi_insert(gl
,0,NULL
);
7142 /*.......................................................................
7143 * Starting from the cursor position and looking towards the end of the
7144 * line, copy 'count' characters to the cut buffer.
7146 static KT_KEY_FN(gl_forward_copy_char
)
7149 * Limit the count to the number of characters available.
7151 if(gl
->buff_curpos
+ count
>= gl
->ntotal
)
7152 count
= gl
->ntotal
- gl
->buff_curpos
;
7156 * Copy the characters to the cut buffer.
7158 memcpy(gl
->cutbuf
, gl
->line
+ gl
->buff_curpos
, count
);
7159 gl
->cutbuf
[count
] = '\0';
7163 /*.......................................................................
7164 * Starting from the character before the cursor position and looking
7165 * backwards towards the start of the line, copy 'count' characters to
7168 static KT_KEY_FN(gl_backward_copy_char
)
7171 * Limit the count to the number of characters available.
7173 if(count
> gl
->buff_curpos
)
7174 count
= gl
->buff_curpos
;
7177 gl_place_cursor(gl
, gl
->buff_curpos
- count
);
7179 * Copy the characters to the cut buffer.
7181 memcpy(gl
->cutbuf
, gl
->line
+ gl
->buff_curpos
, count
);
7182 gl
->cutbuf
[count
] = '\0';
7186 /*.......................................................................
7187 * Starting from the cursor position copy to the specified column into the
7190 static KT_KEY_FN(gl_copy_to_column
)
7192 if (--count
>= gl
->buff_curpos
)
7193 return gl_forward_copy_char(gl
, count
- gl
->buff_curpos
, NULL
);
7195 return gl_backward_copy_char(gl
, gl
->buff_curpos
- count
, NULL
);
7198 /*.......................................................................
7199 * Starting from the cursor position copy characters up to a matching
7200 * parenthesis into the cut buffer.
7202 static KT_KEY_FN(gl_copy_to_parenthesis
)
7204 int curpos
= gl_index_of_matching_paren(gl
);
7206 gl_save_for_undo(gl
);
7207 if(curpos
>= gl
->buff_curpos
)
7208 return gl_forward_copy_char(gl
, curpos
- gl
->buff_curpos
+ 1, NULL
);
7210 return gl_backward_copy_char(gl
, ++gl
->buff_curpos
- curpos
+ 1, NULL
);
7215 /*.......................................................................
7216 * Starting from the cursor position copy the rest of the line into the
7219 static KT_KEY_FN(gl_copy_rest_of_line
)
7222 * Copy the characters to the cut buffer.
7224 memcpy(gl
->cutbuf
, gl
->line
+ gl
->buff_curpos
, gl
->ntotal
- gl
->buff_curpos
);
7225 gl
->cutbuf
[gl
->ntotal
- gl
->buff_curpos
] = '\0';
7229 /*.......................................................................
7230 * Copy from the beginning of the line to the cursor position into the
7233 static KT_KEY_FN(gl_copy_to_bol
)
7236 * Copy the characters to the cut buffer.
7238 memcpy(gl
->cutbuf
, gl
->line
, gl
->buff_curpos
);
7239 gl
->cutbuf
[gl
->buff_curpos
] = '\0';
7240 gl_place_cursor(gl
, 0);
7244 /*.......................................................................
7245 * Copy the entire line into the cut buffer.
7247 static KT_KEY_FN(gl_copy_line
)
7250 * Copy the characters to the cut buffer.
7252 memcpy(gl
->cutbuf
, gl
->line
, gl
->ntotal
);
7253 gl
->cutbuf
[gl
->ntotal
] = '\0';
7257 /*.......................................................................
7258 * Search forwards for the next character that the user enters.
7260 static KT_KEY_FN(gl_forward_find_char
)
7262 int pos
= gl_find_char(gl
, count
, 1, 1, '\0');
7263 return pos
>= 0 && gl_place_cursor(gl
, pos
);
7266 /*.......................................................................
7267 * Search backwards for the next character that the user enters.
7269 static KT_KEY_FN(gl_backward_find_char
)
7271 int pos
= gl_find_char(gl
, count
, 0, 1, '\0');
7272 return pos
>= 0 && gl_place_cursor(gl
, pos
);
7275 /*.......................................................................
7276 * Search forwards for the next character that the user enters. Move up to,
7277 * but not onto, the found character.
7279 static KT_KEY_FN(gl_forward_to_char
)
7281 int pos
= gl_find_char(gl
, count
, 1, 0, '\0');
7282 return pos
>= 0 && gl_place_cursor(gl
, pos
);
7285 /*.......................................................................
7286 * Search backwards for the next character that the user enters. Move back to,
7287 * but not onto, the found character.
7289 static KT_KEY_FN(gl_backward_to_char
)
7291 int pos
= gl_find_char(gl
, count
, 0, 0, '\0');
7292 return pos
>= 0 && gl_place_cursor(gl
, pos
);
7295 /*.......................................................................
7296 * Searching in a given direction, return the index of a given (or
7297 * read) character in the input line, or the character that precedes
7298 * it in the specified search direction. Return -1 if not found.
7301 * gl GetLine * The getline resource object.
7302 * count int The number of times to search.
7303 * forward int True if searching forward.
7304 * onto int True if the search should end on top of the
7305 * character, false if the search should stop
7306 * one character before the character in the
7307 * specified search direction.
7308 * c char The character to be sought, or '\0' if the
7309 * character should be read from the user.
7311 * return int The index of the character in gl->line[], or
7314 static int gl_find_char(GetLine
*gl
, int count
, int forward
, int onto
, char c
)
7316 int pos
; /* The index reached in searching the input line */
7319 * Get a character from the user?
7323 * If we are in the process of repeating a previous change command, substitute
7324 * the last find character.
7326 if(gl
->vi
.repeat
.active
) {
7327 c
= gl
->vi
.find_char
;
7329 if(gl_read_terminal(gl
, 1, &c
))
7332 * Record the details of the new search, for use by repeat finds.
7334 gl
->vi
.find_forward
= forward
;
7335 gl
->vi
.find_onto
= onto
;
7336 gl
->vi
.find_char
= c
;
7340 * Which direction should we search?
7344 * Search forwards 'count' times for the character, starting with the
7345 * character that follows the cursor.
7347 for(i
=0, pos
=gl
->buff_curpos
; i
<count
&& pos
< gl
->ntotal
; i
++) {
7349 * Advance past the last match (or past the current cursor position
7350 * on the first search).
7354 * Search for the next instance of c.
7356 for( ; pos
<gl
->ntotal
&& c
!=gl
->line
[pos
]; pos
++)
7360 * If the character was found and we have been requested to return the
7361 * position of the character that precedes the desired character, then
7362 * we have gone one character too far.
7364 if(!onto
&& pos
<gl
->ntotal
)
7368 * Search backwards 'count' times for the character, starting with the
7369 * character that precedes the cursor.
7371 for(i
=0, pos
=gl
->buff_curpos
; i
<count
&& pos
>= gl
->insert_curpos
; i
++) {
7373 * Step back one from the last match (or from the current cursor
7374 * position on the first search).
7378 * Search for the next instance of c.
7380 for( ; pos
>=gl
->insert_curpos
&& c
!=gl
->line
[pos
]; pos
--)
7384 * If the character was found and we have been requested to return the
7385 * position of the character that precedes the desired character, then
7386 * we have gone one character too far.
7388 if(!onto
&& pos
>=gl
->insert_curpos
)
7392 * If found, return the cursor position of the count'th match.
7393 * Otherwise ring the terminal bell.
7395 if(pos
>= gl
->insert_curpos
&& pos
< gl
->ntotal
) {
7398 (void) gl_ring_bell(gl
, 1, NULL
);
7403 /*.......................................................................
7404 * Repeat the last character search in the same direction as the last
7407 static KT_KEY_FN(gl_repeat_find_char
)
7409 int pos
= gl
->vi
.find_char
?
7410 gl_find_char(gl
, count
, gl
->vi
.find_forward
, gl
->vi
.find_onto
,
7411 gl
->vi
.find_char
) : -1;
7412 return pos
>= 0 && gl_place_cursor(gl
, pos
);
7415 /*.......................................................................
7416 * Repeat the last character search in the opposite direction as the last
7419 static KT_KEY_FN(gl_invert_refind_char
)
7421 int pos
= gl
->vi
.find_char
?
7422 gl_find_char(gl
, count
, !gl
->vi
.find_forward
, gl
->vi
.find_onto
,
7423 gl
->vi
.find_char
) : -1;
7424 return pos
>= 0 && gl_place_cursor(gl
, pos
);
7427 /*.......................................................................
7428 * Search forward from the current position of the cursor for 'count'
7429 * word endings, returning the index of the last one found, or the end of
7430 * the line if there were less than 'count' words.
7433 * gl GetLine * The getline resource object.
7434 * n int The number of word boundaries to search for.
7436 * return int The buffer index of the located position.
7438 static int gl_nth_word_end_forward(GetLine
*gl
, int n
)
7440 int bufpos
; /* The buffer index being checked. */
7443 * In order to guarantee forward motion to the next word ending,
7444 * we need to start from one position to the right of the cursor
7445 * position, since this may already be at the end of a word.
7447 bufpos
= gl
->buff_curpos
+ 1;
7449 * If we are at the end of the line, return the index of the last
7450 * real character on the line. Note that this will be -1 if the line
7453 if(bufpos
>= gl
->ntotal
)
7454 return gl
->ntotal
- 1;
7456 * Search 'n' times, unless the end of the input line is reached first.
7458 for(i
=0; i
<n
&& bufpos
<gl
->ntotal
; i
++) {
7460 * If we are not already within a word, skip to the start of the next word.
7462 for( ; bufpos
<gl
->ntotal
&& !gl_is_word_char((int)gl
->line
[bufpos
]);
7466 * Find the end of the next word.
7468 for( ; bufpos
<gl
->ntotal
&& gl_is_word_char((int)gl
->line
[bufpos
]);
7473 * We will have overshot.
7475 return bufpos
> 0 ? bufpos
-1 : bufpos
;
7478 /*.......................................................................
7479 * Search forward from the current position of the cursor for 'count'
7480 * word starts, returning the index of the last one found, or the end of
7481 * the line if there were less than 'count' words.
7484 * gl GetLine * The getline resource object.
7485 * n int The number of word boundaries to search for.
7487 * return int The buffer index of the located position.
7489 static int gl_nth_word_start_forward(GetLine
*gl
, int n
)
7491 int bufpos
; /* The buffer index being checked. */
7494 * Get the current cursor position.
7496 bufpos
= gl
->buff_curpos
;
7498 * Search 'n' times, unless the end of the input line is reached first.
7500 for(i
=0; i
<n
&& bufpos
<gl
->ntotal
; i
++) {
7502 * Find the end of the current word.
7504 for( ; bufpos
<gl
->ntotal
&& gl_is_word_char((int)gl
->line
[bufpos
]);
7508 * Skip to the start of the next word.
7510 for( ; bufpos
<gl
->ntotal
&& !gl_is_word_char((int)gl
->line
[bufpos
]);
7517 /*.......................................................................
7518 * Search backward from the current position of the cursor for 'count'
7519 * word starts, returning the index of the last one found, or the start
7520 * of the line if there were less than 'count' words.
7523 * gl GetLine * The getline resource object.
7524 * n int The number of word boundaries to search for.
7526 * return int The buffer index of the located position.
7528 static int gl_nth_word_start_backward(GetLine
*gl
, int n
)
7530 int bufpos
; /* The buffer index being checked. */
7533 * Get the current cursor position.
7535 bufpos
= gl
->buff_curpos
;
7537 * Search 'n' times, unless the beginning of the input line (or vi insertion
7538 * point) is reached first.
7540 for(i
=0; i
<n
&& bufpos
> gl
->insert_curpos
; i
++) {
7542 * Starting one character back from the last search, so as not to keep
7543 * settling on the same word-start, search backwards until finding a
7546 while(--bufpos
>= gl
->insert_curpos
&&
7547 !gl_is_word_char((int)gl
->line
[bufpos
]))
7550 * Find the start of the word.
7552 while(--bufpos
>= gl
->insert_curpos
&&
7553 gl_is_word_char((int)gl
->line
[bufpos
]))
7556 * We will have gone one character too far.
7560 return bufpos
>= gl
->insert_curpos
? bufpos
: gl
->insert_curpos
;
7563 /*.......................................................................
7564 * Copy one or more words into the cut buffer without moving the cursor
7567 static KT_KEY_FN(gl_forward_copy_word
)
7570 * Find the location of the count'th start or end of a word
7571 * after the cursor, depending on whether in emacs or vi mode.
7573 int next
= gl
->editor
== GL_EMACS_MODE
?
7574 gl_nth_word_end_forward(gl
, count
) :
7575 gl_nth_word_start_forward(gl
, count
);
7577 * How many characters are to be copied into the cut buffer?
7579 int n
= next
- gl
->buff_curpos
;
7581 * Copy the specified segment and terminate the string.
7583 memcpy(gl
->cutbuf
, gl
->line
+ gl
->buff_curpos
, n
);
7584 gl
->cutbuf
[n
] = '\0';
7588 /*.......................................................................
7589 * Copy one or more words preceding the cursor into the cut buffer,
7590 * without moving the cursor or deleting text.
7592 static KT_KEY_FN(gl_backward_copy_word
)
7595 * Find the location of the count'th start of word before the cursor.
7597 int next
= gl_nth_word_start_backward(gl
, count
);
7599 * How many characters are to be copied into the cut buffer?
7601 int n
= gl
->buff_curpos
- next
;
7602 gl_place_cursor(gl
, next
);
7604 * Copy the specified segment and terminate the string.
7606 memcpy(gl
->cutbuf
, gl
->line
+ next
, n
);
7607 gl
->cutbuf
[n
] = '\0';
7611 /*.......................................................................
7612 * Copy the characters between the cursor and the count'th instance of
7613 * a specified character in the input line, into the cut buffer.
7616 * gl GetLine * The getline resource object.
7617 * count int The number of times to search.
7618 * c char The character to be searched for, or '\0' if
7619 * the character should be read from the user.
7620 * forward int True if searching forward.
7621 * onto int True if the search should end on top of the
7622 * character, false if the search should stop
7623 * one character before the character in the
7624 * specified search direction.
7626 * return int 0 - OK.
7630 static int gl_copy_find(GetLine
*gl
, int count
, char c
, int forward
, int onto
)
7632 int n
; /* The number of characters in the cut buffer */
7634 * Search for the character, and abort the operation if not found.
7636 int pos
= gl_find_char(gl
, count
, forward
, onto
, c
);
7640 * Copy the specified segment.
7643 n
= pos
+ 1 - gl
->buff_curpos
;
7644 memcpy(gl
->cutbuf
, gl
->line
+ gl
->buff_curpos
, n
);
7646 n
= gl
->buff_curpos
- pos
;
7647 memcpy(gl
->cutbuf
, gl
->line
+ pos
, n
);
7648 if(gl
->editor
== GL_VI_MODE
)
7649 gl_place_cursor(gl
, pos
);
7652 * Terminate the copy.
7654 gl
->cutbuf
[n
] = '\0';
7658 /*.......................................................................
7659 * Copy a section up to and including a specified character into the cut
7660 * buffer without moving the cursor or deleting text.
7662 static KT_KEY_FN(gl_forward_copy_find
)
7664 return gl_copy_find(gl
, count
, '\0', 1, 1);
7667 /*.......................................................................
7668 * Copy a section back to and including a specified character into the cut
7669 * buffer without moving the cursor or deleting text.
7671 static KT_KEY_FN(gl_backward_copy_find
)
7673 return gl_copy_find(gl
, count
, '\0', 0, 1);
7676 /*.......................................................................
7677 * Copy a section up to and not including a specified character into the cut
7678 * buffer without moving the cursor or deleting text.
7680 static KT_KEY_FN(gl_forward_copy_to
)
7682 return gl_copy_find(gl
, count
, '\0', 1, 0);
7685 /*.......................................................................
7686 * Copy a section back to and not including a specified character into the cut
7687 * buffer without moving the cursor or deleting text.
7689 static KT_KEY_FN(gl_backward_copy_to
)
7691 return gl_copy_find(gl
, count
, '\0', 0, 0);
7694 /*.......................................................................
7695 * Copy to a character specified in a previous search into the cut
7696 * buffer without moving the cursor or deleting text.
7698 static KT_KEY_FN(gl_copy_refind
)
7700 return gl_copy_find(gl
, count
, gl
->vi
.find_char
, gl
->vi
.find_forward
,
7704 /*.......................................................................
7705 * Copy to a character specified in a previous search, but in the opposite
7706 * direction, into the cut buffer without moving the cursor or deleting text.
7708 static KT_KEY_FN(gl_copy_invert_refind
)
7710 return gl_copy_find(gl
, count
, gl
->vi
.find_char
, !gl
->vi
.find_forward
,
7714 /*.......................................................................
7715 * Set the position of the cursor in the line input buffer and the
7719 * gl GetLine * The getline resource object.
7720 * buff_curpos int The new buffer cursor position.
7722 * return int 0 - OK.
7725 static int gl_place_cursor(GetLine
*gl
, int buff_curpos
)
7728 * Don't allow the cursor position to go out of the bounds of the input
7731 if(buff_curpos
>= gl
->ntotal
)
7732 buff_curpos
= gl
->vi
.command
? gl
->ntotal
-1 : gl
->ntotal
;
7736 * Record the new buffer position.
7738 gl
->buff_curpos
= buff_curpos
;
7740 * Move the terminal cursor to the corresponding character.
7742 return gl_set_term_curpos(gl
, gl
->prompt_len
+
7743 gl_displayed_string_width(gl
, gl
->line
, buff_curpos
, gl
->prompt_len
));
7746 /*.......................................................................
7747 * In vi command mode, this function saves the current line to the
7748 * historical buffer needed by the undo command. In emacs mode it does
7749 * nothing. In order to allow action functions to call other action
7750 * functions, gl_interpret_char() sets gl->vi.undo.saved to 0 before
7751 * invoking an action, and thereafter once any call to this function
7752 * has set it to 1, further calls are ignored.
7755 * gl GetLine * The getline resource object.
7757 static void gl_save_for_undo(GetLine
*gl
)
7759 if(gl
->vi
.command
&& !gl
->vi
.undo
.saved
) {
7760 strlcpy(gl
->vi
.undo
.line
, gl
->line
, gl
->linelen
);
7761 gl
->vi
.undo
.buff_curpos
= gl
->buff_curpos
;
7762 gl
->vi
.undo
.ntotal
= gl
->ntotal
;
7763 gl
->vi
.undo
.saved
= 1;
7765 if(gl
->vi
.command
&& !gl
->vi
.repeat
.saved
&&
7766 gl
->current_action
.fn
!= gl_vi_repeat_change
) {
7767 gl
->vi
.repeat
.action
= gl
->current_action
;
7768 gl
->vi
.repeat
.count
= gl
->current_count
;
7769 gl
->vi
.repeat
.saved
= 1;
7774 /*.......................................................................
7775 * In vi mode, restore the line to the way it was before the last command
7776 * mode operation, storing the current line in the buffer so that the
7777 * undo operation itself can subsequently be undone.
7779 static KT_KEY_FN(gl_vi_undo
)
7782 * Get pointers into the two lines.
7784 char *undo_ptr
= gl
->vi
.undo
.line
;
7785 char *line_ptr
= gl
->line
;
7787 * Swap the characters of the two buffers up to the length of the shortest
7790 while(*undo_ptr
&& *line_ptr
) {
7792 *undo_ptr
++ = *line_ptr
;
7796 * Copy the rest directly.
7798 if(gl
->ntotal
> gl
->vi
.undo
.ntotal
) {
7799 strlcpy(undo_ptr
, line_ptr
, gl
->linelen
);
7802 strlcpy(line_ptr
, undo_ptr
, gl
->linelen
);
7806 * Record the length of the stored string.
7808 gl
->vi
.undo
.ntotal
= gl
->ntotal
;
7810 * Accomodate the new contents of gl->line[].
7812 gl_update_buffer(gl
);
7814 * Set both cursor positions to the leftmost of the saved and current
7815 * cursor positions to emulate what vi does.
7817 if(gl
->buff_curpos
< gl
->vi
.undo
.buff_curpos
)
7818 gl
->vi
.undo
.buff_curpos
= gl
->buff_curpos
;
7820 gl
->buff_curpos
= gl
->vi
.undo
.buff_curpos
;
7822 * Since we have bipassed calling gl_save_for_undo(), record repeat
7823 * information inline.
7825 gl
->vi
.repeat
.action
.fn
= gl_vi_undo
;
7826 gl
->vi
.repeat
.action
.data
= NULL
;
7827 gl
->vi
.repeat
.count
= 1;
7829 * Display the restored line.
7831 gl_queue_redisplay(gl
);
7835 /*.......................................................................
7836 * Delete the following word and leave the user in vi insert mode.
7838 static KT_KEY_FN(gl_vi_forward_change_word
)
7840 gl_save_for_undo(gl
);
7841 gl
->vi
.command
= 0; /* Allow cursor at EOL */
7842 return gl_forward_delete_word(gl
, count
, NULL
) || gl_vi_insert(gl
, 0, NULL
);
7845 /*.......................................................................
7846 * Delete the preceding word and leave the user in vi insert mode.
7848 static KT_KEY_FN(gl_vi_backward_change_word
)
7850 return gl_backward_delete_word(gl
, count
, NULL
) || gl_vi_insert(gl
, 0, NULL
);
7853 /*.......................................................................
7854 * Delete the following section and leave the user in vi insert mode.
7856 static KT_KEY_FN(gl_vi_forward_change_find
)
7858 return gl_delete_find(gl
, count
, '\0', 1, 1, 1);
7861 /*.......................................................................
7862 * Delete the preceding section and leave the user in vi insert mode.
7864 static KT_KEY_FN(gl_vi_backward_change_find
)
7866 return gl_delete_find(gl
, count
, '\0', 0, 1, 1);
7869 /*.......................................................................
7870 * Delete the following section and leave the user in vi insert mode.
7872 static KT_KEY_FN(gl_vi_forward_change_to
)
7874 return gl_delete_find(gl
, count
, '\0', 1, 0, 1);
7877 /*.......................................................................
7878 * Delete the preceding section and leave the user in vi insert mode.
7880 static KT_KEY_FN(gl_vi_backward_change_to
)
7882 return gl_delete_find(gl
, count
, '\0', 0, 0, 1);
7885 /*.......................................................................
7886 * Delete to a character specified by a previous search and leave the user
7887 * in vi insert mode.
7889 static KT_KEY_FN(gl_vi_change_refind
)
7891 return gl_delete_find(gl
, count
, gl
->vi
.find_char
, gl
->vi
.find_forward
,
7892 gl
->vi
.find_onto
, 1);
7895 /*.......................................................................
7896 * Delete to a character specified by a previous search, but in the opposite
7897 * direction, and leave the user in vi insert mode.
7899 static KT_KEY_FN(gl_vi_change_invert_refind
)
7901 return gl_delete_find(gl
, count
, gl
->vi
.find_char
, !gl
->vi
.find_forward
,
7902 gl
->vi
.find_onto
, 1);
7905 /*.......................................................................
7906 * Delete the following character and leave the user in vi insert mode.
7908 static KT_KEY_FN(gl_vi_forward_change_char
)
7910 gl_save_for_undo(gl
);
7911 gl
->vi
.command
= 0; /* Allow cursor at EOL */
7912 return gl_delete_chars(gl
, count
, 1) || gl_vi_insert(gl
, 0, NULL
);
7915 /*.......................................................................
7916 * Delete the preceding character and leave the user in vi insert mode.
7918 static KT_KEY_FN(gl_vi_backward_change_char
)
7920 return gl_backward_delete_char(gl
, count
, NULL
) || gl_vi_insert(gl
, 0, NULL
);
7923 /*.......................................................................
7924 * Starting from the cursor position change characters to the specified column.
7926 static KT_KEY_FN(gl_vi_change_to_column
)
7928 if (--count
>= gl
->buff_curpos
)
7929 return gl_vi_forward_change_char(gl
, count
- gl
->buff_curpos
, NULL
);
7931 return gl_vi_backward_change_char(gl
, gl
->buff_curpos
- count
, NULL
);
7934 /*.......................................................................
7935 * Starting from the cursor position change characters to a matching
7938 static KT_KEY_FN(gl_vi_change_to_parenthesis
)
7940 int curpos
= gl_index_of_matching_paren(gl
);
7942 gl_save_for_undo(gl
);
7943 if(curpos
>= gl
->buff_curpos
)
7944 return gl_vi_forward_change_char(gl
, curpos
- gl
->buff_curpos
+ 1, NULL
);
7946 return gl_vi_backward_change_char(gl
, ++gl
->buff_curpos
- curpos
+ 1,
7952 /*.......................................................................
7953 * If in vi mode, switch to vi command mode.
7956 * gl GetLine * The getline resource object.
7958 static void gl_vi_command_mode(GetLine
*gl
)
7960 if(gl
->editor
== GL_VI_MODE
&& !gl
->vi
.command
) {
7963 gl
->vi
.repeat
.input_curpos
= gl
->insert_curpos
;
7964 gl
->vi
.repeat
.command_curpos
= gl
->buff_curpos
;
7965 gl
->insert_curpos
= 0; /* unrestrict left motion boundary */
7966 gl_cursor_left(gl
, 1, NULL
); /* Vi moves 1 left on entering command mode */
7970 /*.......................................................................
7971 * This is an action function which rings the terminal bell.
7973 static KT_KEY_FN(gl_ring_bell
)
7975 return gl
->silence_bell
? 0 :
7976 gl_print_control_sequence(gl
, 1, gl
->sound_bell
);
7979 /*.......................................................................
7980 * This is the action function which implements the vi-repeat-change
7983 static KT_KEY_FN(gl_vi_repeat_change
)
7985 int status
; /* The return status of the repeated action function */
7988 * Nothing to repeat?
7990 if(!gl
->vi
.repeat
.action
.fn
)
7991 return gl_ring_bell(gl
, 1, NULL
);
7993 * Provide a way for action functions to know whether they are being
7996 gl
->vi
.repeat
.active
= 1;
7998 * Re-run the recorded function.
8000 status
= gl
->vi
.repeat
.action
.fn(gl
, gl
->vi
.repeat
.count
,
8001 gl
->vi
.repeat
.action
.data
);
8003 * Mark the repeat as completed.
8005 gl
->vi
.repeat
.active
= 0;
8007 * Is we are repeating a function that has just switched to input
8008 * mode to allow the user to type, re-enter the text that the user
8009 * previously entered.
8011 if(status
==0 && !gl
->vi
.command
) {
8013 * Make sure that the current line has been saved.
8015 gl_save_for_undo(gl
);
8017 * Repeat a previous insertion or overwrite?
8019 if(gl
->vi
.repeat
.input_curpos
>= 0 &&
8020 gl
->vi
.repeat
.input_curpos
<= gl
->vi
.repeat
.command_curpos
&&
8021 gl
->vi
.repeat
.command_curpos
<= gl
->vi
.undo
.ntotal
) {
8023 * Using the current line which is saved in the undo buffer, plus
8024 * the range of characters therein, as recorded by gl_vi_command_mode(),
8025 * add the characters that the user previously entered, to the input
8028 for(i
=gl
->vi
.repeat
.input_curpos
; i
<gl
->vi
.repeat
.command_curpos
; i
++) {
8029 if(gl_add_char_to_line(gl
, gl
->vi
.undo
.line
[i
]))
8034 * Switch back to command mode, now that the insertion has been repeated.
8036 gl_vi_command_mode(gl
);
8041 /*.......................................................................
8042 * If the cursor is currently over a parenthesis character, return the
8043 * index of its matching parenthesis. If not currently over a parenthesis
8044 * character, return the next close parenthesis character to the right of
8045 * the cursor. If the respective parenthesis character isn't found,
8046 * ring the terminal bell and return -1.
8049 * gl GetLine * The getline resource object.
8051 * return int Either the index of the matching parenthesis,
8052 * or -1 if not found.
8054 static int gl_index_of_matching_paren(GetLine
*gl
)
8058 * List the recognized parentheses, and their matches.
8060 const char *o_paren
= "([{";
8061 const char *c_paren
= ")]}";
8064 * Get the character that is currently under the cursor.
8066 char c
= gl
->line
[gl
->buff_curpos
];
8068 * If the character under the cursor is an open parenthesis, look forward
8069 * for the matching close parenthesis.
8071 if((cptr
=strchr(o_paren
, c
))) {
8072 char match
= c_paren
[cptr
- o_paren
];
8073 int matches_needed
= 1;
8074 for(i
=gl
->buff_curpos
+1; i
<gl
->ntotal
; i
++) {
8075 if(gl
->line
[i
] == c
)
8077 else if(gl
->line
[i
] == match
&& --matches_needed
==0)
8081 * If the character under the cursor is an close parenthesis, look forward
8082 * for the matching open parenthesis.
8084 } else if((cptr
=strchr(c_paren
, c
))) {
8085 char match
= o_paren
[cptr
- c_paren
];
8086 int matches_needed
= 1;
8087 for(i
=gl
->buff_curpos
-1; i
>=0; i
--) {
8088 if(gl
->line
[i
] == c
)
8090 else if(gl
->line
[i
] == match
&& --matches_needed
==0)
8094 * If not currently over a parenthesis character, search forwards for
8095 * the first close parenthesis (this is what the vi % binding does).
8098 for(i
=gl
->buff_curpos
+1; i
<gl
->ntotal
; i
++)
8099 if(strchr(c_paren
, gl
->line
[i
]) != NULL
)
8105 (void) gl_ring_bell(gl
, 1, NULL
);
8109 /*.......................................................................
8110 * If the cursor is currently over a parenthesis character, this action
8111 * function moves the cursor to its matching parenthesis.
8113 static KT_KEY_FN(gl_find_parenthesis
)
8115 int curpos
= gl_index_of_matching_paren(gl
);
8117 return gl_place_cursor(gl
, curpos
);
8121 /*.......................................................................
8122 * Handle the receipt of the potential start of a new key-sequence from
8126 * gl GetLine * The resource object of this library.
8127 * first_char char The first character of the sequence.
8129 * return int 0 - OK.
8132 static int gl_interpret_char(GetLine
*gl
, char first_char
)
8134 char keyseq
[GL_KEY_MAX
+1]; /* A special key sequence being read */
8135 int nkey
=0; /* The number of characters in the key sequence */
8136 int count
; /* The repeat count of an action function */
8137 int ret
; /* The return value of an action function */
8140 * Get the first character.
8142 char c
= first_char
;
8144 * If editing is disabled, just add newly entered characters to the
8145 * input line buffer, and watch for the end of the line.
8147 if(gl
->editor
== GL_NO_EDITOR
) {
8148 gl_discard_chars(gl
, 1);
8149 if(gl
->ntotal
>= gl
->linelen
)
8151 if(c
== '\n' || c
== '\r')
8152 return gl_newline(gl
, 1, NULL
);
8153 gl_buffer_char(gl
, c
, gl
->ntotal
);
8157 * If the user is in the process of specifying a repeat count and the
8158 * new character is a digit, increment the repeat count accordingly.
8160 if(gl
->number
>= 0 && isdigit((int)(unsigned char) c
)) {
8161 gl_discard_chars(gl
, 1);
8162 return gl_digit_argument(gl
, c
, NULL
);
8164 * In vi command mode, all key-sequences entered need to be
8165 * either implicitly or explicitly prefixed with an escape character.
8167 } else if(gl
->vi
.command
&& c
!= GL_ESC_CHAR
) {
8168 keyseq
[nkey
++] = GL_ESC_CHAR
;
8170 * If the first character of the sequence is a printable character,
8171 * then to avoid confusion with the special "up", "down", "left"
8172 * or "right" cursor key bindings, we need to prefix the
8173 * printable character with a backslash escape before looking it up.
8175 } else if(!IS_META_CHAR(c
) && !IS_CTRL_CHAR(c
)) {
8176 keyseq
[nkey
++] = '\\';
8179 * Compose a potentially multiple key-sequence in gl->keyseq.
8181 while(nkey
< GL_KEY_MAX
) {
8182 KtAction
*action
; /* An action function */
8183 KeySym
*keysym
; /* The symbol-table entry of a key-sequence */
8184 int nsym
; /* The number of ambiguously matching key-sequences */
8186 * If the character is an unprintable meta character, split it
8187 * into two characters, an escape character and the character
8188 * that was modified by the meta key.
8190 if(IS_META_CHAR(c
)) {
8191 keyseq
[nkey
++] = GL_ESC_CHAR
;
8192 c
= META_TO_CHAR(c
);
8196 * Append the latest character to the key sequence.
8200 * When doing vi-style editing, an escape at the beginning of any binding
8201 * switches to command mode.
8203 if(keyseq
[0] == GL_ESC_CHAR
&& !gl
->vi
.command
)
8204 gl_vi_command_mode(gl
);
8206 * Lookup the key sequence.
8208 switch(_kt_lookup_keybinding(gl
->bindings
, keyseq
, nkey
, &keysym
, &nsym
)) {
8209 case KT_EXACT_MATCH
:
8211 * Get the matching action function.
8213 action
= keysym
->actions
+ keysym
->binder
;
8215 * Get the repeat count, passing the last keystroke if executing the
8216 * digit-argument action.
8218 if(action
->fn
== gl_digit_argument
) {
8221 count
= gl
->number
>= 0 ? gl
->number
: 1;
8224 * Record the function that is being invoked.
8226 gl
->current_action
= *action
;
8227 gl
->current_count
= count
;
8229 * Mark the current line as not yet preserved for use by the vi undo command.
8231 gl
->vi
.undo
.saved
= 0;
8232 gl
->vi
.repeat
.saved
= 0;
8234 * Execute the action function. Note the action function can tell
8235 * whether the provided repeat count was defaulted or specified
8236 * explicitly by looking at whether gl->number is -1 or not. If
8237 * it is negative, then no repeat count was specified by the user.
8239 ret
= action
->fn(gl
, count
, action
->data
);
8241 * In server mode, the action will return immediately if it tries to
8242 * read input from the terminal, and no input is currently available.
8243 * If this happens, abort. Note that gl_get_input_line() will rewind
8244 * the read-ahead buffer to allow the next call to redo the function
8247 if(gl
->rtn_status
== GLR_BLOCKED
&& gl
->pending_io
==GLP_READ
)
8250 * Discard the now processed characters from the key sequence buffer.
8252 gl_discard_chars(gl
, gl
->nread
);
8254 * If the latest action function wasn't a history action, cancel any
8255 * current history search.
8257 if(gl
->last_search
!= gl
->keyseq_count
)
8258 _glh_cancel_search(gl
->glh
);
8260 * Reset the repeat count after running action functions.
8262 if(action
->fn
!= gl_digit_argument
)
8266 case KT_AMBIG_MATCH
: /* Ambiguous match - so read the next character */
8267 if(gl_read_terminal(gl
, 1, &c
))
8272 * If the first character looked like it might be a prefix of a key-sequence
8273 * but it turned out not to be, ring the bell to tell the user that it
8274 * wasn't recognised.
8276 if(keyseq
[0] != '\\' && keyseq
[0] != '\t') {
8277 gl_ring_bell(gl
, 1, NULL
);
8280 * The user typed a single printable character that doesn't match
8281 * the start of any keysequence, so add it to the line in accordance
8282 * with the current repeat count.
8284 count
= gl
->number
>= 0 ? gl
->number
: 1;
8285 for(i
=0; i
<count
; i
++)
8286 gl_add_char_to_line(gl
, first_char
);
8289 gl_discard_chars(gl
, 1);
8290 _glh_cancel_search(gl
->glh
);
8294 gl_ring_bell(gl
, 1, NULL
);
8295 gl_discard_chars(gl
, gl
->nread
);
8296 _glh_cancel_search(gl
->glh
);
8302 * If the key sequence was too long to match, ring the bell, then
8303 * discard the first character, so that the next attempt to match a
8304 * key-sequence continues with the next key press. In practice this
8305 * shouldn't happen, since one isn't allowed to bind action functions
8306 * to keysequences that are longer than GL_KEY_MAX.
8308 gl_ring_bell(gl
, 1, NULL
);
8309 gl_discard_chars(gl
, 1);
8313 /*.......................................................................
8314 * Configure the application and/or user-specific behavior of
8317 * Note that calling this function between calling new_GetLine() and
8318 * the first call to gl_get_line(), disables the otherwise automatic
8319 * reading of ~/.teclarc on the first call to gl_get_line().
8322 * gl GetLine * The resource object of this library.
8323 * app_string const char * Either NULL, or a string containing one
8324 * or more .teclarc command lines, separated
8325 * by newline characters. This can be used to
8326 * establish an application-specific
8327 * configuration, without the need for an external
8328 * file. This is particularly useful in embedded
8329 * environments where there is no filesystem.
8330 * app_file const char * Either NULL, or the pathname of an
8331 * application-specific .teclarc file. The
8332 * contents of this file, if provided, are
8333 * read after the contents of app_string[].
8334 * user_file const char * Either NULL, or the pathname of a
8335 * user-specific .teclarc file. Except in
8336 * embedded applications, this should
8337 * usually be "~/.teclarc".
8339 * return int 0 - OK.
8340 * 1 - Bad argument(s).
8342 int gl_configure_getline(GetLine
*gl
, const char *app_string
,
8343 const char *app_file
, const char *user_file
)
8345 sigset_t oldset
; /* The signals that were blocked on entry to this function */
8346 int status
; /* The return status of _gl_configure_getline() */
8348 * Check the arguments.
8355 * Block all signals.
8357 if(gl_mask_signals(gl
, &oldset
))
8360 * Execute the private body of the function while signals are blocked.
8362 status
= _gl_configure_getline(gl
, app_string
, app_file
, user_file
);
8364 * Restore the process signal mask.
8366 gl_unmask_signals(gl
, &oldset
);
8370 /*.......................................................................
8371 * This is the private body of the gl_configure_getline() function. It
8372 * assumes that the caller has checked its arguments and blocked the
8373 * delivery of signals.
8375 static int _gl_configure_getline(GetLine
*gl
, const char *app_string
,
8376 const char *app_file
, const char *user_file
)
8379 * Mark getline as having been explicitly configured.
8383 * Start by parsing the configuration string, if provided.
8386 (void) _gl_read_config_string(gl
, app_string
, KTB_NORM
);
8388 * Now parse the application-specific configuration file, if provided.
8391 (void) _gl_read_config_file(gl
, app_file
, KTB_NORM
);
8393 * Finally, parse the user-specific configuration file, if provided.
8396 (void) _gl_read_config_file(gl
, user_file
, KTB_USER
);
8398 * Record the names of the configuration files to allow them to
8399 * be re-read if requested at a later time.
8401 if(gl_record_string(&gl
->app_file
, app_file
) ||
8402 gl_record_string(&gl
->user_file
, user_file
)) {
8404 _err_record_msg(gl
->err
,
8405 "Insufficient memory to record tecla configuration file names",
8412 /*.......................................................................
8413 * Replace a malloc'd string (or NULL), with another malloc'd copy of
8414 * a string (or NULL).
8417 * sptr char ** On input if *sptr!=NULL, *sptr will be
8418 * free'd and *sptr will be set to NULL. Then,
8419 * on output, if string!=NULL a malloc'd copy
8420 * of this string will be assigned to *sptr.
8421 * string const char * The string to be copied, or NULL to simply
8422 * discard any existing string.
8424 * return int 0 - OK.
8425 * 1 - Malloc failure (no error message is generated).
8427 static int gl_record_string(char **sptr
, const char *string
)
8430 * If the original string is the same string, don't do anything.
8432 if(*sptr
== string
|| (*sptr
&& string
&& strcmp(*sptr
, string
)==0))
8435 * Discard any existing cached string.
8442 * Allocate memory for a copy of the specified string.
8445 size_t ssz
= strlen(string
) + 1;
8446 *sptr
= (char *) malloc(ssz
);
8452 strlcpy(*sptr
, string
, ssz
);
8457 #ifndef HIDE_FILE_SYSTEM
8458 /*.......................................................................
8459 * Re-read any application-specific and user-specific files previously
8460 * specified via the gl_configure_getline() function.
8462 static KT_KEY_FN(gl_read_init_files
)
8464 return _gl_configure_getline(gl
, NULL
, gl
->app_file
, gl
->user_file
);
8468 /*.......................................................................
8469 * Save the contents of the history buffer to a given new file.
8472 * gl GetLine * The resource object of this library.
8473 * filename const char * The name of the new file to write to.
8474 * comment const char * Extra information such as timestamps will
8475 * be recorded on a line started with this
8476 * string, the idea being that the file can
8477 * double as a command file. Specify "" if
8479 * max_lines int The maximum number of lines to save, or -1
8480 * to save all of the lines in the history
8483 * return int 0 - OK.
8486 int gl_save_history(GetLine
*gl
, const char *filename
, const char *comment
,
8489 sigset_t oldset
; /* The signals that were blocked on entry to this function */
8490 int status
; /* The return status of _gl_save_history() */
8492 * Check the arguments.
8494 if(!gl
|| !filename
|| !comment
) {
8496 _err_record_msg(gl
->err
, "NULL argument(s)", END_ERR_MSG
);
8501 * Block all signals.
8503 if(gl_mask_signals(gl
, &oldset
))
8506 * Execute the private body of the function while signals are blocked.
8508 status
= _gl_save_history(gl
, filename
, comment
, max_lines
);
8510 * Restore the process signal mask.
8512 gl_unmask_signals(gl
, &oldset
);
8516 /*.......................................................................
8517 * This is the private body of the gl_save_history() function. It
8518 * assumes that the caller has checked its arguments and blocked the
8519 * delivery of signals.
8521 static int _gl_save_history(GetLine
*gl
, const char *filename
,
8522 const char *comment
, int max_lines
)
8525 * If filesystem access is to be excluded, then history files can't
8528 #ifdef WITHOUT_FILE_SYSTEM
8529 _err_record_msg(gl
->err
, "Can't save history without filesystem access",
8534 FileExpansion
*expansion
; /* The expansion of the filename */
8536 * Expand the filename.
8538 expansion
= ef_expand_file(gl
->ef
, filename
, -1);
8540 gl_print_info(gl
, "Unable to expand ", filename
, " (",
8541 ef_last_error(gl
->ef
), ").", GL_END_INFO
);
8545 * Attempt to save to the specified file.
8547 if(_glh_save_history(gl
->glh
, expansion
->files
[0], comment
, max_lines
)) {
8548 _err_record_msg(gl
->err
, _glh_last_error(gl
->glh
), END_ERR_MSG
);
8555 /*.......................................................................
8556 * Restore the contents of the history buffer from a given new file.
8559 * gl GetLine * The resource object of this library.
8560 * filename const char * The name of the new file to write to.
8561 * comment const char * This must be the same string that was
8562 * passed to gl_save_history() when the file
8565 * return int 0 - OK.
8568 int gl_load_history(GetLine
*gl
, const char *filename
, const char *comment
)
8570 sigset_t oldset
; /* The signals that were blocked on entry to this function */
8571 int status
; /* The return status of _gl_load_history() */
8573 * Check the arguments.
8575 if(!gl
|| !filename
|| !comment
) {
8577 _err_record_msg(gl
->err
, "NULL argument(s)", END_ERR_MSG
);
8582 * Block all signals.
8584 if(gl_mask_signals(gl
, &oldset
))
8587 * Execute the private body of the function while signals are blocked.
8589 status
= _gl_load_history(gl
, filename
, comment
);
8591 * Restore the process signal mask.
8593 gl_unmask_signals(gl
, &oldset
);
8597 /*.......................................................................
8598 * This is the private body of the gl_load_history() function. It
8599 * assumes that the caller has checked its arguments and blocked the
8600 * delivery of signals.
8602 static int _gl_load_history(GetLine
*gl
, const char *filename
,
8603 const char *comment
)
8606 * If filesystem access is to be excluded, then history files can't
8609 #ifdef WITHOUT_FILE_SYSTEM
8610 _err_record_msg(gl
->err
, "Can't load history without filesystem access",
8615 FileExpansion
*expansion
; /* The expansion of the filename */
8617 * Expand the filename.
8619 expansion
= ef_expand_file(gl
->ef
, filename
, -1);
8621 gl_print_info(gl
, "Unable to expand ", filename
, " (",
8622 ef_last_error(gl
->ef
), ").", GL_END_INFO
);
8626 * Attempt to load from the specified file.
8628 if(_glh_load_history(gl
->glh
, expansion
->files
[0], comment
,
8629 gl
->cutbuf
, gl
->linelen
+1)) {
8630 _err_record_msg(gl
->err
, _glh_last_error(gl
->glh
), END_ERR_MSG
);
8631 gl
->cutbuf
[0] = '\0';
8634 gl
->cutbuf
[0] = '\0';
8639 /*.......................................................................
8640 * Where possible, register a function and associated data to be called
8641 * whenever a specified event is seen on a file descriptor.
8644 * gl GetLine * The resource object of the command-line input
8646 * fd int The file descriptor to watch.
8647 * event GlFdEvent The type of activity to watch for.
8648 * callback GlFdEventFn * The function to call when the specified
8649 * event occurs. Setting this to 0 removes
8650 * any existing callback.
8651 * data void * A pointer to arbitrary data to pass to the
8652 * callback function.
8654 * return int 0 - OK.
8655 * 1 - Either gl==NULL, or this facility isn't
8656 * available on the the host system
8657 * (ie. select() isn't available). No
8658 * error message is generated in the latter
8661 int gl_watch_fd(GetLine
*gl
, int fd
, GlFdEvent event
,
8662 GlFdEventFn
*callback
, void *data
)
8664 sigset_t oldset
; /* The signals that were blocked on entry to this function */
8665 int status
; /* The return status of _gl_watch_fd() */
8667 * Check the arguments.
8674 _err_record_msg(gl
->err
, "Error: fd < 0", END_ERR_MSG
);
8679 * Block all signals.
8681 if(gl_mask_signals(gl
, &oldset
))
8684 * Execute the private body of the function while signals are blocked.
8686 status
= _gl_watch_fd(gl
, fd
, event
, callback
, data
);
8688 * Restore the process signal mask.
8690 gl_unmask_signals(gl
, &oldset
);
8694 /*.......................................................................
8695 * This is the private body of the gl_watch_fd() function. It
8696 * assumes that the caller has checked its arguments and blocked the
8697 * delivery of signals.
8699 static int _gl_watch_fd(GetLine
*gl
, int fd
, GlFdEvent event
,
8700 GlFdEventFn
*callback
, void *data
)
8701 #if !defined(HAVE_SELECT)
8702 {return 1;} /* The facility isn't supported on this system */
8705 GlFdNode
*prev
; /* The node that precedes 'node' in gl->fd_nodes */
8706 GlFdNode
*node
; /* The file-descriptor node being checked */
8708 * Search the list of already registered fd activity nodes for the specified
8711 for(prev
=NULL
,node
=gl
->fd_nodes
; node
&& node
->fd
!= fd
;
8712 prev
=node
, node
=node
->next
)
8715 * Hasn't a node been allocated for this fd yet?
8719 * If there is no callback to record, just ignore the call.
8724 * Allocate the new node.
8726 node
= (GlFdNode
*) _new_FreeListNode(gl
->fd_node_mem
);
8729 _err_record_msg(gl
->err
, "Insufficient memory", END_ERR_MSG
);
8733 * Prepend the node to the list.
8735 node
->next
= gl
->fd_nodes
;
8736 gl
->fd_nodes
= node
;
8738 * Initialize the node.
8742 node
->rd
.data
= NULL
;
8743 node
->ur
= node
->wr
= node
->rd
;
8746 * Record the new callback.
8750 node
->rd
.fn
= callback
;
8751 node
->rd
.data
= data
;
8753 FD_SET(fd
, &gl
->rfds
);
8755 FD_CLR(fd
, &gl
->rfds
);
8758 node
->wr
.fn
= callback
;
8759 node
->wr
.data
= data
;
8761 FD_SET(fd
, &gl
->wfds
);
8763 FD_CLR(fd
, &gl
->wfds
);
8766 node
->ur
.fn
= callback
;
8767 node
->ur
.data
= data
;
8769 FD_SET(fd
, &gl
->ufds
);
8771 FD_CLR(fd
, &gl
->ufds
);
8775 * Keep a record of the largest file descriptor being watched.
8780 * If we are deleting an existing callback, also delete the parent
8781 * activity node if no callbacks are registered to the fd anymore.
8784 if(!node
->rd
.fn
&& !node
->wr
.fn
&& !node
->ur
.fn
) {
8786 prev
->next
= node
->next
;
8788 gl
->fd_nodes
= node
->next
;
8789 node
= (GlFdNode
*) _del_FreeListNode(gl
->fd_node_mem
, node
);
8796 /*.......................................................................
8797 * On systems with the select() system call, the gl_inactivity_timeout()
8798 * function provides the option of setting (or cancelling) an
8799 * inactivity timeout. Inactivity, in this case, refers both to
8800 * terminal input received from the user, and to I/O on any file
8801 * descriptors registered by calls to gl_watch_fd(). If at any time,
8802 * no activity is seen for the requested time period, the specified
8803 * timeout callback function is called. On returning, this callback
8804 * returns a code which tells gl_get_line() what to do next. Note that
8805 * each call to gl_inactivity_timeout() replaces any previously installed
8806 * timeout callback, and that specifying a callback of 0, turns off
8807 * inactivity timing.
8809 * Beware that although the timeout argument includes a nano-second
8810 * component, few computer clocks presently have resolutions finer
8811 * than a few milliseconds, so asking for less than a few milliseconds
8812 * is equivalent to zero on a lot of systems.
8815 * gl GetLine * The resource object of the command-line input
8817 * callback GlTimeoutFn * The function to call when the inactivity
8818 * timeout is exceeded. To turn off
8819 * inactivity timeouts altogether, send 0.
8820 * data void * A pointer to arbitrary data to pass to the
8821 * callback function.
8822 * sec unsigned long The number of whole seconds in the timeout.
8823 * nsec unsigned long The fractional number of seconds in the
8824 * timeout, expressed in nano-seconds (see
8825 * the caveat above).
8827 * return int 0 - OK.
8828 * 1 - Either gl==NULL, or this facility isn't
8829 * available on the the host system
8830 * (ie. select() isn't available). No
8831 * error message is generated in the latter
8834 int gl_inactivity_timeout(GetLine
*gl
, GlTimeoutFn
*timeout_fn
, void *data
,
8835 unsigned long sec
, unsigned long nsec
)
8836 #if !defined(HAVE_SELECT)
8837 {return 1;} /* The facility isn't supported on this system */
8840 sigset_t oldset
; /* The signals that were blocked on entry to this function */
8842 * Check the arguments.
8849 * Block all signals.
8851 if(gl_mask_signals(gl
, &oldset
))
8854 * Install a new timeout?
8857 gl
->timer
.dt
.tv_sec
= sec
;
8858 gl
->timer
.dt
.tv_usec
= nsec
/ 1000;
8859 gl
->timer
.fn
= timeout_fn
;
8860 gl
->timer
.data
= data
;
8863 gl
->timer
.data
= NULL
;
8866 * Restore the process signal mask.
8868 gl_unmask_signals(gl
, &oldset
);
8873 /*.......................................................................
8874 * When select() is available, this is a private function of
8875 * gl_read_input() which responds to file-descriptor events registered by
8876 * the caller. Note that it assumes that it is being called from within
8877 * gl_read_input()'s sigsetjump() clause.
8880 * gl GetLine * The resource object of this module.
8881 * fd int The file descriptor to be watched for user input.
8883 * return int 0 - OK.
8884 * 1 - An error occurred.
8886 static int gl_event_handler(GetLine
*gl
, int fd
)
8888 #if !defined(HAVE_SELECT)
8892 * Set up a zero-second timeout.
8894 struct timeval zero
;
8895 zero
.tv_sec
= zero
.tv_usec
= 0;
8897 * If at any time no external callbacks remain, quit the loop return,
8898 * so that we can simply wait in read(). This is designed as an
8899 * optimization for when no callbacks have been registered on entry to
8900 * this function, but since callbacks can delete themselves, it can
8903 while(gl
->fd_nodes
|| gl
->timer
.fn
) {
8904 int nready
; /* The number of file descriptors that are ready for I/O */
8906 * Get the set of descriptors to be watched.
8908 fd_set rfds
= gl
->rfds
;
8909 fd_set wfds
= gl
->wfds
;
8910 fd_set ufds
= gl
->ufds
;
8912 * Get the appropriate timeout.
8914 struct timeval dt
= gl
->timer
.fn
? gl
->timer
.dt
: zero
;
8916 * Add the specified user-input file descriptor to the set that is to
8921 * Unblock the signals that we are watching, while select is blocked
8924 gl_catch_signals(gl
);
8926 * Wait for activity on any of the file descriptors.
8928 nready
= select(gl
->max_fd
+1, &rfds
, &wfds
, &ufds
,
8929 (gl
->timer
.fn
|| gl
->io_mode
==GL_SERVER_MODE
) ? &dt
: NULL
);
8931 * We don't want to do a longjmp in the middle of a callback that
8932 * might be modifying global or heap data, so block all the signals
8933 * that we are trapping before executing callback functions. Note that
8934 * the caller will unblock them again when it needs to, so there is
8935 * no need to undo this before returning.
8937 gl_mask_signals(gl
, NULL
);
8939 * If select() returns but none of the file descriptors are reported
8940 * to have activity, then select() timed out.
8944 * Note that in non-blocking server mode, the inactivity timer is used
8945 * to allow I/O to block for a specified amount of time, so in this
8946 * mode we return the postponed blocked status when an abort is
8949 if(gl_call_timeout_handler(gl
)) {
8951 } else if(gl
->io_mode
== GL_SERVER_MODE
) {
8952 gl_record_status(gl
, GLR_BLOCKED
, BLOCKED_ERRNO
);
8956 * If nready < 0, this means an error occurred.
8958 } else if(nready
< 0) {
8959 if(errno
!= EINTR
) {
8960 gl_record_status(gl
, GLR_ERROR
, errno
);
8964 * If the user-input file descriptor has data available, return.
8966 } else if(FD_ISSET(fd
, &rfds
)) {
8969 * Check for activity on any of the file descriptors registered by the
8970 * calling application, and call the associated callback functions.
8973 GlFdNode
*node
; /* The fd event node being checked */
8975 * Search the list for the file descriptor that caused select() to return.
8977 for(node
=gl
->fd_nodes
; node
; node
=node
->next
) {
8979 * Is there urgent out of band data waiting to be read on fd?
8981 if(node
->ur
.fn
&& FD_ISSET(node
->fd
, &ufds
)) {
8982 if(gl_call_fd_handler(gl
, &node
->ur
, node
->fd
, GLFD_URGENT
))
8984 break; /* The callback may have changed the list of nodes */
8986 * Is the fd readable?
8988 } else if(node
->rd
.fn
&& FD_ISSET(node
->fd
, &rfds
)) {
8989 if(gl_call_fd_handler(gl
, &node
->rd
, node
->fd
, GLFD_READ
))
8991 break; /* The callback may have changed the list of nodes */
8993 * Is the fd writable?
8995 } else if(node
->wr
.fn
&& FD_ISSET(node
->fd
, &wfds
)) {
8996 if(gl_call_fd_handler(gl
, &node
->wr
, node
->fd
, GLFD_WRITE
))
8998 break; /* The callback may have changed the list of nodes */
9003 * Just in case the above event handlers asked for the input line to
9004 * be redrawn, flush any pending output.
9006 if(gl_flush_output(gl
))
9013 #if defined(HAVE_SELECT)
9014 /*.......................................................................
9015 * This is a private function of gl_event_handler(), used to call a
9016 * file-descriptor callback.
9019 * gl GetLine * The resource object of gl_get_line().
9020 * gfh GlFdHandler * The I/O handler.
9021 * fd int The file-descriptor being reported.
9022 * event GlFdEvent The I/O event being reported.
9024 * return int 0 - OK.
9027 static int gl_call_fd_handler(GetLine
*gl
, GlFdHandler
*gfh
, int fd
,
9030 Termios attr
; /* The terminal attributes */
9031 int waserr
= 0; /* True after any error */
9033 * Re-enable conversion of newline characters to carriage-return/linefeed,
9034 * so that the callback can write to the terminal without having to do
9037 if(tcgetattr(gl
->input_fd
, &attr
)) {
9038 _err_record_msg(gl
->err
, "tcgetattr error", END_ERR_MSG
);
9041 attr
.c_oflag
|= OPOST
;
9042 while(tcsetattr(gl
->input_fd
, TCSADRAIN
, &attr
)) {
9043 if(errno
!= EINTR
) {
9044 _err_record_msg(gl
->err
, "tcsetattr error", END_ERR_MSG
);
9049 * Invoke the application's callback function.
9051 switch(gfh
->fn(gl
, gfh
->data
, fd
, event
)) {
9054 gl_record_status(gl
, GLR_FDABORT
, 0);
9058 gl_queue_redisplay(gl
);
9064 * Disable conversion of newline characters to carriage-return/linefeed.
9066 attr
.c_oflag
&= ~(OPOST
);
9067 while(tcsetattr(gl
->input_fd
, TCSADRAIN
, &attr
)) {
9068 if(errno
!= EINTR
) {
9069 _err_record_msg(gl
->err
, "tcsetattr error", END_ERR_MSG
);
9076 /*.......................................................................
9077 * This is a private function of gl_event_handler(), used to call a
9078 * inactivity timer callbacks.
9081 * gl GetLine * The resource object of gl_get_line().
9083 * return int 0 - OK.
9086 static int gl_call_timeout_handler(GetLine
*gl
)
9088 Termios attr
; /* The terminal attributes */
9089 int waserr
= 0; /* True after any error */
9091 * Make sure that there is an inactivity timeout callback.
9096 * Re-enable conversion of newline characters to carriage-return/linefeed,
9097 * so that the callback can write to the terminal without having to do
9100 if(tcgetattr(gl
->input_fd
, &attr
)) {
9101 _err_record_msg(gl
->err
, "tcgetattr error", END_ERR_MSG
);
9104 attr
.c_oflag
|= OPOST
;
9105 while(tcsetattr(gl
->input_fd
, TCSADRAIN
, &attr
)) {
9106 if(errno
!= EINTR
) {
9107 _err_record_msg(gl
->err
, "tcsetattr error", END_ERR_MSG
);
9112 * Invoke the application's callback function.
9114 switch(gl
->timer
.fn(gl
, gl
->timer
.data
)) {
9117 gl_record_status(gl
, GLR_TIMEOUT
, 0);
9121 gl_queue_redisplay(gl
);
9127 * Disable conversion of newline characters to carriage-return/linefeed.
9129 attr
.c_oflag
&= ~(OPOST
);
9130 while(tcsetattr(gl
->input_fd
, TCSADRAIN
, &attr
)) {
9131 if(errno
!= EINTR
) {
9132 _err_record_msg(gl
->err
, "tcsetattr error", END_ERR_MSG
);
9138 #endif /* HAVE_SELECT */
9140 /*.......................................................................
9141 * Switch history groups. History groups represent separate history
9142 * lists recorded within a single history buffer. Different groups
9143 * are distinguished by integer identifiers chosen by the calling
9144 * appplicaton. Initially new_GetLine() sets the group identifier to
9145 * 0. Whenever a new line is appended to the history list, the current
9146 * group identifier is recorded with it, and history lookups only
9147 * consider lines marked with the current group identifier.
9150 * gl GetLine * The resource object of gl_get_line().
9151 * id unsigned The new history group identifier.
9153 * return int 0 - OK.
9156 int gl_group_history(GetLine
*gl
, unsigned id
)
9158 sigset_t oldset
; /* The signals that were blocked on entry to this function */
9159 int status
; /* The return status of this function */
9161 * Check the arguments.
9168 * Block all signals while we install the new configuration.
9170 if(gl_mask_signals(gl
, &oldset
))
9173 * If the group isn't being changed, do nothing.
9175 if(_glh_get_group(gl
->glh
) == id
) {
9178 * Establish the new group.
9180 } else if(_glh_set_group(gl
->glh
, id
)) {
9181 _err_record_msg(gl
->err
, _glh_last_error(gl
->glh
), END_ERR_MSG
);
9184 * Prevent history information from the previous group being
9185 * inappropriately used by the next call to gl_get_line().
9188 gl
->preload_history
= 0;
9189 gl
->last_search
= -1;
9193 * Restore the process signal mask.
9195 gl_unmask_signals(gl
, &oldset
);
9199 /*.......................................................................
9200 * Display the contents of the history list.
9203 * gl GetLine * The resource object of gl_get_line().
9204 * fp FILE * The stdio output stream to write to.
9205 * fmt const char * A format string. This containing characters to be
9206 * written verbatim, plus any of the following
9207 * format directives:
9208 * %D - The date, formatted like 2001-11-20
9209 * %T - The time of day, formatted like 23:59:59
9210 * %N - The sequential entry number of the
9211 * line in the history buffer.
9212 * %G - The number of the history group that
9213 * the line belongs to.
9214 * %% - A literal % character.
9215 * %H - The history line itself.
9216 * Note that a '\n' newline character is not
9217 * appended by default.
9218 * all_groups int If true, display history lines from all
9219 * history groups. Otherwise only display
9220 * those of the current history group.
9221 * max_lines int If max_lines is < 0, all available lines
9222 * are displayed. Otherwise only the most
9223 * recent max_lines lines will be displayed.
9225 * return int 0 - OK.
9228 int gl_show_history(GetLine
*gl
, FILE *fp
, const char *fmt
, int all_groups
,
9231 sigset_t oldset
; /* The signals that were blocked on entry to this function */
9232 int status
; /* The return status of this function */
9234 * Check the arguments.
9236 if(!gl
|| !fp
|| !fmt
) {
9238 _err_record_msg(gl
->err
, "NULL argument(s)", END_ERR_MSG
);
9243 * Block all signals.
9245 if(gl_mask_signals(gl
, &oldset
))
9248 * Display the specified history group(s) while signals are blocked.
9250 status
= _glh_show_history(gl
->glh
, _io_write_stdio
, fp
, fmt
, all_groups
,
9251 max_lines
) || fflush(fp
)==EOF
;
9253 _err_record_msg(gl
->err
, _glh_last_error(gl
->glh
), END_ERR_MSG
);
9255 * Restore the process signal mask.
9257 gl_unmask_signals(gl
, &oldset
);
9261 /*.......................................................................
9262 * Update if necessary, and return the current size of the terminal.
9265 * gl GetLine * The resource object of gl_get_line().
9266 * def_ncolumn int If the number of columns in the terminal
9267 * can't be determined, substitute this number.
9268 * def_nline int If the number of lines in the terminal can't
9269 * be determined, substitute this number.
9271 * return GlTerminalSize The current terminal size.
9273 GlTerminalSize
gl_terminal_size(GetLine
*gl
, int def_ncolumn
, int def_nline
)
9275 GlTerminalSize size
; /* The object to be returned */
9276 sigset_t oldset
; /* The signals that were blocked on entry */
9277 /* to this function */
9279 * Block all signals while accessing gl.
9281 gl_mask_signals(gl
, &oldset
);
9283 * Lookup/configure the terminal size.
9285 _gl_terminal_size(gl
, def_ncolumn
, def_nline
, &size
);
9287 * Restore the process signal mask before returning.
9289 gl_unmask_signals(gl
, &oldset
);
9293 /*.......................................................................
9294 * This is the private body of the gl_terminal_size() function. It
9295 * assumes that the caller has checked its arguments and blocked the
9296 * delivery of signals.
9298 static void _gl_terminal_size(GetLine
*gl
, int def_ncolumn
, int def_nline
,
9299 GlTerminalSize
*size
)
9301 const char *env
; /* The value of an environment variable */
9302 int n
; /* A number read from env[] */
9304 * Set the number of lines and columns to non-sensical values so that
9305 * we know later if they have been set.
9310 * Are we reading from a terminal?
9314 * Ask the terminal directly if possible.
9316 (void) _gl_update_size(gl
);
9318 * If gl_update_size() couldn't ask the terminal, it will have
9319 * left gl->nrow and gl->ncolumn unchanged. If these values haven't
9320 * been changed from their initial values of zero, we need to find
9321 * a different method to get the terminal size.
9323 * If the number of lines isn't known yet, first see if the
9324 * LINES environment ariable exists and specifies a believable number.
9325 * If this doesn't work, look up the default size in the terminal
9326 * information database.
9329 if((env
= getenv("LINES")) && (n
=atoi(env
)) > 0)
9333 gl
->nline
= tigetnum((char *)"lines");
9334 #elif defined(USE_TERMCAP)
9336 gl
->nline
= tgetnum("li");
9340 * If the number of lines isn't known yet, first see if the COLUMNS
9341 * environment ariable exists and specifies a believable number. If
9342 * this doesn't work, look up the default size in the terminal
9343 * information database.
9345 if(gl
->ncolumn
< 1) {
9346 if((env
= getenv("COLUMNS")) && (n
=atoi(env
)) > 0)
9350 gl
->ncolumn
= tigetnum((char *)"cols");
9351 #elif defined(USE_TERMCAP)
9353 gl
->ncolumn
= tgetnum("co");
9358 * If we still haven't been able to acquire reasonable values, substitute
9359 * the default values specified by the caller.
9362 gl
->nline
= def_nline
;
9363 if(gl
->ncolumn
<= 0)
9364 gl
->ncolumn
= def_ncolumn
;
9366 * Copy the new size into the return value.
9369 size
->nline
= gl
->nline
;
9370 size
->ncolumn
= gl
->ncolumn
;
9375 /*.......................................................................
9376 * Resize or delete the history buffer.
9379 * gl GetLine * The resource object of gl_get_line().
9380 * bufsize size_t The number of bytes in the history buffer, or 0
9381 * to delete the buffer completely.
9383 * return int 0 - OK.
9384 * 1 - Insufficient memory (the previous buffer
9385 * will have been retained). No error message
9386 * will be displayed.
9388 int gl_resize_history(GetLine
*gl
, size_t bufsize
)
9390 sigset_t oldset
; /* The signals that were blocked on entry to this function */
9391 int status
; /* The return status of this function */
9393 * Check the arguments.
9398 * Block all signals while modifying the contents of gl.
9400 if(gl_mask_signals(gl
, &oldset
))
9403 * Perform the resize while signals are blocked.
9405 status
= _glh_resize_history(gl
->glh
, bufsize
);
9407 _err_record_msg(gl
->err
, _glh_last_error(gl
->glh
), END_ERR_MSG
);
9409 * Restore the process signal mask before returning.
9411 gl_unmask_signals(gl
, &oldset
);
9415 /*.......................................................................
9416 * Set an upper limit to the number of lines that can be recorded in the
9417 * history list, or remove a previously specified limit.
9420 * gl GetLine * The resource object of gl_get_line().
9421 * max_lines int The maximum number of lines to allow, or -1 to
9422 * cancel a previous limit and allow as many lines
9423 * as will fit in the current history buffer size.
9425 void gl_limit_history(GetLine
*gl
, int max_lines
)
9428 sigset_t oldset
; /* The signals that were blocked on entry to this block */
9430 * Temporarily block all signals.
9432 gl_mask_signals(gl
, &oldset
);
9434 * Apply the limit while signals are blocked.
9436 _glh_limit_history(gl
->glh
, max_lines
);
9438 * Restore the process signal mask before returning.
9440 gl_unmask_signals(gl
, &oldset
);
9444 /*.......................................................................
9445 * Discard either all historical lines, or just those associated with the
9446 * current history group.
9449 * gl GetLine * The resource object of gl_get_line().
9450 * all_groups int If true, clear all of the history. If false,
9451 * clear only the stored lines associated with the
9452 * currently selected history group.
9454 void gl_clear_history(GetLine
*gl
, int all_groups
)
9457 sigset_t oldset
; /* The signals that were blocked on entry to this block */
9459 * Temporarily block all signals.
9461 gl_mask_signals(gl
, &oldset
);
9463 * Clear the history buffer while signals are blocked.
9465 _glh_clear_history(gl
->glh
, all_groups
);
9467 * Restore the process signal mask before returning.
9469 gl_unmask_signals(gl
, &oldset
);
9473 /*.......................................................................
9474 * Temporarily enable or disable the gl_get_line() history mechanism.
9477 * gl GetLine * The resource object of gl_get_line().
9478 * enable int If true, turn on the history mechanism. If
9479 * false, disable it.
9481 void gl_toggle_history(GetLine
*gl
, int enable
)
9484 sigset_t oldset
; /* The signals that were blocked on entry to this block */
9486 * Temporarily block all signals.
9488 gl_mask_signals(gl
, &oldset
);
9490 * Change the history recording mode while signals are blocked.
9492 _glh_toggle_history(gl
->glh
, enable
);
9494 * Restore the process signal mask before returning.
9496 gl_unmask_signals(gl
, &oldset
);
9500 /*.......................................................................
9501 * Lookup a history line by its sequential number of entry in the
9505 * gl GetLine * The resource object of gl_get_line().
9506 * id unsigned long The identification number of the line to
9507 * be returned, where 0 denotes the first line
9508 * that was entered in the history list, and
9509 * each subsequently added line has a number
9510 * one greater than the previous one. For
9511 * the range of lines currently in the list,
9512 * see the gl_range_of_history() function.
9514 * line GlHistoryLine * A pointer to the variable in which to
9515 * return the details of the line.
9517 * return int 0 - The line is no longer in the history
9518 * list, and *line has not been changed.
9519 * 1 - The requested line can be found in
9520 * *line. Note that line->line is part
9521 * of the history buffer, so a
9522 * private copy should be made if you
9523 * wish to use it after subsequent calls
9524 * to any functions that take *gl as an
9527 int gl_lookup_history(GetLine
*gl
, unsigned long id
, GlHistoryLine
*line
)
9529 sigset_t oldset
; /* The signals that were blocked on entry to this function */
9530 int status
; /* The return status of this function */
9532 * Check the arguments.
9537 * Block all signals while modifying the contents of gl.
9539 if(gl_mask_signals(gl
, &oldset
))
9542 * Perform the lookup while signals are blocked.
9544 status
= _glh_lookup_history(gl
->glh
, (GlhLineID
) id
, &line
->line
,
9545 &line
->group
, &line
->timestamp
);
9547 _err_record_msg(gl
->err
, _glh_last_error(gl
->glh
), END_ERR_MSG
);
9549 * Restore the process signal mask before returning.
9551 gl_unmask_signals(gl
, &oldset
);
9555 /*.......................................................................
9556 * Query the state of the history list. Note that any of the input/output
9557 * pointers can be specified as NULL.
9560 * gl GetLine * The resource object of gl_get_line().
9562 * state GlHistoryState * A pointer to the variable in which to record
9563 * the return values.
9565 void gl_state_of_history(GetLine
*gl
, GlHistoryState
*state
)
9568 sigset_t oldset
; /* The signals that were blocked on entry to this block */
9570 * Temporarily block all signals.
9572 gl_mask_signals(gl
, &oldset
);
9574 * Lookup the status while signals are blocked.
9576 _glh_state_of_history(gl
->glh
, &state
->enabled
, &state
->group
,
9579 * Restore the process signal mask before returning.
9581 gl_unmask_signals(gl
, &oldset
);
9585 /*.......................................................................
9586 * Query the number and range of lines in the history buffer.
9589 * gl GetLine * The resource object of gl_get_line().
9590 * range GlHistoryRange * A pointer to the variable in which to record
9591 * the return values. If range->nline=0, the
9592 * range of lines will be given as 0-0.
9594 void gl_range_of_history(GetLine
*gl
, GlHistoryRange
*range
)
9597 sigset_t oldset
; /* The signals that were blocked on entry to this block */
9599 * Temporarily block all signals.
9601 gl_mask_signals(gl
, &oldset
);
9603 * Lookup the information while signals are blocked.
9605 _glh_range_of_history(gl
->glh
, &range
->oldest
, &range
->newest
,
9608 * Restore the process signal mask before returning.
9610 gl_unmask_signals(gl
, &oldset
);
9614 /*.......................................................................
9615 * Return the size of the history buffer and the amount of the
9616 * buffer that is currently in use.
9619 * gl GetLine * The gl_get_line() resource object.
9621 * GlHistorySize size * A pointer to the variable in which to return
9624 void gl_size_of_history(GetLine
*gl
, GlHistorySize
*size
)
9627 sigset_t oldset
; /* The signals that were blocked on entry to this block */
9629 * Temporarily block all signals.
9631 gl_mask_signals(gl
, &oldset
);
9633 * Lookup the information while signals are blocked.
9635 _glh_size_of_history(gl
->glh
, &size
->size
, &size
->used
);
9637 * Restore the process signal mask before returning.
9639 gl_unmask_signals(gl
, &oldset
);
9643 /*.......................................................................
9644 * This is the action function that lists the contents of the history
9647 static KT_KEY_FN(gl_list_history
)
9652 if(gl_start_newline(gl
, 1))
9655 * List history lines that belong to the current group.
9657 _glh_show_history(gl
->glh
, gl_write_fn
, gl
, "%N %T %H\r\n", 0,
9658 count
<=1 ? -1 : count
);
9660 * Arrange for the input line to be redisplayed.
9662 gl_queue_redisplay(gl
);
9666 /*.......................................................................
9667 * Specify whether text that users type should be displayed or hidden.
9668 * In the latter case, only the prompt is displayed, and the final
9669 * input line is not archived in the history list.
9672 * gl GetLine * The gl_get_line() resource object.
9673 * enable int 0 - Disable echoing.
9674 * 1 - Enable echoing.
9675 * -1 - Just query the mode without changing it.
9677 * return int The echoing disposition that was in effect
9678 * before this function was called:
9679 * 0 - Echoing was disabled.
9680 * 1 - Echoing was enabled.
9682 int gl_echo_mode(GetLine
*gl
, int enable
)
9685 sigset_t oldset
; /* The signals that were blocked on entry to this block */
9686 int was_echoing
; /* The echoing disposition on entry to this function */
9688 * Temporarily block all signals.
9690 gl_mask_signals(gl
, &oldset
);
9692 * Install the new disposition while signals are blocked.
9694 was_echoing
= gl
->echo
;
9698 * Restore the process signal mask before returning.
9700 gl_unmask_signals(gl
, &oldset
);
9702 * Return the original echoing disposition.
9709 /*.......................................................................
9710 * Display the prompt.
9713 * gl GetLine * The resource object of gl_get_line().
9715 * return int 0 - OK.
9718 static int gl_display_prompt(GetLine
*gl
)
9720 const char *pptr
; /* A pointer into gl->prompt[] */
9721 unsigned old_attr
=0; /* The current text display attributes */
9722 unsigned new_attr
=0; /* The requested text display attributes */
9724 * Temporarily switch to echoing output characters.
9726 int kept_echo
= gl
->echo
;
9729 * In case the screen got messed up, send a carriage return to
9730 * put the cursor at the beginning of the current terminal line.
9732 if(gl_print_control_sequence(gl
, 1, gl
->bol
))
9735 * Mark the line as partially displayed.
9739 * Write the prompt, using the currently selected prompt style.
9741 switch(gl
->prompt_style
) {
9742 case GL_LITERAL_PROMPT
:
9743 if(gl_print_string(gl
, gl
->prompt
, '\0'))
9746 case GL_FORMAT_PROMPT
:
9747 for(pptr
=gl
->prompt
; *pptr
; pptr
++) {
9749 * Does the latest character appear to be the start of a directive?
9753 * Check for and act on attribute changing directives.
9757 * Add or remove a text attribute from the new set of attributes.
9759 case 'B': case 'U': case 'S': case 'P': case 'F': case 'V':
9760 case 'b': case 'u': case 's': case 'p': case 'f': case 'v':
9762 case 'B': /* Switch to a bold font */
9763 new_attr
|= GL_TXT_BOLD
;
9765 case 'b': /* Switch to a non-bold font */
9766 new_attr
&= ~GL_TXT_BOLD
;
9768 case 'U': /* Start underlining */
9769 new_attr
|= GL_TXT_UNDERLINE
;
9771 case 'u': /* Stop underlining */
9772 new_attr
&= ~GL_TXT_UNDERLINE
;
9774 case 'S': /* Start highlighting */
9775 new_attr
|= GL_TXT_STANDOUT
;
9777 case 's': /* Stop highlighting */
9778 new_attr
&= ~GL_TXT_STANDOUT
;
9780 case 'P': /* Switch to a pale font */
9781 new_attr
|= GL_TXT_DIM
;
9783 case 'p': /* Switch to a non-pale font */
9784 new_attr
&= ~GL_TXT_DIM
;
9786 case 'F': /* Switch to a flashing font */
9787 new_attr
|= GL_TXT_BLINK
;
9789 case 'f': /* Switch to a steady font */
9790 new_attr
&= ~GL_TXT_BLINK
;
9792 case 'V': /* Switch to reverse video */
9793 new_attr
|= GL_TXT_REVERSE
;
9795 case 'v': /* Switch out of reverse video */
9796 new_attr
&= ~GL_TXT_REVERSE
;
9801 * A literal % is represented by %%. Skip the leading %.
9809 * Many terminals, when asked to turn off a single text attribute, turn
9810 * them all off, so the portable way to turn one off individually is to
9811 * explicitly turn them all off, then specify those that we want from
9814 if(old_attr
& ~new_attr
) {
9815 if(gl_print_control_sequence(gl
, 1, gl
->text_attr_off
))
9820 * Install new text attributes?
9822 if(new_attr
!= old_attr
) {
9823 if(new_attr
& GL_TXT_BOLD
&& !(old_attr
& GL_TXT_BOLD
) &&
9824 gl_print_control_sequence(gl
, 1, gl
->bold
))
9826 if(new_attr
& GL_TXT_UNDERLINE
&& !(old_attr
& GL_TXT_UNDERLINE
) &&
9827 gl_print_control_sequence(gl
, 1, gl
->underline
))
9829 if(new_attr
& GL_TXT_STANDOUT
&& !(old_attr
& GL_TXT_STANDOUT
) &&
9830 gl_print_control_sequence(gl
, 1, gl
->standout
))
9832 if(new_attr
& GL_TXT_DIM
&& !(old_attr
& GL_TXT_DIM
) &&
9833 gl_print_control_sequence(gl
, 1, gl
->dim
))
9835 if(new_attr
& GL_TXT_REVERSE
&& !(old_attr
& GL_TXT_REVERSE
) &&
9836 gl_print_control_sequence(gl
, 1, gl
->reverse
))
9838 if(new_attr
& GL_TXT_BLINK
&& !(old_attr
& GL_TXT_BLINK
) &&
9839 gl_print_control_sequence(gl
, 1, gl
->blink
))
9841 old_attr
= new_attr
;
9844 * Display the latest character.
9846 if(gl_print_char(gl
, *pptr
, pptr
[1]))
9850 * Turn off all text attributes now that we have finished drawing
9853 if(gl_print_control_sequence(gl
, 1, gl
->text_attr_off
))
9858 * Restore the original echo mode.
9860 gl
->echo
= kept_echo
;
9862 * The prompt has now been displayed at least once.
9864 gl
->prompt_changed
= 0;
9868 /*.......................................................................
9869 * This function can be called from gl_get_line() callbacks to have
9870 * the prompt changed when they return. It has no effect if gl_get_line()
9871 * is not currently being invoked.
9874 * gl GetLine * The resource object of gl_get_line().
9875 * prompt const char * The new prompt.
9877 void gl_replace_prompt(GetLine
*gl
, const char *prompt
)
9880 sigset_t oldset
; /* The signals that were blocked on entry to this block */
9882 * Temporarily block all signals.
9884 gl_mask_signals(gl
, &oldset
);
9886 * Replace the prompt.
9888 _gl_replace_prompt(gl
, prompt
);
9890 * Restore the process signal mask before returning.
9892 gl_unmask_signals(gl
, &oldset
);
9896 /*.......................................................................
9897 * This is the private body of the gl_replace_prompt() function. It
9898 * assumes that the caller has checked its arguments and blocked the
9899 * delivery of signals.
9901 static void _gl_replace_prompt(GetLine
*gl
, const char *prompt
)
9906 * Substitute an empty prompt?
9911 * Gaurd against aliasing between prompt and gl->prompt.
9913 if(gl
->prompt
!= prompt
) {
9915 * Get the length of the new prompt string.
9917 size_t slen
= strlen(prompt
);
9919 * If needed, allocate a new buffer for the prompt string.
9921 size
= sizeof(char) * (slen
+ 1);
9922 if(!gl
->prompt
|| slen
> strlen(gl
->prompt
)) {
9923 char *new_prompt
= gl
->prompt
? realloc(gl
->prompt
, size
) : malloc(size
);
9926 gl
->prompt
= new_prompt
;
9929 * Make a copy of the new prompt.
9931 strlcpy(gl
->prompt
, prompt
, size
);
9934 * Record the statistics of the new prompt.
9936 gl
->prompt_len
= gl_displayed_prompt_width(gl
);
9937 gl
->prompt_changed
= 1;
9938 gl_queue_redisplay(gl
);
9942 /*.......................................................................
9943 * Work out the length of the current prompt on the terminal, according
9944 * to the current prompt formatting style.
9947 * gl GetLine * The resource object of this library.
9949 * return int The number of displayed characters.
9951 static int gl_displayed_prompt_width(GetLine
*gl
)
9953 int slen
=0; /* The displayed number of characters */
9954 const char *pptr
; /* A pointer into prompt[] */
9956 * The length differs according to the prompt display style.
9958 switch(gl
->prompt_style
) {
9959 case GL_LITERAL_PROMPT
:
9960 return gl_displayed_string_width(gl
, gl
->prompt
, -1, 0);
9962 case GL_FORMAT_PROMPT
:
9964 * Add up the length of the displayed string, while filtering out
9965 * attribute directives.
9967 for(pptr
=gl
->prompt
; *pptr
; pptr
++) {
9969 * Does the latest character appear to be the start of a directive?
9973 * Check for and skip attribute changing directives.
9976 case 'B': case 'b': case 'U': case 'u': case 'S': case 's':
9980 * A literal % is represented by %%. Skip the leading %.
9987 slen
+= gl_displayed_char_width(gl
, *pptr
, slen
);
9994 /*.......................................................................
9995 * Specify whether to heed text attribute directives within prompt
9999 * gl GetLine * The resource object of gl_get_line().
10000 * style GlPromptStyle The style of prompt (see the definition of
10001 * GlPromptStyle in libtecla.h for details).
10003 void gl_prompt_style(GetLine
*gl
, GlPromptStyle style
)
10006 sigset_t oldset
; /* The signals that were blocked on entry to this block */
10008 * Temporarily block all signals.
10010 gl_mask_signals(gl
, &oldset
);
10012 * Install the new style in gl while signals are blocked.
10014 if(style
!= gl
->prompt_style
) {
10015 gl
->prompt_style
= style
;
10016 gl
->prompt_len
= gl_displayed_prompt_width(gl
);
10017 gl
->prompt_changed
= 1;
10018 gl_queue_redisplay(gl
);
10021 * Restore the process signal mask before returning.
10023 gl_unmask_signals(gl
, &oldset
);
10027 /*.......................................................................
10028 * Tell gl_get_line() how to respond to a given signal. This can be used
10029 * both to override the default responses to signals that gl_get_line()
10030 * normally catches and to add new signals to the list that are to be
10034 * gl GetLine * The resource object of gl_get_line().
10035 * signo int The number of the signal to be caught.
10036 * flags unsigned A bitwise union of GlSignalFlags enumerators.
10037 * after GlAfterSignal What to do after the application's signal
10038 * handler has been called.
10039 * errno_value int The value to set errno to.
10041 * return int 0 - OK.
10044 int gl_trap_signal(GetLine
*gl
, int signo
, unsigned flags
,
10045 GlAfterSignal after
, int errno_value
)
10047 sigset_t oldset
; /* The signals that were blocked on entry to this function */
10048 int status
; /* The return status of this function */
10050 * Check the arguments.
10057 * Block all signals while modifying the contents of gl.
10059 if(gl_mask_signals(gl
, &oldset
))
10062 * Perform the modification while signals are blocked.
10064 status
= _gl_trap_signal(gl
, signo
, flags
, after
, errno_value
);
10066 * Restore the process signal mask before returning.
10068 gl_unmask_signals(gl
, &oldset
);
10072 /*.......................................................................
10073 * This is the private body of the gl_trap_signal() function. It
10074 * assumes that the caller has checked its arguments and blocked the
10075 * delivery of signals.
10077 static int _gl_trap_signal(GetLine
*gl
, int signo
, unsigned flags
,
10078 GlAfterSignal after
, int errno_value
)
10082 * Complain if an attempt is made to trap untrappable signals.
10083 * These would otherwise cause errors later in gl_mask_signals().
10096 * See if the signal has already been registered.
10098 for(sig
=gl
->sigs
; sig
&& sig
->signo
!= signo
; sig
= sig
->next
)
10101 * If the signal hasn't already been registered, allocate a node for
10105 sig
= (GlSignalNode
*) _new_FreeListNode(gl
->sig_mem
);
10109 * Add the new node to the head of the list.
10111 sig
->next
= gl
->sigs
;
10114 * Record the signal number.
10116 sig
->signo
= signo
;
10118 * Create a signal set that includes just this signal.
10120 sigemptyset(&sig
->proc_mask
);
10121 if(sigaddset(&sig
->proc_mask
, signo
) == -1) {
10122 _err_record_msg(gl
->err
, "sigaddset error", END_ERR_MSG
);
10123 sig
= (GlSignalNode
*) _del_FreeListNode(gl
->sig_mem
, sig
);
10127 * Add the signal to the bit-mask of signals being trapped.
10129 sigaddset(&gl
->all_signal_set
, signo
);
10132 * Record the new signal attributes.
10134 sig
->flags
= flags
;
10135 sig
->after
= after
;
10136 sig
->errno_value
= errno_value
;
10140 /*.......................................................................
10141 * Remove a signal from the list of signals that gl_get_line() traps.
10144 * gl GetLine * The resource object of gl_get_line().
10145 * signo int The number of the signal to be ignored.
10147 * return int 0 - OK.
10150 int gl_ignore_signal(GetLine
*gl
, int signo
)
10152 GlSignalNode
*sig
; /* The gl->sigs list node of the specified signal */
10153 GlSignalNode
*prev
; /* The node that precedes sig in the list */
10154 sigset_t oldset
; /* The signals that were blocked on entry to this */
10157 * Check the arguments.
10164 * Block all signals while modifying the contents of gl.
10166 if(gl_mask_signals(gl
, &oldset
))
10169 * Find the node of the gl->sigs list which records the disposition
10170 * of the specified signal.
10172 for(prev
=NULL
,sig
=gl
->sigs
; sig
&& sig
->signo
!= signo
;
10173 prev
=sig
,sig
=sig
->next
)
10177 * Remove the node from the list.
10180 prev
->next
= sig
->next
;
10182 gl
->sigs
= sig
->next
;
10184 * Return the node to the freelist.
10186 sig
= (GlSignalNode
*) _del_FreeListNode(gl
->sig_mem
, sig
);
10188 * Remove the signal from the bit-mask union of signals being trapped.
10190 sigdelset(&gl
->all_signal_set
, signo
);
10193 * Restore the process signal mask before returning.
10195 gl_unmask_signals(gl
, &oldset
);
10199 /*.......................................................................
10200 * This function is called when an input line has been completed. It
10201 * appends the specified newline character, terminates the line,
10202 * records the line in the history buffer if appropriate, and positions
10203 * the terminal cursor at the start of the next line.
10206 * gl GetLine * The resource object of gl_get_line().
10207 * newline_char int The newline character to add to the end
10210 * return int 0 - OK.
10213 static int gl_line_ended(GetLine
*gl
, int newline_char
)
10216 * If the newline character is printable, display it at the end of
10217 * the line, and add it to the input line buffer.
10219 if(isprint((int)(unsigned char) newline_char
)) {
10220 if(gl_end_of_line(gl
, 1, NULL
) || gl_add_char_to_line(gl
, newline_char
))
10224 * Otherwise just append a newline character to the input line buffer.
10226 newline_char
= '\n';
10227 gl_buffer_char(gl
, newline_char
, gl
->ntotal
);
10230 * Add the line to the history buffer if it was entered with a
10231 * newline character.
10233 if(gl
->echo
&& gl
->automatic_history
&& newline_char
=='\n')
10234 (void) _gl_append_history(gl
, gl
->line
);
10236 * Except when depending on the system-provided line editing, start a new
10237 * line after the end of the line that has just been entered.
10239 if(gl
->editor
!= GL_NO_EDITOR
&& gl_start_newline(gl
, 1))
10242 * Record the successful return status.
10244 gl_record_status(gl
, GLR_NEWLINE
, 0);
10246 * Attempt to flush any pending output.
10248 (void) gl_flush_output(gl
);
10250 * The next call to gl_get_line() will write the prompt for a new line
10251 * (or continue the above flush if incomplete), so if we manage to
10252 * flush the terminal now, report that we are waiting to write to the
10255 gl
->pending_io
= GLP_WRITE
;
10259 /*.......................................................................
10260 * Return the last signal that was caught by the most recent call to
10261 * gl_get_line(), or -1 if no signals were caught. This is useful if
10262 * gl_get_line() returns errno=EINTR and you need to find out what signal
10263 * caused it to abort.
10266 * gl GetLine * The resource object of gl_get_line().
10268 * return int The last signal caught by the most recent
10269 * call to gl_get_line(), or -1 if no signals
10272 int gl_last_signal(GetLine
*gl
)
10274 int signo
= -1; /* The requested signal number */
10276 sigset_t oldset
; /* The signals that were blocked on entry to this block */
10278 * Temporarily block all signals.
10280 gl_mask_signals(gl
, &oldset
);
10282 * Access gl now that signals are blocked.
10284 signo
= gl
->last_signal
;
10286 * Restore the process signal mask before returning.
10288 gl_unmask_signals(gl
, &oldset
);
10293 /*.......................................................................
10294 * Prepare to edit a new line.
10297 * gl GetLine * The resource object of this library.
10298 * prompt char * The prompt to prefix the line with, or NULL to
10299 * use the same prompt that was used by the previous
10301 * start_line char * The initial contents of the input line, or NULL
10302 * if it should start out empty.
10303 * start_pos int If start_line isn't NULL, this specifies the
10304 * index of the character over which the cursor
10305 * should initially be positioned within the line.
10306 * If you just want it to follow the last character
10307 * of the line, send -1.
10309 * return int 0 - OK.
10312 static int gl_present_line(GetLine
*gl
, const char *prompt
,
10313 const char *start_line
, int start_pos
)
10316 * Reset the properties of the line.
10318 gl_reset_input_line(gl
);
10320 * Record the new prompt and its displayed width.
10323 _gl_replace_prompt(gl
, prompt
);
10325 * Reset the history search pointers.
10327 if(_glh_cancel_search(gl
->glh
)) {
10328 _err_record_msg(gl
->err
, _glh_last_error(gl
->glh
), END_ERR_MSG
);
10332 * If the previous line was entered via the repeat-history action,
10333 * preload the specified history line.
10335 if(gl
->preload_history
) {
10336 gl
->preload_history
= 0;
10337 if(gl
->preload_id
) {
10338 if(_glh_recall_line(gl
->glh
, gl
->preload_id
, gl
->line
, gl
->linelen
+1)) {
10339 gl_update_buffer(gl
); /* Compute gl->ntotal etc.. */
10340 gl
->buff_curpos
= gl
->ntotal
;
10342 gl_truncate_buffer(gl
, 0);
10344 gl
->preload_id
= 0;
10347 * Present a specified initial line?
10349 } else if(start_line
) {
10350 char *cptr
; /* A pointer into gl->line[] */
10352 * Measure the length of the starting line.
10354 int start_len
= strlen(start_line
);
10356 * If the length of the line is greater than the available space,
10359 if(start_len
> gl
->linelen
)
10360 start_len
= gl
->linelen
;
10362 * Load the line into the buffer.
10364 if(start_line
!= gl
->line
)
10365 gl_buffer_string(gl
, start_line
, start_len
, 0);
10367 * Strip off any trailing newline and carriage return characters.
10369 for(cptr
=gl
->line
+ gl
->ntotal
- 1; cptr
>= gl
->line
&&
10370 (*cptr
=='\n' || *cptr
=='\r'); cptr
--,gl
->ntotal
--)
10372 gl_truncate_buffer(gl
, gl
->ntotal
< 0 ? 0 : gl
->ntotal
);
10374 * Where should the cursor be placed within the line?
10376 if(start_pos
< 0 || start_pos
> gl
->ntotal
) {
10377 if(gl_place_cursor(gl
, gl
->ntotal
))
10380 if(gl_place_cursor(gl
, start_pos
))
10384 * Clear the input line?
10387 gl_truncate_buffer(gl
, 0);
10390 * Arrange for the line to be displayed by gl_flush_output().
10392 gl_queue_redisplay(gl
);
10394 * Update the display.
10396 return gl_flush_output(gl
);
10399 /*.......................................................................
10400 * Reset all line input parameters for a new input line.
10403 * gl GetLine * The line editor resource object.
10405 static void gl_reset_input_line(GetLine
*gl
)
10408 gl
->line
[0] = '\0';
10409 gl
->buff_curpos
= 0;
10410 gl
->term_curpos
= 0;
10412 gl
->insert_curpos
= 0;
10420 gl
->vi
.command
= 0;
10421 gl
->vi
.undo
.line
[0] = '\0';
10422 gl
->vi
.undo
.ntotal
= 0;
10423 gl
->vi
.undo
.buff_curpos
= 0;
10424 gl
->vi
.repeat
.action
.fn
= 0;
10425 gl
->vi
.repeat
.action
.data
= 0;
10426 gl
->last_signal
= -1;
10429 /*.......................................................................
10430 * Print an informational message to the terminal, after starting a new
10434 * gl GetLine * The line editor resource object.
10435 * ... const char * Zero or more strings to be printed.
10436 * ... void * The last argument must always be GL_END_INFO.
10438 * return int 0 - OK.
10441 static int gl_print_info(GetLine
*gl
, ...)
10443 va_list ap
; /* The variable argument list */
10444 const char *s
; /* The string being printed */
10445 int waserr
= 0; /* True after an error */
10447 * Only display output when echoing is on.
10451 * Skip to the start of the next empty line before displaying the message.
10453 if(gl_start_newline(gl
, 1))
10456 * Display the list of provided messages.
10459 while(!waserr
&& (s
= va_arg(ap
, const char *)) != GL_END_INFO
)
10460 waserr
= gl_print_raw_string(gl
, 1, s
, -1);
10465 waserr
= waserr
|| gl_print_raw_string(gl
, 1, "\n\r", -1);
10467 * Arrange for the input line to be redrawn.
10469 gl_queue_redisplay(gl
);
10474 /*.......................................................................
10475 * Go to the start of the next empty line, ready to output miscellaneous
10476 * text to the screen.
10478 * Note that when async-signal safety is required, the 'buffered'
10479 * argument must be 0.
10482 * gl GetLine * The line editor resource object.
10483 * buffered int If true, used buffered I/O when writing to
10484 * the terminal. Otherwise use async-signal-safe
10487 * return int 0 - OK.
10490 static int gl_start_newline(GetLine
*gl
, int buffered
)
10492 int waserr
= 0; /* True after any I/O error */
10494 * Move the cursor to the start of the terminal line that follows the
10495 * last line of the partially enterred line. In order that this
10496 * function remain async-signal safe when write_fn is signal safe, we
10497 * can't call our normal output functions, since they call tputs(),
10498 * who's signal saftey isn't defined. Fortunately, we can simply use
10499 * \r and \n to move the cursor to the right place.
10501 if(gl
->displayed
) { /* Is an input line currently displayed? */
10503 * On which terminal lines are the cursor and the last character of the
10506 int curs_line
= gl
->term_curpos
/ gl
->ncolumn
;
10507 int last_line
= gl
->term_len
/ gl
->ncolumn
;
10509 * Move the cursor to the start of the line that follows the last
10510 * terminal line that is occupied by the input line.
10512 for( ; curs_line
< last_line
+ 1; curs_line
++)
10513 waserr
= waserr
|| gl_print_raw_string(gl
, buffered
, "\n", 1);
10514 waserr
= waserr
|| gl_print_raw_string(gl
, buffered
, "\r", 1);
10516 * Mark the line as no longer displayed.
10518 gl_line_erased(gl
);
10523 /*.......................................................................
10524 * The callback through which all terminal output is routed.
10525 * This simply appends characters to a queue buffer, which is
10526 * subsequently flushed to the output channel by gl_flush_output().
10529 * data void * The pointer to a GetLine line editor resource object
10530 * cast to (void *).
10531 * s const char * The string to be written.
10532 * n int The number of characters to write from s[].
10534 * return int The number of characters written. This will always
10535 * be equal to 'n' unless an error occurs.
10537 static GL_WRITE_FN(gl_write_fn
)
10539 GetLine
*gl
= (GetLine
*) data
;
10540 int ndone
= _glq_append_chars(gl
->cq
, s
, n
, gl
->flush_fn
, gl
);
10542 _err_record_msg(gl
->err
, _glq_last_error(gl
->cq
), END_ERR_MSG
);
10546 /*.......................................................................
10547 * Ask gl_get_line() what caused it to return.
10550 * gl GetLine * The line editor resource object.
10552 * return GlReturnStatus The return status of the last call to
10555 GlReturnStatus
gl_return_status(GetLine
*gl
)
10557 GlReturnStatus rtn_status
= GLR_ERROR
; /* The requested status */
10559 sigset_t oldset
; /* The signals that were blocked on entry to this block */
10561 * Temporarily block all signals.
10563 gl_mask_signals(gl
, &oldset
);
10565 * Access gl while signals are blocked.
10567 rtn_status
= gl
->rtn_status
;
10569 * Restore the process signal mask before returning.
10571 gl_unmask_signals(gl
, &oldset
);
10576 /*.......................................................................
10577 * In non-blocking server-I/O mode, this function should be called
10578 * from the application's external event loop to see what type of
10579 * terminal I/O is being waited for by gl_get_line(), and thus what
10580 * direction of I/O to wait for with select() or poll().
10583 * gl GetLine * The resource object of gl_get_line().
10585 * return GlPendingIO The type of pending I/O being waited for.
10587 GlPendingIO
gl_pending_io(GetLine
*gl
)
10589 GlPendingIO pending_io
= GLP_WRITE
; /* The requested information */
10591 sigset_t oldset
; /* The signals that were blocked on entry to this block */
10593 * Temporarily block all signals.
10595 gl_mask_signals(gl
, &oldset
);
10597 * Access gl while signals are blocked.
10599 pending_io
= gl
->pending_io
;
10601 * Restore the process signal mask before returning.
10603 gl_unmask_signals(gl
, &oldset
);
10608 /*.......................................................................
10609 * In server mode, this function configures the terminal for non-blocking
10610 * raw terminal I/O. In normal I/O mode it does nothing.
10612 * Callers of this function must be careful to trap all signals that
10613 * terminate or suspend the program, and call gl_normal_io()
10614 * from the corresponding signal handlers in order to restore the
10615 * terminal to its original settings before the program is terminated
10616 * or suspended. They should also trap the SIGCONT signal to detect
10617 * when the program resumes, and ensure that its signal handler
10618 * call gl_raw_io() to redisplay the line and resume editing.
10620 * This function is async signal safe.
10623 * gl GetLine * The line editor resource object.
10625 * return int 0 - OK.
10628 int gl_raw_io(GetLine
*gl
)
10630 sigset_t oldset
; /* The signals that were blocked on entry to this function */
10631 int status
; /* The return status of _gl_raw_io() */
10633 * Check the arguments.
10640 * Block all signals.
10642 if(gl_mask_signals(gl
, &oldset
))
10645 * Don't allow applications to switch into raw mode unless in server mode.
10647 if(gl
->io_mode
!= GL_SERVER_MODE
) {
10648 _err_record_msg(gl
->err
, "Can't switch to raw I/O unless in server mode",
10654 * Execute the private body of the function while signals are blocked.
10656 status
= _gl_raw_io(gl
, 1);
10659 * Restore the process signal mask.
10661 gl_unmask_signals(gl
, &oldset
);
10665 /*.......................................................................
10666 * This is the private body of the public function, gl_raw_io().
10667 * It assumes that the caller has checked its arguments and blocked the
10668 * delivery of signals.
10670 * This function is async signal safe.
10672 static int _gl_raw_io(GetLine
*gl
, int redisplay
)
10675 * If we are already in the correct mode, do nothing.
10680 * Switch the terminal to raw mode.
10682 if(gl
->is_term
&& gl_raw_terminal_mode(gl
))
10685 * Switch to non-blocking I/O mode?
10687 if(gl
->io_mode
==GL_SERVER_MODE
&&
10688 (gl_nonblocking_io(gl
, gl
->input_fd
) ||
10689 gl_nonblocking_io(gl
, gl
->output_fd
) ||
10690 (gl
->file_fp
&& gl_nonblocking_io(gl
, fileno(gl
->file_fp
))))) {
10692 gl_restore_terminal_attributes(gl
);
10696 * If an input line is being entered, arrange for it to be
10701 gl_queue_redisplay(gl
);
10706 /*.......................................................................
10707 * Restore the terminal to the state that it had when
10708 * gl_raw_io() was last called. After calling
10709 * gl_raw_io(), this function must be called before
10710 * terminating or suspending the program, and before attempting other
10711 * uses of the terminal from within the program. See gl_raw_io()
10712 * for more details.
10715 * gl GetLine * The line editor resource object.
10717 * return int 0 - OK.
10720 int gl_normal_io(GetLine
*gl
)
10722 sigset_t oldset
; /* The signals that were blocked on entry to this function */
10723 int status
; /* The return status of _gl_normal_io() */
10725 * Check the arguments.
10732 * Block all signals.
10734 if(gl_mask_signals(gl
, &oldset
))
10737 * Execute the private body of the function while signals are blocked.
10739 status
= _gl_normal_io(gl
);
10741 * Restore the process signal mask.
10743 gl_unmask_signals(gl
, &oldset
);
10747 /*.......................................................................
10748 * This is the private body of the public function, gl_normal_io().
10749 * It assumes that the caller has checked its arguments and blocked the
10750 * delivery of signals.
10752 static int _gl_normal_io(GetLine
*gl
)
10755 * If we are already in normal mode, do nothing.
10760 * Postpone subsequent redisplays until after _gl_raw_io(gl, 1)
10765 * Switch back to blocking I/O. Note that this is essential to do
10766 * here, because when using non-blocking I/O, the terminal output
10767 * buffering code can't always make room for new output without calling
10768 * malloc(), and a call to malloc() would mean that this function
10769 * couldn't safely be called from signal handlers.
10771 if(gl
->io_mode
==GL_SERVER_MODE
&&
10772 (gl_blocking_io(gl
, gl
->input_fd
) ||
10773 gl_blocking_io(gl
, gl
->output_fd
) ||
10774 (gl
->file_fp
&& gl_blocking_io(gl
, fileno(gl
->file_fp
)))))
10777 * Move the cursor to the next empty terminal line. Note that
10778 * unbuffered I/O is requested, to ensure that gl_start_newline() be
10779 * async-signal-safe.
10781 if(gl
->is_term
&& gl_start_newline(gl
, 0))
10784 * Switch the terminal to normal mode.
10786 if(gl
->is_term
&& gl_restore_terminal_attributes(gl
)) {
10788 * On error, revert to non-blocking I/O if needed, so that on failure
10789 * we remain in raw mode.
10791 if(gl
->io_mode
==GL_SERVER_MODE
) {
10792 gl_nonblocking_io(gl
, gl
->input_fd
);
10793 gl_nonblocking_io(gl
, gl
->output_fd
);
10795 gl_nonblocking_io(gl
, fileno(gl
->file_fp
));
10802 /*.......................................................................
10803 * This function allows you to install an additional completion
10804 * action, or to change the completion function of an existing
10805 * one. This should be called before the first call to gl_get_line()
10806 * so that the name of the action be defined before the user's
10807 * configuration file is read.
10810 * gl GetLine * The resource object of the command-line input
10812 * data void * This is passed to match_fn() whenever it is
10813 * called. It could, for example, point to a
10814 * symbol table that match_fn() would look up
10816 * match_fn CplMatchFn * The function that will identify the prefix
10817 * to be completed from the input line, and
10818 * report matching symbols.
10819 * list_only int If non-zero, install an action that only lists
10820 * possible completions, rather than attempting
10821 * to perform the completion.
10822 * name const char * The name with which users can refer to the
10823 * binding in tecla configuration files.
10824 * keyseq const char * Either NULL, or a key sequence with which
10825 * to invoke the binding. This should be
10826 * specified in the same manner as key-sequences
10827 * in tecla configuration files (eg. "M-^I").
10829 * return int 0 - OK.
10832 int gl_completion_action(GetLine
*gl
, void *data
, CplMatchFn
*match_fn
,
10833 int list_only
, const char *name
, const char *keyseq
)
10835 sigset_t oldset
; /* The signals that were blocked on entry to this function */
10836 int status
; /* The return status of _gl_completion_action() */
10838 * Check the arguments.
10840 if(!gl
|| !name
|| !match_fn
) {
10845 * Block all signals.
10847 if(gl_mask_signals(gl
, &oldset
))
10850 * Install the new action while signals are blocked.
10852 status
= _gl_completion_action(gl
, data
, match_fn
, list_only
, name
, keyseq
);
10854 * Restore the process signal mask.
10856 gl_unmask_signals(gl
, &oldset
);
10860 /*.......................................................................
10861 * This is the private body of the public function, gl_completion_action().
10862 * It assumes that the caller has checked its arguments and blocked the
10863 * delivery of signals.
10865 static int _gl_completion_action(GetLine
*gl
, void *data
, CplMatchFn
*match_fn
,
10866 int list_only
, const char *name
,
10867 const char *keyseq
)
10869 KtKeyFn
*current_fn
; /* An existing action function */
10870 void *current_data
; /* The action-function callback data */
10872 * Which action function is desired?
10874 KtKeyFn
*action_fn
= list_only
? gl_list_completions
: gl_complete_word
;
10876 * Is there already an action of the specified name?
10878 if(_kt_lookup_action(gl
->bindings
, name
, ¤t_fn
, ¤t_data
) == 0) {
10880 * If the action has the same type as the one being requested,
10881 * simply change the contents of its GlCplCallback callback data.
10883 if(current_fn
== action_fn
) {
10884 GlCplCallback
*cb
= (GlCplCallback
*) current_data
;
10889 _err_record_msg(gl
->err
,
10890 "Illegal attempt to change the type of an existing completion action",
10895 * No existing action has the specified name.
10899 * Allocate a new GlCplCallback callback object.
10901 GlCplCallback
*cb
= (GlCplCallback
*) _new_FreeListNode(gl
->cpl_mem
);
10904 _err_record_msg(gl
->err
, "Insufficient memory to add completion action",
10909 * Record the completion callback data.
10914 * Attempt to register the new action.
10916 if(_kt_set_action(gl
->bindings
, name
, action_fn
, cb
)) {
10917 _err_record_msg(gl
->err
, _kt_last_error(gl
->bindings
), END_ERR_MSG
);
10918 _del_FreeListNode(gl
->cpl_mem
, (void *) cb
);
10923 * Bind the action to a given key-sequence?
10925 if(keyseq
&& _kt_set_keybinding(gl
->bindings
, KTB_NORM
, keyseq
, name
)) {
10926 _err_record_msg(gl
->err
, _kt_last_error(gl
->bindings
), END_ERR_MSG
);
10932 /*.......................................................................
10933 * Register an application-provided function as an action function.
10934 * This should preferably be called before the first call to gl_get_line()
10935 * so that the name of the action becomes defined before the user's
10936 * configuration file is read.
10939 * gl GetLine * The resource object of the command-line input
10941 * data void * Arbitrary application-specific callback
10942 * data to be passed to the callback
10944 * fn GlActionFn * The application-specific function that
10945 * implements the action. This will be invoked
10946 * whenever the user presses any
10947 * key-sequence which is bound to this action.
10948 * name const char * The name with which users can refer to the
10949 * binding in tecla configuration files.
10950 * keyseq const char * The key sequence with which to invoke
10951 * the binding. This should be specified in the
10952 * same manner as key-sequences in tecla
10953 * configuration files (eg. "M-^I").
10955 * return int 0 - OK.
10958 int gl_register_action(GetLine
*gl
, void *data
, GlActionFn
*fn
,
10959 const char *name
, const char *keyseq
)
10961 sigset_t oldset
; /* The signals that were blocked on entry to this function */
10962 int status
; /* The return status of _gl_register_action() */
10964 * Check the arguments.
10966 if(!gl
|| !name
|| !fn
) {
10971 * Block all signals.
10973 if(gl_mask_signals(gl
, &oldset
))
10976 * Install the new action while signals are blocked.
10978 status
= _gl_register_action(gl
, data
, fn
, name
, keyseq
);
10980 * Restore the process signal mask.
10982 gl_unmask_signals(gl
, &oldset
);
10986 /*.......................................................................
10987 * This is the private body of the public function, gl_register_action().
10988 * It assumes that the caller has checked its arguments and blocked the
10989 * delivery of signals.
10991 static int _gl_register_action(GetLine
*gl
, void *data
, GlActionFn
*fn
,
10992 const char *name
, const char *keyseq
)
10994 KtKeyFn
*current_fn
; /* An existing action function */
10995 void *current_data
; /* The action-function callback data */
10997 * Get the action function which actually runs the application-provided
11000 KtKeyFn
*action_fn
= gl_run_external_action
;
11002 * Is there already an action of the specified name?
11004 if(_kt_lookup_action(gl
->bindings
, name
, ¤t_fn
, ¤t_data
) == 0) {
11006 * If the action has the same type as the one being requested,
11007 * simply change the contents of its GlCplCallback callback data.
11009 if(current_fn
== action_fn
) {
11010 GlExternalAction
*a
= (GlExternalAction
*) current_data
;
11015 _err_record_msg(gl
->err
,
11016 "Illegal attempt to change the type of an existing action",
11021 * No existing action has the specified name.
11025 * Allocate a new GlCplCallback callback object.
11027 GlExternalAction
*a
=
11028 (GlExternalAction
*) _new_FreeListNode(gl
->ext_act_mem
);
11031 _err_record_msg(gl
->err
, "Insufficient memory to add completion action",
11036 * Record the completion callback data.
11041 * Attempt to register the new action.
11043 if(_kt_set_action(gl
->bindings
, name
, action_fn
, a
)) {
11044 _err_record_msg(gl
->err
, _kt_last_error(gl
->bindings
), END_ERR_MSG
);
11045 _del_FreeListNode(gl
->cpl_mem
, (void *) a
);
11050 * Bind the action to a given key-sequence?
11052 if(keyseq
&& _kt_set_keybinding(gl
->bindings
, KTB_NORM
, keyseq
, name
)) {
11053 _err_record_msg(gl
->err
, _kt_last_error(gl
->bindings
), END_ERR_MSG
);
11059 /*.......................................................................
11060 * Invoke an action function previously registered by a call to
11061 * gl_register_action().
11063 static KT_KEY_FN(gl_run_external_action
)
11065 GlAfterAction status
; /* The return value of the action function */
11067 * Get the container of the action function and associated callback data.
11069 GlExternalAction
*a
= (GlExternalAction
*) data
;
11071 * Invoke the action function.
11073 status
= a
->fn(gl
, a
->data
, count
, gl
->buff_curpos
, gl
->line
);
11075 * If the callback took us out of raw (possibly non-blocking) input
11076 * mode, restore this mode, and queue a redisplay of the input line.
11078 if(_gl_raw_io(gl
, 1))
11081 * Finally, check to see what the action function wants us to do next.
11086 gl_record_status(gl
, GLR_ERROR
, errno
);
11090 return gl_newline(gl
, 1, NULL
);
11098 /*.......................................................................
11099 * In server-I/O mode the terminal is left in raw mode between calls
11100 * to gl_get_line(), so it is necessary for the application to install
11101 * terminal restoring signal handlers for signals that could terminate
11102 * or suspend the process, plus a terminal reconfiguration handler to
11103 * be called when a process resumption signal is received, and finally
11104 * a handler to be called when a terminal-resize signal is received.
11106 * Since there are many signals that by default terminate or suspend
11107 * processes, and different systems support different sub-sets of
11108 * these signals, this function provides a convenient wrapper around
11109 * sigaction() for assigning the specified handlers to all appropriate
11110 * signals. It also arranges that when any one of these signals is
11111 * being handled, all other catchable signals are blocked. This is
11112 * necessary so that the specified signal handlers can safely call
11113 * gl_raw_io(), gl_normal_io() and gl_update_size() without
11114 * reentrancy issues.
11117 * term_handler void (*)(int) The signal handler to invoke when
11118 * a process terminating signal is
11120 * susp_handler void (*)(int) The signal handler to invoke when
11121 * a process suspending signal is
11123 * cont_handler void (*)(int) The signal handler to invoke when
11124 * a process resumption signal is
11125 * received (ie. SIGCONT).
11126 * size_handler void (*)(int) The signal handler to invoke when
11127 * a terminal-resize signal (ie. SIGWINCH)
11130 * return int 0 - OK.
11133 int gl_tty_signals(void (*term_handler
)(int), void (*susp_handler
)(int),
11134 void (*cont_handler
)(int), void (*size_handler
)(int))
11138 * Search for signals of the specified classes, and assign the
11139 * associated signal handler to them.
11141 for(i
=0; i
<sizeof(gl_signal_list
)/sizeof(gl_signal_list
[0]); i
++) {
11142 const struct GlDefSignal
*sig
= gl_signal_list
+ i
;
11143 if(sig
->attr
& GLSA_SUSP
) {
11144 if(gl_set_tty_signal(sig
->signo
, term_handler
))
11146 } else if(sig
->attr
& GLSA_TERM
) {
11147 if(gl_set_tty_signal(sig
->signo
, susp_handler
))
11149 } else if(sig
->attr
& GLSA_CONT
) {
11150 if(gl_set_tty_signal(sig
->signo
, cont_handler
))
11152 } else if(sig
->attr
& GLSA_SIZE
) {
11153 if(gl_set_tty_signal(sig
->signo
, size_handler
))
11160 /*.......................................................................
11161 * This is a private function of gl_tty_signals(). It installs a given
11162 * signal handler, and arranges that when that signal handler is being
11163 * invoked other signals are blocked. The latter is important to allow
11164 * functions like gl_normal_io(), gl_raw_io() and gl_update_size()
11165 * to be called from signal handlers.
11168 * signo int The signal to be trapped.
11169 * handler void (*)(int) The signal handler to assign to the signal.
11171 static int gl_set_tty_signal(int signo
, void (*handler
)(int))
11173 SigAction act
; /* The signal handler configuation */
11175 * Arrange to block all trappable signals except the one that is being
11176 * assigned (the trapped signal will be blocked automatically by the
11179 gl_list_trappable_signals(&act
.sa_mask
);
11180 sigdelset(&act
.sa_mask
, signo
);
11182 * Assign the signal handler.
11184 act
.sa_handler
= handler
;
11186 * There is only one portable signal handling flag, and it isn't
11187 * relevant to us, so don't specify any flags.
11191 * Register the signal handler.
11193 if(sigaction(signo
, &act
, NULL
))
11198 /*.......................................................................
11199 * Display a left-justified string over multiple terminal lines,
11200 * taking account of the current width of the terminal. Optional
11201 * indentation and an optional prefix string can be specified to be
11202 * displayed at the start of each new terminal line used. Similarly,
11203 * an optional suffix can be specified to be displayed at the end of
11204 * each terminal line. If needed, a single paragraph can be broken
11205 * across multiple calls. Note that literal newlines in the input
11206 * string can be used to force a newline at any point and that you
11207 * should use this feature to explicitly end all paragraphs, including
11208 * at the end of the last string that you write. Note that when a new
11209 * line is started between two words that are separated by spaces,
11210 * those spaces are not output, whereas when a new line is started
11211 * because a newline character was found in the string, only the
11212 * spaces before the newline character are discarded.
11215 * gl GetLine * The resource object of gl_get_line().
11216 * indentation int The number of spaces of indentation to write
11217 * at the beginning of each new terminal line.
11218 * prefix const char * An optional prefix string to write after the
11219 * indentation margin at the start of each new
11220 * terminal line. You can specify NULL if no
11221 * prefix is required.
11222 * suffix const char * An optional suffix string to draw at the end
11223 * of the terminal line. Spaces will be added
11224 * where necessary to ensure that the suffix ends
11225 * in the last column of the terminal line. If
11226 * no suffix is desired, specify NULL.
11227 * fill_char int The padding character to use when indenting
11228 * the line or padding up to the suffix.
11229 * def_width int If the terminal width isn't known, such as when
11230 * writing to a pipe or redirecting to a file,
11231 * this number specifies what width to assume.
11232 * start int The number of characters already written to
11233 * the start of the current terminal line. This
11234 * is primarily used to allow individual
11235 * paragraphs to be written over multiple calls
11236 * to this function, but can also be used to
11237 * allow you to start the first line of a
11238 * paragraph with a different prefix or
11239 * indentation than those specified above.
11240 * string const char * The string to be written.
11242 * return int On error -1 is returned. Otherwise the
11243 * return value is the terminal column index at
11244 * which the cursor was left after writing the
11245 * final word in the string. Successful return
11246 * values can thus be passed verbatim to the
11247 * 'start' arguments of subsequent calls to
11248 * gl_display_text() to allow the printing of a
11249 * paragraph to be broken across multiple calls
11250 * to gl_display_text().
11252 int gl_display_text(GetLine
*gl
, int indentation
, const char *prefix
,
11253 const char *suffix
, int fill_char
,
11254 int def_width
, int start
, const char *string
)
11256 sigset_t oldset
; /* The signals that were blocked on entry to this function */
11257 int status
; /* The return status of _gl_completion_action() */
11259 * Check the arguments?
11261 if(!gl
|| !string
) {
11266 * Block all signals.
11268 if(gl_mask_signals(gl
, &oldset
))
11271 * Display the text while signals are blocked.
11273 status
= _io_display_text(_io_write_stdio
, gl
->output_fp
, indentation
,
11274 prefix
, suffix
, fill_char
,
11275 gl
->ncolumn
> 0 ? gl
->ncolumn
: def_width
,
11278 * Restore the process signal mask.
11280 gl_unmask_signals(gl
, &oldset
);
11284 /*.......................................................................
11285 * Block all of the signals that we are currently trapping.
11288 * gl GetLine * The resource object of gl_get_line().
11290 * oldset sigset_t * The superseded process signal mask
11291 * will be return in *oldset unless oldset is
11294 * return int 0 - OK.
11297 static int gl_mask_signals(GetLine
*gl
, sigset_t
*oldset
)
11300 * Block all signals in all_signal_set, along with any others that are
11301 * already blocked by the application.
11303 if(sigprocmask(SIG_BLOCK
, &gl
->all_signal_set
, oldset
) >= 0) {
11304 gl
->signals_masked
= 1;
11308 * On error attempt to query the current process signal mask, so
11309 * that oldset be the correct process signal mask to restore later
11310 * if the caller of this function ignores the error return value.
11313 (void) sigprocmask(SIG_SETMASK
, NULL
, oldset
);
11314 gl
->signals_masked
= 0;
11318 /*.......................................................................
11319 * Restore a process signal mask that was previously returned via the
11320 * oldset argument of gl_mask_signals().
11323 * gl GetLine * The resource object of gl_get_line().
11325 * oldset sigset_t * The process signal mask to be restored.
11327 * return int 0 - OK.
11330 static int gl_unmask_signals(GetLine
*gl
, sigset_t
*oldset
)
11332 gl
->signals_masked
= 0;
11333 return sigprocmask(SIG_SETMASK
, oldset
, NULL
) < 0;
11336 /*.......................................................................
11337 * Arrange to temporarily catch the signals marked in gl->use_signal_set.
11340 * gl GetLine * The resource object of gl_get_line().
11342 * return int 0 - OK.
11345 static int gl_catch_signals(GetLine
*gl
)
11347 return sigprocmask(SIG_UNBLOCK
, &gl
->use_signal_set
, NULL
) < 0;
11350 /*.......................................................................
11351 * Select the I/O mode to be used by gl_get_line().
11354 * gl GetLine * The resource object of gl_get_line().
11355 * mode GlIOMode The I/O mode to establish.
11357 * return int 0 - OK.
11360 int gl_io_mode(GetLine
*gl
, GlIOMode mode
)
11362 sigset_t oldset
; /* The signals that were blocked on entry to this function */
11363 int status
; /* The return status of _gl_io_mode() */
11365 * Check the arguments.
11372 * Check that the requested mode is known.
11375 case GL_NORMAL_MODE
:
11376 case GL_SERVER_MODE
:
11380 _err_record_msg(gl
->err
, "Unknown gl_get_line() I/O mode requested.",
11385 * Block all signals.
11387 if(gl_mask_signals(gl
, &oldset
))
11390 * Invoke the private body of this function.
11392 status
= _gl_io_mode(gl
, mode
);
11394 * Restore the process signal mask.
11396 gl_unmask_signals(gl
, &oldset
);
11400 /*.......................................................................
11401 * This is the private body of the public function, gl_io_mode().
11402 * It assumes that the caller has checked its arguments and blocked the
11403 * delivery of signals.
11405 static int _gl_io_mode(GetLine
*gl
, GlIOMode mode
)
11408 * Are we already in the specified mode?
11410 if(mode
== gl
->io_mode
)
11413 * First revert to normal I/O in the current I/O mode.
11417 * Record the new mode.
11419 gl
->io_mode
= mode
;
11421 * Perform any actions needed by the new mode.
11423 if(mode
==GL_SERVER_MODE
) {
11424 if(_gl_raw_io(gl
, 1))
11430 /*.......................................................................
11431 * Return extra information (ie. in addition to that provided by errno)
11432 * about the last error to occur in either gl_get_line() or its
11433 * associated public functions.
11436 * gl GetLine * The resource object of gl_get_line().
11438 * buff char * An optional output buffer. Note that if the
11439 * calling application calls any gl_*()
11440 * functions from signal handlers, it should
11441 * provide a buffer here, so that a copy of
11442 * the latest error message can safely be made
11443 * while signals are blocked.
11444 * n size_t The allocated size of buff[].
11446 * return const char * A pointer to the error message. This will
11447 * be the buff argument, unless buff==NULL, in
11448 * which case it will be a pointer to an
11449 * internal error buffer. In the latter case,
11450 * note that the contents of the returned buffer
11451 * will change on subsequent calls to any gl_*()
11454 const char *gl_error_message(GetLine
*gl
, char *buff
, size_t n
)
11457 static const char *msg
= "NULL GetLine argument";
11459 strncpy(buff
, msg
, n
);
11465 sigset_t oldset
; /* The signals that were blocked on entry to this block */
11467 * Temporarily block all signals.
11469 gl_mask_signals(gl
, &oldset
);
11471 * Copy the error message into the specified buffer.
11473 if(buff
&& n
> 0) {
11474 strncpy(buff
, _err_get_msg(gl
->err
), n
);
11478 * Restore the process signal mask before returning.
11480 gl_unmask_signals(gl
, &oldset
);
11482 return _err_get_msg(gl
->err
);
11487 /*.......................................................................
11488 * Return the signal mask used by gl_get_line(). This is the set of
11489 * signals that gl_get_line() is currently configured to trap.
11492 * gl GetLine * The resource object of gl_get_line().
11494 * set sigset_t * The set of signals will be returned in *set,
11495 * in the form of a signal process mask, as
11496 * used by sigaction(), sigprocmask(),
11497 * sigpending(), sigsuspend(), sigsetjmp() and
11498 * other standard POSIX signal-aware
11501 * return int 0 - OK.
11502 * 1 - Error (examine errno for reason).
11504 int gl_list_signals(GetLine
*gl
, sigset_t
*set
)
11507 * Check the arguments.
11511 _err_record_msg(gl
->err
, "NULL argument(s)", END_ERR_MSG
);
11516 * Copy the signal mask into *set.
11518 memcpy(set
, &gl
->all_signal_set
, sizeof(*set
));
11522 /*.......................................................................
11523 * By default, gl_get_line() doesn't trap signals that are blocked
11524 * when it is called. This default can be changed either on a
11525 * per-signal basis by calling gl_trap_signal(), or on a global basis
11526 * by calling this function. What this function does is add the
11527 * GLS_UNBLOCK_SIG flag to all signals that are currently configured
11528 * to be trapped by gl_get_line(), such that when subsequent calls to
11529 * gl_get_line() wait for I/O, these signals are temporarily
11530 * unblocked. This behavior is useful in non-blocking server-I/O mode,
11531 * where it is used to avoid race conditions related to handling these
11532 * signals externally to gl_get_line(). See the demonstration code in
11533 * demo3.c, or the gl_handle_signal() man page for further
11537 * gl GetLine * The resource object of gl_get_line().
11539 void gl_catch_blocked(GetLine
*gl
)
11541 sigset_t oldset
; /* The process signal mask to restore */
11542 GlSignalNode
*sig
; /* A signal node in gl->sigs */
11544 * Check the arguments.
11551 * Temporarily block all signals while we modify the contents of gl.
11553 gl_mask_signals(gl
, &oldset
);
11555 * Add the GLS_UNBLOCK_SIG flag to all configured signals.
11557 for(sig
=gl
->sigs
; sig
; sig
=sig
->next
)
11558 sig
->flags
|= GLS_UNBLOCK_SIG
;
11560 * Restore the process signal mask that was superseded by the call
11561 * to gl_mask_signals().
11563 gl_unmask_signals(gl
, &oldset
);
11567 /*.......................................................................
11568 * Respond to signals who's default effects have important
11569 * consequences to gl_get_line(). This is intended for use in
11570 * non-blocking server mode, where the external event loop is
11571 * responsible for catching signals. Signals that are handled include
11572 * those that by default terminate or suspend the process, and the
11573 * signal that indicates that the terminal size has changed. Note that
11574 * this function is not signal safe and should thus not be called from
11575 * a signal handler itself. See the gl_io_mode() man page for how it
11578 * In the case of signals that by default terminate or suspend
11579 * processes, command-line editing will be suspended, the terminal
11580 * returned to a usable state, then the default disposition of the
11581 * signal restored and the signal resent, in order to suspend or
11582 * terminate the process. If the process subsequently resumes,
11583 * command-line editing is resumed.
11585 * In the case of signals that indicate that the terminal has been
11586 * resized, the new size will be queried, and any input line that is
11587 * being edited will be redrawn to fit the new dimensions of the
11591 * signo int The number of the signal to respond to.
11592 * gl GetLine * The first element of an array of 'ngl' GetLine
11594 * ngl int The number of elements in the gl[] array. Normally
11595 * this will be one.
11597 void gl_handle_signal(int signo
, GetLine
*gl
, int ngl
)
11599 int attr
; /* The attributes of the specified signal */
11600 sigset_t all_signals
; /* The set of trappable signals */
11601 sigset_t oldset
; /* The process signal mask to restore */
11609 * Look up the default attributes of the specified signal.
11611 attr
= gl_classify_signal(signo
);
11613 * If the signal isn't known, we are done.
11618 * Temporarily block all signals while we modify the gl objects.
11620 gl_list_trappable_signals(&all_signals
);
11621 sigprocmask(SIG_BLOCK
, &all_signals
, &oldset
);
11623 * Suspend or terminate the process?
11625 if(attr
& (GLSA_SUSP
| GLSA_TERM
)) {
11626 gl_suspend_process(signo
, gl
, ngl
);
11628 * Resize the terminal? Note that ioctl() isn't defined as being
11629 * signal safe, so we can't call gl_update_size() here. However,
11630 * gl_get_line() checks for resizes on each call, so simply arrange
11631 * for the application's event loop to call gl_get_line() as soon as
11632 * it becomes possible to write to the terminal. Note that if the
11633 * caller is calling select() or poll when this happens, these functions
11634 * get interrupted, since a signal has been caught.
11636 } else if(attr
& GLSA_SIZE
) {
11637 for(i
=0; i
<ngl
; i
++)
11638 gl
[i
].pending_io
= GLP_WRITE
;
11641 * Restore the process signal mask that was superseded by the call
11642 * to gl_mask_signals().
11644 sigprocmask(SIG_SETMASK
, &oldset
, NULL
);
11648 /*.......................................................................
11649 * Respond to an externally caught process suspension or
11650 * termination signal.
11652 * After restoring the terminal to a usable state, suspend or
11653 * terminate the calling process, using the original signal with its
11654 * default disposition restored to do so. If the process subsequently
11655 * resumes, resume editing any input lines that were being entered.
11658 * signo int The signal number to suspend the process with. Note
11659 * that the default disposition of this signal will be
11660 * restored before the signal is sent, so provided
11661 * that the default disposition of this signal is to
11662 * either suspend or terminate the application,
11663 * that is what wil happen, regardless of what signal
11664 * handler is currently assigned to this signal.
11665 * gl GetLine * The first element of an array of 'ngl' GetLine objects
11666 * whose terminals should be restored to a sane state
11667 * while the application is suspended.
11668 * ngl int The number of elements in the gl[] array.
11670 static void gl_suspend_process(int signo
, GetLine
*gl
, int ngl
)
11672 sigset_t only_signo
; /* A signal set containing just signo */
11673 sigset_t oldset
; /* The signal mask on entry to this function */
11674 sigset_t all_signals
; /* A signal set containing all signals */
11675 struct sigaction old_action
; /* The current signal handler */
11676 struct sigaction def_action
; /* The default signal handler */
11679 * Create a signal mask containing the signal that was trapped.
11681 sigemptyset(&only_signo
);
11682 sigaddset(&only_signo
, signo
);
11684 * Temporarily block all signals.
11686 gl_list_trappable_signals(&all_signals
);
11687 sigprocmask(SIG_BLOCK
, &all_signals
, &oldset
);
11689 * Restore the terminal to a usable state.
11691 for(i
=0; i
<ngl
; i
++) {
11692 GetLine
*obj
= gl
+ i
;
11693 if(obj
->raw_mode
) {
11694 _gl_normal_io(obj
);
11695 if(!obj
->raw_mode
) /* Check that gl_normal_io() succeded */
11696 obj
->raw_mode
= -1; /* Flag raw mode as needing to be restored */
11700 * Restore the system default disposition of the signal that we
11701 * caught. Note that this signal is currently blocked. Note that we
11702 * don't use memcpy() to copy signal sets here, because the signal safety
11703 * of memcpy() is undefined.
11705 def_action
.sa_handler
= SIG_DFL
;
11707 char *orig
= (char *) &all_signals
;
11708 char *dest
= (char *) &def_action
.sa_mask
;
11709 for(i
=0; i
<sizeof(sigset_t
); i
++)
11712 sigaction(signo
, &def_action
, &old_action
);
11714 * Resend the signal, and unblock it so that it gets delivered to
11715 * the application. This will invoke the default action of this signal.
11718 sigprocmask(SIG_UNBLOCK
, &only_signo
, NULL
);
11720 * If the process resumes again, it will resume here.
11721 * Block the signal again, then restore our signal handler.
11723 sigprocmask(SIG_BLOCK
, &only_signo
, NULL
);
11724 sigaction(signo
, &old_action
, NULL
);
11726 * Resume command-line editing.
11728 for(i
=0; i
<ngl
; i
++) {
11729 GetLine
*obj
= gl
+ i
;
11730 if(obj
->raw_mode
== -1) { /* Did we flag the need to restore raw mode? */
11731 obj
->raw_mode
= 0; /* gl_raw_io() does nothing unless raw_mode==0 */
11732 _gl_raw_io(obj
, 1);
11736 * Restore the process signal mask to the way it was when this function
11739 sigprocmask(SIG_SETMASK
, &oldset
, NULL
);
11743 /*.......................................................................
11744 * Return the information about the default attributes of a given signal.
11745 * The attributes that are returned are as defined by the standards that
11746 * created them, including POSIX, SVR4 and 4.3+BSD, and are taken from a
11747 * table in Richard Steven's book, "Advanced programming in the UNIX
11751 * signo int The signal to be characterized.
11753 * return int A bitwise union of GlSigAttr enumerators, or 0
11754 * if the signal isn't known.
11756 static int gl_classify_signal(int signo
)
11760 * Search for the specified signal in the gl_signal_list[] table.
11762 for(i
=0; i
<sizeof(gl_signal_list
)/sizeof(gl_signal_list
[0]); i
++) {
11763 const struct GlDefSignal
*sig
= gl_signal_list
+ i
;
11764 if(sig
->signo
== signo
)
11768 * Signal not known.
11773 /*.......................................................................
11774 * When in non-blocking server mode, this function can be used to abandon
11775 * the current incompletely entered input line, and prepare to start
11776 * editing a new line on the next call to gl_get_line().
11779 * gl GetLine * The line editor resource object.
11781 void gl_abandon_line(GetLine
*gl
)
11783 sigset_t oldset
; /* The process signal mask to restore */
11785 * Check the arguments.
11792 * Temporarily block all signals while we modify the contents of gl.
11794 gl_mask_signals(gl
, &oldset
);
11796 * Mark the input line as discarded.
11798 _gl_abandon_line(gl
);
11800 * Restore the process signal mask that was superseded by the call
11801 * to gl_mask_signals().
11803 gl_unmask_signals(gl
, &oldset
);
11807 /*.......................................................................
11808 * This is the private body of the gl_abandon_line() function. It
11809 * assumes that the caller has checked its arguments and blocked the
11810 * delivery of signals.
11812 void _gl_abandon_line(GetLine
*gl
)
11815 gl
->pending_io
= GLP_WRITE
;
11818 /*.......................................................................
11819 * How many characters are needed to write a number as an octal string?
11822 * num unsigned The to be measured.
11824 * return int The number of characters needed.
11826 static int gl_octal_width(unsigned num
)
11828 int n
; /* The number of characters needed to render the number */
11829 for(n
=1; num
/= 8; n
++)
11834 /*.......................................................................
11835 * Tell gl_get_line() the current terminal size. Note that this is only
11836 * necessary on systems where changes in terminal size aren't reported
11840 * gl GetLine * The resource object of gl_get_line().
11841 * ncolumn int The number of columns in the terminal.
11842 * nline int The number of lines in the terminal.
11844 * return int 0 - OK.
11847 int gl_set_term_size(GetLine
*gl
, int ncolumn
, int nline
)
11849 sigset_t oldset
; /* The signals that were blocked on entry */
11850 /* to this function */
11851 int status
; /* The return status */
11853 * Block all signals while accessing gl.
11855 gl_mask_signals(gl
, &oldset
);
11857 * Install the new terminal size.
11859 status
= _gl_set_term_size(gl
, ncolumn
, nline
);
11861 * Restore the process signal mask before returning.
11863 gl_unmask_signals(gl
, &oldset
);
11867 /*.......................................................................
11868 * This is the private body of the gl_set_term_size() function. It
11869 * assumes that the caller has checked its arguments and blocked the
11870 * delivery of signals.
11872 static int _gl_set_term_size(GetLine
*gl
, int ncolumn
, int nline
)
11875 * Check the arguments.
11882 * Reject non-sensical dimensions.
11884 if(ncolumn
<= 0 || nline
<= 0) {
11885 _err_record_msg(gl
->err
, "Invalid terminal size", END_ERR_MSG
);
11890 * Install the new dimensions in the terminal driver if possible, so
11891 * that future calls to gl_query_size() get the new value.
11895 struct winsize size
;
11896 size
.ws_row
= nline
;
11897 size
.ws_col
= ncolumn
;
11898 size
.ws_xpixel
= 0;
11899 size
.ws_ypixel
= 0;
11900 if(ioctl(gl
->output_fd
, TIOCSWINSZ
, &size
) == -1) {
11901 _err_record_msg(gl
->err
, "Can't change terminal size", END_ERR_MSG
);
11907 * If an input line is in the process of being edited, redisplay it to
11908 * accomodate the new dimensions, and record the new dimensions in
11909 * gl->nline and gl->ncolumn.
11911 return gl_handle_tty_resize(gl
, ncolumn
, nline
);
11914 /*.......................................................................
11915 * Record a character in the input line buffer at a given position.
11918 * gl GetLine * The resource object of gl_get_line().
11919 * c char The character to be recorded.
11920 * bufpos int The index in the buffer at which to record the
11923 * return int 0 - OK.
11924 * 1 - Insufficient room.
11926 static int gl_buffer_char(GetLine
*gl
, char c
, int bufpos
)
11929 * Guard against buffer overruns.
11931 if(bufpos
>= gl
->linelen
)
11934 * Record the new character.
11936 gl
->line
[bufpos
] = c
;
11938 * If the new character was placed beyond the end of the current input
11939 * line, update gl->ntotal to reflect the increased number of characters
11940 * that are in gl->line, and terminate the string.
11942 if(bufpos
>= gl
->ntotal
) {
11943 gl
->ntotal
= bufpos
+1;
11944 gl
->line
[gl
->ntotal
] = '\0';
11949 /*.......................................................................
11950 * Copy a given string into the input buffer, overwriting the current
11954 * gl GetLine * The resource object of gl_get_line().
11955 * s const char * The string to be recorded.
11956 * n int The number of characters to be copied from the
11958 * bufpos int The index in the buffer at which to place the
11959 * the first character of the string.
11961 * return int 0 - OK.
11962 * 1 - String truncated to fit.
11964 static int gl_buffer_string(GetLine
*gl
, const char *s
, int n
, int bufpos
)
11966 int nnew
; /* The number of characters actually recorded */
11969 * How many of the characters will fit within the buffer?
11971 nnew
= bufpos
+ n
<= gl
->linelen
? n
: (gl
->linelen
- bufpos
);
11973 * Record the first nnew characters of s[] in the buffer.
11975 for(i
=0; i
<nnew
; i
++)
11976 gl_buffer_char(gl
, s
[i
], bufpos
+ i
);
11978 * Was the string truncated?
11983 /*.......................................................................
11984 * Make room in the input buffer for a string to be inserted. This
11985 * involves moving the characters that follow a specified point, towards
11986 * the end of the buffer.
11989 * gl GetLine * The resource object of gl_get_line().
11990 * start int The index of the first character to be moved.
11991 * n int The width of the gap.
11993 * return int 0 - OK.
11994 * 1 - Insufficient room.
11996 static int gl_make_gap_in_buffer(GetLine
*gl
, int start
, int n
)
11999 * Ensure that the buffer has sufficient space.
12001 if(gl
->ntotal
+ n
> gl
->linelen
)
12004 * Move everything including and beyond the character at 'start'
12005 * towards the end of the string.
12007 memmove(gl
->line
+ start
+ n
, gl
->line
+ start
, gl
->ntotal
- start
+ 1);
12009 * Update the recorded size of the line.
12015 /*.......................................................................
12016 * Remove a given number of characters from the input buffer. This
12017 * involves moving the characters that follow the removed characters to
12018 * where the removed sub-string started in the input buffer.
12021 * gl GetLine * The resource object of gl_get_line().
12022 * start int The first character to be removed.
12023 * n int The number of characters to remove.
12025 static void gl_remove_from_buffer(GetLine
*gl
, int start
, int n
)
12027 memmove(gl
->line
+ start
, gl
->line
+ start
+ n
, gl
->ntotal
- start
- n
+ 1);
12029 * Update the recorded size of the line.
12034 /*.......................................................................
12035 * Truncate the string in the input line buffer after a given number of
12039 * gl GetLine * The resource object of gl_get_line().
12040 * n int The new length of the line.
12042 * return int 0 - OK.
12043 * 1 - n > gl->linelen.
12045 static int gl_truncate_buffer(GetLine
*gl
, int n
)
12047 if(n
> gl
->linelen
)
12049 gl
->line
[n
] = '\0';
12054 /*.......................................................................
12055 * When the contents of gl->line[] are changed without calling any of the
12056 * gl_ buffer manipulation functions, this function must be called to
12057 * compute the length of this string, and ancillary information.
12060 * gl GetLine * The resource object of gl_get_line().
12062 static void gl_update_buffer(GetLine
*gl
)
12064 int len
; /* The length of the line */
12066 * Measure the length of the input line.
12068 for(len
=0; len
<= gl
->linelen
&& gl
->line
[len
]; len
++)
12071 * Just in case the string wasn't correctly terminated, do so here.
12073 gl
->line
[len
] = '\0';
12075 * Record the number of characters that are now in gl->line[].
12079 * Ensure that the cursor stays within the bounds of the modified
12082 if(gl
->buff_curpos
> gl
->ntotal
)
12083 gl
->buff_curpos
= gl
->ntotal
;
12085 * Arrange for the input line to be redrawn.
12087 gl_queue_redisplay(gl
);
12091 /*.......................................................................
12092 * Erase the displayed input line, including its prompt, and leave the
12093 * cursor where the erased line started. Note that to allow this
12094 * function to be used when responding to a terminal resize, this
12095 * function is designed to work even if the horizontal cursor position
12096 * doesn't match the internally recorded position.
12099 * gl GetLine * The resource object of gl_get_line().
12101 * return int 0 - OK.
12104 static int gl_erase_line(GetLine
*gl
)
12107 * Is a line currently displayed?
12109 if(gl
->displayed
) {
12111 * Relative the the start of the input line, which terminal line of
12112 * the current input line is the cursor currently on?
12114 int cursor_line
= gl
->term_curpos
/ gl
->ncolumn
;
12116 * Move the cursor to the start of the line.
12118 for( ; cursor_line
> 0; cursor_line
--) {
12119 if(gl_print_control_sequence(gl
, 1, gl
->up
))
12122 if(gl_print_control_sequence(gl
, 1, gl
->bol
))
12125 * Clear from the start of the line to the end of the terminal.
12127 if(gl_print_control_sequence(gl
, gl
->nline
, gl
->clear_eod
))
12130 * Mark the line as no longer displayed.
12132 gl_line_erased(gl
);
12137 /*.......................................................................
12138 * Arrange for the input line to be redisplayed by gl_flush_output(),
12139 * as soon as the output queue becomes empty.
12142 * gl GetLine * The resource object of gl_get_line().
12144 static void gl_queue_redisplay(GetLine
*gl
)
12147 gl
->pending_io
= GLP_WRITE
;
12150 /*.......................................................................
12151 * Truncate the displayed input line starting from the current
12152 * terminal cursor position, and leave the cursor at the end of the
12153 * truncated line. The input-line buffer is not affected.
12156 * gl GetLine * The resource object of gl_get_line().
12158 * return int 0 - OK.
12161 static int gl_truncate_display(GetLine
*gl
)
12164 * Keep a record of the current terminal cursor position.
12166 int term_curpos
= gl
->term_curpos
;
12168 * First clear from the cursor to the end of the current input line.
12170 if(gl_print_control_sequence(gl
, 1, gl
->clear_eol
))
12173 * If there is more than one line displayed, go to the start of the
12174 * next line and clear from there to the end of the display. Note that
12175 * we can't use clear_eod to do the whole job of clearing from the
12176 * current cursor position to the end of the terminal because
12177 * clear_eod is only defined when used at the start of a terminal line
12178 * (eg. with gnome terminals, clear_eod clears from the start of the
12179 * current terminal line, rather than from the current cursor
12182 if(gl
->term_len
/ gl
->ncolumn
> gl
->term_curpos
/ gl
->ncolumn
) {
12183 if(gl_print_control_sequence(gl
, 1, gl
->down
) ||
12184 gl_print_control_sequence(gl
, 1, gl
->bol
) ||
12185 gl_print_control_sequence(gl
, gl
->nline
, gl
->clear_eod
))
12188 * Where is the cursor now?
12190 gl
->term_curpos
= gl
->ncolumn
* (term_curpos
/ gl
->ncolumn
+ 1);
12192 * Restore the cursor position.
12194 gl_set_term_curpos(gl
, term_curpos
);
12197 * Update the recorded position of the final character.
12199 gl
->term_len
= gl
->term_curpos
;
12203 /*.......................................................................
12204 * Return the set of all trappable signals.
12207 * signals sigset_t * The set of signals will be recorded in
12210 static void gl_list_trappable_signals(sigset_t
*signals
)
12213 * Start with the set of all signals.
12215 sigfillset(signals
);
12217 * Remove un-trappable signals from this set.
12220 sigdelset(signals
, SIGKILL
);
12223 sigdelset(signals
, SIGSTOP
);
12227 /*.......................................................................
12228 * Read an input line from a non-interactive input stream.
12231 * gl GetLine * The resource object of gl_get_line().
12233 * return int 0 - OK
12236 static int gl_read_stream_line(GetLine
*gl
)
12238 char c
= '\0'; /* The latest character read from fp */
12240 * Record the fact that we are about to read input.
12242 gl
->pending_io
= GLP_READ
;
12244 * If we are starting a new line, reset the line-input parameters.
12247 gl_reset_input_line(gl
);
12249 * Read one character at a time.
12251 while(gl
->ntotal
< gl
->linelen
&& c
!= '\n') {
12253 * Attempt to read one more character.
12255 switch(gl_read_input(gl
, &c
)) {
12258 case GL_READ_EOF
: /* Reached end-of-file? */
12260 * If any characters were read before the end-of-file condition,
12261 * interpolate a newline character, so that the caller sees a
12262 * properly terminated line. Otherwise return an end-of-file
12265 if(gl
->ntotal
> 0) {
12268 gl_record_status(gl
, GLR_EOF
, 0);
12272 case GL_READ_BLOCKED
: /* Input blocked? */
12273 gl_record_status(gl
, GLR_BLOCKED
, BLOCKED_ERRNO
);
12276 case GL_READ_ERROR
: /* I/O error? */
12281 * Append the character to the line buffer.
12283 if(gl_buffer_char(gl
, c
, gl
->ntotal
))
12287 * Was the end of the input line reached before running out of buffer space?
12289 gl
->endline
= (c
== '\n');
12293 /*.......................................................................
12294 * Read a single character from a non-interactive input stream.
12297 * gl GetLine * The resource object of gl_get_line().
12299 * return int The character, or EOF on error.
12301 static int gl_read_stream_char(GetLine
*gl
)
12303 char c
= '\0'; /* The latest character read from fp */
12304 int retval
= EOF
; /* The return value of this function */
12306 * Arrange to discard any incomplete input line.
12308 _gl_abandon_line(gl
);
12310 * Record the fact that we are about to read input.
12312 gl
->pending_io
= GLP_READ
;
12314 * Attempt to read one more character.
12316 switch(gl_read_input(gl
, &c
)) {
12317 case GL_READ_OK
: /* Success */
12320 case GL_READ_BLOCKED
: /* The read blocked */
12321 gl_record_status(gl
, GLR_BLOCKED
, BLOCKED_ERRNO
);
12322 retval
= EOF
; /* Failure */
12324 case GL_READ_EOF
: /* End of file reached */
12325 gl_record_status(gl
, GLR_EOF
, 0);
12326 retval
= EOF
; /* Failure */
12328 case GL_READ_ERROR
:
12329 retval
= EOF
; /* Failure */
12335 /*.......................................................................
12336 * Bind a key sequence to a given action.
12339 * gl GetLine * The resource object of gl_get_line().
12340 * origin GlKeyOrigin The originator of the key binding.
12341 * key const char * The key-sequence to be bound (or unbound).
12342 * action const char * The name of the action to bind the key to,
12343 * or either NULL or "" to unbind the
12346 * return int 0 - OK
12349 int gl_bind_keyseq(GetLine
*gl
, GlKeyOrigin origin
, const char *keyseq
,
12350 const char *action
)
12352 KtBinder binder
; /* The private internal equivalent of 'origin' */
12354 * Check the arguments.
12356 if(!gl
|| !keyseq
) {
12359 _err_record_msg(gl
->err
, "NULL argument(s)", END_ERR_MSG
);
12363 * An empty action string requests that the key-sequence be unbound.
12364 * This is indicated to _kt_set_keybinding() by passing a NULL action
12365 * string, so convert an empty string to a NULL action pointer.
12367 if(action
&& *action
=='\0')
12370 * Translate the public originator enumeration to the private equivalent.
12372 binder
= origin
==GL_USER_KEY
? KTB_USER
: KTB_NORM
;
12374 * Bind the action to a given key-sequence?
12376 if(keyseq
&& _kt_set_keybinding(gl
->bindings
, binder
, keyseq
, action
)) {
12377 _err_record_msg(gl
->err
, _kt_last_error(gl
->bindings
), END_ERR_MSG
);
12383 /*.......................................................................
12384 * This is the public wrapper around the gl_clear_termina() function.
12385 * It clears the terminal and leaves the cursor at the home position.
12386 * In server I/O mode, the next call to gl_get_line() will also
12387 * redisplay the current input line.
12390 * gl GetLine * The resource object of gl_get_line().
12392 * return int 0 - OK.
12395 int gl_erase_terminal(GetLine
*gl
)
12397 sigset_t oldset
; /* The signals that were blocked on entry */
12398 /* to this function */
12399 int status
; /* The return status */
12401 * Block all signals while accessing gl.
12403 gl_mask_signals(gl
, &oldset
);
12405 * Clear the terminal.
12407 status
= gl_clear_screen(gl
, 1, NULL
);
12409 * Attempt to flush the clear-screen control codes to the terminal.
12410 * If this doesn't complete the job, the next call to gl_get_line()
12413 (void) gl_flush_output(gl
);
12415 * Restore the process signal mask before returning.
12417 gl_unmask_signals(gl
, &oldset
);
12421 /*.......................................................................
12422 * This function must be called by any function that erases the input
12426 * gl GetLine * The resource object of gl_get_line().
12428 static void gl_line_erased(GetLine
*gl
)
12431 gl
->term_curpos
= 0;
12435 /*.......................................................................
12436 * Append a specified line to the history list.
12439 * gl GetLine * The resource object of gl_get_line().
12440 * line const char * The line to be added.
12442 * return int 0 - OK.
12445 int gl_append_history(GetLine
*gl
, const char *line
)
12447 sigset_t oldset
; /* The signals that were blocked on entry */
12448 /* to this function */
12449 int status
; /* The return status */
12451 * Check the arguments.
12458 * Block all signals.
12460 if(gl_mask_signals(gl
, &oldset
))
12463 * Execute the private body of the function while signals are blocked.
12465 status
= _gl_append_history(gl
, line
);
12467 * Restore the process signal mask.
12469 gl_unmask_signals(gl
, &oldset
);
12473 /*.......................................................................
12474 * This is the private body of the public function, gl_append_history().
12475 * It assumes that the caller has checked its arguments and blocked the
12476 * delivery of signals.
12478 static int _gl_append_history(GetLine
*gl
, const char *line
)
12480 int status
=_glh_add_history(gl
->glh
, line
, 0);
12482 _err_record_msg(gl
->err
, _glh_last_error(gl
->glh
), END_ERR_MSG
);
12486 /*.......................................................................
12487 * Enable or disable the automatic addition of newly entered lines to the
12491 * gl GetLine * The resource object of gl_get_line().
12492 * enable int If true, subsequently entered lines will
12493 * automatically be added to the history list
12494 * before they are returned to the caller of
12495 * gl_get_line(). If 0, the choice of how and
12496 * when to archive lines in the history list,
12497 * is left up to the calling application, which
12498 * can do so via calls to gl_append_history().
12500 * return int 0 - OK.
12503 int gl_automatic_history(GetLine
*gl
, int enable
)
12505 sigset_t oldset
; /* The signals that were blocked on entry */
12506 /* to this function */
12508 * Check the arguments.
12515 * Block all signals.
12517 if(gl_mask_signals(gl
, &oldset
))
12520 * Execute the private body of the function while signals are blocked.
12522 gl
->automatic_history
= enable
;
12524 * Restore the process signal mask.
12526 gl_unmask_signals(gl
, &oldset
);
12530 /*.......................................................................
12531 * This is a public function that reads a single uninterpretted
12532 * character from the user, without displaying anything.
12535 * gl GetLine * A resource object previously returned by
12538 * return int The character that was read, or EOF if the read
12539 * had to be aborted (in which case you can call
12540 * gl_return_status() to find out why).
12542 int gl_read_char(GetLine
*gl
)
12544 int retval
; /* The return value of _gl_read_char() */
12546 * This function can be called from application callback functions,
12547 * so check whether signals have already been masked, so that we don't
12548 * do it again, and overwrite gl->old_signal_set.
12550 int was_masked
= gl
->signals_masked
;
12552 * Check the arguments.
12559 * Temporarily block all of the signals that we have been asked to trap.
12561 if(!was_masked
&& gl_mask_signals(gl
, &gl
->old_signal_set
))
12564 * Perform the character reading task.
12566 retval
= _gl_read_char(gl
);
12568 * Restore the process signal mask to how it was when this function was
12572 gl_unmask_signals(gl
, &gl
->old_signal_set
);
12576 /*.......................................................................
12577 * This is the main body of the public function gl_read_char().
12579 static int _gl_read_char(GetLine
*gl
)
12581 int retval
= EOF
; /* The return value */
12582 int waserr
= 0; /* True if an error occurs */
12583 char c
; /* The character read */
12585 * This function can be called from application callback functions,
12586 * so check whether signals have already been overriden, so that we don't
12587 * overwrite the preserved signal handlers with gl_get_line()s. Also
12588 * record whether we are currently in raw I/O mode or not, so that this
12589 * can be left in the same state on leaving this function.
12591 int was_overriden
= gl
->signals_overriden
;
12592 int was_raw
= gl
->raw_mode
;
12594 * Also keep a record of the direction of any I/O that gl_get_line()
12595 * is awaiting, so that we can restore this status on return.
12597 GlPendingIO old_pending_io
= gl
->pending_io
;
12599 * Assume that this call will successfully complete the input operation
12600 * until proven otherwise.
12602 gl_clear_status(gl
);
12604 * If this is the first call to this function or gl_get_line(),
12605 * since new_GetLine(), complete any postponed configuration.
12607 if(!gl
->configured
) {
12608 (void) _gl_configure_getline(gl
, NULL
, NULL
, TECLA_CONFIG_FILE
);
12609 gl
->configured
= 1;
12612 * Before installing our signal handler functions, record the fact
12613 * that there are no pending signals.
12615 gl_pending_signal
= -1;
12617 * Temporarily override the signal handlers of the calling program,
12618 * so that we can intercept signals that would leave the terminal
12622 waserr
= gl_override_signal_handlers(gl
);
12624 * After recording the current terminal settings, switch the terminal
12625 * into raw input mode, without redisplaying any partially entered input
12629 waserr
= waserr
|| _gl_raw_io(gl
, 0);
12631 * Attempt to read the line. This will require more than one attempt if
12632 * either a current temporary input file is opened by gl_get_input_line()
12633 * or the end of a temporary input file is reached by gl_read_stream_line().
12637 * Read a line from a non-interactive stream?
12639 if(gl
->file_fp
|| !gl
->is_term
) {
12640 retval
= gl_read_stream_char(gl
);
12641 if(retval
!= EOF
) { /* Success? */
12643 } else if(gl
->file_fp
) { /* End of temporary input file? */
12644 gl_revert_input(gl
);
12645 gl_record_status(gl
, GLR_NEWLINE
, 0);
12646 } else { /* An error? */
12652 * Read from the terminal? Note that the above if() block may have
12653 * changed gl->file_fp, so it is necessary to retest it here, rather
12654 * than using an else statement.
12656 if(!gl
->file_fp
&& gl
->is_term
) {
12658 * Flush any pending output to the terminal before waiting
12659 * for the user to type a character.
12661 if(_glq_char_count(gl
->cq
) > 0 && gl_flush_output(gl
)) {
12664 * Read one character. Don't append it to the key buffer, since
12665 * this would subseuqnely appear as bogus input to the line editor.
12667 } else if(gl_read_terminal(gl
, 0, &c
) == 0) {
12669 * Record the character for return.
12673 * In this mode, count each character as being a new key-sequence.
12675 gl
->keyseq_count
++;
12677 * Delete the character that was read, from the key-press buffer.
12679 gl_discard_chars(gl
, 1);
12688 * If an error occurred, but gl->rtn_status is still set to
12689 * GLR_NEWLINE, change the status to GLR_ERROR. Otherwise
12690 * leave it at whatever specific value was assigned by the function
12691 * that aborted input. This means that only functions that trap
12692 * non-generic errors have to remember to update gl->rtn_status
12695 if(waserr
&& gl
->rtn_status
== GLR_NEWLINE
)
12696 gl_record_status(gl
, GLR_ERROR
, errno
);
12698 * Restore terminal settings, if they were changed by this function.
12700 if(!was_raw
&& gl
->io_mode
!= GL_SERVER_MODE
)
12703 * Restore the signal handlers, if they were overriden by this function.
12706 gl_restore_signal_handlers(gl
);
12708 * If this function gets aborted early, the errno value associated
12709 * with the event that caused this to happen is recorded in
12710 * gl->rtn_errno. Since errno may have been overwritten by cleanup
12711 * functions after this, restore its value to the value that it had
12712 * when the error condition occured, so that the caller can examine it
12713 * to find out what happened.
12715 errno
= gl
->rtn_errno
;
12717 * Error conditions are signalled to the caller, by setting the returned
12718 * character to EOF.
12720 if(gl
->rtn_status
!= GLR_NEWLINE
)
12723 * Restore the indication of what direction of I/O gl_get_line()
12724 * was awaiting before this call.
12726 gl
->pending_io
= old_pending_io
;
12728 * Return the acquired character.
12733 /*.......................................................................
12734 * Reset the GetLine completion status. This function should be called
12735 * at the start of gl_get_line(), gl_read_char() and gl_query_char()
12736 * to discard the completion status and non-zero errno value of any
12737 * preceding calls to these functions.
12740 * gl GetLine * The resource object of this module.
12742 static void gl_clear_status(GetLine
*gl
)
12744 gl_record_status(gl
, GLR_NEWLINE
, 0);
12747 /*.......................................................................
12748 * When an error or other event causes gl_get_line() to return, this
12749 * function should be called to record information about what
12750 * happened, including the value of errno and the value that
12751 * gl_return_status() should return.
12754 * gl GetLine * The resource object of this module.
12755 * rtn_status GlReturnStatus The completion status. To clear a
12756 * previous abnormal completion status,
12757 * specify GLR_NEWLINE (this is what
12758 * gl_clear_status() does).
12759 * rtn_errno int The associated value of errno.
12761 static void gl_record_status(GetLine
*gl
, GlReturnStatus rtn_status
,
12765 * If rtn_status==GLR_NEWLINE, then this resets the completion status, so we
12766 * should always heed this. Otherwise, only record the first abnormal
12767 * condition that occurs after such a reset.
12769 if(rtn_status
== GLR_NEWLINE
|| gl
->rtn_status
== GLR_NEWLINE
) {
12770 gl
->rtn_status
= rtn_status
;
12771 gl
->rtn_errno
= rtn_errno
;