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