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