1 /* readline.c -- a general facility for reading lines of input
2 with emacs style editing and completion. */
4 /* Copyright (C) 1987,1989 Free Software Foundation, Inc.
6 This file contains the Readline Library (the Library), a set of
7 routines for providing Emacs style line input to programs that ask
10 The Library is free software; you can redistribute it and/or modify
11 it under the terms of the GNU General Public License as published by
12 the Free Software Foundation; either version 1, or (at your option)
15 The Library is distributed in the hope that it will be useful, but
16 WITHOUT ANY WARRANTY; without even the implied warranty of
17 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
18 General Public License for more details.
20 The GNU General Public License is often shipped with GNU software, and
21 is generally kept in a file called COPYING or LICENSE. If you do not
22 have a copy of the license, write to the Free Software Foundation,
23 675 Mass Ave, Cambridge, MA 02139, USA. */
25 /* Remove these declarations when we have a complete libgnu.a. */
28 extern char *xmalloc (), *xrealloc ();
30 static char *xmalloc (), *xrealloc ();
34 #include <sys/types.h>
41 #define NEW_TTY_DRIVER
42 #if defined (SYSV) || defined (hpux) || defined (Xenix)
54 /* These next are for filename completion. Perhaps this belongs
55 in a different place. */
60 struct passwd *getpwuid (), *getpwent ();
63 #define HACK_TERMCAP_MOTION
76 #define d_namlen d_reclen
81 /* Some standard library routines. */
86 #define digit(c) ((c) >= '0' && (c) <= '9')
90 #define isletter(c) (((c) >= 'A' && (c) <= 'Z') || ((c) >= 'a' && (c) <= 'z'))
94 #define digit_value(c) ((c) - '0')
99 #define member(c, s) ((c) ? index ((s), (c)) : 0)
103 #define isident(c) ((isletter(c) || digit(c) || c == '_'))
107 #define exchange(x, y) {int temp = x; x = y; y = temp;}
110 static update_line ();
111 static void output_character_function ();
112 static delete_chars ();
113 static delete_chars ();
114 static insert_some_chars ();
116 #ifdef VOID_SIGHANDLER
117 #define sighandler void
119 #define sighandler int
122 /* This typedef is equivalant to the one for Function; it allows us
123 to say SigHandler *foo = signal (SIGKILL, SIG_IGN); */
124 typedef sighandler SigHandler ();
126 /* If on, then readline handles signals in a way that doesn't screw. */
127 #define HANDLE_SIGNALS
130 /* **************************************************************** */
132 /* Line editing input utility */
134 /* **************************************************************** */
136 /* A pointer to the keymap that is currently in use.
137 By default, it is the standard emacs keymap. */
138 Keymap keymap = emacs_standard_keymap;
143 /* The current style of editing. */
144 int rl_editing_mode = emacs_mode;
146 /* Non-zero if the previous command was a kill command. */
147 static int last_command_was_kill = 0;
149 /* The current value of the numeric argument specified by the user. */
150 int rl_numeric_arg = 1;
152 /* Non-zero if an argument was typed. */
153 int rl_explicit_arg = 0;
155 /* Temporary value used while generating the argument. */
156 static int arg_sign = 1;
158 /* Non-zero means we have been called at least once before. */
159 static int rl_initialized = 0;
161 /* If non-zero, this program is running in an EMACS buffer. */
162 static char *running_in_emacs = (char *)NULL;
164 /* The current offset in the current input line. */
167 /* Mark in the current input line. */
170 /* Length of the current input line. */
173 /* Make this non-zero to return the current input_line. */
176 /* The last function executed by readline. */
177 Function *rl_last_func = (Function *)NULL;
179 /* Top level environment for readline_internal (). */
180 static jmp_buf readline_top_level;
182 /* The streams we interact with. */
183 static FILE *in_stream, *out_stream;
185 /* The names of the streams that we do input and output to. */
186 FILE *rl_instream = stdin, *rl_outstream = stdout;
188 /* Non-zero means echo characters as they are read. */
189 int readline_echoing_p = 1;
191 /* Current prompt. */
194 /* The number of characters read in order to type this complete command. */
195 int rl_key_sequence_length = 0;
197 /* If non-zero, then this is the address of a function to call just
198 before readline_internal () prints the first prompt. */
199 Function *rl_startup_hook = (Function *)NULL;
201 /* If non-zero, then this is the address of a function to call when
202 completing on a directory name. The function is called with
203 the address of a string (the current directory name) as an arg. */
204 Function *rl_symbolic_link_hook = (Function *)NULL;
206 /* What we use internally. You should always refer to RL_LINE_BUFFER. */
207 static char *the_line;
209 /* The character that can generate an EOF. Really read from
210 the terminal driver... just defaulted here. */
211 static int eof_char = CTRL ('D');
213 /* Non-zero makes this the next keystroke to read. */
214 int rl_pending_input = 0;
216 /* Pointer to a useful terminal name. */
217 char *rl_terminal_name = (char *)NULL;
219 /* Line buffer and maintenence. */
220 char *rl_line_buffer = (char *)NULL;
221 static int rl_line_buffer_len = 0;
222 #define DEFAULT_BUFFER_SIZE 256
225 /* **************************************************************** */
227 /* `Forward' declarations */
229 /* **************************************************************** */
231 /* Non-zero means do not parse any lines other than comments and
232 parser directives. */
233 static unsigned char parsing_conditionalized_out = 0;
235 /* Caseless strcmp (). */
236 static int stricmp (), strnicmp ();
238 /* Non-zero means to save keys that we dispatch on in a kbd macro. */
239 static int defining_kbd_macro = 0;
242 /* **************************************************************** */
244 /* Top Level Functions */
246 /* **************************************************************** */
248 /* Read a line of input. Prompt with PROMPT. A NULL PROMPT means
249 none. A return value of NULL means that EOF was encountered. */
254 static rl_prep_terminal (), rl_deprep_terminal ();
255 char *readline_internal ();
260 /* If we are at EOF return a NULL string. */
261 if (rl_pending_input == EOF)
263 rl_pending_input = 0;
264 return ((char *)NULL);
270 #ifdef HANDLE_SIGNALS
274 value = readline_internal ();
275 rl_deprep_terminal ();
277 #ifdef HANDLE_SIGNALS
284 /* Read a line of input from the global rl_instream, doing output on
285 the global rl_outstream.
286 If rl_prompt is non-null, then that is our prompt. */
290 int lastc, c, eof_found;
292 in_stream = rl_instream; out_stream = rl_outstream;
293 lastc = eof_found = 0;
296 (*rl_startup_hook) ();
298 if (!readline_echoing_p)
302 fprintf (out_stream, "%s", rl_prompt);
311 if (rl_editing_mode == vi_mode)
312 rl_vi_insertion_mode ();
318 int lk = last_command_was_kill;
319 int code = setjmp (readline_top_level);
324 if (!rl_pending_input)
326 /* Then initialize the argument and number of keys read. */
328 rl_key_sequence_length = 0;
333 /* EOF typed to a non-blank line is a <NL>. */
334 if (c == EOF && rl_end)
337 /* The character eof_char typed to blank line, and not as the
338 previous character is interpreted as EOF. */
339 if (((c == eof_char && lastc != c) || c == EOF) && !rl_end)
346 rl_dispatch (c, keymap);
348 /* If there was no change in last_command_was_kill, then no kill
349 has taken place. Note that if input is pending we are reading
350 a prefix command, so nothing has changed yet. */
351 if (!rl_pending_input)
353 if (lk == last_command_was_kill)
354 last_command_was_kill = 0;
358 /* In vi mode, when you exit insert mode, the cursor moves back
359 over the previous character. We explicitly check for that here. */
360 if (rl_editing_mode == vi_mode && keymap == vi_movement_keymap)
368 /* Restore the original of this history line, iff the line that we
369 are editing was originally in the history, AND the line has changed. */
371 HIST_ENTRY *entry = current_history ();
373 if (entry && rl_undo_list)
375 char *temp = savestring (the_line);
377 entry = replace_history_entry (where_history (), the_line,
379 free_history_entry (entry);
381 strcpy (the_line, temp);
386 /* At any rate, it is highly likely that this line has an undo list. Get
394 return (savestring (the_line));
398 /* **************************************************************** */
400 /* Signal Handling */
402 /* **************************************************************** */
405 static SigHandler *old_sigwinch = (SigHandler *)NULL;
408 rl_handle_sigwinch (sig, code, scp)
410 struct sigcontext *scp;
412 char *term = rl_terminal_name, *getenv ();
414 if (readline_echoing_p)
417 term = getenv ("TERM");
420 rl_reset_terminal (term);
423 rl_forced_update_display ();
428 old_sigwinch != (SigHandler *)SIG_IGN &&
429 old_sigwinch != (SigHandler *)SIG_DFL)
430 (*old_sigwinch)(sig, code, scp);
432 #endif /* SIGWINCH */
434 #ifdef HANDLE_SIGNALS
435 /* Interrupt handling. */
436 static SigHandler *old_int = (SigHandler *)NULL,
437 *old_tstp = (SigHandler *)NULL,
438 *old_ttou = (SigHandler *)NULL,
439 *old_ttin = (SigHandler *)NULL,
440 *old_cont = (SigHandler *)NULL;
442 /* Handle an interrupt character. */
444 rl_signal_handler (sig, code, scp)
446 struct sigcontext *scp;
448 static rl_prep_terminal (), rl_deprep_terminal ();
463 rl_clean_up_for_exit ();
464 rl_deprep_terminal ();
466 rl_pending_input = 0;
468 kill (getpid (), sig);
478 old_int = (SigHandler *)signal (SIGINT, rl_signal_handler);
479 if (old_int == (SigHandler *)SIG_IGN)
480 signal (SIGINT, SIG_IGN);
483 old_tstp = (SigHandler *)signal (SIGTSTP, rl_signal_handler);
484 if (old_tstp == (SigHandler *)SIG_IGN)
485 signal (SIGTSTP, SIG_IGN);
488 old_ttou = (SigHandler *)signal (SIGTTOU, rl_signal_handler);
489 old_ttin = (SigHandler *)signal (SIGTTIN, rl_signal_handler);
491 if (old_tstp == (SigHandler *)SIG_IGN)
493 signal (SIGTTOU, SIG_IGN);
494 signal (SIGTTIN, SIG_IGN);
499 old_sigwinch = (SigHandler *)signal (SIGWINCH, rl_handle_sigwinch);
505 signal (SIGINT, old_int);
508 signal (SIGTSTP, old_tstp);
512 signal (SIGTTOU, old_ttou);
513 signal (SIGTTIN, old_ttin);
517 signal (SIGWINCH, old_sigwinch);
520 #endif /* HANDLE_SIGNALS */
523 /* **************************************************************** */
525 /* Character Input Buffering */
527 /* **************************************************************** */
529 /* If the terminal was in xoff state when we got to it, then xon_char
530 contains the character that is supposed to start it again. */
531 static int xon_char, xoff_state;
532 static int pop_index = 0, push_index = 0, ibuffer_len = 511;
533 static unsigned char ibuffer[512];
535 /* Non-null means it is a pointer to a function to run while waiting for
537 Function *rl_event_hook = (Function *)NULL;
539 #define any_typein (push_index != pop_index)
541 /* Add KEY to the buffer of characters to be read. */
548 rl_pending_input = EOF;
550 ibuffer[push_index++] = key;
551 if (push_index >= ibuffer_len)
555 /* Return the amount of space available in the
556 buffer for stuffing characters. */
560 if (pop_index > push_index)
561 return (pop_index - push_index);
563 return (ibuffer_len - (push_index - pop_index));
566 /* Get a key from the buffer of characters to be read.
567 Return the key in KEY.
568 Result is KEY if there was a key, or 0 if there wasn't. */
573 if (push_index == pop_index)
576 *key = ibuffer[pop_index++];
578 if (pop_index >= ibuffer_len)
584 /* Stuff KEY into the *front* of the input buffer.
585 Returns non-zero if successful, zero if there is
586 no space left in the buffer. */
591 if (ibuffer_space ())
595 pop_index = ibuffer_len - 1;
596 ibuffer[pop_index] = key;
602 /* If a character is available to be read, then read it
603 and stuff it into IBUFFER. Otherwise, just return. */
606 int tty = fileno (in_stream);
607 register int tem, result = -1;
612 result = ioctl (tty, FIONREAD, &chars_avail);
617 fcntl (tty, F_SETFL, O_NDELAY);
618 chars_avail = read (tty, &input, 1);
619 fcntl (tty, F_SETFL, 0);
620 if (chars_avail == -1 && errno == EAGAIN)
624 tem = ibuffer_space ();
626 if (chars_avail > tem)
629 /* One cannot read all of the available input. I can only read a single
630 character at a time, or else programs which require input can be
631 thwarted. If the buffer is larger than one character, I lose.
633 if (tem < ibuffer_len)
638 while (chars_avail--)
639 rl_stuff_char (rl_getc (in_stream));
644 rl_stuff_char (input);
648 /* Read a key, including pending input. */
654 rl_key_sequence_length++;
656 if (rl_pending_input)
658 c = rl_pending_input;
659 rl_pending_input = 0;
663 static int next_macro_key ();
665 /* If input is coming from a macro, then use that. */
666 if (c = next_macro_key ())
669 /* If the user has an event function, then call it periodically. */
672 while (rl_event_hook && !rl_get_char (&c))
680 if (!rl_get_char (&c))
681 c = rl_getc (in_stream);
685 #ifdef NEVER /* This breaks supdup to 4.0.3c machines. */
687 /* Ugh. But I can't think of a better way. */
688 if (xoff_state && c == xon_char)
690 ioctl (fileno (in_stream), TIOCSTART, 0);
692 return (rl_read_key ());
694 #endif /* TIOCSTART */
700 /* I'm beginning to hate the declaration rules for various compilers. */
701 static void add_macro_char ();
703 /* Do the command associated with KEY in MAP.
704 If the associated command is really a keymap, then read
705 another key, and dispatch into that map. */
706 rl_dispatch (key, map)
711 if (defining_kbd_macro)
712 add_macro_char (key);
714 if (key > 127 && key < 256)
716 if (map[ESC].type == ISKMAP)
718 map = (Keymap)map[ESC].function;
720 rl_dispatch (key, map);
727 switch (map[key].type)
731 Function *func = map[key].function;
733 if (func != (Function *)NULL)
735 /* Special case rl_do_lowercase_version (). */
736 if (func == rl_do_lowercase_version)
738 rl_dispatch (to_lower (key), map);
742 (*map[key].function)(rl_numeric_arg * arg_sign, key);
753 if (map[key].function != (Function *)NULL)
757 rl_key_sequence_length++;
758 newkey = rl_read_key ();
759 rl_dispatch (newkey, (Keymap)map[key].function);
769 if (map[key].function != (Function *)NULL)
771 static with_macro_input ();
772 char *macro = savestring ((char *)map[key].function);
774 with_macro_input (macro);
780 /* If we have input pending, then the last command was a prefix
781 command. Don't change the state of rl_last_func. */
782 if (!rl_pending_input)
783 rl_last_func = map[key].function;
787 /* **************************************************************** */
789 /* Hacking Keyboard Macros */
791 /* **************************************************************** */
793 /* The currently executing macro string. If this is non-zero,
794 then it is a malloc ()'ed string where input is coming from. */
795 static char *executing_macro = (char *)NULL;
797 /* The offset in the above string to the next character to be read. */
798 static int executing_macro_index = 0;
800 /* The current macro string being built. Characters get stuffed
801 in here by add_macro_char (). */
802 static char *current_macro = (char *)NULL;
804 /* The size of the buffer allocated to current_macro. */
805 static int current_macro_size = 0;
807 /* The index at which characters are being added to current_macro. */
808 static int current_macro_index = 0;
810 /* A structure used to save nested macro strings.
811 It is a linked list of string/index for each saved macro. */
813 struct saved_macro *next;
818 /* The list of saved macros. */
819 struct saved_macro *macro_list = (struct saved_macro *)NULL;
821 /* Forward declarations of static functions. Thank you C. */
822 static void push_executing_macro (), pop_executing_macro ();
824 /* This one has to be declared earlier in the file. */
825 /* static void add_macro_char (); */
827 /* Set up to read subsequent input from STRING.
828 STRING is free ()'ed when we are done with it. */
830 with_macro_input (string)
833 push_executing_macro ();
834 executing_macro = string;
835 executing_macro_index = 0;
838 /* Return the next character available from a macro, or 0 if
839 there are no macro characters. */
843 if (!executing_macro)
846 if (!executing_macro[executing_macro_index])
848 pop_executing_macro ();
849 return (next_macro_key ());
852 return (executing_macro[executing_macro_index++]);
855 /* Save the currently executing macro on a stack of saved macros. */
857 push_executing_macro ()
859 struct saved_macro *saver;
861 saver = (struct saved_macro *)xmalloc (sizeof (struct saved_macro));
862 saver->next = macro_list;
863 saver->index = executing_macro_index;
864 saver->string = executing_macro;
869 /* Discard the current macro, replacing it with the one
870 on the top of the stack of saved macros. */
872 pop_executing_macro ()
875 free (executing_macro);
877 executing_macro = (char *)NULL;
878 executing_macro_index = 0;
882 struct saved_macro *disposer = macro_list;
883 executing_macro = macro_list->string;
884 executing_macro_index = macro_list->index;
885 macro_list = macro_list->next;
890 /* Add a character to the macro being built. */
895 if (current_macro_index + 1 >= current_macro_size)
898 current_macro = (char *)xmalloc (current_macro_size = 25);
901 (char *)xrealloc (current_macro, current_macro_size += 25);
904 current_macro[current_macro_index++] = c;
905 current_macro[current_macro_index] = '\0';
908 /* Begin defining a keyboard macro.
909 Keystrokes are recorded as they are executed.
910 End the definition with rl_end_kbd_macro ().
911 If a numeric argument was explicitly typed, then append this
912 definition to the end of the existing macro, and start by
913 re-executing the existing macro. */
914 rl_start_kbd_macro (ignore1, ignore2)
915 int ignore1, ignore2;
917 if (defining_kbd_macro)
923 with_macro_input (savestring (current_macro));
926 current_macro_index = 0;
928 defining_kbd_macro = 1;
931 /* Stop defining a keyboard macro.
932 A numeric argument says to execute the macro right now,
933 that many times, counting the definition as the first time. */
934 rl_end_kbd_macro (count, ignore)
937 if (!defining_kbd_macro)
940 current_macro_index -= (rl_key_sequence_length - 1);
941 current_macro[current_macro_index] = '\0';
943 defining_kbd_macro = 0;
945 rl_call_last_kbd_macro (--count, 0);
948 /* Execute the most recently defined keyboard macro.
949 COUNT says how many times to execute it. */
950 rl_call_last_kbd_macro (count, ignore)
957 with_macro_input (savestring (current_macro));
961 /* **************************************************************** */
963 /* Initializations */
965 /* **************************************************************** */
967 /* Initliaze readline (and terminal if not already). */
970 extern char *rl_display_prompt;
972 /* If we have never been called before, initialize the
973 terminal and data structures. */
976 readline_initialize_everything ();
980 /* Initalize the current line information. */
981 rl_point = rl_end = 0;
982 the_line = rl_line_buffer;
985 /* We aren't done yet. We haven't even gotten started yet! */
988 /* Tell the history routines what is going on. */
989 start_using_history ();
991 /* Make the display buffer match the state of the line. */
993 extern char *rl_display_prompt;
994 extern int forced_display;
998 rl_display_prompt = rl_prompt ? rl_prompt : "";
1002 /* No such function typed yet. */
1003 rl_last_func = (Function *)NULL;
1005 /* Parsing of key-bindings begins in an enabled state. */
1006 parsing_conditionalized_out = 0;
1009 /* Initialize the entire state of the world. */
1010 readline_initialize_everything ()
1012 /* Find out if we are running in Emacs. */
1013 running_in_emacs = (char *)getenv ("EMACS");
1015 /* Allocate data structures. */
1016 if (!rl_line_buffer)
1018 (char *)xmalloc (rl_line_buffer_len = DEFAULT_BUFFER_SIZE);
1020 /* Initialize the terminal interface. */
1021 init_terminal_io ((char *)NULL);
1023 /* Bind tty characters to readline functions. */
1024 readline_default_bindings ();
1026 /* Initialize the function names. */
1027 rl_initialize_funmap ();
1029 /* Read in the init file. */
1030 rl_read_init_file ((char *)NULL);
1032 /* If the completion parser's default word break characters haven't
1033 been set yet, then do so now. */
1035 extern char *rl_completer_word_break_characters;
1036 extern char *rl_basic_word_break_characters;
1038 if (rl_completer_word_break_characters == (char *)NULL)
1039 rl_completer_word_break_characters = rl_basic_word_break_characters;
1043 /* If this system allows us to look at the values of the regular
1044 input editing characters, then bind them to their readline
1046 readline_default_bindings ()
1049 #ifdef NEW_TTY_DRIVER
1050 struct sgttyb ttybuff;
1051 int tty = fileno (rl_instream);
1053 if (ioctl (tty, TIOCGETP, &ttybuff) != -1)
1055 int erase = ttybuff.sg_erase, kill = ttybuff.sg_kill;
1057 if (erase != -1 && keymap[erase].type == ISFUNC)
1058 keymap[erase].function = rl_rubout;
1060 if (kill != -1 && keymap[kill].type == ISFUNC)
1061 keymap[kill].function = rl_unix_line_discard;
1068 if (ioctl (tty, TIOCGLTC, <) != -1)
1070 int erase = lt.t_werasc, nextc = lt.t_lnextc;
1072 if (erase != -1 && keymap[erase].type == ISFUNC)
1073 keymap[erase].function = rl_unix_word_rubout;
1075 if (nextc != -1 && keymap[nextc].type == ISFUNC)
1076 keymap[nextc].function = rl_quoted_insert;
1079 #endif /* TIOCGLTC */
1080 #else /* not NEW_TTY_DRIVER */
1081 struct termio ttybuff;
1082 int tty = fileno (rl_instream);
1084 if (ioctl (tty, TCGETA, &ttybuff) != -1)
1086 int erase = ttybuff.c_cc[VERASE];
1087 int kill = ttybuff.c_cc[VKILL];
1089 if (erase != -1 && keymap[(unsigned char)erase].type == ISFUNC)
1090 keymap[(unsigned char)erase].function = rl_rubout;
1092 if (kill != -1 && keymap[(unsigned char)kill].type == ISFUNC)
1093 keymap[(unsigned char)kill].function = rl_unix_line_discard;
1095 #endif /* NEW_TTY_DRIVER */
1099 /* **************************************************************** */
1101 /* Numeric Arguments */
1103 /* **************************************************************** */
1105 /* Handle C-u style numeric args, as well as M--, and M-digits. */
1107 /* Add the current digit to the argument in progress. */
1108 rl_digit_argument (ignore, key)
1111 rl_pending_input = key;
1115 /* What to do when you abort reading an argument. */
1116 rl_discard_argument ()
1119 rl_clear_message ();
1120 rl_init_argument ();
1123 /* Create a default argument. */
1126 rl_numeric_arg = arg_sign = 1;
1127 rl_explicit_arg = 0;
1130 /* C-u, universal argument. Multiply the current argument by 4.
1131 Read a key. If the key has nothing to do with arguments, then
1132 dispatch on it. If the key is the abort character then abort. */
1133 rl_universal_argument ()
1135 rl_numeric_arg *= 4;
1144 rl_message ("(arg: %d) ", arg_sign * rl_numeric_arg);
1145 key = c = rl_read_key ();
1147 if (keymap[c].type == ISFUNC &&
1148 keymap[c].function == rl_universal_argument)
1150 rl_numeric_arg *= 4;
1156 if (rl_explicit_arg)
1157 rl_numeric_arg = (rl_numeric_arg * 10) + (c - '0');
1159 rl_numeric_arg = (c - '0');
1160 rl_explicit_arg = 1;
1164 if (c == '-' && !rl_explicit_arg)
1171 rl_clear_message ();
1172 rl_dispatch (key, keymap);
1180 /* **************************************************************** */
1184 /* **************************************************************** */
1186 /* This is the stuff that is hard for me. I never seem to write good
1187 display routines in C. Let's see how I do this time. */
1189 /* (PWP) Well... Good for a simple line updater, but totally ignores
1190 the problems of input lines longer than the screen width.
1192 update_line and the code that calls it makes a multiple line,
1193 automatically wrapping line update. Carefull attention needs
1194 to be paid to the vertical position variables.
1196 handling of terminals with autowrap on (incl. DEC braindamage)
1197 could be improved a bit. Right now I just cheat and decrement
1198 screenwidth by one. */
1200 /* Keep two buffers; one which reflects the current contents of the
1201 screen, and the other to draw what we think the new contents should
1202 be. Then compare the buffers, and make whatever changes to the
1203 screen itself that we should. Finally, make the buffer that we
1204 just drew into be the one which reflects the current contents of the
1205 screen, and place the cursor where it belongs.
1207 Commands that want to can fix the display themselves, and then let
1208 this function know that the display has been fixed by setting the
1209 RL_DISPLAY_FIXED variable. This is good for efficiency. */
1211 /* Termcap variables: */
1212 extern char *term_up, *term_dc, *term_cr;
1213 extern int screenheight, screenwidth, terminal_can_insert;
1215 /* What YOU turn on when you have handled all redisplay yourself. */
1216 int rl_display_fixed = 0;
1218 /* The visible cursor position. If you print some text, adjust this. */
1222 /* The last left edge of text that was displayed. This is used when
1223 doing horizontal scrolling. It shifts in thirds of a screenwidth. */
1224 static int last_lmargin = 0;
1226 /* The line display buffers. One is the line currently displayed on
1227 the screen. The other is the line about to be displayed. */
1228 static char *visible_line = (char *)NULL;
1229 static char *invisible_line = (char *)NULL;
1231 /* Number of lines currently on screen minus 1. */
1234 /* A buffer for `modeline' messages. */
1237 /* Non-zero forces the redisplay even if we thought it was unnecessary. */
1238 int forced_display = 0;
1240 /* The stuff that gets printed out before the actual text of the line.
1241 This is usually pointing to rl_prompt. */
1242 char *rl_display_prompt = (char *)NULL;
1244 /* Default and initial buffer size. Can grow. */
1245 static int line_size = 1024;
1247 /* Non-zero means to always use horizontal scrolling in line display. */
1248 static int horizontal_scroll_mode = 0;
1250 /* Non-zero means to display an asterisk at the starts of history lines
1251 which have been modified. */
1252 static int mark_modified_lines = 0;
1254 /* I really disagree with this, but my boss (among others) insists that we
1255 support compilers that don't work. I don't think we are gaining by doing
1256 so; what is the advantage in producing better code if we can't use it? */
1257 /* The following two declarations belong inside the
1258 function block, not here. */
1259 static void move_cursor_relative ();
1260 static void output_some_chars ();
1261 static void output_character_function ();
1262 static int compare_strings ();
1264 /* Basic redisplay algorithm. */
1267 register int in, out, c, linenum;
1268 register char *line = invisible_line;
1270 int inv_botlin = 0; /* Number of lines in newly drawn buffer. */
1272 extern int readline_echoing_p;
1274 if (!readline_echoing_p)
1277 if (!rl_display_prompt)
1278 rl_display_prompt = "";
1280 if (!invisible_line)
1282 visible_line = (char *)xmalloc (line_size);
1283 invisible_line = (char *)xmalloc (line_size);
1284 line = invisible_line;
1285 for (in = 0; in < line_size; in++)
1287 visible_line[in] = 0;
1288 invisible_line[in] = 1;
1293 /* Draw the line into the buffer. */
1296 /* Mark the line as modified or not. We only do this for history
1299 if (mark_modified_lines && current_history () && rl_undo_list)
1305 /* If someone thought that the redisplay was handled, but the currently
1306 visible line has a different modification state than the one about
1307 to become visible, then correct the callers misconception. */
1308 if (visible_line[0] != invisible_line[0])
1309 rl_display_fixed = 0;
1311 strncpy (line + out, rl_display_prompt, strlen (rl_display_prompt));
1312 out += strlen (rl_display_prompt);
1315 for (in = 0; in < rl_end; in++)
1319 if (out + 1 >= line_size)
1322 visible_line = (char *)xrealloc (visible_line, line_size);
1323 invisible_line = (char *)xrealloc (invisible_line, line_size);
1324 line = invisible_line;
1334 line[out++] = c - 128;
1336 #define DISPLAY_TABS
1340 register int newout = (out | (int)7) + 1;
1341 while (out < newout)
1349 line[out++] = c + 64;
1358 /* PWP: now is when things get a bit hairy. The visible and invisible
1359 line buffers are really multiple lines, which would wrap every
1360 (screenwidth - 1) characters. Go through each in turn, finding
1361 the changed region and updating it. The line order is top to bottom. */
1363 /* If we can move the cursor up and down, then use multiple lines,
1364 otherwise, let long lines display in a single terminal line, and
1365 horizontally scroll it. */
1367 if (!horizontal_scroll_mode && term_up && *term_up)
1369 int total_screen_chars = (screenwidth * screenheight);
1371 if (!rl_display_fixed || forced_display)
1375 /* If we have more than a screenful of material to display, then
1376 only display a screenful. We should display the last screen,
1377 not the first. I'll fix this in a minute. */
1378 if (out >= total_screen_chars)
1379 out = total_screen_chars - 1;
1381 /* Number of screen lines to display. */
1382 inv_botlin = out / screenwidth;
1384 /* For each line in the buffer, do the updating display. */
1385 for (linenum = 0; linenum <= inv_botlin; linenum++)
1386 update_line (linenum > vis_botlin ? ""
1387 : &visible_line[linenum * screenwidth],
1388 &invisible_line[linenum * screenwidth],
1391 /* We may have deleted some lines. If so, clear the left over
1392 blank ones at the bottom out. */
1393 if (vis_botlin > inv_botlin)
1396 for (; linenum <= vis_botlin; linenum++)
1398 tt = &visible_line[linenum * screenwidth];
1399 move_vert (linenum);
1400 move_cursor_relative (0, tt);
1401 clear_to_eol ((linenum == vis_botlin)?
1402 strlen (tt) : screenwidth);
1405 vis_botlin = inv_botlin;
1407 /* Move the cursor where it should be. */
1408 move_vert (c_pos / screenwidth);
1409 move_cursor_relative (c_pos % screenwidth,
1410 &invisible_line[(c_pos / screenwidth) * screenwidth]);
1413 else /* Do horizontal scrolling. */
1417 /* Always at top line. */
1420 /* If the display position of the cursor would be off the edge
1421 of the screen, start the display of this line at an offset that
1422 leaves the cursor on the screen. */
1423 if (c_pos - last_lmargin > screenwidth - 2)
1424 lmargin = (c_pos / (screenwidth / 3) - 2) * (screenwidth / 3);
1425 else if (c_pos - last_lmargin < 1)
1426 lmargin = ((c_pos - 1) / (screenwidth / 3)) * (screenwidth / 3);
1428 lmargin = last_lmargin;
1430 /* If the first character on the screen isn't the first character
1431 in the display line, indicate this with a special character. */
1433 line[lmargin] = '<';
1435 if (lmargin + screenwidth < out)
1436 line[lmargin + screenwidth - 1] = '>';
1438 if (!rl_display_fixed || forced_display || lmargin != last_lmargin)
1441 update_line (&visible_line[last_lmargin],
1442 &invisible_line[lmargin], 0);
1444 move_cursor_relative (c_pos - lmargin, &invisible_line[lmargin]);
1445 last_lmargin = lmargin;
1448 fflush (out_stream);
1450 /* Swap visible and non-visible lines. */
1452 char *temp = visible_line;
1453 visible_line = invisible_line;
1454 invisible_line = temp;
1455 rl_display_fixed = 0;
1459 /* PWP: update_line() is based on finding the middle difference of each
1460 line on the screen; vis:
1462 /old first difference
1463 /beginning of line | /old last same /old EOL
1465 old: eddie> Oh, my little gruntle-buggy is to me, as lurgid as
1466 new: eddie> Oh, my little buggy says to me, as lurgid as
1468 \beginning of line | \new last same \new end of line
1469 \new first difference
1471 All are character pointers for the sake of speed. Special cases for
1472 no differences, as well as for end of line additions must be handeled.
1474 Could be made even smarter, but this works well enough */
1476 update_line (old, new, current_line)
1477 register char *old, *new;
1480 register char *ofd, *ols, *oe, *nfd, *nls, *ne;
1481 int lendiff, wsatend;
1483 /* Find first difference. */
1484 for (ofd = old, nfd = new;
1485 (ofd - old < screenwidth) && *ofd && (*ofd == *nfd);
1489 /* Move to the end of the screen line. */
1490 for (oe = ofd; ((oe - old) < screenwidth) && *oe; oe++);
1491 for (ne = nfd; ((ne - new) < screenwidth) && *ne; ne++);
1493 /* If no difference, continue to next line. */
1494 if (ofd == oe && nfd == ne)
1497 wsatend = 1; /* flag for trailing whitespace */
1498 ols = oe - 1; /* find last same */
1500 while ((ols > ofd) && (nls > nfd) && (*ols == *nls))
1513 else if (*ols != *nls)
1515 if (*ols) /* don't step past the NUL */
1521 move_vert (current_line);
1522 move_cursor_relative (ofd - old, old);
1524 /* if (len (new) > len (old)) */
1525 lendiff = (nls - nfd) - (ols - ofd);
1527 /* Insert (diff(len(old),len(new)) ch */
1530 if (terminal_can_insert)
1532 extern char *term_IC;
1534 /* Sometimes it is cheaper to print the characters rather than
1535 use the terminal's capabilities. */
1536 if ((2 * (ne - nfd)) < lendiff && !term_IC)
1538 output_some_chars (nfd, (ne - nfd));
1539 last_c_pos += (ne - nfd);
1545 insert_some_chars (nfd, lendiff);
1546 last_c_pos += lendiff;
1550 /* At the end of a line the characters do not have to
1551 be "inserted". They can just be placed on the screen. */
1552 output_some_chars (nfd, lendiff);
1553 last_c_pos += lendiff;
1555 /* Copy (new) chars to screen from first diff to last match. */
1556 if (((nls - nfd) - lendiff) > 0)
1558 output_some_chars (&nfd[lendiff], ((nls - nfd) - lendiff));
1559 last_c_pos += ((nls - nfd) - lendiff);
1564 { /* cannot insert chars, write to EOL */
1565 output_some_chars (nfd, (ne - nfd));
1566 last_c_pos += (ne - nfd);
1569 else /* Delete characters from line. */
1571 /* If possible and inexpensive to use terminal deletion, then do so. */
1572 if (term_dc && (2 * (ne - nfd)) >= (-lendiff))
1575 delete_chars (-lendiff); /* delete (diff) characters */
1577 /* Copy (new) chars to screen from first diff to last match */
1578 if ((nls - nfd) > 0)
1580 output_some_chars (nfd, (nls - nfd));
1581 last_c_pos += (nls - nfd);
1584 /* Otherwise, print over the existing material. */
1587 output_some_chars (nfd, (ne - nfd));
1588 last_c_pos += (ne - nfd);
1589 clear_to_eol ((oe - old) - (ne - new));
1594 /* (PWP) tell the update routines that we have moved onto a
1595 new (empty) line. */
1599 visible_line[0] = '\0';
1601 last_c_pos = last_v_pos = 0;
1602 vis_botlin = last_lmargin = 0;
1605 /* Actually update the display, period. */
1606 rl_forced_update_display ()
1610 register char *temp = visible_line;
1612 while (*temp) *temp++ = '\0';
1619 /* Move the cursor from last_c_pos to NEW, which are buffer indices.
1620 DATA is the contents of the screen line of interest; i.e., where
1621 the movement is being done. */
1623 move_cursor_relative (new, data)
1629 /* It may be faster to output a CR, and then move forwards instead
1630 of moving backwards. */
1631 if (new + 1 < last_c_pos - new)
1633 tputs (term_cr, 1, output_character_function);
1637 if (last_c_pos == new) return;
1639 if (last_c_pos < new)
1641 /* Move the cursor forward. We do it by printing the command
1642 to move the cursor forward if there is one, else print that
1643 portion of the output buffer again. Which is cheaper? */
1645 /* The above comment is left here for posterity. It is faster
1646 to print one character (non-control) than to print a control
1647 sequence telling the terminal to move forward one character.
1648 That kind of control is for people who don't know what the
1649 data is underneath the cursor. */
1650 #ifdef HACK_TERMCAP_MOTION
1651 extern char *term_forward_char;
1653 if (term_forward_char)
1654 for (i = last_c_pos; i < new; i++)
1655 tputs (term_forward_char, 1, output_character_function);
1657 for (i = last_c_pos; i < new; i++)
1658 putc (data[i], out_stream);
1660 for (i = last_c_pos; i < new; i++)
1661 putc (data[i], out_stream);
1662 #endif /* HACK_TERMCAP_MOTION */
1665 backspace (last_c_pos - new);
1669 /* PWP: move the cursor up or down. */
1673 void output_character_function ();
1674 register int delta, i;
1676 if (last_v_pos == to) return;
1678 if (to > screenheight)
1681 if ((delta = to - last_v_pos) > 0)
1683 for (i = 0; i < delta; i++)
1684 putc ('\n', out_stream);
1685 tputs (term_cr, 1, output_character_function);
1686 last_c_pos = 0; /* because crlf() will do \r\n */
1690 if (term_up && *term_up)
1691 for (i = 0; i < -delta; i++)
1692 tputs (term_up, 1, output_character_function);
1694 last_v_pos = to; /* now to is here */
1697 /* Physically print C on out_stream. This is for functions which know
1698 how to optimize the display. */
1704 fprintf (out_stream, "M-");
1709 if (c < 32 && c != '\t')
1718 putc (c, out_stream);
1719 fflush (out_stream);
1724 rl_character_len (c, pos)
1725 register int c, pos;
1727 if (c < ' ' || c > 126)
1730 return (((pos | (int)7) + 1) - pos);
1739 rl_character_len (c)
1742 if (c < ' ' || c > 126)
1747 #endif /* DISPLAY_TAB */
1749 /* How to print things in the "echo-area". The prompt is treated as a
1751 rl_message (string, arg1, arg2)
1754 sprintf (msg_buf, string, arg1, arg2);
1755 rl_display_prompt = msg_buf;
1759 /* How to clear things from the "echo-area". */
1762 rl_display_prompt = rl_prompt;
1766 /* **************************************************************** */
1768 /* Terminal and Termcap */
1770 /* **************************************************************** */
1772 static char *term_buffer = (char *)NULL;
1773 static char *term_string_buffer = (char *)NULL;
1775 /* Non-zero means this terminal can't really do anything. */
1781 /* Some strings to control terminal actions. These are output by tputs (). */
1782 char *term_goto, *term_clreol, *term_cr, *term_clrpag, *term_backspace;
1784 int screenwidth, screenheight;
1786 /* Non-zero if we determine that the terminal can do character insertion. */
1787 int terminal_can_insert = 0;
1789 /* How to insert characters. */
1790 char *term_im, *term_ei, *term_ic, *term_ip, *term_IC;
1792 /* How to delete characters. */
1793 char *term_dc, *term_DC;
1795 #ifdef HACK_TERMCAP_MOTION
1796 char *term_forward_char;
1797 #endif /* HACK_TERMCAP_MOTION */
1799 /* How to go up a line. */
1802 /* Re-initialize the terminal considering that the TERM/TERMCAP variable
1804 rl_reset_terminal (terminal_name)
1805 char *terminal_name;
1807 init_terminal_io (terminal_name);
1810 init_terminal_io (terminal_name)
1811 char *terminal_name;
1813 char *term = (terminal_name? terminal_name : (char *)getenv ("TERM"));
1814 char *tgetstr (), *buffer;
1817 if (!term_string_buffer)
1818 term_string_buffer = (char *)xmalloc (2048);
1821 term_buffer = (char *)xmalloc (2048);
1823 buffer = term_string_buffer;
1825 term_clrpag = term_cr = term_clreol = (char *)NULL;
1830 if (tgetent (term_buffer, term) < 0)
1836 PC = tgetstr ("pc", &buffer)? *buffer : 0;
1838 term_backspace = tgetstr ("le", &buffer);
1840 term_cr = tgetstr ("cr", &buffer);
1841 term_clreol = tgetstr ("ce", &buffer);
1842 term_clrpag = tgetstr ("cl", &buffer);
1847 #ifdef HACK_TERMCAP_MOTION
1848 term_forward_char = tgetstr ("nd", &buffer);
1849 #endif /* HACK_TERMCAP_MOTION */
1851 screenwidth = tgetnum ("co");
1852 if (screenwidth <= 0)
1854 screenwidth--; /* PWP: avoid autowrap bugs */
1856 screenheight = tgetnum ("li");
1857 if (screenheight <= 0)
1860 term_im = tgetstr ("im", &buffer);
1861 term_ei = tgetstr ("ei", &buffer);
1862 term_IC = tgetstr ("IC", &buffer);
1863 term_ic = tgetstr ("ic", &buffer);
1865 /* "An application program can assume that the terminal can do
1866 character insertion if *any one of* the capabilities `IC',
1867 `im', `ic' or `ip' is provided." But we can't do anything if
1868 only `ip' is provided, so... */
1869 terminal_can_insert = (term_IC || term_im || term_ic);
1871 term_up = tgetstr ("up", &buffer);
1872 term_dc = tgetstr ("dc", &buffer);
1873 term_DC = tgetstr ("DC", &buffer);
1876 /* A function for the use of tputs () */
1878 output_character_function (c)
1881 putc (c, out_stream);
1884 /* Write COUNT characters from STRING to the output stream. */
1886 output_some_chars (string, count)
1890 fwrite (string, 1, count, out_stream);
1894 /* Delete COUNT characters from the display line. */
1896 delete_chars (count)
1899 if (count > screenwidth)
1902 if (term_DC && *term_DC)
1904 char *tgoto (), *buffer;
1905 buffer = tgoto (term_DC, 0, count);
1906 tputs (buffer, 1, output_character_function);
1910 if (term_dc && *term_dc)
1912 tputs (term_dc, 1, output_character_function);
1916 /* Insert COUNT character from STRING to the output stream. */
1918 insert_some_chars (string, count)
1922 /* If IC is defined, then we do not have to "enter" insert mode. */
1925 char *tgoto (), *buffer;
1926 buffer = tgoto (term_IC, 0, count);
1927 tputs (buffer, 1, output_character_function);
1928 output_some_chars (string, count);
1934 /* If we have to turn on insert-mode, then do so. */
1935 if (term_im && *term_im)
1936 tputs (term_im, 1, output_character_function);
1938 /* If there is a special command for inserting characters, then
1939 use that first to open up the space. */
1940 if (term_ic && *term_ic)
1942 for (i = count; i--; )
1943 tputs (term_ic, 1, output_character_function);
1946 /* Print the text. */
1947 output_some_chars (string, count);
1949 /* If there is a string to turn off insert mode, we had best use
1951 if (term_ei && *term_ei)
1952 tputs (term_ei, 1, output_character_function);
1956 /* Move the cursor back. */
1963 for (i = 0; i < count; i++)
1964 tputs (term_backspace, 1, output_character_function);
1966 for (i = 0; i < count; i++)
1967 putc ('\b', out_stream);
1970 /* Move to the start of the next line. */
1973 tputs (term_cr, 1, output_character_function);
1974 putc ('\n', out_stream);
1977 /* Clear to the end of the line. COUNT is the minimum
1978 number of character spaces to clear, */
1979 clear_to_eol (count)
1984 tputs (term_clreol, 1, output_character_function);
1990 /* Do one more character space. */
1993 for (i = 0; i < count; i++)
1994 putc (' ', out_stream);
2001 /* **************************************************************** */
2003 /* Saving and Restoring the TTY */
2005 /* **************************************************************** */
2007 /* Non-zero means that the terminal is in a prepped state. */
2008 static int terminal_prepped = 0;
2010 #ifdef NEW_TTY_DRIVER
2012 /* Standard flags, including ECHO. */
2013 static int original_tty_flags = 0;
2015 /* Local mode flags, like LPASS8. */
2016 static int local_mode_flags = 0;
2018 /* Terminal characters. This has C-s and C-q in it. */
2019 static struct tchars original_tchars;
2021 /* Local special characters. This has the interrupt characters in it. */
2022 static struct ltchars original_ltchars;
2024 /* We use this to get and set the tty_flags. */
2025 static struct sgttyb the_ttybuff;
2027 /* Put the terminal in CBREAK mode so that we can detect key presses. */
2031 int tty = fileno (rl_instream);
2032 int oldmask = sigblock (sigmask (SIGINT));
2034 if (!terminal_prepped)
2036 /* We always get the latest tty values. Maybe stty changed them. */
2037 ioctl (tty, TIOCGETP, &the_ttybuff);
2038 original_tty_flags = the_ttybuff.sg_flags;
2040 readline_echoing_p = (original_tty_flags & ECHO);
2043 #if defined (TIOCLGET)
2044 ioctl (tty, TIOCLGET, &local_mode_flags);
2047 /* If this terminal doesn't care how the 8th bit is used,
2048 then we can use it for the meta-key.
2049 We check by seeing if BOTH odd and even parity are allowed. */
2050 if ((the_ttybuff.sg_flags & ODDP) && (the_ttybuff.sg_flags & EVENP))
2053 the_ttybuff.sg_flags |= PASS8;
2055 /* Hack on local mode flags if we can. */
2056 #if defined (TIOCLGET) && defined (LPASS8)
2059 flags = local_mode_flags | LPASS8;
2060 ioctl (tty, TIOCLSET, &flags);
2069 ioctl (tty, TIOCGETC, &original_tchars);
2070 bcopy (&original_tchars, &temp, sizeof (struct tchars));
2072 /* Get rid of C-s and C-q.
2073 We remember the value of startc (C-q) so that if the terminal is in
2074 xoff state, the user can xon it by pressing that character. */
2075 xon_char = temp.t_startc;
2079 /* If there is an XON character, bind it to restart the output. */
2081 rl_bind_key (xon_char, rl_restart_output);
2083 /* If there is an EOF char, bind eof_char to it. */
2084 if (temp.t_eofc != -1)
2085 eof_char = temp.t_eofc;
2088 /* Get rid of C-\ and C-c. */
2089 temp.t_intrc = temp.t_quitc = -1;
2092 ioctl (tty, TIOCSETC, &temp);
2094 #endif /* TIOCGETC */
2098 struct ltchars temp;
2100 ioctl (tty, TIOCGLTC, &original_ltchars);
2101 bcopy (&original_ltchars, &temp, sizeof (struct ltchars));
2103 /* Make the interrupt keys go away. Just enough to make people happy. */
2104 temp.t_dsuspc = -1; /* C-y */
2105 temp.t_lnextc = -1; /* C-v */
2107 ioctl (tty, TIOCSLTC, &temp);
2109 #endif /* TIOCGLTC */
2111 the_ttybuff.sg_flags &= ~ECHO;
2112 the_ttybuff.sg_flags |= CBREAK;
2113 ioctl (tty, TIOCSETN, &the_ttybuff);
2115 terminal_prepped = 1;
2117 sigsetmask (oldmask);
2120 /* Restore the terminal to its original state. */
2122 rl_deprep_terminal ()
2124 int tty = fileno (rl_instream);
2125 int oldmask = sigblock (sigmask (SIGINT));
2127 if (terminal_prepped)
2129 the_ttybuff.sg_flags = original_tty_flags;
2130 ioctl (tty, TIOCSETN, &the_ttybuff);
2131 readline_echoing_p = 1;
2133 #if defined (TIOCLGET)
2134 ioctl (tty, TIOCLSET, &local_mode_flags);
2138 ioctl (tty, TIOCSLTC, &original_ltchars);
2142 ioctl (tty, TIOCSETC, &original_tchars);
2144 terminal_prepped = 0;
2147 sigsetmask (oldmask);
2150 #else /* !defined (NEW_TTY_DRIVER) */
2156 #if !defined (VTIME)
2160 static struct termio otio;
2165 int tty = fileno (rl_instream);
2168 ioctl (tty, TCGETA, &tio);
2169 ioctl (tty, TCGETA, &otio);
2171 readline_echoing_p = (tio.c_lflag & ECHO);
2173 tio.c_lflag &= ~(ICANON|ECHO);
2174 tio.c_iflag &= ~(IXON|IXOFF|IXANY|ISTRIP|INPCK);
2176 #if !defined (HANDLE_SIGNALS)
2177 tio.c_lflag &= ~ISIG;
2181 tio.c_cc[VTIME] = 0;
2182 ioctl (tty, TCSETAW, &tio);
2183 ioctl (tty, TCXONC, 1); /* Simulate a ^Q. */
2187 rl_deprep_terminal ()
2189 int tty = fileno (rl_instream);
2190 ioctl (tty, TCSETAW, &otio);
2191 ioctl (tty, TCXONC, 1); /* Simulate a ^Q. */
2193 #endif /* NEW_TTY_DRIVER */
2196 /* **************************************************************** */
2198 /* Utility Functions */
2200 /* **************************************************************** */
2202 /* Return 0 if C is not a member of the class of characters that belong
2203 in words, or 1 if it is. */
2205 int allow_pathname_alphabetic_chars = 0;
2206 char *pathname_alphabetic_chars = "/-_=~.#$";
2213 if (pure_alphabetic (c) || (numeric (c)))
2216 if (allow_pathname_alphabetic_chars)
2217 return ((int)rindex (pathname_alphabetic_chars, c));
2222 /* Return non-zero if C is a numeric character. */
2227 return (c >= '0' && c <= '9');
2230 /* Ring the terminal bell. */
2234 if (readline_echoing_p)
2236 fprintf (stderr, "\007");
2242 /* How to abort things. */
2246 rl_clear_message ();
2247 rl_init_argument ();
2248 rl_pending_input = 0;
2250 defining_kbd_macro = 0;
2251 while (executing_macro)
2252 pop_executing_macro ();
2254 longjmp (readline_top_level, 1);
2257 /* Return a copy of the string between FROM and TO.
2258 FROM is inclusive, TO is not. */
2263 register int length;
2266 /* Fix it if the caller is confused. */
2274 copy = (char *)xmalloc (1 + length);
2275 strncpy (copy, the_line + from, length);
2276 copy[length] = '\0';
2281 /* **************************************************************** */
2283 /* Insert and Delete */
2285 /* **************************************************************** */
2288 /* Insert a string of text into the line at point. This is the only
2289 way that you should do insertion. rl_insert () calls this
2291 rl_insert_text (string)
2294 extern int doing_an_undo;
2295 register int i, l = strlen (string);
2296 while (rl_end + l >= rl_line_buffer_len)
2299 (char *)xrealloc (rl_line_buffer,
2300 rl_line_buffer_len += DEFAULT_BUFFER_SIZE);
2301 the_line = rl_line_buffer;
2304 for (i = rl_end; i >= rl_point; i--)
2305 the_line[i + l] = the_line[i];
2306 strncpy (the_line + rl_point, string, l);
2308 /* Remember how to undo this if we aren't undoing something. */
2311 /* If possible and desirable, concatenate the undos. */
2312 if ((strlen (string) == 1) &&
2314 (rl_undo_list->what == UNDO_INSERT) &&
2315 (rl_undo_list->end == rl_point) &&
2316 (rl_undo_list->end - rl_undo_list->start < 20))
2317 rl_undo_list->end++;
2319 rl_add_undo (UNDO_INSERT, rl_point, rl_point + l, (char *)NULL);
2323 the_line[rl_end] = '\0';
2326 /* Delete the string between FROM and TO. FROM is
2327 inclusive, TO is not. */
2328 rl_delete_text (from, to)
2331 extern int doing_an_undo;
2332 register char *text;
2334 /* Fix it if the caller is confused. */
2340 text = rl_copy (from, to);
2341 strncpy (the_line + from, the_line + to, rl_end - to);
2343 /* Remember how to undo this delete. */
2345 rl_add_undo (UNDO_DELETE, from, to, text);
2349 rl_end -= (to - from);
2350 the_line[rl_end] = '\0';
2354 /* **************************************************************** */
2356 /* Readline character functions */
2358 /* **************************************************************** */
2360 /* This is not a gap editor, just a stupid line input routine. No hair
2361 is involved in writing any of the functions, and none should be. */
2365 rl_end is the place in the string that we would place '\0';
2366 i.e., it is always safe to place '\0' there.
2368 rl_point is the place in the string where the cursor is. Sometimes
2369 this is the same as rl_end.
2371 Any command that is called interactively receives two arguments.
2372 The first is a count: the numeric arg pased to this command.
2373 The second is the key which invoked this command.
2377 /* **************************************************************** */
2379 /* Movement Commands */
2381 /* **************************************************************** */
2383 /* Note that if you `optimize' the display for these functions, you cannot
2384 use said functions in other functions which do not do optimizing display.
2385 I.e., you will have to update the data base for rl_redisplay, and you
2386 might as well let rl_redisplay do that job. */
2388 /* Move forward COUNT characters. */
2393 rl_backward (-count);
2398 if (rl_point == (rl_end - (rl_editing_mode == vi_mode)))
2400 if (rl_point == rl_end)
2412 /* Move backward COUNT characters. */
2417 rl_forward (-count);
2432 /* Move to the beginning of the line. */
2438 /* Move to the end of the line. */
2444 /* Move forward a word. We do what Emacs does. */
2445 rl_forward_word (count)
2452 rl_backward_word (-count);
2458 if (rl_point == rl_end)
2461 /* If we are not in a word, move forward until we are in one.
2462 Then, move forward until we hit a non-alphabetic character. */
2463 c = the_line[rl_point];
2464 if (!alphabetic (c))
2466 while (++rl_point < rl_end)
2468 c = the_line[rl_point];
2469 if (alphabetic (c)) break;
2472 if (rl_point == rl_end) return;
2473 while (++rl_point < rl_end)
2475 c = the_line[rl_point];
2476 if (!alphabetic (c)) break;
2482 /* Move backward a word. We do what Emacs does. */
2483 rl_backward_word (count)
2490 rl_forward_word (-count);
2499 /* Like rl_forward_word (), except that we look at the characters
2500 just before point. */
2502 c = the_line[rl_point - 1];
2503 if (!alphabetic (c))
2507 c = the_line[rl_point - 1];
2508 if (alphabetic (c)) break;
2514 c = the_line[rl_point - 1];
2515 if (!alphabetic (c))
2523 /* Clear the current line. Numeric argument to C-l does this. */
2526 int curr_line = last_c_pos / screenwidth;
2527 extern char *term_clreol;
2529 move_vert(curr_line);
2530 move_cursor_relative (0, the_line); /* XXX is this right */
2533 tputs (term_clreol, 1, output_character_function);
2535 rl_forced_update_display ();
2536 rl_display_fixed = 1;
2539 /* C-l typed to a line without quoting clears the screen, and then reprints
2540 the prompt and the current input line. Given a numeric arg, redraw only
2541 the current line. */
2544 extern char *term_clrpag;
2546 if (rl_explicit_arg)
2553 tputs (term_clrpag, 1, output_character_function);
2557 rl_forced_update_display ();
2558 rl_display_fixed = 1;
2562 /* **************************************************************** */
2566 /* **************************************************************** */
2568 /* Insert the character C at the current location, moving point forward. */
2569 rl_insert (count, c)
2578 /* If we can optimize, then do it. But don't let people crash
2579 readline because of extra large arguments. */
2580 if (count > 1 && count < 1024)
2582 string = (char *)alloca (1 + count);
2584 for (i = 0; i < count; i++)
2588 rl_insert_text (string);
2596 string = (char *)alloca (1024 + 1);
2598 for (i = 0; i < 1024; i++)
2603 decreaser = (count > 1024 ? 1024 : count);
2604 string[decreaser] = '\0';
2605 rl_insert_text (string);
2611 /* We are inserting a single character.
2612 If there is pending input, then make a string of all of the
2613 pending characters that are bound to rl_insert, and insert
2620 string = (char *)alloca (ibuffer_len + 1);
2623 while ((t = rl_get_char (&key)) &&
2624 (keymap[key].type == ISFUNC &&
2625 keymap[key].function == rl_insert))
2629 rl_unget_char (key);
2632 rl_insert_text (string);
2637 /* Inserting a single character. */
2638 string = (char *)alloca (2);
2642 rl_insert_text (string);
2646 /* Insert the next typed character verbatim. */
2647 rl_quoted_insert (count)
2650 int c = rl_read_key ();
2651 rl_insert (count, c);
2654 /* Insert a tab character. */
2655 rl_tab_insert (count)
2658 rl_insert (count, '\t');
2661 /* What to do when a NEWLINE is pressed. We accept the whole line.
2662 KEY is the key that invoked this command. I guess it could have
2663 meaning in the future. */
2664 rl_newline (count, key)
2672 extern int vi_doing_insert;
2673 if (vi_doing_insert)
2675 rl_end_undo_group ();
2676 vi_doing_insert = 0;
2679 #endif /* VI_MODE */
2681 if (readline_echoing_p)
2683 move_vert (vis_botlin);
2686 fflush (out_stream);
2691 rl_clean_up_for_exit ()
2693 if (readline_echoing_p)
2695 move_vert (vis_botlin);
2697 fflush (out_stream);
2698 rl_restart_output ();
2702 /* What to do for some uppercase characters, like meta characters,
2703 and some characters appearing in emacs_ctlx_keymap. This function
2704 is just a stub, you bind keys to it and the code in rl_dispatch ()
2705 is special cased. */
2706 rl_do_lowercase_version (ignore1, ignore2)
2707 int ignore1, ignore2;
2711 /* Rubout the character behind point. */
2729 int orig_point = rl_point;
2730 rl_backward (count);
2731 rl_kill_text (orig_point, rl_point);
2735 int c = the_line[--rl_point];
2736 rl_delete_text (rl_point, rl_point + 1);
2738 if (rl_point == rl_end && alphabetic (c) && last_c_pos)
2741 putc (' ', out_stream);
2744 visible_line[last_c_pos] = '\0';
2750 /* Delete the character under the cursor. Given a numeric argument,
2751 kill that many characters instead. */
2752 rl_delete (count, invoking_key)
2753 int count, invoking_key;
2761 if (rl_point == rl_end)
2769 int orig_point = rl_point;
2771 rl_kill_text (orig_point, rl_point);
2772 rl_point = orig_point;
2775 rl_delete_text (rl_point, rl_point + 1);
2779 /* **************************************************************** */
2783 /* **************************************************************** */
2785 /* The next two functions mimic unix line editing behaviour, except they
2786 save the deleted text on the kill ring. This is safer than not saving
2787 it, and since we have a ring, nobody should get screwed. */
2789 /* This does what C-w does in Unix. We can't prevent people from
2790 using behaviour that they expect. */
2791 rl_unix_word_rubout ()
2793 if (!rl_point) ding ();
2795 int orig_point = rl_point;
2796 while (rl_point && whitespace (the_line[rl_point - 1]))
2798 while (rl_point && !whitespace (the_line[rl_point - 1]))
2800 rl_kill_text (rl_point, orig_point);
2804 /* Here is C-u doing what Unix does. You don't *have* to use these
2805 key-bindings. We have a choice of killing the entire line, or
2806 killing from where we are to the start of the line. We choose the
2807 latter, because if you are a Unix weenie, then you haven't backspaced
2808 into the line at all, and if you aren't, then you know what you are
2810 rl_unix_line_discard ()
2812 if (!rl_point) ding ();
2814 rl_kill_text (rl_point, 0);
2821 /* **************************************************************** */
2823 /* Commands For Typos */
2825 /* **************************************************************** */
2827 /* Random and interesting things in here. */
2830 /* **************************************************************** */
2834 /* **************************************************************** */
2836 /* The three kinds of things that we know how to do. */
2841 /* Uppercase the word at point. */
2842 rl_upcase_word (count)
2845 rl_change_case (count, UpCase);
2848 /* Lowercase the word at point. */
2849 rl_downcase_word (count)
2852 rl_change_case (count, DownCase);
2855 /* Upcase the first letter, downcase the rest. */
2856 rl_capitalize_word (count)
2859 rl_change_case (count, CapCase);
2862 /* The meaty function.
2863 Change the case of COUNT words, performing OP on them.
2864 OP is one of UpCase, DownCase, or CapCase.
2865 If a negative argument is given, leave point where it started,
2866 otherwise, leave it where it moves to. */
2867 rl_change_case (count, op)
2870 register int start = rl_point, end;
2873 rl_forward_word (count);
2883 /* We are going to modify some text, so let's prepare to undo it. */
2884 rl_modifying (start, end);
2886 for (; start < end; start++)
2891 the_line[start] = to_upper (the_line[start]);
2895 the_line[start] = to_lower (the_line[start]);
2901 the_line[start] = to_upper (the_line[start]);
2906 the_line[start] = to_lower (the_line[start]);
2908 if (!pure_alphabetic (the_line[start]))
2919 /* **************************************************************** */
2923 /* **************************************************************** */
2925 /* Transpose the words at point. */
2926 rl_transpose_words (count)
2929 char *word1, *word2;
2930 int w1_beg, w1_end, w2_beg, w2_end;
2931 int orig_point = rl_point;
2935 /* Find the two words. */
2936 rl_forward_word (count);
2938 rl_backward_word (1);
2940 rl_backward_word (count);
2942 rl_forward_word (1);
2945 /* Do some check to make sure that there really are two words. */
2946 if ((w1_beg == w2_beg) || (w2_beg < w1_end))
2949 rl_point = orig_point;
2953 /* Get the text of the words. */
2954 word1 = rl_copy (w1_beg, w1_end);
2955 word2 = rl_copy (w2_beg, w2_end);
2957 /* We are about to do many insertions and deletions. Remember them
2958 as one operation. */
2959 rl_begin_undo_group ();
2961 /* Do the stuff at word2 first, so that we don't have to worry
2962 about word1 moving. */
2964 rl_delete_text (w2_beg, w2_end);
2965 rl_insert_text (word1);
2968 rl_delete_text (w1_beg, w1_end);
2969 rl_insert_text (word2);
2971 /* This is exactly correct since the text before this point has not
2972 changed in length. */
2975 /* I think that does it. */
2976 rl_end_undo_group ();
2977 free (word1); free (word2);
2980 /* Transpose the characters at point. If point is at the end of the line,
2981 then transpose the characters before point. */
2982 rl_transpose_chars (count)
2988 if (!rl_point || rl_end < 2) {
2994 if (rl_point == rl_end) {
2995 int t = the_line[rl_point - 1];
2996 the_line[rl_point - 1] = the_line[rl_point - 2];
2997 the_line[rl_point - 2] = t;
2999 int t = the_line[rl_point];
3000 the_line[rl_point] = the_line[rl_point - 1];
3001 the_line[rl_point - 1] = t;
3002 if (count < 0 && rl_point)
3015 /* **************************************************************** */
3017 /* Bogus Flow Control */
3019 /* **************************************************************** */
3021 rl_restart_output (count, key)
3024 int fildes = fileno (stdin);
3026 ioctl (fildes, TIOCSTART, 0);
3027 #endif /* TIOCSTART */
3030 /* **************************************************************** */
3032 /* Completion matching, from readline's point of view. */
3034 /* **************************************************************** */
3036 /* Pointer to the generator function for completion_matches ().
3037 NULL means to use filename_entry_function (), the default filename
3039 Function *rl_completion_entry_function = (Function *)NULL;
3041 /* Pointer to alternative function to create matches.
3042 Function is called with TEXT, START, and END.
3043 START and END are indices in RL_LINE_BUFFER saying what the boundaries
3045 If this function exists and returns NULL then call the value of
3046 rl_completion_entry_function to try to match, otherwise use the
3047 array of strings returned. */
3048 Function *rl_attempted_completion_function = (Function *)NULL;
3050 /* Complete the word at or before point. You have supplied the function
3051 that does the initial simple matching selection algorithm (see
3052 completion_matches ()). The default is to do filename completion. */
3053 rl_complete (ignore, invoking_key)
3054 int ignore, invoking_key;
3056 rl_complete_internal (TAB);
3059 /* List the possible completions. See description of rl_complete (). */
3060 rl_possible_completions ()
3062 rl_complete_internal ('?');
3065 /* The user must press "y" or "n". Non-zero return means "y" pressed. */
3071 if (c == 'y' || c == 'Y') return (1);
3072 if (c == 'n' || c == 'N') return (0);
3073 if (c == ABORT_CHAR) rl_abort ();
3077 /* Up to this many items will be displayed in response to a
3078 possible-completions call. After that, we ask the user if
3079 she is sure she wants to see them all. */
3080 int rl_completion_query_items = 100;
3082 /* The basic list of characters that signal a break between words for the
3083 completer routine. The contents of this variable is what breaks words
3084 in the shell, i.e. " \t\n\"\\'`@$><=" */
3085 char *rl_basic_word_break_characters = " \t\n\"\\'`@$><=";
3087 /* The list of characters that signal a break between words for
3088 rl_complete_internal. The default list is the contents of
3089 rl_basic_word_break_characters. */
3090 char *rl_completer_word_break_characters = (char *)NULL;
3092 /* List of characters that are word break characters, but should be left
3093 in TEXT when it is passed to the completion function. The shell uses
3094 this to help determine what kind of completing to do. */
3095 char *rl_special_prefixes = (char *)NULL;
3097 /* If non-zero, then disallow duplicates in the matches. */
3098 int rl_ignore_completion_duplicates = 1;
3100 /* Non-zero means that the results of the matches are to be treated
3101 as filenames. This is ALWAYS zero on entry, and can only be changed
3102 within a completion entry finder function. */
3103 int rl_filename_completion_desired = 0;
3105 /* Complete the word at or before point.
3106 WHAT_TO_DO says what to do with the completion.
3107 `?' means list the possible completions.
3108 TAB means do standard completion.
3109 `*' means insert all of the possible completions. */
3110 rl_complete_internal (what_to_do)
3113 char *filename_completion_function ();
3114 char **completion_matches (), **matches;
3116 int start, end, delimiter = 0;
3119 if (rl_completion_entry_function)
3120 our_func = rl_completion_entry_function;
3122 our_func = (int (*)())filename_completion_function;
3124 /* Only the completion entry function can change this. */
3125 rl_filename_completion_desired = 0;
3127 /* We now look backwards for the start of a filename/variable word. */
3131 while (--rl_point &&
3132 !rindex (rl_completer_word_break_characters, the_line[rl_point]));
3134 /* If we are at a word break, then advance past it. */
3135 if (rindex (rl_completer_word_break_characters, (the_line[rl_point])))
3137 /* If the character that caused the word break was a quoting
3138 character, then remember it as the delimiter. */
3139 if (rindex ("\"'", the_line[rl_point]) && (end - rl_point) > 1)
3140 delimiter = the_line[rl_point];
3142 /* If the character isn't needed to determine something special
3143 about what kind of completion to perform, then advance past it. */
3145 if (!rl_special_prefixes ||
3146 !rindex (rl_special_prefixes, the_line[rl_point]))
3153 text = rl_copy (start, end);
3155 /* If the user wants to TRY to complete, but then wants to give
3156 up and use the default completion function, they set the
3157 variable rl_attempted_completion_function. */
3158 if (rl_attempted_completion_function)
3161 (char **)(*rl_attempted_completion_function) (text, start, end);
3164 goto after_usual_completion;
3167 matches = completion_matches (text, our_func, start, end);
3169 after_usual_completion:
3180 /* It seems to me that in all the cases we handle we would like
3181 to ignore duplicate possiblilities. Scan for the text to
3182 insert being identical to the other completions. */
3183 if (rl_ignore_completion_duplicates)
3185 char *lowest_common;
3188 /* Sort the items. */
3189 /* It is safe to sort this array, because the lowest common
3190 denominator found in matches[0] will remain in place. */
3191 for (i = 0; matches[i]; i++);
3192 qsort (matches, i, sizeof (char *), compare_strings);
3194 /* Remember the lowest common denimator for it may be unique. */
3195 lowest_common = savestring (matches[0]);
3197 for (i = 0; matches[i + 1]; i++)
3199 if (strcmp (matches[i], matches[i + 1]) == 0)
3202 matches[i] = (char *)-1;
3208 /* We have marked all the dead slots with (char *)-1.
3209 Copy all the non-dead entries into a new array. */
3212 (char **)malloc ((3 + newlen) * sizeof (char *));
3214 for (i = 1, j = 1; matches[i]; i++)
3215 if (matches[i] != (char *)-1)
3216 temp_array[j++] = matches[i];
3217 temp_array[j] = (char *)NULL;
3219 if (matches[0] != (char *)-1)
3223 matches = temp_array;
3226 /* Place the lowest common denominator back in [0]. */
3227 matches[0] = lowest_common;
3229 /* If there is one string left, and it is identical to the
3230 lowest common denominator, then the LCD is the string to
3232 if (j == 2 && strcmp (matches[0], matches[1]) == 0)
3235 matches[1] = (char *)NULL;
3244 rl_delete_text (start, rl_point);
3246 rl_insert_text (matches[0]);
3249 /* If there are more matches, ring the bell to indicate.
3250 If this was the only match, and we are hacking files,
3251 check the file to see if it was a directory. If so,
3252 add a '/' to the name. If not, and we are at the end
3253 of the line, then add a space. */
3256 ding (); /* There are other matches remaining. */
3260 char temp_string[2];
3262 temp_string[0] = delimiter ? delimiter : ' ';
3263 temp_string[1] = '\0';
3265 if (rl_filename_completion_desired)
3268 char *tilde_expand ();
3269 char *filename = tilde_expand (matches[0]);
3271 if ((stat (filename, &finfo) == 0) &&
3272 ((finfo.st_mode & S_IFMT) == S_IFDIR))
3274 if (the_line[rl_point] != '/')
3275 rl_insert_text ("/");
3279 if (rl_point == rl_end)
3280 rl_insert_text (temp_string);
3286 if (rl_point == rl_end)
3287 rl_insert_text (temp_string);
3296 rl_delete_text (start, rl_point);
3298 rl_begin_undo_group ();
3303 rl_insert_text (matches[i++]);
3304 rl_insert_text (" ");
3309 rl_insert_text (matches[0]);
3310 rl_insert_text (" ");
3312 rl_end_undo_group ();
3319 int len, count, limit, max = 0;
3322 /* Handle simple case first. What if there is only one answer? */
3327 if (rl_filename_completion_desired)
3328 temp = rindex (matches[0], '/');
3330 temp = (char *)NULL;
3338 fprintf (out_stream, "%s", temp);
3343 /* There is more than one answer. Find out how many there are,
3344 and find out what the maximum printed length of a single entry
3346 for (i = 1; matches[i]; i++)
3348 char *temp = (char *)NULL;
3350 /* If we are hacking filenames, then only count the characters
3351 after the last slash in the pathname. */
3352 if (rl_filename_completion_desired)
3353 temp = rindex (matches[i], '/');
3355 temp = (char *)NULL;
3362 if (strlen (temp) > max)
3363 max = strlen (temp);
3368 /* If there are many items, then ask the user if she
3369 really wants to see them all. */
3370 if (len >= rl_completion_query_items)
3373 fprintf (out_stream,
3374 "There are %d possibilities. Do you really", len);
3376 fprintf (out_stream, "wish to see them all? (y or n)");
3377 fflush (out_stream);
3384 /* How many items of MAX length can we fit in the screen window? */
3386 limit = screenwidth / max;
3387 if (limit != 1 && (limit * max == screenwidth))
3390 /* How many iterations of the printing loop? */
3391 count = (len + (limit - 1)) / limit;
3393 /* Watch out for special case. If LEN is less than LIMIT, then
3394 just do the inner printing loop. */
3395 if (len < limit) count = 1;
3397 /* Sort the items if they are not already sorted. */
3398 if (!rl_ignore_completion_duplicates)
3399 qsort (matches, len, sizeof (char *), compare_strings);
3401 /* Print the sorted items, up-and-down alphabetically, like
3405 for (i = 1; i < count + 1; i++)
3407 for (j = 0, l = i; j < limit; j++)
3409 if (l > len || !matches[l])
3415 char *temp = (char *)NULL;
3417 if (rl_filename_completion_desired)
3418 temp = rindex (matches[l], '/');
3420 temp = (char *)NULL;
3427 fprintf (out_stream, "%s", temp);
3428 for (k = 0; k < max - strlen (temp); k++)
3429 putc (' ', out_stream);
3445 for (i = 0; matches[i]; i++)
3451 /* Stupid comparison routine for qsort () ing strings. */
3453 compare_strings (s1, s2)
3456 return (strcmp (*s1, *s2));
3459 /* A completion function for usernames.
3460 TEXT contains a partial username preceded by a random
3461 character (usually `~'). */
3463 username_completion_function (text, state)
3467 static char *username = (char *)NULL;
3468 static struct passwd *entry;
3475 username = savestring (&text[1]);
3476 namelen = strlen (username);
3480 while (entry = getpwent ())
3482 if (strncmp (username, entry->pw_name, namelen) == 0)
3489 return ((char *)NULL);
3493 char *value = (char *)xmalloc (2 + strlen (entry->pw_name));
3495 strcpy (value + 1, entry->pw_name);
3496 rl_filename_completion_desired = 1;
3501 /* If non-null, this contains the address of a function to call if the
3502 standard meaning for expanding a tilde fails. The function is called
3503 with the text (sans tilde, as in "foo"), and returns a malloc()'ed string
3504 which is the expansion, or a NULL pointer if there is no expansion. */
3505 Function *rl_tilde_expander = (Function *)NULL;
3507 /* Expand FILENAME if it begins with a tilde. This always returns
3510 tilde_expand (filename)
3513 char *dirname = filename ? savestring (filename) : (char *)NULL;
3515 if (dirname && *dirname == '~')
3518 if (!dirname[1] || dirname[1] == '/')
3520 /* Prepend $HOME to the rest of the string. */
3521 char *temp_home = (char *)getenv ("HOME");
3523 temp_name = (char *)alloca (1 + strlen (&dirname[1])
3524 + (temp_home? strlen (temp_home) : 0));
3525 temp_name[0] = '\0';
3527 strcpy (temp_name, temp_home);
3528 strcat (temp_name, &dirname[1]);
3530 dirname = savestring (temp_name);
3534 struct passwd *getpwnam (), *user_entry;
3535 char *username = (char *)alloca (257);
3538 for (i = 1; c = dirname[i]; i++)
3540 if (c == '/') break;
3541 else username[i - 1] = c;
3543 username[i - 1] = '\0';
3545 if (!(user_entry = getpwnam (username)))
3547 /* If the calling program has a special syntax for
3548 expanding tildes, and we couldn't find a standard
3549 expansion, then let them try. */
3550 if (rl_tilde_expander)
3554 expansion = (char *)(*rl_tilde_expander) (username);
3558 temp_name = (char *)alloca (1 + strlen (expansion)
3559 + strlen (&dirname[i]));
3560 strcpy (temp_name, expansion);
3561 strcat (temp_name, &dirname[i]);
3567 * We shouldn't report errors.
3572 temp_name = (char *)alloca (1 + strlen (user_entry->pw_dir)
3573 + strlen (&dirname[i]));
3574 strcpy (temp_name, user_entry->pw_dir);
3575 strcat (temp_name, &dirname[i]);
3578 dirname = savestring (temp_name);
3586 /* **************************************************************** */
3588 /* Undo, and Undoing */
3590 /* **************************************************************** */
3592 /* Non-zero tells rl_delete_text and rl_insert_text to not add to
3594 int doing_an_undo = 0;
3596 /* The current undo list for THE_LINE. */
3597 UNDO_LIST *rl_undo_list = (UNDO_LIST *)NULL;
3599 /* Remember how to undo something. Concatenate some undos if that
3601 rl_add_undo (what, start, end, text)
3602 enum undo_code what;
3606 UNDO_LIST *temp = (UNDO_LIST *)xmalloc (sizeof (UNDO_LIST));
3608 temp->start = start;
3611 temp->next = rl_undo_list;
3612 rl_undo_list = temp;
3615 /* Free the existing undo list. */
3618 while (rl_undo_list) {
3619 UNDO_LIST *release = rl_undo_list;
3620 rl_undo_list = rl_undo_list->next;
3622 if (release->what == UNDO_DELETE)
3623 free (release->text);
3629 /* Undo the next thing in the list. Return 0 if there
3630 is nothing to undo, or non-zero if there was. */
3635 int waiting_for_begin = 0;
3643 switch (rl_undo_list->what) {
3645 /* Undoing deletes means inserting some text. */
3647 rl_point = rl_undo_list->start;
3648 rl_insert_text (rl_undo_list->text);
3649 free (rl_undo_list->text);
3652 /* Undoing inserts means deleting some text. */
3654 rl_delete_text (rl_undo_list->start, rl_undo_list->end);
3655 rl_point = rl_undo_list->start;
3658 /* Undoing an END means undoing everything 'til we get to
3661 waiting_for_begin++;
3664 /* Undoing a BEGIN means that we are done with this group. */
3666 if (waiting_for_begin)
3667 waiting_for_begin--;
3675 release = rl_undo_list;
3676 rl_undo_list = rl_undo_list->next;
3679 if (waiting_for_begin)
3685 /* Begin a group. Subsequent undos are undone as an atomic operation. */
3686 rl_begin_undo_group ()
3688 rl_add_undo (UNDO_BEGIN, 0, 0, 0);
3691 /* End an undo group started with rl_begin_undo_group (). */
3692 rl_end_undo_group ()
3694 rl_add_undo (UNDO_END, 0, 0, 0);
3697 /* Save an undo entry for the text from START to END. */
3698 rl_modifying (start, end)
3710 char *temp = rl_copy (start, end);
3711 rl_begin_undo_group ();
3712 rl_add_undo (UNDO_DELETE, start, end, temp);
3713 rl_add_undo (UNDO_INSERT, start, end, (char *)NULL);
3714 rl_end_undo_group ();
3718 /* Revert the current line to its previous state. */
3721 if (!rl_undo_list) ding ();
3723 while (rl_undo_list)
3728 /* Do some undoing of things that were done. */
3729 rl_undo_command (count)
3731 if (count < 0) return; /* Nothing to do. */
3747 /* **************************************************************** */
3749 /* History Utilities */
3751 /* **************************************************************** */
3753 /* We already have a history library, and that is what we use to control
3754 the history features of readline. However, this is our local interface
3755 to the history mechanism. */
3757 /* While we are editing the history, this is the saved
3758 version of the original line. */
3759 HIST_ENTRY *saved_line_for_history = (HIST_ENTRY *)NULL;
3761 /* Set the history pointer back to the last entry in the history. */
3762 start_using_history ()
3765 if (saved_line_for_history)
3766 free_history_entry (saved_line_for_history);
3768 saved_line_for_history = (HIST_ENTRY *)NULL;
3771 /* Free the contents (and containing structure) of a HIST_ENTRY. */
3772 free_history_entry (entry)
3781 /* Perhaps put back the current line if it has changed. */
3782 maybe_replace_line ()
3784 HIST_ENTRY *temp = current_history ();
3786 /* If the current line has changed, save the changes. */
3787 if (temp && ((UNDO_LIST *)(temp->data) != rl_undo_list)) {
3788 temp = replace_history_entry (where_history (), the_line, rl_undo_list);
3794 /* Put back the saved_line_for_history if there is one. */
3795 maybe_unsave_line ()
3797 if (saved_line_for_history) {
3798 strcpy (the_line, saved_line_for_history->line);
3799 rl_undo_list = (UNDO_LIST *)saved_line_for_history->data;
3800 free_history_entry (saved_line_for_history);
3801 saved_line_for_history = (HIST_ENTRY *)NULL;
3802 rl_end = rl_point = strlen (the_line);
3808 /* Save the current line in saved_line_for_history. */
3811 if (!saved_line_for_history) {
3812 saved_line_for_history = (HIST_ENTRY *)xmalloc (sizeof (HIST_ENTRY));
3813 saved_line_for_history->line = savestring (the_line);
3814 saved_line_for_history->data = (char *)rl_undo_list;
3820 /* **************************************************************** */
3822 /* History Commands */
3824 /* **************************************************************** */
3826 /* Meta-< goes to the start of the history. */
3827 rl_beginning_of_history ()
3829 rl_get_previous_history (1 + where_history ());
3832 /* Meta-> goes to the end of the history. (The current line). */
3833 rl_end_of_history ()
3835 maybe_replace_line ();
3837 maybe_unsave_line ();
3840 /* Move down to the next history line. */
3841 rl_get_next_history (count)
3844 HIST_ENTRY *temp = (HIST_ENTRY *)NULL;
3848 rl_get_previous_history (-count);
3855 maybe_replace_line ();
3859 temp = next_history ();
3866 maybe_unsave_line ();
3869 strcpy (the_line, temp->line);
3870 rl_undo_list = (UNDO_LIST *)temp->data;
3871 rl_end = rl_point = strlen (the_line);
3875 /* Get the previous item out of our interactive history, making it the current
3876 line. If there is no previous history, just ding. */
3877 rl_get_previous_history (count)
3880 HIST_ENTRY *old_temp = (HIST_ENTRY *)NULL;
3881 HIST_ENTRY *temp = (HIST_ENTRY *)NULL;
3885 rl_get_next_history (-count);
3892 /* If we don't have a line saved, then save this one. */
3895 /* If the current line has changed, save the changes. */
3896 maybe_replace_line ();
3900 temp = previous_history ();
3908 /* If there was a large argument, and we moved back to the start of the
3909 history, that is not an error. So use the last value found. */
3910 if (!temp && old_temp)
3917 strcpy (the_line, temp->line);
3918 rl_undo_list = (UNDO_LIST *)temp->data;
3919 rl_end = rl_point = strlen (the_line);
3921 if (rl_editing_mode == vi_mode)
3923 #endif /* VI_MODE */
3927 /* There is a command in ksh which yanks into this line, the last word
3928 of the previous line. Here it is. We left it on M-. */
3929 rl_yank_previous_last_arg (ignore)
3936 /* **************************************************************** */
3938 /* I-Search and Searching */
3940 /* **************************************************************** */
3942 /* Search backwards through the history looking for a string which is typed
3943 interactively. Start with the current line. */
3944 rl_reverse_search_history (sign, key)
3948 rl_search_history (-sign, key);
3951 /* Search forwards through the history looking for a string which is typed
3952 interactively. Start with the current line. */
3953 rl_forward_search_history (sign, key)
3957 rl_search_history (sign, key);
3960 /* Display the current state of the search in the echo-area.
3961 SEARCH_STRING contains the string that is being searched for,
3962 DIRECTION is zero for forward, or 1 for reverse,
3963 WHERE is the history list number of the current line. If it is
3964 -1, then this line is the starting one. */
3965 rl_display_search (search_string, reverse_p, where)
3966 char *search_string;
3967 int reverse_p, where;
3969 char *message = (char *)NULL;
3972 (char *)alloca (1 + (search_string ? strlen (search_string) : 0) + 30);
3978 sprintf (message, "[%d]", where + history_base);
3981 strcat (message, "(");
3984 strcat (message, "reverse-");
3986 strcat (message, "i-search)`");
3989 strcat (message, search_string);
3991 strcat (message, "': ");
3992 rl_message (message, 0, 0);
3996 /* Search through the history looking for an interactively typed string.
3997 This is analogous to i-search. We start the search in the current line.
3998 DIRECTION is which direction to search; > 0 means forward, < 0 means
4000 rl_search_history (direction, invoking_key)
4004 /* The string that the user types in to search for. */
4005 char *search_string = (char *)alloca (128);
4007 /* The current length of SEARCH_STRING. */
4008 int search_string_index;
4010 /* The list of lines to search through. */
4013 /* The length of LINES. */
4016 /* Where we get LINES from. */
4017 HIST_ENTRY **hlist = history_list ();
4019 int orig_point = rl_point;
4020 int orig_line = where_history ();
4021 int last_found_line = orig_line;
4026 /* The line currently being searched. */
4029 /* Offset in that line. */
4032 /* Non-zero if we are doing a reverse search. */
4033 int reverse = (direction < 0);
4035 /* Create an arrary of pointers to the lines that we want to search. */
4037 maybe_replace_line ();
4039 for (i = 0; hlist[i]; i++);
4041 /* Allocate space for this many lines, +1 for the current input line,
4042 and remember those lines. */
4043 lines = (char **)alloca ((1 + (hlen = i)) * sizeof (char *));
4044 for (i = 0; i < hlen; i++)
4045 lines[i] = hlist[i]->line;
4047 if (saved_line_for_history)
4048 lines[i] = saved_line_for_history->line;
4051 /* So I have to type it in this way instead. */
4052 lines[i] = (char *)alloca (1 + strlen (the_line));
4053 strcpy (lines[i], &the_line[0]);
4058 /* The line where we start the search. */
4061 /* Initialize search parameters. */
4062 *search_string = '\0';
4063 search_string_index = 0;
4065 rl_display_search (search_string, reverse, -1);
4074 /* Hack C to Do What I Mean. */
4076 Function *f = (Function *)NULL;
4078 if (keymap[c].type == ISFUNC)
4079 f = keymap[c].function;
4081 if (f == rl_reverse_search_history)
4082 c = reverse ? -1 : -2;
4083 else if (f == rl_forward_search_history)
4084 c = !reverse ? -1 : -2;
4093 /* case invoking_key: */
4097 /* switch directions */
4099 direction = -direction;
4100 reverse = (direction < 0);
4105 strcpy (the_line, lines[orig_line]);
4106 rl_point = orig_point;
4107 rl_end = strlen (the_line);
4108 rl_clear_message ();
4112 if (c < 32 || c > 126)
4114 rl_execute_next (c);
4120 search_string[search_string_index++] = c;
4121 search_string[search_string_index] = '\0';
4126 if (!search_string_index)
4133 if (index != strlen (sline))
4148 search_string_index) == 0)
4155 register int limit =
4156 (strlen (sline) - search_string_index) + 1;
4158 while (index < limit)
4160 if (strncmp (search_string,
4162 search_string_index) == 0)
4171 /* At limit for direction? */
4172 if ((reverse && i < 0) ||
4173 (!reverse && i == hlen))
4178 index = strlen (sline);
4182 /* If the search string is longer than the current
4184 if (search_string_index > strlen (sline))
4187 /* Start actually searching. */
4189 index -= search_string_index;
4193 /* We cannot find the search string. Ding the bell. */
4195 i = last_found_line;
4199 /* We have found the search string. Just display it. But don't
4200 actually move there in the history list until the user accepts
4202 strcpy (the_line, lines[i]);
4204 rl_end = strlen (the_line);
4205 last_found_line = i;
4206 rl_display_search (search_string, reverse,
4207 (i == orig_line) ? -1 : i);
4212 /* The user has won. They found the string that they wanted. Now all
4213 we have to do is place them there. */
4215 int now = last_found_line;
4217 /* First put back the original state. */
4218 strcpy (the_line, lines[orig_line]);
4220 if (now < orig_line)
4221 rl_get_previous_history (orig_line - now);
4223 rl_get_next_history (now - orig_line);
4226 rl_clear_message ();
4230 /* Make C be the next command to be executed. */
4234 rl_pending_input = c;
4237 /* **************************************************************** */
4239 /* Killing Mechanism */
4241 /* **************************************************************** */
4243 /* What we assume for a max number of kills. */
4244 #define DEFAULT_MAX_KILLS 10
4246 /* The real variable to look at to find out when to flush kills. */
4247 int rl_max_kills = DEFAULT_MAX_KILLS;
4249 /* Where to store killed text. */
4250 char **rl_kill_ring = (char **)NULL;
4252 /* Where we are in the kill ring. */
4253 int rl_kill_index = 0;
4255 /* How many slots we have in the kill ring. */
4256 int rl_kill_ring_length = 0;
4258 /* How to say that you only want to save a certain amount
4259 of kill material. */
4260 rl_set_retained_kills (num)
4264 /* The way to kill something. This appends or prepends to the last
4265 kill, if the last command was a kill command. if FROM is less
4266 than TO, then the text is appended, otherwise prepended. If the
4267 last command was not a kill command, then a new slot is made for
4269 rl_kill_text (from, to)
4273 char *text = rl_copy (from, to);
4275 /* Is there anything to kill? */
4278 last_command_was_kill++;
4282 /* Delete the copied text from the line. */
4283 rl_delete_text (from, to);
4285 /* First, find the slot to work with. */
4286 if (!last_command_was_kill) {
4288 /* Get a new slot. */
4289 if (!rl_kill_ring) {
4291 /* If we don't have any defined, then make one. */
4293 (char **)xmalloc (((rl_kill_ring_length = 1) + 1) * sizeof (char *));
4298 /* We have to add a new slot on the end, unless we have exceeded
4299 the max limit for remembering kills. */
4300 slot = rl_kill_ring_length;
4301 if (slot == rl_max_kills) {
4303 free (rl_kill_ring[0]);
4304 for (i = 0; i < slot; i++)
4305 rl_kill_ring[i] = rl_kill_ring[i + 1];
4308 (char **)xrealloc (rl_kill_ring,
4309 ((slot = (rl_kill_ring_length += 1)) + 1)
4315 slot = rl_kill_ring_length - 1;
4318 /* If the last command was a kill, prepend or append. */
4319 if (last_command_was_kill) {
4320 char *old = rl_kill_ring[slot];
4321 char *new = (char *)xmalloc (1 + strlen (old) + strlen (text));
4332 rl_kill_ring[slot] = new;
4334 rl_kill_ring[slot] = text;
4336 rl_kill_index = slot;
4337 last_command_was_kill++;
4340 /* Now REMEMBER! In order to do prepending or appending correctly, kill
4341 commands always make rl_point's original position be the FROM argument,
4342 and rl_point's extent be the TO argument. */
4345 /* **************************************************************** */
4347 /* Killing Commands */
4349 /* **************************************************************** */
4351 /* Delete the word at point, saving the text in the kill ring. */
4352 rl_kill_word (count)
4355 int orig_point = rl_point;
4358 rl_backward_kill_word (-count);
4361 rl_forward_word (count);
4363 if (rl_point != orig_point)
4364 rl_kill_text (orig_point, rl_point);
4366 rl_point = orig_point;
4370 /* Rubout the word before point, placing it on the kill ring. */
4371 rl_backward_kill_word (count)
4374 int orig_point = rl_point;
4377 rl_kill_word (-count);
4380 rl_backward_word (count);
4382 if (rl_point != orig_point)
4383 rl_kill_text (orig_point, rl_point);
4387 /* Kill from here to the end of the line. If DIRECTION is negative, kill
4388 back to the line start instead. */
4389 rl_kill_line (direction)
4392 int orig_point = rl_point;
4395 rl_backward_kill_line (1);
4399 if (orig_point != rl_point)
4400 rl_kill_text (orig_point, rl_point);
4401 rl_point = orig_point;
4405 /* Kill backwards to the start of the line. If DIRECTION is negative, kill
4406 forwards to the line end instead. */
4407 rl_backward_kill_line (direction)
4410 int orig_point = rl_point;
4421 rl_kill_text (orig_point, rl_point);
4426 /* Yank back the last killed text. This ignores arguments. */
4429 if (!rl_kill_ring) rl_abort ();
4430 rl_insert_text (rl_kill_ring[rl_kill_index]);
4433 /* If the last command was yank, or yank_pop, and the text just
4434 before point is identical to the current kill item, then
4435 delete that text from the line, rotate the index down, and
4436 yank back some other text. */
4441 if (((rl_last_func != rl_yank_pop) && (rl_last_func != rl_yank)) ||
4447 l = strlen (rl_kill_ring[rl_kill_index]);
4448 if (((rl_point - l) >= 0) &&
4449 (strncmp (the_line + (rl_point - l),
4450 rl_kill_ring[rl_kill_index], l) == 0))
4452 rl_delete_text ((rl_point - l), rl_point);
4455 if (rl_kill_index < 0)
4456 rl_kill_index = rl_kill_ring_length - 1;
4464 /* Yank the COUNTth argument from the previous history line. */
4465 rl_yank_nth_arg (count, ignore)
4468 register HIST_ENTRY *entry = previous_history ();
4479 arg = history_arg_extract (count, count, entry->line);
4486 rl_begin_undo_group ();
4487 if (rl_point && the_line[rl_point - 1] != ' ')
4488 rl_insert_text (" ");
4489 rl_insert_text (arg);
4491 rl_end_undo_group ();
4496 #include "vi_mode.c"
4497 #endif /* VI_MODE */
4499 /* How to toggle back and forth between editing modes. */
4500 rl_vi_editing_mode ()
4503 rl_editing_mode = vi_mode;
4504 rl_vi_insertion_mode ();
4505 #endif /* VI_MODE */
4508 rl_emacs_editing_mode ()
4510 rl_editing_mode = emacs_mode;
4511 keymap = emacs_standard_keymap;
4515 /* **************************************************************** */
4519 /* **************************************************************** */
4521 /* Non-zero means that case is not significant in completion. */
4522 int completion_case_fold = 0;
4524 /* Return an array of (char *) which is a list of completions for TEXT.
4525 If there are no completions, return a NULL pointer.
4526 The first entry in the returned array is the substitution for TEXT.
4527 The remaining entries are the possible completions.
4528 The array is terminated with a NULL pointer.
4530 ENTRY_FUNCTION is a function of two args, and returns a (char *).
4531 The first argument is TEXT.
4532 The second is a state argument; it should be zero on the first call, and
4533 non-zero on subsequent calls. It returns a NULL pointer to the caller
4534 when there are no more matches.
4537 completion_matches (text, entry_function)
4539 char *(*entry_function) ();
4541 /* Number of slots in match_list. */
4542 int match_list_size;
4544 /* The list of matches. */
4546 (char **)xmalloc (((match_list_size = 10) + 1) * sizeof (char *));
4548 /* Number of matches actually found. */
4551 /* Temporary string binder. */
4554 match_list[1] = (char *)NULL;
4556 while (string = (*entry_function) (text, matches))
4558 if (matches + 1 == match_list_size)
4560 (char **)xrealloc (match_list,
4561 ((match_list_size += 10) + 1) * sizeof (char *));
4563 match_list[++matches] = string;
4564 match_list[matches + 1] = (char *)NULL;
4567 /* If there were any matches, then look through them finding out the
4568 lowest common denominator. That then becomes match_list[0]. */
4572 int low = 100000; /* Count of max-matched characters. */
4574 /* If only one match, just use that. */
4577 match_list[0] = match_list[1];
4578 match_list[1] = (char *)NULL;
4582 /* Otherwise, compare each member of the list with
4583 the next, finding out where they stop matching. */
4587 register int c1, c2, si;
4589 if (completion_case_fold)
4592 (c1 = to_lower(match_list[i][si])) &&
4593 (c2 = to_lower(match_list[i + 1][si]));
4595 if (c1 != c2) break;
4600 (c1 = match_list[i][si]) &&
4601 (c2 = match_list[i + 1][si]);
4603 if (c1 != c2) break;
4606 if (low > si) low = si;
4609 match_list[0] = (char *)xmalloc (low + 1);
4610 strncpy (match_list[0], match_list[1], low);
4611 match_list[0][low] = '\0';
4614 else /* There were no matches. */
4617 match_list = (char **)NULL;
4619 return (match_list);
4622 /* Okay, now we write the entry_function for filename completion. In the
4623 general case. Note that completion in the shell is a little different
4624 because of all the pathnames that must be followed when looking up the
4625 completion for a command. */
4627 filename_completion_function (text, state)
4631 static DIR *directory;
4632 static char *filename = (char *)NULL;
4633 static char *dirname = (char *)NULL;
4634 static char *users_dirname = (char *)NULL;
4635 static int filename_len;
4637 struct direct *entry = (struct direct *)NULL;
4639 /* If we don't have any state, then do some initialization. */
4644 if (dirname) free (dirname);
4645 if (filename) free (filename);
4646 if (users_dirname) free (users_dirname);
4648 filename = savestring (text);
4649 if (!*text) text = ".";
4650 dirname = savestring (text);
4652 temp = rindex (dirname, '/');
4656 strcpy (filename, ++temp);
4660 strcpy (dirname, ".");
4662 /* We aren't done yet. We also support the "~user" syntax. */
4664 /* Save the version of the directory that the user typed. */
4665 users_dirname = savestring (dirname);
4667 char *tilde_expand (), *temp_dirname = tilde_expand (dirname);
4669 dirname = temp_dirname;
4671 if (rl_symbolic_link_hook)
4672 (*rl_symbolic_link_hook) (&dirname);
4674 directory = opendir (dirname);
4675 filename_len = strlen (filename);
4677 rl_filename_completion_desired = 1;
4680 /* At this point we should entertain the possibility of hacking wildcarded
4681 filenames, like /usr/man*\/te<TAB>. If the directory name contains
4682 globbing characters, then build an array of directories to glob on, and
4683 glob on the first one. */
4685 /* Now that we have some state, we can read the directory. */
4687 while (directory && (entry = readdir (directory)))
4689 /* Special case for no filename.
4690 All entries except "." and ".." match. */
4693 if ((strcmp (entry->d_name, ".") != 0) &&
4694 (strcmp (entry->d_name, "..") != 0))
4699 /* Otherwise, if these match upto the length of filename, then
4702 if ((strlen (entry->d_name) >= filename_len) &&
4703 (strncmp (filename, entry->d_name, filename_len) == 0))
4705 if ((entry->d_namlen >= filename_len) &&
4706 (strncmp (filename, entry->d_name, filename_len) == 0))
4707 #endif /* TMB_SYSV */
4718 closedir (directory);
4719 directory = (DIR *)NULL;
4721 return (char *)NULL;
4727 if (dirname && (strcmp (dirname, ".") != 0))
4730 temp = (char *)xmalloc (1 + strlen (users_dirname)
4731 + strlen (entry->d_name));
4733 temp = (char *)xmalloc (1 + strlen (users_dirname)
4735 #endif /* TMB_SYSV */
4736 strcpy (temp, users_dirname);
4737 strcat (temp, entry->d_name);
4741 temp = (savestring (entry->d_name));
4748 /* **************************************************************** */
4752 /* **************************************************************** */
4754 /* rl_add_defun (char *name, Function *function, int key)
4755 Add NAME to the list of named functions. Make FUNCTION
4756 be the function that gets called.
4757 If KEY is not -1, then bind it. */
4758 rl_add_defun (name, function, key)
4764 rl_bind_key (key, function);
4765 rl_add_funmap_entry (name, function);
4768 /* Bind KEY to FUNCTION. Returns non-zero if KEY is out of range. */
4770 rl_bind_key (key, function)
4777 if (key > 127 && key < 256)
4779 if (keymap[ESC].type == ISKMAP)
4781 Keymap escmap = (Keymap)keymap[ESC].function;
4784 escmap[key].type = ISFUNC;
4785 escmap[key].function = function;
4791 keymap[key].type = ISFUNC;
4792 keymap[key].function = function;
4796 /* Bind KEY to FUNCTION in MAP. Returns non-zero in case of invalid
4799 rl_bind_key_in_map (key, function, map)
4805 Keymap oldmap = keymap;
4808 result = rl_bind_key (key, function);
4813 /* Make KEY do nothing in the currently selected keymap.
4814 Returns non-zero in case of error. */
4819 return (rl_bind_key (key, (Function *)NULL));
4822 /* Make KEY do nothing in MAP.
4823 Returns non-zero in case of error. */
4825 rl_unbind_key_in_map (key, map)
4829 return (rl_bind_key_in_map (key, (Function *)NULL, map));
4832 /* Bind the key sequence represented by the string KEYSEQ to
4833 FUNCTION. This makes new keymaps as necessary. The initial
4834 place to do bindings is in MAP. */
4835 rl_set_key (keyseq, function, map)
4840 rl_generic_bind (ISFUNC, keyseq, function, map);
4843 /* Bind the key sequence represented by the string KEYSEQ to
4844 the string of characters MACRO. This makes new keymaps as
4845 necessary. The initial place to do bindings is in MAP. */
4846 rl_macro_bind (keyseq, macro, map)
4847 char *keyseq, *macro;
4850 char *macro_keys = (char *)xmalloc (2 * (strlen (macro)));
4853 if (rl_translate_keyseq (macro, macro_keys, ¯o_keys_len))
4858 rl_generic_bind (ISMACR, keyseq, macro_keys, map);
4861 /* Bind the key sequence represented by the string KEYSEQ to
4862 the arbitrary pointer DATA. TYPE says what kind of data is
4863 pointed to by DATA, right now this can be a function (ISFUNC),
4864 a macro (ISMACR), or a keymap (ISKMAP). This makes new keymaps
4865 as necessary. The initial place to do bindings is in MAP. */
4866 rl_generic_bind (type, keyseq, data, map)
4868 char *keyseq, *data;
4875 /* If no keys to bind to, exit right away. */
4876 if (!keyseq || !*keyseq)
4883 keys = (char *)alloca (1 + (2 * strlen (keyseq)));
4885 /* Translate the ASCII representation of KEYSEQ into an array
4886 of characters. Stuff the characters into ARRAY, and the
4887 length of ARRAY into LENGTH. */
4888 if (rl_translate_keyseq (keyseq, keys, &keys_len))
4891 /* Bind keys, making new keymaps as necessary. */
4892 for (i = 0; i < keys_len; i++)
4894 if (i + 1 < keys_len)
4896 if (map[keys[i]].type != ISKMAP)
4898 if (map[i].type == ISMACR)
4899 free ((char *)map[i].function);
4901 map[keys[i]].type = ISKMAP;
4902 map[keys[i]].function = (Function *)rl_make_bare_keymap ();
4904 map = (Keymap)map[keys[i]].function;
4908 if (map[keys[i]].type == ISMACR)
4909 free ((char *)map[keys[i]].function);
4911 map[keys[i]].function = (Function *)data;
4912 map[keys[i]].type = type;
4917 /* Translate the ASCII representation of SEQ, stuffing the
4918 values into ARRAY, an array of characters. LEN gets the
4919 final length of ARRAY. Return non-zero if there was an
4920 error parsing SEQ. */
4921 rl_translate_keyseq (seq, array, len)
4925 register int i, c, l = 0;
4927 for (i = 0; c = seq[i]; i++)
4936 if (((c == 'C' || c == 'M') && seq[i + 1] == '-') ||
4939 /* Handle special case of backwards define. */
4940 if (strncmp (&seq[i], "C-\\M-", 5) == 0)
4944 array[l++] = CTRL (to_upper (seq[i]));
4959 array[l++] = CTRL (to_upper (seq[i]));
4977 /* Return a pointer to the function that STRING represents.
4978 If STRING doesn't have a matching function, then a NULL pointer
4981 rl_named_function (string)
4986 for (i = 0; funmap[i]; i++)
4987 if (stricmp (funmap[i]->name, string) == 0)
4988 return (funmap[i]->function);
4989 return ((Function *)NULL);
4992 /* The last key bindings file read. */
4993 static char *last_readline_init_file = "~/.inputrc";
4995 /* Re-read the current keybindings file. */
4996 rl_re_read_init_file (count, ignore)
4999 rl_read_init_file (last_readline_init_file);
5002 /* Do key bindings from a file. If FILENAME is NULL it defaults
5003 to `~/.inputrc'. If the file existed and could be opened and
5004 read, 0 is returned, otherwise errno is returned. */
5006 rl_read_init_file (filename)
5010 int line_size, line_index;
5011 char *line = (char *)xmalloc (line_size = 100);
5017 /* Default the filename. */
5019 filename = "~/.inputrc";
5021 openname = tilde_expand (filename);
5023 /* Open the file. */
5024 file = fopen (openname, "r");
5030 last_readline_init_file = filename;
5032 /* Loop reading lines from the file. Lines that start with `#' are
5033 comments, all other lines are commands for readline initialization. */
5034 while ((c = rl_getc (file)) != EOF)
5036 /* If comment, flush to EOL. */
5039 while ((c = rl_getc (file)) != EOF && c != '\n');
5045 /* Otherwise, this is the start of a line. Read the
5046 line from the file. */
5048 while (c != EOF && c != '\n')
5050 line[line_index++] = c;
5051 if (line_index == line_size)
5052 line = (char *)xrealloc (line, line_size += 100);
5055 line[line_index] = '\0';
5057 /* Parse the line. */
5058 rl_parse_and_bind (line);
5064 /* Close up the file and exit. */
5070 /* **************************************************************** */
5072 /* Parser Directives */
5074 /* **************************************************************** */
5078 /* Calling programs set this to have their argv[0]. */
5079 char *rl_readline_name = "other";
5081 /* Stack of previous values of parsing_conditionalized_out. */
5082 static unsigned char *if_stack = (unsigned char *)NULL;
5083 static int if_stack_depth = 0;
5084 static int if_stack_size = 0;
5086 /* Push parsing_conditionalized_out, and set parser state based on ARGS. */
5092 /* Push parser state. */
5093 if (if_stack_depth + 1 >= if_stack_size)
5096 if_stack = (unsigned char *)xmalloc (if_stack_size = 20);
5098 if_stack = (unsigned char *)xrealloc (if_stack, if_stack_size += 20);
5100 if_stack[if_stack_depth++] = parsing_conditionalized_out;
5102 /* We only check to see if the first word in ARGS is the same as the
5103 value stored in rl_readline_name. */
5105 /* Isolate first argument. */
5106 for (i = 0; args[i] && !whitespace (args[i]); i++);
5111 if (stricmp (args, rl_readline_name) == 0)
5112 parsing_conditionalized_out = 0;
5114 parsing_conditionalized_out = 1;
5117 /* Invert the current parser state if there is anything on the stack. */
5122 parsing_conditionalized_out = !parsing_conditionalized_out;
5125 /* *** What, no error message? *** */
5129 /* Terminate a conditional, popping the value of
5130 parsing_conditionalized_out from the stack. */
5135 parsing_conditionalized_out = if_stack[--if_stack_depth];
5138 /* *** What, no error message? *** */
5142 /* Associate textual names with actual functions. */
5146 } parser_directives [] = {
5147 { "if", parser_if },
5148 { "endif", parser_endif },
5149 { "else", parser_else },
5150 { (char *)0x0, (Function *)0x0 }
5153 /* Handle a parser directive. STATEMENT is the line of the directive
5154 without any leading `$'. */
5156 handle_parser_directive (statement)
5160 char *directive, *args;
5162 /* Isolate the actual directive. */
5164 /* Skip whitespace. */
5165 for (i = 0; whitespace (statement[i]); i++);
5167 directive = &statement[i];
5169 for (; statement[i] && !whitespace (statement[i]); i++);
5172 statement[i++] = '\0';
5174 for (; statement[i] && whitespace (statement[i]); i++);
5176 args = &statement[i];
5178 /* Lookup the command, and act on it. */
5179 for (i = 0; parser_directives[i].name; i++)
5180 if (stricmp (directive, parser_directives[i].name) == 0)
5182 (*parser_directives[i].function) (args);
5186 /* *** Should an error message be output? */
5190 /* Read the binding command from STRING and perform it.
5191 A key binding command looks like: Keyname: function-name\0,
5192 a variable binding command looks like: set variable value.
5193 A new-style keybinding looks like "\C-x\C-x": exchange-point-and-mark. */
5194 rl_parse_and_bind (string)
5197 extern char *possible_control_prefixes[], *possible_meta_prefixes[];
5198 char *funname, *kname;
5199 static int substring_member_of_array ();
5203 if (!string || !*string || *string == '#')
5206 /* If this is a parser directive, act on it. */
5209 handle_parser_directive (&string[1]);
5213 /* If we are supposed to be skipping parsing right now, then do it. */
5214 if (parsing_conditionalized_out)
5218 /* If this keyname is a complex key expression surrounded by quotes,
5219 advance to after the matching close quote. */
5222 for (i = 1; c = string[i]; i++)
5224 if (c == '"' && string[i - 1] != '\\')
5229 /* Advance to the colon (:) or whitespace which separates the two objects. */
5230 for (; (c = string[i]) && c != ':' && c != ' ' && c != '\t'; i++ );
5232 /* Mark the end of the command (or keyname). */
5236 /* If this is a command to set a variable, then do that. */
5237 if (stricmp (string, "set") == 0)
5239 char *var = string + i;
5242 /* Make VAR point to start of variable name. */
5243 while (*var && whitespace (*var)) var++;
5245 /* Make value point to start of value string. */
5247 while (*value && !whitespace (*value)) value++;
5250 while (*value && whitespace (*value)) value++;
5252 rl_variable_bind (var, value);
5256 /* Skip any whitespace between keyname and funname. */
5257 for (; string[i] && whitespace (string[i]); i++);
5258 funname = &string[i];
5260 /* Now isolate funname.
5261 For straight function names just look for whitespace, since
5262 that will signify the end of the string. But this could be a
5263 macro definition. In that case, the string is quoted, so skip
5264 to the matching delimiter. */
5265 if (*funname == '\'' || *funname == '"')
5267 int delimiter = string[i++];
5269 for (; c = string[i]; i++)
5271 if (c == delimiter && string[i - 1] != '\\')
5278 /* Advance to the end of the string. */
5279 for (; string[i] && !whitespace (string[i]); i++);
5281 /* No extra whitespace at the end of the string. */
5284 /* If this is a new-style key-binding, then do the binding with
5285 rl_set_key (). Otherwise, let the older code deal with it. */
5288 char *seq = (char *)alloca (1 + strlen (string));
5289 register int j, k = 0;
5291 for (j = 1; string[j]; j++)
5293 if (string[j] == '"' && string[j - 1] != '\\')
5296 seq[k++] = string[j];
5300 /* Binding macro? */
5301 if (*funname == '\'' || *funname == '"')
5303 j = strlen (funname);
5305 if (j && funname[j - 1] == *funname)
5306 funname[j - 1] = '\0';
5308 rl_macro_bind (seq, &funname[1], keymap);
5311 rl_set_key (seq, rl_named_function (funname), keymap);
5316 /* Get the actual character we want to deal with. */
5317 kname = rindex (string, '-');
5323 key = glean_key_from_name (kname);
5325 /* Add in control and meta bits. */
5326 if (substring_member_of_array (string, possible_control_prefixes))
5327 key = CTRL (to_upper (key));
5329 if (substring_member_of_array (string, possible_meta_prefixes))
5332 /* Temporary. Handle old-style keyname with macro-binding. */
5333 if (*funname == '\'' || *funname == '"')
5336 int fl = strlen (funname);
5338 seq[0] = key; seq[1] = '\0';
5339 if (fl && funname[fl - 1] == *funname)
5340 funname[fl - 1] = '\0';
5342 rl_macro_bind (seq, &funname[1], keymap);
5345 rl_bind_key (key, rl_named_function (funname));
5348 rl_variable_bind (name, value)
5351 if (stricmp (name, "editing-mode") == 0)
5353 if (strnicmp (value, "vi", 2) == 0)
5356 keymap = vi_insertion_keymap;
5357 rl_editing_mode = vi_mode;
5358 #endif /* VI_MODE */
5360 else if (strnicmp (value, "emacs", 5) == 0)
5362 keymap = emacs_standard_keymap;
5363 rl_editing_mode = emacs_mode;
5366 else if (stricmp (name, "horizontal-scroll-mode") == 0)
5368 if (!*value || stricmp (value, "On") == 0)
5369 horizontal_scroll_mode = 1;
5371 horizontal_scroll_mode = 0;
5373 else if (stricmp (name, "mark-modified-lines") == 0)
5375 if (!*value || stricmp (value, "On") == 0)
5376 mark_modified_lines = 1;
5378 mark_modified_lines = 0;
5382 /* Return the character which matches NAME.
5383 For example, `Space' returns ' '. */
5390 assoc_list name_key_alist[] = {
5396 { "Newline", '\n' },
5400 { "Escape", '\033' },
5407 glean_key_from_name (name)
5412 for (i = 0; name_key_alist[i].name; i++)
5413 if (stricmp (name, name_key_alist[i].name) == 0)
5414 return (name_key_alist[i].value);
5420 /* **************************************************************** */
5422 /* String Utility Functions */
5424 /* **************************************************************** */
5426 /* Return non-zero if any members of ARRAY are a substring in STRING. */
5428 substring_member_of_array (string, array)
5429 char *string, **array;
5431 static char *strindex ();
5435 if (strindex (string, *array))
5442 /* Whoops, Unix doesn't have strnicmp. */
5444 /* Compare at most COUNT characters from string1 to string2. Case
5447 strnicmp (string1, string2, count)
5448 char *string1, *string2;
5450 register char ch1, ch2;
5456 if (to_upper(ch1) == to_upper(ch2))
5463 /* strcmp (), but caseless. */
5465 stricmp (string1, string2)
5466 char *string1, *string2;
5468 register char ch1, ch2;
5470 while (*string1 && *string2)
5474 if (to_upper(ch1) != to_upper(ch2))
5477 return (*string1 | *string2);
5480 /* Determine if s2 occurs in s1. If so, return a pointer to the
5481 match in s1. The compare is case insensitive. */
5484 register char *s1, *s2;
5486 register int i, l = strlen (s2);
5487 register int len = strlen (s1);
5489 for (i = 0; (len - i) >= l; i++)
5490 if (strnicmp (&s1[i], s2, l) == 0)
5492 return ((char *)NULL);
5496 /* **************************************************************** */
5500 /* **************************************************************** */
5502 /* Since system V reads input differently than we do, I have to
5503 make a special version of getc for that. */
5508 #include <sys/errno.h>
5519 result = read (fileno (stream), &c, sizeof (char));
5520 if (result == sizeof (char))
5532 return (getc (stream));
5536 #ifdef STATIC_MALLOC
5538 /* **************************************************************** */
5540 /* xmalloc and xrealloc () */
5542 /* **************************************************************** */
5544 static void memory_error_and_abort ();
5550 char *temp = (char *)malloc (bytes);
5553 memory_error_and_abort ();
5558 xrealloc (pointer, bytes)
5562 char *temp = (char *)realloc (pointer, bytes);
5565 memory_error_and_abort ();
5570 memory_error_and_abort ()
5572 fprintf (stderr, "readline: Out of virtual memory!\n");
5575 #endif /* STATIC_MALLOC */
5578 /* **************************************************************** */
5580 /* Testing Readline */
5582 /* **************************************************************** */
5588 HIST_ENTRY **history_list ();
5589 char *temp = (char *)NULL;
5590 char *prompt = "readline% ";
5595 temp = readline (prompt);
5601 /* If there is anything on the line, print it and remember it. */
5604 fprintf (stderr, "%s\r\n", temp);
5608 /* Check for `command' that we handle. */
5609 if (strcmp (temp, "quit") == 0)
5612 if (strcmp (temp, "list") == 0) {
5613 HIST_ENTRY **list = history_list ();
5616 for (i = 0; list[i]; i++) {
5617 fprintf (stderr, "%d: %s\r\n", i, list[i]->line);
5618 free (list[i]->line);
5632 * compile-command: "gcc -g -traditional -I. -I.. -DTEST -o readline readline.c keymaps.o funmap.o history.o -ltermcap"