Remove empty line to silence troff warning.
[dragonfly.git] / lib / libedit / readline.c
1 /*-
2  * Copyright (c) 1997 The NetBSD Foundation, Inc.
3  * All rights reserved.
4  *
5  * This code is derived from software contributed to The NetBSD Foundation
6  * by Jaromir Dolecek.
7  *
8  * Redistribution and use in source and binary forms, with or without
9  * modification, are permitted provided that the following conditions
10  * are met:
11  * 1. Redistributions of source code must retain the above copyright
12  *    notice, this list of conditions and the following disclaimer.
13  * 2. Redistributions in binary form must reproduce the above copyright
14  *    notice, this list of conditions and the following disclaimer in the
15  *    documentation and/or other materials provided with the distribution.
16  * 3. All advertising materials mentioning features or use of this software
17  *    must display the following acknowledgement:
18  *      This product includes software developed by the NetBSD
19  *      Foundation, Inc. and its contributors.
20  * 4. Neither the name of The NetBSD Foundation nor the names of its
21  *    contributors may be used to endorse or promote products derived
22  *    from this software without specific prior written permission.
23  *
24  * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
25  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
26  * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
27  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
28  * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
29  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
30  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
31  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
32  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
33  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
34  * POSSIBILITY OF SUCH DAMAGE.
35  *
36  * $NetBSD: readline.c,v 1.57 2005/06/11 18:18:59 christos Exp $
37  * $DragonFly: src/lib/libedit/readline.c,v 1.1 2005/11/13 11:58:30 corecode Exp $
38  */
39
40 #include "config.h"
41
42 #include <sys/types.h>
43 #include <sys/stat.h>
44 #include <stdio.h>
45 #include <dirent.h>
46 #include <string.h>
47 #include <pwd.h>
48 #include <ctype.h>
49 #include <stdlib.h>
50 #include <unistd.h>
51 #include <limits.h>
52 #include <errno.h>
53 #include <fcntl.h>
54 #ifdef HAVE_VIS_H
55 #include <vis.h>
56 #else
57 #include "np/vis.h"
58 #endif
59 #ifdef HAVE_ALLOCA_H
60 #include <alloca.h>
61 #endif
62 #include "el.h"
63 #include "fcns.h"               /* for EL_NUM_FCNS */
64 #include "histedit.h"
65 #include "readline/readline.h"
66 #include "filecomplete.h"
67
68 /* for rl_complete() */
69 #define TAB             '\r'
70
71 /* see comment at the #ifdef for sense of this */
72 /* #define GDB_411_HACK */
73
74 /* readline compatibility stuff - look at readline sources/documentation */
75 /* to see what these variables mean */
76 const char *rl_library_version = "EditLine wrapper";
77 static char empty[] = { '\0' };
78 static char expand_chars[] = { ' ', '\t', '\n', '=', '(', '\0' };
79 static char break_chars[] = { ' ', '\t', '\n', '"', '\\', '\'', '`', '@', '$',
80     '>', '<', '=', ';', '|', '&', '{', '(', '\0' };
81 char *rl_readline_name = empty;
82 FILE *rl_instream = NULL;
83 FILE *rl_outstream = NULL;
84 int rl_point = 0;
85 int rl_end = 0;
86 char *rl_line_buffer = NULL;
87 VCPFunction *rl_linefunc = NULL;
88 int rl_done = 0;
89 VFunction *rl_event_hook = NULL;
90
91 int history_base = 1;           /* probably never subject to change */
92 int history_length = 0;
93 int max_input_history = 0;
94 char history_expansion_char = '!';
95 char history_subst_char = '^';
96 char *history_no_expand_chars = expand_chars;
97 Function *history_inhibit_expansion_function = NULL;
98 char *history_arg_extract(int start, int end, const char *str);
99
100 int rl_inhibit_completion = 0;
101 int rl_attempted_completion_over = 0;
102 char *rl_basic_word_break_characters = break_chars;
103 char *rl_completer_word_break_characters = NULL;
104 char *rl_completer_quote_characters = NULL;
105 Function *rl_completion_entry_function = NULL;
106 CPPFunction *rl_attempted_completion_function = NULL;
107 Function *rl_pre_input_hook = NULL;
108 Function *rl_startup1_hook = NULL;
109 Function *rl_getc_function = NULL;
110 char *rl_terminal_name = NULL;
111 int rl_already_prompted = 0;
112 int rl_filename_completion_desired = 0;
113 int rl_ignore_completion_duplicates = 0;
114 int rl_catch_signals = 1;
115 VFunction *rl_redisplay_function = NULL;
116 Function *rl_startup_hook = NULL;
117 VFunction *rl_completion_display_matches_hook = NULL;
118 VFunction *rl_prep_term_function = NULL;
119 VFunction *rl_deprep_term_function = NULL;
120
121 /*
122  * The current prompt string.
123  */
124 char *rl_prompt = NULL;
125 /*
126  * This is set to character indicating type of completion being done by
127  * rl_complete_internal(); this is available for application completion
128  * functions.
129  */
130 int rl_completion_type = 0;
131
132 /*
133  * If more than this number of items results from query for possible
134  * completions, we ask user if they are sure to really display the list.
135  */
136 int rl_completion_query_items = 100;
137
138 /*
139  * List of characters which are word break characters, but should be left
140  * in the parsed text when it is passed to the completion function.
141  * Shell uses this to help determine what kind of completing to do.
142  */
143 char *rl_special_prefixes = NULL;
144
145 /*
146  * This is the character appended to the completed words if at the end of
147  * the line. Default is ' ' (a space).
148  */
149 int rl_completion_append_character = ' ';
150
151 /* stuff below is used internally by libedit for readline emulation */
152
153 static History *h = NULL;
154 static EditLine *e = NULL;
155 static Function *map[256];
156
157 /* internal functions */
158 static unsigned char     _el_rl_complete(EditLine *, int);
159 static unsigned char     _el_rl_tstp(EditLine *, int);
160 static char             *_get_prompt(EditLine *);
161 static HIST_ENTRY       *_move_history(int);
162 static int               _history_expand_command(const char *, size_t, size_t,
163     char **);
164 static char             *_rl_compat_sub(const char *, const char *,
165     const char *, int);
166 static int               _rl_event_read_char(EditLine *, char *);
167 static void              _rl_update_pos(void);
168
169
170 /* ARGSUSED */
171 static char *
172 _get_prompt(EditLine *el __attribute__((__unused__)))
173 {
174         rl_already_prompted = 1;
175         return (rl_prompt);
176 }
177
178
179 /*
180  * generic function for moving around history
181  */
182 static HIST_ENTRY *
183 _move_history(int op)
184 {
185         HistEvent ev;
186         static HIST_ENTRY rl_he;
187
188         if (history(h, &ev, op) != 0)
189                 return (HIST_ENTRY *) NULL;
190
191         rl_he.line = ev.str;
192         rl_he.data = NULL;
193
194         return (&rl_he);
195 }
196
197
198 /*
199  * READLINE compatibility stuff
200  */
201
202 /*
203  * initialize rl compat stuff
204  */
205 int
206 rl_initialize(void)
207 {
208         HistEvent ev;
209         const LineInfo *li;
210         int editmode = 1;
211         struct termios t;
212
213         if (e != NULL)
214                 el_end(e);
215         if (h != NULL)
216                 history_end(h);
217
218         if (!rl_instream)
219                 rl_instream = stdin;
220         if (!rl_outstream)
221                 rl_outstream = stdout;
222
223         /*
224          * See if we don't really want to run the editor
225          */
226         if (tcgetattr(fileno(rl_instream), &t) != -1 && (t.c_lflag & ECHO) == 0)
227                 editmode = 0;
228
229         e = el_init(rl_readline_name, rl_instream, rl_outstream, stderr);
230
231         if (!editmode)
232                 el_set(e, EL_EDITMODE, 0);
233
234         h = history_init();
235         if (!e || !h)
236                 return (-1);
237
238         history(h, &ev, H_SETSIZE, INT_MAX);    /* unlimited */
239         history_length = 0;
240         max_input_history = INT_MAX;
241         el_set(e, EL_HIST, history, h);
242
243         /* for proper prompt printing in readline() */
244         rl_prompt = strdup("");
245         if (rl_prompt == NULL) {
246                 history_end(h);
247                 el_end(e);
248                 return -1;
249         }
250         el_set(e, EL_PROMPT, _get_prompt);
251         el_set(e, EL_SIGNAL, rl_catch_signals);
252
253         /* set default mode to "emacs"-style and read setting afterwards */
254         /* so this can be overriden */
255         el_set(e, EL_EDITOR, "emacs");
256         if (rl_terminal_name != NULL)
257                 el_set(e, EL_TERMINAL, rl_terminal_name);
258         else
259                 el_get(e, EL_TERMINAL, &rl_terminal_name);
260
261         /*
262          * Word completion - this has to go AFTER rebinding keys
263          * to emacs-style.
264          */
265         el_set(e, EL_ADDFN, "rl_complete",
266             "ReadLine compatible completion function",
267             _el_rl_complete);
268         el_set(e, EL_BIND, "^I", "rl_complete", NULL);
269
270         /*
271          * Send TSTP when ^Z is pressed.
272          */
273         el_set(e, EL_ADDFN, "rl_tstp",
274             "ReadLine compatible suspend function",
275             _el_rl_tstp);
276         el_set(e, EL_BIND, "^Z", "rl_tstp", NULL);
277                 
278         /* read settings from configuration file */
279         el_source(e, NULL);
280
281         /*
282          * Unfortunately, some applications really do use rl_point
283          * and rl_line_buffer directly.
284          */
285         li = el_line(e);
286         /* a cheesy way to get rid of const cast. */
287         rl_line_buffer = memchr(li->buffer, *li->buffer, 1);
288         _rl_update_pos();
289
290         if (rl_startup_hook)
291                 (*rl_startup_hook)(NULL, 0);
292
293         return (0);
294 }
295
296
297 /*
298  * read one line from input stream and return it, chomping
299  * trailing newline (if there is any)
300  */
301 char *
302 readline(const char *prompt)
303 {
304         HistEvent ev;
305         int count;
306         const char *ret;
307         char *buf;
308         static int used_event_hook;
309
310         if (e == NULL || h == NULL)
311                 rl_initialize();
312
313         rl_done = 0;
314
315         /* update prompt accordingly to what has been passed */
316         if (!prompt)
317                 prompt = "";
318         if (strcmp(rl_prompt, prompt) != 0) {
319                 free(rl_prompt);
320                 rl_prompt = strdup(prompt);
321                 if (rl_prompt == NULL)
322                         return NULL;
323         }
324
325         if (rl_pre_input_hook)
326                 (*rl_pre_input_hook)(NULL, 0);
327
328         if (rl_event_hook && !(e->el_flags&NO_TTY)) {
329                 el_set(e, EL_GETCFN, _rl_event_read_char);
330                 used_event_hook = 1;
331         }
332
333         if (!rl_event_hook && used_event_hook) {
334                 el_set(e, EL_GETCFN, EL_BUILTIN_GETCFN);
335                 used_event_hook = 0;
336         }
337
338         rl_already_prompted = 0;
339
340         /* get one line from input stream */
341         ret = el_gets(e, &count);
342
343         if (ret && count > 0) {
344                 int lastidx;
345
346                 buf = strdup(ret);
347                 if (buf == NULL)
348                         return NULL;
349                 lastidx = count - 1;
350                 if (buf[lastidx] == '\n')
351                         buf[lastidx] = '\0';
352         } else
353                 buf = NULL;
354
355         history(h, &ev, H_GETSIZE);
356         history_length = ev.num;
357
358         return buf;
359 }
360
361 /*
362  * history functions
363  */
364
365 /*
366  * is normally called before application starts to use
367  * history expansion functions
368  */
369 void
370 using_history(void)
371 {
372         if (h == NULL || e == NULL)
373                 rl_initialize();
374 }
375
376
377 /*
378  * substitute ``what'' with ``with'', returning resulting string; if
379  * globally == 1, substitutes all occurrences of what, otherwise only the
380  * first one
381  */
382 static char *
383 _rl_compat_sub(const char *str, const char *what, const char *with,
384     int globally)
385 {
386         const   char    *s;
387         char    *r, *result;
388         size_t  len, with_len, what_len;
389
390         len = strlen(str);
391         with_len = strlen(with);
392         what_len = strlen(what);
393
394         /* calculate length we need for result */
395         s = str;
396         while (*s) {
397                 if (*s == *what && !strncmp(s, what, what_len)) {
398                         len += with_len - what_len;
399                         if (!globally)
400                                 break;
401                         s += what_len;
402                 } else
403                         s++;
404         }
405         r = result = malloc(len + 1);
406         if (result == NULL)
407                 return NULL;
408         s = str;
409         while (*s) {
410                 if (*s == *what && !strncmp(s, what, what_len)) {
411                         (void)strncpy(r, with, with_len);
412                         r += with_len;
413                         s += what_len;
414                         if (!globally) {
415                                 (void)strcpy(r, s);
416                                 return(result);
417                         }
418                 } else
419                         *r++ = *s++;
420         }
421         *r = 0;
422         return(result);
423 }
424
425 static  char    *last_search_pat;       /* last !?pat[?] search pattern */
426 static  char    *last_search_match;     /* last !?pat[?] that matched */
427
428 const char *
429 get_history_event(const char *cmd, int *cindex, int qchar)
430 {
431         int idx, sign, sub, num, begin, ret;
432         size_t len;
433         char    *pat;
434         const char *rptr;
435         HistEvent ev;
436
437         idx = *cindex;
438         if (cmd[idx++] != history_expansion_char)
439                 return(NULL);
440
441         /* find out which event to take */
442         if (cmd[idx] == history_expansion_char || cmd[idx] == 0) {
443                 if (history(h, &ev, H_FIRST) != 0)
444                         return(NULL);
445                 *cindex = cmd[idx]? (idx + 1):idx;
446                 return(ev.str);
447         }
448         sign = 0;
449         if (cmd[idx] == '-') {
450                 sign = 1;
451                 idx++;
452         }
453
454         if ('0' <= cmd[idx] && cmd[idx] <= '9') {
455                 HIST_ENTRY *rl_he;
456
457                 num = 0;
458                 while (cmd[idx] && '0' <= cmd[idx] && cmd[idx] <= '9') {
459                         num = num * 10 + cmd[idx] - '0';
460                         idx++;
461                 }
462                 if (sign)
463                         num = history_length - num + 1;
464
465                 if (!(rl_he = history_get(num)))
466                         return(NULL);
467
468                 *cindex = idx;
469                 return(rl_he->line);
470         }
471         sub = 0;
472         if (cmd[idx] == '?') {
473                 sub = 1;
474                 idx++;
475         }
476         begin = idx;
477         while (cmd[idx]) {
478                 if (cmd[idx] == '\n')
479                         break;
480                 if (sub && cmd[idx] == '?')
481                         break;
482                 if (!sub && (cmd[idx] == ':' || cmd[idx] == ' '
483                                     || cmd[idx] == '\t' || cmd[idx] == qchar))
484                         break;
485                 idx++;
486         }
487         len = idx - begin;
488         if (sub && cmd[idx] == '?')
489                 idx++;
490         if (sub && len == 0 && last_search_pat && *last_search_pat)
491                 pat = last_search_pat;
492         else if (len == 0)
493                 return(NULL);
494         else {
495                 if ((pat = malloc(len + 1)) == NULL)
496                         return NULL;
497                 (void)strncpy(pat, cmd + begin, len);
498                 pat[len] = '\0';
499         }
500
501         if (history(h, &ev, H_CURR) != 0) {
502                 if (pat != last_search_pat)
503                         free(pat);
504                 return (NULL);
505         }
506         num = ev.num;
507
508         if (sub) {
509                 if (pat != last_search_pat) {
510                         if (last_search_pat)
511                                 free(last_search_pat);
512                         last_search_pat = pat;
513                 }
514                 ret = history_search(pat, -1);
515         } else
516                 ret = history_search_prefix(pat, -1);
517
518         if (ret == -1) {
519                 /* restore to end of list on failed search */
520                 history(h, &ev, H_FIRST);
521                 (void)fprintf(rl_outstream, "%s: Event not found\n", pat);
522                 if (pat != last_search_pat)
523                         free(pat);
524                 return(NULL);
525         }
526
527         if (sub && len) {
528                 if (last_search_match && last_search_match != pat)
529                         free(last_search_match);
530                 last_search_match = pat;
531         }
532
533         if (pat != last_search_pat)
534                 free(pat);
535
536         if (history(h, &ev, H_CURR) != 0)
537                 return(NULL);
538         *cindex = idx;
539         rptr = ev.str;
540
541         /* roll back to original position */
542         (void)history(h, &ev, H_SET, num);
543
544         return rptr;
545 }
546
547 /*
548  * the real function doing history expansion - takes as argument command
549  * to do and data upon which the command should be executed
550  * does expansion the way I've understood readline documentation
551  *
552  * returns 0 if data was not modified, 1 if it was and 2 if the string
553  * should be only printed and not executed; in case of error,
554  * returns -1 and *result points to NULL
555  * it's callers responsibility to free() string returned in *result
556  */
557 static int
558 _history_expand_command(const char *command, size_t offs, size_t cmdlen,
559     char **result)
560 {
561         char *tmp, *search = NULL, *aptr;
562         const char *ptr, *cmd;
563         static char *from = NULL, *to = NULL;
564         int start, end, idx, has_mods = 0;
565         int p_on = 0, g_on = 0;
566
567         *result = NULL;
568         aptr = NULL;
569         ptr = NULL;
570
571         /* First get event specifier */
572         idx = 0;
573
574         if (strchr(":^*$", command[offs + 1])) {
575                 char str[4];
576                 /*
577                 * "!:" is shorthand for "!!:".
578                 * "!^", "!*" and "!$" are shorthand for
579                 * "!!:^", "!!:*" and "!!:$" respectively.
580                 */
581                 str[0] = str[1] = '!';
582                 str[2] = '0';
583                 ptr = get_history_event(str, &idx, 0);
584                 idx = (command[offs + 1] == ':')? 1:0;
585                 has_mods = 1;
586         } else {
587                 if (command[offs + 1] == '#') {
588                         /* use command so far */
589                         if ((aptr = malloc(offs + 1)) == NULL)
590                                 return -1;
591                         (void)strncpy(aptr, command, offs);
592                         aptr[offs] = '\0';
593                         idx = 1;
594                 } else {
595                         int     qchar;
596
597                         qchar = (offs > 0 && command[offs - 1] == '"')? '"':0;
598                         ptr = get_history_event(command + offs, &idx, qchar);
599                 }
600                 has_mods = command[offs + idx] == ':';
601         }
602
603         if (ptr == NULL && aptr == NULL)
604                 return(-1);
605
606         if (!has_mods) {
607                 *result = strdup(aptr? aptr : ptr);
608                 if (aptr)
609                         free(aptr);
610                 return(1);
611         }
612
613         cmd = command + offs + idx + 1;
614
615         /* Now parse any word designators */
616
617         if (*cmd == '%')        /* last word matched by ?pat? */
618                 tmp = strdup(last_search_match? last_search_match:"");
619         else if (strchr("^*$-0123456789", *cmd)) {
620                 start = end = -1;
621                 if (*cmd == '^')
622                         start = end = 1, cmd++;
623                 else if (*cmd == '$')
624                         start = -1, cmd++;
625                 else if (*cmd == '*')
626                         start = 1, cmd++;
627                else if (*cmd == '-' || isdigit((unsigned char) *cmd)) {
628                         start = 0;
629                         while (*cmd && '0' <= *cmd && *cmd <= '9')
630                                 start = start * 10 + *cmd++ - '0';
631
632                         if (*cmd == '-') {
633                                 if (isdigit((unsigned char) cmd[1])) {
634                                         cmd++;
635                                         end = 0;
636                                         while (*cmd && '0' <= *cmd && *cmd <= '9')
637                                                 end = end * 10 + *cmd++ - '0';
638                                 } else if (cmd[1] == '$') {
639                                         cmd += 2;
640                                         end = -1;
641                                 } else {
642                                         cmd++;
643                                         end = -2;
644                                 }
645                         } else if (*cmd == '*')
646                                 end = -1, cmd++;
647                         else
648                                 end = start;
649                 }
650                 tmp = history_arg_extract(start, end, aptr? aptr:ptr);
651                 if (tmp == NULL) {
652                         (void)fprintf(rl_outstream, "%s: Bad word specifier",
653                             command + offs + idx);
654                         if (aptr)
655                                 free(aptr);
656                         return(-1);
657                 }
658         } else
659                 tmp = strdup(aptr? aptr:ptr);
660
661         if (aptr)
662                 free(aptr);
663
664         if (*cmd == 0 || (cmd - (command + offs) >= cmdlen)) {
665                 *result = tmp;
666                 return(1);
667         }
668
669         for (; *cmd; cmd++) {
670                 if (*cmd == ':')
671                         continue;
672                 else if (*cmd == 'h') {         /* remove trailing path */
673                         if ((aptr = strrchr(tmp, '/')) != NULL)
674                                 *aptr = 0;
675                 } else if (*cmd == 't') {       /* remove leading path */
676                         if ((aptr = strrchr(tmp, '/')) != NULL) {
677                                 aptr = strdup(aptr + 1);
678                                 free(tmp);
679                                 tmp = aptr;
680                         }
681                 } else if (*cmd == 'r') {       /* remove trailing suffix */
682                         if ((aptr = strrchr(tmp, '.')) != NULL)
683                                 *aptr = 0;
684                 } else if (*cmd == 'e') {       /* remove all but suffix */
685                         if ((aptr = strrchr(tmp, '.')) != NULL) {
686                                 aptr = strdup(aptr);
687                                 free(tmp);
688                                 tmp = aptr;
689                         }
690                 } else if (*cmd == 'p')         /* print only */
691                         p_on = 1;
692                 else if (*cmd == 'g')
693                         g_on = 2;
694                 else if (*cmd == 's' || *cmd == '&') {
695                         char *what, *with, delim;
696                         size_t len, from_len;
697                         size_t size;
698
699                         if (*cmd == '&' && (from == NULL || to == NULL))
700                                 continue;
701                         else if (*cmd == 's') {
702                                 delim = *(++cmd), cmd++;
703                                 size = 16;
704                                 what = realloc(from, size);
705                                 if (what == NULL) {
706                                         free(from);
707                                         return 0;
708                                 }
709                                 len = 0;
710                                 for (; *cmd && *cmd != delim; cmd++) {
711                                         if (*cmd == '\\' && cmd[1] == delim)
712                                                 cmd++;
713                                         if (len >= size) {
714                                                 char *nwhat;
715                                                 nwhat = realloc(what,
716                                                                 (size <<= 1));
717                                                 if (nwhat == NULL) {
718                                                         free(what);
719                                                         return 0;
720                                                 }
721                                                 what = nwhat;
722                                         }
723                                         what[len++] = *cmd;
724                                 }
725                                 what[len] = '\0';
726                                 from = what;
727                                 if (*what == '\0') {
728                                         free(what);
729                                         if (search) {
730                                                 from = strdup(search);
731                                                 if (from == NULL)
732                                                         return 0;
733                                         } else {
734                                                 from = NULL;
735                                                 return (-1);
736                                         }
737                                 }
738                                 cmd++;  /* shift after delim */
739                                 if (!*cmd)
740                                         continue;
741
742                                 size = 16;
743                                 with = realloc(to, size);
744                                 if (with == NULL) {
745                                         free(to);
746                                         return -1;
747                                 }
748                                 len = 0;
749                                 from_len = strlen(from);
750                                 for (; *cmd && *cmd != delim; cmd++) {
751                                         if (len + from_len + 1 >= size) {
752                                                 char *nwith;
753                                                 size += from_len + 1;
754                                                 nwith = realloc(with, size);
755                                                 if (nwith == NULL) {
756                                                         free(with);
757                                                         return -1;
758                                                 }
759                                                 with = nwith;
760                                         }
761                                         if (*cmd == '&') {
762                                                 /* safe */
763                                                 (void)strcpy(&with[len], from);
764                                                 len += from_len;
765                                                 continue;
766                                         }
767                                         if (*cmd == '\\'
768                                             && (*(cmd + 1) == delim
769                                                 || *(cmd + 1) == '&'))
770                                                 cmd++;
771                                         with[len++] = *cmd;
772                                 }
773                                 with[len] = '\0';
774                                 to = with;
775                         }
776
777                         aptr = _rl_compat_sub(tmp, from, to, g_on);
778                         if (aptr) {
779                                 free(tmp);
780                                 tmp = aptr;
781                         }
782                         g_on = 0;
783                 }
784         }
785         *result = tmp;
786         return (p_on? 2:1);
787 }
788
789
790 /*
791  * csh-style history expansion
792  */
793 int
794 history_expand(char *str, char **output)
795 {
796         int ret = 0;
797         size_t idx, i, size;
798         char *tmp, *result;
799
800         if (h == NULL || e == NULL)
801                 rl_initialize();
802
803         if (history_expansion_char == 0) {
804                 *output = strdup(str);
805                 return(0);
806         }
807
808         *output = NULL;
809         if (str[0] == history_subst_char) {
810                 /* ^foo^foo2^ is equivalent to !!:s^foo^foo2^ */
811                 *output = malloc(strlen(str) + 4 + 1);
812                 if (*output == NULL)
813                         return 0;
814                 (*output)[0] = (*output)[1] = history_expansion_char;
815                 (*output)[2] = ':';
816                 (*output)[3] = 's';
817                 (void)strcpy((*output) + 4, str);
818                 str = *output;
819         } else {
820                 *output = strdup(str);
821                 if (*output == NULL)
822                         return 0;
823         }
824
825 #define ADD_STRING(what, len)                                           \
826         {                                                               \
827                 if (idx + len + 1 > size) {                             \
828                         char *nresult = realloc(result, (size += len + 1));\
829                         if (nresult == NULL) {                          \
830                                 free(*output);                          \
831                                 return 0;                               \
832                         }                                               \
833                         result = nresult;                               \
834                 }                                                       \
835                 (void)strncpy(&result[idx], what, len);                 \
836                 idx += len;                                             \
837                 result[idx] = '\0';                                     \
838         }
839
840         result = NULL;
841         size = idx = 0;
842         for (i = 0; str[i];) {
843                 int qchar, loop_again;
844                 size_t len, start, j;
845
846                 qchar = 0;
847                 loop_again = 1;
848                 start = j = i;
849 loop:
850                 for (; str[j]; j++) {
851                         if (str[j] == '\\' &&
852                             str[j + 1] == history_expansion_char) {
853                                 (void)strcpy(&str[j], &str[j + 1]);
854                                 continue;
855                         }
856                         if (!loop_again) {
857                                 if (isspace((unsigned char) str[j])
858                                     || str[j] == qchar)
859                                         break;
860                         }
861                         if (str[j] == history_expansion_char
862                             && !strchr(history_no_expand_chars, str[j + 1])
863                             && (!history_inhibit_expansion_function ||
864                             (*history_inhibit_expansion_function)(str,
865                             (int)j) == 0))
866                                 break;
867                 }
868
869                 if (str[j] && loop_again) {
870                         i = j;
871                         qchar = (j > 0 && str[j - 1] == '"' )? '"':0;
872                         j++;
873                         if (str[j] == history_expansion_char)
874                                 j++;
875                         loop_again = 0;
876                         goto loop;
877                 }
878                 len = i - start;
879                 tmp = &str[start];
880                 ADD_STRING(tmp, len);
881
882                 if (str[i] == '\0' || str[i] != history_expansion_char) {
883                         len = j - i;
884                         tmp = &str[i];
885                         ADD_STRING(tmp, len);
886                         if (start == 0)
887                                 ret = 0;
888                         else
889                                 ret = 1;
890                         break;
891                 }
892                 ret = _history_expand_command (str, i, (j - i), &tmp);
893                 if (ret > 0 && tmp) {
894                         len = strlen(tmp);
895                         ADD_STRING(tmp, len);
896                         free(tmp);
897                 }
898                 i = j;
899         }
900
901         /* ret is 2 for "print only" option */
902         if (ret == 2) {
903                 add_history(result);
904 #ifdef GDB_411_HACK
905                 /* gdb 4.11 has been shipped with readline, where */
906                 /* history_expand() returned -1 when the line     */
907                 /* should not be executed; in readline 2.1+       */
908                 /* it should return 2 in such a case              */
909                 ret = -1;
910 #endif
911         }
912         free(*output);
913         *output = result;
914
915         return (ret);
916 }
917
918 /*
919 * Return a string consisting of arguments of "str" from "start" to "end".
920 */
921 char *
922 history_arg_extract(int start, int end, const char *str)
923 {
924         size_t  i, len, max;
925         char    **arr, *result;
926
927         arr = history_tokenize(str);
928         if (!arr)
929                 return(NULL);
930         if (arr && *arr == NULL) {
931                 free(arr);
932                 return(NULL);
933         }
934
935         for (max = 0; arr[max]; max++)
936                 continue;
937         max--;
938
939         if (start == '$')
940                 start = max;
941         if (end == '$')
942                 end = max;
943         if (end < 0)
944                 end = max + end + 1;
945         if (start < 0)
946                 start = end;
947
948         if (start < 0 || end < 0 || start > max || end > max || start > end)
949                 return(NULL);
950
951         for (i = start, len = 0; i <= end; i++)
952                 len += strlen(arr[i]) + 1;
953         len++;
954         result = malloc(len);
955         if (result == NULL)
956                 return NULL;
957
958         for (i = start, len = 0; i <= end; i++) {
959                 (void)strcpy(result + len, arr[i]);
960                 len += strlen(arr[i]);
961                 if (i < end)
962                         result[len++] = ' ';
963         }
964         result[len] = 0;
965
966         for (i = 0; arr[i]; i++)
967                 free(arr[i]);
968         free(arr);
969
970         return(result);
971 }
972
973 /*
974  * Parse the string into individual tokens,
975  * similar to how shell would do it.
976  */
977 char **
978 history_tokenize(const char *str)
979 {
980         int size = 1, idx = 0, i, start;
981         size_t len;
982         char **result = NULL, *temp, delim = '\0';
983
984         for (i = 0; str[i];) {
985                 while (isspace((unsigned char) str[i]))
986                         i++;
987                 start = i;
988                 for (; str[i];) {
989                         if (str[i] == '\\') {
990                                 if (str[i+1] != '\0')
991                                         i++;
992                         } else if (str[i] == delim)
993                                 delim = '\0';
994                         else if (!delim &&
995                                     (isspace((unsigned char) str[i]) ||
996                                 strchr("()<>;&|$", str[i])))
997                                 break;
998                         else if (!delim && strchr("'`\"", str[i]))
999                                 delim = str[i];
1000                         if (str[i])
1001                                 i++;
1002                 }
1003
1004                 if (idx + 2 >= size) {
1005                         char **nresult;
1006                         size <<= 1;
1007                         nresult = realloc(result, size * sizeof(char *));
1008                         if (nresult == NULL) {
1009                                 free(result);
1010                                 return NULL;
1011                         }
1012                         result = nresult;
1013                 }
1014                 len = i - start;
1015                 temp = malloc(len + 1);
1016                 if (temp == NULL) {
1017                         for (i = 0; i < idx; i++)
1018                                 free(result[i]);
1019                         free(result);
1020                         return NULL;
1021                 }
1022                 (void)strncpy(temp, &str[start], len);
1023                 temp[len] = '\0';
1024                 result[idx++] = temp;
1025                 result[idx] = NULL;
1026                 if (str[i])
1027                         i++;
1028         }
1029         return (result);
1030 }
1031
1032
1033 /*
1034  * limit size of history record to ``max'' events
1035  */
1036 void
1037 stifle_history(int max)
1038 {
1039         HistEvent ev;
1040
1041         if (h == NULL || e == NULL)
1042                 rl_initialize();
1043
1044         if (history(h, &ev, H_SETSIZE, max) == 0)
1045                 max_input_history = max;
1046 }
1047
1048
1049 /*
1050  * "unlimit" size of history - set the limit to maximum allowed int value
1051  */
1052 int
1053 unstifle_history(void)
1054 {
1055         HistEvent ev;
1056         int omax;
1057
1058         history(h, &ev, H_SETSIZE, INT_MAX);
1059         omax = max_input_history;
1060         max_input_history = INT_MAX;
1061         return (omax);          /* some value _must_ be returned */
1062 }
1063
1064
1065 int
1066 history_is_stifled(void)
1067 {
1068
1069         /* cannot return true answer */
1070         return (max_input_history != INT_MAX);
1071 }
1072
1073
1074 /*
1075  * read history from a file given
1076  */
1077 int
1078 read_history(const char *filename)
1079 {
1080         HistEvent ev;
1081
1082         if (h == NULL || e == NULL)
1083                 rl_initialize();
1084         return (history(h, &ev, H_LOAD, filename));
1085 }
1086
1087
1088 /*
1089  * write history to a file given
1090  */
1091 int
1092 write_history(const char *filename)
1093 {
1094         HistEvent ev;
1095
1096         if (h == NULL || e == NULL)
1097                 rl_initialize();
1098         return (history(h, &ev, H_SAVE, filename));
1099 }
1100
1101
1102 /*
1103  * returns history ``num''th event
1104  *
1105  * returned pointer points to static variable
1106  */
1107 HIST_ENTRY *
1108 history_get(int num)
1109 {
1110         static HIST_ENTRY she;
1111         HistEvent ev;
1112         int curr_num;
1113
1114         if (h == NULL || e == NULL)
1115                 rl_initialize();
1116
1117         /* save current position */
1118         if (history(h, &ev, H_CURR) != 0)
1119                 return (NULL);
1120         curr_num = ev.num;
1121
1122         /* start from most recent */
1123         if (history(h, &ev, H_FIRST) != 0)
1124                 return (NULL);  /* error */
1125
1126         /* look backwards for event matching specified offset */
1127         if (history(h, &ev, H_NEXT_EVENT, num))
1128                 return (NULL);
1129
1130         she.line = ev.str;
1131         she.data = NULL;
1132
1133         /* restore pointer to where it was */
1134         (void)history(h, &ev, H_SET, curr_num);
1135
1136         return (&she);
1137 }
1138
1139
1140 /*
1141  * add the line to history table
1142  */
1143 int
1144 add_history(const char *line)
1145 {
1146         HistEvent ev;
1147
1148         if (h == NULL || e == NULL)
1149                 rl_initialize();
1150
1151         (void)history(h, &ev, H_ENTER, line);
1152         if (history(h, &ev, H_GETSIZE) == 0)
1153                 history_length = ev.num;
1154
1155         return (!(history_length > 0)); /* return 0 if all is okay */
1156 }
1157
1158
1159 /*
1160  * clear the history list - delete all entries
1161  */
1162 void
1163 clear_history(void)
1164 {
1165         HistEvent ev;
1166
1167         history(h, &ev, H_CLEAR);
1168 }
1169
1170
1171 /*
1172  * returns offset of the current history event
1173  */
1174 int
1175 where_history(void)
1176 {
1177         HistEvent ev;
1178         int curr_num, off;
1179
1180         if (history(h, &ev, H_CURR) != 0)
1181                 return (0);
1182         curr_num = ev.num;
1183
1184         history(h, &ev, H_FIRST);
1185         off = 1;
1186         while (ev.num != curr_num && history(h, &ev, H_NEXT) == 0)
1187                 off++;
1188
1189         return (off);
1190 }
1191
1192
1193 /*
1194  * returns current history event or NULL if there is no such event
1195  */
1196 HIST_ENTRY *
1197 current_history(void)
1198 {
1199
1200         return (_move_history(H_CURR));
1201 }
1202
1203
1204 /*
1205  * returns total number of bytes history events' data are using
1206  */
1207 int
1208 history_total_bytes(void)
1209 {
1210         HistEvent ev;
1211         int curr_num, size;
1212
1213         if (history(h, &ev, H_CURR) != 0)
1214                 return (-1);
1215         curr_num = ev.num;
1216
1217         history(h, &ev, H_FIRST);
1218         size = 0;
1219         do
1220                 size += strlen(ev.str);
1221         while (history(h, &ev, H_NEXT) == 0);
1222
1223         /* get to the same position as before */
1224         history(h, &ev, H_PREV_EVENT, curr_num);
1225
1226         return (size);
1227 }
1228
1229
1230 /*
1231  * sets the position in the history list to ``pos''
1232  */
1233 int
1234 history_set_pos(int pos)
1235 {
1236         HistEvent ev;
1237         int curr_num;
1238
1239         if (pos > history_length || pos < 0)
1240                 return (-1);
1241
1242         history(h, &ev, H_CURR);
1243         curr_num = ev.num;
1244
1245         if (history(h, &ev, H_SET, pos)) {
1246                 history(h, &ev, H_SET, curr_num);
1247                 return(-1);
1248         }
1249         return (0);
1250 }
1251
1252
1253 /*
1254  * returns previous event in history and shifts pointer accordingly
1255  */
1256 HIST_ENTRY *
1257 previous_history(void)
1258 {
1259
1260         return (_move_history(H_PREV));
1261 }
1262
1263
1264 /*
1265  * returns next event in history and shifts pointer accordingly
1266  */
1267 HIST_ENTRY *
1268 next_history(void)
1269 {
1270
1271         return (_move_history(H_NEXT));
1272 }
1273
1274
1275 /*
1276  * searches for first history event containing the str
1277  */
1278 int
1279 history_search(const char *str, int direction)
1280 {
1281         HistEvent ev;
1282         const char *strp;
1283         int curr_num;
1284
1285         if (history(h, &ev, H_CURR) != 0)
1286                 return (-1);
1287         curr_num = ev.num;
1288
1289         for (;;) {
1290                 if ((strp = strstr(ev.str, str)) != NULL)
1291                         return (int) (strp - ev.str);
1292                 if (history(h, &ev, direction < 0 ? H_NEXT:H_PREV) != 0)
1293                         break;
1294         }
1295         history(h, &ev, H_SET, curr_num);
1296         return (-1);
1297 }
1298
1299
1300 /*
1301  * searches for first history event beginning with str
1302  */
1303 int
1304 history_search_prefix(const char *str, int direction)
1305 {
1306         HistEvent ev;
1307
1308         return (history(h, &ev, direction < 0? H_PREV_STR:H_NEXT_STR, str));
1309 }
1310
1311
1312 /*
1313  * search for event in history containing str, starting at offset
1314  * abs(pos); continue backward, if pos<0, forward otherwise
1315  */
1316 /* ARGSUSED */
1317 int
1318 history_search_pos(const char *str,
1319                    int direction __attribute__((__unused__)), int pos)
1320 {
1321         HistEvent ev;
1322         int curr_num, off;
1323
1324         off = (pos > 0) ? pos : -pos;
1325         pos = (pos > 0) ? 1 : -1;
1326
1327         if (history(h, &ev, H_CURR) != 0)
1328                 return (-1);
1329         curr_num = ev.num;
1330
1331         if (history_set_pos(off) != 0 || history(h, &ev, H_CURR) != 0)
1332                 return (-1);
1333
1334
1335         for (;;) {
1336                 if (strstr(ev.str, str))
1337                         return (off);
1338                 if (history(h, &ev, (pos < 0) ? H_PREV : H_NEXT) != 0)
1339                         break;
1340         }
1341
1342         /* set "current" pointer back to previous state */
1343         history(h, &ev, (pos < 0) ? H_NEXT_EVENT : H_PREV_EVENT, curr_num);
1344
1345         return (-1);
1346 }
1347
1348
1349 /********************************/
1350 /* completion functions */
1351
1352 char *
1353 tilde_expand(char *name)
1354 {
1355         return fn_tilde_expand(name);
1356 }
1357
1358 char *
1359 filename_completion_function(const char *name, int state)
1360 {
1361         return fn_filename_completion_function(name, state);
1362 }
1363
1364 /*
1365  * a completion generator for usernames; returns _first_ username
1366  * which starts with supplied text
1367  * text contains a partial username preceded by random character
1368  * (usually '~'); state is ignored
1369  * it's callers responsibility to free returned value
1370  */
1371 char *
1372 username_completion_function(const char *text, int state)
1373 {
1374         /*
1375                 For when getpwent_r is supported:
1376         struct passwd *pwd, pwres;
1377         char pwbuf[1024];
1378         */
1379         struct passwd *pwd;
1380         /* remove the above when getpwend_r is supported */
1381
1382         if (text[0] == '\0')
1383                 return (NULL);
1384
1385         if (*text == '~')
1386                 text++;
1387
1388         if (state == 0)
1389                 setpwent();
1390
1391         /*
1392                 For when getpwent_r is supported:
1393         while (getpwent_r(&pwres, pwbuf, sizeof(pwbuf), &pwd) == 0
1394             && pwd != NULL && text[0] == pwd->pw_name[0]
1395             && strcmp(text, pwd->pw_name) == 0);
1396         */
1397         for (;;) {
1398                 pwd = getpwent();
1399                 if (pwd != NULL && text[0] == pwd->pw_name[0] && strcmp(text, pwd->pw_name) == 0)
1400                         break;
1401                 
1402         }
1403         /* remove the above when getpwend_r is supported */
1404
1405         if (pwd == NULL) {
1406                 endpwent();
1407                 return (NULL);
1408         }
1409         return (strdup(pwd->pw_name));
1410 }
1411
1412
1413 /*
1414  * el-compatible wrapper to send TSTP on ^Z
1415  */
1416 /* ARGSUSED */
1417 static unsigned char
1418 _el_rl_tstp(EditLine *el __attribute__((__unused__)), int ch __attribute__((__unused__)))
1419 {
1420         (void)kill(0, SIGTSTP);
1421         return CC_NORM;
1422 }
1423
1424 /*
1425  * Display list of strings in columnar format on readline's output stream.
1426  * 'matches' is list of strings, 'len' is number of strings in 'matches',
1427  * 'max' is maximum length of string in 'matches'.
1428  */
1429 void
1430 rl_display_match_list(char **matches, int len, int max)
1431 {
1432
1433         fn_display_match_list(e, matches, len, max);
1434 }
1435
1436 static const char *
1437 /*ARGSUSED*/
1438 _rl_completion_append_character_function(const char *dummy
1439     __attribute__((__unused__)))
1440 {
1441         static char buf[2];
1442         buf[1] = rl_completion_append_character;
1443         return buf;
1444 }
1445
1446
1447 /*
1448  * complete word at current point
1449  */
1450 /* ARGSUSED */
1451 int
1452 rl_complete(int ignore __attribute__((__unused__)), int invoking_key)
1453 {
1454         if (h == NULL || e == NULL)
1455                 rl_initialize();
1456
1457         if (rl_inhibit_completion) {
1458                 char arr[2];
1459                 arr[0] = (char)invoking_key;
1460                 arr[1] = '\0';
1461                 el_insertstr(e, arr);
1462                 return (CC_REFRESH);
1463         }
1464
1465         /* Just look at how many global variables modify this operation! */
1466         return fn_complete(e,
1467             (CPFunction *)rl_completion_entry_function,
1468             rl_attempted_completion_function,
1469             rl_basic_word_break_characters, rl_special_prefixes,
1470             _rl_completion_append_character_function, rl_completion_query_items,
1471             &rl_completion_type, &rl_attempted_completion_over,
1472             &rl_point, &rl_end);
1473 }
1474
1475
1476 /* ARGSUSED */
1477 static unsigned char
1478 _el_rl_complete(EditLine *el __attribute__((__unused__)), int ch)
1479 {
1480         return (unsigned char)rl_complete(0, ch);
1481 }
1482
1483 /*
1484  * misc other functions
1485  */
1486
1487 /*
1488  * bind key c to readline-type function func
1489  */
1490 int
1491 rl_bind_key(int c, int func(int, int))
1492 {
1493         int retval = -1;
1494
1495         if (h == NULL || e == NULL)
1496                 rl_initialize();
1497
1498         if (func == rl_insert) {
1499                 /* XXX notice there is no range checking of ``c'' */
1500                 e->el_map.key[c] = ED_INSERT;
1501                 retval = 0;
1502         }
1503         return (retval);
1504 }
1505
1506
1507 /*
1508  * read one key from input - handles chars pushed back
1509  * to input stream also
1510  */
1511 int
1512 rl_read_key(void)
1513 {
1514         char fooarr[2 * sizeof(int)];
1515
1516         if (e == NULL || h == NULL)
1517                 rl_initialize();
1518
1519         return (el_getc(e, fooarr));
1520 }
1521
1522
1523 /*
1524  * reset the terminal
1525  */
1526 /* ARGSUSED */
1527 void
1528 rl_reset_terminal(const char *p __attribute__((__unused__)))
1529 {
1530
1531         if (h == NULL || e == NULL)
1532                 rl_initialize();
1533         el_reset(e);
1534 }
1535
1536
1537 /*
1538  * insert character ``c'' back into input stream, ``count'' times
1539  */
1540 int
1541 rl_insert(int count, int c)
1542 {
1543         char arr[2];
1544
1545         if (h == NULL || e == NULL)
1546                 rl_initialize();
1547
1548         /* XXX - int -> char conversion can lose on multichars */
1549         arr[0] = c;
1550         arr[1] = '\0';
1551
1552         for (; count > 0; count--)
1553                 el_push(e, arr);
1554
1555         return (0);
1556 }
1557
1558 /*ARGSUSED*/
1559 int
1560 rl_newline(int count, int c)
1561 {
1562         /*
1563          * Readline-4.0 appears to ignore the args.
1564          */
1565         return rl_insert(1, '\n');
1566 }
1567
1568 /*ARGSUSED*/
1569 static unsigned char
1570 rl_bind_wrapper(EditLine *el, unsigned char c)
1571 {
1572         if (map[c] == NULL)
1573             return CC_ERROR;
1574
1575         _rl_update_pos();
1576
1577         (*map[c])(NULL, c);
1578
1579         /* If rl_done was set by the above call, deal with it here */
1580         if (rl_done)
1581                 return CC_EOF;
1582
1583         return CC_NORM;
1584 }
1585
1586 int
1587 rl_add_defun(const char *name, Function *fun, int c)
1588 {
1589         char dest[8];
1590         if (c >= sizeof(map) / sizeof(map[0]) || c < 0)
1591                 return -1;
1592         map[(unsigned char)c] = fun;
1593         el_set(e, EL_ADDFN, name, name, rl_bind_wrapper);
1594         vis(dest, c, VIS_WHITE|VIS_NOSLASH, 0);
1595         el_set(e, EL_BIND, dest, name);
1596         return 0;
1597 }
1598
1599 void
1600 rl_callback_read_char()
1601 {
1602         int count = 0, done = 0;
1603         const char *buf = el_gets(e, &count);
1604         char *wbuf;
1605
1606         if (buf == NULL || count-- <= 0)
1607                 return;
1608         if (count == 0 && buf[0] == CTRL('d'))
1609                 done = 1;
1610         if (buf[count] == '\n' || buf[count] == '\r')
1611                 done = 2;
1612
1613         if (done && rl_linefunc != NULL) {
1614                 el_set(e, EL_UNBUFFERED, 0);
1615                 if (done == 2) {
1616                     if ((wbuf = strdup(buf)) != NULL)
1617                         wbuf[count] = '\0';
1618                 } else
1619                         wbuf = NULL;
1620                 (*(void (*)(const char *))rl_linefunc)(wbuf);
1621                 el_set(e, EL_UNBUFFERED, 1);
1622         }
1623 }
1624
1625 void 
1626 rl_callback_handler_install (const char *prompt, VCPFunction *linefunc)
1627 {
1628         if (e == NULL) {
1629                 rl_initialize();
1630         }
1631         if (rl_prompt)
1632                 free(rl_prompt);
1633         rl_prompt = prompt ? strdup(strchr(prompt, *prompt)) : NULL;
1634         rl_linefunc = linefunc;
1635         el_set(e, EL_UNBUFFERED, 1);
1636 }   
1637
1638 void 
1639 rl_callback_handler_remove(void)
1640 {
1641         el_set(e, EL_UNBUFFERED, 0);
1642 }
1643
1644 void
1645 rl_redisplay(void)
1646 {
1647         char a[2];
1648         a[0] = CTRL('r');
1649         a[1] = '\0';
1650         el_push(e, a);
1651 }
1652
1653 int
1654 rl_get_previous_history(int count, int key)
1655 {
1656         char a[2];
1657         a[0] = key;
1658         a[1] = '\0';
1659         while (count--)
1660                 el_push(e, a);
1661         return 0;
1662 }
1663
1664 void
1665 /*ARGSUSED*/
1666 rl_prep_terminal(int meta_flag)
1667 {
1668         el_set(e, EL_PREP_TERM, 1);
1669 }
1670
1671 void
1672 rl_deprep_terminal()
1673 {
1674         el_set(e, EL_PREP_TERM, 0);
1675 }
1676
1677 int
1678 rl_read_init_file(const char *s)
1679 {
1680         return(el_source(e, s));
1681 }
1682
1683 int
1684 rl_parse_and_bind(const char *line)
1685 {
1686         const char **argv;
1687         int argc;
1688         Tokenizer *tok;
1689
1690         tok = tok_init(NULL);
1691         tok_str(tok, line, &argc, &argv);
1692         argc = el_parse(e, argc, argv);
1693         tok_end(tok);
1694         return (argc ? 1 : 0);
1695 }
1696
1697 int
1698 rl_variable_bind(const char *var, const char *value)
1699 {
1700         /*
1701          * The proper return value is undocument, but this is what the
1702          * readline source seems to do.
1703          */
1704         return ((el_set(e, EL_BIND, "", var, value) == -1) ? 1 : 0);
1705 }
1706
1707 void
1708 rl_stuff_char(int c)
1709 {
1710         char buf[2];
1711
1712         buf[0] = c;
1713         buf[1] = '\0';
1714         el_insertstr(e, buf);
1715 }
1716
1717 static int
1718 _rl_event_read_char(EditLine *el, char *cp)
1719 {
1720         int     n, num_read = 0;
1721
1722         *cp = 0;
1723         while (rl_event_hook) {
1724
1725                 (*rl_event_hook)();
1726
1727 #if defined(FIONREAD)
1728                 if (ioctl(el->el_infd, FIONREAD, &n) < 0)
1729                         return(-1);
1730                 if (n)
1731                         num_read = read(el->el_infd, cp, 1);
1732                 else
1733                         num_read = 0;
1734 #elif defined(F_SETFL) && defined(O_NDELAY)
1735                 if ((n = fcntl(el->el_infd, F_GETFL, 0)) < 0)
1736                         return(-1);
1737                 if (fcntl(el->el_infd, F_SETFL, n|O_NDELAY) < 0)
1738                         return(-1);
1739                 num_read = read(el->el_infd, cp, 1);
1740                 if (fcntl(el->el_infd, F_SETFL, n))
1741                         return(-1);
1742 #else
1743                 /* not non-blocking, but what you gonna do? */
1744                 num_read = read(el->el_infd, cp, 1);
1745                 return(-1);
1746 #endif
1747
1748                 if (num_read < 0 && errno == EAGAIN)
1749                         continue;
1750                 if (num_read == 0)
1751                         continue;
1752                 break;
1753         }
1754         if (!rl_event_hook)
1755                 el_set(el, EL_GETCFN, EL_BUILTIN_GETCFN);
1756         return(num_read);
1757 }
1758
1759 static void
1760 _rl_update_pos(void)
1761 {
1762         const LineInfo *li = el_line(e);
1763
1764         rl_point = li->cursor - li->buffer;
1765         rl_end = li->lastchar - li->buffer;
1766 }