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