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