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