root/src/noitedit/readline.c

Revision bafab25395cb398ddf5eae42145f0d0bfc00ec22, 38.4 kB (checked in by Theo Schlossnagle <jesus@omniti.com>, 6 years ago)

import of libedit... prepare to hack

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