2 * Copyright (c) 1997 The NetBSD Foundation, Inc.
5 * This code is derived from software contributed to The NetBSD Foundation
8 * Redistribution and use in source and binary forms, with or without
9 * modification, are permitted provided that the following conditions
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.
17 * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
18 * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
19 * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
20 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
21 * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
22 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
23 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
24 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
25 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
26 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
27 * POSSIBILITY OF SUCH DAMAGE.
29 * $NetBSD: readline.c,v 1.75 2008/04/29 06:53:01 martin Exp $
30 * $DragonFly: src/lib/libedit/readline.c,v 1.5 2008/09/30 16:57:05 swildner Exp $
35 #include <sys/types.h>
57 #include "fcns.h" /* for EL_NUM_FCNS */
59 #include "readline/readline.h"
60 #include "filecomplete.h"
62 void rl_prep_terminal(int);
63 void rl_deprep_terminal(void);
65 /* for rl_complete() */
68 /* see comment at the #ifdef for sense of this */
69 /* #define GDB_411_HACK */
71 /* readline compatibility stuff - look at readline sources/documentation */
72 /* to see what these variables mean */
73 const char *rl_library_version = "EditLine wrapper";
74 static char empty[] = { '\0' };
75 static char expand_chars[] = { ' ', '\t', '\n', '=', '(', '\0' };
76 static char break_chars[] = { ' ', '\t', '\n', '"', '\\', '\'', '`', '@', '$',
77 '>', '<', '=', ';', '|', '&', '{', '(', '\0' };
78 char *rl_readline_name = empty;
79 FILE *rl_instream = NULL;
80 FILE *rl_outstream = NULL;
83 char *rl_line_buffer = NULL;
84 VCPFunction *rl_linefunc = NULL;
86 VFunction *rl_event_hook = NULL;
87 KEYMAP_ENTRY_ARRAY emacs_standard_keymap,
91 int history_base = 1; /* probably never subject to change */
92 int history_length = 0;
93 int max_input_history = 0;
94 char history_expansion_char = '!';
95 char history_subst_char = '^';
96 char *history_no_expand_chars = expand_chars;
97 Function *history_inhibit_expansion_function = NULL;
98 char *history_arg_extract(int start, int end, const char *str);
100 int rl_inhibit_completion = 0;
101 int rl_attempted_completion_over = 0;
102 char *rl_basic_word_break_characters = break_chars;
103 char *rl_completer_word_break_characters = NULL;
104 char *rl_completer_quote_characters = NULL;
105 Function *rl_completion_entry_function = NULL;
106 CPPFunction *rl_attempted_completion_function = NULL;
107 Function *rl_pre_input_hook = NULL;
108 Function *rl_startup1_hook = NULL;
109 int (*rl_getc_function)(FILE *) = NULL;
110 char *rl_terminal_name = NULL;
111 int rl_already_prompted = 0;
112 int rl_filename_completion_desired = 0;
113 int rl_ignore_completion_duplicates = 0;
114 int rl_catch_signals = 1;
115 int readline_echoing_p = 1;
116 int _rl_print_completions_horizontally = 0;
117 VFunction *rl_redisplay_function = NULL;
118 Function *rl_startup_hook = NULL;
119 VFunction *rl_completion_display_matches_hook = NULL;
120 VFunction *rl_prep_term_function = (VFunction *)rl_prep_terminal;
121 VFunction *rl_deprep_term_function = (VFunction *)rl_deprep_terminal;
124 * The current prompt string.
126 char *rl_prompt = NULL;
128 * This is set to character indicating type of completion being done by
129 * rl_complete_internal(); this is available for application completion
132 int rl_completion_type = 0;
135 * If more than this number of items results from query for possible
136 * completions, we ask user if they are sure to really display the list.
138 int rl_completion_query_items = 100;
141 * List of characters which are word break characters, but should be left
142 * in the parsed text when it is passed to the completion function.
143 * Shell uses this to help determine what kind of completing to do.
145 char *rl_special_prefixes = NULL;
148 * This is the character appended to the completed words if at the end of
149 * the line. Default is ' ' (a space).
151 int rl_completion_append_character = ' ';
153 /* stuff below is used internally by libedit for readline emulation */
155 static History *h = NULL;
156 static EditLine *e = NULL;
157 static Function *map[256];
158 static jmp_buf topbuf;
160 /* internal functions */
161 static unsigned char _el_rl_complete(EditLine *, int);
162 static unsigned char _el_rl_tstp(EditLine *, int);
163 static char *_get_prompt(EditLine *);
164 static int _getc_function(EditLine *, char *);
165 static HIST_ENTRY *_move_history(int);
166 static int _history_expand_command(const char *, size_t, size_t,
168 static char *_rl_compat_sub(const char *, const char *,
170 static int _rl_event_read_char(EditLine *, char *);
171 static void _rl_update_pos(void);
176 _get_prompt(EditLine *el __attribute__((__unused__)))
178 rl_already_prompted = 1;
184 * generic function for moving around history
187 _move_history(int op)
190 static HIST_ENTRY rl_he;
192 if (history(h, &ev, op) != 0)
193 return (HIST_ENTRY *) NULL;
203 * read one key from user defined input function
207 _getc_function(EditLine *el, char *c)
211 i = (*rl_getc_function)(NULL);
220 * READLINE compatibility stuff
224 * initialize rl compat stuff
242 rl_outstream = stdout;
245 * See if we don't really want to run the editor
247 if (tcgetattr(fileno(rl_instream), &t) != -1 && (t.c_lflag & ECHO) == 0)
250 e = el_init(rl_readline_name, rl_instream, rl_outstream, stderr);
253 el_set(e, EL_EDITMODE, 0);
259 history(h, &ev, H_SETSIZE, INT_MAX); /* unlimited */
261 max_input_history = INT_MAX;
262 el_set(e, EL_HIST, history, h);
264 /* setup getc function if valid */
265 if (rl_getc_function)
266 el_set(e, EL_GETCFN, _getc_function);
268 /* for proper prompt printing in readline() */
269 rl_prompt = strdup("");
270 if (rl_prompt == NULL) {
275 el_set(e, EL_PROMPT, _get_prompt);
276 el_set(e, EL_SIGNAL, rl_catch_signals);
278 /* set default mode to "emacs"-style and read setting afterwards */
279 /* so this can be overriden */
280 el_set(e, EL_EDITOR, "emacs");
281 if (rl_terminal_name != NULL)
282 el_set(e, EL_TERMINAL, rl_terminal_name);
284 el_get(e, EL_TERMINAL, &rl_terminal_name);
287 * Word completion - this has to go AFTER rebinding keys
290 el_set(e, EL_ADDFN, "rl_complete",
291 "ReadLine compatible completion function",
293 el_set(e, EL_BIND, "^I", "rl_complete", NULL);
296 * Send TSTP when ^Z is pressed.
298 el_set(e, EL_ADDFN, "rl_tstp",
299 "ReadLine compatible suspend function",
301 el_set(e, EL_BIND, "^Z", "rl_tstp", NULL);
303 /* read settings from configuration file */
307 * Unfortunately, some applications really do use rl_point
308 * and rl_line_buffer directly.
311 /* a cheesy way to get rid of const cast. */
312 rl_line_buffer = memchr(li->buffer, *li->buffer, 1);
316 (*rl_startup_hook)(NULL, 0);
323 * read one line from input stream and return it, chomping
324 * trailing newline (if there is any)
327 readline(const char *p)
330 const char * volatile prompt = p;
334 static int used_event_hook;
336 if (e == NULL || h == NULL)
341 (void)setjmp(topbuf);
343 /* update prompt accordingly to what has been passed */
346 if (strcmp(rl_prompt, prompt) != 0) {
348 rl_prompt = strdup(prompt);
349 if (rl_prompt == NULL)
353 if (rl_pre_input_hook)
354 (*rl_pre_input_hook)(NULL, 0);
356 if (rl_event_hook && !(e->el_flags&NO_TTY)) {
357 el_set(e, EL_GETCFN, _rl_event_read_char);
361 if (!rl_event_hook && used_event_hook) {
362 el_set(e, EL_GETCFN, EL_BUILTIN_GETCFN);
366 rl_already_prompted = 0;
368 /* get one line from input stream */
369 ret = el_gets(e, &count);
371 if (ret && count > 0) {
378 if (buf[lastidx] == '\n')
383 history(h, &ev, H_GETSIZE);
384 history_length = ev.num;
394 * is normally called before application starts to use
395 * history expansion functions
400 if (h == NULL || e == NULL)
406 * substitute ``what'' with ``with'', returning resulting string; if
407 * globally == 1, substitutes all occurrences of what, otherwise only the
411 _rl_compat_sub(const char *str, const char *what, const char *with,
416 size_t len, with_len, what_len;
419 with_len = strlen(with);
420 what_len = strlen(what);
422 /* calculate length we need for result */
425 if (*s == *what && !strncmp(s, what, what_len)) {
426 len += with_len - what_len;
433 r = result = malloc(len + 1);
438 if (*s == *what && !strncmp(s, what, what_len)) {
439 (void)strncpy(r, with, with_len);
453 static char *last_search_pat; /* last !?pat[?] search pattern */
454 static char *last_search_match; /* last !?pat[?] that matched */
457 get_history_event(const char *cmd, int *cindex, int qchar)
459 int idx, sign, sub, num, begin, ret;
466 if (cmd[idx++] != history_expansion_char)
469 /* find out which event to take */
470 if (cmd[idx] == history_expansion_char || cmd[idx] == 0) {
471 if (history(h, &ev, H_FIRST) != 0)
473 *cindex = cmd[idx]? (idx + 1):idx;
477 if (cmd[idx] == '-') {
482 if ('0' <= cmd[idx] && cmd[idx] <= '9') {
486 while (cmd[idx] && '0' <= cmd[idx] && cmd[idx] <= '9') {
487 num = num * 10 + cmd[idx] - '0';
491 num = history_length - num + 1;
493 if (!(rl_he = history_get(num)))
500 if (cmd[idx] == '?') {
506 if (cmd[idx] == '\n')
508 if (sub && cmd[idx] == '?')
510 if (!sub && (cmd[idx] == ':' || cmd[idx] == ' '
511 || cmd[idx] == '\t' || cmd[idx] == qchar))
516 if (sub && cmd[idx] == '?')
518 if (sub && len == 0 && last_search_pat && *last_search_pat)
519 pat = last_search_pat;
523 if ((pat = malloc(len + 1)) == NULL)
525 (void)strncpy(pat, cmd + begin, len);
529 if (history(h, &ev, H_CURR) != 0) {
530 if (pat != last_search_pat)
537 if (pat != last_search_pat) {
539 free(last_search_pat);
540 last_search_pat = pat;
542 ret = history_search(pat, -1);
544 ret = history_search_prefix(pat, -1);
547 /* restore to end of list on failed search */
548 history(h, &ev, H_FIRST);
549 (void)fprintf(rl_outstream, "%s: Event not found\n", pat);
550 if (pat != last_search_pat)
556 if (last_search_match && last_search_match != pat)
557 free(last_search_match);
558 last_search_match = pat;
561 if (pat != last_search_pat)
564 if (history(h, &ev, H_CURR) != 0)
569 /* roll back to original position */
570 (void)history(h, &ev, H_SET, num);
576 * the real function doing history expansion - takes as argument command
577 * to do and data upon which the command should be executed
578 * does expansion the way I've understood readline documentation
580 * returns 0 if data was not modified, 1 if it was and 2 if the string
581 * should be only printed and not executed; in case of error,
582 * returns -1 and *result points to NULL
583 * it's callers responsibility to free() string returned in *result
586 _history_expand_command(const char *command, size_t offs, size_t cmdlen,
589 char *tmp, *search = NULL, *aptr;
590 const char *ptr, *cmd;
591 static char *from = NULL, *to = NULL;
592 int start, end, idx, has_mods = 0;
593 int p_on = 0, g_on = 0;
599 /* First get event specifier */
602 if (strchr(":^*$", command[offs + 1])) {
605 * "!:" is shorthand for "!!:".
606 * "!^", "!*" and "!$" are shorthand for
607 * "!!:^", "!!:*" and "!!:$" respectively.
609 str[0] = str[1] = '!';
611 ptr = get_history_event(str, &idx, 0);
612 idx = (command[offs + 1] == ':')? 1:0;
615 if (command[offs + 1] == '#') {
616 /* use command so far */
617 if ((aptr = malloc(offs + 1)) == NULL)
619 (void)strncpy(aptr, command, offs);
625 qchar = (offs > 0 && command[offs - 1] == '"')? '"':0;
626 ptr = get_history_event(command + offs, &idx, qchar);
628 has_mods = command[offs + idx] == ':';
631 if (ptr == NULL && aptr == NULL)
635 *result = strdup(aptr? aptr : ptr);
641 cmd = command + offs + idx + 1;
643 /* Now parse any word designators */
645 if (*cmd == '%') /* last word matched by ?pat? */
646 tmp = strdup(last_search_match? last_search_match:"");
647 else if (strchr("^*$-0123456789", *cmd)) {
650 start = end = 1, cmd++;
651 else if (*cmd == '$')
653 else if (*cmd == '*')
655 else if (*cmd == '-' || isdigit((unsigned char) *cmd)) {
657 while (*cmd && '0' <= *cmd && *cmd <= '9')
658 start = start * 10 + *cmd++ - '0';
661 if (isdigit((unsigned char) cmd[1])) {
664 while (*cmd && '0' <= *cmd && *cmd <= '9')
665 end = end * 10 + *cmd++ - '0';
666 } else if (cmd[1] == '$') {
673 } else if (*cmd == '*')
678 tmp = history_arg_extract(start, end, aptr? aptr:ptr);
680 (void)fprintf(rl_outstream, "%s: Bad word specifier",
681 command + offs + idx);
687 tmp = strdup(aptr? aptr:ptr);
692 if (*cmd == 0 || (cmd - (command + offs) >= cmdlen)) {
697 for (; *cmd; cmd++) {
700 else if (*cmd == 'h') { /* remove trailing path */
701 if ((aptr = strrchr(tmp, '/')) != NULL)
703 } else if (*cmd == 't') { /* remove leading path */
704 if ((aptr = strrchr(tmp, '/')) != NULL) {
705 aptr = strdup(aptr + 1);
709 } else if (*cmd == 'r') { /* remove trailing suffix */
710 if ((aptr = strrchr(tmp, '.')) != NULL)
712 } else if (*cmd == 'e') { /* remove all but suffix */
713 if ((aptr = strrchr(tmp, '.')) != NULL) {
718 } else if (*cmd == 'p') /* print only */
720 else if (*cmd == 'g')
722 else if (*cmd == 's' || *cmd == '&') {
723 char *what, *with, delim;
724 size_t len, from_len;
727 if (*cmd == '&' && (from == NULL || to == NULL))
729 else if (*cmd == 's') {
730 delim = *(++cmd), cmd++;
732 what = realloc(from, size);
739 for (; *cmd && *cmd != delim; cmd++) {
740 if (*cmd == '\\' && cmd[1] == delim)
744 nwhat = realloc(what,
760 from = strdup(search);
771 cmd++; /* shift after delim */
776 with = realloc(to, size);
783 from_len = strlen(from);
784 for (; *cmd && *cmd != delim; cmd++) {
785 if (len + from_len + 1 >= size) {
787 size += from_len + 1;
788 nwith = realloc(with, size);
798 (void)strcpy(&with[len], from);
803 && (*(cmd + 1) == delim
804 || *(cmd + 1) == '&'))
812 aptr = _rl_compat_sub(tmp, from, to, g_on);
826 * csh-style history expansion
829 history_expand(char *str, char **output)
835 if (h == NULL || e == NULL)
838 if (history_expansion_char == 0) {
839 *output = strdup(str);
844 if (str[0] == history_subst_char) {
845 /* ^foo^foo2^ is equivalent to !!:s^foo^foo2^ */
846 *output = malloc(strlen(str) + 4 + 1);
849 (*output)[0] = (*output)[1] = history_expansion_char;
852 (void)strcpy((*output) + 4, str);
855 *output = strdup(str);
860 #define ADD_STRING(what, len, fr) \
862 if (idx + len + 1 > size) { \
863 char *nresult = realloc(result, (size += len + 1));\
864 if (nresult == NULL) { \
866 if (/*CONSTCOND*/fr) \
872 (void)strncpy(&result[idx], what, len); \
874 result[idx] = '\0'; \
880 for (i = 0; str[i];) {
881 int qchar, loop_again;
882 size_t len, start, j;
888 for (; str[j]; j++) {
889 if (str[j] == '\\' &&
890 str[j + 1] == history_expansion_char) {
891 (void)strcpy(&str[j], &str[j + 1]);
895 if (isspace((unsigned char) str[j])
899 if (str[j] == history_expansion_char
900 && !strchr(history_no_expand_chars, str[j + 1])
901 && (!history_inhibit_expansion_function ||
902 (*history_inhibit_expansion_function)(str,
907 if (str[j] && loop_again) {
909 qchar = (j > 0 && str[j - 1] == '"' )? '"':0;
911 if (str[j] == history_expansion_char)
917 ADD_STRING(&str[start], len, 0);
919 if (str[i] == '\0' || str[i] != history_expansion_char) {
921 ADD_STRING(&str[i], len, 0);
928 ret = _history_expand_command (str, i, (j - i), &tmp);
929 if (ret > 0 && tmp) {
931 ADD_STRING(tmp, len, 1);
940 /* ret is 2 for "print only" option */
944 /* gdb 4.11 has been shipped with readline, where */
945 /* history_expand() returned -1 when the line */
946 /* should not be executed; in readline 2.1+ */
947 /* it should return 2 in such a case */
958 * Return a string consisting of arguments of "str" from "start" to "end".
961 history_arg_extract(int start, int end, const char *str)
966 arr = history_tokenize(str);
969 if (arr && *arr == NULL) {
974 for (max = 0; arr[max]; max++)
987 if (start < 0 || end < 0 || start > max || end > max || start > end)
990 for (i = start, len = 0; i <= end; i++)
991 len += strlen(arr[i]) + 1;
993 result = malloc(len);
997 for (i = start, len = 0; i <= end; i++) {
998 (void)strcpy(result + len, arr[i]);
999 len += strlen(arr[i]);
1001 result[len++] = ' ';
1005 for (i = 0; arr[i]; i++)
1013 * Parse the string into individual tokens,
1014 * similar to how shell would do it.
1017 history_tokenize(const char *str)
1019 int size = 1, idx = 0, i, start;
1021 char **result = NULL, *temp, delim = '\0';
1023 for (i = 0; str[i];) {
1024 while (isspace((unsigned char) str[i]))
1028 if (str[i] == '\\') {
1029 if (str[i+1] != '\0')
1031 } else if (str[i] == delim)
1034 (isspace((unsigned char) str[i]) ||
1035 strchr("()<>;&|$", str[i])))
1037 else if (!delim && strchr("'`\"", str[i]))
1043 if (idx + 2 >= size) {
1046 nresult = realloc(result, size * sizeof(char *));
1047 if (nresult == NULL) {
1054 temp = malloc(len + 1);
1056 for (i = 0; i < idx; i++)
1061 (void)strncpy(temp, &str[start], len);
1063 result[idx++] = temp;
1073 * limit size of history record to ``max'' events
1076 stifle_history(int max)
1080 if (h == NULL || e == NULL)
1083 if (history(h, &ev, H_SETSIZE, max) == 0)
1084 max_input_history = max;
1089 * "unlimit" size of history - set the limit to maximum allowed int value
1092 unstifle_history(void)
1097 history(h, &ev, H_SETSIZE, INT_MAX);
1098 omax = max_input_history;
1099 max_input_history = INT_MAX;
1100 return (omax); /* some value _must_ be returned */
1105 history_is_stifled(void)
1108 /* cannot return true answer */
1109 return (max_input_history != INT_MAX);
1114 * read history from a file given
1117 read_history(const char *filename)
1121 if (h == NULL || e == NULL)
1123 return (history(h, &ev, H_LOAD, filename) == -1);
1128 * write history to a file given
1131 write_history(const char *filename)
1135 if (h == NULL || e == NULL)
1137 return (history(h, &ev, H_SAVE, filename) == -1);
1142 * returns history ``num''th event
1144 * returned pointer points to static variable
1147 history_get(int num)
1149 static HIST_ENTRY she;
1153 if (h == NULL || e == NULL)
1156 /* save current position */
1157 if (history(h, &ev, H_CURR) != 0)
1161 /* start from most recent */
1162 if (history(h, &ev, H_FIRST) != 0)
1163 return (NULL); /* error */
1165 /* look backwards for event matching specified offset */
1166 if (history(h, &ev, H_NEXT_EVENT, num + 1))
1172 /* restore pointer to where it was */
1173 (void)history(h, &ev, H_SET, curr_num);
1180 * add the line to history table
1183 add_history(const char *line)
1187 if (h == NULL || e == NULL)
1190 (void)history(h, &ev, H_ENTER, line);
1191 if (history(h, &ev, H_GETSIZE) == 0)
1192 history_length = ev.num;
1194 return (!(history_length > 0)); /* return 0 if all is okay */
1199 * remove the specified entry from the history list and return it.
1202 remove_history(int num)
1207 if (h == NULL || e == NULL)
1210 if (history(h, &ev, H_DEL, num) != 0)
1213 if ((she = malloc(sizeof(*she))) == NULL)
1224 * clear the history list - delete all entries
1231 history(h, &ev, H_CLEAR);
1236 * returns offset of the current history event
1244 if (history(h, &ev, H_CURR) != 0)
1248 history(h, &ev, H_FIRST);
1250 while (ev.num != curr_num && history(h, &ev, H_NEXT) == 0)
1258 * returns current history event or NULL if there is no such event
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)
1277 if (history(h, &ev, H_CURR) != 0)
1281 history(h, &ev, H_FIRST);
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);
1295 * sets the position in the history list to ``pos''
1298 history_set_pos(int pos)
1303 if (pos > history_length || pos < 0)
1306 history(h, &ev, H_CURR);
1309 if (history(h, &ev, H_SET, pos)) {
1310 history(h, &ev, H_SET, curr_num);
1318 * returns previous event in history and shifts pointer accordingly
1321 previous_history(void)
1324 return (_move_history(H_PREV));
1329 * returns next event in history and shifts pointer accordingly
1335 return (_move_history(H_NEXT));
1340 * searches for first history event containing the str
1343 history_search(const char *str, int direction)
1349 if (history(h, &ev, H_CURR) != 0)
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)
1359 history(h, &ev, H_SET, curr_num);
1365 * searches for first history event beginning with str
1368 history_search_prefix(const char *str, int direction)
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
1382 history_search_pos(const char *str,
1383 int direction __attribute__((__unused__)), int pos)
1388 off = (pos > 0) ? pos : -pos;
1389 pos = (pos > 0) ? 1 : -1;
1391 if (history(h, &ev, H_CURR) != 0)
1395 if (history_set_pos(off) != 0 || history(h, &ev, H_CURR) != 0)
1400 if (strstr(ev.str, str))
1402 if (history(h, &ev, (pos < 0) ? H_PREV : H_NEXT) != 0)
1406 /* set "current" pointer back to previous state */
1407 history(h, &ev, (pos < 0) ? H_NEXT_EVENT : H_PREV_EVENT, curr_num);
1413 /********************************/
1414 /* completion functions */
1417 tilde_expand(char *name)
1419 return fn_tilde_expand(name);
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
1436 username_completion_function(const char *text, int state)
1439 For when getpwent_r is supported:
1440 struct passwd *pwd, pwres;
1444 /* remove the above when getpwend_r is supported */
1446 if (text[0] == '\0')
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);
1463 if (pwd != NULL && text[0] == pwd->pw_name[0] && strcmp(text, pwd->pw_name) == 0)
1467 /* remove the above when getpwend_r is supported */
1473 return (strdup(pwd->pw_name));
1478 * el-compatible wrapper to send TSTP on ^Z
1481 static unsigned char
1482 _el_rl_tstp(EditLine *el __attribute__((__unused__)), int ch __attribute__((__unused__)))
1484 (void)kill(0, SIGTSTP);
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'.
1494 rl_display_match_list(char **matches, int len, int max)
1497 fn_display_match_list(e, matches, len, max);
1502 _rl_completion_append_character_function(const char *dummy
1503 __attribute__((__unused__)))
1506 buf[1] = rl_completion_append_character;
1512 * complete word at current point
1516 rl_complete(int ignore __attribute__((__unused__)), int invoking_key)
1518 if (h == NULL || e == NULL)
1521 if (rl_inhibit_completion) {
1523 arr[0] = (char)invoking_key;
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);
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))
1559 if (h == NULL || e == NULL)
1562 if (func == rl_insert) {
1563 /* XXX notice there is no range checking of ``c'' */
1564 e->el_map.key[c] = ED_INSERT;
1572 * read one key from input - handles chars pushed back
1573 * to input stream also
1578 char fooarr[2 * sizeof(int)];
1580 if (e == NULL || h == NULL)
1583 return (el_getc(e, fooarr));
1588 * reset the terminal
1592 rl_reset_terminal(const char *p __attribute__((__unused__)))
1595 if (h == NULL || e == NULL)
1602 * insert character ``c'' back into input stream, ``count'' times
1605 rl_insert(int count, int c)
1609 if (h == NULL || e == NULL)
1612 /* XXX - int -> char conversion can lose on multichars */
1616 for (; count > 0; count--)
1624 rl_newline(int count, int c)
1627 * Readline-4.0 appears to ignore the args.
1629 return rl_insert(1, '\n');
1633 static unsigned char
1634 rl_bind_wrapper(EditLine *el, unsigned char c)
1643 /* If rl_done was set by the above call, deal with it here */
1651 rl_add_defun(const char *name, Function *fun, int c)
1654 if (c >= sizeof(map) / sizeof(map[0]) || c < 0)
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);
1664 rl_callback_read_char(void)
1666 int count = 0, done = 0;
1667 const char *buf = el_gets(e, &count);
1670 if (buf == NULL || count-- <= 0)
1672 if (count == 0 && buf[0] == e->el_tty.t_c[TS_IO][C_EOF])
1674 if (buf[count] == '\n' || buf[count] == '\r')
1677 if (done && rl_linefunc != NULL) {
1678 el_set(e, EL_UNBUFFERED, 0);
1680 if ((wbuf = strdup(buf)) != NULL)
1684 (*(void (*)(const char *))rl_linefunc)(wbuf);
1685 el_set(e, EL_UNBUFFERED, 1);
1690 rl_callback_handler_install(const char *prompt, VCPFunction *linefunc)
1697 rl_prompt = prompt ? strdup(strchr(prompt, *prompt)) : NULL;
1698 rl_linefunc = linefunc;
1699 el_set(e, EL_UNBUFFERED, 1);
1703 rl_callback_handler_remove(void)
1705 el_set(e, EL_UNBUFFERED, 0);
1713 a[0] = e->el_tty.t_c[TS_IO][C_REPRINT];
1719 rl_get_previous_history(int count, int key)
1731 rl_prep_terminal(int meta_flag)
1733 el_set(e, EL_PREP_TERM, 1);
1737 rl_deprep_terminal(void)
1739 el_set(e, EL_PREP_TERM, 0);
1743 rl_read_init_file(const char *s)
1745 return(el_source(e, s));
1749 rl_parse_and_bind(const char *line)
1755 tok = tok_init(NULL);
1756 tok_str(tok, line, &argc, &argv);
1757 argc = el_parse(e, argc, argv);
1759 return (argc ? 1 : 0);
1763 rl_variable_bind(const char *var, const char *value)
1766 * The proper return value is undocument, but this is what the
1767 * readline source seems to do.
1769 return ((el_set(e, EL_BIND, "", var, value) == -1) ? 1 : 0);
1773 rl_stuff_char(int c)
1779 el_insertstr(e, buf);
1783 _rl_event_read_char(EditLine *el, char *cp)
1785 int n, num_read = 0;
1788 while (rl_event_hook) {
1792 #if defined(FIONREAD)
1793 if (ioctl(el->el_infd, FIONREAD, &n) < 0)
1796 num_read = read(el->el_infd, cp, 1);
1799 #elif defined(F_SETFL) && defined(O_NDELAY)
1800 if ((n = fcntl(el->el_infd, F_GETFL, 0)) < 0)
1802 if (fcntl(el->el_infd, F_SETFL, n|O_NDELAY) < 0)
1804 num_read = read(el->el_infd, cp, 1);
1805 if (fcntl(el->el_infd, F_SETFL, n))
1808 /* not non-blocking, but what you gonna do? */
1809 num_read = read(el->el_infd, cp, 1);
1813 if (num_read < 0 && errno == EAGAIN)
1820 el_set(el, EL_GETCFN, EL_BUILTIN_GETCFN);
1825 _rl_update_pos(void)
1827 const LineInfo *li = el_line(e);
1829 rl_point = li->cursor - li->buffer;
1830 rl_end = li->lastchar - li->buffer;
1834 rl_get_screen_size(int *rows, int *cols)
1837 el_get(e, EL_GETTC, "li", rows);
1839 el_get(e, EL_GETTC, "co", cols);
1843 rl_set_screen_size(int rows, int cols)
1846 (void)snprintf(buf, sizeof(buf), "%d", rows);
1847 el_set(e, EL_SETTC, "li", buf);
1848 (void)snprintf(buf, sizeof(buf), "%d", cols);
1849 el_set(e, EL_SETTC, "co", buf);
1853 rl_completion_matches(const char *str, rl_compentry_func_t *fun)
1855 size_t len, max, i, j, min;
1856 char **list, *match, *a, *b;
1860 if ((list = malloc(max * sizeof(*list))) == NULL)
1863 while ((match = (*fun)(str, (int)(len - 1))) != NULL) {
1867 if ((nl = realloc(list, max * sizeof(*nl))) == NULL)
1871 list[len++] = match;
1877 if ((list[0] = strdup(list[1])) == NULL)
1881 qsort(&list[1], len - 1, sizeof(*list),
1882 (int (*)(const void *, const void *)) strcmp);
1884 for (i = 1, a = list[i]; i < len - 1; i++, a = b) {
1886 for (j = 0; a[j] && a[j] == b[j]; j++)
1891 if (min == 0 && *str) {
1892 if ((list[0] = strdup(str)) == NULL)
1895 if ((list[0] = malloc(min + 1)) == NULL)
1897 (void)memcpy(list[0], list[1], min);
1898 list[0][min] = '\0';
1908 rl_filename_completion_function (const char *text, int state)
1910 return fn_filename_completion_function(text, state);
1914 rl_forced_update_display(void)
1916 el_set(e, EL_REFRESH);
1920 _rl_abort_internal(void)
1928 _rl_qsort_string_compare(char **s1, char **s2)
1930 return strcoll(*s1, *s2);
1935 rl_kill_text(int from, int to)
1941 rl_make_bare_keymap(void)
1954 rl_set_keymap(Keymap k)
1960 rl_generic_bind(int type, const char * keyseq, const char * data, Keymap k)
1967 rl_bind_key_in_map(int key, Function *fun, Keymap k)