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