root/src/noitedit/readline.c

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

fix warnings, refs #34

  • 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         temp = malloc(strlen(pass->pw_dir) + 1 + strlen(txt) + 1);
1330         (void) sprintf(temp, "%s/%s", pass->pw_dir, txt);
1331
1332         return (temp);
1333 #endif
1334 }
1335
1336
1337 /*
1338  * return first found file name starting by the ``text'' or NULL if no
1339  * such file can be found
1340  * value of ``state'' is ignored
1341  *
1342  * it's caller's responsibility to free returned string
1343  */
1344 char *
1345 filename_completion_function(const char *text, int state)
1346 {
1347 #if _MSC_VER
1348         return NULL;
1349 #else
1350         static DIR *dir = NULL;
1351         static char *filename = NULL, *dirname = NULL;
1352         static size_t filename_len = 0;
1353         struct dirent *entry;
1354         char *temp;
1355         size_t len;
1356
1357         if (state == 0 || dir == NULL) {
1358                 if (dir != NULL) {
1359                         closedir(dir);
1360                         dir = NULL;
1361                 }
1362                 temp = strrchr(text, '/');
1363                 if (temp) {
1364                         temp++;
1365                         filename = realloc(filename, strlen(temp) + 1);
1366                         (void) strcpy(filename, temp);
1367                         len = temp - text;      /* including last slash */
1368                         dirname = realloc(dirname, len + 1);
1369                         (void) strncpy(dirname, text, len);
1370                         dirname[len] = '\0';
1371                 } else {
1372                         filename = strdup(text);
1373                         dirname = NULL;
1374                 }
1375
1376                 /* support for ``~user'' syntax */
1377                 if (dirname && *dirname == '~') {
1378                         temp = tilde_expand(dirname);
1379                         dirname = realloc(dirname, strlen(temp) + 1);
1380                         (void) strcpy(dirname, temp);   /* safe */
1381                         free(temp);     /* no longer needed */
1382                 }
1383                 /* will be used in cycle */
1384                 filename_len = strlen(filename);
1385                 if (filename_len == 0)
1386                         return (NULL);  /* no expansion possible */
1387
1388                 dir = opendir(dirname ? dirname : ".");
1389                 if (!dir)
1390                         return (NULL);  /* cannot open the directory */
1391         }
1392         /* find the match */
1393         while ((entry = readdir(dir)) != NULL) {
1394                 /* otherwise, get first entry where first */
1395                 /* filename_len characters are equal      */
1396                 if (entry->d_name[0] == filename[0]
1397 #if defined(__SVR4) || defined(__linux__)
1398                     && strlen(entry->d_name) >= filename_len
1399 #else
1400                     && entry->d_namlen >= filename_len
1401 #endif
1402                     && strncmp(entry->d_name, filename,
1403                         filename_len) == 0)
1404                         break;
1405         }
1406
1407         if (entry) {            /* match found */
1408
1409                 struct stat stbuf;
1410 #if defined(__SVR4) || defined(__linux__)
1411                 len = strlen(entry->d_name) +
1412 #else
1413                 len = entry->d_namlen +
1414 #endif
1415                     ((dirname) ? strlen(dirname) : 0) + 1 + 1;
1416                 temp = malloc(len);
1417                 (void) sprintf(temp, "%s%s",
1418                     dirname ? dirname : "", entry->d_name);     /* safe */
1419
1420                 /* test, if it's directory */
1421                 if (stat(temp, &stbuf) == 0 && S_ISDIR(stbuf.st_mode))
1422                         strcat(temp, "/");      /* safe */
1423         } else
1424                 temp = NULL;
1425
1426         return (temp);
1427 #endif
1428 }
1429
1430
1431 /*
1432  * a completion generator for usernames; returns _first_ username
1433  * which starts with supplied text
1434  * text contains a partial username preceded by random character
1435  * (usually '~'); state is ignored
1436  * it's callers responsibility to free returned value
1437  */
1438 char *
1439 username_completion_function(const char *text, int state)
1440 {
1441 #if _MSC_VER
1442         return NULL;
1443 #else
1444         struct passwd *pwd;
1445
1446         if (text[0] == '\0')
1447                 return (NULL);
1448
1449         if (*text == '~')
1450                 text++;
1451
1452         if (state == 0)
1453                 setpwent();
1454
1455         while ((pwd = getpwent()) && text[0] == pwd->pw_name[0]
1456             && strcmp(text, pwd->pw_name) == 0);
1457
1458         if (pwd == NULL) {
1459                 endpwent();
1460                 return (NULL);
1461         }
1462         return (strdup(pwd->pw_name));
1463 #endif
1464 }
1465
1466
1467 /*
1468  * el-compatible wrapper around rl_complete; needed for key binding
1469  */
1470 /* ARGSUSED */
1471 static unsigned char
1472 _el_rl_complete(EditLine *el, int ch)
1473 {
1474         return (unsigned char) rl_complete(0, ch);
1475 }
1476
1477
1478 /*
1479  * returns list of completitions for text given
1480  */
1481 char **
1482 completion_matches(const char *text, CPFunction *genfunc)
1483 {
1484         char **match_list = NULL, *retstr, *prevstr;
1485         size_t match_list_len, max_equal, which, i;
1486         int matches;
1487
1488         if (h == NULL || e == NULL)
1489                 rl_initialize();
1490
1491         matches = 0;
1492         match_list_len = 1;
1493         while ((retstr = (*genfunc) (text, matches)) != NULL) {
1494                 if (matches + 1 >= match_list_len) {
1495                         match_list_len <<= 1;
1496                         match_list = realloc(match_list,
1497                             match_list_len * sizeof(char *));
1498                 }
1499                 match_list[++matches] = retstr;
1500         }
1501
1502         if (!match_list)
1503                 return (char **) NULL;  /* nothing found */
1504
1505         /* find least denominator and insert it to match_list[0] */
1506         which = 2;
1507         prevstr = match_list[1];
1508         max_equal = strlen(prevstr);
1509         for (; which <= matches; which++) {
1510                 for (i = 0; i < max_equal &&
1511                     prevstr[i] == match_list[which][i]; i++)
1512                         continue;
1513                 max_equal = i;
1514         }
1515
1516         retstr = malloc(max_equal + 1);
1517         (void) strncpy(retstr, match_list[1], max_equal);
1518         retstr[max_equal] = '\0';
1519         match_list[0] = retstr;
1520
1521         /* add NULL as last pointer to the array */
1522         if (matches + 1 >= match_list_len)
1523                 match_list = realloc(match_list,
1524                     (match_list_len + 1) * sizeof(char *));
1525         match_list[matches + 1] = (char *) NULL;
1526
1527         return (match_list);
1528 }
1529
1530 /*
1531  * Sort function for qsort(). Just wrapper around strcasecmp().
1532  */
1533 static int
1534 _rl_qsort_string_compare(i1, i2)
1535         const void *i1, *i2;
1536 {
1537         /*LINTED const castaway*/
1538         const char *s1 = ((const char **)i1)[0];
1539         /*LINTED const castaway*/
1540         const char *s2 = ((const char **)i2)[0];
1541
1542         return strcasecmp(s1, s2);
1543 }
1544
1545 /*
1546  * Display list of strings in columnar format on readline's output stream.
1547  * 'matches' is list of strings, 'len' is number of strings in 'matches',
1548  * 'max' is maximum length of string in 'matches'.
1549  */
1550 void
1551 rl_display_match_list (matches, len, max)
1552      char **matches;
1553      int len, max;
1554 {
1555         int i, idx, limit, count;
1556         int screenwidth = e->el_term.t_size.h;
1557
1558         /*
1559          * Find out how many entries can be put on one line, count
1560          * with two spaces between strings.
1561          */
1562         limit = screenwidth / (max + 2);
1563         if (limit == 0)
1564                 limit = 1;
1565
1566         /* how many lines of output */
1567         count = len / limit;
1568         if (count * limit < len)
1569                 count++;
1570
1571         /* Sort the items if they are not already sorted. */
1572         qsort(&matches[1], (size_t)(len - 1), sizeof(char *),
1573             _rl_qsort_string_compare);
1574
1575         idx = 1;
1576         for(; count > 0; count--) {
1577                 for(i=0; i < limit && matches[idx]; i++, idx++)
1578                         e->el_std_printf(e, "%-*s  ", max, matches[idx]);
1579                 e->el_std_printf(e, "\n");
1580         }
1581 }
1582
1583 /*
1584  * Complete the word at or before point, called by rl_complete()
1585  * 'what_to_do' says what to do with the completion.
1586  * `?' means list the possible completions.
1587  * TAB means do standard completion.
1588  * `*' means insert all of the possible completions.
1589  * `!' means to do standard completion, and list all possible completions if
1590  * there is more than one.
1591  *
1592  * Note: '*' support is not implemented
1593  */
1594 static int
1595 rl_complete_internal(int what_to_do)
1596 {
1597         CPFunction *complet_func;
1598         const LineInfo *li;
1599         char *temp, **matches;
1600         const char *ctemp;
1601         size_t len;
1602
1603         rl_completion_type = what_to_do;
1604
1605         if (h == NULL || e == NULL)
1606                 rl_initialize();
1607
1608         complet_func = rl_completion_entry_function;
1609         if (!complet_func)
1610                 complet_func = filename_completion_function;
1611
1612         /* We now look backwards for the start of a filename/variable word */
1613         li = el_line(e);
1614         ctemp = (const char *) li->cursor;
1615         while (ctemp > li->buffer
1616             && !strchr(rl_basic_word_break_characters, ctemp[-1])
1617             && (!rl_special_prefixes
1618                         || !strchr(rl_special_prefixes, ctemp[-1]) ) )
1619                 ctemp--;
1620
1621         len = li->cursor - ctemp;
1622         temp = alloca(len + 1);
1623         (void) strncpy(temp, ctemp, len);
1624         temp[len] = '\0';
1625
1626         /* these can be used by function called in completion_matches() */
1627         /* or (*rl_attempted_completion_function)() */
1628         rl_point = li->cursor - li->buffer;
1629         rl_end = li->lastchar - li->buffer;
1630
1631         if (!rl_attempted_completion_function)
1632                 matches = completion_matches(temp, complet_func);
1633         else {
1634                 int end = li->cursor - li->buffer;
1635                 matches = (*rl_attempted_completion_function) (temp, (int)
1636                     (end - len), end);
1637         }
1638
1639         if (matches) {
1640                 int i, retval = CC_REFRESH;
1641                 int matches_num, maxlen, match_len, match_display=1;
1642
1643                 /*
1644                  * Only replace the completed string with common part of
1645                  * possible matches if there is possible completion.
1646                  */
1647                 if (matches[0][0] != '\0') {
1648                         el_deletestr(e, (int) len);
1649                         el_insertstr(e, matches[0]);
1650                 }
1651
1652                 if (what_to_do == '?')
1653                         goto display_matches;
1654
1655                 if (matches[2] == NULL && strcmp(matches[0], matches[1]) == 0) {
1656                         /*
1657                          * We found exact match. Add a space after
1658                          * it, unless we do filename completition and the
1659                          * object is a directory.
1660                          */
1661                         size_t alen = strlen(matches[0]);
1662                         if ((complet_func != filename_completion_function
1663                               || (alen > 0 && (matches[0])[alen - 1] != '/'))
1664                             && rl_completion_append_character) {
1665                                 char buf[2];
1666                                 buf[0] = rl_completion_append_character;
1667                                 buf[1] = '\0';
1668                                 el_insertstr(e, buf);
1669                         }
1670                 } else if (what_to_do == '!') {
1671     display_matches:
1672                         /*
1673                          * More than one match and requested to list possible
1674                          * matches.
1675                          */
1676
1677                         for(i=1, maxlen=0; matches[i]; i++) {
1678                                 match_len = strlen(matches[i]);
1679                                 if (match_len > maxlen)
1680                                         maxlen = match_len;
1681                         }
1682                         matches_num = i - 1;
1683                                
1684                         /* newline to get on next line from command line */
1685                         e->el_std_printf(e, "\n");
1686
1687                         /*
1688                          * If there are too many items, ask user for display
1689                          * confirmation.
1690                          */
1691                         if (matches_num > rl_completion_query_items) {
1692                                 e->el_std_printf(e,
1693                                 "Display all %d possibilities? (y or n) ",
1694                                         matches_num);
1695                                 e->el_std_flush(e);
1696                                 if (getc(stdin) != 'y')
1697                                         match_display = 0;
1698                                 e->el_std_printf(e, "\n");
1699                         }
1700
1701                         if (match_display)
1702                                 rl_display_match_list(matches, matches_num,
1703                                         maxlen);
1704                         retval = CC_REDISPLAY;
1705                 } else if (matches[0][0]) {
1706                         /*
1707                          * There was some common match, but the name was
1708                          * not complete enough. Next tab will print possible
1709                          * completions.
1710                          */
1711                         el_beep(e);
1712                 } else {
1713                         /* lcd is not a valid object - further specification */
1714                         /* is needed */
1715                         el_beep(e);
1716                         retval = CC_NORM;
1717                 }
1718
1719                 /* free elements of array and the array itself */
1720                 for (i = 0; matches[i]; i++)
1721                         free(matches[i]);
1722                 free(matches), matches = NULL;
1723
1724                 return (retval);
1725         }
1726         return (CC_NORM);
1727 }
1728
1729
1730 /*
1731  * complete word at current point
1732  */
1733 int
1734 rl_complete(int ignore, int invoking_key)
1735 {
1736         if (h == NULL || e == NULL)
1737                 rl_initialize();
1738
1739         if (rl_inhibit_completion) {
1740                 rl_insert(ignore, invoking_key);
1741                 return (CC_REFRESH);
1742         } else if (e->el_state.lastcmd == el_rl_complete_cmdnum)
1743                 return rl_complete_internal('?');
1744         else if (_rl_complete_show_all)
1745                 return rl_complete_internal('!');
1746         else
1747                 return (rl_complete_internal(TAB));
1748 }
1749
1750
1751 /*
1752  * misc other functions
1753  */
1754
1755 /*
1756  * bind key c to readline-type function func
1757  */
1758 int
1759 rl_bind_key(int c, int func(int, int))
1760 {
1761         int retval = -1;
1762
1763         if (h == NULL || e == NULL)
1764                 rl_initialize();
1765
1766         if (func == rl_insert) {
1767                 /* XXX notice there is no range checking of ``c'' */
1768                 e->el_map.key[c] = ED_INSERT;
1769                 retval = 0;
1770         }
1771         return (retval);
1772 }
1773
1774
1775 /*
1776  * read one key from input - handles chars pushed back
1777  * to input stream also
1778  */
1779 int
1780 rl_read_key(void)
1781 {
1782         char fooarr[2 * sizeof(int)];
1783
1784         if (e == NULL || h == NULL)
1785                 rl_initialize();
1786
1787         return (el_getc(e, fooarr));
1788 }
1789
1790
1791 /*
1792  * reset the terminal
1793  */
1794 /* ARGSUSED */
1795 void
1796 rl_reset_terminal(const char *p)
1797 {
1798
1799         if (h == NULL || e == NULL)
1800                 rl_initialize();
1801         el_reset(e);
1802 }
1803
1804
1805 /*
1806  * insert character ``c'' back into input stream, ``count'' times
1807  */
1808 int
1809 rl_insert(int count, int c)
1810 {
1811         char arr[2];
1812
1813         if (h == NULL || e == NULL)
1814                 rl_initialize();
1815
1816         /* XXX - int -> char conversion can lose on multichars */
1817         arr[0] = c;
1818         arr[1] = '\0';
1819
1820         for (; count > 0; count--)
1821                 el_push(e, arr);
1822
1823         return (0);
1824 }
Note: See TracBrowser for help on using the browser.