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