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