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