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