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