1 /* readline.c -- a general facility for reading lines of input
2    with emacs style editing and completion. */
3 
4 /* Copyright (C) 1987-2005 Free Software Foundation, Inc.
5 
6    This file is part of the GNU Readline Library, a library for
7    reading lines of text with interactive input and history editing.
8 
9    The GNU Readline Library is free software; you can redistribute it
10    and/or modify it under the terms of the GNU General Public License
11    as published by the Free Software Foundation; either version 2, or
12    (at your option) any later version.
13 
14    The GNU Readline Library is distributed in the hope that it will be
15    useful, but WITHOUT ANY WARRANTY; without even the implied warranty
16    of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17    GNU General Public License for more details.
18 
19    The GNU General Public License is often shipped with GNU software, and
20    is generally kept in a file called COPYING or LICENSE.  If you do not
21    have a copy of the license, write to the Free Software Foundation,
22    51 Franklin Street, Fifth Floor, Boston, MA  02110-1335  USA. */
23 #define READLINE_LIBRARY
24 
25 #if defined (HAVE_CONFIG_H)
26 #  include "config_readline.h"
27 #endif
28 
29 #include <sys/types.h>
30 #include "posixstat.h"
31 #include <fcntl.h>
32 #if defined (HAVE_SYS_FILE_H)
33 #  include <sys/file.h>
34 #endif /* HAVE_SYS_FILE_H */
35 
36 #if defined (HAVE_UNISTD_H)
37 #  include <unistd.h>
38 #endif /* HAVE_UNISTD_H */
39 
40 #if defined (HAVE_STDLIB_H)
41 #  include <stdlib.h>
42 #else
43 #  include "ansi_stdlib.h"
44 #endif /* HAVE_STDLIB_H */
45 
46 #if defined (HAVE_LOCALE_H)
47 #  include <locale.h>
48 #endif
49 
50 #include <stdio.h>
51 #include "posixjmp.h"
52 #include <errno.h>
53 
54 #if !defined (errno)
55 extern int errno;
56 #endif /* !errno */
57 
58 /* System-specific feature definitions and include files. */
59 #include "rldefs.h"
60 #include "rlmbutil.h"
61 
62 #if defined (__EMX__)
63 #  define INCL_DOSPROCESS
64 #  include <os2.h>
65 #endif /* __EMX__ */
66 
67 /* Some standard library routines. */
68 #include "readline.h"
69 #include "history.h"
70 
71 #include "rlprivate.h"
72 #include "rlshell.h"
73 #include "xmalloc.h"
74 
75 #ifndef RL_LIBRARY_VERSION
76 #  define RL_LIBRARY_VERSION "5.1"
77 #endif
78 
79 #ifndef RL_READLINE_VERSION
80 #  define RL_READLINE_VERSION	0x0501
81 #endif
82 
83 extern void _rl_free_history_entry PARAMS((HIST_ENTRY *));
84 
85 /* Forward declarations used in this file. */
86 static char *readline_internal PARAMS((void));
87 static void readline_initialize_everything PARAMS((void));
88 
89 static void bind_arrow_keys_internal PARAMS((Keymap));
90 static void bind_arrow_keys PARAMS((void));
91 
92 static void readline_default_bindings PARAMS((void));
93 
94 static int _rl_subseq_result PARAMS((int, Keymap, int, int));
95 static int _rl_subseq_getchar PARAMS((int));
96 
97 /* **************************************************************** */
98 /*								    */
99 /*			Line editing input utility		    */
100 /*								    */
101 /* **************************************************************** */
102 
103 const char *rl_library_version = RL_LIBRARY_VERSION;
104 
105 int rl_readline_version = RL_READLINE_VERSION;
106 
107 /* True if this is `real' readline as opposed to some stub substitute. */
108 int rl_gnu_readline_p = 1;
109 
110 /* A pointer to the keymap that is currently in use.
111    By default, it is the standard emacs keymap. */
112 Keymap _rl_keymap = emacs_standard_keymap;
113 
114 
115 /* The current style of editing. */
116 int rl_editing_mode = emacs_mode;
117 
118 /* The current insert mode:  input (the default) or overwrite */
119 int rl_insert_mode = RL_IM_DEFAULT;
120 
121 /* Non-zero if we called this function from _rl_dispatch().  It's present
122    so functions can find out whether they were called from a key binding
123    or directly from an application. */
124 int rl_dispatching;
125 
126 /* Non-zero if the previous command was a kill command. */
127 int _rl_last_command_was_kill = 0;
128 
129 /* The current value of the numeric argument specified by the user. */
130 int rl_numeric_arg = 1;
131 
132 /* Non-zero if an argument was typed. */
133 int rl_explicit_arg = 0;
134 
135 /* Temporary value used while generating the argument. */
136 int rl_arg_sign = 1;
137 
138 /* Non-zero means we have been called at least once before. */
139 static int rl_initialized;
140 
141 #if 0
142 /* If non-zero, this program is running in an EMACS buffer. */
143 static int running_in_emacs;
144 #endif
145 
146 /* Flags word encapsulating the current readline state. */
147 int rl_readline_state = RL_STATE_NONE;
148 
149 /* The current offset in the current input line. */
150 int rl_point;
151 
152 /* Mark in the current input line. */
153 int rl_mark;
154 
155 /* Length of the current input line. */
156 int rl_end;
157 
158 /* Make this non-zero to return the current input_line. */
159 int rl_done;
160 
161 /* The last function executed by readline. */
162 rl_command_func_t *rl_last_func = (rl_command_func_t *)NULL;
163 
164 /* Top level environment for readline_internal (). */
165 procenv_t readline_top_level;
166 
167 /* The streams we interact with. */
168 FILE *_rl_in_stream, *_rl_out_stream;
169 
170 /* The names of the streams that we do input and output to. */
171 FILE *rl_instream = (FILE *)NULL;
172 FILE *rl_outstream = (FILE *)NULL;
173 
174 /* Non-zero means echo characters as they are read.  Defaults to no echo;
175    set to 1 if there is a controlling terminal, we can get its attributes,
176    and the attributes include `echo'.  Look at rltty.c:prepare_terminal_settings
177    for the code that sets it. */
178 int readline_echoing_p = 0;
179 
180 /* Current prompt. */
181 char *rl_prompt = (char *)NULL;
182 int rl_visible_prompt_length = 0;
183 
184 /* Set to non-zero by calling application if it has already printed rl_prompt
185    and does not want readline to do it the first time. */
186 int rl_already_prompted = 0;
187 
188 /* The number of characters read in order to type this complete command. */
189 int rl_key_sequence_length = 0;
190 
191 /* If non-zero, then this is the address of a function to call just
192    before readline_internal_setup () prints the first prompt. */
193 rl_hook_func_t *rl_startup_hook = (rl_hook_func_t *)NULL;
194 
195 /* If non-zero, this is the address of a function to call just before
196    readline_internal_setup () returns and readline_internal starts
197    reading input characters. */
198 rl_hook_func_t *rl_pre_input_hook = (rl_hook_func_t *)NULL;
199 
200 /* What we use internally.  You should always refer to RL_LINE_BUFFER. */
201 static char *the_line;
202 
203 /* The character that can generate an EOF.  Really read from
204    the terminal driver... just defaulted here. */
205 int _rl_eof_char = CTRL ('D');
206 
207 /* Non-zero makes this the next keystroke to read. */
208 int rl_pending_input = 0;
209 
210 /* Pointer to a useful terminal name. */
211 const char *rl_terminal_name = (const char *)NULL;
212 
213 /* Non-zero means to always use horizontal scrolling in line display. */
214 int _rl_horizontal_scroll_mode = 0;
215 
216 /* Non-zero means to display an asterisk at the starts of history lines
217    which have been modified. */
218 int _rl_mark_modified_lines = 0;
219 
220 /* The style of `bell' notification preferred.  This can be set to NO_BELL,
221    AUDIBLE_BELL, or VISIBLE_BELL. */
222 int _rl_bell_preference = AUDIBLE_BELL;
223 
224 /* String inserted into the line by rl_insert_comment (). */
225 char *_rl_comment_begin;
226 
227 /* Keymap holding the function currently being executed. */
228 Keymap rl_executing_keymap;
229 
230 /* Keymap we're currently using to dispatch. */
231 Keymap _rl_dispatching_keymap;
232 
233 /* Non-zero means to erase entire line, including prompt, on empty input lines. */
234 int rl_erase_empty_line = 0;
235 
236 /* Non-zero means to read only this many characters rather than up to a
237    character bound to accept-line. */
238 int rl_num_chars_to_read;
239 
240 /* Line buffer and maintenence. */
241 char *rl_line_buffer = (char *)NULL;
242 int rl_line_buffer_len = 0;
243 
244 /* Key sequence `contexts' */
245 _rl_keyseq_cxt *_rl_kscxt = 0;
246 
247 /* Forward declarations used by the display, termcap, and history code. */
248 
249 /* **************************************************************** */
250 /*								    */
251 /*			`Forward' declarations  		    */
252 /*								    */
253 /* **************************************************************** */
254 
255 /* Non-zero means do not parse any lines other than comments and
256    parser directives. */
257 unsigned char _rl_parsing_conditionalized_out = 0;
258 
259 /* Non-zero means to convert characters with the meta bit set to
260    escape-prefixed characters so we can indirect through
261    emacs_meta_keymap or vi_escape_keymap. */
262 int _rl_convert_meta_chars_to_ascii = 1;
263 
264 /* Non-zero means to output characters with the meta bit set directly
265    rather than as a meta-prefixed escape sequence. */
266 int _rl_output_meta_chars = 0;
267 
268 /* Non-zero means to look at the termios special characters and bind
269    them to equivalent readline functions at startup. */
270 int _rl_bind_stty_chars = 1;
271 
272 /* **************************************************************** */
273 /*								    */
274 /*			Top Level Functions			    */
275 /*								    */
276 /* **************************************************************** */
277 
278 /* Non-zero means treat 0200 bit in terminal input as Meta bit. */
279 int _rl_meta_flag = 0;	/* Forward declaration */
280 
281 /* Set up the prompt and expand it.  Called from readline() and
282    rl_callback_handler_install (). */
283 int
284 rl_set_prompt (prompt)
285      const char *prompt;
286 {
287   FREE (rl_prompt);
288   rl_prompt = prompt ? savestring (prompt) : (char *)NULL;
289   rl_display_prompt = rl_prompt ? rl_prompt : (char*) "";
290 
291   rl_visible_prompt_length = rl_expand_prompt (rl_prompt);
292   return 0;
293 }
294 
295 /* Read a line of input.  Prompt with PROMPT.  An empty PROMPT means
296    none.  A return value of NULL means that EOF was encountered. */
297 char *
298 readline (prompt)
299      const char *prompt;
300 {
301   char *value;
302 
303   /* If we are at EOF return a NULL string. */
304   if (rl_pending_input == EOF)
305     {
306       rl_clear_pending_input ();
307       return ((char *)NULL);
308     }
309 
310   rl_set_prompt (prompt);
311 
312   rl_initialize ();
313   if (rl_prep_term_function)
314     (*rl_prep_term_function) (_rl_meta_flag);
315 
316 #if defined (HANDLE_SIGNALS)
317   rl_set_signals ();
318 #endif
319 
320   value = readline_internal ();
321   if (rl_deprep_term_function)
322     (*rl_deprep_term_function) ();
323 
324 #if defined (HANDLE_SIGNALS)
325   rl_clear_signals ();
326 #endif
327 
328   return (value);
329 }
330 
331 #if defined (READLINE_CALLBACKS)
332 #  define STATIC_CALLBACK
333 #else
334 #  define STATIC_CALLBACK static
335 #endif
336 
337 STATIC_CALLBACK void
338 readline_internal_setup ()
339 {
340   char *nprompt;
341 
342   _rl_in_stream = rl_instream;
343   _rl_out_stream = rl_outstream;
344 
345   if (rl_startup_hook)
346     (*rl_startup_hook) ();
347 
348   /* If we're not echoing, we still want to at least print a prompt, because
349      rl_redisplay will not do it for us.  If the calling application has a
350      custom redisplay function, though, let that function handle it. */
351   if (readline_echoing_p == 0 && rl_redisplay_function == rl_redisplay)
352     {
353       if (rl_prompt && rl_already_prompted == 0)
354 	{
355 	  nprompt = _rl_strip_prompt (rl_prompt);
356 	  fprintf (_rl_out_stream, "%s", nprompt);
357 	  fflush (_rl_out_stream);
358 	  free (nprompt);
359 	}
360     }
361   else
362     {
363       if (rl_prompt && rl_already_prompted)
364 	rl_on_new_line_with_prompt ();
365       else
366 	rl_on_new_line ();
367       (*rl_redisplay_function) ();
368     }
369 
370 #if defined (VI_MODE)
371   if (rl_editing_mode == vi_mode)
372     rl_vi_insertion_mode (1, 'i');
373 #endif /* VI_MODE */
374 
375   if (rl_pre_input_hook)
376     (*rl_pre_input_hook) ();
377 }
378 
379 STATIC_CALLBACK char *
380 readline_internal_teardown (eof)
381      int eof;
382 {
383   char *temp;
384   HIST_ENTRY *entry;
385 
386   /* Restore the original of this history line, iff the line that we
387      are editing was originally in the history, AND the line has changed. */
388   entry = current_history ();
389 
390   if (entry && rl_undo_list)
391     {
392       temp = savestring (the_line);
393       rl_revert_line (1, 0);
394       entry = replace_history_entry (where_history (), the_line, (histdata_t)NULL);
395       _rl_free_history_entry (entry);
396 
397       strcpy (the_line, temp);
398       free (temp);
399     }
400 
401   /* At any rate, it is highly likely that this line has an undo list.  Get
402      rid of it now. */
403   if (rl_undo_list)
404     rl_free_undo_list ();
405 
406   /* Restore normal cursor, if available. */
407   _rl_set_insert_mode (RL_IM_INSERT, 0);
408 
409   return (eof ? (char *)NULL : savestring (the_line));
410 }
411 
412 void
413 _rl_internal_char_cleanup ()
414 {
415 #if defined (VI_MODE)
416   /* In vi mode, when you exit insert mode, the cursor moves back
417      over the previous character.  We explicitly check for that here. */
418   if (rl_editing_mode == vi_mode && _rl_keymap == vi_movement_keymap)
419     rl_vi_check ();
420 #endif /* VI_MODE */
421 
422   if (rl_num_chars_to_read && rl_end >= rl_num_chars_to_read)
423     {
424       (*rl_redisplay_function) ();
425       _rl_want_redisplay = 0;
426       rl_newline (1, '\n');
427     }
428 
429   if (rl_done == 0)
430     {
431       (*rl_redisplay_function) ();
432       _rl_want_redisplay = 0;
433     }
434 
435   /* If the application writer has told us to erase the entire line if
436      the only character typed was something bound to rl_newline, do so. */
437   if (rl_erase_empty_line && rl_done && rl_last_func == rl_newline &&
438       rl_point == 0 && rl_end == 0)
439     _rl_erase_entire_line ();
440 }
441 
442 STATIC_CALLBACK int
443 #if defined (READLINE_CALLBACKS)
444 readline_internal_char ()
445 #else
446 readline_internal_charloop ()
447 #endif
448 {
449   static int lastc;
450   int c, code, lk;
451 
452   lastc = -1;
453 
454 #if !defined (READLINE_CALLBACKS)
455   while (rl_done == 0)
456     {
457 #endif
458       lk = _rl_last_command_was_kill;
459 
460       code = setjmp (readline_top_level);
461 
462       if (code)
463 	{
464 	  (*rl_redisplay_function) ();
465 	  _rl_want_redisplay = 0;
466 	  /* If we get here, we're not being called from something dispatched
467 	     from _rl_callback_read_char(), which sets up its own value of
468 	     readline_top_level (saving and restoring the old, of course), so
469 	     we can just return here. */
470 	  if (RL_ISSTATE (RL_STATE_CALLBACK))
471 	    return (0);
472 	}
473 
474       if (rl_pending_input == 0)
475 	{
476 	  /* Then initialize the argument and number of keys read. */
477 	  _rl_reset_argument ();
478 	  rl_key_sequence_length = 0;
479 	}
480 
481       RL_SETSTATE(RL_STATE_READCMD);
482       c = rl_read_key ();
483       RL_UNSETSTATE(RL_STATE_READCMD);
484 
485       /* look at input.c:rl_getc() for the circumstances under which this will
486 	 be returned; punt immediately on read error without converting it to
487 	 a newline. */
488       if (c == READERR)
489 	{
490 #if defined (READLINE_CALLBACKS)
491 	  RL_SETSTATE(RL_STATE_DONE);
492 	  return (rl_done = 1);
493 #else
494 	  eof_found = 1;
495 	  break;
496 #endif
497 	}
498 
499       /* EOF typed to a non-blank line is a <NL>. */
500       if (c == EOF && rl_end)
501 	c = NEWLINE;
502 
503       /* The character _rl_eof_char typed to blank line, and not as the
504 	 previous character is interpreted as EOF. */
505       if (((c == _rl_eof_char && lastc != c) || c == EOF) && !rl_end)
506 	{
507 #if defined (READLINE_CALLBACKS)
508 	  RL_SETSTATE(RL_STATE_DONE);
509 	  return (rl_done = 1);
510 #else
511 	  eof_found = 1;
512 	  break;
513 #endif
514 	}
515 
516       lastc = c;
517       _rl_dispatch ((unsigned char)c, _rl_keymap);
518 
519       /* If there was no change in _rl_last_command_was_kill, then no kill
520 	 has taken place.  Note that if input is pending we are reading
521 	 a prefix command, so nothing has changed yet. */
522       if (rl_pending_input == 0 && lk == _rl_last_command_was_kill)
523 	_rl_last_command_was_kill = 0;
524 
525       _rl_internal_char_cleanup ();
526 
527 #if defined (READLINE_CALLBACKS)
528       return 0;
529 #else
530     }
531 
532   return (eof_found);
533 #endif
534 }
535 
536 #if defined (READLINE_CALLBACKS)
537 static int
538 readline_internal_charloop ()
539 {
540   int eof = 1;
541 
542   while (rl_done == 0)
543     eof = readline_internal_char ();
544   return (eof);
545 }
546 #endif /* READLINE_CALLBACKS */
547 
548 /* Read a line of input from the global rl_instream, doing output on
549    the global rl_outstream.
550    If rl_prompt is non-null, then that is our prompt. */
551 static char *
552 readline_internal ()
553 {
554   int eof;
555 
556   readline_internal_setup ();
557   eof = readline_internal_charloop ();
558   return (readline_internal_teardown (eof));
559 }
560 
561 void
562 _rl_init_line_state ()
563 {
564   rl_point = rl_end = rl_mark = 0;
565   the_line = rl_line_buffer;
566   the_line[0] = 0;
567 }
568 
569 void
570 _rl_set_the_line ()
571 {
572   the_line = rl_line_buffer;
573 }
574 
575 #if defined (READLINE_CALLBACKS)
576 _rl_keyseq_cxt *
577 _rl_keyseq_cxt_alloc ()
578 {
579   _rl_keyseq_cxt *cxt;
580 
581   cxt = (_rl_keyseq_cxt *)xmalloc (sizeof (_rl_keyseq_cxt));
582 
583   cxt->flags = cxt->subseq_arg = cxt->subseq_retval = 0;
584 
585   cxt->okey = 0;
586   cxt->ocxt = _rl_kscxt;
587   cxt->childval = 42;		/* sentinel value */
588 
589   return cxt;
590 }
591 
592 void
593 _rl_keyseq_cxt_dispose (cxt)
594     _rl_keyseq_cxt *cxt;
595 {
596   free (cxt);
597 }
598 
599 void
600 _rl_keyseq_chain_dispose ()
601 {
602   _rl_keyseq_cxt *cxt;
603 
604   while (_rl_kscxt)
605     {
606       cxt = _rl_kscxt;
607       _rl_kscxt = _rl_kscxt->ocxt;
608       _rl_keyseq_cxt_dispose (cxt);
609     }
610 }
611 #endif
612 
613 static int
614 _rl_subseq_getchar (key)
615      int key;
616 {
617   int k;
618 
619   if (key == ESC)
620     RL_SETSTATE(RL_STATE_METANEXT);
621   RL_SETSTATE(RL_STATE_MOREINPUT);
622   k = rl_read_key ();
623   RL_UNSETSTATE(RL_STATE_MOREINPUT);
624   if (key == ESC)
625     RL_UNSETSTATE(RL_STATE_METANEXT);
626 
627   return k;
628 }
629 
630 #if defined (READLINE_CALLBACKS)
631 int
632 _rl_dispatch_callback (cxt)
633      _rl_keyseq_cxt *cxt;
634 {
635   int nkey, r;
636 
637   /* For now */
638 #if 1
639   /* The first time this context is used, we want to read input and dispatch
640      on it.  When traversing the chain of contexts back `up', we want to use
641      the value from the next context down.  We're simulating recursion using
642      a chain of contexts. */
643   if ((cxt->flags & KSEQ_DISPATCHED) == 0)
644     {
645       nkey = _rl_subseq_getchar (cxt->okey);
646       r = _rl_dispatch_subseq (nkey, cxt->dmap, cxt->subseq_arg);
647       cxt->flags |= KSEQ_DISPATCHED;
648     }
649   else
650     r = cxt->childval;
651 #else
652   r = _rl_dispatch_subseq (nkey, cxt->dmap, cxt->subseq_arg);
653 #endif
654 
655   /* For now */
656   r = _rl_subseq_result (r, cxt->oldmap, cxt->okey, (cxt->flags & KSEQ_SUBSEQ));
657 
658   if (r == 0)			/* success! */
659     {
660       _rl_keyseq_chain_dispose ();
661       RL_UNSETSTATE (RL_STATE_MULTIKEY);
662       return r;
663     }
664 
665   if (r != -3)			/* magic value that says we added to the chain */
666     _rl_kscxt = cxt->ocxt;
667   if (_rl_kscxt)
668     _rl_kscxt->childval = r;
669   if (r != -3)
670     _rl_keyseq_cxt_dispose (cxt);
671 
672   return r;
673 }
674 #endif /* READLINE_CALLBACKS */
675 
676 /* Do the command associated with KEY in MAP.
677    If the associated command is really a keymap, then read
678    another key, and dispatch into that map. */
679 int
680 _rl_dispatch (key, map)
681      register int key;
682      Keymap map;
683 {
684   _rl_dispatching_keymap = map;
685   return _rl_dispatch_subseq (key, map, 0);
686 }
687 
688 int
689 _rl_dispatch_subseq (key, map, got_subseq)
690      register int key;
691      Keymap map;
692      int got_subseq;
693 {
694   int r, newkey;
695   char *macro;
696   rl_command_func_t *func;
697 #if defined (READLINE_CALLBACKS)
698   _rl_keyseq_cxt *cxt;
699 #endif
700 
701   if (META_CHAR (key) && _rl_convert_meta_chars_to_ascii)
702     {
703       if (map[ESC].type == ISKMAP)
704 	{
705 	  if (RL_ISSTATE (RL_STATE_MACRODEF))
706 	    _rl_add_macro_char (ESC);
707 	  map = FUNCTION_TO_KEYMAP (map, ESC);
708 	  key = UNMETA (key);
709 	  rl_key_sequence_length += 2;
710 	  return (_rl_dispatch (key, map));
711 	}
712       else
713 	rl_ding ();
714       return 0;
715     }
716 
717   if (RL_ISSTATE (RL_STATE_MACRODEF))
718     _rl_add_macro_char (key);
719 
720   r = 0;
721   switch (map[key].type)
722     {
723     case ISFUNC:
724       func = map[key].function;
725       if (func)
726 	{
727 	  /* Special case rl_do_lowercase_version (). */
728 	  if (func == rl_do_lowercase_version)
729 	    return (_rl_dispatch (_rl_to_lower (key), map));
730 
731 	  rl_executing_keymap = map;
732 
733 	  rl_dispatching = 1;
734 	  RL_SETSTATE(RL_STATE_DISPATCHING);
735 	  (*map[key].function)(rl_numeric_arg * rl_arg_sign, key);
736 	  RL_UNSETSTATE(RL_STATE_DISPATCHING);
737 	  rl_dispatching = 0;
738 
739 	  /* If we have input pending, then the last command was a prefix
740 	     command.  Don't change the state of rl_last_func.  Otherwise,
741 	     remember the last command executed in this variable. */
742 	  if (rl_pending_input == 0 && map[key].function != rl_digit_argument)
743 	    rl_last_func = map[key].function;
744 	}
745       else if (map[ANYOTHERKEY].function)
746 	{
747 	  /* OK, there's no function bound in this map, but there is a
748 	     shadow function that was overridden when the current keymap
749 	     was created.  Return -2 to note  that. */
750 	  _rl_unget_char  (key);
751 	  return -2;
752 	}
753       else if (got_subseq)
754 	{
755 	  /* Return -1 to note that we're in a subsequence, but  we don't
756 	     have a matching key, nor was one overridden.  This means
757 	     we need to back up the recursion chain and find the last
758 	     subsequence that is bound to a function. */
759 	  _rl_unget_char (key);
760 	  return -1;
761 	}
762       else
763 	{
764 #if defined (READLINE_CALLBACKS)
765 	  RL_UNSETSTATE (RL_STATE_MULTIKEY);
766 	  _rl_keyseq_chain_dispose ();
767 #endif
768 	  _rl_abort_internal ();
769 	  return -1;
770 	}
771       break;
772 
773     case ISKMAP:
774       if (map[key].function != 0)
775 	{
776 #if defined (VI_MODE)
777 	  /* The only way this test will be true is if a subsequence has been
778 	     bound starting with ESC, generally the arrow keys.  What we do is
779 	     check whether there's input in the queue, which there generally
780 	     will be if an arrow key has been pressed, and, if there's not,
781 	     just dispatch to (what we assume is) rl_vi_movement_mode right
782 	     away.  This is essentially an input test with a zero timeout. */
783 	  if (rl_editing_mode == vi_mode && key == ESC && map == vi_insertion_keymap
784 	      && _rl_input_queued (0) == 0)
785 	    return (_rl_dispatch (ANYOTHERKEY, FUNCTION_TO_KEYMAP (map, key)));
786 #endif
787 
788 	  rl_key_sequence_length++;
789 	  _rl_dispatching_keymap = FUNCTION_TO_KEYMAP (map, key);
790 
791 	  /* Allocate new context here.  Use linked contexts (linked through
792 	     cxt->ocxt) to simulate recursion */
793 #if defined (READLINE_CALLBACKS)
794 	  if (RL_ISSTATE (RL_STATE_CALLBACK))
795 	    {
796 	      /* Return 0 only the first time, to indicate success to
797 		 _rl_callback_read_char.  The rest of the time, we're called
798 		 from _rl_dispatch_callback, so we return 3 to indicate
799 		 special handling is necessary. */
800 	      r = RL_ISSTATE (RL_STATE_MULTIKEY) ? -3 : 0;
801 	      cxt = _rl_keyseq_cxt_alloc ();
802 
803 	      if (got_subseq)
804 		cxt->flags |= KSEQ_SUBSEQ;
805 	      cxt->okey = key;
806 	      cxt->oldmap = map;
807 	      cxt->dmap = _rl_dispatching_keymap;
808 	      cxt->subseq_arg = got_subseq || cxt->dmap[ANYOTHERKEY].function;
809 
810 	      RL_SETSTATE (RL_STATE_MULTIKEY);
811 	      _rl_kscxt = cxt;
812 
813 	      return r;		/* don't indicate immediate success */
814 	    }
815 #endif
816 
817 	  newkey = _rl_subseq_getchar (key);
818 	  if (newkey < 0)
819 	    {
820 	      _rl_abort_internal ();
821 	      return -1;
822 	    }
823 
824 	  r = _rl_dispatch_subseq (newkey, _rl_dispatching_keymap, got_subseq || map[ANYOTHERKEY].function);
825 	  return _rl_subseq_result (r, map, key, got_subseq);
826 	}
827       else
828 	{
829 	  _rl_abort_internal ();
830 	  return -1;
831 	}
832       break;
833 
834     case ISMACR:
835       if (map[key].function != 0)
836 	{
837 	  macro = savestring ((char *)map[key].function);
838 	  _rl_with_macro_input (macro);
839 	  return 0;
840 	}
841       break;
842     }
843 #if defined (VI_MODE)
844   if (rl_editing_mode == vi_mode && _rl_keymap == vi_movement_keymap &&
845       key != ANYOTHERKEY &&
846       _rl_vi_textmod_command (key))
847     _rl_vi_set_last (key, rl_numeric_arg, rl_arg_sign);
848 #endif
849 
850   return (r);
851 }
852 
853 static int
854 _rl_subseq_result (r, map, key, got_subseq)
855      int r;
856      Keymap map;
857      int key, got_subseq;
858 {
859   Keymap m;
860   int type, nt;
861   rl_command_func_t *func, *nf;
862 
863   if (r == -2)
864     /* We didn't match anything, and the keymap we're indexed into
865        shadowed a function previously bound to that prefix.  Call
866        the function.  The recursive call to _rl_dispatch_subseq has
867        already taken care of pushing any necessary input back onto
868        the input queue with _rl_unget_char. */
869     {
870       m = _rl_dispatching_keymap;
871       type = m[ANYOTHERKEY].type;
872       func = m[ANYOTHERKEY].function;
873       if (type == ISFUNC && func == rl_do_lowercase_version)
874 	r = _rl_dispatch (_rl_to_lower (key), map);
875       else if (type == ISFUNC && func == rl_insert)
876 	{
877 	  /* If the function that was shadowed was self-insert, we
878 	     somehow need a keymap with map[key].func == self-insert.
879 	     Let's use this one. */
880 	  nt = m[key].type;
881 	  nf = m[key].function;
882 
883 	  m[key].type = type;
884 	  m[key].function = func;
885 	  r = _rl_dispatch (key, m);
886 	  m[key].type = nt;
887 	  m[key].function = nf;
888 	}
889       else
890 	r = _rl_dispatch (ANYOTHERKEY, m);
891     }
892   else if (r && map[ANYOTHERKEY].function)
893     {
894       /* We didn't match (r is probably -1), so return something to
895 	 tell the caller that it should try ANYOTHERKEY for an
896 	 overridden function. */
897       _rl_unget_char (key);
898       _rl_dispatching_keymap = map;
899       return -2;
900     }
901   else if (r && got_subseq)
902     {
903       /* OK, back up the chain. */
904       _rl_unget_char (key);
905       _rl_dispatching_keymap = map;
906       return -1;
907     }
908 
909   return r;
910 }
911 
912 /* **************************************************************** */
913 /*								    */
914 /*			Initializations 			    */
915 /*								    */
916 /* **************************************************************** */
917 
918 /* Initialize readline (and terminal if not already). */
919 int
920 rl_initialize ()
921 {
922   /* If we have never been called before, initialize the
923      terminal and data structures. */
924   if (!rl_initialized)
925     {
926       RL_SETSTATE(RL_STATE_INITIALIZING);
927       readline_initialize_everything ();
928       RL_UNSETSTATE(RL_STATE_INITIALIZING);
929       rl_initialized++;
930       RL_SETSTATE(RL_STATE_INITIALIZED);
931     }
932 
933   /* Initalize the current line information. */
934   _rl_init_line_state ();
935 
936   /* We aren't done yet.  We haven't even gotten started yet! */
937   rl_done = 0;
938   RL_UNSETSTATE(RL_STATE_DONE);
939 
940   /* Tell the history routines what is going on. */
941   _rl_start_using_history ();
942 
943   /* Make the display buffer match the state of the line. */
944   rl_reset_line_state ();
945 
946   /* No such function typed yet. */
947   rl_last_func = (rl_command_func_t *)NULL;
948 
949   /* Parsing of key-bindings begins in an enabled state. */
950   _rl_parsing_conditionalized_out = 0;
951 
952 #if defined (VI_MODE)
953   if (rl_editing_mode == vi_mode)
954     _rl_vi_initialize_line ();
955 #endif
956 
957   /* Each line starts in insert mode (the default). */
958   _rl_set_insert_mode (RL_IM_DEFAULT, 1);
959 
960   return 0;
961 }
962 
963 #if 0
964 #if defined (__EMX__)
965 static void
966 _emx_build_environ ()
967 {
968   TIB *tibp;
969   PIB *pibp;
970   char *t, **tp;
971   int c;
972 
973   DosGetInfoBlocks (&tibp, &pibp);
974   t = pibp->pib_pchenv;
975   for (c = 1; *t; c++)
976     t += strlen (t) + 1;
977   tp = environ = (char **)xmalloc ((c + 1) * sizeof (char *));
978   t = pibp->pib_pchenv;
979   while (*t)
980     {
981       *tp++ = t;
982       t += strlen (t) + 1;
983     }
984   *tp = 0;
985 }
986 #endif /* __EMX__ */
987 #endif
988 
989 /* Initialize the entire state of the world. */
990 static void
991 readline_initialize_everything ()
992 {
993 #if 0
994 #if defined (__EMX__)
995   if (environ == 0)
996     _emx_build_environ ();
997 #endif
998 #endif
999 
1000 #if 0
1001   /* Find out if we are running in Emacs -- UNUSED. */
1002   running_in_emacs = sh_get_env_value ("EMACS") != (char *)0;
1003 #endif
1004 
1005   /* Set up input and output if they are not already set up. */
1006   if (!rl_instream)
1007     rl_instream = stdin;
1008 
1009   if (!rl_outstream)
1010     rl_outstream = stdout;
1011 
1012   /* Bind _rl_in_stream and _rl_out_stream immediately.  These values
1013      may change, but they may also be used before readline_internal ()
1014      is called. */
1015   _rl_in_stream = rl_instream;
1016   _rl_out_stream = rl_outstream;
1017 
1018   /* Allocate data structures. */
1019   if (rl_line_buffer == 0)
1020     rl_line_buffer = (char *)xmalloc (rl_line_buffer_len = DEFAULT_BUFFER_SIZE);
1021 
1022   /* Initialize the terminal interface. */
1023   if (rl_terminal_name == 0)
1024     rl_terminal_name = sh_get_env_value ("TERM");
1025   _rl_init_terminal_io (rl_terminal_name);
1026 
1027   /* Bind tty characters to readline functions. */
1028   readline_default_bindings ();
1029 
1030   /* Initialize the function names. */
1031   rl_initialize_funmap ();
1032 
1033   /* Decide whether we should automatically go into eight-bit mode. */
1034   _rl_init_eightbit ();
1035 
1036   /* Read in the init file. */
1037   rl_read_init_file ((char *)NULL);
1038 
1039   /* XXX */
1040   if (_rl_horizontal_scroll_mode && _rl_term_autowrap)
1041     {
1042       _rl_screenwidth--;
1043       _rl_screenchars -= _rl_screenheight;
1044     }
1045 
1046   /* Override the effect of any `set keymap' assignments in the
1047      inputrc file. */
1048   rl_set_keymap_from_edit_mode ();
1049 
1050   /* Try to bind a common arrow key prefix, if not already bound. */
1051   bind_arrow_keys ();
1052 
1053   /* Enable the meta key, if this terminal has one. */
1054   if (_rl_enable_meta)
1055     _rl_enable_meta_key ();
1056 
1057   /* If the completion parser's default word break characters haven't
1058      been set yet, then do so now. */
1059   if (rl_completer_word_break_characters == (char *)NULL)
1060     rl_completer_word_break_characters = (char *)rl_basic_word_break_characters;
1061 }
1062 
1063 /* If this system allows us to look at the values of the regular
1064    input editing characters, then bind them to their readline
1065    equivalents, iff the characters are not bound to keymaps. */
1066 static void
1067 readline_default_bindings ()
1068 {
1069   if (_rl_bind_stty_chars)
1070     rl_tty_set_default_bindings (_rl_keymap);
1071 }
1072 
1073 /* Bind some common arrow key sequences in MAP. */
1074 static void
1075 bind_arrow_keys_internal (map)
1076      Keymap map;
1077 {
1078   Keymap xkeymap;
1079 
1080   xkeymap = _rl_keymap;
1081   _rl_keymap = map;
1082 
1083 #if defined (__MSDOS__)
1084   rl_bind_keyseq_if_unbound ("\033[0A", rl_get_previous_history);
1085   rl_bind_keyseq_if_unbound ("\033[0B", rl_backward_char);
1086   rl_bind_keyseq_if_unbound ("\033[0C", rl_forward_char);
1087   rl_bind_keyseq_if_unbound ("\033[0D", rl_get_next_history);
1088 #endif
1089 
1090   rl_bind_keyseq_if_unbound ("\033[A", rl_get_previous_history);
1091   rl_bind_keyseq_if_unbound ("\033[B", rl_get_next_history);
1092   rl_bind_keyseq_if_unbound ("\033[C", rl_forward_char);
1093   rl_bind_keyseq_if_unbound ("\033[D", rl_backward_char);
1094   rl_bind_keyseq_if_unbound ("\033[H", rl_beg_of_line);
1095   rl_bind_keyseq_if_unbound ("\033[F", rl_end_of_line);
1096 
1097   rl_bind_keyseq_if_unbound ("\033OA", rl_get_previous_history);
1098   rl_bind_keyseq_if_unbound ("\033OB", rl_get_next_history);
1099   rl_bind_keyseq_if_unbound ("\033OC", rl_forward_char);
1100   rl_bind_keyseq_if_unbound ("\033OD", rl_backward_char);
1101   rl_bind_keyseq_if_unbound ("\033OH", rl_beg_of_line);
1102   rl_bind_keyseq_if_unbound ("\033OF", rl_end_of_line);
1103 
1104 #if defined (__MINGW32__)
1105   rl_bind_keyseq_if_unbound ("\340H", rl_get_previous_history);
1106   rl_bind_keyseq_if_unbound ("\340P", rl_get_next_history);
1107   rl_bind_keyseq_if_unbound ("\340M", rl_forward_char);
1108   rl_bind_keyseq_if_unbound ("\340K", rl_backward_char);
1109 #endif
1110 
1111   _rl_keymap = xkeymap;
1112 }
1113 
1114 /* Try and bind the common arrow key prefixes after giving termcap and
1115    the inputrc file a chance to bind them and create `real' keymaps
1116    for the arrow key prefix. */
1117 static void
1118 bind_arrow_keys ()
1119 {
1120   bind_arrow_keys_internal (emacs_standard_keymap);
1121 
1122 #if defined (VI_MODE)
1123   bind_arrow_keys_internal (vi_movement_keymap);
1124   bind_arrow_keys_internal (vi_insertion_keymap);
1125 #endif
1126 }
1127 
1128 /* **************************************************************** */
1129 /*								    */
1130 /*		Saving and Restoring Readline's state		    */
1131 /*								    */
1132 /* **************************************************************** */
1133 
1134 int
1135 rl_save_state (sp)
1136      struct readline_state *sp;
1137 {
1138   if (sp == 0)
1139     return -1;
1140 
1141   sp->point = rl_point;
1142   sp->end = rl_end;
1143   sp->mark = rl_mark;
1144   sp->buffer = rl_line_buffer;
1145   sp->buflen = rl_line_buffer_len;
1146   sp->ul = rl_undo_list;
1147   sp->prompt = rl_prompt;
1148 
1149   sp->rlstate = rl_readline_state;
1150   sp->done = rl_done;
1151   sp->kmap = _rl_keymap;
1152 
1153   sp->lastfunc = rl_last_func;
1154   sp->insmode = rl_insert_mode;
1155   sp->edmode = rl_editing_mode;
1156   sp->kseqlen = rl_key_sequence_length;
1157   sp->inf = rl_instream;
1158   sp->outf = rl_outstream;
1159   sp->pendingin = rl_pending_input;
1160   sp->macro = rl_executing_macro;
1161 
1162   sp->catchsigs = rl_catch_signals;
1163   sp->catchsigwinch = rl_catch_sigwinch;
1164 
1165   return (0);
1166 }
1167 
1168 int
1169 rl_restore_state (sp)
1170      struct readline_state *sp;
1171 {
1172   if (sp == 0)
1173     return -1;
1174 
1175   rl_point = sp->point;
1176   rl_end = sp->end;
1177   rl_mark = sp->mark;
1178   the_line = rl_line_buffer = sp->buffer;
1179   rl_line_buffer_len = sp->buflen;
1180   rl_undo_list = sp->ul;
1181   rl_prompt = sp->prompt;
1182 
1183   rl_readline_state = sp->rlstate;
1184   rl_done = sp->done;
1185   _rl_keymap = sp->kmap;
1186 
1187   rl_last_func = sp->lastfunc;
1188   rl_insert_mode = sp->insmode;
1189   rl_editing_mode = sp->edmode;
1190   rl_key_sequence_length = sp->kseqlen;
1191   rl_instream = sp->inf;
1192   rl_outstream = sp->outf;
1193   rl_pending_input = sp->pendingin;
1194   rl_executing_macro = sp->macro;
1195 
1196   rl_catch_signals = sp->catchsigs;
1197   rl_catch_sigwinch = sp->catchsigwinch;
1198 
1199   return (0);
1200 }
1201