Start flushing out the IPI routines and do some clean-up.
[dragonfly/vkernel-mp.git] / lib / libedit / readline.c
blob402c5a2bd764bf26132b4fe368ef734fbea2ec3e
1 /*-
2 * Copyright (c) 1997 The NetBSD Foundation, Inc.
3 * All rights reserved.
5 * This code is derived from software contributed to The NetBSD Foundation
6 * by Jaromir Dolecek.
8 * Redistribution and use in source and binary forms, with or without
9 * modification, are permitted provided that the following conditions
10 * are met:
11 * 1. Redistributions of source code must retain the above copyright
12 * notice, this list of conditions and the following disclaimer.
13 * 2. Redistributions in binary form must reproduce the above copyright
14 * notice, this list of conditions and the following disclaimer in the
15 * documentation and/or other materials provided with the distribution.
16 * 3. Neither the name of The NetBSD Foundation nor the names of its
17 * contributors may be used to endorse or promote products derived
18 * from this software without specific prior written permission.
20 * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
21 * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
22 * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
23 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
24 * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
25 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
26 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
27 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
28 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
29 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
30 * POSSIBILITY OF SUCH DAMAGE.
32 * $NetBSD: readline.c,v 1.70 2006/11/24 00:01:17 christos Exp $
33 * $DragonFly: src/lib/libedit/readline.c,v 1.2 2007/05/05 00:27:39 pavalos Exp $
36 #include "config.h"
38 #include <sys/types.h>
39 #include <sys/stat.h>
40 #include <stdio.h>
41 #include <dirent.h>
42 #include <string.h>
43 #include <pwd.h>
44 #include <ctype.h>
45 #include <stdlib.h>
46 #include <unistd.h>
47 #include <limits.h>
48 #include <errno.h>
49 #include <fcntl.h>
50 #include <setjmp.h>
51 #ifdef HAVE_VIS_H
52 #include <vis.h>
53 #else
54 #include "np/vis.h"
55 #endif
56 #ifdef HAVE_ALLOCA_H
57 #include <alloca.h>
58 #endif
59 #include "el.h"
60 #include "fcns.h" /* for EL_NUM_FCNS */
61 #include "histedit.h"
62 #include "readline/readline.h"
63 #include "filecomplete.h"
65 void rl_prep_terminal(int);
66 void rl_deprep_terminal(void);
68 /* for rl_complete() */
69 #define TAB '\r'
71 /* see comment at the #ifdef for sense of this */
72 /* #define GDB_411_HACK */
74 /* readline compatibility stuff - look at readline sources/documentation */
75 /* to see what these variables mean */
76 const char *rl_library_version = "EditLine wrapper";
77 static char empty[] = { '\0' };
78 static char expand_chars[] = { ' ', '\t', '\n', '=', '(', '\0' };
79 static char break_chars[] = { ' ', '\t', '\n', '"', '\\', '\'', '`', '@', '$',
80 '>', '<', '=', ';', '|', '&', '{', '(', '\0' };
81 char *rl_readline_name = empty;
82 FILE *rl_instream = NULL;
83 FILE *rl_outstream = NULL;
84 int rl_point = 0;
85 int rl_end = 0;
86 char *rl_line_buffer = NULL;
87 VCPFunction *rl_linefunc = NULL;
88 int rl_done = 0;
89 VFunction *rl_event_hook = NULL;
90 KEYMAP_ENTRY_ARRAY emacs_standard_keymap,
91 emacs_meta_keymap,
92 emacs_ctlx_keymap;
94 int history_base = 1; /* probably never subject to change */
95 int history_length = 0;
96 int max_input_history = 0;
97 char history_expansion_char = '!';
98 char history_subst_char = '^';
99 char *history_no_expand_chars = expand_chars;
100 Function *history_inhibit_expansion_function = NULL;
101 char *history_arg_extract(int start, int end, const char *str);
103 int rl_inhibit_completion = 0;
104 int rl_attempted_completion_over = 0;
105 char *rl_basic_word_break_characters = break_chars;
106 char *rl_completer_word_break_characters = NULL;
107 char *rl_completer_quote_characters = NULL;
108 Function *rl_completion_entry_function = NULL;
109 CPPFunction *rl_attempted_completion_function = NULL;
110 Function *rl_pre_input_hook = NULL;
111 Function *rl_startup1_hook = NULL;
112 Function *rl_getc_function = NULL;
113 char *rl_terminal_name = NULL;
114 int rl_already_prompted = 0;
115 int rl_filename_completion_desired = 0;
116 int rl_ignore_completion_duplicates = 0;
117 int rl_catch_signals = 1;
118 int readline_echoing_p = 1;
119 int _rl_print_completions_horizontally = 0;
120 VFunction *rl_redisplay_function = NULL;
121 Function *rl_startup_hook = NULL;
122 VFunction *rl_completion_display_matches_hook = NULL;
123 VFunction *rl_prep_term_function = (VFunction *)rl_prep_terminal;
124 VFunction *rl_deprep_term_function = (VFunction *)rl_deprep_terminal;
127 * The current prompt string.
129 char *rl_prompt = NULL;
131 * This is set to character indicating type of completion being done by
132 * rl_complete_internal(); this is available for application completion
133 * functions.
135 int rl_completion_type = 0;
138 * If more than this number of items results from query for possible
139 * completions, we ask user if they are sure to really display the list.
141 int rl_completion_query_items = 100;
144 * List of characters which are word break characters, but should be left
145 * in the parsed text when it is passed to the completion function.
146 * Shell uses this to help determine what kind of completing to do.
148 char *rl_special_prefixes = NULL;
151 * This is the character appended to the completed words if at the end of
152 * the line. Default is ' ' (a space).
154 int rl_completion_append_character = ' ';
156 /* stuff below is used internally by libedit for readline emulation */
158 static History *h = NULL;
159 static EditLine *e = NULL;
160 static Function *map[256];
161 static jmp_buf topbuf;
163 /* internal functions */
164 static unsigned char _el_rl_complete(EditLine *, int);
165 static unsigned char _el_rl_tstp(EditLine *, int);
166 static char *_get_prompt(EditLine *);
167 static int _getc_function(EditLine *, char *);
168 static HIST_ENTRY *_move_history(int);
169 static int _history_expand_command(const char *, size_t, size_t,
170 char **);
171 static char *_rl_compat_sub(const char *, const char *,
172 const char *, int);
173 static int _rl_event_read_char(EditLine *, char *);
174 static void _rl_update_pos(void);
177 /* ARGSUSED */
178 static char *
179 _get_prompt(EditLine *el __attribute__((__unused__)))
181 rl_already_prompted = 1;
182 return (rl_prompt);
187 * generic function for moving around history
189 static HIST_ENTRY *
190 _move_history(int op)
192 HistEvent ev;
193 static HIST_ENTRY rl_he;
195 if (history(h, &ev, op) != 0)
196 return (HIST_ENTRY *) NULL;
198 rl_he.line = ev.str;
199 rl_he.data = NULL;
201 return (&rl_he);
206 * read one key from user defined input function
208 static int
209 /*ARGSUSED*/
210 _getc_function(EditLine *el, char *c)
212 int i;
214 i = (*rl_getc_function)(NULL, 0);
215 if (i == -1)
216 return 0;
217 *c = i;
218 return 1;
223 * READLINE compatibility stuff
227 * initialize rl compat stuff
230 rl_initialize(void)
232 HistEvent ev;
233 const LineInfo *li;
234 int editmode = 1;
235 struct termios t;
237 if (e != NULL)
238 el_end(e);
239 if (h != NULL)
240 history_end(h);
242 if (!rl_instream)
243 rl_instream = stdin;
244 if (!rl_outstream)
245 rl_outstream = stdout;
248 * See if we don't really want to run the editor
250 if (tcgetattr(fileno(rl_instream), &t) != -1 && (t.c_lflag & ECHO) == 0)
251 editmode = 0;
253 e = el_init(rl_readline_name, rl_instream, rl_outstream, stderr);
255 if (!editmode)
256 el_set(e, EL_EDITMODE, 0);
258 h = history_init();
259 if (!e || !h)
260 return (-1);
262 history(h, &ev, H_SETSIZE, INT_MAX); /* unlimited */
263 history_length = 0;
264 max_input_history = INT_MAX;
265 el_set(e, EL_HIST, history, h);
267 /* setup getc function if valid */
268 if (rl_getc_function)
269 el_set(e, EL_GETCFN, _getc_function);
271 /* for proper prompt printing in readline() */
272 rl_prompt = strdup("");
273 if (rl_prompt == NULL) {
274 history_end(h);
275 el_end(e);
276 return -1;
278 el_set(e, EL_PROMPT, _get_prompt);
279 el_set(e, EL_SIGNAL, rl_catch_signals);
281 /* set default mode to "emacs"-style and read setting afterwards */
282 /* so this can be overriden */
283 el_set(e, EL_EDITOR, "emacs");
284 if (rl_terminal_name != NULL)
285 el_set(e, EL_TERMINAL, rl_terminal_name);
286 else
287 el_get(e, EL_TERMINAL, &rl_terminal_name);
290 * Word completion - this has to go AFTER rebinding keys
291 * to emacs-style.
293 el_set(e, EL_ADDFN, "rl_complete",
294 "ReadLine compatible completion function",
295 _el_rl_complete);
296 el_set(e, EL_BIND, "^I", "rl_complete", NULL);
299 * Send TSTP when ^Z is pressed.
301 el_set(e, EL_ADDFN, "rl_tstp",
302 "ReadLine compatible suspend function",
303 _el_rl_tstp);
304 el_set(e, EL_BIND, "^Z", "rl_tstp", NULL);
306 /* read settings from configuration file */
307 el_source(e, NULL);
310 * Unfortunately, some applications really do use rl_point
311 * and rl_line_buffer directly.
313 li = el_line(e);
314 /* a cheesy way to get rid of const cast. */
315 rl_line_buffer = memchr(li->buffer, *li->buffer, 1);
316 _rl_update_pos();
318 if (rl_startup_hook)
319 (*rl_startup_hook)(NULL, 0);
321 return (0);
326 * read one line from input stream and return it, chomping
327 * trailing newline (if there is any)
329 char *
330 readline(const char *p)
332 HistEvent ev;
333 const char * volatile prompt = p;
334 int count;
335 const char *ret;
336 char *buf;
337 static int used_event_hook;
339 if (e == NULL || h == NULL)
340 rl_initialize();
342 rl_done = 0;
344 (void)setjmp(topbuf);
346 /* update prompt accordingly to what has been passed */
347 if (!prompt)
348 prompt = "";
349 if (strcmp(rl_prompt, prompt) != 0) {
350 free(rl_prompt);
351 rl_prompt = strdup(prompt);
352 if (rl_prompt == NULL)
353 return NULL;
356 if (rl_pre_input_hook)
357 (*rl_pre_input_hook)(NULL, 0);
359 if (rl_event_hook && !(e->el_flags&NO_TTY)) {
360 el_set(e, EL_GETCFN, _rl_event_read_char);
361 used_event_hook = 1;
364 if (!rl_event_hook && used_event_hook) {
365 el_set(e, EL_GETCFN, EL_BUILTIN_GETCFN);
366 used_event_hook = 0;
369 rl_already_prompted = 0;
371 /* get one line from input stream */
372 ret = el_gets(e, &count);
374 if (ret && count > 0) {
375 int lastidx;
377 buf = strdup(ret);
378 if (buf == NULL)
379 return NULL;
380 lastidx = count - 1;
381 if (buf[lastidx] == '\n')
382 buf[lastidx] = '\0';
383 } else
384 buf = NULL;
386 history(h, &ev, H_GETSIZE);
387 history_length = ev.num;
389 return buf;
393 * history functions
397 * is normally called before application starts to use
398 * history expansion functions
400 void
401 using_history(void)
403 if (h == NULL || e == NULL)
404 rl_initialize();
409 * substitute ``what'' with ``with'', returning resulting string; if
410 * globally == 1, substitutes all occurrences of what, otherwise only the
411 * first one
413 static char *
414 _rl_compat_sub(const char *str, const char *what, const char *with,
415 int globally)
417 const char *s;
418 char *r, *result;
419 size_t len, with_len, what_len;
421 len = strlen(str);
422 with_len = strlen(with);
423 what_len = strlen(what);
425 /* calculate length we need for result */
426 s = str;
427 while (*s) {
428 if (*s == *what && !strncmp(s, what, what_len)) {
429 len += with_len - what_len;
430 if (!globally)
431 break;
432 s += what_len;
433 } else
434 s++;
436 r = result = malloc(len + 1);
437 if (result == NULL)
438 return NULL;
439 s = str;
440 while (*s) {
441 if (*s == *what && !strncmp(s, what, what_len)) {
442 (void)strncpy(r, with, with_len);
443 r += with_len;
444 s += what_len;
445 if (!globally) {
446 (void)strcpy(r, s);
447 return(result);
449 } else
450 *r++ = *s++;
452 *r = 0;
453 return(result);
456 static char *last_search_pat; /* last !?pat[?] search pattern */
457 static char *last_search_match; /* last !?pat[?] that matched */
459 const char *
460 get_history_event(const char *cmd, int *cindex, int qchar)
462 int idx, sign, sub, num, begin, ret;
463 size_t len;
464 char *pat;
465 const char *rptr;
466 HistEvent ev;
468 idx = *cindex;
469 if (cmd[idx++] != history_expansion_char)
470 return(NULL);
472 /* find out which event to take */
473 if (cmd[idx] == history_expansion_char || cmd[idx] == 0) {
474 if (history(h, &ev, H_FIRST) != 0)
475 return(NULL);
476 *cindex = cmd[idx]? (idx + 1):idx;
477 return(ev.str);
479 sign = 0;
480 if (cmd[idx] == '-') {
481 sign = 1;
482 idx++;
485 if ('0' <= cmd[idx] && cmd[idx] <= '9') {
486 HIST_ENTRY *rl_he;
488 num = 0;
489 while (cmd[idx] && '0' <= cmd[idx] && cmd[idx] <= '9') {
490 num = num * 10 + cmd[idx] - '0';
491 idx++;
493 if (sign)
494 num = history_length - num + 1;
496 if (!(rl_he = history_get(num)))
497 return(NULL);
499 *cindex = idx;
500 return(rl_he->line);
502 sub = 0;
503 if (cmd[idx] == '?') {
504 sub = 1;
505 idx++;
507 begin = idx;
508 while (cmd[idx]) {
509 if (cmd[idx] == '\n')
510 break;
511 if (sub && cmd[idx] == '?')
512 break;
513 if (!sub && (cmd[idx] == ':' || cmd[idx] == ' '
514 || cmd[idx] == '\t' || cmd[idx] == qchar))
515 break;
516 idx++;
518 len = idx - begin;
519 if (sub && cmd[idx] == '?')
520 idx++;
521 if (sub && len == 0 && last_search_pat && *last_search_pat)
522 pat = last_search_pat;
523 else if (len == 0)
524 return(NULL);
525 else {
526 if ((pat = malloc(len + 1)) == NULL)
527 return NULL;
528 (void)strncpy(pat, cmd + begin, len);
529 pat[len] = '\0';
532 if (history(h, &ev, H_CURR) != 0) {
533 if (pat != last_search_pat)
534 free(pat);
535 return (NULL);
537 num = ev.num;
539 if (sub) {
540 if (pat != last_search_pat) {
541 if (last_search_pat)
542 free(last_search_pat);
543 last_search_pat = pat;
545 ret = history_search(pat, -1);
546 } else
547 ret = history_search_prefix(pat, -1);
549 if (ret == -1) {
550 /* restore to end of list on failed search */
551 history(h, &ev, H_FIRST);
552 (void)fprintf(rl_outstream, "%s: Event not found\n", pat);
553 if (pat != last_search_pat)
554 free(pat);
555 return(NULL);
558 if (sub && len) {
559 if (last_search_match && last_search_match != pat)
560 free(last_search_match);
561 last_search_match = pat;
564 if (pat != last_search_pat)
565 free(pat);
567 if (history(h, &ev, H_CURR) != 0)
568 return(NULL);
569 *cindex = idx;
570 rptr = ev.str;
572 /* roll back to original position */
573 (void)history(h, &ev, H_SET, num);
575 return rptr;
579 * the real function doing history expansion - takes as argument command
580 * to do and data upon which the command should be executed
581 * does expansion the way I've understood readline documentation
583 * returns 0 if data was not modified, 1 if it was and 2 if the string
584 * should be only printed and not executed; in case of error,
585 * returns -1 and *result points to NULL
586 * it's callers responsibility to free() string returned in *result
588 static int
589 _history_expand_command(const char *command, size_t offs, size_t cmdlen,
590 char **result)
592 char *tmp, *search = NULL, *aptr;
593 const char *ptr, *cmd;
594 static char *from = NULL, *to = NULL;
595 int start, end, idx, has_mods = 0;
596 int p_on = 0, g_on = 0;
598 *result = NULL;
599 aptr = NULL;
600 ptr = NULL;
602 /* First get event specifier */
603 idx = 0;
605 if (strchr(":^*$", command[offs + 1])) {
606 char str[4];
608 * "!:" is shorthand for "!!:".
609 * "!^", "!*" and "!$" are shorthand for
610 * "!!:^", "!!:*" and "!!:$" respectively.
612 str[0] = str[1] = '!';
613 str[2] = '0';
614 ptr = get_history_event(str, &idx, 0);
615 idx = (command[offs + 1] == ':')? 1:0;
616 has_mods = 1;
617 } else {
618 if (command[offs + 1] == '#') {
619 /* use command so far */
620 if ((aptr = malloc(offs + 1)) == NULL)
621 return -1;
622 (void)strncpy(aptr, command, offs);
623 aptr[offs] = '\0';
624 idx = 1;
625 } else {
626 int qchar;
628 qchar = (offs > 0 && command[offs - 1] == '"')? '"':0;
629 ptr = get_history_event(command + offs, &idx, qchar);
631 has_mods = command[offs + idx] == ':';
634 if (ptr == NULL && aptr == NULL)
635 return(-1);
637 if (!has_mods) {
638 *result = strdup(aptr? aptr : ptr);
639 if (aptr)
640 free(aptr);
641 return(1);
644 cmd = command + offs + idx + 1;
646 /* Now parse any word designators */
648 if (*cmd == '%') /* last word matched by ?pat? */
649 tmp = strdup(last_search_match? last_search_match:"");
650 else if (strchr("^*$-0123456789", *cmd)) {
651 start = end = -1;
652 if (*cmd == '^')
653 start = end = 1, cmd++;
654 else if (*cmd == '$')
655 start = -1, cmd++;
656 else if (*cmd == '*')
657 start = 1, cmd++;
658 else if (*cmd == '-' || isdigit((unsigned char) *cmd)) {
659 start = 0;
660 while (*cmd && '0' <= *cmd && *cmd <= '9')
661 start = start * 10 + *cmd++ - '0';
663 if (*cmd == '-') {
664 if (isdigit((unsigned char) cmd[1])) {
665 cmd++;
666 end = 0;
667 while (*cmd && '0' <= *cmd && *cmd <= '9')
668 end = end * 10 + *cmd++ - '0';
669 } else if (cmd[1] == '$') {
670 cmd += 2;
671 end = -1;
672 } else {
673 cmd++;
674 end = -2;
676 } else if (*cmd == '*')
677 end = -1, cmd++;
678 else
679 end = start;
681 tmp = history_arg_extract(start, end, aptr? aptr:ptr);
682 if (tmp == NULL) {
683 (void)fprintf(rl_outstream, "%s: Bad word specifier",
684 command + offs + idx);
685 if (aptr)
686 free(aptr);
687 return(-1);
689 } else
690 tmp = strdup(aptr? aptr:ptr);
692 if (aptr)
693 free(aptr);
695 if (*cmd == 0 || (cmd - (command + offs) >= cmdlen)) {
696 *result = tmp;
697 return(1);
700 for (; *cmd; cmd++) {
701 if (*cmd == ':')
702 continue;
703 else if (*cmd == 'h') { /* remove trailing path */
704 if ((aptr = strrchr(tmp, '/')) != NULL)
705 *aptr = 0;
706 } else if (*cmd == 't') { /* remove leading path */
707 if ((aptr = strrchr(tmp, '/')) != NULL) {
708 aptr = strdup(aptr + 1);
709 free(tmp);
710 tmp = aptr;
712 } else if (*cmd == 'r') { /* remove trailing suffix */
713 if ((aptr = strrchr(tmp, '.')) != NULL)
714 *aptr = 0;
715 } else if (*cmd == 'e') { /* remove all but suffix */
716 if ((aptr = strrchr(tmp, '.')) != NULL) {
717 aptr = strdup(aptr);
718 free(tmp);
719 tmp = aptr;
721 } else if (*cmd == 'p') /* print only */
722 p_on = 1;
723 else if (*cmd == 'g')
724 g_on = 2;
725 else if (*cmd == 's' || *cmd == '&') {
726 char *what, *with, delim;
727 size_t len, from_len;
728 size_t size;
730 if (*cmd == '&' && (from == NULL || to == NULL))
731 continue;
732 else if (*cmd == 's') {
733 delim = *(++cmd), cmd++;
734 size = 16;
735 what = realloc(from, size);
736 if (what == NULL) {
737 free(from);
738 free(tmp);
739 return 0;
741 len = 0;
742 for (; *cmd && *cmd != delim; cmd++) {
743 if (*cmd == '\\' && cmd[1] == delim)
744 cmd++;
745 if (len >= size) {
746 char *nwhat;
747 nwhat = realloc(what,
748 (size <<= 1));
749 if (nwhat == NULL) {
750 free(what);
751 free(tmp);
752 return 0;
754 what = nwhat;
756 what[len++] = *cmd;
758 what[len] = '\0';
759 from = what;
760 if (*what == '\0') {
761 free(what);
762 if (search) {
763 from = strdup(search);
764 if (from == NULL) {
765 free(tmp);
766 return 0;
768 } else {
769 from = NULL;
770 free(tmp);
771 return (-1);
774 cmd++; /* shift after delim */
775 if (!*cmd)
776 continue;
778 size = 16;
779 with = realloc(to, size);
780 if (with == NULL) {
781 free(to);
782 free(tmp);
783 return -1;
785 len = 0;
786 from_len = strlen(from);
787 for (; *cmd && *cmd != delim; cmd++) {
788 if (len + from_len + 1 >= size) {
789 char *nwith;
790 size += from_len + 1;
791 nwith = realloc(with, size);
792 if (nwith == NULL) {
793 free(with);
794 free(tmp);
795 return -1;
797 with = nwith;
799 if (*cmd == '&') {
800 /* safe */
801 (void)strcpy(&with[len], from);
802 len += from_len;
803 continue;
805 if (*cmd == '\\'
806 && (*(cmd + 1) == delim
807 || *(cmd + 1) == '&'))
808 cmd++;
809 with[len++] = *cmd;
811 with[len] = '\0';
812 to = with;
815 aptr = _rl_compat_sub(tmp, from, to, g_on);
816 if (aptr) {
817 free(tmp);
818 tmp = aptr;
820 g_on = 0;
823 *result = tmp;
824 return (p_on? 2:1);
829 * csh-style history expansion
832 history_expand(char *str, char **output)
834 int ret = 0;
835 size_t idx, i, size;
836 char *tmp, *result;
838 if (h == NULL || e == NULL)
839 rl_initialize();
841 if (history_expansion_char == 0) {
842 *output = strdup(str);
843 return(0);
846 *output = NULL;
847 if (str[0] == history_subst_char) {
848 /* ^foo^foo2^ is equivalent to !!:s^foo^foo2^ */
849 *output = malloc(strlen(str) + 4 + 1);
850 if (*output == NULL)
851 return 0;
852 (*output)[0] = (*output)[1] = history_expansion_char;
853 (*output)[2] = ':';
854 (*output)[3] = 's';
855 (void)strcpy((*output) + 4, str);
856 str = *output;
857 } else {
858 *output = strdup(str);
859 if (*output == NULL)
860 return 0;
863 #define ADD_STRING(what, len, fr) \
865 if (idx + len + 1 > size) { \
866 char *nresult = realloc(result, (size += len + 1));\
867 if (nresult == NULL) { \
868 free(*output); \
869 if (/*CONSTCOND*/fr) \
870 free(tmp); \
871 return 0; \
873 result = nresult; \
875 (void)strncpy(&result[idx], what, len); \
876 idx += len; \
877 result[idx] = '\0'; \
880 result = NULL;
881 size = idx = 0;
882 tmp = NULL;
883 for (i = 0; str[i];) {
884 int qchar, loop_again;
885 size_t len, start, j;
887 qchar = 0;
888 loop_again = 1;
889 start = j = i;
890 loop:
891 for (; str[j]; j++) {
892 if (str[j] == '\\' &&
893 str[j + 1] == history_expansion_char) {
894 (void)strcpy(&str[j], &str[j + 1]);
895 continue;
897 if (!loop_again) {
898 if (isspace((unsigned char) str[j])
899 || str[j] == qchar)
900 break;
902 if (str[j] == history_expansion_char
903 && !strchr(history_no_expand_chars, str[j + 1])
904 && (!history_inhibit_expansion_function ||
905 (*history_inhibit_expansion_function)(str,
906 (int)j) == 0))
907 break;
910 if (str[j] && loop_again) {
911 i = j;
912 qchar = (j > 0 && str[j - 1] == '"' )? '"':0;
913 j++;
914 if (str[j] == history_expansion_char)
915 j++;
916 loop_again = 0;
917 goto loop;
919 len = i - start;
920 ADD_STRING(&str[start], len, 0);
922 if (str[i] == '\0' || str[i] != history_expansion_char) {
923 len = j - i;
924 ADD_STRING(&str[i], len, 0);
925 if (start == 0)
926 ret = 0;
927 else
928 ret = 1;
929 break;
931 ret = _history_expand_command (str, i, (j - i), &tmp);
932 if (ret > 0 && tmp) {
933 len = strlen(tmp);
934 ADD_STRING(tmp, len, 1);
936 if (tmp) {
937 free(tmp);
938 tmp = NULL;
940 i = j;
943 /* ret is 2 for "print only" option */
944 if (ret == 2) {
945 add_history(result);
946 #ifdef GDB_411_HACK
947 /* gdb 4.11 has been shipped with readline, where */
948 /* history_expand() returned -1 when the line */
949 /* should not be executed; in readline 2.1+ */
950 /* it should return 2 in such a case */
951 ret = -1;
952 #endif
954 free(*output);
955 *output = result;
957 return (ret);
961 * Return a string consisting of arguments of "str" from "start" to "end".
963 char *
964 history_arg_extract(int start, int end, const char *str)
966 size_t i, len, max;
967 char **arr, *result;
969 arr = history_tokenize(str);
970 if (!arr)
971 return(NULL);
972 if (arr && *arr == NULL) {
973 free(arr);
974 return(NULL);
977 for (max = 0; arr[max]; max++)
978 continue;
979 max--;
981 if (start == '$')
982 start = max;
983 if (end == '$')
984 end = max;
985 if (end < 0)
986 end = max + end + 1;
987 if (start < 0)
988 start = end;
990 if (start < 0 || end < 0 || start > max || end > max || start > end)
991 return(NULL);
993 for (i = start, len = 0; i <= end; i++)
994 len += strlen(arr[i]) + 1;
995 len++;
996 result = malloc(len);
997 if (result == NULL)
998 return NULL;
1000 for (i = start, len = 0; i <= end; i++) {
1001 (void)strcpy(result + len, arr[i]);
1002 len += strlen(arr[i]);
1003 if (i < end)
1004 result[len++] = ' ';
1006 result[len] = 0;
1008 for (i = 0; arr[i]; i++)
1009 free(arr[i]);
1010 free(arr);
1012 return(result);
1016 * Parse the string into individual tokens,
1017 * similar to how shell would do it.
1019 char **
1020 history_tokenize(const char *str)
1022 int size = 1, idx = 0, i, start;
1023 size_t len;
1024 char **result = NULL, *temp, delim = '\0';
1026 for (i = 0; str[i];) {
1027 while (isspace((unsigned char) str[i]))
1028 i++;
1029 start = i;
1030 for (; str[i];) {
1031 if (str[i] == '\\') {
1032 if (str[i+1] != '\0')
1033 i++;
1034 } else if (str[i] == delim)
1035 delim = '\0';
1036 else if (!delim &&
1037 (isspace((unsigned char) str[i]) ||
1038 strchr("()<>;&|$", str[i])))
1039 break;
1040 else if (!delim && strchr("'`\"", str[i]))
1041 delim = str[i];
1042 if (str[i])
1043 i++;
1046 if (idx + 2 >= size) {
1047 char **nresult;
1048 size <<= 1;
1049 nresult = realloc(result, size * sizeof(char *));
1050 if (nresult == NULL) {
1051 free(result);
1052 return NULL;
1054 result = nresult;
1056 len = i - start;
1057 temp = malloc(len + 1);
1058 if (temp == NULL) {
1059 for (i = 0; i < idx; i++)
1060 free(result[i]);
1061 free(result);
1062 return NULL;
1064 (void)strncpy(temp, &str[start], len);
1065 temp[len] = '\0';
1066 result[idx++] = temp;
1067 result[idx] = NULL;
1068 if (str[i])
1069 i++;
1071 return (result);
1076 * limit size of history record to ``max'' events
1078 void
1079 stifle_history(int max)
1081 HistEvent ev;
1083 if (h == NULL || e == NULL)
1084 rl_initialize();
1086 if (history(h, &ev, H_SETSIZE, max) == 0)
1087 max_input_history = max;
1092 * "unlimit" size of history - set the limit to maximum allowed int value
1095 unstifle_history(void)
1097 HistEvent ev;
1098 int omax;
1100 history(h, &ev, H_SETSIZE, INT_MAX);
1101 omax = max_input_history;
1102 max_input_history = INT_MAX;
1103 return (omax); /* some value _must_ be returned */
1108 history_is_stifled(void)
1111 /* cannot return true answer */
1112 return (max_input_history != INT_MAX);
1117 * read history from a file given
1120 read_history(const char *filename)
1122 HistEvent ev;
1124 if (h == NULL || e == NULL)
1125 rl_initialize();
1126 return (history(h, &ev, H_LOAD, filename) == -1);
1131 * write history to a file given
1134 write_history(const char *filename)
1136 HistEvent ev;
1138 if (h == NULL || e == NULL)
1139 rl_initialize();
1140 return (history(h, &ev, H_SAVE, filename) == -1);
1145 * returns history ``num''th event
1147 * returned pointer points to static variable
1149 HIST_ENTRY *
1150 history_get(int num)
1152 static HIST_ENTRY she;
1153 HistEvent ev;
1154 int curr_num;
1156 if (h == NULL || e == NULL)
1157 rl_initialize();
1159 /* save current position */
1160 if (history(h, &ev, H_CURR) != 0)
1161 return (NULL);
1162 curr_num = ev.num;
1164 /* start from most recent */
1165 if (history(h, &ev, H_FIRST) != 0)
1166 return (NULL); /* error */
1168 /* look backwards for event matching specified offset */
1169 if (history(h, &ev, H_NEXT_EVENT, num))
1170 return (NULL);
1172 she.line = ev.str;
1173 she.data = NULL;
1175 /* restore pointer to where it was */
1176 (void)history(h, &ev, H_SET, curr_num);
1178 return (&she);
1183 * add the line to history table
1186 add_history(const char *line)
1188 HistEvent ev;
1190 if (h == NULL || e == NULL)
1191 rl_initialize();
1193 (void)history(h, &ev, H_ENTER, line);
1194 if (history(h, &ev, H_GETSIZE) == 0)
1195 history_length = ev.num;
1197 return (!(history_length > 0)); /* return 0 if all is okay */
1202 * remove the specified entry from the history list and return it.
1204 HIST_ENTRY *
1205 remove_history(int num)
1207 static HIST_ENTRY she;
1208 HistEvent ev;
1210 if (h == NULL || e == NULL)
1211 rl_initialize();
1213 if (history(h, &ev, H_DEL, num) != 0)
1214 return NULL;
1216 she.line = ev.str;
1217 she.data = NULL;
1219 return &she;
1224 * clear the history list - delete all entries
1226 void
1227 clear_history(void)
1229 HistEvent ev;
1231 history(h, &ev, H_CLEAR);
1236 * returns offset of the current history event
1239 where_history(void)
1241 HistEvent ev;
1242 int curr_num, off;
1244 if (history(h, &ev, H_CURR) != 0)
1245 return (0);
1246 curr_num = ev.num;
1248 history(h, &ev, H_FIRST);
1249 off = 1;
1250 while (ev.num != curr_num && history(h, &ev, H_NEXT) == 0)
1251 off++;
1253 return (off);
1258 * returns current history event or NULL if there is no such event
1260 HIST_ENTRY *
1261 current_history(void)
1264 return (_move_history(H_CURR));
1269 * returns total number of bytes history events' data are using
1272 history_total_bytes(void)
1274 HistEvent ev;
1275 int curr_num, size;
1277 if (history(h, &ev, H_CURR) != 0)
1278 return (-1);
1279 curr_num = ev.num;
1281 history(h, &ev, H_FIRST);
1282 size = 0;
1284 size += strlen(ev.str);
1285 while (history(h, &ev, H_NEXT) == 0);
1287 /* get to the same position as before */
1288 history(h, &ev, H_PREV_EVENT, curr_num);
1290 return (size);
1295 * sets the position in the history list to ``pos''
1298 history_set_pos(int pos)
1300 HistEvent ev;
1301 int curr_num;
1303 if (pos > history_length || pos < 0)
1304 return (-1);
1306 history(h, &ev, H_CURR);
1307 curr_num = ev.num;
1309 if (history(h, &ev, H_SET, pos)) {
1310 history(h, &ev, H_SET, curr_num);
1311 return(-1);
1313 return (0);
1318 * returns previous event in history and shifts pointer accordingly
1320 HIST_ENTRY *
1321 previous_history(void)
1324 return (_move_history(H_PREV));
1329 * returns next event in history and shifts pointer accordingly
1331 HIST_ENTRY *
1332 next_history(void)
1335 return (_move_history(H_NEXT));
1340 * searches for first history event containing the str
1343 history_search(const char *str, int direction)
1345 HistEvent ev;
1346 const char *strp;
1347 int curr_num;
1349 if (history(h, &ev, H_CURR) != 0)
1350 return (-1);
1351 curr_num = ev.num;
1353 for (;;) {
1354 if ((strp = strstr(ev.str, str)) != NULL)
1355 return (int) (strp - ev.str);
1356 if (history(h, &ev, direction < 0 ? H_NEXT:H_PREV) != 0)
1357 break;
1359 history(h, &ev, H_SET, curr_num);
1360 return (-1);
1365 * searches for first history event beginning with str
1368 history_search_prefix(const char *str, int direction)
1370 HistEvent ev;
1372 return (history(h, &ev, direction < 0? H_PREV_STR:H_NEXT_STR, str));
1377 * search for event in history containing str, starting at offset
1378 * abs(pos); continue backward, if pos<0, forward otherwise
1380 /* ARGSUSED */
1382 history_search_pos(const char *str,
1383 int direction __attribute__((__unused__)), int pos)
1385 HistEvent ev;
1386 int curr_num, off;
1388 off = (pos > 0) ? pos : -pos;
1389 pos = (pos > 0) ? 1 : -1;
1391 if (history(h, &ev, H_CURR) != 0)
1392 return (-1);
1393 curr_num = ev.num;
1395 if (history_set_pos(off) != 0 || history(h, &ev, H_CURR) != 0)
1396 return (-1);
1399 for (;;) {
1400 if (strstr(ev.str, str))
1401 return (off);
1402 if (history(h, &ev, (pos < 0) ? H_PREV : H_NEXT) != 0)
1403 break;
1406 /* set "current" pointer back to previous state */
1407 history(h, &ev, (pos < 0) ? H_NEXT_EVENT : H_PREV_EVENT, curr_num);
1409 return (-1);
1413 /********************************/
1414 /* completion functions */
1416 char *
1417 tilde_expand(char *name)
1419 return fn_tilde_expand(name);
1422 char *
1423 filename_completion_function(const char *name, int state)
1425 return fn_filename_completion_function(name, state);
1429 * a completion generator for usernames; returns _first_ username
1430 * which starts with supplied text
1431 * text contains a partial username preceded by random character
1432 * (usually '~'); state is ignored
1433 * it's callers responsibility to free returned value
1435 char *
1436 username_completion_function(const char *text, int state)
1439 For when getpwent_r is supported:
1440 struct passwd *pwd, pwres;
1441 char pwbuf[1024];
1443 struct passwd *pwd;
1444 /* remove the above when getpwend_r is supported */
1446 if (text[0] == '\0')
1447 return (NULL);
1449 if (*text == '~')
1450 text++;
1452 if (state == 0)
1453 setpwent();
1456 For when getpwent_r is supported:
1457 while (getpwent_r(&pwres, pwbuf, sizeof(pwbuf), &pwd) == 0
1458 && pwd != NULL && text[0] == pwd->pw_name[0]
1459 && strcmp(text, pwd->pw_name) == 0);
1461 for (;;) {
1462 pwd = getpwent();
1463 if (pwd != NULL && text[0] == pwd->pw_name[0] && strcmp(text, pwd->pw_name) == 0)
1464 break;
1467 /* remove the above when getpwend_r is supported */
1469 if (pwd == NULL) {
1470 endpwent();
1471 return (NULL);
1473 return (strdup(pwd->pw_name));
1478 * el-compatible wrapper to send TSTP on ^Z
1480 /* ARGSUSED */
1481 static unsigned char
1482 _el_rl_tstp(EditLine *el __attribute__((__unused__)), int ch __attribute__((__unused__)))
1484 (void)kill(0, SIGTSTP);
1485 return CC_NORM;
1489 * Display list of strings in columnar format on readline's output stream.
1490 * 'matches' is list of strings, 'len' is number of strings in 'matches',
1491 * 'max' is maximum length of string in 'matches'.
1493 void
1494 rl_display_match_list(char **matches, int len, int max)
1497 fn_display_match_list(e, matches, len, max);
1500 static const char *
1501 /*ARGSUSED*/
1502 _rl_completion_append_character_function(const char *dummy
1503 __attribute__((__unused__)))
1505 static char buf[2];
1506 buf[1] = rl_completion_append_character;
1507 return buf;
1512 * complete word at current point
1514 /* ARGSUSED */
1516 rl_complete(int ignore __attribute__((__unused__)), int invoking_key)
1518 if (h == NULL || e == NULL)
1519 rl_initialize();
1521 if (rl_inhibit_completion) {
1522 char arr[2];
1523 arr[0] = (char)invoking_key;
1524 arr[1] = '\0';
1525 el_insertstr(e, arr);
1526 return (CC_REFRESH);
1529 /* Just look at how many global variables modify this operation! */
1530 return fn_complete(e,
1531 (CPFunction *)rl_completion_entry_function,
1532 rl_attempted_completion_function,
1533 rl_basic_word_break_characters, rl_special_prefixes,
1534 _rl_completion_append_character_function, rl_completion_query_items,
1535 &rl_completion_type, &rl_attempted_completion_over,
1536 &rl_point, &rl_end);
1540 /* ARGSUSED */
1541 static unsigned char
1542 _el_rl_complete(EditLine *el __attribute__((__unused__)), int ch)
1544 return (unsigned char)rl_complete(0, ch);
1548 * misc other functions
1552 * bind key c to readline-type function func
1555 rl_bind_key(int c, int func(int, int))
1557 int retval = -1;
1559 if (h == NULL || e == NULL)
1560 rl_initialize();
1562 if (func == rl_insert) {
1563 /* XXX notice there is no range checking of ``c'' */
1564 e->el_map.key[c] = ED_INSERT;
1565 retval = 0;
1567 return (retval);
1572 * read one key from input - handles chars pushed back
1573 * to input stream also
1576 rl_read_key(void)
1578 char fooarr[2 * sizeof(int)];
1580 if (e == NULL || h == NULL)
1581 rl_initialize();
1583 return (el_getc(e, fooarr));
1588 * reset the terminal
1590 /* ARGSUSED */
1591 void
1592 rl_reset_terminal(const char *p __attribute__((__unused__)))
1595 if (h == NULL || e == NULL)
1596 rl_initialize();
1597 el_reset(e);
1602 * insert character ``c'' back into input stream, ``count'' times
1605 rl_insert(int count, int c)
1607 char arr[2];
1609 if (h == NULL || e == NULL)
1610 rl_initialize();
1612 /* XXX - int -> char conversion can lose on multichars */
1613 arr[0] = c;
1614 arr[1] = '\0';
1616 for (; count > 0; count--)
1617 el_push(e, arr);
1619 return (0);
1622 /*ARGSUSED*/
1624 rl_newline(int count, int c)
1627 * Readline-4.0 appears to ignore the args.
1629 return rl_insert(1, '\n');
1632 /*ARGSUSED*/
1633 static unsigned char
1634 rl_bind_wrapper(EditLine *el, unsigned char c)
1636 if (map[c] == NULL)
1637 return CC_ERROR;
1639 _rl_update_pos();
1641 (*map[c])(NULL, c);
1643 /* If rl_done was set by the above call, deal with it here */
1644 if (rl_done)
1645 return CC_EOF;
1647 return CC_NORM;
1651 rl_add_defun(const char *name, Function *fun, int c)
1653 char dest[8];
1654 if (c >= sizeof(map) / sizeof(map[0]) || c < 0)
1655 return -1;
1656 map[(unsigned char)c] = fun;
1657 el_set(e, EL_ADDFN, name, name, rl_bind_wrapper);
1658 vis(dest, c, VIS_WHITE|VIS_NOSLASH, 0);
1659 el_set(e, EL_BIND, dest, name);
1660 return 0;
1663 void
1664 rl_callback_read_char()
1666 int count = 0, done = 0;
1667 const char *buf = el_gets(e, &count);
1668 char *wbuf;
1670 if (buf == NULL || count-- <= 0)
1671 return;
1672 if (count == 0 && buf[0] == e->el_tty.t_c[TS_IO][C_EOF])
1673 done = 1;
1674 if (buf[count] == '\n' || buf[count] == '\r')
1675 done = 2;
1677 if (done && rl_linefunc != NULL) {
1678 el_set(e, EL_UNBUFFERED, 0);
1679 if (done == 2) {
1680 if ((wbuf = strdup(buf)) != NULL)
1681 wbuf[count] = '\0';
1682 } else
1683 wbuf = NULL;
1684 (*(void (*)(const char *))rl_linefunc)(wbuf);
1685 el_set(e, EL_UNBUFFERED, 1);
1689 void
1690 rl_callback_handler_install (const char *prompt, VCPFunction *linefunc)
1692 if (e == NULL) {
1693 rl_initialize();
1695 if (rl_prompt)
1696 free(rl_prompt);
1697 rl_prompt = prompt ? strdup(strchr(prompt, *prompt)) : NULL;
1698 rl_linefunc = linefunc;
1699 el_set(e, EL_UNBUFFERED, 1);
1702 void
1703 rl_callback_handler_remove(void)
1705 el_set(e, EL_UNBUFFERED, 0);
1708 void
1709 rl_redisplay(void)
1711 char a[2];
1712 a[0] = e->el_tty.t_c[TS_IO][C_REPRINT];
1713 a[1] = '\0';
1714 el_push(e, a);
1718 rl_get_previous_history(int count, int key)
1720 char a[2];
1721 a[0] = key;
1722 a[1] = '\0';
1723 while (count--)
1724 el_push(e, a);
1725 return 0;
1728 void
1729 /*ARGSUSED*/
1730 rl_prep_terminal(int meta_flag)
1732 el_set(e, EL_PREP_TERM, 1);
1735 void
1736 rl_deprep_terminal(void)
1738 el_set(e, EL_PREP_TERM, 0);
1742 rl_read_init_file(const char *s)
1744 return(el_source(e, s));
1748 rl_parse_and_bind(const char *line)
1750 const char **argv;
1751 int argc;
1752 Tokenizer *tok;
1754 tok = tok_init(NULL);
1755 tok_str(tok, line, &argc, &argv);
1756 argc = el_parse(e, argc, argv);
1757 tok_end(tok);
1758 return (argc ? 1 : 0);
1762 rl_variable_bind(const char *var, const char *value)
1765 * The proper return value is undocument, but this is what the
1766 * readline source seems to do.
1768 return ((el_set(e, EL_BIND, "", var, value) == -1) ? 1 : 0);
1771 void
1772 rl_stuff_char(int c)
1774 char buf[2];
1776 buf[0] = c;
1777 buf[1] = '\0';
1778 el_insertstr(e, buf);
1781 static int
1782 _rl_event_read_char(EditLine *el, char *cp)
1784 int n, num_read = 0;
1786 *cp = 0;
1787 while (rl_event_hook) {
1789 (*rl_event_hook)();
1791 #if defined(FIONREAD)
1792 if (ioctl(el->el_infd, FIONREAD, &n) < 0)
1793 return(-1);
1794 if (n)
1795 num_read = read(el->el_infd, cp, 1);
1796 else
1797 num_read = 0;
1798 #elif defined(F_SETFL) && defined(O_NDELAY)
1799 if ((n = fcntl(el->el_infd, F_GETFL, 0)) < 0)
1800 return(-1);
1801 if (fcntl(el->el_infd, F_SETFL, n|O_NDELAY) < 0)
1802 return(-1);
1803 num_read = read(el->el_infd, cp, 1);
1804 if (fcntl(el->el_infd, F_SETFL, n))
1805 return(-1);
1806 #else
1807 /* not non-blocking, but what you gonna do? */
1808 num_read = read(el->el_infd, cp, 1);
1809 return(-1);
1810 #endif
1812 if (num_read < 0 && errno == EAGAIN)
1813 continue;
1814 if (num_read == 0)
1815 continue;
1816 break;
1818 if (!rl_event_hook)
1819 el_set(el, EL_GETCFN, EL_BUILTIN_GETCFN);
1820 return(num_read);
1823 static void
1824 _rl_update_pos(void)
1826 const LineInfo *li = el_line(e);
1828 rl_point = li->cursor - li->buffer;
1829 rl_end = li->lastchar - li->buffer;
1832 void
1833 rl_get_screen_size(int *rows, int *cols)
1835 if (rows)
1836 el_get(e, EL_GETTC, "li", rows);
1837 if (cols)
1838 el_get(e, EL_GETTC, "co", cols);
1841 void
1842 rl_set_screen_size(int rows, int cols)
1844 char buf[64];
1845 (void)snprintf(buf, sizeof(buf), "%d", rows);
1846 el_set(e, EL_SETTC, "li", buf);
1847 (void)snprintf(buf, sizeof(buf), "%d", cols);
1848 el_set(e, EL_SETTC, "co", buf);
1851 char *
1852 rl_filename_completion_function (const char *text, int state)
1854 return fn_filename_completion_function(text, state);
1858 _rl_abort_internal(void)
1860 el_beep(e);
1861 longjmp(topbuf, 1);
1862 /*NOTREACHED*/
1866 _rl_qsort_string_compare(char **s1, char **s2)
1868 return strcoll(*s1, *s2);
1872 /*ARGSUSED*/
1873 rl_kill_text(int from, int to)
1875 return 0;
1878 Keymap
1879 rl_make_bare_keymap(void)
1881 return NULL;
1884 Keymap
1885 rl_get_keymap(void)
1887 return NULL;
1890 void
1891 /*ARGSUSED*/
1892 rl_set_keymap(Keymap k)
1897 /*ARGSUSED*/
1898 rl_generic_bind(int type, const char * keyseq, const char * data, Keymap k)
1900 return 0;
1904 /*ARGSUSED*/
1905 rl_bind_key_in_map(int key, Function *fun, Keymap k)
1907 return 0;