1 /* $NetBSD: readline.c,v 1.139 2016/10/28 18:32:26 christos Exp $ */
4 * Copyright (c) 1997 The NetBSD Foundation, Inc.
7 * This code is derived from software contributed to The NetBSD Foundation
10 * Redistribution and use in source and binary forms, with or without
11 * modification, are permitted provided that the following conditions
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.
19 * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
20 * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
21 * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
22 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
23 * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
24 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
25 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
26 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
27 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
28 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
29 * POSSIBILITY OF SUCH DAMAGE.
33 #if !defined(lint) && !defined(SCCSID)
34 __RCSID("$NetBSD: readline.c,v 1.139 2016/10/28 18:32:26 christos Exp $");
35 #endif /* not lint && not SCCSID */
39 #include <sys/types.h>
54 #include "readline/readline.h"
57 #include "filecomplete.h"
59 void rl_prep_terminal(int);
60 void rl_deprep_terminal(void);
62 /* for rl_complete() */
65 /* see comment at the #ifdef for sense of this */
66 /* #define GDB_411_HACK */
68 /* readline compatibility stuff - look at readline sources/documentation */
69 /* to see what these variables mean */
70 const char *rl_library_version = "EditLine wrapper";
71 int rl_readline_version = RL_READLINE_VERSION;
72 static char empty[] = { '\0' };
73 static char expand_chars[] = { ' ', '\t', '\n', '=', '(', '\0' };
74 static char break_chars[] = { ' ', '\t', '\n', '"', '\\', '\'', '`', '@', '$',
75 '>', '<', '=', ';', '|', '&', '{', '(', '\0' };
76 char *rl_readline_name = empty;
77 FILE *rl_instream = NULL;
78 FILE *rl_outstream = NULL;
81 char *rl_line_buffer = NULL;
82 rl_vcpfunc_t *rl_linefunc = NULL;
84 VFunction *rl_event_hook = NULL;
85 KEYMAP_ENTRY_ARRAY emacs_standard_keymap,
89 * The following is not implemented; we always catch signals in the
90 * libedit fashion: set handlers on entry to el_gets() and clear them
91 * on the way out. This simplistic approach works for most cases; if
92 * it does not work for your application, please let us know.
94 int rl_catch_signals = 1;
95 int rl_catch_sigwinch = 1;
97 int history_base = 1; /* probably never subject to change */
98 int history_length = 0;
99 int history_offset = 0;
100 int max_input_history = 0;
101 char history_expansion_char = '!';
102 char history_subst_char = '^';
103 char *history_no_expand_chars = expand_chars;
104 Function *history_inhibit_expansion_function = NULL;
105 char *history_arg_extract(int start, int end, const char *str);
107 int rl_inhibit_completion = 0;
108 int rl_attempted_completion_over = 0;
109 char *rl_basic_word_break_characters = break_chars;
110 char *rl_completer_word_break_characters = NULL;
111 char *rl_completer_quote_characters = NULL;
112 rl_compentry_func_t *rl_completion_entry_function = NULL;
113 char *(*rl_completion_word_break_hook)(void) = NULL;
114 rl_completion_func_t *rl_attempted_completion_function = NULL;
115 Function *rl_pre_input_hook = NULL;
116 Function *rl_startup1_hook = NULL;
117 int (*rl_getc_function)(FILE *) = NULL;
118 char *rl_terminal_name = NULL;
119 int rl_already_prompted = 0;
120 int rl_filename_completion_desired = 0;
121 int rl_ignore_completion_duplicates = 0;
122 int readline_echoing_p = 1;
123 int _rl_print_completions_horizontally = 0;
124 VFunction *rl_redisplay_function = NULL;
125 Function *rl_startup_hook = NULL;
126 VFunction *rl_completion_display_matches_hook = NULL;
127 VFunction *rl_prep_term_function = (VFunction *)rl_prep_terminal;
128 VFunction *rl_deprep_term_function = (VFunction *)rl_deprep_terminal;
129 KEYMAP_ENTRY_ARRAY emacs_meta_keymap;
132 * The current prompt string.
134 char *rl_prompt = NULL;
136 * This is set to character indicating type of completion being done by
137 * rl_complete_internal(); this is available for application completion
140 int rl_completion_type = 0;
143 * If more than this number of items results from query for possible
144 * completions, we ask user if they are sure to really display the list.
146 int rl_completion_query_items = 100;
149 * List of characters which are word break characters, but should be left
150 * in the parsed text when it is passed to the completion function.
151 * Shell uses this to help determine what kind of completing to do.
153 char *rl_special_prefixes = NULL;
156 * This is the character appended to the completed words if at the end of
157 * the line. Default is ' ' (a space).
159 int rl_completion_append_character = ' ';
161 /* stuff below is used internally by libedit for readline emulation */
163 static History *h = NULL;
164 static EditLine *e = NULL;
165 static rl_command_func_t *map[256];
166 static jmp_buf topbuf;
168 /* internal functions */
169 static unsigned char _el_rl_complete(EditLine *, int);
170 static unsigned char _el_rl_tstp(EditLine *, int);
171 static char *_get_prompt(EditLine *);
172 static int _getc_function(EditLine *, wchar_t *);
173 static int _history_expand_command(const char *, size_t, size_t,
175 static char *_rl_compat_sub(const char *, const char *,
177 static int _rl_event_read_char(EditLine *, wchar_t *);
178 static void _rl_update_pos(void);
180 static HIST_ENTRY rl_he;
184 _get_prompt(EditLine *el __attribute__((__unused__)))
186 rl_already_prompted = 1;
192 * read one key from user defined input function
196 _getc_function(EditLine *el __attribute__((__unused__)), wchar_t *c)
200 i = (*rl_getc_function)(rl_instream);
208 _resize_fun(EditLine *el, void *a)
214 /* a cheesy way to get rid of const cast. */
215 *ap = memchr(li->buffer, *li->buffer, (size_t)1);
219 _default_history_file(void)
228 if ((p = getpwuid(getuid())) == NULL)
231 len = strlen(p->pw_dir) + sizeof("/.history");
232 if ((path = malloc(len)) == NULL)
235 (void)snprintf(path, len, "%s/.history", p->pw_dir);
240 * READLINE compatibility stuff
247 rl_set_prompt(const char *prompt)
253 if (rl_prompt != NULL && strcmp(rl_prompt, prompt) == 0)
257 rl_prompt = strdup(prompt);
258 if (rl_prompt == NULL)
261 while ((p = strchr(rl_prompt, RL_PROMPT_END_IGNORE)) != NULL)
262 *p = RL_PROMPT_START_IGNORE;
268 * initialize rl compat stuff
285 rl_outstream = stdout;
288 * See if we don't really want to run the editor
290 if (tcgetattr(fileno(rl_instream), &t) != -1 && (t.c_lflag & ECHO) == 0)
293 e = el_init(rl_readline_name, rl_instream, rl_outstream, stderr);
296 el_set(e, EL_EDITMODE, 0);
302 history(h, &ev, H_SETSIZE, INT_MAX); /* unlimited */
304 max_input_history = INT_MAX;
305 el_set(e, EL_HIST, history, h);
307 /* Setup resize function */
308 el_set(e, EL_RESIZE, _resize_fun, &rl_line_buffer);
310 /* setup getc function if valid */
311 if (rl_getc_function)
312 el_set(e, EL_GETCFN, _getc_function);
314 /* for proper prompt printing in readline() */
315 if (rl_set_prompt("") == -1) {
320 el_set(e, EL_PROMPT, _get_prompt, RL_PROMPT_START_IGNORE);
321 el_set(e, EL_SIGNAL, rl_catch_signals);
323 /* set default mode to "emacs"-style and read setting afterwards */
324 /* so this can be overridden */
325 el_set(e, EL_EDITOR, "emacs");
326 if (rl_terminal_name != NULL)
327 el_set(e, EL_TERMINAL, rl_terminal_name);
329 el_get(e, EL_TERMINAL, &rl_terminal_name);
332 * Word completion - this has to go AFTER rebinding keys
335 el_set(e, EL_ADDFN, "rl_complete",
336 "ReadLine compatible completion function",
338 el_set(e, EL_BIND, "^I", "rl_complete", NULL);
341 * Send TSTP when ^Z is pressed.
343 el_set(e, EL_ADDFN, "rl_tstp",
344 "ReadLine compatible suspend function",
346 el_set(e, EL_BIND, "^Z", "rl_tstp", NULL);
349 * Set some readline compatible key-bindings.
351 el_set(e, EL_BIND, "^R", "em-inc-search-prev", NULL);
354 * Allow the use of Home/End keys.
356 el_set(e, EL_BIND, "\\e[1~", "ed-move-to-beg", NULL);
357 el_set(e, EL_BIND, "\\e[4~", "ed-move-to-end", NULL);
358 el_set(e, EL_BIND, "\\e[7~", "ed-move-to-beg", NULL);
359 el_set(e, EL_BIND, "\\e[8~", "ed-move-to-end", NULL);
360 el_set(e, EL_BIND, "\\e[H", "ed-move-to-beg", NULL);
361 el_set(e, EL_BIND, "\\e[F", "ed-move-to-end", NULL);
364 * Allow the use of the Delete/Insert keys.
366 el_set(e, EL_BIND, "\\e[3~", "ed-delete-next-char", NULL);
367 el_set(e, EL_BIND, "\\e[2~", "ed-quoted-insert", NULL);
370 * Ctrl-left-arrow and Ctrl-right-arrow for word moving.
372 el_set(e, EL_BIND, "\\e[1;5C", "em-next-word", NULL);
373 el_set(e, EL_BIND, "\\e[1;5D", "ed-prev-word", NULL);
374 el_set(e, EL_BIND, "\\e[5C", "em-next-word", NULL);
375 el_set(e, EL_BIND, "\\e[5D", "ed-prev-word", NULL);
376 el_set(e, EL_BIND, "\\e\\e[C", "em-next-word", NULL);
377 el_set(e, EL_BIND, "\\e\\e[D", "ed-prev-word", NULL);
379 /* read settings from configuration file */
383 * Unfortunately, some applications really do use rl_point
384 * and rl_line_buffer directly.
386 _resize_fun(e, &rl_line_buffer);
390 (*rl_startup_hook)(NULL, 0);
397 * read one line from input stream and return it, chomping
398 * trailing newline (if there is any)
401 readline(const char *p)
404 const char * volatile prompt = p;
408 static int used_event_hook;
410 if (e == NULL || h == NULL)
415 (void)setjmp(topbuf);
417 /* update prompt accordingly to what has been passed */
418 if (rl_set_prompt(prompt) == -1)
421 if (rl_pre_input_hook)
422 (*rl_pre_input_hook)(NULL, 0);
424 if (rl_event_hook && !(e->el_flags&NO_TTY)) {
425 el_set(e, EL_GETCFN, _rl_event_read_char);
429 if (!rl_event_hook && used_event_hook) {
430 el_set(e, EL_GETCFN, EL_BUILTIN_GETCFN);
434 rl_already_prompted = 0;
436 /* get one line from input stream */
437 ret = el_gets(e, &count);
439 if (ret && count > 0) {
446 if (buf[lastidx] == '\n')
451 history(h, &ev, H_GETSIZE);
452 history_length = ev.num;
462 * is normally called before application starts to use
463 * history expansion functions
468 if (h == NULL || e == NULL)
470 history_offset = history_length;
475 * substitute ``what'' with ``with'', returning resulting string; if
476 * globally == 1, substitutes all occurrences of what, otherwise only the
480 _rl_compat_sub(const char *str, const char *what, const char *with,
485 size_t len, with_len, what_len;
488 with_len = strlen(with);
489 what_len = strlen(what);
491 /* calculate length we need for result */
494 if (*s == *what && !strncmp(s, what, what_len)) {
495 len += with_len - what_len;
502 r = result = el_malloc((len + 1) * sizeof(*r));
507 if (*s == *what && !strncmp(s, what, what_len)) {
508 (void)strncpy(r, with, with_len);
522 static char *last_search_pat; /* last !?pat[?] search pattern */
523 static char *last_search_match; /* last !?pat[?] that matched */
526 get_history_event(const char *cmd, int *cindex, int qchar)
528 int idx, sign, sub, num, begin, ret;
535 if (cmd[idx++] != history_expansion_char)
538 /* find out which event to take */
539 if (cmd[idx] == history_expansion_char || cmd[idx] == '\0') {
540 if (history(h, &ev, H_FIRST) != 0)
542 *cindex = cmd[idx]? (idx + 1):idx;
546 if (cmd[idx] == '-') {
551 if ('0' <= cmd[idx] && cmd[idx] <= '9') {
555 while (cmd[idx] && '0' <= cmd[idx] && cmd[idx] <= '9') {
556 num = num * 10 + cmd[idx] - '0';
560 num = history_length - num + 1;
562 if (!(he = history_get(num)))
569 if (cmd[idx] == '?') {
575 if (cmd[idx] == '\n')
577 if (sub && cmd[idx] == '?')
579 if (!sub && (cmd[idx] == ':' || cmd[idx] == ' '
580 || cmd[idx] == '\t' || cmd[idx] == qchar))
584 len = (size_t)idx - (size_t)begin;
585 if (sub && cmd[idx] == '?')
587 if (sub && len == 0 && last_search_pat && *last_search_pat)
588 pat = last_search_pat;
592 if ((pat = el_malloc((len + 1) * sizeof(*pat))) == NULL)
594 (void)strncpy(pat, cmd + begin, len);
598 if (history(h, &ev, H_CURR) != 0) {
599 if (pat != last_search_pat)
606 if (pat != last_search_pat) {
608 el_free(last_search_pat);
609 last_search_pat = pat;
611 ret = history_search(pat, -1);
613 ret = history_search_prefix(pat, -1);
616 /* restore to end of list on failed search */
617 history(h, &ev, H_FIRST);
618 (void)fprintf(rl_outstream, "%s: Event not found\n", pat);
619 if (pat != last_search_pat)
625 if (last_search_match && last_search_match != pat)
626 el_free(last_search_match);
627 last_search_match = pat;
630 if (pat != last_search_pat)
633 if (history(h, &ev, H_CURR) != 0)
638 /* roll back to original position */
639 (void)history(h, &ev, H_SET, num);
645 * the real function doing history expansion - takes as argument command
646 * to do and data upon which the command should be executed
647 * does expansion the way I've understood readline documentation
649 * returns 0 if data was not modified, 1 if it was and 2 if the string
650 * should be only printed and not executed; in case of error,
651 * returns -1 and *result points to NULL
652 * it's the caller's responsibility to free() the string returned in *result
655 _history_expand_command(const char *command, size_t offs, size_t cmdlen,
658 char *tmp, *search = NULL, *aptr;
659 const char *ptr, *cmd;
660 static char *from = NULL, *to = NULL;
661 int start, end, idx, has_mods = 0;
662 int p_on = 0, g_on = 0;
668 /* First get event specifier */
671 if (strchr(":^*$", command[offs + 1])) {
674 * "!:" is shorthand for "!!:".
675 * "!^", "!*" and "!$" are shorthand for
676 * "!!:^", "!!:*" and "!!:$" respectively.
678 str[0] = str[1] = '!';
680 ptr = get_history_event(str, &idx, 0);
681 idx = (command[offs + 1] == ':')? 1:0;
684 if (command[offs + 1] == '#') {
685 /* use command so far */
686 if ((aptr = el_malloc((offs + 1) * sizeof(*aptr)))
689 (void)strncpy(aptr, command, offs);
695 qchar = (offs > 0 && command[offs - 1] == '"')? '"':0;
696 ptr = get_history_event(command + offs, &idx, qchar);
698 has_mods = command[offs + (size_t)idx] == ':';
701 if (ptr == NULL && aptr == NULL)
705 *result = strdup(aptr ? aptr : ptr);
713 cmd = command + offs + idx + 1;
715 /* Now parse any word designators */
717 if (*cmd == '%') /* last word matched by ?pat? */
718 tmp = strdup(last_search_match? last_search_match:"");
719 else if (strchr("^*$-0123456789", *cmd)) {
722 start = end = 1, cmd++;
723 else if (*cmd == '$')
725 else if (*cmd == '*')
727 else if (*cmd == '-' || isdigit((unsigned char) *cmd)) {
729 while (*cmd && '0' <= *cmd && *cmd <= '9')
730 start = start * 10 + *cmd++ - '0';
733 if (isdigit((unsigned char) cmd[1])) {
736 while (*cmd && '0' <= *cmd && *cmd <= '9')
737 end = end * 10 + *cmd++ - '0';
738 } else if (cmd[1] == '$') {
745 } else if (*cmd == '*')
750 tmp = history_arg_extract(start, end, aptr? aptr:ptr);
752 (void)fprintf(rl_outstream, "%s: Bad word specifier",
753 command + offs + idx);
759 tmp = strdup(aptr? aptr:ptr);
764 if (*cmd == '\0' || ((size_t)(cmd - (command + offs)) >= cmdlen)) {
769 for (; *cmd; cmd++) {
772 else if (*cmd == 'h') { /* remove trailing path */
773 if ((aptr = strrchr(tmp, '/')) != NULL)
775 } else if (*cmd == 't') { /* remove leading path */
776 if ((aptr = strrchr(tmp, '/')) != NULL) {
777 aptr = strdup(aptr + 1);
781 } else if (*cmd == 'r') { /* remove trailing suffix */
782 if ((aptr = strrchr(tmp, '.')) != NULL)
784 } else if (*cmd == 'e') { /* remove all but suffix */
785 if ((aptr = strrchr(tmp, '.')) != NULL) {
790 } else if (*cmd == 'p') /* print only */
792 else if (*cmd == 'g')
794 else if (*cmd == 's' || *cmd == '&') {
795 char *what, *with, delim;
796 size_t len, from_len;
799 if (*cmd == '&' && (from == NULL || to == NULL))
801 else if (*cmd == 's') {
802 delim = *(++cmd), cmd++;
804 what = el_realloc(from, size * sizeof(*what));
811 for (; *cmd && *cmd != delim; cmd++) {
812 if (*cmd == '\\' && cmd[1] == delim)
816 nwhat = el_realloc(what,
833 from = strdup(search);
844 cmd++; /* shift after delim */
849 with = el_realloc(to, size * sizeof(*with));
856 from_len = strlen(from);
857 for (; *cmd && *cmd != delim; cmd++) {
858 if (len + from_len + 1 >= size) {
860 size += from_len + 1;
861 nwith = el_realloc(with,
862 size * sizeof(*nwith));
872 (void)strcpy(&with[len], from);
877 && (*(cmd + 1) == delim
878 || *(cmd + 1) == '&'))
886 aptr = _rl_compat_sub(tmp, from, to, g_on);
900 * csh-style history expansion
903 history_expand(char *str, char **output)
909 if (h == NULL || e == NULL)
912 if (history_expansion_char == 0) {
913 *output = strdup(str);
918 if (str[0] == history_subst_char) {
919 /* ^foo^foo2^ is equivalent to !!:s^foo^foo2^ */
920 *output = el_malloc((strlen(str) + 4 + 1) * sizeof(**output));
923 (*output)[0] = (*output)[1] = history_expansion_char;
926 (void)strcpy((*output) + 4, str);
929 *output = strdup(str);
934 #define ADD_STRING(what, len, fr) \
936 if (idx + len + 1 > size) { \
937 char *nresult = el_realloc(result, \
938 (size += len + 1) * sizeof(*nresult)); \
939 if (nresult == NULL) { \
941 if (/*CONSTCOND*/fr) \
947 (void)strncpy(&result[idx], what, len); \
949 result[idx] = '\0'; \
955 for (i = 0; str[i];) {
956 int qchar, loop_again;
957 size_t len, start, j;
963 for (; str[j]; j++) {
964 if (str[j] == '\\' &&
965 str[j + 1] == history_expansion_char) {
966 len = strlen(&str[j + 1]) + 1;
967 memmove(&str[j], &str[j + 1], len);
971 if (isspace((unsigned char) str[j])
975 if (str[j] == history_expansion_char
976 && !strchr(history_no_expand_chars, str[j + 1])
977 && (!history_inhibit_expansion_function ||
978 (*history_inhibit_expansion_function)(str,
983 if (str[j] && loop_again) {
985 qchar = (j > 0 && str[j - 1] == '"' )? '"':0;
987 if (str[j] == history_expansion_char)
993 ADD_STRING(&str[start], len, 0);
995 if (str[i] == '\0' || str[i] != history_expansion_char) {
997 ADD_STRING(&str[i], len, 0);
1004 ret = _history_expand_command (str, i, (j - i), &tmp);
1005 if (ret > 0 && tmp) {
1007 ADD_STRING(tmp, len, 1);
1016 /* ret is 2 for "print only" option */
1018 add_history(result);
1020 /* gdb 4.11 has been shipped with readline, where */
1021 /* history_expand() returned -1 when the line */
1022 /* should not be executed; in readline 2.1+ */
1023 /* it should return 2 in such a case */
1034 * Return a string consisting of arguments of "str" from "start" to "end".
1037 history_arg_extract(int start, int end, const char *str)
1040 char **arr, *result = NULL;
1042 arr = history_tokenize(str);
1045 if (arr && *arr == NULL)
1048 for (max = 0; arr[max]; max++)
1057 end = (int)max + end + 1;
1061 if (start < 0 || end < 0 || (size_t)start > max ||
1062 (size_t)end > max || start > end)
1065 for (i = (size_t)start, len = 0; i <= (size_t)end; i++)
1066 len += strlen(arr[i]) + 1;
1068 result = el_malloc(len * sizeof(*result));
1072 for (i = (size_t)start, len = 0; i <= (size_t)end; i++) {
1073 (void)strcpy(result + len, arr[i]);
1074 len += strlen(arr[i]);
1075 if (i < (size_t)end)
1076 result[len++] = ' ';
1081 for (i = 0; arr[i]; i++)
1089 * Parse the string into individual tokens,
1090 * similar to how shell would do it.
1093 history_tokenize(const char *str)
1095 int size = 1, idx = 0, i, start;
1097 char **result = NULL, *temp, delim = '\0';
1099 for (i = 0; str[i];) {
1100 while (isspace((unsigned char) str[i]))
1104 if (str[i] == '\\') {
1105 if (str[i+1] != '\0')
1107 } else if (str[i] == delim)
1110 (isspace((unsigned char) str[i]) ||
1111 strchr("()<>;&|$", str[i])))
1113 else if (!delim && strchr("'`\"", str[i]))
1119 if (idx + 2 >= size) {
1122 nresult = el_realloc(result, (size_t)size * sizeof(*nresult));
1123 if (nresult == NULL) {
1129 len = (size_t)i - (size_t)start;
1130 temp = el_malloc((size_t)(len + 1) * sizeof(*temp));
1132 for (i = 0; i < idx; i++)
1137 (void)strncpy(temp, &str[start], len);
1139 result[idx++] = temp;
1149 * limit size of history record to ``max'' events
1152 stifle_history(int max)
1157 if (h == NULL || e == NULL)
1160 if (history(h, &ev, H_SETSIZE, max) == 0) {
1161 max_input_history = max;
1162 if (history_length > max)
1163 history_base = history_length - max;
1164 while (history_length > max) {
1165 he = remove_history(0);
1167 el_free((void *)(unsigned long)he->line);
1175 * "unlimit" size of history - set the limit to maximum allowed int value
1178 unstifle_history(void)
1183 history(h, &ev, H_SETSIZE, INT_MAX);
1184 omax = max_input_history;
1185 max_input_history = INT_MAX;
1186 return omax; /* some value _must_ be returned */
1191 history_is_stifled(void)
1194 /* cannot return true answer */
1195 return max_input_history != INT_MAX;
1198 static const char _history_tmp_template[] = "/tmp/.historyXXXXXX";
1201 history_truncate_file (const char *filename, int nlines)
1205 char template[sizeof(_history_tmp_template)];
1213 if (filename == NULL && (filename = _default_history_file()) == NULL)
1215 if ((fp = fopen(filename, "r+")) == NULL)
1217 strcpy(template, _history_tmp_template);
1218 if ((fd = mkstemp(template)) == -1) {
1223 if ((tp = fdopen(fd, "r+")) == NULL) {
1230 if (fread(buf, sizeof(buf), (size_t)1, fp) != 1) {
1235 if (fseeko(fp, (off_t)sizeof(buf) * count, SEEK_SET) ==
1240 left = (ssize_t)fread(buf, (size_t)1, sizeof(buf), fp);
1248 } else if (fwrite(buf, (size_t)left, (size_t)1, tp)
1256 if (fwrite(buf, sizeof(buf), (size_t)1, tp) != 1) {
1264 cp = buf + left - 1;
1268 while (--cp >= buf) {
1270 if (--nlines == 0) {
1271 if (++cp >= buf + sizeof(buf)) {
1279 if (nlines <= 0 || count == 0)
1282 if (fseeko(tp, (off_t)sizeof(buf) * count, SEEK_SET) < 0) {
1286 if (fread(buf, sizeof(buf), (size_t)1, tp) != 1) {
1294 cp = buf + sizeof(buf);
1297 if (ret || nlines > 0)
1300 if (fseeko(fp, (off_t)0, SEEK_SET) == (off_t)-1) {
1305 if (fseeko(tp, (off_t)sizeof(buf) * count + (cp - buf), SEEK_SET) ==
1312 if ((left = (ssize_t)fread(buf, (size_t)1, sizeof(buf), tp)) == 0) {
1317 if (fwrite(buf, (size_t)left, (size_t)1, fp) != 1) {
1323 if((off = ftello(fp)) > 0)
1324 (void)ftruncate(fileno(fp), off);
1337 * read history from a file given
1340 read_history(const char *filename)
1344 if (h == NULL || e == NULL)
1346 if (filename == NULL && (filename = _default_history_file()) == NULL)
1348 return history(h, &ev, H_LOAD, filename) == -1 ?
1349 (errno ? errno : EINVAL) : 0;
1354 * write history to a file given
1357 write_history(const char *filename)
1361 if (h == NULL || e == NULL)
1363 if (filename == NULL && (filename = _default_history_file()) == NULL)
1365 return history(h, &ev, H_SAVE, filename) == -1 ?
1366 (errno ? errno : EINVAL) : 0;
1371 * returns history ``num''th event
1373 * returned pointer points to static variable
1376 history_get(int num)
1378 static HIST_ENTRY she;
1382 if (h == NULL || e == NULL)
1385 if (num < history_base)
1388 /* save current position */
1389 if (history(h, &ev, H_CURR) != 0)
1394 * use H_DELDATA to set to nth history (without delete) by passing
1395 * (void **)-1 -- as in history_set_pos
1397 if (history(h, &ev, H_DELDATA, num - history_base, (void **)-1) != 0)
1400 /* get current entry */
1401 if (history(h, &ev, H_CURR) != 0)
1403 if (history(h, &ev, H_NEXT_EVDATA, ev.num, &she.data) != 0)
1407 /* restore pointer to where it was */
1408 (void)history(h, &ev, H_SET, curr_num);
1413 /* restore pointer to where it was */
1414 (void)history(h, &ev, H_SET, curr_num);
1420 * add the line to history table
1423 add_history(const char *line)
1427 if (h == NULL || e == NULL)
1430 if (history(h, &ev, H_ENTER, line) == -1)
1433 (void)history(h, &ev, H_GETSIZE);
1434 if (ev.num == history_length)
1437 history_length = ev.num;
1443 * remove the specified entry from the history list and return it.
1446 remove_history(int num)
1451 if (h == NULL || e == NULL)
1454 if ((he = el_malloc(sizeof(*he))) == NULL)
1457 if (history(h, &ev, H_DELDATA, num, &he->data) != 0) {
1463 if (history(h, &ev, H_GETSIZE) == 0)
1464 history_length = ev.num;
1471 * replace the line and data of the num-th entry
1474 replace_history_entry(int num, const char *line, histdata_t data)
1480 if (h == NULL || e == NULL)
1483 /* save current position */
1484 if (history(h, &ev, H_CURR) != 0)
1488 /* start from the oldest */
1489 if (history(h, &ev, H_LAST) != 0)
1490 return NULL; /* error */
1492 if ((he = el_malloc(sizeof(*he))) == NULL)
1495 /* look forwards for event matching specified offset */
1496 if (history(h, &ev, H_NEXT_EVDATA, num, &he->data))
1499 he->line = strdup(ev.str);
1500 if (he->line == NULL)
1503 if (history(h, &ev, H_REPLACE, line, data))
1506 /* restore pointer to where it was */
1507 if (history(h, &ev, H_SET, curr_num))
1517 * clear the history list - delete all entries
1524 if (h == NULL || e == NULL)
1527 (void)history(h, &ev, H_CLEAR);
1528 history_offset = history_length = 0;
1533 * returns offset of the current history event
1538 return history_offset;
1541 static HIST_ENTRY **_history_listp;
1542 static HIST_ENTRY *_history_list;
1548 HIST_ENTRY **nlp, *nl;
1551 if (history(h, &ev, H_LAST) != 0)
1554 if ((nlp = el_realloc(_history_listp,
1555 (size_t)history_length * sizeof(*nlp))) == NULL)
1557 _history_listp = nlp;
1559 if ((nl = el_realloc(_history_list,
1560 (size_t)history_length * sizeof(*nl))) == NULL)
1566 _history_listp[i] = &_history_list[i];
1567 _history_list[i].line = ev.str;
1568 _history_list[i].data = NULL;
1569 if (i++ == history_length)
1571 } while (history(h, &ev, H_PREV) == 0);
1572 return _history_listp;
1576 * returns current history event or NULL if there is no such event
1579 current_history(void)
1583 if (history(h, &ev, H_PREV_EVENT, history_offset + 1) != 0)
1586 rl_he.line = ev.str;
1593 * returns total number of bytes history events' data are using
1596 history_total_bytes(void)
1602 if (history(h, &ev, H_CURR) != 0)
1606 (void)history(h, &ev, H_FIRST);
1609 size += strlen(ev.str) * sizeof(*ev.str);
1610 while (history(h, &ev, H_NEXT) == 0);
1612 /* get to the same position as before */
1613 history(h, &ev, H_PREV_EVENT, curr_num);
1620 * sets the position in the history list to ``pos''
1623 history_set_pos(int pos)
1625 if (pos >= history_length || pos < 0)
1628 history_offset = pos;
1634 * returns previous event in history and shifts pointer accordingly
1635 * Note that readline and editline define directions in opposite ways.
1638 previous_history(void)
1642 if (history_offset == 0)
1645 if (history(h, &ev, H_LAST) != 0)
1649 return current_history();
1654 * returns next event in history and shifts pointer accordingly
1661 if (history_offset >= history_length)
1664 if (history(h, &ev, H_LAST) != 0)
1668 return current_history();
1673 * searches for first history event containing the str
1676 history_search(const char *str, int direction)
1682 if (history(h, &ev, H_CURR) != 0)
1687 if ((strp = strstr(ev.str, str)) != NULL)
1688 return (int)(strp - ev.str);
1689 if (history(h, &ev, direction < 0 ? H_NEXT:H_PREV) != 0)
1692 (void)history(h, &ev, H_SET, curr_num);
1698 * searches for first history event beginning with str
1701 history_search_prefix(const char *str, int direction)
1705 return (history(h, &ev, direction < 0 ?
1706 H_PREV_STR : H_NEXT_STR, str));
1711 * search for event in history containing str, starting at offset
1712 * abs(pos); continue backward, if pos<0, forward otherwise
1716 history_search_pos(const char *str,
1717 int direction __attribute__((__unused__)), int pos)
1722 off = (pos > 0) ? pos : -pos;
1723 pos = (pos > 0) ? 1 : -1;
1725 if (history(h, &ev, H_CURR) != 0)
1729 if (!history_set_pos(off) || history(h, &ev, H_CURR) != 0)
1733 if (strstr(ev.str, str))
1735 if (history(h, &ev, (pos < 0) ? H_PREV : H_NEXT) != 0)
1739 /* set "current" pointer back to previous state */
1740 (void)history(h, &ev,
1741 pos < 0 ? H_NEXT_EVENT : H_PREV_EVENT, curr_num);
1747 /********************************/
1748 /* completion functions */
1751 tilde_expand(char *name)
1753 return fn_tilde_expand(name);
1757 filename_completion_function(const char *name, int state)
1759 return fn_filename_completion_function(name, state);
1763 * a completion generator for usernames; returns _first_ username
1764 * which starts with supplied text
1765 * text contains a partial username preceded by random character
1766 * (usually '~'); state resets search from start (??? should we do that anyway)
1767 * it's the caller's responsibility to free the returned value
1770 username_completion_function(const char *text, int state)
1772 #if defined(HAVE_GETPW_R_POSIX) || defined(HAVE_GETPW_R_DRAFT)
1773 struct passwd pwres;
1776 struct passwd *pass = NULL;
1778 if (text[0] == '\0')
1788 (pass = getpwent()) != NULL
1789 && text[0] == pass->pw_name[0]
1790 && strcmp(text, pass->pw_name) == 0)
1797 return strdup(pass->pw_name);
1802 * el-compatible wrapper to send TSTP on ^Z
1805 static unsigned char
1806 _el_rl_tstp(EditLine *el __attribute__((__unused__)), int ch __attribute__((__unused__)))
1808 (void)kill(0, SIGTSTP);
1813 * Display list of strings in columnar format on readline's output stream.
1814 * 'matches' is list of strings, 'len' is number of strings in 'matches',
1815 * 'max' is maximum length of string in 'matches'.
1818 rl_display_match_list(char **matches, int len, int max)
1821 fn_display_match_list(e, matches, (size_t)len, (size_t)max);
1826 _rl_completion_append_character_function(const char *dummy
1827 __attribute__((__unused__)))
1830 buf[0] = (char)rl_completion_append_character;
1837 * complete word at current point
1841 rl_complete(int ignore __attribute__((__unused__)), int invoking_key)
1843 static ct_buffer_t wbreak_conv, sprefix_conv;
1846 if (h == NULL || e == NULL)
1849 if (rl_inhibit_completion) {
1851 arr[0] = (char)invoking_key;
1853 el_insertstr(e, arr);
1857 if (rl_completion_word_break_hook != NULL)
1858 breakchars = (*rl_completion_word_break_hook)();
1860 breakchars = rl_basic_word_break_characters;
1864 /* Just look at how many global variables modify this operation! */
1865 return fn_complete(e,
1866 (rl_compentry_func_t *)rl_completion_entry_function,
1867 rl_attempted_completion_function,
1868 ct_decode_string(rl_basic_word_break_characters, &wbreak_conv),
1869 ct_decode_string(breakchars, &sprefix_conv),
1870 _rl_completion_append_character_function,
1871 (size_t)rl_completion_query_items,
1872 &rl_completion_type, &rl_attempted_completion_over,
1873 &rl_point, &rl_end);
1880 static unsigned char
1881 _el_rl_complete(EditLine *el __attribute__((__unused__)), int ch)
1883 return (unsigned char)rl_complete(0, ch);
1887 * misc other functions
1891 * bind key c to readline-type function func
1894 rl_bind_key(int c, rl_command_func_t *func)
1898 if (h == NULL || e == NULL)
1901 if (func == rl_insert) {
1902 /* XXX notice there is no range checking of ``c'' */
1903 e->el_map.key[c] = ED_INSERT;
1911 * read one key from input - handles chars pushed back
1912 * to input stream also
1917 char fooarr[2 * sizeof(int)];
1919 if (e == NULL || h == NULL)
1922 return el_getc(e, fooarr);
1927 * reset the terminal
1931 rl_reset_terminal(const char *p __attribute__((__unused__)))
1934 if (h == NULL || e == NULL)
1941 * insert character ``c'' back into input stream, ``count'' times
1944 rl_insert(int count, int c)
1948 if (h == NULL || e == NULL)
1951 /* XXX - int -> char conversion can lose on multichars */
1955 for (; count > 0; count--)
1962 rl_insert_text(const char *text)
1964 if (!text || *text == 0)
1967 if (h == NULL || e == NULL)
1970 if (el_insertstr(e, text) < 0)
1972 return (int)strlen(text);
1977 rl_newline(int count __attribute__((__unused__)),
1978 int c __attribute__((__unused__)))
1981 * Readline-4.0 appears to ignore the args.
1983 return rl_insert(1, '\n');
1987 static unsigned char
1988 rl_bind_wrapper(EditLine *el __attribute__((__unused__)), unsigned char c)
1997 /* If rl_done was set by the above call, deal with it here */
2005 rl_add_defun(const char *name, rl_command_func_t *fun, int c)
2008 if ((size_t)c >= sizeof(map) / sizeof(map[0]) || c < 0)
2010 map[(unsigned char)c] = fun;
2011 el_set(e, EL_ADDFN, name, name, rl_bind_wrapper);
2012 vis(dest, c, VIS_WHITE|VIS_NOSLASH, 0);
2013 el_set(e, EL_BIND, dest, name, NULL);
2018 rl_callback_read_char(void)
2020 int count = 0, done = 0;
2021 const char *buf = el_gets(e, &count);
2024 if (buf == NULL || count-- <= 0)
2026 if (count == 0 && buf[0] == e->el_tty.t_c[TS_IO][C_EOF])
2028 if (buf[count] == '\n' || buf[count] == '\r')
2031 if (done && rl_linefunc != NULL) {
2032 el_set(e, EL_UNBUFFERED, 0);
2034 if ((wbuf = strdup(buf)) != NULL)
2038 (*(void (*)(const char *))rl_linefunc)(wbuf);
2039 el_set(e, EL_UNBUFFERED, 1);
2044 rl_callback_handler_install(const char *prompt, rl_vcpfunc_t *linefunc)
2049 (void)rl_set_prompt(prompt);
2050 rl_linefunc = linefunc;
2051 el_set(e, EL_UNBUFFERED, 1);
2055 rl_callback_handler_remove(void)
2057 el_set(e, EL_UNBUFFERED, 0);
2065 a[0] = (char)e->el_tty.t_c[TS_IO][C_REPRINT];
2071 rl_get_previous_history(int count, int key)
2083 rl_prep_terminal(int meta_flag __attribute__((__unused__)))
2085 el_set(e, EL_PREP_TERM, 1);
2089 rl_deprep_terminal(void)
2091 el_set(e, EL_PREP_TERM, 0);
2095 rl_read_init_file(const char *s)
2097 return el_source(e, s);
2101 rl_parse_and_bind(const char *line)
2107 tok = tok_init(NULL);
2108 tok_str(tok, line, &argc, &argv);
2109 argc = el_parse(e, argc, argv);
2111 return argc ? 1 : 0;
2115 rl_variable_bind(const char *var, const char *value)
2118 * The proper return value is undocument, but this is what the
2119 * readline source seems to do.
2121 return el_set(e, EL_BIND, "", var, value, NULL) == -1 ? 1 : 0;
2125 rl_stuff_char(int c)
2131 el_insertstr(e, buf);
2135 _rl_event_read_char(EditLine *el, wchar_t *wc)
2139 ssize_t num_read = 0;
2143 while (rl_event_hook) {
2147 #if defined(FIONREAD)
2148 if (ioctl(el->el_infd, FIONREAD, &n) < 0)
2151 num_read = read(el->el_infd, &ch, (size_t)1);
2154 #elif defined(F_SETFL) && defined(O_NDELAY)
2155 if ((n = fcntl(el->el_infd, F_GETFL, 0)) < 0)
2157 if (fcntl(el->el_infd, F_SETFL, n|O_NDELAY) < 0)
2159 num_read = read(el->el_infd, &ch, 1);
2160 if (fcntl(el->el_infd, F_SETFL, n))
2163 /* not non-blocking, but what you gonna do? */
2164 num_read = read(el->el_infd, &ch, 1);
2168 if (num_read < 0 && errno == EAGAIN)
2175 el_set(el, EL_GETCFN, EL_BUILTIN_GETCFN);
2177 return (int)num_read;
2181 _rl_update_pos(void)
2183 const LineInfo *li = el_line(e);
2185 rl_point = (int)(li->cursor - li->buffer);
2186 rl_end = (int)(li->lastchar - li->buffer);
2190 rl_get_screen_size(int *rows, int *cols)
2193 el_get(e, EL_GETTC, "li", rows, (void *)0);
2195 el_get(e, EL_GETTC, "co", cols, (void *)0);
2199 rl_set_screen_size(int rows, int cols)
2202 (void)snprintf(buf, sizeof(buf), "%d", rows);
2203 el_set(e, EL_SETTC, "li", buf, NULL);
2204 (void)snprintf(buf, sizeof(buf), "%d", cols);
2205 el_set(e, EL_SETTC, "co", buf, NULL);
2209 rl_completion_matches(const char *str, rl_compentry_func_t *fun)
2211 size_t len, max, i, j, min;
2212 char **list, *match, *a, *b;
2216 if ((list = el_malloc(max * sizeof(*list))) == NULL)
2219 while ((match = (*fun)(str, (int)(len - 1))) != NULL) {
2220 list[len++] = match;
2224 if ((nl = el_realloc(list, max * sizeof(*nl))) == NULL)
2233 if ((list[0] = strdup(list[1])) == NULL)
2237 qsort(&list[1], len - 1, sizeof(*list),
2238 (int (*)(const void *, const void *)) strcmp);
2240 for (i = 1, a = list[i]; i < len - 1; i++, a = b) {
2242 for (j = 0; a[j] && a[j] == b[j]; j++)
2247 if (min == 0 && *str) {
2248 if ((list[0] = strdup(str)) == NULL)
2251 if ((list[0] = el_malloc((min + 1) * sizeof(*list[0]))) == NULL)
2253 (void)memcpy(list[0], list[1], min);
2254 list[0][min] = '\0';
2264 rl_filename_completion_function (const char *text, int state)
2266 return fn_filename_completion_function(text, state);
2270 rl_forced_update_display(void)
2272 el_set(e, EL_REFRESH);
2276 _rl_abort_internal(void)
2284 _rl_qsort_string_compare(char **s1, char **s2)
2286 return strcoll(*s1, *s2);
2290 history_get_history_state(void)
2294 if ((hs = el_malloc(sizeof(*hs))) == NULL)
2296 hs->length = history_length;
2302 rl_kill_text(int from __attribute__((__unused__)),
2303 int to __attribute__((__unused__)))
2309 rl_make_bare_keymap(void)
2322 rl_set_keymap(Keymap k __attribute__((__unused__)))
2328 rl_generic_bind(int type __attribute__((__unused__)),
2329 const char * keyseq __attribute__((__unused__)),
2330 const char * data __attribute__((__unused__)),
2331 Keymap k __attribute__((__unused__)))
2338 rl_bind_key_in_map(int key __attribute__((__unused__)),
2339 rl_command_func_t *fun __attribute__((__unused__)),
2340 Keymap k __attribute__((__unused__)))
2345 /* unsupported, but needed by python */
2347 rl_cleanup_after_signal(void)
2352 rl_on_new_line(void)
2358 rl_free_line_state(void)
2364 rl_set_keyboard_input_timeout(int u __attribute__((__unused__)))