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