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