root/src/noitedit/readline.c

Revision a2ad36166780d4001768d1e8bead80f058ce072f, 38.9 kB (checked in by Theo Schlossnagle <jesus@omniti.com>, 9 years ago)

closes #143

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