This commit was generated by cvs2svn to track changes on a CVS vendor
[external/binutils.git] / readline / readline.c
1 /* readline.c -- a general facility for reading lines of input
2    with emacs style editing and completion. */
3
4 /* Copyright (C) 1987,1989 Free Software Foundation, Inc.
5
6    This file contains the Readline Library (the Library), a set of
7    routines for providing Emacs style line input to programs that ask
8    for it.
9
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)
13    any later version.
14
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.
19
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. */
24
25 /* Remove these declarations when we have a complete libgnu.a. */
26 #define STATIC_MALLOC
27 #ifndef STATIC_MALLOC
28 extern char *xmalloc (), *xrealloc ();
29 #else
30 static char *xmalloc (), *xrealloc ();
31 #endif
32
33 #include <stdio.h>
34 #include <sys/types.h>
35 #include <fcntl.h>
36 #include <sys/file.h>
37 #include <signal.h>
38
39 #ifdef __GNUC__
40 #define alloca __builtin_alloca
41 #else
42 #if defined (sparc) && defined (sun)
43 #include <alloca.h>
44 #endif
45 #endif
46
47 #define NEW_TTY_DRIVER
48 #if defined (SYSV) || defined (hpux)  || defined (Xenix)
49 #undef NEW_TTY_DRIVER
50 #include <termio.h>
51 #else
52 #include <sgtty.h>
53 #endif
54
55 #include <errno.h>
56 extern int errno;
57
58 #include <setjmp.h>
59
60 /* These next are for filename completion.  Perhaps this belongs
61    in a different place. */
62 #include <sys/stat.h>
63
64 #include <pwd.h>
65 #ifdef SYSV
66 struct passwd *getpwuid (), *getpwent ();
67 #endif
68
69 #define HACK_TERMCAP_MOTION
70
71 #ifndef SYSV
72 #include <sys/dir.h>
73 #else  /* SYSV */
74 #if defined (Xenix)
75 #include <sys/ndir.h>
76 #else
77 #ifdef hpux
78 #include <ndir.h>
79 #else
80 #include <dirent.h>
81 #define direct dirent
82 #define d_namlen d_reclen
83 #endif  /* hpux */
84 #endif  /* xenix */
85 #endif  /* SYSV */
86
87 /* Some standard library routines. */
88 #include "readline.h"
89 #include "history.h"
90
91 #ifndef digit
92 #define digit(c)  ((c) >= '0' && (c) <= '9')
93 #endif
94
95 #ifndef isletter
96 #define isletter(c) (((c) >= 'A' && (c) <= 'Z') || ((c) >= 'a' && (c) <= 'z'))
97 #endif
98
99 #ifndef digit_value
100 #define digit_value(c) ((c) - '0')
101 #endif
102
103 #ifndef member
104 char *index ();
105 #define member(c, s) ((c) ? index ((s), (c)) : 0)
106 #endif
107
108 #ifndef isident
109 #define isident(c) ((isletter(c) || digit(c) || c == '_'))
110 #endif
111
112 #ifndef exchange
113 #define exchange(x, y) {int temp = x; x = y; y = temp;}
114 #endif
115
116 static update_line ();
117 static void output_character_function ();
118 static delete_chars ();
119 static delete_chars ();
120 static insert_some_chars ();
121
122 #ifdef VOID_SIGHANDLER
123 #define sighandler void
124 #else
125 #define sighandler int
126 #endif
127
128 /* This typedef is equivalant to the one for Function; it allows us
129    to say SigHandler *foo = signal (SIGKILL, SIG_IGN); */
130 typedef sighandler SigHandler ();
131
132 /* If on, then readline handles signals in a way that doesn't screw. */
133 #define HANDLE_SIGNALS
134
135 \f
136 /* **************************************************************** */
137 /*                                                                  */
138 /*                      Line editing input utility                  */
139 /*                                                                  */
140 /* **************************************************************** */
141
142 /* A pointer to the keymap that is currently in use.
143    By default, it is the standard emacs keymap. */
144 Keymap keymap = emacs_standard_keymap;
145
146 #define vi_mode 0
147 #define emacs_mode 1
148
149 /* The current style of editing. */
150 int rl_editing_mode = emacs_mode;
151
152 /* Non-zero if the previous command was a kill command. */
153 static int last_command_was_kill = 0;
154
155 /* The current value of the numeric argument specified by the user. */
156 int rl_numeric_arg = 1;
157
158 /* Non-zero if an argument was typed. */
159 int rl_explicit_arg = 0;
160
161 /* Temporary value used while generating the argument. */
162 static int arg_sign = 1;
163
164 /* Non-zero means we have been called at least once before. */
165 static int rl_initialized = 0;
166
167 /* If non-zero, this program is running in an EMACS buffer. */
168 static char *running_in_emacs = (char *)NULL;
169
170 /* The current offset in the current input line. */
171 int rl_point;
172
173 /* Mark in the current input line. */
174 int rl_mark;
175
176 /* Length of the current input line. */
177 int rl_end;
178
179 /* Make this non-zero to return the current input_line. */
180 int rl_done;
181
182 /* The last function executed by readline. */
183 Function *rl_last_func = (Function *)NULL;
184
185 /* Top level environment for readline_internal (). */
186 static jmp_buf readline_top_level;
187
188 /* The streams we interact with. */
189 static FILE *in_stream, *out_stream;
190
191 /* The names of the streams that we do input and output to. */
192 FILE *rl_instream = stdin, *rl_outstream = stdout;
193
194 /* Non-zero means echo characters as they are read. */
195 int readline_echoing_p = 1;
196
197 /* Current prompt. */
198 char *rl_prompt;
199
200 /* The number of characters read in order to type this complete command. */
201 int rl_key_sequence_length = 0;
202
203 /* If non-zero, then this is the address of a function to call just
204    before readline_internal () prints the first prompt. */
205 Function *rl_startup_hook = (Function *)NULL;
206
207 /* If non-zero, then this is the address of a function to call when
208    completing on a directory name.  The function is called with
209    the address of a string (the current directory name) as an arg. */
210 Function *rl_symbolic_link_hook = (Function *)NULL;
211
212 /* What we use internally.  You should always refer to RL_LINE_BUFFER. */
213 static char *the_line;
214
215 /* The character that can generate an EOF.  Really read from
216    the terminal driver... just defaulted here. */
217 static int eof_char = CTRL ('D');
218
219 /* Non-zero makes this the next keystroke to read. */
220 int rl_pending_input = 0;
221
222 /* Pointer to a useful terminal name. */
223 char *rl_terminal_name = (char *)NULL;
224
225 /* Line buffer and maintenence. */
226 char *rl_line_buffer = (char *)NULL;
227 static int rl_line_buffer_len = 0;
228 #define DEFAULT_BUFFER_SIZE 256
229
230 \f
231 /* **************************************************************** */
232 /*                                                                  */
233 /*                      `Forward' declarations                      */
234 /*                                                                  */
235 /* **************************************************************** */
236
237 /* Non-zero means do not parse any lines other than comments and
238    parser directives. */
239 static unsigned char parsing_conditionalized_out = 0;
240
241 /* Caseless strcmp (). */
242 static int stricmp (), strnicmp ();
243
244 /* Non-zero means to save keys that we dispatch on in a kbd macro. */
245 static int defining_kbd_macro = 0;
246
247 \f
248 /* **************************************************************** */
249 /*                                                                  */
250 /*                      Top Level Functions                         */
251 /*                                                                  */
252 /* **************************************************************** */
253
254 /* Read a line of input.  Prompt with PROMPT.  A NULL PROMPT means
255    none.  A return value of NULL means that EOF was encountered. */
256 char *
257 readline (prompt)
258      char *prompt;
259 {
260   static rl_prep_terminal (), rl_deprep_terminal ();
261   char *readline_internal ();
262   char *value;
263
264   rl_prompt = prompt;
265
266   /* If we are at EOF return a NULL string. */
267   if (rl_pending_input == EOF)
268     {
269       rl_pending_input = 0;
270       return ((char *)NULL);
271     }
272
273   rl_initialize ();
274   rl_prep_terminal ();
275
276 #ifdef HANDLE_SIGNALS
277   rl_set_signals ();
278 #endif
279
280   value = readline_internal ();
281   rl_deprep_terminal ();
282
283 #ifdef HANDLE_SIGNALS
284   rl_clear_signals ();
285 #endif
286
287   return (value);
288 }
289
290 /* Read a line of input from the global rl_instream, doing output on
291    the global rl_outstream.
292    If rl_prompt is non-null, then that is our prompt. */
293 char *
294 readline_internal ()
295 {
296   int lastc, c, eof_found;
297
298   in_stream = rl_instream; out_stream = rl_outstream;
299   lastc = eof_found = 0;
300
301   if (rl_startup_hook)
302     (*rl_startup_hook) ();
303
304   if (!readline_echoing_p)
305     {
306       if (rl_prompt)
307         {
308           fprintf (out_stream, "%s", rl_prompt);
309           fflush (out_stream);
310         }
311     }
312   else
313     {
314       rl_on_new_line ();
315       rl_redisplay ();
316 #ifdef VI_MODE
317       if (rl_editing_mode == vi_mode)
318         rl_vi_insertion_mode ();
319 #endif /* VI_MODE */
320     }
321
322   while (!rl_done)
323     {
324       int lk = last_command_was_kill;
325       int code = setjmp (readline_top_level);
326
327       if (code)
328         rl_redisplay ();
329
330       if (!rl_pending_input)
331         {
332           /* Then initialize the argument and number of keys read. */
333           rl_init_argument ();
334           rl_key_sequence_length = 0;
335         }
336
337       c = rl_read_key ();
338
339       /* EOF typed to a non-blank line is a <NL>. */
340       if (c == EOF && rl_end)
341         c = NEWLINE;
342
343       /* The character eof_char typed to blank line, and not as the
344          previous character is interpreted as EOF. */
345       if (((c == eof_char && lastc != c) || c == EOF) && !rl_end)
346         {
347           eof_found = 1;
348           break;
349         }
350
351       lastc = c;
352       rl_dispatch (c, keymap);
353
354       /* If there was no change in last_command_was_kill, then no kill
355          has taken place.  Note that if input is pending we are reading
356          a prefix command, so nothing has changed yet. */
357       if (!rl_pending_input)
358         {
359           if (lk == last_command_was_kill)
360             last_command_was_kill = 0;
361         }
362
363 #ifdef VI_MODE
364       /* In vi mode, when you exit insert mode, the cursor moves back
365          over the previous character.  We explicitly check for that here. */
366       if (rl_editing_mode == vi_mode && keymap == vi_movement_keymap)
367         rl_vi_check ();
368 #endif
369
370       if (!rl_done)
371         rl_redisplay ();
372     }
373
374   /* Restore the original of this history line, iff the line that we
375      are editing was originally in the history, AND the line has changed. */
376   {
377     HIST_ENTRY *entry = current_history ();
378
379     if (entry && rl_undo_list)
380       {
381         char *temp = savestring (the_line);
382         rl_revert_line ();
383         entry = replace_history_entry (where_history (), the_line,
384                                        (HIST_ENTRY *)NULL);
385         free_history_entry (entry);
386
387         strcpy (the_line, temp);
388         free (temp);
389       }
390   }
391
392   /* At any rate, it is highly likely that this line has an undo list.  Get
393      rid of it now. */
394   if (rl_undo_list)
395     free_undo_list ();
396
397   if (eof_found)
398     return (char *)NULL;
399   else
400     return (savestring (the_line));
401 }
402
403 \f
404 /* **************************************************************** */
405 /*                                                                  */
406 /*                         Signal Handling                          */
407 /*                                                                  */
408 /* **************************************************************** */
409
410 #ifdef SIGWINCH
411 static SigHandler *old_sigwinch = (SigHandler *)NULL;
412
413 static sighandler
414 rl_handle_sigwinch (sig, code, scp)
415      int sig, code;
416      struct sigcontext *scp;
417 {
418   char *term = rl_terminal_name, *getenv ();
419
420   if (readline_echoing_p)
421     {
422       if (!term)
423         term = getenv ("TERM");
424       if (!term)
425         term = "dumb";
426       rl_reset_terminal (term);
427 #ifdef NEVER
428       crlf ();
429       rl_forced_update_display ();
430 #endif
431     }
432
433   if (old_sigwinch &&
434       old_sigwinch != (SigHandler *)SIG_IGN &&
435       old_sigwinch != (SigHandler *)SIG_DFL)
436     (*old_sigwinch)(sig, code, scp);
437 }
438 #endif  /* SIGWINCH */
439
440 #ifdef HANDLE_SIGNALS
441 /* Interrupt handling. */
442 static SigHandler *old_int  = (SigHandler *)NULL,
443                   *old_tstp = (SigHandler *)NULL,
444                   *old_ttou = (SigHandler *)NULL,
445                   *old_ttin = (SigHandler *)NULL,
446                   *old_cont = (SigHandler *)NULL;
447
448 /* Handle an interrupt character. */
449 static sighandler
450 rl_signal_handler (sig, code, scp)
451      int sig, code;
452      struct sigcontext *scp;
453 {
454   static rl_prep_terminal (), rl_deprep_terminal ();
455
456   switch (sig)
457     {
458     case SIGINT:
459       free_undo_list ();
460       rl_clear_message ();
461       rl_init_argument ();
462
463 #ifdef SIGTSTP
464     case SIGTSTP:
465     case SIGTTOU:
466     case SIGTTIN:
467 #endif
468
469       rl_clean_up_for_exit ();
470       rl_deprep_terminal ();
471       rl_clear_signals ();
472       rl_pending_input = 0;
473
474       kill (getpid (), sig);
475       sigsetmask (0);
476
477       rl_prep_terminal ();
478       rl_set_signals ();
479     }
480 }
481
482 rl_set_signals ()
483 {
484   old_int = (SigHandler *)signal (SIGINT, rl_signal_handler);
485   if (old_int == (SigHandler *)SIG_IGN)
486     signal (SIGINT, SIG_IGN);
487
488 #ifdef SIGTSTP
489   old_tstp = (SigHandler *)signal (SIGTSTP, rl_signal_handler);
490   if (old_tstp == (SigHandler *)SIG_IGN)
491     signal (SIGTSTP, SIG_IGN);
492 #endif
493 #ifdef SIGTTOU
494   old_ttou = (SigHandler *)signal (SIGTTOU, rl_signal_handler);
495   old_ttin = (SigHandler *)signal (SIGTTIN, rl_signal_handler);
496
497   if (old_tstp == (SigHandler *)SIG_IGN)
498     {
499       signal (SIGTTOU, SIG_IGN);
500       signal (SIGTTIN, SIG_IGN);
501     }
502 #endif
503
504 #ifdef SIGWINCH
505   old_sigwinch = (SigHandler *)signal (SIGWINCH, rl_handle_sigwinch);
506 #endif
507 }
508
509 rl_clear_signals ()
510 {
511   signal (SIGINT, old_int);
512
513 #ifdef SIGTSTP
514   signal (SIGTSTP, old_tstp);
515 #endif
516
517 #ifdef SIGTTOU
518   signal (SIGTTOU, old_ttou);
519   signal (SIGTTIN, old_ttin);
520 #endif
521
522 #ifdef SIGWINCH
523       signal (SIGWINCH, old_sigwinch);
524 #endif
525 }
526 #endif  /* HANDLE_SIGNALS */
527
528 \f
529 /* **************************************************************** */
530 /*                                                                  */
531 /*                      Character Input Buffering                   */
532 /*                                                                  */
533 /* **************************************************************** */
534
535 /* If the terminal was in xoff state when we got to it, then xon_char
536    contains the character that is supposed to start it again. */
537 static int xon_char, xoff_state;
538 static int pop_index = 0, push_index = 0, ibuffer_len = 511;
539 static unsigned char ibuffer[512];
540
541 /* Non-null means it is a pointer to a function to run while waiting for
542    character input. */
543 Function *rl_event_hook = (Function *)NULL;
544
545 #define any_typein (push_index != pop_index)
546
547 /* Add KEY to the buffer of characters to be read. */
548 rl_stuff_char (key)
549      int key;
550 {
551   if (key == EOF)
552     {
553       key = NEWLINE;
554       rl_pending_input = EOF;
555     }
556   ibuffer[push_index++] = key;
557   if (push_index >= ibuffer_len)
558     push_index = 0;
559 }
560
561 /* Return the amount of space available in the
562    buffer for stuffing characters. */
563 int
564 ibuffer_space ()
565 {
566   if (pop_index > push_index)
567     return (pop_index - push_index);
568   else
569     return (ibuffer_len - (push_index - pop_index));
570 }
571
572 /* Get a key from the buffer of characters to be read.
573    Return the key in KEY.
574    Result is KEY if there was a key, or 0 if there wasn't. */
575 int
576 rl_get_char (key)
577      int *key;
578 {
579   if (push_index == pop_index)
580     return (0);
581
582   *key = ibuffer[pop_index++];
583
584   if (pop_index >= ibuffer_len)
585     pop_index = 0;
586
587   return (1);
588 }
589
590 /* Stuff KEY into the *front* of the input buffer.
591    Returns non-zero if successful, zero if there is
592    no space left in the buffer. */
593 int
594 rl_unget_char (key)
595      int key;
596 {
597   if (ibuffer_space ())
598     {
599       pop_index--;
600       if (pop_index < 0)
601         pop_index = ibuffer_len - 1;
602       ibuffer[pop_index] = key;
603       return (1);
604     }
605   return (0);
606 }
607
608 /* If a character is available to be read, then read it
609    and stuff it into IBUFFER.  Otherwise, just return. */
610 rl_gather_tyi ()
611 {
612   int tty = fileno (in_stream);
613   register int tem, result = -1;
614   long chars_avail;
615   char input;
616
617 #ifdef FIONREAD
618   result = ioctl (tty, FIONREAD, &chars_avail);
619 #endif
620
621   if (result == -1)
622     {
623       fcntl (tty, F_SETFL, O_NDELAY);
624       chars_avail = read (tty, &input, 1);
625       fcntl (tty, F_SETFL, 0);
626       if (chars_avail == -1 && errno == EAGAIN)
627         return;
628     }
629
630   tem = ibuffer_space ();
631
632   if (chars_avail > tem)
633     chars_avail = tem;
634
635   /* One cannot read all of the available input.  I can only read a single
636      character at a time, or else programs which require input can be
637      thwarted.  If the buffer is larger than one character, I lose.
638      Damn! */
639   if (tem < ibuffer_len)
640     chars_avail = 0;
641
642   if (result != -1)
643     {
644       while (chars_avail--)
645         rl_stuff_char (rl_getc (in_stream));
646     }
647   else
648     {
649       if (chars_avail)
650         rl_stuff_char (input);
651     }
652 }
653
654 /* Read a key, including pending input. */
655 int
656 rl_read_key ()
657 {
658   int c;
659
660   rl_key_sequence_length++;
661
662   if (rl_pending_input)
663     {
664       c = rl_pending_input;
665       rl_pending_input = 0;
666     }
667   else
668     {
669       static int next_macro_key ();
670
671       /* If input is coming from a macro, then use that. */
672       if (c = next_macro_key ())
673         return (c);
674
675       /* If the user has an event function, then call it periodically. */
676       if (rl_event_hook)
677         {
678           while (rl_event_hook && !rl_get_char (&c))
679             {
680               (*rl_event_hook) ();
681               rl_gather_tyi ();
682             }
683         }
684       else
685         {
686           if (!rl_get_char (&c))
687             c = rl_getc (in_stream);
688         }
689     }
690
691 #ifdef NEVER  /* This breaks supdup to 4.0.3c machines. */
692 #ifdef TIOCSTART
693   /* Ugh.  But I can't think of a better way. */
694   if (xoff_state && c == xon_char)
695     {
696       ioctl (fileno (in_stream), TIOCSTART, 0);
697       xoff_state = 0;
698       return (rl_read_key ());
699     }
700 #endif /* TIOCSTART */
701 #endif
702
703   return (c);
704 }
705
706 /* I'm beginning to hate the declaration rules for various compilers. */
707 static void add_macro_char ();
708
709 /* Do the command associated with KEY in MAP.
710    If the associated command is really a keymap, then read
711    another key, and dispatch into that map. */
712 rl_dispatch (key, map)
713      register int key;
714      Keymap map;
715 {
716
717   if (defining_kbd_macro)
718     add_macro_char (key);
719
720   if (key > 127 && key < 256)
721     {
722       if (map[ESC].type == ISKMAP)
723         {
724           map = (Keymap)map[ESC].function;
725           key -= 128;
726           rl_dispatch (key, map);
727         }
728       else
729         ding ();
730       return;
731     }
732
733   switch (map[key].type)
734     {
735     case ISFUNC:
736       {
737         Function *func = map[key].function;
738
739         if (func != (Function *)NULL)
740           {
741             /* Special case rl_do_lowercase_version (). */
742             if (func == rl_do_lowercase_version)
743               {
744                 rl_dispatch (to_lower (key), map);
745                 return;
746               }
747
748             (*map[key].function)(rl_numeric_arg * arg_sign, key);
749           }
750         else
751           {
752             ding ();
753             return;
754           }
755       }
756       break;
757
758     case ISKMAP:
759       if (map[key].function != (Function *)NULL)
760         {
761           int newkey;
762
763           rl_key_sequence_length++;
764           newkey = rl_read_key ();
765           rl_dispatch (newkey, (Keymap)map[key].function);
766         }
767       else
768         {
769           ding ();
770           return;
771         }
772       break;
773
774     case ISMACR:
775       if (map[key].function != (Function *)NULL)
776         {
777           static with_macro_input ();
778           char *macro = savestring ((char *)map[key].function);
779
780           with_macro_input (macro);
781           return;
782         }
783       break;
784     }
785
786   /* If we have input pending, then the last command was a prefix
787      command.  Don't change the state of rl_last_func. */
788   if (!rl_pending_input)
789     rl_last_func = map[key].function;
790 }
791
792 \f
793 /* **************************************************************** */
794 /*                                                                  */
795 /*                      Hacking Keyboard Macros                     */
796 /*                                                                  */
797 /* **************************************************************** */
798
799 /* The currently executing macro string.  If this is non-zero,
800    then it is a malloc ()'ed string where input is coming from. */
801 static char *executing_macro = (char *)NULL;
802
803 /* The offset in the above string to the next character to be read. */
804 static int executing_macro_index = 0;
805
806 /* The current macro string being built.  Characters get stuffed
807    in here by add_macro_char (). */
808 static char *current_macro = (char *)NULL;
809
810 /* The size of the buffer allocated to current_macro. */
811 static int current_macro_size = 0;
812
813 /* The index at which characters are being added to current_macro. */
814 static int current_macro_index = 0;
815
816 /* A structure used to save nested macro strings.
817    It is a linked list of string/index for each saved macro. */
818 struct saved_macro {
819   struct saved_macro *next;
820   char *string;
821   int index;
822 };
823
824 /* The list of saved macros. */
825 struct saved_macro *macro_list = (struct saved_macro *)NULL;
826
827 /* Forward declarations of static functions.  Thank you C. */
828 static void push_executing_macro (), pop_executing_macro ();
829
830 /* This one has to be declared earlier in the file. */
831 /* static void add_macro_char (); */
832
833 /* Set up to read subsequent input from STRING.
834    STRING is free ()'ed when we are done with it. */
835 static
836 with_macro_input (string)
837      char *string;
838 {
839   push_executing_macro ();
840   executing_macro = string;
841   executing_macro_index = 0;
842 }
843
844 /* Return the next character available from a macro, or 0 if
845    there are no macro characters. */
846 static int
847 next_macro_key ()
848 {
849   if (!executing_macro)
850     return (0);
851
852   if (!executing_macro[executing_macro_index])
853     {
854       pop_executing_macro ();
855       return (next_macro_key ());
856     }
857
858   return (executing_macro[executing_macro_index++]);
859 }
860
861 /* Save the currently executing macro on a stack of saved macros. */
862 static void
863 push_executing_macro ()
864 {
865   struct saved_macro *saver;
866
867   saver = (struct saved_macro *)xmalloc (sizeof (struct saved_macro));
868   saver->next = macro_list;
869   saver->index = executing_macro_index;
870   saver->string = executing_macro;
871
872   macro_list = saver;
873 }
874
875 /* Discard the current macro, replacing it with the one
876    on the top of the stack of saved macros. */
877 static void
878 pop_executing_macro ()
879 {
880   if (executing_macro)
881     free (executing_macro);
882
883   executing_macro = (char *)NULL;
884   executing_macro_index = 0;
885
886   if (macro_list)
887     {
888       struct saved_macro *disposer = macro_list;
889       executing_macro = macro_list->string;
890       executing_macro_index = macro_list->index;
891       macro_list = macro_list->next;
892       free (disposer);
893     }
894 }
895
896 /* Add a character to the macro being built. */
897 static void
898 add_macro_char (c)
899      int c;
900 {
901   if (current_macro_index + 1 >= current_macro_size)
902     {
903       if (!current_macro)
904         current_macro = (char *)xmalloc (current_macro_size = 25);
905       else
906         current_macro =
907           (char *)xrealloc (current_macro, current_macro_size += 25);
908     }
909
910   current_macro[current_macro_index++] = c;
911   current_macro[current_macro_index] = '\0';
912 }
913
914 /* Begin defining a keyboard macro.
915    Keystrokes are recorded as they are executed.
916    End the definition with rl_end_kbd_macro ().
917    If a numeric argument was explicitly typed, then append this
918    definition to the end of the existing macro, and start by
919    re-executing the existing macro. */
920 rl_start_kbd_macro (ignore1, ignore2)
921      int ignore1, ignore2;
922 {
923   if (defining_kbd_macro)
924     rl_abort ();
925
926   if (rl_explicit_arg)
927     {
928       if (current_macro)
929         with_macro_input (savestring (current_macro));
930     }
931   else
932     current_macro_index = 0;
933
934   defining_kbd_macro = 1;
935 }
936
937 /* Stop defining a keyboard macro.
938    A numeric argument says to execute the macro right now,
939    that many times, counting the definition as the first time. */
940 rl_end_kbd_macro (count, ignore)
941      int count, ignore;
942 {
943   if (!defining_kbd_macro)
944     rl_abort ();
945
946   current_macro_index -= (rl_key_sequence_length - 1);
947   current_macro[current_macro_index] = '\0';
948
949   defining_kbd_macro = 0;
950
951   rl_call_last_kbd_macro (--count, 0);
952 }
953
954 /* Execute the most recently defined keyboard macro.
955    COUNT says how many times to execute it. */
956 rl_call_last_kbd_macro (count, ignore)
957      int count, ignore;
958 {
959   if (!current_macro)
960     rl_abort ();
961
962   while (count--)
963     with_macro_input (savestring (current_macro));
964 }
965
966 \f
967 /* **************************************************************** */
968 /*                                                                  */
969 /*                      Initializations                             */
970 /*                                                                  */
971 /* **************************************************************** */
972
973 /* Initliaze readline (and terminal if not already). */
974 rl_initialize ()
975 {
976   extern char *rl_display_prompt;
977
978   /* If we have never been called before, initialize the
979      terminal and data structures. */
980   if (!rl_initialized)
981     {
982       readline_initialize_everything ();
983       rl_initialized++;
984     }
985
986   /* Initalize the current line information. */
987   rl_point = rl_end = 0;
988   the_line = rl_line_buffer;
989   the_line[0] = 0;
990
991   /* We aren't done yet.  We haven't even gotten started yet! */
992   rl_done = 0;
993
994   /* Tell the history routines what is going on. */
995   start_using_history ();
996
997   /* Make the display buffer match the state of the line. */
998   {
999     extern char *rl_display_prompt;
1000     extern int forced_display;
1001
1002     rl_on_new_line ();
1003
1004     rl_display_prompt = rl_prompt ? rl_prompt : "";
1005     forced_display = 1;
1006   }
1007
1008   /* No such function typed yet. */
1009   rl_last_func = (Function *)NULL;
1010
1011   /* Parsing of key-bindings begins in an enabled state. */
1012   parsing_conditionalized_out = 0;
1013 }
1014
1015 /* Initialize the entire state of the world. */
1016 readline_initialize_everything ()
1017 {
1018   /* Find out if we are running in Emacs. */
1019   running_in_emacs = (char *)getenv ("EMACS");
1020
1021   /* Allocate data structures. */
1022   if (!rl_line_buffer)
1023     rl_line_buffer =
1024       (char *)xmalloc (rl_line_buffer_len = DEFAULT_BUFFER_SIZE);
1025
1026   /* Initialize the terminal interface. */
1027   init_terminal_io ((char *)NULL);
1028
1029   /* Bind tty characters to readline functions. */
1030   readline_default_bindings ();
1031
1032   /* Initialize the function names. */
1033   rl_initialize_funmap ();
1034
1035   /* Read in the init file. */
1036   rl_read_init_file ((char *)NULL);
1037
1038   /* If the completion parser's default word break characters haven't
1039      been set yet, then do so now. */
1040   {
1041     extern char *rl_completer_word_break_characters;
1042     extern char *rl_basic_word_break_characters;
1043
1044     if (rl_completer_word_break_characters == (char *)NULL)
1045       rl_completer_word_break_characters = rl_basic_word_break_characters;
1046   }
1047 }
1048
1049 /* If this system allows us to look at the values of the regular
1050    input editing characters, then bind them to their readline
1051    equivalents. */
1052 readline_default_bindings ()
1053 {
1054
1055 #ifdef NEW_TTY_DRIVER
1056   struct sgttyb ttybuff;
1057   int tty = fileno (rl_instream);
1058
1059   if (ioctl (tty, TIOCGETP, &ttybuff) != -1)
1060     {
1061       int erase = ttybuff.sg_erase, kill = ttybuff.sg_kill;
1062
1063       if (erase != -1 && keymap[erase].type == ISFUNC)
1064         keymap[erase].function = rl_rubout;
1065
1066       if (kill != -1 && keymap[kill].type == ISFUNC)
1067         keymap[kill].function = rl_unix_line_discard;
1068     }
1069
1070 #ifdef TIOCGLTC
1071   {
1072     struct ltchars lt;
1073
1074     if (ioctl (tty, TIOCGLTC, &lt) != -1)
1075       {
1076         int erase = lt.t_werasc, nextc = lt.t_lnextc;
1077
1078         if (erase != -1 && keymap[erase].type == ISFUNC)
1079           keymap[erase].function = rl_unix_word_rubout;
1080
1081         if (nextc != -1 && keymap[nextc].type == ISFUNC)
1082           keymap[nextc].function = rl_quoted_insert;
1083       }
1084   }
1085 #endif /* TIOCGLTC */
1086 #else /* not NEW_TTY_DRIVER */
1087   struct termio ttybuff;
1088   int tty = fileno (rl_instream);
1089
1090   if (ioctl (tty, TCGETA, &ttybuff) != -1)
1091     {
1092       int erase = ttybuff.c_cc[VERASE];
1093       int kill = ttybuff.c_cc[VKILL];
1094
1095       if (erase != -1 && keymap[(unsigned char)erase].type == ISFUNC)
1096         keymap[(unsigned char)erase].function = rl_rubout;
1097
1098       if (kill != -1 && keymap[(unsigned char)kill].type == ISFUNC)
1099         keymap[(unsigned char)kill].function = rl_unix_line_discard;
1100     }
1101 #endif /* NEW_TTY_DRIVER */
1102 }
1103
1104 \f
1105 /* **************************************************************** */
1106 /*                                                                  */
1107 /*                      Numeric Arguments                           */
1108 /*                                                                  */
1109 /* **************************************************************** */
1110
1111 /* Handle C-u style numeric args, as well as M--, and M-digits. */
1112
1113 /* Add the current digit to the argument in progress. */
1114 rl_digit_argument (ignore, key)
1115      int ignore, key;
1116 {
1117   rl_pending_input = key;
1118   rl_digit_loop ();
1119 }
1120
1121 /* What to do when you abort reading an argument. */
1122 rl_discard_argument ()
1123 {
1124   ding ();
1125   rl_clear_message ();
1126   rl_init_argument ();
1127 }
1128
1129 /* Create a default argument. */
1130 rl_init_argument ()
1131 {
1132   rl_numeric_arg = arg_sign = 1;
1133   rl_explicit_arg = 0;
1134 }
1135
1136 /* C-u, universal argument.  Multiply the current argument by 4.
1137    Read a key.  If the key has nothing to do with arguments, then
1138    dispatch on it.  If the key is the abort character then abort. */
1139 rl_universal_argument ()
1140 {
1141   rl_numeric_arg *= 4;
1142   rl_digit_loop ();
1143 }
1144
1145 rl_digit_loop ()
1146 {
1147   int key, c;
1148   while (1)
1149     {
1150       rl_message ("(arg: %d) ", arg_sign * rl_numeric_arg);
1151       key = c = rl_read_key ();
1152
1153       if (keymap[c].type == ISFUNC &&
1154           keymap[c].function == rl_universal_argument)
1155         {
1156           rl_numeric_arg *= 4;
1157           continue;
1158         }
1159       c = UNMETA (c);
1160       if (numeric (c))
1161         {
1162           if (rl_explicit_arg)
1163             rl_numeric_arg = (rl_numeric_arg * 10) + (c - '0');
1164           else
1165             rl_numeric_arg = (c - '0');
1166           rl_explicit_arg = 1;
1167         }
1168       else
1169         {
1170           if (c == '-' && !rl_explicit_arg)
1171             {
1172               rl_numeric_arg = 1;
1173               arg_sign = -1;
1174             }
1175           else
1176             {
1177               rl_clear_message ();
1178               rl_dispatch (key, keymap);
1179               return;
1180             }
1181         }
1182     }
1183 }
1184
1185 \f
1186 /* **************************************************************** */
1187 /*                                                                  */
1188 /*                      Display stuff                               */
1189 /*                                                                  */
1190 /* **************************************************************** */
1191
1192 /* This is the stuff that is hard for me.  I never seem to write good
1193    display routines in C.  Let's see how I do this time. */
1194
1195 /* (PWP) Well... Good for a simple line updater, but totally ignores
1196    the problems of input lines longer than the screen width.
1197
1198    update_line and the code that calls it makes a multiple line,
1199    automatically wrapping line update.  Carefull attention needs
1200    to be paid to the vertical position variables.
1201
1202    handling of terminals with autowrap on (incl. DEC braindamage)
1203    could be improved a bit.  Right now I just cheat and decrement
1204    screenwidth by one. */
1205
1206 /* Keep two buffers; one which reflects the current contents of the
1207    screen, and the other to draw what we think the new contents should
1208    be.  Then compare the buffers, and make whatever changes to the
1209    screen itself that we should.  Finally, make the buffer that we
1210    just drew into be the one which reflects the current contents of the
1211    screen, and place the cursor where it belongs.
1212
1213    Commands that want to can fix the display themselves, and then let
1214    this function know that the display has been fixed by setting the
1215    RL_DISPLAY_FIXED variable.  This is good for efficiency. */
1216
1217 /* Termcap variables: */
1218 extern char *term_up, *term_dc, *term_cr;
1219 extern int screenheight, screenwidth, terminal_can_insert;
1220
1221 /* What YOU turn on when you have handled all redisplay yourself. */
1222 int rl_display_fixed = 0;
1223
1224 /* The visible cursor position.  If you print some text, adjust this. */
1225 int last_c_pos = 0;
1226 int last_v_pos = 0;
1227
1228 /* The last left edge of text that was displayed.  This is used when
1229    doing horizontal scrolling.  It shifts in thirds of a screenwidth. */
1230 static int last_lmargin = 0;
1231
1232 /* The line display buffers.  One is the line currently displayed on
1233    the screen.  The other is the line about to be displayed. */
1234 static char *visible_line = (char *)NULL;
1235 static char *invisible_line = (char *)NULL;
1236
1237 /* Number of lines currently on screen minus 1. */
1238 int vis_botlin = 0;
1239
1240 /* A buffer for `modeline' messages. */
1241 char msg_buf[128];
1242
1243 /* Non-zero forces the redisplay even if we thought it was unnecessary. */
1244 int forced_display = 0;
1245
1246 /* The stuff that gets printed out before the actual text of the line.
1247    This is usually pointing to rl_prompt. */
1248 char *rl_display_prompt = (char *)NULL;
1249
1250 /* Default and initial buffer size.  Can grow. */
1251 static int line_size = 1024;
1252
1253 /* Non-zero means to always use horizontal scrolling in line display. */
1254 static int horizontal_scroll_mode = 0;
1255
1256 /* Non-zero means to display an asterisk at the starts of history lines
1257    which have been modified. */
1258 static int mark_modified_lines = 0;
1259
1260 /* I really disagree with this, but my boss (among others) insists that we
1261    support compilers that don't work.  I don't think we are gaining by doing
1262    so; what is the advantage in producing better code if we can't use it? */
1263 /* The following two declarations belong inside the
1264    function block, not here. */
1265 static void move_cursor_relative ();
1266 static void output_some_chars ();
1267 static void output_character_function ();
1268 static int compare_strings ();
1269
1270 /* Basic redisplay algorithm. */
1271 rl_redisplay ()
1272 {
1273   register int in, out, c, linenum;
1274   register char *line = invisible_line;
1275   int c_pos = 0;
1276   int inv_botlin = 0;           /* Number of lines in newly drawn buffer. */
1277
1278   extern int readline_echoing_p;
1279
1280   if (!readline_echoing_p)
1281     return;
1282
1283   if (!rl_display_prompt)
1284     rl_display_prompt = "";
1285
1286   if (!invisible_line)
1287     {
1288       visible_line = (char *)xmalloc (line_size);
1289       invisible_line = (char *)xmalloc (line_size);
1290       line = invisible_line;
1291       for (in = 0; in < line_size; in++)
1292         {
1293           visible_line[in] = 0;
1294           invisible_line[in] = 1;
1295         }
1296       rl_on_new_line ();
1297     }
1298
1299   /* Draw the line into the buffer. */
1300   c_pos = -1;
1301
1302   /* Mark the line as modified or not.  We only do this for history
1303      lines. */
1304   out = 0;
1305   if (mark_modified_lines && current_history () && rl_undo_list)
1306     {
1307       line[out++] = '*';
1308       line[out] = '\0';
1309     }
1310
1311   /* If someone thought that the redisplay was handled, but the currently
1312      visible line has a different modification state than the one about
1313      to become visible, then correct the callers misconception. */
1314   if (visible_line[0] != invisible_line[0])
1315     rl_display_fixed = 0;
1316
1317   strncpy (line + out,  rl_display_prompt, strlen (rl_display_prompt));
1318   out += strlen (rl_display_prompt);
1319   line[out] = '\0';
1320
1321   for (in = 0; in < rl_end; in++)
1322     {
1323       c = the_line[in];
1324
1325       if (out + 1 >= line_size)
1326         {
1327           line_size *= 2;
1328           visible_line = (char *)xrealloc (visible_line, line_size);
1329           invisible_line = (char *)xrealloc (invisible_line, line_size);
1330           line = invisible_line;
1331         }
1332
1333       if (in == rl_point)
1334         c_pos = out;
1335
1336       if (c > 127)
1337         {
1338           line[out++] = 'M';
1339           line[out++] = '-';
1340           line[out++] = c - 128;
1341         }
1342 #define DISPLAY_TABS
1343 #ifdef DISPLAY_TABS
1344       else if (c == '\t')
1345         {
1346           register int newout = (out | (int)7) + 1;
1347           while (out < newout)
1348             line[out++] = ' ';
1349         }
1350 #endif
1351       else if (c < 32)
1352         {
1353           line[out++] = 'C';
1354           line[out++] = '-';
1355           line[out++] = c + 64;
1356         }
1357       else
1358         line[out++] = c;
1359     }
1360   line[out] = '\0';
1361   if (c_pos < 0)
1362     c_pos = out;
1363
1364   /* PWP: now is when things get a bit hairy.  The visible and invisible
1365      line buffers are really multiple lines, which would wrap every
1366      (screenwidth - 1) characters.  Go through each in turn, finding
1367      the changed region and updating it.  The line order is top to bottom. */
1368
1369   /* If we can move the cursor up and down, then use multiple lines,
1370      otherwise, let long lines display in a single terminal line, and
1371      horizontally scroll it. */
1372
1373   if (!horizontal_scroll_mode && term_up && *term_up)
1374     {
1375       int total_screen_chars = (screenwidth * screenheight);
1376
1377       if (!rl_display_fixed || forced_display)
1378         {
1379           forced_display = 0;
1380
1381           /* If we have more than a screenful of material to display, then
1382              only display a screenful.  We should display the last screen,
1383              not the first.  I'll fix this in a minute. */
1384           if (out >= total_screen_chars)
1385             out = total_screen_chars - 1;
1386
1387           /* Number of screen lines to display. */
1388           inv_botlin = out / screenwidth;
1389
1390           /* For each line in the buffer, do the updating display. */
1391           for (linenum = 0; linenum <= inv_botlin; linenum++)
1392             update_line (linenum > vis_botlin ? ""
1393                          : &visible_line[linenum * screenwidth],
1394                          &invisible_line[linenum * screenwidth],
1395                          linenum);
1396
1397           /* We may have deleted some lines.  If so, clear the left over
1398              blank ones at the bottom out. */
1399           if (vis_botlin > inv_botlin)
1400             {
1401               char *tt;
1402               for (; linenum <= vis_botlin; linenum++)
1403                 {
1404                   tt = &visible_line[linenum * screenwidth];
1405                   move_vert (linenum);
1406                   move_cursor_relative (0, tt);
1407                   clear_to_eol ((linenum == vis_botlin)?
1408                                 strlen (tt) : screenwidth);
1409                 }
1410             }
1411           vis_botlin = inv_botlin;
1412
1413           /* Move the cursor where it should be. */
1414           move_vert (c_pos / screenwidth);
1415           move_cursor_relative (c_pos % screenwidth,
1416                                 &invisible_line[(c_pos / screenwidth) * screenwidth]);
1417         }
1418     }
1419   else                          /* Do horizontal scrolling. */
1420     {
1421       int lmargin;
1422
1423       /* Always at top line. */
1424       last_v_pos = 0;
1425
1426       /* If the display position of the cursor would be off the edge
1427          of the screen, start the display of this line at an offset that
1428          leaves the cursor on the screen. */
1429       if (c_pos - last_lmargin > screenwidth - 2)
1430         lmargin = (c_pos / (screenwidth / 3) - 2) * (screenwidth / 3);
1431       else if (c_pos - last_lmargin < 1)
1432         lmargin = ((c_pos - 1) / (screenwidth / 3)) * (screenwidth / 3);
1433       else
1434         lmargin = last_lmargin;
1435
1436       /* If the first character on the screen isn't the first character
1437          in the display line, indicate this with a special character. */
1438       if (lmargin > 0)
1439         line[lmargin] = '<';
1440
1441       if (lmargin + screenwidth < out)
1442         line[lmargin + screenwidth - 1] = '>';
1443
1444       if (!rl_display_fixed || forced_display || lmargin != last_lmargin)
1445         {
1446           forced_display = 0;
1447           update_line (&visible_line[last_lmargin],
1448                        &invisible_line[lmargin], 0);
1449
1450           move_cursor_relative (c_pos - lmargin, &invisible_line[lmargin]);
1451           last_lmargin = lmargin;
1452         }
1453     }
1454   fflush (out_stream);
1455
1456   /* Swap visible and non-visible lines. */
1457   {
1458     char *temp = visible_line;
1459     visible_line = invisible_line;
1460     invisible_line = temp;
1461     rl_display_fixed = 0;
1462   }
1463 }
1464
1465 /* PWP: update_line() is based on finding the middle difference of each
1466    line on the screen; vis:
1467
1468                              /old first difference
1469         /beginning of line   |              /old last same       /old EOL
1470         v                    v              v                    v
1471 old:    eddie> Oh, my little gruntle-buggy is to me, as lurgid as
1472 new:    eddie> Oh, my little buggy says to me, as lurgid as
1473         ^                    ^        ^                    ^
1474         \beginning of line   |        \new last same       \new end of line
1475                              \new first difference
1476
1477    All are character pointers for the sake of speed.  Special cases for
1478    no differences, as well as for end of line additions must be handeled.
1479
1480    Could be made even smarter, but this works well enough */
1481 static
1482 update_line (old, new, current_line)
1483      register char *old, *new;
1484      int current_line;
1485 {
1486   register char *ofd, *ols, *oe, *nfd, *nls, *ne;
1487   int lendiff, wsatend;
1488
1489   /* Find first difference. */
1490   for (ofd = old, nfd = new;
1491        (ofd - old < screenwidth) && *ofd && (*ofd == *nfd);
1492        ofd++, nfd++)
1493     ;
1494
1495   /* Move to the end of the screen line. */
1496   for (oe = ofd; ((oe - old) < screenwidth) && *oe; oe++);
1497   for (ne = nfd; ((ne - new) < screenwidth) && *ne; ne++);
1498
1499   /* If no difference, continue to next line. */
1500   if (ofd == oe && nfd == ne)
1501     return;
1502
1503   wsatend = 1;                  /* flag for trailing whitespace */
1504   ols = oe - 1;                 /* find last same */
1505   nls = ne - 1;
1506   while ((*ols == *nls) && (ols > ofd) && (nls > nfd))
1507     {
1508       if (*ols != ' ')
1509         wsatend = 0;
1510       ols--;
1511       nls--;
1512     }
1513
1514   if (wsatend)
1515     {
1516       ols = oe;
1517       nls = ne;
1518     }
1519   else if (*ols != *nls)
1520     {
1521       if (*ols)                 /* don't step past the NUL */
1522         ols++;
1523       if (*nls)
1524         nls++;
1525     }
1526
1527   move_vert (current_line);
1528   move_cursor_relative (ofd - old, old);
1529
1530   /* if (len (new) > len (old)) */
1531   lendiff = (nls - nfd) - (ols - ofd);
1532
1533   /* Insert (diff(len(old),len(new)) ch */
1534   if (lendiff > 0)
1535     {
1536       if (terminal_can_insert)
1537         {
1538           extern char *term_IC;
1539
1540           /* Sometimes it is cheaper to print the characters rather than
1541              use the terminal's capabilities. */
1542           if ((2 * (ne - nfd)) < lendiff && !term_IC)
1543             {
1544               output_some_chars (nfd, (ne - nfd));
1545               last_c_pos += (ne - nfd);
1546             }
1547           else
1548             {
1549               if (*ols)
1550                 {
1551                   insert_some_chars (nfd, lendiff);
1552                   last_c_pos += lendiff;
1553                 }
1554               else
1555                 {
1556                   /* At the end of a line the characters do not have to
1557                      be "inserted".  They can just be placed on the screen. */
1558                   output_some_chars (nfd, lendiff);
1559                   last_c_pos += lendiff;
1560                 }
1561               /* Copy (new) chars to screen from first diff to last match. */
1562               if (((nls - nfd) - lendiff) > 0)
1563                 {
1564                   output_some_chars (&nfd[lendiff], ((nls - nfd) - lendiff));
1565                   last_c_pos += ((nls - nfd) - lendiff);
1566                 }
1567             }
1568         }
1569       else
1570         {               /* cannot insert chars, write to EOL */
1571           output_some_chars (nfd, (ne - nfd));
1572           last_c_pos += (ne - nfd);
1573         }
1574     }
1575   else                          /* Delete characters from line. */
1576     {
1577       /* If possible and inexpensive to use terminal deletion, then do so. */
1578       if (term_dc && (2 * (ne - nfd)) >= (-lendiff))
1579         {
1580           if (lendiff)
1581             delete_chars (-lendiff); /* delete (diff) characters */
1582
1583           /* Copy (new) chars to screen from first diff to last match */
1584           if ((nls - nfd) > 0)
1585             {
1586               output_some_chars (nfd, (nls - nfd));
1587               last_c_pos += (nls - nfd);
1588             }
1589         }
1590       /* Otherwise, print over the existing material. */
1591       else
1592         {
1593           output_some_chars (nfd, (ne - nfd));
1594           last_c_pos += (ne - nfd);
1595           clear_to_eol ((oe - old) - (ne - new));
1596         }
1597     }
1598 }
1599
1600 /* (PWP) tell the update routines that we have moved onto a
1601    new (empty) line. */
1602 rl_on_new_line ()
1603 {
1604   if (visible_line)
1605     visible_line[0] = '\0';
1606
1607   last_c_pos = last_v_pos = 0;
1608   vis_botlin = last_lmargin = 0;
1609 }
1610
1611 /* Actually update the display, period. */
1612 rl_forced_update_display ()
1613 {
1614   if (visible_line)
1615     {
1616       register char *temp = visible_line;
1617
1618       while (*temp) *temp++ = '\0';
1619     }
1620   rl_on_new_line ();
1621   forced_display++;
1622   rl_redisplay ();
1623 }
1624
1625 /* Move the cursor from last_c_pos to NEW, which are buffer indices.
1626    DATA is the contents of the screen line of interest; i.e., where
1627    the movement is being done. */
1628 static void
1629 move_cursor_relative (new, data)
1630      int new;
1631      char *data;
1632 {
1633   register int i;
1634
1635   /* It may be faster to output a CR, and then move forwards instead
1636      of moving backwards. */
1637   if (new + 1 < last_c_pos - new)
1638     {
1639       tputs (term_cr, 1, output_character_function);
1640       last_c_pos = 0;
1641     }
1642
1643   if (last_c_pos == new) return;
1644
1645   if (last_c_pos < new)
1646     {
1647       /* Move the cursor forward.  We do it by printing the command
1648          to move the cursor forward if there is one, else print that
1649          portion of the output buffer again.  Which is cheaper? */
1650
1651       /* The above comment is left here for posterity.  It is faster
1652          to print one character (non-control) than to print a control
1653          sequence telling the terminal to move forward one character.
1654          That kind of control is for people who don't know what the
1655          data is underneath the cursor. */
1656 #ifdef HACK_TERMCAP_MOTION
1657       extern char *term_forward_char;
1658
1659       if (term_forward_char)
1660         for (i = last_c_pos; i < new; i++)
1661           tputs (term_forward_char, 1, output_character_function);
1662       else
1663         for (i = last_c_pos; i < new; i++)
1664           putc (data[i], out_stream);
1665 #else
1666       for (i = last_c_pos; i < new; i++)
1667         putc (data[i], out_stream);
1668 #endif                          /* HACK_TERMCAP_MOTION */
1669     }
1670   else
1671     backspace (last_c_pos - new);
1672   last_c_pos = new;
1673 }
1674
1675 /* PWP: move the cursor up or down. */
1676 move_vert (to)
1677      int to;
1678 {
1679   void output_character_function ();
1680   register int delta, i;
1681
1682   if (last_v_pos == to) return;
1683
1684   if (to > screenheight)
1685     return;
1686
1687   if ((delta = to - last_v_pos) > 0)
1688     {
1689       for (i = 0; i < delta; i++)
1690         putc ('\n', out_stream);
1691       tputs (term_cr, 1, output_character_function);
1692       last_c_pos = 0;           /* because crlf() will do \r\n */
1693     }
1694   else
1695     {                   /* delta < 0 */
1696       if (term_up && *term_up)
1697         for (i = 0; i < -delta; i++)
1698           tputs (term_up, 1, output_character_function);
1699     }
1700   last_v_pos = to;              /* now to is here */
1701 }
1702
1703 /* Physically print C on out_stream.  This is for functions which know
1704    how to optimize the display. */
1705 rl_show_char (c)
1706      int c;
1707 {
1708   if (c > 127)
1709     {
1710       fprintf (out_stream, "M-");
1711       c -= 128;
1712     }
1713
1714 #ifdef DISPLAY_TABS
1715   if (c < 32 && c != '\t')
1716 #else
1717   if (c < 32)
1718 #endif
1719     {
1720
1721       c += 64;
1722     }
1723
1724   putc (c, out_stream);
1725   fflush (out_stream);
1726 }
1727
1728 #ifdef DISPLAY_TABS
1729 int
1730 rl_character_len (c, pos)
1731      register int c, pos;
1732 {
1733   if (c < ' ' || c > 126)
1734     {
1735       if (c == '\t')
1736         return (((pos | (int)7) + 1) - pos);
1737       else
1738         return (3);
1739     }
1740   else
1741     return (1);
1742 }
1743 #else
1744 int
1745 rl_character_len (c)
1746      int c;
1747 {
1748   if (c < ' ' || c > 126)
1749     return (3);
1750   else
1751     return (1);
1752 }
1753 #endif  /* DISPLAY_TAB */
1754
1755 /* How to print things in the "echo-area".  The prompt is treated as a
1756    mini-modeline. */
1757 rl_message (string, arg1, arg2)
1758      char *string;
1759 {
1760   sprintf (msg_buf, string, arg1, arg2);
1761   rl_display_prompt = msg_buf;
1762   rl_redisplay ();
1763 }
1764
1765 /* How to clear things from the "echo-area". */
1766 rl_clear_message ()
1767 {
1768   rl_display_prompt = rl_prompt;
1769   rl_redisplay ();
1770 }
1771 \f
1772 /* **************************************************************** */
1773 /*                                                                  */
1774 /*                      Terminal and Termcap                        */
1775 /*                                                                  */
1776 /* **************************************************************** */
1777
1778 static char *term_buffer = (char *)NULL;
1779 static char *term_string_buffer = (char *)NULL;
1780
1781 /* Non-zero means this terminal can't really do anything. */
1782 int dumb_term = 0;
1783
1784 char PC;
1785 char *BC, *UP;
1786
1787 /* Some strings to control terminal actions.  These are output by tputs (). */
1788 char *term_goto, *term_clreol, *term_cr, *term_clrpag, *term_backspace;
1789
1790 int screenwidth, screenheight;
1791
1792 /* Non-zero if we determine that the terminal can do character insertion. */
1793 int terminal_can_insert = 0;
1794
1795 /* How to insert characters. */
1796 char *term_im, *term_ei, *term_ic, *term_ip, *term_IC;
1797
1798 /* How to delete characters. */
1799 char *term_dc, *term_DC;
1800
1801 #ifdef HACK_TERMCAP_MOTION
1802 char *term_forward_char;
1803 #endif  /* HACK_TERMCAP_MOTION */
1804
1805 /* How to go up a line. */
1806 char *term_up;
1807
1808 /* Re-initialize the terminal considering that the TERM/TERMCAP variable
1809    has changed. */
1810 rl_reset_terminal (terminal_name)
1811      char *terminal_name;
1812 {
1813   init_terminal_io (terminal_name);
1814 }
1815
1816 init_terminal_io (terminal_name)
1817      char *terminal_name;
1818 {
1819   char *term = (terminal_name? terminal_name : (char *)getenv ("TERM"));
1820   char *tgetstr (), *buffer;
1821
1822
1823   if (!term_string_buffer)
1824     term_string_buffer = (char *)xmalloc (2048);
1825
1826   if (!term_buffer)
1827     term_buffer = (char *)xmalloc (2048);
1828
1829   buffer = term_string_buffer;
1830
1831   term_clrpag = term_cr = term_clreol = (char *)NULL;
1832
1833   if (!term)
1834     term = "dumb";
1835
1836   if (tgetent (term_buffer, term) < 0)
1837     {
1838       dumb_term = 1;
1839       return;
1840     }
1841
1842   BC = tgetstr ("pc", &buffer);
1843   PC = buffer ? *buffer : 0;
1844
1845   term_backspace = tgetstr ("le", &buffer);
1846
1847   term_cr = tgetstr ("cr", &buffer);
1848   term_clreol = tgetstr ("ce", &buffer);
1849   term_clrpag = tgetstr ("cl", &buffer);
1850
1851   if (!term_cr)
1852     term_cr =  "\r";
1853
1854 #ifdef HACK_TERMCAP_MOTION
1855   term_forward_char = tgetstr ("nd", &buffer);
1856 #endif  /* HACK_TERMCAP_MOTION */
1857
1858   screenwidth = tgetnum ("co");
1859   if (screenwidth <= 0)
1860     screenwidth = 80;
1861   screenwidth--;                /* PWP: avoid autowrap bugs */
1862
1863   screenheight = tgetnum ("li");
1864   if (screenheight <= 0)
1865     screenheight = 24;
1866
1867   term_im = tgetstr ("im", &buffer);
1868   term_ei = tgetstr ("ei", &buffer);
1869   term_IC = tgetstr ("IC", &buffer);
1870   term_ic = tgetstr ("ic", &buffer);
1871
1872   /* "An application program can assume that the terminal can do
1873       character insertion if *any one of* the capabilities `IC',
1874       `im', `ic' or `ip' is provided."  But we can't do anything if
1875       only `ip' is provided, so... */
1876   terminal_can_insert = (term_IC || term_im || term_ic);
1877
1878   term_up = tgetstr ("up", &buffer);
1879   term_dc = tgetstr ("dc", &buffer);
1880   term_DC = tgetstr ("DC", &buffer);
1881 }
1882
1883 /* A function for the use of tputs () */
1884 static void
1885 output_character_function (c)
1886      int c;
1887 {
1888   putc (c, out_stream);
1889 }
1890
1891 /* Write COUNT characters from STRING to the output stream. */
1892 static void
1893 output_some_chars (string, count)
1894      char *string;
1895      int count;
1896 {
1897   fwrite (string, 1, count, out_stream);
1898 }
1899
1900
1901 /* Delete COUNT characters from the display line. */
1902 static
1903 delete_chars (count)
1904      int count;
1905 {
1906   if (count > screenwidth)
1907     return;
1908
1909   if (term_DC && *term_DC)
1910     {
1911       char *tgoto (), *buffer;
1912       buffer = tgoto (term_DC, 0, count);
1913       tputs (buffer, 1, output_character_function);
1914     }
1915   else
1916     {
1917       if (term_dc && *term_dc)
1918         while (count--)
1919           tputs (term_dc, 1, output_character_function);
1920     }
1921 }
1922
1923 /* Insert COUNT character from STRING to the output stream. */
1924 static
1925 insert_some_chars (string, count)
1926      char *string;
1927      int count;
1928 {
1929   /* If IC is defined, then we do not have to "enter" insert mode. */
1930   if (term_IC)
1931     {
1932       char *tgoto (), *buffer;
1933       buffer = tgoto (term_IC, 0, count);
1934       tputs (buffer, 1, output_character_function);
1935       output_some_chars (string, count);
1936     }
1937   else
1938     {
1939       register int i;
1940
1941       /* If we have to turn on insert-mode, then do so. */
1942       if (term_im && *term_im)
1943         tputs (term_im, 1, output_character_function);
1944
1945       /* If there is a special command for inserting characters, then
1946          use that first to open up the space. */
1947       if (term_ic && *term_ic)
1948         {
1949           for (i = count; i--; )
1950             tputs (term_ic, 1, output_character_function);
1951         }
1952
1953       /* Print the text. */
1954       output_some_chars (string, count);
1955
1956       /* If there is a string to turn off insert mode, we had best use
1957          it now. */
1958       if (term_ei && *term_ei)
1959         tputs (term_ei, 1, output_character_function);
1960     }
1961 }
1962
1963 /* Move the cursor back. */
1964 backspace (count)
1965      int count;
1966 {
1967   register int i;
1968
1969   if (term_backspace)
1970     for (i = 0; i < count; i++)
1971       tputs (term_backspace, 1, output_character_function);
1972   else
1973     for (i = 0; i < count; i++)
1974       putc ('\b', out_stream);
1975 }
1976
1977 /* Move to the start of the next line. */
1978 crlf ()
1979 {
1980   tputs (term_cr, 1, output_character_function);
1981   putc ('\n', out_stream);
1982 }
1983
1984 /* Clear to the end of the line.  COUNT is the minimum
1985    number of character spaces to clear, */
1986 clear_to_eol (count)
1987      int count;
1988 {
1989   if (term_clreol)
1990     {
1991       tputs (term_clreol, 1, output_character_function);
1992     }
1993   else
1994     {
1995       register int i;
1996
1997       /* Do one more character space. */
1998       count++;
1999
2000       for (i = 0; i < count; i++)
2001         putc (' ', out_stream);
2002
2003       backspace (count);
2004     }
2005 }
2006
2007 \f
2008 /* **************************************************************** */
2009 /*                                                                  */
2010 /*                    Saving and Restoring the TTY                  */
2011 /*                                                                  */
2012 /* **************************************************************** */
2013
2014 /* Non-zero means that the terminal is in a prepped state. */
2015 static int terminal_prepped = 0;
2016
2017 #ifdef NEW_TTY_DRIVER
2018
2019 /* Standard flags, including ECHO. */
2020 static int original_tty_flags = 0;
2021
2022 /* Local mode flags, like LPASS8. */
2023 static int local_mode_flags = 0;
2024
2025 /* Terminal characters.  This has C-s and C-q in it. */
2026 static struct tchars original_tchars;
2027
2028 /* Local special characters.  This has the interrupt characters in it. */
2029 static struct ltchars original_ltchars;
2030
2031 /* We use this to get and set the tty_flags. */
2032 static struct sgttyb the_ttybuff;
2033
2034 /* Put the terminal in CBREAK mode so that we can detect key presses. */
2035 static
2036 rl_prep_terminal ()
2037 {
2038   int tty = fileno (rl_instream);
2039   int oldmask = sigblock (sigmask (SIGINT));
2040
2041   if (!terminal_prepped)
2042     {
2043       /* We always get the latest tty values.  Maybe stty changed them. */
2044       ioctl (tty, TIOCGETP, &the_ttybuff);
2045       original_tty_flags = the_ttybuff.sg_flags;
2046
2047       readline_echoing_p = (original_tty_flags & ECHO);
2048
2049         
2050 #if defined (TIOCLGET)
2051       ioctl (tty, TIOCLGET, &local_mode_flags);
2052 #endif
2053
2054       /* If this terminal doesn't care how the 8th bit is used,
2055          then we can use it for the meta-key.
2056          We check by seeing if BOTH odd and even parity are allowed. */
2057       if ((the_ttybuff.sg_flags & ODDP) && (the_ttybuff.sg_flags & EVENP))
2058         {
2059 #ifdef PASS8
2060           the_ttybuff.sg_flags |= PASS8;
2061 #endif
2062           /* Hack on local mode flags if we can. */
2063 #if defined (TIOCLGET) && defined (LPASS8)
2064           {
2065             int flags;
2066             flags = local_mode_flags | LPASS8;
2067             ioctl (tty, TIOCLSET, &flags);
2068           }
2069 #endif
2070         }
2071
2072 #ifdef TIOCGETC
2073       {
2074         struct tchars temp;
2075
2076         ioctl (tty, TIOCGETC, &original_tchars);
2077         bcopy (&original_tchars, &temp, sizeof (struct tchars));
2078
2079         /* Get rid of C-s and C-q.
2080            We remember the value of startc (C-q) so that if the terminal is in
2081            xoff state, the user can xon it by pressing that character. */
2082         xon_char = temp.t_startc;
2083         temp.t_stopc = -1;
2084         temp.t_startc = -1;
2085
2086         /* If there is an XON character, bind it to restart the output. */
2087         if (xon_char != -1)
2088           rl_bind_key (xon_char, rl_restart_output);
2089
2090         /* If there is an EOF char, bind eof_char to it. */
2091         if (temp.t_eofc != -1)
2092           eof_char = temp.t_eofc;
2093
2094 #ifdef NEVER
2095         /* Get rid of C-\ and C-c. */
2096         temp.t_intrc = temp.t_quitc = -1;
2097 #endif
2098
2099         ioctl (tty, TIOCSETC, &temp);
2100       }
2101 #endif /* TIOCGETC */
2102
2103 #ifdef TIOCGLTC
2104       {
2105         struct ltchars temp;
2106
2107         ioctl (tty, TIOCGLTC, &original_ltchars);
2108         bcopy (&original_ltchars, &temp, sizeof (struct ltchars));
2109
2110         /* Make the interrupt keys go away.  Just enough to make people happy. */
2111         temp.t_dsuspc = -1;     /* C-y */
2112         temp.t_lnextc = -1;     /* C-v */
2113
2114         ioctl (tty, TIOCSLTC, &temp);
2115       }
2116 #endif /* TIOCGLTC */
2117
2118       the_ttybuff.sg_flags &= ~ECHO;
2119       the_ttybuff.sg_flags |= CBREAK;
2120       ioctl (tty, TIOCSETN, &the_ttybuff);
2121
2122       terminal_prepped = 1;
2123     }
2124   sigsetmask (oldmask);
2125 }
2126
2127 /* Restore the terminal to its original state. */
2128 static
2129 rl_deprep_terminal ()
2130 {
2131   int tty = fileno (rl_instream);
2132   int oldmask = sigblock (sigmask (SIGINT));
2133
2134   if (terminal_prepped)
2135     {
2136       the_ttybuff.sg_flags = original_tty_flags;
2137       ioctl (tty, TIOCSETN, &the_ttybuff);
2138       readline_echoing_p = 1;
2139
2140 #if defined (TIOCLGET)
2141       ioctl (tty, TIOCLSET, &local_mode_flags);
2142 #endif
2143
2144 #ifdef TIOCSLTC
2145       ioctl (tty, TIOCSLTC, &original_ltchars);
2146 #endif
2147
2148 #ifdef TIOCSETC
2149       ioctl (tty, TIOCSETC, &original_tchars);
2150 #endif
2151       terminal_prepped = 0;
2152     }
2153
2154   sigsetmask (oldmask);
2155 }
2156
2157 #else  /* !defined (NEW_TTY_DRIVER) */
2158
2159 #if !defined (VMIN)
2160 #define VMIN VEOF
2161 #endif
2162
2163 #if !defined (VTIME)
2164 #define VTIME VEOL
2165 #endif
2166
2167 static struct termio otio;
2168
2169 static
2170 rl_prep_terminal ()
2171 {
2172   int tty = fileno (rl_instream);
2173   struct termio tio;
2174
2175   ioctl (tty, TCGETA, &tio);
2176   ioctl (tty, TCGETA, &otio);
2177
2178   readline_echoing_p = (tio.c_lflag & ECHO);
2179
2180   tio.c_lflag &= ~(ICANON|ECHO);
2181   tio.c_iflag &= ~(IXON|IXOFF|IXANY|ISTRIP|INPCK);
2182
2183 #if !defined (HANDLE_SIGNALS)
2184   tio.c_lflag &= ~ISIG;
2185 #endif
2186
2187   tio.c_cc[VMIN] = 1;
2188   tio.c_cc[VTIME] = 0;
2189   ioctl (tty, TCSETAW, &tio);
2190   ioctl (tty, TCXONC, 1);       /* Simulate a ^Q. */
2191 }
2192
2193 static
2194 rl_deprep_terminal ()
2195 {
2196   int tty = fileno (rl_instream);
2197   ioctl (tty, TCSETAW, &otio);
2198   ioctl (tty, TCXONC, 1);       /* Simulate a ^Q. */
2199 }
2200 #endif  /* NEW_TTY_DRIVER */
2201
2202 \f
2203 /* **************************************************************** */
2204 /*                                                                  */
2205 /*                      Utility Functions                           */
2206 /*                                                                  */
2207 /* **************************************************************** */
2208
2209 /* Return 0 if C is not a member of the class of characters that belong
2210    in words, or 1 if it is. */
2211
2212 int allow_pathname_alphabetic_chars = 0;
2213 char *pathname_alphabetic_chars = "/-_=~.#$";
2214
2215 int
2216 alphabetic (c)
2217      int c;
2218 {
2219   char *rindex ();
2220   if (pure_alphabetic (c) || (numeric (c)))
2221     return (1);
2222
2223   if (allow_pathname_alphabetic_chars)
2224     return ((int)rindex (pathname_alphabetic_chars, c));
2225   else
2226     return (0);
2227 }
2228
2229 /* Return non-zero if C is a numeric character. */
2230 int
2231 numeric (c)
2232      int c;
2233 {
2234   return (c >= '0' && c <= '9');
2235 }
2236
2237 /* Ring the terminal bell. */
2238 int
2239 ding ()
2240 {
2241   if (readline_echoing_p)
2242     {
2243       fprintf (stderr, "\007");
2244       fflush (stderr);
2245     }
2246   return (-1);
2247 }
2248
2249 /* How to abort things. */
2250 rl_abort ()
2251 {
2252   ding ();
2253   rl_clear_message ();
2254   rl_init_argument ();
2255   rl_pending_input = 0;
2256
2257   defining_kbd_macro = 0;
2258   while (executing_macro)
2259     pop_executing_macro ();
2260
2261   longjmp (readline_top_level, 1);
2262 }
2263
2264 /* Return a copy of the string between FROM and TO.
2265    FROM is inclusive, TO is not. */
2266 static char *
2267 rl_copy (from, to)
2268      int from, to;
2269 {
2270   register int length;
2271   char *copy;
2272
2273   /* Fix it if the caller is confused. */
2274   if (from > to) {
2275     int t = from;
2276     from = to;
2277     to = t;
2278   }
2279
2280   length = to - from;
2281   copy = (char *)xmalloc (1 + length);
2282   strncpy (copy, the_line + from, length);
2283   copy[length] = '\0';
2284   return (copy);
2285 }
2286
2287 \f
2288 /* **************************************************************** */
2289 /*                                                                  */
2290 /*                      Insert and Delete                           */
2291 /*                                                                  */
2292 /* **************************************************************** */
2293
2294
2295 /* Insert a string of text into the line at point.  This is the only
2296    way that you should do insertion.  rl_insert () calls this
2297    function. */
2298 rl_insert_text (string)
2299      char *string;
2300 {
2301   extern int doing_an_undo;
2302   register int i, l = strlen (string);
2303   while (rl_end + l >= rl_line_buffer_len)
2304     {
2305       rl_line_buffer =
2306         (char *)xrealloc (rl_line_buffer,
2307                           rl_line_buffer_len += DEFAULT_BUFFER_SIZE);
2308       the_line = rl_line_buffer;
2309     }
2310
2311   for (i = rl_end; i >= rl_point; i--)
2312     the_line[i + l] = the_line[i];
2313   strncpy (the_line + rl_point, string, l);
2314
2315   /* Remember how to undo this if we aren't undoing something. */
2316   if (!doing_an_undo)
2317     {
2318       /* If possible and desirable, concatenate the undos. */
2319       if ((strlen (string) == 1) &&
2320           rl_undo_list &&
2321           (rl_undo_list->what == UNDO_INSERT) &&
2322           (rl_undo_list->end == rl_point) &&
2323           (rl_undo_list->end - rl_undo_list->start < 20))
2324         rl_undo_list->end++;
2325       else
2326         rl_add_undo (UNDO_INSERT, rl_point, rl_point + l, (char *)NULL);
2327     }
2328   rl_point += l;
2329   rl_end += l;
2330   the_line[rl_end] = '\0';
2331 }
2332
2333 /* Delete the string between FROM and TO.  FROM is
2334    inclusive, TO is not. */
2335 rl_delete_text (from, to)
2336      int from, to;
2337 {
2338   extern int doing_an_undo;
2339   register char *text;
2340
2341   /* Fix it if the caller is confused. */
2342   if (from > to) {
2343     int t = from;
2344     from = to;
2345     to = t;
2346   }
2347   text = rl_copy (from, to);
2348   strncpy (the_line + from, the_line + to, rl_end - to);
2349
2350   /* Remember how to undo this delete. */
2351   if (!doing_an_undo)
2352     rl_add_undo (UNDO_DELETE, from, to, text);
2353   else
2354     free (text);
2355
2356   rl_end -= (to - from);
2357   the_line[rl_end] = '\0';
2358 }
2359
2360 \f
2361 /* **************************************************************** */
2362 /*                                                                  */
2363 /*                      Readline character functions                */
2364 /*                                                                  */
2365 /* **************************************************************** */
2366
2367 /* This is not a gap editor, just a stupid line input routine.  No hair
2368    is involved in writing any of the functions, and none should be. */
2369
2370 /* Note that:
2371
2372    rl_end is the place in the string that we would place '\0';
2373    i.e., it is always safe to place '\0' there.
2374
2375    rl_point is the place in the string where the cursor is.  Sometimes
2376    this is the same as rl_end.
2377
2378    Any command that is called interactively receives two arguments.
2379    The first is a count: the numeric arg pased to this command.
2380    The second is the key which invoked this command.
2381 */
2382
2383 \f
2384 /* **************************************************************** */
2385 /*                                                                  */
2386 /*                      Movement Commands                           */
2387 /*                                                                  */
2388 /* **************************************************************** */
2389
2390 /* Note that if you `optimize' the display for these functions, you cannot
2391    use said functions in other functions which do not do optimizing display.
2392    I.e., you will have to update the data base for rl_redisplay, and you
2393    might as well let rl_redisplay do that job. */
2394
2395 /* Move forward COUNT characters. */
2396 rl_forward (count)
2397      int count;
2398 {
2399   if (count < 0)
2400     rl_backward (-count);
2401   else
2402     while (count)
2403       {
2404 #ifdef VI_MODE
2405         if (rl_point == (rl_end - (rl_editing_mode == vi_mode)))
2406 #else
2407         if (rl_point == rl_end)
2408 #endif
2409           {
2410             ding ();
2411             return;
2412           }
2413         else
2414           rl_point++;
2415         --count;
2416       }
2417 }
2418
2419 /* Move backward COUNT characters. */
2420 rl_backward (count)
2421      int count;
2422 {
2423   if (count < 0)
2424     rl_forward (-count);
2425   else
2426     while (count)
2427       {
2428         if (!rl_point)
2429           {
2430             ding ();
2431             return;
2432           }
2433         else
2434           --rl_point;
2435         --count;
2436       }
2437 }
2438
2439 /* Move to the beginning of the line. */
2440 rl_beg_of_line ()
2441 {
2442   rl_point = 0;
2443 }
2444
2445 /* Move to the end of the line. */
2446 rl_end_of_line ()
2447 {
2448   rl_point = rl_end;
2449 }
2450
2451 /* Move forward a word.  We do what Emacs does. */
2452 rl_forward_word (count)
2453      int count;
2454 {
2455   int c;
2456
2457   if (count < 0)
2458     {
2459       rl_backward_word (-count);
2460       return;
2461     }
2462
2463   while (count)
2464     {
2465       if (rl_point == rl_end)
2466         return;
2467
2468       /* If we are not in a word, move forward until we are in one.
2469          Then, move forward until we hit a non-alphabetic character. */
2470       c = the_line[rl_point];
2471       if (!alphabetic (c))
2472         {
2473           while (++rl_point < rl_end)
2474             {
2475               c = the_line[rl_point];
2476               if (alphabetic (c)) break;
2477             }
2478         }
2479       if (rl_point == rl_end) return;
2480       while (++rl_point < rl_end)
2481         {
2482           c = the_line[rl_point];
2483           if (!alphabetic (c)) break;
2484         }
2485       --count;
2486     }
2487 }
2488
2489 /* Move backward a word.  We do what Emacs does. */
2490 rl_backward_word (count)
2491      int count;
2492 {
2493   int c;
2494
2495   if (count < 0)
2496     {
2497       rl_forward_word (-count);
2498       return;
2499     }
2500
2501   while (count)
2502     {
2503       if (!rl_point)
2504         return;
2505
2506       /* Like rl_forward_word (), except that we look at the characters
2507          just before point. */
2508
2509       c = the_line[rl_point - 1];
2510       if (!alphabetic (c))
2511         {
2512           while (--rl_point)
2513             {
2514               c = the_line[rl_point - 1];
2515               if (alphabetic (c)) break;
2516             }
2517         }
2518
2519       while (rl_point)
2520         {
2521           c = the_line[rl_point - 1];
2522           if (!alphabetic (c))
2523             break;
2524           else --rl_point;
2525         }
2526       --count;
2527     }
2528 }
2529
2530 /* Clear the current line.  Numeric argument to C-l does this. */
2531 rl_refresh_line ()
2532 {
2533   int curr_line = last_c_pos / screenwidth;
2534   extern char *term_clreol;
2535
2536   move_vert(curr_line);
2537   move_cursor_relative (0, the_line);   /* XXX is this right */
2538
2539   if (term_clreol)
2540     tputs (term_clreol, 1, output_character_function);
2541
2542   rl_forced_update_display ();
2543   rl_display_fixed = 1;
2544 }
2545
2546 /* C-l typed to a line without quoting clears the screen, and then reprints
2547    the prompt and the current input line.  Given a numeric arg, redraw only
2548    the current line. */
2549 rl_clear_screen ()
2550 {
2551   extern char *term_clrpag;
2552
2553   if (rl_explicit_arg)
2554     {
2555       rl_refresh_line ();
2556       return;
2557     }
2558
2559   if (term_clrpag)
2560     tputs (term_clrpag, 1, output_character_function);
2561   else
2562     crlf ();
2563
2564   rl_forced_update_display ();
2565   rl_display_fixed = 1;
2566 }
2567
2568 \f
2569 /* **************************************************************** */
2570 /*                                                                  */
2571 /*                      Text commands                               */
2572 /*                                                                  */
2573 /* **************************************************************** */
2574
2575 /* Insert the character C at the current location, moving point forward. */
2576 rl_insert (count, c)
2577      int count, c;
2578 {
2579   register int i;
2580   char *string;
2581
2582   if (count <= 0)
2583     return;
2584
2585   /* If we can optimize, then do it.  But don't let people crash
2586      readline because of extra large arguments. */
2587   if (count > 1 && count < 1024)
2588     {
2589       string = (char *)alloca (1 + count);
2590
2591       for (i = 0; i < count; i++)
2592         string[i] = c;
2593
2594       string[i] = '\0';
2595       rl_insert_text (string);
2596       return;
2597     }
2598
2599   if (count > 1024)
2600     {
2601       int decreaser;
2602
2603       string = (char *)alloca (1024 + 1);
2604
2605       for (i = 0; i < 1024; i++)
2606         string[i] = c;
2607
2608       while (count)
2609         {
2610           decreaser = (count > 1024 ? 1024 : count);
2611           string[decreaser] = '\0';
2612           rl_insert_text (string);
2613           count -= decreaser;
2614         }
2615       return;
2616     }
2617
2618   /* We are inserting a single character.
2619      If there is pending input, then make a string of all of the
2620      pending characters that are bound to rl_insert, and insert
2621      them all. */
2622   if (any_typein)
2623     {
2624       int key = 0, t;
2625
2626       i = 0;
2627       string = (char *)alloca (ibuffer_len + 1);
2628       string[i++] = c;
2629
2630       while ((t = rl_get_char (&key)) &&
2631              (keymap[key].type == ISFUNC &&
2632               keymap[key].function == rl_insert))
2633         string[i++] = key;
2634
2635       if (t)
2636         rl_unget_char (key);
2637
2638       string[i] = '\0';
2639       rl_insert_text (string);
2640       return;
2641     }
2642   else
2643     {
2644       /* Inserting a single character. */
2645       string = (char *)alloca (2);
2646
2647       string[1] = '\0';
2648       string[0] = c;
2649       rl_insert_text (string);
2650     }
2651 }
2652
2653 /* Insert the next typed character verbatim. */
2654 rl_quoted_insert (count)
2655      int count;
2656 {
2657   int c = rl_read_key ();
2658   rl_insert (count, c);
2659 }
2660
2661 /* Insert a tab character. */
2662 rl_tab_insert (count)
2663      int count;
2664 {
2665   rl_insert (count, '\t');
2666 }
2667
2668 /* What to do when a NEWLINE is pressed.  We accept the whole line.
2669    KEY is the key that invoked this command.  I guess it could have
2670    meaning in the future. */
2671 rl_newline (count, key)
2672      int count, key;
2673 {
2674
2675   rl_done = 1;
2676
2677 #ifdef VI_MODE
2678   {
2679     extern int vi_doing_insert;
2680     if (vi_doing_insert)
2681       {
2682         rl_end_undo_group ();
2683         vi_doing_insert = 0;
2684       }
2685   }
2686 #endif /* VI_MODE */
2687
2688   if (readline_echoing_p)
2689     {
2690       move_vert (vis_botlin);
2691       vis_botlin = 0;
2692       crlf ();
2693       fflush (out_stream);
2694       rl_display_fixed++;
2695     }
2696 }
2697
2698 rl_clean_up_for_exit ()
2699 {
2700   if (readline_echoing_p)
2701     {
2702       move_vert (vis_botlin);
2703       vis_botlin = 0;
2704       fflush (out_stream);
2705       rl_restart_output ();
2706     }
2707 }
2708
2709 /* What to do for some uppercase characters, like meta characters,
2710    and some characters appearing in emacs_ctlx_keymap.  This function
2711    is just a stub, you bind keys to it and the code in rl_dispatch ()
2712    is special cased. */
2713 rl_do_lowercase_version (ignore1, ignore2)
2714      int ignore1, ignore2;
2715 {
2716 }
2717
2718 /* Rubout the character behind point. */
2719 rl_rubout (count)
2720      int count;
2721 {
2722   if (count < 0)
2723     {
2724       rl_delete (-count);
2725       return;
2726     }
2727
2728   if (!rl_point)
2729     {
2730       ding ();
2731       return;
2732     }
2733
2734   if (count > 1)
2735     {
2736       int orig_point = rl_point;
2737       rl_backward (count);
2738       rl_kill_text (orig_point, rl_point);
2739     }
2740   else
2741     {
2742       int c = the_line[--rl_point];
2743       rl_delete_text (rl_point, rl_point + 1);
2744
2745       if (rl_point == rl_end && alphabetic (c) && last_c_pos)
2746         {
2747           backspace (1);
2748           putc (' ', out_stream);
2749           backspace (1);
2750           last_c_pos--;
2751           visible_line[last_c_pos] = '\0';
2752           rl_display_fixed++;
2753         }
2754     }
2755 }
2756
2757 /* Delete the character under the cursor.  Given a numeric argument,
2758    kill that many characters instead. */
2759 rl_delete (count, invoking_key)
2760      int count, invoking_key;
2761 {
2762   if (count < 0)
2763     {
2764       rl_rubout (-count);
2765       return;
2766     }
2767
2768   if (rl_point == rl_end)
2769     {
2770       ding ();
2771       return;
2772     }
2773
2774   if (count > 1)
2775     {
2776       int orig_point = rl_point;
2777       rl_forward (count);
2778       rl_kill_text (orig_point, rl_point);
2779       rl_point = orig_point;
2780     }
2781   else
2782     rl_delete_text (rl_point, rl_point + 1);
2783 }
2784
2785 \f
2786 /* **************************************************************** */
2787 /*                                                                  */
2788 /*                      Kill commands                               */
2789 /*                                                                  */
2790 /* **************************************************************** */
2791
2792 /* The next two functions mimic unix line editing behaviour, except they
2793    save the deleted text on the kill ring.  This is safer than not saving
2794    it, and since we have a ring, nobody should get screwed. */
2795
2796 /* This does what C-w does in Unix.  We can't prevent people from
2797    using behaviour that they expect. */
2798 rl_unix_word_rubout ()
2799 {
2800   if (!rl_point) ding ();
2801   else {
2802     int orig_point = rl_point;
2803     while (rl_point && whitespace (the_line[rl_point - 1]))
2804       rl_point--;
2805     while (rl_point && !whitespace (the_line[rl_point - 1]))
2806       rl_point--;
2807     rl_kill_text (rl_point, orig_point);
2808   }
2809 }
2810
2811 /* Here is C-u doing what Unix does.  You don't *have* to use these
2812    key-bindings.  We have a choice of killing the entire line, or
2813    killing from where we are to the start of the line.  We choose the
2814    latter, because if you are a Unix weenie, then you haven't backspaced
2815    into the line at all, and if you aren't, then you know what you are
2816    doing. */
2817 rl_unix_line_discard ()
2818 {
2819   if (!rl_point) ding ();
2820   else {
2821     rl_kill_text (rl_point, 0);
2822     rl_point = 0;
2823   }
2824 }
2825
2826 \f
2827
2828 /* **************************************************************** */
2829 /*                                                                  */
2830 /*                      Commands For Typos                          */
2831 /*                                                                  */
2832 /* **************************************************************** */
2833
2834 /* Random and interesting things in here.  */
2835
2836
2837 /* **************************************************************** */
2838 /*                                                                  */
2839 /*                      Changing Case                               */
2840 /*                                                                  */
2841 /* **************************************************************** */
2842
2843 /* The three kinds of things that we know how to do. */
2844 #define UpCase 1
2845 #define DownCase 2
2846 #define CapCase 3
2847
2848 /* Uppercase the word at point. */
2849 rl_upcase_word (count)
2850      int count;
2851 {
2852   rl_change_case (count, UpCase);
2853 }
2854
2855 /* Lowercase the word at point. */
2856 rl_downcase_word (count)
2857      int count;
2858 {
2859   rl_change_case (count, DownCase);
2860 }
2861
2862 /* Upcase the first letter, downcase the rest. */
2863 rl_capitalize_word (count)
2864      int count;
2865 {
2866   rl_change_case (count, CapCase);
2867 }
2868
2869 /* The meaty function.
2870    Change the case of COUNT words, performing OP on them.
2871    OP is one of UpCase, DownCase, or CapCase.
2872    If a negative argument is given, leave point where it started,
2873    otherwise, leave it where it moves to. */
2874 rl_change_case (count, op)
2875      int count, op;
2876 {
2877   register int start = rl_point, end;
2878   int state = 0;
2879
2880   rl_forward_word (count);
2881   end = rl_point;
2882
2883   if (count < 0)
2884     {
2885       int temp = start;
2886       start = end;
2887       end = temp;
2888     }
2889
2890   /* We are going to modify some text, so let's prepare to undo it. */
2891   rl_modifying (start, end);
2892
2893   for (; start < end; start++)
2894     {
2895       switch (op)
2896         {
2897         case UpCase:
2898           the_line[start] = to_upper (the_line[start]);
2899           break;
2900
2901         case DownCase:
2902           the_line[start] = to_lower (the_line[start]);
2903           break;
2904
2905         case CapCase:
2906           if (state == 0)
2907             {
2908               the_line[start] = to_upper (the_line[start]);
2909               state = 1;
2910             }
2911           else
2912             {
2913               the_line[start] = to_lower (the_line[start]);
2914             }
2915           if (!pure_alphabetic (the_line[start]))
2916             state = 0;
2917           break;
2918
2919         default:
2920           abort ();
2921         }
2922     }
2923   rl_point = end;
2924 }
2925
2926 /* **************************************************************** */
2927 /*                                                                  */
2928 /*                      Transposition                               */
2929 /*                                                                  */
2930 /* **************************************************************** */
2931
2932 /* Transpose the words at point. */
2933 rl_transpose_words (count)
2934      int count;
2935 {
2936   char *word1, *word2;
2937   int w1_beg, w1_end, w2_beg, w2_end;
2938   int orig_point = rl_point;
2939
2940   if (!count) return;
2941
2942   /* Find the two words. */
2943   rl_forward_word (count);
2944   w2_end = rl_point;
2945   rl_backward_word (1);
2946   w2_beg = rl_point;
2947   rl_backward_word (count);
2948   w1_beg = rl_point;
2949   rl_forward_word (1);
2950   w1_end = rl_point;
2951
2952   /* Do some check to make sure that there really are two words. */
2953   if ((w1_beg == w2_beg) || (w2_beg < w1_end))
2954     {
2955       ding ();
2956       rl_point = orig_point;
2957       return;
2958     }
2959
2960   /* Get the text of the words. */
2961   word1 = rl_copy (w1_beg, w1_end);
2962   word2 = rl_copy (w2_beg, w2_end);
2963
2964   /* We are about to do many insertions and deletions.  Remember them
2965      as one operation. */
2966   rl_begin_undo_group ();
2967
2968   /* Do the stuff at word2 first, so that we don't have to worry
2969      about word1 moving. */
2970   rl_point = w2_beg;
2971   rl_delete_text (w2_beg, w2_end);
2972   rl_insert_text (word1);
2973
2974   rl_point = w1_beg;
2975   rl_delete_text (w1_beg, w1_end);
2976   rl_insert_text (word2);
2977
2978   /* This is exactly correct since the text before this point has not
2979      changed in length. */
2980   rl_point = w2_end;
2981
2982   /* I think that does it. */
2983   rl_end_undo_group ();
2984   free (word1); free (word2);
2985 }
2986
2987 /* Transpose the characters at point.  If point is at the end of the line,
2988    then transpose the characters before point. */
2989 rl_transpose_chars (count)
2990      int count;
2991 {
2992   if (!count)
2993     return;
2994
2995   if (!rl_point || rl_end < 2) {
2996     ding ();
2997     return;
2998   }
2999
3000   while (count) {
3001     if (rl_point == rl_end) {
3002       int t = the_line[rl_point - 1];
3003       the_line[rl_point - 1] = the_line[rl_point - 2];
3004       the_line[rl_point - 2] = t;
3005     } else {
3006       int t = the_line[rl_point];
3007       the_line[rl_point] = the_line[rl_point - 1];
3008       the_line[rl_point - 1] = t;
3009       if (count < 0 && rl_point)
3010         rl_point--;
3011       else
3012         rl_point++;
3013     }
3014     if (count < 0)
3015       count++;
3016     else
3017       count--;
3018   }
3019 }
3020
3021 \f
3022 /* **************************************************************** */
3023 /*                                                                  */
3024 /*                      Bogus Flow Control                          */
3025 /*                                                                  */
3026 /* **************************************************************** */
3027
3028 rl_restart_output (count, key)
3029      int count, key;
3030 {
3031   int fildes = fileno (stdin);
3032 #ifdef TIOCSTART
3033   ioctl (fildes, TIOCSTART, 0);
3034 #endif /* TIOCSTART */
3035 }
3036
3037 /* **************************************************************** */
3038 /*                                                                  */
3039 /*      Completion matching, from readline's point of view.         */
3040 /*                                                                  */
3041 /* **************************************************************** */
3042
3043 /* Pointer to the generator function for completion_matches ().
3044    NULL means to use filename_entry_function (), the default filename
3045    completer. */
3046 Function *rl_completion_entry_function = (Function *)NULL;
3047
3048 /* Pointer to alternative function to create matches.
3049    Function is called with TEXT, START, and END.
3050    START and END are indices in RL_LINE_BUFFER saying what the boundaries
3051    of TEXT are.
3052    If this function exists and returns NULL then call the value of
3053    rl_completion_entry_function to try to match, otherwise use the
3054    array of strings returned. */
3055 Function *rl_attempted_completion_function = (Function *)NULL;
3056
3057 /* Complete the word at or before point.  You have supplied the function
3058    that does the initial simple matching selection algorithm (see
3059    completion_matches ()).  The default is to do filename completion. */
3060 rl_complete (ignore, invoking_key)
3061      int ignore, invoking_key;
3062 {
3063   rl_complete_internal (TAB);
3064 }
3065
3066 /* List the possible completions.  See description of rl_complete (). */
3067 rl_possible_completions ()
3068 {
3069   rl_complete_internal ('?');
3070 }
3071
3072 /* The user must press "y" or "n". Non-zero return means "y" pressed. */
3073 get_y_or_n ()
3074 {
3075   int c;
3076  loop:
3077   c = rl_read_key ();
3078   if (c == 'y' || c == 'Y') return (1);
3079   if (c == 'n' || c == 'N') return (0);
3080   if (c == ABORT_CHAR) rl_abort ();
3081   ding (); goto loop;
3082 }
3083
3084 /* Up to this many items will be displayed in response to a
3085    possible-completions call.  After that, we ask the user if
3086    she is sure she wants to see them all. */
3087 int rl_completion_query_items = 100;
3088
3089 /* The basic list of characters that signal a break between words for the
3090    completer routine.  The contents of this variable is what breaks words
3091    in the shell, i.e. " \t\n\"\\'`@$><=" */
3092 char *rl_basic_word_break_characters = " \t\n\"\\'`@$><=";
3093
3094 /* The list of characters that signal a break between words for
3095    rl_complete_internal.  The default list is the contents of
3096    rl_basic_word_break_characters.  */
3097 char *rl_completer_word_break_characters = (char *)NULL;
3098
3099 /* List of characters that are word break characters, but should be left
3100    in TEXT when it is passed to the completion function.  The shell uses
3101    this to help determine what kind of completing to do. */
3102 char *rl_special_prefixes = (char *)NULL;
3103
3104 /* If non-zero, then disallow duplicates in the matches. */
3105 int rl_ignore_completion_duplicates = 1;
3106
3107 /* Non-zero means that the results of the matches are to be treated
3108    as filenames.  This is ALWAYS zero on entry, and can only be changed
3109    within a completion entry finder function. */
3110 int rl_filename_completion_desired = 0;
3111
3112 /* Complete the word at or before point.
3113    WHAT_TO_DO says what to do with the completion.
3114    `?' means list the possible completions.
3115    TAB means do standard completion.
3116    `*' means insert all of the possible completions. */
3117 rl_complete_internal (what_to_do)
3118      int what_to_do;
3119 {
3120   char *filename_completion_function ();
3121   char **completion_matches (), **matches;
3122   Function *our_func;
3123   int start, end, delimiter = 0;
3124   char *text;
3125
3126   if (rl_completion_entry_function)
3127     our_func = rl_completion_entry_function;
3128   else
3129     our_func = (int (*)())filename_completion_function;
3130
3131   /* Only the completion entry function can change this. */
3132   rl_filename_completion_desired = 0;
3133
3134   /* We now look backwards for the start of a filename/variable word. */
3135   end = rl_point;
3136   if (rl_point)
3137     {
3138       while (--rl_point &&
3139              !rindex (rl_completer_word_break_characters, the_line[rl_point]));
3140
3141       /* If we are at a word break, then advance past it. */
3142       if (rindex (rl_completer_word_break_characters,  (the_line[rl_point])))
3143         {
3144           /* If the character that caused the word break was a quoting
3145              character, then remember it as the delimiter. */
3146           if (rindex ("\"'", the_line[rl_point]) && (end - rl_point) > 1)
3147             delimiter = the_line[rl_point];
3148
3149           /* If the character isn't needed to determine something special
3150              about what kind of completion to perform, then advance past it. */
3151
3152           if (!rl_special_prefixes ||
3153               !rindex (rl_special_prefixes, the_line[rl_point]))
3154             rl_point++;
3155         }
3156     }
3157
3158   start = rl_point;
3159   rl_point = end;
3160   text = rl_copy (start, end);
3161
3162   /* If the user wants to TRY to complete, but then wants to give
3163      up and use the default completion function, they set the
3164      variable rl_attempted_completion_function. */
3165   if (rl_attempted_completion_function)
3166     {
3167       matches =
3168         (char **)(*rl_attempted_completion_function) (text, start, end);
3169
3170       if (matches)
3171         goto after_usual_completion;
3172     }
3173
3174   matches = completion_matches (text, our_func, start, end);
3175
3176  after_usual_completion:
3177   free (text);
3178
3179   if (!matches)
3180     ding ();
3181   else
3182     {
3183       register int i;
3184
3185     some_matches:
3186
3187       /* It seems to me that in all the cases we handle we would like
3188          to ignore duplicate possiblilities.  Scan for the text to
3189          insert being identical to the other completions. */
3190       if (rl_ignore_completion_duplicates)
3191         {
3192           char *lowest_common;
3193           int j, newlen = 0;
3194
3195           /* Sort the items. */
3196           /* It is safe to sort this array, because the lowest common
3197              denominator found in matches[0] will remain in place. */
3198           for (i = 0; matches[i]; i++);
3199           qsort (matches, i, sizeof (char *), compare_strings);
3200
3201           /* Remember the lowest common denimator for it may be unique. */
3202           lowest_common = savestring (matches[0]);
3203
3204           for (i = 0; matches[i + 1]; i++)
3205             {
3206               if (strcmp (matches[i], matches[i + 1]) == 0)
3207                 {
3208                   free (matches[i]);
3209                   matches[i] = (char *)-1;
3210                 }
3211               else
3212                 newlen++;
3213             }
3214
3215           /* We have marked all the dead slots with (char *)-1.
3216              Copy all the non-dead entries into a new array. */
3217           {
3218             char **temp_array =
3219               (char **)malloc ((3 + newlen) * sizeof (char *));
3220
3221             for (i = 1, j = 1; matches[i]; i++)
3222               if (matches[i] != (char *)-1)
3223                 temp_array[j++] = matches[i];
3224             temp_array[j] = (char *)NULL;
3225
3226             if (matches[0] != (char *)-1)
3227               free (matches[0]);
3228             free (matches);
3229
3230             matches = temp_array;
3231           }
3232
3233           /* Place the lowest common denominator back in [0]. */
3234           matches[0] = lowest_common;
3235
3236           /* If there is one string left, and it is identical to the
3237              lowest common denominator, then the LCD is the string to
3238              insert. */
3239           if (j == 2 && strcmp (matches[0], matches[1]) == 0)
3240             {
3241               free (matches[1]);
3242               matches[1] = (char *)NULL;
3243             }
3244         }
3245
3246       switch (what_to_do)
3247         {
3248         case TAB:
3249           if (matches[0])
3250             {
3251               rl_delete_text (start, rl_point);
3252               rl_point = start;
3253               rl_insert_text (matches[0]);
3254             }
3255
3256           /* If there are more matches, ring the bell to indicate.
3257              If this was the only match, and we are hacking files,
3258              check the file to see if it was a directory.  If so,
3259              add a '/' to the name.  If not, and we are at the end
3260              of the line, then add a space. */
3261           if (matches[1])
3262             {
3263               ding ();          /* There are other matches remaining. */
3264             }
3265           else
3266             {
3267               char temp_string[2];
3268
3269               temp_string[0] = delimiter ? delimiter : ' ';
3270               temp_string[1] = '\0';
3271
3272               if (rl_filename_completion_desired)
3273                 {
3274                   struct stat finfo;
3275                   char *tilde_expand ();
3276                   char *filename = tilde_expand (matches[0]);
3277
3278                   if ((stat (filename, &finfo) == 0) &&
3279                       ((finfo.st_mode & S_IFMT) == S_IFDIR))
3280                     {
3281                       if (the_line[rl_point] != '/')
3282                         rl_insert_text ("/");
3283                     }
3284                   else
3285                     {
3286                       if (rl_point == rl_end)
3287                         rl_insert_text (temp_string);
3288                     }
3289                   free (filename);
3290                 }
3291               else
3292                 {
3293                   if (rl_point == rl_end)
3294                     rl_insert_text (temp_string);
3295                 }
3296             }
3297           break;
3298
3299         case '*':
3300           {
3301             int i = 1;
3302
3303             rl_delete_text (start, rl_point);
3304             rl_point = start;
3305             rl_begin_undo_group ();
3306             if (matches[1])
3307               {
3308                 while (matches[i])
3309                   {
3310                     rl_insert_text (matches[i++]);
3311                     rl_insert_text (" ");
3312                   }
3313               }
3314             else
3315               {
3316                 rl_insert_text (matches[0]);
3317                 rl_insert_text (" ");
3318               }
3319             rl_end_undo_group ();
3320           }
3321           break;
3322
3323
3324         case '?':
3325           {
3326             int len, count, limit, max = 0;
3327             int j, k, l;
3328
3329             /* Handle simple case first.  What if there is only one answer? */
3330             if (!matches[1])
3331               {
3332                 char *rindex (), *temp;
3333
3334                 if (rl_filename_completion_desired)
3335                   temp = rindex (matches[0], '/');
3336                 else
3337                   temp = (char *)NULL;
3338
3339                 if (!temp)
3340                   temp = matches[0];
3341                 else
3342                   temp++;
3343
3344                 crlf ();
3345                 fprintf (out_stream, "%s", temp);
3346                 crlf ();
3347                 goto restart;
3348               }
3349
3350             /* There is more than one answer.  Find out how many there are,
3351                and find out what the maximum printed length of a single entry
3352                is. */
3353             for (i = 1; matches[i]; i++)
3354               {
3355                 char *rindex (), *temp = (char *)NULL;
3356
3357                 /* If we are hacking filenames, then only count the characters
3358                    after the last slash in the pathname. */
3359                 if (rl_filename_completion_desired)
3360                   temp = rindex (matches[i], '/');
3361                 else
3362                   temp = (char *)NULL;
3363
3364                 if (!temp)
3365                   temp = matches[i];
3366                 else
3367                   temp++;
3368
3369                 if (strlen (temp) > max)
3370                   max = strlen (temp);
3371               }
3372
3373             len = i;
3374
3375             /* If there are many items, then ask the user if she
3376                really wants to see them all. */
3377             if (len >= rl_completion_query_items)
3378               {
3379                 crlf ();
3380                 fprintf (out_stream,
3381                          "There are %d possibilities.  Do you really", len);
3382                 crlf ();
3383                 fprintf (out_stream, "wish to see them all? (y or n)");
3384                 fflush (out_stream);
3385                 if (!get_y_or_n ())
3386                   {
3387                     crlf ();
3388                     goto restart;
3389                   }
3390               }
3391             /* How many items of MAX length can we fit in the screen window? */
3392             max += 2;
3393             limit = screenwidth / max;
3394             if (limit != 1 && (limit * max == screenwidth))
3395               limit--;
3396
3397             /* How many iterations of the printing loop? */
3398             count = (len + (limit - 1)) / limit;
3399
3400             /* Watch out for special case.  If LEN is less than LIMIT, then
3401                just do the inner printing loop. */
3402             if (len < limit) count = 1;
3403
3404             /* Sort the items if they are not already sorted. */
3405             if (!rl_ignore_completion_duplicates)
3406               qsort (matches, len, sizeof (char *), compare_strings);
3407
3408             /* Print the sorted items, up-and-down alphabetically, like
3409                ls might. */
3410             crlf ();
3411
3412             for (i = 1; i < count + 1; i++)
3413               {
3414                 for (j = 0, l = i; j < limit; j++)
3415                   {
3416                     if (l > len || !matches[l])
3417                       {
3418                         break;
3419                       }
3420                     else
3421                       {
3422                         char *rindex (), *temp = (char *)NULL;
3423
3424                         if (rl_filename_completion_desired)
3425                           temp = rindex (matches[l], '/');
3426                         else
3427                           temp = (char *)NULL;
3428
3429                         if (!temp)
3430                           temp = matches[l];
3431                         else
3432                           temp++;
3433
3434                         fprintf (out_stream, "%s", temp);
3435                         for (k = 0; k < max - strlen (temp); k++)
3436                           putc (' ', out_stream);
3437                       }
3438                     l += count;
3439                   }
3440                 crlf ();
3441               }
3442           restart:
3443
3444             rl_on_new_line ();
3445           }
3446           break;
3447
3448         default:
3449           abort ();
3450         }
3451
3452       for (i = 0; matches[i]; i++)
3453         free (matches[i]);
3454       free (matches);
3455     }
3456 }
3457
3458 /* Stupid comparison routine for qsort () ing strings. */
3459 static int
3460 compare_strings (s1, s2)
3461   char **s1, **s2;
3462 {
3463   return (strcmp (*s1, *s2));
3464 }
3465
3466 /* A completion function for usernames.
3467    TEXT contains a partial username preceded by a random
3468    character (usually `~').  */
3469 char *
3470 username_completion_function (text, state)
3471      int state;
3472      char *text;
3473 {
3474   static char *username = (char *)NULL;
3475   static struct passwd *entry;
3476   static int namelen;
3477
3478   if (!state)
3479     {
3480       if (username)
3481         free (username);
3482       username = savestring (&text[1]);
3483       namelen = strlen (username);
3484       setpwent ();
3485     }
3486
3487   while (entry = getpwent ())
3488     {
3489       if (strncmp (username, entry->pw_name, namelen) == 0)
3490         break;
3491     }
3492
3493   if (!entry)
3494     {
3495       endpwent ();
3496       return ((char *)NULL);
3497     }
3498   else
3499     {
3500       char *value = (char *)xmalloc (2 + strlen (entry->pw_name));
3501       *value = *text;
3502       strcpy (value + 1, entry->pw_name);
3503       rl_filename_completion_desired = 1;
3504       return (value);
3505     }
3506 }
3507
3508 /* If non-null, this contains the address of a function to call if the
3509    standard meaning for expanding a tilde fails.  The function is called
3510    with the text (sans tilde, as in "foo"), and returns a malloc()'ed string
3511    which is the expansion, or a NULL pointer if there is no expansion. */
3512 Function *rl_tilde_expander = (Function *)NULL;
3513
3514 /* Expand FILENAME if it begins with a tilde.  This always returns
3515    a new string. */
3516 char *
3517 tilde_expand (filename)
3518      char *filename;
3519 {
3520   char *dirname = filename ? savestring (filename) : (char *)NULL;
3521
3522   if (dirname && *dirname == '~')
3523     {
3524       char *temp_name;
3525       if (!dirname[1] || dirname[1] == '/')
3526         {
3527           /* Prepend $HOME to the rest of the string. */
3528           char *temp_home = (char *)getenv ("HOME");
3529
3530           temp_name = (char *)alloca (1 + strlen (&dirname[1])
3531                                       + (temp_home? strlen (temp_home) : 0));
3532           temp_name[0] = '\0';
3533           if (temp_home)
3534             strcpy (temp_name, temp_home);
3535           strcat (temp_name, &dirname[1]);
3536           free (dirname);
3537           dirname = savestring (temp_name);
3538         }
3539       else
3540         {
3541           struct passwd *getpwnam (), *user_entry;
3542           char *username = (char *)alloca (257);
3543           int i, c;
3544
3545           for (i = 1; c = dirname[i]; i++)
3546             {
3547               if (c == '/') break;
3548               else username[i - 1] = c;
3549             }
3550           username[i - 1] = '\0';
3551
3552           if (!(user_entry = getpwnam (username)))
3553             {
3554               /* If the calling program has a special syntax for
3555                  expanding tildes, and we couldn't find a standard
3556                  expansion, then let them try. */
3557               if (rl_tilde_expander)
3558                 {
3559                   char *expansion;
3560
3561                   expansion = (char *)(*rl_tilde_expander) (username);
3562
3563                   if (expansion)
3564                     {
3565                       temp_name = (char *)alloca (1 + strlen (expansion)
3566                                                   + strlen (&dirname[i]));
3567                       strcpy (temp_name, expansion);
3568                       strcat (temp_name, &dirname[i]);
3569                       free (expansion);
3570                       goto return_name;
3571                     }
3572                 }
3573               /*
3574                * We shouldn't report errors.
3575                */
3576             }
3577           else
3578             {
3579               temp_name = (char *)alloca (1 + strlen (user_entry->pw_dir)
3580                                           + strlen (&dirname[i]));
3581               strcpy (temp_name, user_entry->pw_dir);
3582               strcat (temp_name, &dirname[i]);
3583             return_name:
3584               free (dirname);
3585               dirname = savestring (temp_name);
3586             }
3587         }
3588     }
3589   return (dirname);
3590 }
3591
3592 \f
3593 /* **************************************************************** */
3594 /*                                                                  */
3595 /*                      Undo, and Undoing                           */
3596 /*                                                                  */
3597 /* **************************************************************** */
3598
3599 /* Non-zero tells rl_delete_text and rl_insert_text to not add to
3600    the undo list. */
3601 int doing_an_undo = 0;
3602
3603 /* The current undo list for THE_LINE. */
3604 UNDO_LIST *rl_undo_list = (UNDO_LIST *)NULL;
3605
3606 /* Remember how to undo something.  Concatenate some undos if that
3607    seems right. */
3608 rl_add_undo (what, start, end, text)
3609      enum undo_code what;
3610      int start, end;
3611      char *text;
3612 {
3613   UNDO_LIST *temp = (UNDO_LIST *)xmalloc (sizeof (UNDO_LIST));
3614   temp->what = what;
3615   temp->start = start;
3616   temp->end = end;
3617   temp->text = text;
3618   temp->next = rl_undo_list;
3619   rl_undo_list = temp;
3620 }
3621
3622 /* Free the existing undo list. */
3623 free_undo_list ()
3624 {
3625   while (rl_undo_list) {
3626     UNDO_LIST *release = rl_undo_list;
3627     rl_undo_list = rl_undo_list->next;
3628
3629     if (release->what == UNDO_DELETE)
3630       free (release->text);
3631
3632     free (release);
3633   }
3634 }
3635
3636 /* Undo the next thing in the list.  Return 0 if there
3637    is nothing to undo, or non-zero if there was. */
3638 int
3639 rl_do_undo ()
3640 {
3641   UNDO_LIST *release;
3642   int waiting_for_begin = 0;
3643
3644 undo_thing:
3645   if (!rl_undo_list)
3646     return (0);
3647
3648   doing_an_undo = 1;
3649
3650   switch (rl_undo_list->what) {
3651
3652     /* Undoing deletes means inserting some text. */
3653   case UNDO_DELETE:
3654     rl_point = rl_undo_list->start;
3655     rl_insert_text (rl_undo_list->text);
3656     free (rl_undo_list->text);
3657     break;
3658
3659     /* Undoing inserts means deleting some text. */
3660   case UNDO_INSERT:
3661     rl_delete_text (rl_undo_list->start, rl_undo_list->end);
3662     rl_point = rl_undo_list->start;
3663     break;
3664
3665     /* Undoing an END means undoing everything 'til we get to
3666        a BEGIN. */
3667   case UNDO_END:
3668     waiting_for_begin++;
3669     break;
3670
3671     /* Undoing a BEGIN means that we are done with this group. */
3672   case UNDO_BEGIN:
3673     if (waiting_for_begin)
3674       waiting_for_begin--;
3675     else
3676       abort ();
3677     break;
3678   }
3679
3680   doing_an_undo = 0;
3681
3682   release = rl_undo_list;
3683   rl_undo_list = rl_undo_list->next;
3684   free (release);
3685
3686   if (waiting_for_begin)
3687     goto undo_thing;
3688
3689   return (1);
3690 }
3691
3692 /* Begin a group.  Subsequent undos are undone as an atomic operation. */
3693 rl_begin_undo_group ()
3694 {
3695   rl_add_undo (UNDO_BEGIN, 0, 0, 0);
3696 }
3697
3698 /* End an undo group started with rl_begin_undo_group (). */
3699 rl_end_undo_group ()
3700 {
3701   rl_add_undo (UNDO_END, 0, 0, 0);
3702 }
3703
3704 /* Save an undo entry for the text from START to END. */
3705 rl_modifying (start, end)
3706      int start, end;
3707 {
3708   if (start > end)
3709     {
3710       int t = start;
3711       start = end;
3712       end = t;
3713     }
3714
3715   if (start != end)
3716     {
3717       char *temp = rl_copy (start, end);
3718       rl_begin_undo_group ();
3719       rl_add_undo (UNDO_DELETE, start, end, temp);
3720       rl_add_undo (UNDO_INSERT, start, end, (char *)NULL);
3721       rl_end_undo_group ();
3722     }
3723 }
3724
3725 /* Revert the current line to its previous state. */
3726 rl_revert_line ()
3727 {
3728   if (!rl_undo_list) ding ();
3729   else {
3730     while (rl_undo_list)
3731       rl_do_undo ();
3732   }
3733 }
3734
3735 /* Do some undoing of things that were done. */
3736 rl_undo_command (count)
3737 {
3738   if (count < 0) return;        /* Nothing to do. */
3739
3740   while (count)
3741     {
3742       if (rl_do_undo ())
3743         {
3744           count--;
3745         }
3746       else
3747         {
3748           ding ();
3749           break;
3750         }
3751     }
3752 }
3753 \f
3754 /* **************************************************************** */
3755 /*                                                                  */
3756 /*                      History Utilities                           */
3757 /*                                                                  */
3758 /* **************************************************************** */
3759
3760 /* We already have a history library, and that is what we use to control
3761    the history features of readline.  However, this is our local interface
3762    to the history mechanism. */
3763
3764 /* While we are editing the history, this is the saved
3765    version of the original line. */
3766 HIST_ENTRY *saved_line_for_history = (HIST_ENTRY *)NULL;
3767
3768 /* Set the history pointer back to the last entry in the history. */
3769 start_using_history ()
3770 {
3771   using_history ();
3772   if (saved_line_for_history)
3773     free_history_entry (saved_line_for_history);
3774
3775   saved_line_for_history = (HIST_ENTRY *)NULL;
3776 }
3777
3778 /* Free the contents (and containing structure) of a HIST_ENTRY. */
3779 free_history_entry (entry)
3780      HIST_ENTRY *entry;
3781 {
3782   if (!entry) return;
3783   if (entry->line)
3784     free (entry->line);
3785   free (entry);
3786 }
3787
3788 /* Perhaps put back the current line if it has changed. */
3789 maybe_replace_line ()
3790 {
3791   HIST_ENTRY *temp = current_history ();
3792
3793   /* If the current line has changed, save the changes. */
3794   if (temp && ((UNDO_LIST *)(temp->data) != rl_undo_list)) {
3795     temp = replace_history_entry (where_history (), the_line, rl_undo_list);
3796     free (temp->line);
3797     free (temp);
3798   }
3799 }
3800
3801 /* Put back the saved_line_for_history if there is one. */
3802 maybe_unsave_line ()
3803 {
3804   if (saved_line_for_history) {
3805     strcpy (the_line, saved_line_for_history->line);
3806     rl_undo_list = (UNDO_LIST *)saved_line_for_history->data;
3807     free_history_entry (saved_line_for_history);
3808     saved_line_for_history = (HIST_ENTRY *)NULL;
3809     rl_end = rl_point = strlen (the_line);
3810   } else {
3811     ding ();
3812   }
3813 }
3814
3815 /* Save the current line in saved_line_for_history. */
3816 maybe_save_line ()
3817 {
3818   if (!saved_line_for_history) {
3819     saved_line_for_history = (HIST_ENTRY *)xmalloc (sizeof (HIST_ENTRY));
3820     saved_line_for_history->line = savestring (the_line);
3821     saved_line_for_history->data = (char *)rl_undo_list;
3822   }
3823 }
3824
3825
3826 \f
3827 /* **************************************************************** */
3828 /*                                                                  */
3829 /*                      History Commands                            */
3830 /*                                                                  */
3831 /* **************************************************************** */
3832
3833 /* Meta-< goes to the start of the history. */
3834 rl_beginning_of_history ()
3835 {
3836   rl_get_previous_history (1 + where_history ());
3837 }
3838
3839 /* Meta-> goes to the end of the history.  (The current line). */
3840 rl_end_of_history ()
3841 {
3842   maybe_replace_line ();
3843   using_history ();
3844   maybe_unsave_line ();
3845 }
3846
3847 /* Move down to the next history line. */
3848 rl_get_next_history (count)
3849      int count;
3850 {
3851   HIST_ENTRY *temp = (HIST_ENTRY *)NULL;
3852
3853   if (count < 0)
3854     {
3855       rl_get_previous_history (-count);
3856       return;
3857     }
3858
3859   if (!count)
3860     return;
3861
3862   maybe_replace_line ();
3863
3864   while (count)
3865     {
3866       temp = next_history ();
3867       if (!temp)
3868         break;
3869       --count;
3870     }
3871
3872   if (!temp)
3873     maybe_unsave_line ();
3874   else
3875     {
3876       strcpy (the_line, temp->line);
3877       rl_undo_list = (UNDO_LIST *)temp->data;
3878       rl_end = rl_point = strlen (the_line);
3879     }
3880 }
3881
3882 /* Get the previous item out of our interactive history, making it the current
3883    line.  If there is no previous history, just ding. */
3884 rl_get_previous_history (count)
3885      int count;
3886 {
3887   HIST_ENTRY *old_temp = (HIST_ENTRY *)NULL;
3888   HIST_ENTRY *temp = (HIST_ENTRY *)NULL;
3889
3890   if (count < 0)
3891     {
3892       rl_get_next_history (-count);
3893       return;
3894     }
3895
3896   if (!count)
3897     return;
3898
3899   /* If we don't have a line saved, then save this one. */
3900   maybe_save_line ();
3901
3902   /* If the current line has changed, save the changes. */
3903   maybe_replace_line ();
3904
3905   while (count)
3906     {
3907       temp = previous_history ();
3908       if (!temp)
3909         break;
3910       else
3911         old_temp = temp;
3912       --count;
3913     }
3914
3915   /* If there was a large argument, and we moved back to the start of the
3916      history, that is not an error.  So use the last value found. */
3917   if (!temp && old_temp)
3918     temp = old_temp;
3919
3920   if (!temp)
3921     ding ();
3922   else
3923     {
3924       strcpy (the_line, temp->line);
3925       rl_undo_list = (UNDO_LIST *)temp->data;
3926       rl_end = rl_point = strlen (the_line);
3927 #ifdef VI_MODE
3928       if (rl_editing_mode == vi_mode)
3929         rl_point = 0;
3930 #endif /* VI_MODE */
3931     }
3932 }
3933
3934 /* There is a command in ksh which yanks into this line, the last word
3935    of the previous line.  Here it is.  We left it on M-. */
3936 rl_yank_previous_last_arg (ignore)
3937      int ignore;
3938 {
3939 }
3940
3941
3942 \f
3943 /* **************************************************************** */
3944 /*                                                                  */
3945 /*                      I-Search and Searching                      */
3946 /*                                                                  */
3947 /* **************************************************************** */
3948
3949 /* Search backwards through the history looking for a string which is typed
3950    interactively.  Start with the current line. */
3951 rl_reverse_search_history (sign, key)
3952      int sign;
3953      int key;
3954 {
3955   rl_search_history (-sign, key);
3956 }
3957
3958 /* Search forwards through the history looking for a string which is typed
3959    interactively.  Start with the current line. */
3960 rl_forward_search_history (sign, key)
3961      int sign;
3962      int key;
3963 {
3964   rl_search_history (sign, key);
3965 }
3966
3967 /* Display the current state of the search in the echo-area.
3968    SEARCH_STRING contains the string that is being searched for,
3969    DIRECTION is zero for forward, or 1 for reverse,
3970    WHERE is the history list number of the current line.  If it is
3971    -1, then this line is the starting one. */
3972 rl_display_search (search_string, reverse_p, where)
3973      char *search_string;
3974      int reverse_p, where;
3975 {
3976   char *message = (char *)NULL;
3977
3978   message =
3979     (char *)alloca (1 + (search_string ? strlen (search_string) : 0) + 30);
3980
3981   *message = '\0';
3982
3983 #ifdef NEVER
3984   if (where != -1)
3985     sprintf (message, "[%d]", where + history_base);
3986 #endif
3987
3988   strcat (message, "(");
3989
3990   if (reverse_p)
3991     strcat (message, "reverse-");
3992
3993   strcat (message, "i-search)`");
3994
3995   if (search_string)
3996     strcat (message, search_string);
3997
3998   strcat (message, "': ");
3999   rl_message (message, 0, 0);
4000   rl_redisplay ();
4001 }
4002
4003 /* Search through the history looking for an interactively typed string.
4004    This is analogous to i-search.  We start the search in the current line.
4005    DIRECTION is which direction to search; > 0 means forward, < 0 means
4006    backwards. */
4007 rl_search_history (direction, invoking_key)
4008      int direction;
4009      int invoking_key;
4010 {
4011   /* The string that the user types in to search for. */
4012   char *search_string = (char *)alloca (128);
4013
4014   /* The current length of SEARCH_STRING. */
4015   int search_string_index;
4016
4017   /* The list of lines to search through. */
4018   char **lines;
4019
4020   /* The length of LINES. */
4021   int hlen;
4022
4023   /* Where we get LINES from. */
4024   HIST_ENTRY **hlist = history_list ();
4025
4026   int orig_point = rl_point;
4027   int orig_line = where_history ();
4028   int last_found_line = orig_line;
4029   int c, done = 0;
4030   register int i = 0;
4031
4032
4033   /* The line currently being searched. */
4034   char *sline;
4035
4036   /* Offset in that line. */
4037   int index;
4038
4039   /* Non-zero if we are doing a reverse search. */
4040   int reverse = (direction < 0);
4041
4042   /* Create an arrary of pointers to the lines that we want to search. */
4043
4044   maybe_replace_line ();
4045   if (hlist)
4046     for (i = 0; hlist[i]; i++);
4047
4048   /* Allocate space for this many lines, +1 for the current input line,
4049      and remember those lines. */
4050   lines = (char **)alloca ((1 + (hlen = i)) * sizeof (char *));
4051   for (i = 0; i < hlen; i++)
4052     lines[i] = hlist[i]->line;
4053
4054   if (saved_line_for_history)
4055     lines[i] = saved_line_for_history->line;
4056   else
4057     {
4058       /* So I have to type it in this way instead. */
4059       lines[i] = (char *)alloca (1 + strlen (the_line));
4060       strcpy (lines[i], &the_line[0]);
4061     }
4062
4063   hlen++;
4064
4065   /* The line where we start the search. */
4066   i = orig_line;
4067
4068   /* Initialize search parameters. */
4069   *search_string = '\0';
4070   search_string_index = 0;
4071
4072   rl_display_search (search_string, reverse, -1);
4073
4074   sline = the_line;
4075   index = rl_point;
4076
4077   while (!done)
4078     {
4079       c = rl_read_key ();
4080
4081       /* Hack C to Do What I Mean. */
4082       {
4083         Function *f = (Function *)NULL;
4084
4085         if (keymap[c].type == ISFUNC)
4086           f = keymap[c].function;
4087
4088         if (f == rl_reverse_search_history)
4089           c = reverse ? -1 : -2;
4090         else if (f == rl_forward_search_history)
4091           c =  !reverse ? -1 : -2;
4092       }
4093
4094       switch (c)
4095         {
4096         case ESC:
4097           done = 1;
4098           continue;
4099
4100           /* case invoking_key: */
4101         case -1:
4102           goto search_again;
4103
4104           /* switch directions */
4105         case -2:
4106           direction = -direction;
4107           reverse = (direction < 0);
4108
4109           goto do_search;
4110
4111         case CTRL ('G'):
4112           strcpy (the_line, lines[orig_line]);
4113           rl_point = orig_point;
4114           rl_end = strlen (the_line);
4115           rl_clear_message ();
4116           return;
4117
4118         default:
4119           if (c < 32 || c > 126)
4120             {
4121               rl_execute_next (c);
4122               done = 1;
4123               continue;
4124             }
4125           else
4126             {
4127               search_string[search_string_index++] = c;
4128               search_string[search_string_index] = '\0';
4129               goto do_search;
4130
4131             search_again:
4132
4133               if (!search_string_index)
4134                 continue;
4135               else
4136                 {
4137                   if (reverse)
4138                     --index;
4139                   else
4140                     if (index != strlen (sline))
4141                       ++index;
4142                     else
4143                       ding ();
4144                 }
4145             do_search:
4146
4147               while (1)
4148                 {
4149                   if (reverse)
4150                     {
4151                       while (index >= 0)
4152                         if (strncmp
4153                             (search_string,
4154                              sline + index,
4155                              search_string_index) == 0)
4156                           goto string_found;
4157                         else
4158                           index--;
4159                     }
4160                   else
4161                     {
4162                       register int limit =
4163                         (strlen (sline) - search_string_index) + 1;
4164
4165                       while (index < limit)
4166                         {
4167                           if (strncmp (search_string,
4168                                        sline + index,
4169                                        search_string_index) == 0)
4170                             goto string_found;
4171                           index++;
4172                         }
4173                     }
4174
4175                 next_line:
4176                   i += direction;
4177
4178                   /* At limit for direction? */
4179                   if ((reverse && i < 0) ||
4180                       (!reverse && i == hlen))
4181                     goto search_failed;
4182
4183                   sline = lines[i];
4184                   if (reverse)
4185                     index = strlen (sline);
4186                   else
4187                     index = 0;
4188
4189                   /* If the search string is longer than the current
4190                      line, no match. */
4191                   if (search_string_index > strlen (sline))
4192                     goto next_line;
4193
4194                   /* Start actually searching. */
4195                   if (reverse)
4196                     index -= search_string_index;
4197                 }
4198
4199             search_failed:
4200               /* We cannot find the search string.  Ding the bell. */
4201               ding ();
4202               i = last_found_line;
4203               break;
4204
4205             string_found:
4206               /* We have found the search string.  Just display it.  But don't
4207                  actually move there in the history list until the user accepts
4208                  the location. */
4209               strcpy (the_line, lines[i]);
4210               rl_point = index;
4211               rl_end = strlen (the_line);
4212               last_found_line = i;
4213               rl_display_search (search_string, reverse,
4214                                  (i == orig_line) ? -1 : i);
4215             }
4216         }
4217       continue;
4218     }
4219   /* The user has won.  They found the string that they wanted.  Now all
4220      we have to do is place them there. */
4221   {
4222     int now = last_found_line;
4223
4224     /* First put back the original state. */
4225     strcpy (the_line, lines[orig_line]);
4226
4227     if (now < orig_line)
4228       rl_get_previous_history (orig_line - now);
4229     else
4230       rl_get_next_history (now - orig_line);
4231
4232     rl_point = index;
4233     rl_clear_message ();
4234   }
4235 }
4236
4237 /* Make C be the next command to be executed. */
4238 rl_execute_next (c)
4239      int c;
4240 {
4241   rl_pending_input = c;
4242 }
4243 \f
4244 /* **************************************************************** */
4245 /*                                                                  */
4246 /*                      Killing Mechanism                           */
4247 /*                                                                  */
4248 /* **************************************************************** */
4249
4250 /* What we assume for a max number of kills. */
4251 #define DEFAULT_MAX_KILLS 10
4252
4253 /* The real variable to look at to find out when to flush kills. */
4254 int rl_max_kills = DEFAULT_MAX_KILLS;
4255
4256 /* Where to store killed text. */
4257 char **rl_kill_ring = (char **)NULL;
4258
4259 /* Where we are in the kill ring. */
4260 int rl_kill_index = 0;
4261
4262 /* How many slots we have in the kill ring. */
4263 int rl_kill_ring_length = 0;
4264
4265 /* How to say that you only want to save a certain amount
4266    of kill material. */
4267 rl_set_retained_kills (num)
4268      int num;
4269 {}
4270
4271 /* The way to kill something.  This appends or prepends to the last
4272    kill, if the last command was a kill command.  if FROM is less
4273    than TO, then the text is appended, otherwise prepended.  If the
4274    last command was not a kill command, then a new slot is made for
4275    this kill. */
4276 rl_kill_text (from, to)
4277      int from, to;
4278 {
4279   int slot;
4280   char *text = rl_copy (from, to);
4281
4282   /* Is there anything to kill? */
4283   if (from == to) {
4284     free (text);
4285     last_command_was_kill++;
4286     return;
4287   }
4288
4289   /* Delete the copied text from the line. */
4290   rl_delete_text (from, to);
4291
4292   /* First, find the slot to work with. */
4293   if (!last_command_was_kill) {
4294
4295     /* Get a new slot.  */
4296     if (!rl_kill_ring) {
4297
4298       /* If we don't have any defined, then make one. */
4299       rl_kill_ring =
4300         (char **)xmalloc (((rl_kill_ring_length = 1) + 1) * sizeof (char *));
4301       slot = 1;
4302
4303     } else {
4304
4305       /* We have to add a new slot on the end, unless we have exceeded
4306          the max limit for remembering kills. */
4307       slot = rl_kill_ring_length;
4308       if (slot == rl_max_kills) {
4309         register int i;
4310         free (rl_kill_ring[0]);
4311         for (i = 0; i < slot; i++)
4312           rl_kill_ring[i] = rl_kill_ring[i + 1];
4313       } else {
4314         rl_kill_ring =
4315           (char **)xrealloc (rl_kill_ring,
4316                              ((slot = (rl_kill_ring_length += 1)) + 1)
4317                              * sizeof (char *));
4318       }
4319     }
4320     slot--;
4321   } else {
4322     slot = rl_kill_ring_length - 1;
4323   }
4324
4325   /* If the last command was a kill, prepend or append. */
4326   if (last_command_was_kill) {
4327     char *old = rl_kill_ring[slot];
4328     char *new = (char *)xmalloc (1 + strlen (old) + strlen (text));
4329
4330     if (from < to) {
4331       strcpy (new, old);
4332       strcat (new, text);
4333     } else {
4334       strcpy (new, text);
4335       strcat (new, old);
4336     }
4337     free (old);
4338     free (text);
4339     rl_kill_ring[slot] = new;
4340   } else {
4341     rl_kill_ring[slot] = text;
4342   }
4343   rl_kill_index = slot;
4344   last_command_was_kill++;
4345 }
4346
4347 /* Now REMEMBER!  In order to do prepending or appending correctly, kill
4348    commands always make rl_point's original position be the FROM argument,
4349    and rl_point's extent be the TO argument. */
4350
4351
4352 /* **************************************************************** */
4353 /*                                                                  */
4354 /*                      Killing Commands                            */
4355 /*                                                                  */
4356 /* **************************************************************** */
4357
4358 /* Delete the word at point, saving the text in the kill ring. */
4359 rl_kill_word (count)
4360      int count;
4361 {
4362   int orig_point = rl_point;
4363
4364   if (count < 0)
4365     rl_backward_kill_word (-count);
4366   else
4367     {
4368       rl_forward_word (count);
4369
4370       if (rl_point != orig_point)
4371         rl_kill_text (orig_point, rl_point);
4372
4373       rl_point = orig_point;
4374     }
4375 }
4376
4377 /* Rubout the word before point, placing it on the kill ring. */
4378 rl_backward_kill_word (count)
4379      int count;
4380 {
4381   int orig_point = rl_point;
4382
4383   if (count < 0)
4384     rl_kill_word (-count);
4385   else
4386     {
4387       rl_backward_word (count);
4388
4389       if (rl_point != orig_point)
4390         rl_kill_text (orig_point, rl_point);
4391     }
4392 }
4393
4394 /* Kill from here to the end of the line.  If DIRECTION is negative, kill
4395    back to the line start instead. */
4396 rl_kill_line (direction)
4397      int direction;
4398 {
4399   int orig_point = rl_point;
4400
4401   if (direction < 0)
4402     rl_backward_kill_line (1);
4403   else
4404     {
4405       rl_end_of_line ();
4406       if (orig_point != rl_point)
4407         rl_kill_text (orig_point, rl_point);
4408       rl_point = orig_point;
4409     }
4410 }
4411
4412 /* Kill backwards to the start of the line.  If DIRECTION is negative, kill
4413    forwards to the line end instead. */
4414 rl_backward_kill_line (direction)
4415      int direction;
4416 {
4417   int orig_point = rl_point;
4418
4419   if (direction < 0)
4420     rl_kill_line (1);
4421   else
4422     {
4423       if (!rl_point)
4424         ding ();
4425       else
4426         {
4427           rl_beg_of_line ();
4428           rl_kill_text (orig_point, rl_point);
4429         }
4430     }
4431 }
4432
4433 /* Yank back the last killed text.  This ignores arguments. */
4434 rl_yank ()
4435 {
4436   if (!rl_kill_ring) rl_abort ();
4437   rl_insert_text (rl_kill_ring[rl_kill_index]);
4438 }
4439
4440 /* If the last command was yank, or yank_pop, and the text just
4441    before point is identical to the current kill item, then
4442    delete that text from the line, rotate the index down, and
4443    yank back some other text. */
4444 rl_yank_pop ()
4445 {
4446   int l;
4447
4448   if (((rl_last_func != rl_yank_pop) && (rl_last_func != rl_yank)) ||
4449       !rl_kill_ring)
4450     {
4451       rl_abort ();
4452     }
4453
4454   l = strlen (rl_kill_ring[rl_kill_index]);
4455   if (((rl_point - l) >= 0) &&
4456       (strncmp (the_line + (rl_point - l),
4457                 rl_kill_ring[rl_kill_index], l) == 0))
4458     {
4459       rl_delete_text ((rl_point - l), rl_point);
4460       rl_point -= l;
4461       rl_kill_index--;
4462       if (rl_kill_index < 0)
4463         rl_kill_index = rl_kill_ring_length - 1;
4464       rl_yank ();
4465     }
4466   else
4467     rl_abort ();
4468
4469 }
4470
4471 /* Yank the COUNTth argument from the previous history line. */
4472 rl_yank_nth_arg (count, ignore)
4473      int count;
4474 {
4475   register HIST_ENTRY *entry = previous_history ();
4476   char *arg;
4477
4478   if (entry)
4479     next_history ();
4480   else
4481     {
4482       ding ();
4483       return;
4484     }
4485
4486   arg = history_arg_extract (count, count, entry->line);
4487   if (!arg || !*arg)
4488     {
4489       ding ();
4490       return;
4491     }
4492
4493   rl_begin_undo_group ();
4494   if (rl_point && the_line[rl_point - 1] != ' ')
4495     rl_insert_text (" ");
4496   rl_insert_text (arg);
4497   free (arg);
4498   rl_end_undo_group ();
4499 }
4500
4501 /* Vi Mode. */
4502 #ifdef VI_MODE
4503 #include "vi_mode.c"
4504 #endif /* VI_MODE */
4505
4506 /* How to toggle back and forth between editing modes. */
4507 rl_vi_editing_mode ()
4508 {
4509 #ifdef VI_MODE
4510   rl_editing_mode = vi_mode;
4511   rl_vi_insertion_mode ();
4512 #endif /* VI_MODE */
4513 }
4514
4515 rl_emacs_editing_mode ()
4516 {
4517   rl_editing_mode = emacs_mode;
4518   keymap = emacs_standard_keymap;
4519 }
4520
4521 \f
4522 /* **************************************************************** */
4523 /*                                                                  */
4524 /*                           Completion                             */
4525 /*                                                                  */
4526 /* **************************************************************** */
4527
4528 /* Non-zero means that case is not significant in completion. */
4529 int completion_case_fold = 0;
4530
4531 /* Return an array of (char *) which is a list of completions for TEXT.
4532    If there are no completions, return a NULL pointer.
4533    The first entry in the returned array is the substitution for TEXT.
4534     The remaining entries are the possible completions.
4535    The array is terminated with a NULL pointer.
4536
4537    ENTRY_FUNCTION is a function of two args, and returns a (char *).
4538      The first argument is TEXT.
4539      The second is a state argument; it should be zero on the first call, and
4540      non-zero on subsequent calls.  It returns a NULL pointer to the caller
4541      when there are no more matches.
4542  */
4543 char **
4544 completion_matches (text, entry_function)
4545      char *text;
4546      char *(*entry_function) ();
4547 {
4548   /* Number of slots in match_list. */
4549   int match_list_size;
4550
4551   /* The list of matches. */
4552   char **match_list =
4553     (char **)xmalloc (((match_list_size = 10) + 1) * sizeof (char *));
4554
4555   /* Number of matches actually found. */
4556   int matches = 0;
4557
4558   /* Temporary string binder. */
4559   char *string;
4560
4561   match_list[1] = (char *)NULL;
4562
4563   while (string = (*entry_function) (text, matches))
4564     {
4565       if (matches + 1 == match_list_size)
4566         match_list =
4567           (char **)xrealloc (match_list,
4568                              ((match_list_size += 10) + 1) * sizeof (char *));
4569
4570       match_list[++matches] = string;
4571       match_list[matches + 1] = (char *)NULL;
4572     }
4573
4574   /* If there were any matches, then look through them finding out the
4575      lowest common denominator.  That then becomes match_list[0]. */
4576   if (matches)
4577     {
4578       register int i = 1;
4579       int low = 100000;         /* Count of max-matched characters. */
4580
4581       /* If only one match, just use that. */
4582       if (matches == 1)
4583         {
4584           match_list[0] = match_list[1];
4585           match_list[1] = (char *)NULL;
4586         }
4587       else
4588         {
4589           /* Otherwise, compare each member of the list with
4590              the next, finding out where they stop matching. */
4591
4592           while (i < matches)
4593             {
4594               register int c1, c2, si;
4595
4596               if (completion_case_fold)
4597                 {
4598                   for (si = 0;
4599                        (c1 = to_lower(match_list[i][si])) &&
4600                        (c2 = to_lower(match_list[i + 1][si]));
4601                        si++)
4602                     if (c1 != c2) break;
4603                 }
4604               else
4605                 {
4606                   for (si = 0;
4607                        (c1 = match_list[i][si]) &&
4608                        (c2 = match_list[i + 1][si]);
4609                        si++)
4610                     if (c1 != c2) break;
4611                 }
4612
4613               if (low > si) low = si;
4614               i++;
4615             }
4616           match_list[0] = (char *)xmalloc (low + 1);
4617           strncpy (match_list[0], match_list[1], low);
4618           match_list[0][low] = '\0';
4619         }
4620     }
4621   else                          /* There were no matches. */
4622     {
4623       free (match_list);
4624       match_list = (char **)NULL;
4625     }
4626   return (match_list);
4627 }
4628
4629 /* Okay, now we write the entry_function for filename completion.  In the
4630    general case.  Note that completion in the shell is a little different
4631    because of all the pathnames that must be followed when looking up the
4632    completion for a command. */
4633 char *
4634 filename_completion_function (text, state)
4635      int state;
4636      char *text;
4637 {
4638   static DIR *directory;
4639   static char *filename = (char *)NULL;
4640   static char *dirname = (char *)NULL;
4641   static char *users_dirname = (char *)NULL;
4642   static int filename_len;
4643
4644   struct direct *entry = (struct direct *)NULL;
4645
4646   /* If we don't have any state, then do some initialization. */
4647   if (!state)
4648     {
4649       char *rindex (), *temp;
4650
4651       if (dirname) free (dirname);
4652       if (filename) free (filename);
4653       if (users_dirname) free (users_dirname);
4654
4655       filename = savestring (text);
4656       if (!*text) text = ".";
4657       dirname = savestring (text);
4658
4659       temp = rindex (dirname, '/');
4660
4661       if (temp)
4662         {
4663           strcpy (filename, ++temp);
4664           *temp = '\0';
4665         }
4666       else
4667         strcpy (dirname, ".");
4668
4669       /* We aren't done yet.  We also support the "~user" syntax. */
4670
4671       /* Save the version of the directory that the user typed. */
4672       users_dirname = savestring (dirname);
4673       {
4674         char *tilde_expand (), *temp_dirname = tilde_expand (dirname);
4675         free (dirname);
4676         dirname = temp_dirname;
4677
4678         if (rl_symbolic_link_hook)
4679           (*rl_symbolic_link_hook) (&dirname);
4680       }
4681       directory = opendir (dirname);
4682       filename_len = strlen (filename);
4683
4684       rl_filename_completion_desired = 1;
4685     }
4686
4687   /* At this point we should entertain the possibility of hacking wildcarded
4688      filenames, like /usr/man*\/te<TAB>.  If the directory name contains
4689      globbing characters, then build an array of directories to glob on, and
4690      glob on the first one. */
4691
4692   /* Now that we have some state, we can read the directory. */
4693
4694   while (directory && (entry = readdir (directory)))
4695     {
4696       /* Special case for no filename.
4697          All entries except "." and ".." match. */
4698       if (!filename_len)
4699         {
4700           if ((strcmp (entry->d_name, ".") != 0) &&
4701               (strcmp (entry->d_name, "..") != 0))
4702             break;
4703         }
4704       else
4705         {
4706           /* Otherwise, if these match upto the length of filename, then
4707              it is a match. */
4708 #ifdef TMB_SYSV
4709           if ((strlen (entry->d_name) >= filename_len) &&
4710               (strncmp (filename, entry->d_name, filename_len) == 0))
4711 #else
4712             if ((entry->d_namlen >= filename_len) &&
4713                 (strncmp (filename, entry->d_name, filename_len) == 0))
4714 #endif /* TMB_SYSV */
4715               {
4716                 break;
4717               }
4718         }
4719     }
4720
4721   if (!entry)
4722     {
4723       if (directory)
4724         {
4725           closedir (directory);
4726           directory = (DIR *)NULL;
4727         }
4728       return (char *)NULL;
4729     }
4730   else
4731     {
4732       char *temp;
4733
4734       if (dirname && (strcmp (dirname, ".") != 0))
4735         {
4736 #ifdef TMB_SYSV
4737           temp = (char *)xmalloc (1 + strlen (users_dirname)
4738                                   + strlen (entry->d_name));
4739 #else
4740           temp = (char *)xmalloc (1 + strlen (users_dirname)
4741                                   + entry->d_namlen);
4742 #endif /* TMB_SYSV */
4743           strcpy (temp, users_dirname);
4744           strcat (temp, entry->d_name);
4745         }
4746       else
4747         {
4748           temp = (savestring (entry->d_name));
4749         }
4750       return (temp);
4751     }
4752 }
4753
4754 \f
4755 /* **************************************************************** */
4756 /*                                                                  */
4757 /*                      Binding keys                                */
4758 /*                                                                  */
4759 /* **************************************************************** */
4760
4761 /* rl_add_defun (char *name, Function *function, int key)
4762    Add NAME to the list of named functions.  Make FUNCTION
4763    be the function that gets called.
4764    If KEY is not -1, then bind it. */
4765 rl_add_defun (name, function, key)
4766      char *name;
4767      Function *function;
4768      int key;
4769 {
4770   if (key != -1)
4771     rl_bind_key (key, function);
4772   rl_add_funmap_entry (name, function);
4773 }
4774
4775 /* Bind KEY to FUNCTION.  Returns non-zero if KEY is out of range. */
4776 int
4777 rl_bind_key (key, function)
4778      int key;
4779      Function *function;
4780 {
4781   if (key < 0)
4782     return (key);
4783
4784   if (key > 127 && key < 256)
4785     {
4786       if (keymap[ESC].type == ISKMAP)
4787         {
4788           Keymap escmap = (Keymap)keymap[ESC].function;
4789
4790           key -= 128;
4791           escmap[key].type = ISFUNC;
4792           escmap[key].function = function;
4793           return (0);
4794         }
4795       return (key);
4796     }
4797
4798   keymap[key].type = ISFUNC;
4799   keymap[key].function = function;
4800  return (0);
4801 }
4802
4803 /* Bind KEY to FUNCTION in MAP.  Returns non-zero in case of invalid
4804    KEY. */
4805 int
4806 rl_bind_key_in_map (key, function, map)
4807      int key;
4808      Function *function;
4809      Keymap map;
4810 {
4811   int result;
4812   Keymap oldmap = keymap;
4813
4814   keymap = map;
4815   result = rl_bind_key (key, function);
4816   keymap = oldmap;
4817   return (result);
4818 }
4819
4820 /* Make KEY do nothing in the currently selected keymap.
4821    Returns non-zero in case of error. */
4822 int
4823 rl_unbind_key (key)
4824      int key;
4825 {
4826   return (rl_bind_key (key, (Function *)NULL));
4827 }
4828
4829 /* Make KEY do nothing in MAP.
4830    Returns non-zero in case of error. */
4831 int
4832 rl_unbind_key_in_map (key, map)
4833      int key;
4834      Keymap map;
4835 {
4836   return (rl_bind_key_in_map (key, (Function *)NULL, map));
4837 }
4838
4839 /* Bind the key sequence represented by the string KEYSEQ to
4840    FUNCTION.  This makes new keymaps as necessary.  The initial
4841    place to do bindings is in MAP. */
4842 rl_set_key (keyseq, function, map)
4843      char *keyseq;
4844      Function *function;
4845      Keymap map;
4846 {
4847   rl_generic_bind (ISFUNC, keyseq, function, map);
4848 }
4849
4850 /* Bind the key sequence represented by the string KEYSEQ to
4851    the string of characters MACRO.  This makes new keymaps as
4852    necessary.  The initial place to do bindings is in MAP. */
4853 rl_macro_bind (keyseq, macro, map)
4854      char *keyseq, *macro;
4855      Keymap map;
4856 {
4857   char *macro_keys = (char *)xmalloc (2 * (strlen (macro)));
4858   int macro_keys_len;
4859
4860   if (rl_translate_keyseq (macro, macro_keys, &macro_keys_len))
4861     {
4862       free (macro_keys);
4863       return;
4864     }
4865   rl_generic_bind (ISMACR, keyseq, macro_keys, map);
4866 }
4867
4868 /* Bind the key sequence represented by the string KEYSEQ to
4869    the arbitrary pointer DATA.  TYPE says what kind of data is
4870    pointed to by DATA, right now this can be a function (ISFUNC),
4871    a macro (ISMACR), or a keymap (ISKMAP).  This makes new keymaps
4872    as necessary.  The initial place to do bindings is in MAP. */
4873 rl_generic_bind (type, keyseq, data, map)
4874      int type;
4875      char *keyseq, *data;
4876      Keymap map;
4877 {
4878   char *keys;
4879   int keys_len;
4880   register int i;
4881
4882   /* If no keys to bind to, exit right away. */
4883   if (!keyseq || !*keyseq)
4884     {
4885       if (type == ISMACR)
4886         free (data);
4887       return;
4888     }
4889
4890   keys = (char *)alloca (1 + (2 * strlen (keyseq)));
4891
4892   /* Translate the ASCII representation of KEYSEQ into an array
4893      of characters.  Stuff the characters into ARRAY, and the
4894      length of ARRAY into LENGTH. */
4895   if (rl_translate_keyseq (keyseq, keys, &keys_len))
4896     return;
4897
4898   /* Bind keys, making new keymaps as necessary. */
4899   for (i = 0; i < keys_len; i++)
4900     {
4901       if (i + 1 < keys_len)
4902         {
4903           if (map[keys[i]].type != ISKMAP)
4904             {
4905               if (map[i].type == ISMACR)
4906                 free ((char *)map[i].function);
4907
4908               map[keys[i]].type = ISKMAP;
4909               map[keys[i]].function = (Function *)rl_make_bare_keymap ();
4910             }
4911           map = (Keymap)map[keys[i]].function;
4912         }
4913       else
4914         {
4915           if (map[keys[i]].type == ISMACR)
4916             free ((char *)map[keys[i]].function);
4917
4918           map[keys[i]].function = (Function *)data;
4919           map[keys[i]].type = type;
4920         }
4921     }
4922 }
4923
4924 /* Translate the ASCII representation of SEQ, stuffing the
4925    values into ARRAY, an array of characters.  LEN gets the
4926    final length of ARRAY.  Return non-zero if there was an
4927    error parsing SEQ. */
4928 rl_translate_keyseq (seq, array, len)
4929      char *seq, *array;
4930      int *len;
4931 {
4932   register int i, c, l = 0;
4933
4934   for (i = 0; c = seq[i]; i++)
4935     {
4936       if (c == '\\')
4937         {
4938           c = seq[++i];
4939
4940           if (!c)
4941             break;
4942
4943           if (((c == 'C' || c == 'M') &&  seq[i + 1] == '-') ||
4944               (c == 'e'))
4945             {
4946               /* Handle special case of backwards define. */
4947               if (strncmp (&seq[i], "C-\\M-", 5) == 0)
4948                 {
4949                   array[l++] = ESC;
4950                   i += 5;
4951                   array[l++] = CTRL (to_upper (seq[i]));
4952                   if (!seq[i])
4953                     i--;
4954                   continue;
4955                 }
4956
4957               switch (c)
4958                 {
4959                 case 'M':
4960                   i++;
4961                   array[l++] = ESC;
4962                   break;
4963
4964                 case 'C':
4965                   i += 2;
4966                   array[l++] = CTRL (to_upper (seq[i]));
4967                   break;
4968
4969                 case 'e':
4970                   array[l++] = ESC;
4971                 }
4972
4973               continue;
4974             }
4975         }
4976       array[l++] = c;
4977     }
4978
4979   *len = l;
4980   array[l] = '\0';
4981   return (0);
4982 }
4983
4984 /* Return a pointer to the function that STRING represents.
4985    If STRING doesn't have a matching function, then a NULL pointer
4986    is returned. */
4987 Function *
4988 rl_named_function (string)
4989      char *string;
4990 {
4991   register int i;
4992
4993   for (i = 0; funmap[i]; i++)
4994     if (stricmp (funmap[i]->name, string) == 0)
4995       return (funmap[i]->function);
4996   return ((Function *)NULL);
4997 }
4998
4999 /* The last key bindings file read. */
5000 static char *last_readline_init_file = "~/.inputrc";
5001
5002 /* Re-read the current keybindings file. */
5003 rl_re_read_init_file (count, ignore)
5004      int count, ignore;
5005 {
5006   rl_read_init_file (last_readline_init_file);
5007 }
5008
5009 /* Do key bindings from a file.  If FILENAME is NULL it defaults
5010    to `~/.inputrc'.  If the file existed and could be opened and
5011    read, 0 is returned, otherwise errno is returned. */
5012 int
5013 rl_read_init_file (filename)
5014      char *filename;
5015 {
5016   extern int errno;
5017   int line_size, line_index;
5018   char *line = (char *)xmalloc (line_size = 100);
5019   char *openname;
5020   FILE *file;
5021
5022   int c;
5023
5024   /* Default the filename. */
5025   if (!filename)
5026     filename = "~/.inputrc";
5027
5028   openname = tilde_expand (filename);
5029
5030   /* Open the file. */
5031   file = fopen (openname, "r");
5032   free (openname);
5033
5034   if (!file)
5035     return (errno);
5036
5037   last_readline_init_file = filename;
5038
5039   /* Loop reading lines from the file.  Lines that start with `#' are
5040      comments, all other lines are commands for readline initialization. */
5041   while ((c = rl_getc (file)) != EOF)
5042     {
5043       /* If comment, flush to EOL. */
5044       if (c == '#')
5045         {
5046           while ((c = rl_getc (file)) != EOF && c != '\n');
5047           if (c == EOF)
5048             goto function_exit;
5049           continue;
5050         }
5051
5052       /* Otherwise, this is the start of a line.  Read the
5053          line from the file. */
5054       line_index = 0;
5055       while (c != EOF && c != '\n')
5056         {
5057           line[line_index++] = c;
5058           if (line_index == line_size)
5059             line = (char *)xrealloc (line, line_size += 100);
5060           c = rl_getc (file);
5061         }
5062       line[line_index] = '\0';
5063
5064       /* Parse the line. */
5065       rl_parse_and_bind (line);
5066     }
5067
5068 function_exit:
5069
5070   free (line);
5071   /* Close up the file and exit. */
5072   fclose (file);
5073   return (0);
5074 }
5075
5076
5077 /* **************************************************************** */
5078 /*                                                                  */
5079 /*                      Parser Directives                           */
5080 /*                                                                  */
5081 /* **************************************************************** */
5082
5083 /* Conditionals. */
5084
5085 /* Calling programs set this to have their argv[0]. */
5086 char *rl_readline_name = "other";
5087
5088 /* Stack of previous values of parsing_conditionalized_out. */
5089 static unsigned char *if_stack = (unsigned char *)NULL;
5090 static int if_stack_depth = 0;
5091 static int if_stack_size = 0;
5092
5093 /* Push parsing_conditionalized_out, and set parser state based on ARGS. */
5094 parser_if (args)
5095      char *args;
5096 {
5097   register int i;
5098
5099   /* Push parser state. */
5100   if (if_stack_depth + 1 >= if_stack_size)
5101     {
5102       if (!if_stack)
5103         if_stack = (unsigned char *)xmalloc (if_stack_size = 20);
5104       else
5105         if_stack = (unsigned char *)xrealloc (if_stack, if_stack_size += 20);
5106     }
5107   if_stack[if_stack_depth++] = parsing_conditionalized_out;
5108
5109   /* We only check to see if the first word in ARGS is the same as the
5110      value stored in rl_readline_name. */
5111
5112   /* Isolate first argument. */
5113   for (i = 0; args[i] && !whitespace (args[i]); i++);
5114
5115   if (args[i])
5116     args[i++] = '\0';
5117
5118   if (stricmp (args, rl_readline_name) == 0)
5119     parsing_conditionalized_out = 0;
5120   else
5121     parsing_conditionalized_out = 1;
5122 }
5123
5124 /* Invert the current parser state if there is anything on the stack. */
5125 parser_else (args)
5126      char *args;
5127 {
5128   if (if_stack_depth)
5129     parsing_conditionalized_out = !parsing_conditionalized_out;
5130   else
5131     {
5132       /* *** What, no error message? *** */
5133     }
5134 }
5135
5136 /* Terminate a conditional, popping the value of
5137    parsing_conditionalized_out from the stack. */
5138 parser_endif (args)
5139      char *args;
5140 {
5141   if (if_stack_depth)
5142     parsing_conditionalized_out = if_stack[--if_stack_depth];
5143   else
5144     {
5145       /* *** What, no error message? *** */
5146     }
5147 }
5148
5149 /* Associate textual names with actual functions. */
5150 static struct {
5151   char *name;
5152   Function *function;
5153 } parser_directives [] = {
5154   { "if", parser_if },
5155   { "endif", parser_endif },
5156   { "else", parser_else },
5157   { (char *)0x0, (Function *)0x0 }
5158 };
5159
5160 /* Handle a parser directive.  STATEMENT is the line of the directive
5161    without any leading `$'. */
5162 static int
5163 handle_parser_directive (statement)
5164      char *statement;
5165 {
5166   register int i;
5167   char *directive, *args;
5168
5169   /* Isolate the actual directive. */
5170
5171   /* Skip whitespace. */
5172   for (i = 0; whitespace (statement[i]); i++);
5173
5174   directive = &statement[i];
5175
5176   for (; statement[i] && !whitespace (statement[i]); i++);
5177
5178   if (statement[i])
5179     statement[i++] = '\0';
5180
5181   for (; statement[i] && whitespace (statement[i]); i++);
5182
5183   args = &statement[i];
5184
5185   /* Lookup the command, and act on it. */
5186   for (i = 0; parser_directives[i].name; i++)
5187     if (stricmp (directive, parser_directives[i].name) == 0)
5188       {
5189         (*parser_directives[i].function) (args);
5190         return (0);
5191       }
5192
5193   /* *** Should an error message be output? */
5194   return (1);
5195 }
5196
5197 /* Read the binding command from STRING and perform it.
5198    A key binding command looks like: Keyname: function-name\0,
5199    a variable binding command looks like: set variable value.
5200    A new-style keybinding looks like "\C-x\C-x": exchange-point-and-mark. */
5201 rl_parse_and_bind (string)
5202      char *string;
5203 {
5204   extern char *possible_control_prefixes[], *possible_meta_prefixes[];
5205   char *rindex (), *funname, *kname;
5206   static int substring_member_of_array ();
5207   register int c;
5208   int key, i;
5209
5210   if (!string || !*string || *string == '#')
5211     return;
5212
5213   /* If this is a parser directive, act on it. */
5214   if (*string == '$')
5215     {
5216       handle_parser_directive (&string[1]);
5217       return;
5218     }
5219
5220   /* If we are supposed to be skipping parsing right now, then do it. */
5221   if (parsing_conditionalized_out)
5222     return;
5223
5224   i = 0;
5225   /* If this keyname is a complex key expression surrounded by quotes,
5226      advance to after the matching close quote. */
5227   if (*string == '"')
5228     {
5229       for (i = 1; c = string[i]; i++)
5230         {
5231           if (c == '"' && string[i - 1] != '\\')
5232             break;
5233         }
5234     }
5235
5236   /* Advance to the colon (:) or whitespace which separates the two objects. */
5237   for (; (c = string[i]) && c != ':' && c != ' ' && c != '\t'; i++ );
5238
5239   /* Mark the end of the command (or keyname). */
5240   if (string[i])
5241     string[i++] = '\0';
5242
5243   /* If this is a command to set a variable, then do that. */
5244   if (stricmp (string, "set") == 0)
5245     {
5246       char *var = string + i;
5247       char *value;
5248
5249       /* Make VAR point to start of variable name. */
5250       while (*var && whitespace (*var)) var++;
5251
5252       /* Make value point to start of value string. */
5253       value = var;
5254       while (*value && !whitespace (*value)) value++;
5255       if (*value)
5256         *value++ = '\0';
5257       while (*value && whitespace (*value)) value++;
5258
5259       rl_variable_bind (var, value);
5260       return;
5261     }
5262
5263   /* Skip any whitespace between keyname and funname. */
5264   for (; string[i] && whitespace (string[i]); i++);
5265   funname = &string[i];
5266
5267   /* Now isolate funname.
5268      For straight function names just look for whitespace, since
5269      that will signify the end of the string.  But this could be a
5270      macro definition.  In that case, the string is quoted, so skip
5271      to the matching delimiter. */
5272   if (*funname == '\'' || *funname == '"')
5273     {
5274       int delimiter = string[i++];
5275
5276       for (; c = string[i]; i++)
5277         {
5278           if (c == delimiter && string[i - 1] != '\\')
5279             break;
5280         }
5281       if (c)
5282         i++;
5283     }
5284
5285   /* Advance to the end of the string.  */
5286   for (; string[i] && !whitespace (string[i]); i++);
5287
5288   /* No extra whitespace at the end of the string. */
5289   string[i] = '\0';
5290
5291   /* If this is a new-style key-binding, then do the binding with
5292      rl_set_key ().  Otherwise, let the older code deal with it. */
5293   if (*string == '"')
5294     {
5295       char *seq = (char *)alloca (1 + strlen (string));
5296       register int j, k = 0;
5297
5298       for (j = 1; string[j]; j++)
5299         {
5300           if (string[j] == '"' && string[j - 1] != '\\')
5301             break;
5302
5303           seq[k++] = string[j];
5304         }
5305       seq[k] = '\0';
5306
5307       /* Binding macro? */
5308       if (*funname == '\'' || *funname == '"')
5309         {
5310           j = strlen (funname);
5311
5312           if (j && funname[j - 1] == *funname)
5313             funname[j - 1] = '\0';
5314
5315           rl_macro_bind (seq, &funname[1], keymap);
5316         }
5317       else
5318         rl_set_key (seq, rl_named_function (funname), keymap);
5319
5320       return;
5321     }
5322
5323   /* Get the actual character we want to deal with. */
5324   kname = rindex (string, '-');
5325   if (!kname)
5326     kname = string;
5327   else
5328     kname++;
5329
5330   key = glean_key_from_name (kname);
5331
5332   /* Add in control and meta bits. */
5333   if (substring_member_of_array (string, possible_control_prefixes))
5334     key = CTRL (to_upper (key));
5335
5336   if (substring_member_of_array (string, possible_meta_prefixes))
5337     key = META (key);
5338
5339   /* Temporary.  Handle old-style keyname with macro-binding. */
5340   if (*funname == '\'' || *funname == '"')
5341     {
5342       char seq[2];
5343       int fl = strlen (funname);
5344
5345       seq[0] = key; seq[1] = '\0';
5346       if (fl && funname[fl - 1] == *funname)
5347         funname[fl - 1] = '\0';
5348
5349       rl_macro_bind (seq, &funname[1], keymap);
5350     }
5351   else
5352     rl_bind_key (key, rl_named_function (funname));
5353 }
5354
5355 rl_variable_bind (name, value)
5356      char *name, *value;
5357 {
5358   if (stricmp (name, "editing-mode") == 0)
5359     {
5360       if (strnicmp (value, "vi", 2) == 0)
5361         {
5362 #ifdef VI_MODE
5363           keymap = vi_insertion_keymap;
5364           rl_editing_mode = vi_mode;
5365 #endif /* VI_MODE */
5366         }
5367       else if (strnicmp (value, "emacs", 5) == 0)
5368         {
5369           keymap = emacs_standard_keymap;
5370           rl_editing_mode = emacs_mode;
5371         }
5372     }
5373   else if (stricmp (name, "horizontal-scroll-mode") == 0)
5374     {
5375       if (!*value || stricmp (value, "On") == 0)
5376         horizontal_scroll_mode = 1;
5377       else
5378         horizontal_scroll_mode = 0;
5379     }
5380   else if (stricmp (name, "mark-modified-lines") == 0)
5381     {
5382       if (!*value || stricmp (value, "On") == 0)
5383         mark_modified_lines = 1;
5384       else
5385         mark_modified_lines = 0;
5386     }
5387 }
5388
5389 /* Return the character which matches NAME.
5390    For example, `Space' returns ' '. */
5391
5392 typedef struct {
5393   char *name;
5394   int value;
5395 } assoc_list;
5396
5397 assoc_list name_key_alist[] = {
5398   { "Space", ' ' },
5399   { "SPC", ' ' },
5400   { "Rubout", 0x7f },
5401   { "DEL", 0x7f },
5402   { "Tab", 0x09 },
5403   { "Newline", '\n' },
5404   { "Return", '\r' },
5405   { "RET", '\r' },
5406   { "LFD", '\n' },
5407   { "Escape", '\033' },
5408   { "ESC", '\033' },
5409
5410   { (char *)0x0, 0 }
5411 };
5412
5413 int
5414 glean_key_from_name (name)
5415      char *name;
5416 {
5417   register int i;
5418
5419   for (i = 0; name_key_alist[i].name; i++)
5420     if (stricmp (name, name_key_alist[i].name) == 0)
5421       return (name_key_alist[i].value);
5422
5423   return (*name);
5424 }
5425
5426 \f
5427 /* **************************************************************** */
5428 /*                                                                  */
5429 /*                      String Utility Functions                    */
5430 /*                                                                  */
5431 /* **************************************************************** */
5432
5433 /* Return non-zero if any members of ARRAY are a substring in STRING. */
5434 static int
5435 substring_member_of_array (string, array)
5436      char *string, **array;
5437 {
5438   static char *strindex ();
5439
5440   while (*array)
5441     {
5442       if (strindex (string, *array))
5443         return (1);
5444       array++;
5445     }
5446   return (0);
5447 }
5448
5449 /* Whoops, Unix doesn't have strnicmp. */
5450
5451 /* Compare at most COUNT characters from string1 to string2.  Case
5452    doesn't matter. */
5453 static int
5454 strnicmp (string1, string2, count)
5455      char *string1, *string2;
5456 {
5457   register char ch1, ch2;
5458
5459   while (count)
5460     {
5461       ch1 = *string1++;
5462       ch2 = *string2++;
5463       if (to_upper(ch1) == to_upper(ch2))
5464         count--;
5465       else break;
5466     }
5467   return (count);
5468 }
5469
5470 /* strcmp (), but caseless. */
5471 static int
5472 stricmp (string1, string2)
5473      char *string1, *string2;
5474 {
5475   register char ch1, ch2;
5476
5477   while (*string1 && *string2)
5478     {
5479       ch1 = *string1++;
5480       ch2 = *string2++;
5481       if (to_upper(ch1) != to_upper(ch2))
5482         return (1);
5483     }
5484   return (*string1 | *string2);
5485 }
5486
5487 /* Determine if s2 occurs in s1.  If so, return a pointer to the
5488    match in s1.  The compare is case insensitive. */
5489 static char *
5490 strindex (s1, s2)
5491      register char *s1, *s2;
5492 {
5493   register int i, l = strlen (s2);
5494   register int len = strlen (s1);
5495
5496   for (i = 0; (len - i) >= l; i++)
5497     if (strnicmp (&s1[i], s2, l) == 0)
5498       return (s1 + i);
5499   return ((char *)NULL);
5500 }
5501
5502 \f
5503 /* **************************************************************** */
5504 /*                                                                  */
5505 /*                      SYSV Support                                */
5506 /*                                                                  */
5507 /* **************************************************************** */
5508
5509 /* Since system V reads input differently than we do, I have to
5510    make a special version of getc for that. */
5511
5512 #ifdef SYSV
5513
5514 extern int errno;
5515 #include <sys/errno.h>
5516
5517 int
5518 rl_getc (stream)
5519      FILE *stream;
5520 {
5521   int result;
5522   unsigned char c;
5523
5524   while (1)
5525     {
5526       result = read (fileno (stream), &c, sizeof (char));
5527       if (result == sizeof (char))
5528         return (c);
5529
5530       if (errno != EINTR)
5531         return (EOF);
5532     }
5533 }
5534 #else
5535 int
5536 rl_getc (stream)
5537      FILE *stream;
5538 {
5539   return (getc (stream));
5540 }
5541 #endif
5542
5543 #ifdef STATIC_MALLOC
5544 \f
5545 /* **************************************************************** */
5546 /*                                                                  */
5547 /*                      xmalloc and xrealloc ()                     */
5548 /*                                                                  */
5549 /* **************************************************************** */
5550
5551 static void memory_error_and_abort ();
5552
5553 static char *
5554 xmalloc (bytes)
5555      int bytes;
5556 {
5557   char *temp = (char *)malloc (bytes);
5558
5559   if (!temp)
5560     memory_error_and_abort ();
5561   return (temp);
5562 }
5563
5564 static char *
5565 xrealloc (pointer, bytes)
5566      char *pointer;
5567      int bytes;
5568 {
5569   char *temp = (char *)realloc (pointer, bytes);
5570
5571   if (!temp)
5572     memory_error_and_abort ();
5573   return (temp);
5574 }
5575
5576 static void
5577 memory_error_and_abort ()
5578 {
5579   fprintf (stderr, "readline: Out of virtual memory!\n");
5580   abort ();
5581 }
5582 #endif /* STATIC_MALLOC */
5583
5584 \f
5585 /* **************************************************************** */
5586 /*                                                                  */
5587 /*                      Testing Readline                            */
5588 /*                                                                  */
5589 /* **************************************************************** */
5590
5591 #ifdef TEST
5592
5593 main ()
5594 {
5595   HIST_ENTRY **history_list ();
5596   char *temp = (char *)NULL;
5597   char *prompt = "readline% ";
5598   int done = 0;
5599
5600   while (!done)
5601     {
5602       temp = readline (prompt);
5603
5604       /* Test for EOF. */
5605       if (!temp)
5606         exit (1);
5607
5608       /* If there is anything on the line, print it and remember it. */
5609       if (*temp)
5610         {
5611           fprintf (stderr, "%s\r\n", temp);
5612           add_history (temp);
5613         }
5614
5615       /* Check for `command' that we handle. */
5616       if (strcmp (temp, "quit") == 0)
5617         done = 1;
5618
5619       if (strcmp (temp, "list") == 0) {
5620         HIST_ENTRY **list = history_list ();
5621         register int i;
5622         if (list) {
5623           for (i = 0; list[i]; i++) {
5624             fprintf (stderr, "%d: %s\r\n", i, list[i]->line);
5625             free (list[i]->line);
5626           }
5627           free (list);
5628         }
5629       }
5630       free (temp);
5631     }
5632 }
5633
5634 #endif /* TEST */
5635
5636 \f
5637 /*
5638  * Local variables:
5639  * compile-command: "gcc -g -traditional -I. -I.. -DTEST -o readline readline.c keymaps.o funmap.o history.o -ltermcap"
5640  * end:
5641  */