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