root/src/noitedit/readline.c

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

write the eventer... checks are working, but the telnet console is not, refs #32

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