1 /* $NetBSD: readline.c,v 1.157 2019/08/21 11:11:48 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.157 2019/08/21 11:11:48 christos Exp $");
35 #endif /* not lint && not SCCSID */
37 #include <sys/types.h>
53 #include "readline/readline.h"
56 #include "filecomplete.h"
58 void rl_prep_terminal(int);
59 void rl_deprep_terminal(void);
61 /* for rl_complete() */
64 /* see comment at the #ifdef for sense of this */
65 /* #define GDB_411_HACK */
67 /* readline compatibility stuff - look at readline sources/documentation */
68 /* to see what these variables mean */
69 const char *rl_library_version = "EditLine wrapper";
70 int rl_readline_version = RL_READLINE_VERSION;
71 static char empty[] = { '\0' };
72 static char expand_chars[] = { ' ', '\t', '\n', '=', '(', '\0' };
73 static char break_chars[] = { ' ', '\t', '\n', '"', '\\', '\'', '`', '@', '$',
74 '>', '<', '=', ';', '|', '&', '{', '(', '\0' };
75 const char *rl_readline_name = empty;
76 FILE *rl_instream = NULL;
77 FILE *rl_outstream = NULL;
80 char *rl_line_buffer = NULL;
81 rl_vcpfunc_t *rl_linefunc = NULL;
83 rl_hook_func_t *rl_event_hook = NULL;
84 KEYMAP_ENTRY_ARRAY emacs_standard_keymap,
88 * The following is not implemented; we always catch signals in the
89 * libedit fashion: set handlers on entry to el_gets() and clear them
90 * on the way out. This simplistic approach works for most cases; if
91 * it does not work for your application, please let us know.
93 int rl_catch_signals = 1;
94 int rl_catch_sigwinch = 1;
96 int history_base = 1; /* probably never subject to change */
97 int history_length = 0;
98 int history_offset = 0;
99 int max_input_history = 0;
100 char history_expansion_char = '!';
101 char history_subst_char = '^';
102 char *history_no_expand_chars = expand_chars;
103 Function *history_inhibit_expansion_function = NULL;
104 char *history_arg_extract(int start, int end, const char *str);
106 int rl_inhibit_completion = 0;
107 int rl_attempted_completion_over = 0;
108 const char *rl_basic_word_break_characters = break_chars;
109 char *rl_completer_word_break_characters = NULL;
110 const char *rl_completer_quote_characters = NULL;
111 rl_compentry_func_t *rl_completion_entry_function = NULL;
112 char *(*rl_completion_word_break_hook)(void) = NULL;
113 rl_completion_func_t *rl_attempted_completion_function = NULL;
114 Function *rl_pre_input_hook = NULL;
115 Function *rl_startup1_hook = NULL;
116 int (*rl_getc_function)(FILE *) = NULL;
117 char *rl_terminal_name = NULL;
118 int rl_already_prompted = 0;
119 int rl_filename_completion_desired = 0;
120 int rl_ignore_completion_duplicates = 0;
121 int readline_echoing_p = 1;
122 int _rl_print_completions_horizontally = 0;
123 VFunction *rl_redisplay_function = NULL;
124 Function *rl_startup_hook = NULL;
125 int rl_did_startup_hook = 0;
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 const 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 /* Remove adjacent end/start markers to avoid double-escapes. */
263 if (p[1] == RL_PROMPT_START_IGNORE) {
264 memmove(p, p + 2, 1 + strlen(p + 2));
266 *p = RL_PROMPT_START_IGNORE;
274 * initialize rl compat stuff
291 rl_outstream = stdout;
294 * See if we don't really want to run the editor
296 if (tcgetattr(fileno(rl_instream), &t) != -1 && (t.c_lflag & ECHO) == 0)
299 e = el_init_internal(rl_readline_name, rl_instream, rl_outstream,
300 stderr, fileno(rl_instream), fileno(rl_outstream), fileno(stderr),
304 el_set(e, EL_EDITMODE, 0);
310 history(h, &ev, H_SETSIZE, INT_MAX); /* unlimited */
312 max_input_history = INT_MAX;
313 el_set(e, EL_HIST, history, h);
315 /* Setup resize function */
316 el_set(e, EL_RESIZE, _resize_fun, &rl_line_buffer);
318 /* setup getc function if valid */
319 if (rl_getc_function)
320 el_set(e, EL_GETCFN, _getc_function);
322 /* for proper prompt printing in readline() */
323 if (rl_set_prompt("") == -1) {
328 el_set(e, EL_PROMPT_ESC, _get_prompt, RL_PROMPT_START_IGNORE);
329 el_set(e, EL_SIGNAL, rl_catch_signals);
331 /* set default mode to "emacs"-style and read setting afterwards */
332 /* so this can be overridden */
333 el_set(e, EL_EDITOR, "emacs");
334 if (rl_terminal_name != NULL)
335 el_set(e, EL_TERMINAL, rl_terminal_name);
337 el_get(e, EL_TERMINAL, &rl_terminal_name);
340 * Word completion - this has to go AFTER rebinding keys
343 el_set(e, EL_ADDFN, "rl_complete",
344 "ReadLine compatible completion function",
346 el_set(e, EL_BIND, "^I", "rl_complete", NULL);
349 * Send TSTP when ^Z is pressed.
351 el_set(e, EL_ADDFN, "rl_tstp",
352 "ReadLine compatible suspend function",
354 el_set(e, EL_BIND, "^Z", "rl_tstp", NULL);
357 * Set some readline compatible key-bindings.
359 el_set(e, EL_BIND, "^R", "em-inc-search-prev", NULL);
362 * Allow the use of Home/End keys.
364 el_set(e, EL_BIND, "\\e[1~", "ed-move-to-beg", NULL);
365 el_set(e, EL_BIND, "\\e[4~", "ed-move-to-end", NULL);
366 el_set(e, EL_BIND, "\\e[7~", "ed-move-to-beg", NULL);
367 el_set(e, EL_BIND, "\\e[8~", "ed-move-to-end", NULL);
368 el_set(e, EL_BIND, "\\e[H", "ed-move-to-beg", NULL);
369 el_set(e, EL_BIND, "\\e[F", "ed-move-to-end", NULL);
372 * Allow the use of the Delete/Insert keys.
374 el_set(e, EL_BIND, "\\e[3~", "ed-delete-next-char", NULL);
375 el_set(e, EL_BIND, "\\e[2~", "ed-quoted-insert", NULL);
378 * Ctrl-left-arrow and Ctrl-right-arrow for word moving.
380 el_set(e, EL_BIND, "\\e[1;5C", "em-next-word", NULL);
381 el_set(e, EL_BIND, "\\e[1;5D", "ed-prev-word", NULL);
382 el_set(e, EL_BIND, "\\e[5C", "em-next-word", NULL);
383 el_set(e, EL_BIND, "\\e[5D", "ed-prev-word", NULL);
384 el_set(e, EL_BIND, "\\e\\e[C", "em-next-word", NULL);
385 el_set(e, EL_BIND, "\\e\\e[D", "ed-prev-word", NULL);
387 /* read settings from configuration file */
391 * Unfortunately, some applications really do use rl_point
392 * and rl_line_buffer directly.
394 _resize_fun(e, &rl_line_buffer);
397 tty_end(e, TCSADRAIN);
404 * read one line from input stream and return it, chomping
405 * trailing newline (if there is any)
408 readline(const char *p)
411 const char * volatile prompt = p;
415 static int used_event_hook;
417 if (e == NULL || h == NULL)
419 if (rl_did_startup_hook == 0 && rl_startup_hook) {
420 rl_did_startup_hook = 1;
421 (*rl_startup_hook)(NULL, 0);
428 (void)setjmp(topbuf);
431 /* update prompt accordingly to what has been passed */
432 if (rl_set_prompt(prompt) == -1)
435 if (rl_pre_input_hook)
436 (*rl_pre_input_hook)(NULL, 0);
438 if (rl_event_hook && !(e->el_flags & NO_TTY)) {
439 el_set(e, EL_GETCFN, _rl_event_read_char);
443 if (!rl_event_hook && used_event_hook) {
444 el_set(e, EL_GETCFN, EL_BUILTIN_GETCFN);
448 rl_already_prompted = 0;
450 /* get one line from input stream */
451 ret = el_gets(e, &count);
453 if (ret && count > 0) {
460 if (buf[lastidx] == '\n')
465 history(h, &ev, H_GETSIZE);
466 history_length = ev.num;
469 tty_end(e, TCSADRAIN);
478 * is normally called before application starts to use
479 * history expansion functions
484 if (h == NULL || e == NULL)
486 history_offset = history_length;
491 * substitute ``what'' with ``with'', returning resulting string; if
492 * globally == 1, substitutes all occurrences of what, otherwise only the
496 _rl_compat_sub(const char *str, const char *what, const char *with,
501 size_t len, with_len, what_len;
504 with_len = strlen(with);
505 what_len = strlen(what);
507 /* calculate length we need for result */
510 if (*s == *what && !strncmp(s, what, what_len)) {
511 len += with_len - what_len;
518 r = result = el_calloc(len + 1, sizeof(*r));
523 if (*s == *what && !strncmp(s, what, what_len)) {
524 (void)strncpy(r, with, with_len);
538 static char *last_search_pat; /* last !?pat[?] search pattern */
539 static char *last_search_match; /* last !?pat[?] that matched */
542 get_history_event(const char *cmd, int *cindex, int qchar)
544 int idx, sign, sub, num, begin, ret;
551 if (cmd[idx++] != history_expansion_char)
554 /* find out which event to take */
555 if (cmd[idx] == history_expansion_char || cmd[idx] == '\0') {
556 if (history(h, &ev, H_FIRST) != 0)
558 *cindex = cmd[idx]? (idx + 1):idx;
562 if (cmd[idx] == '-') {
567 if ('0' <= cmd[idx] && cmd[idx] <= '9') {
571 while (cmd[idx] && '0' <= cmd[idx] && cmd[idx] <= '9') {
572 num = num * 10 + cmd[idx] - '0';
576 num = history_length - num + history_base;
578 if (!(he = history_get(num)))
585 if (cmd[idx] == '?') {
591 if (cmd[idx] == '\n')
593 if (sub && cmd[idx] == '?')
595 if (!sub && (cmd[idx] == ':' || cmd[idx] == ' '
596 || cmd[idx] == '\t' || cmd[idx] == qchar))
600 len = (size_t)idx - (size_t)begin;
601 if (sub && cmd[idx] == '?')
603 if (sub && len == 0 && last_search_pat && *last_search_pat)
604 pat = last_search_pat;
608 if ((pat = el_calloc(len + 1, sizeof(*pat))) == NULL)
610 (void)strncpy(pat, cmd + begin, len);
614 if (history(h, &ev, H_CURR) != 0) {
615 if (pat != last_search_pat)
622 if (pat != last_search_pat) {
624 el_free(last_search_pat);
625 last_search_pat = pat;
627 ret = history_search(pat, -1);
629 ret = history_search_prefix(pat, -1);
632 /* restore to end of list on failed search */
633 history(h, &ev, H_FIRST);
634 (void)fprintf(rl_outstream, "%s: Event not found\n", pat);
635 if (pat != last_search_pat)
641 if (last_search_match && last_search_match != pat)
642 el_free(last_search_match);
643 last_search_match = pat;
646 if (pat != last_search_pat)
649 if (history(h, &ev, H_CURR) != 0)
654 /* roll back to original position */
655 (void)history(h, &ev, H_SET, num);
661 * the real function doing history expansion - takes as argument command
662 * to do and data upon which the command should be executed
663 * does expansion the way I've understood readline documentation
665 * returns 0 if data was not modified, 1 if it was and 2 if the string
666 * should be only printed and not executed; in case of error,
667 * returns -1 and *result points to NULL
668 * it's the caller's responsibility to free() the string returned in *result
671 _history_expand_command(const char *command, size_t offs, size_t cmdlen,
674 char *tmp, *search = NULL, *aptr;
675 const char *ptr, *cmd;
676 static char *from = NULL, *to = NULL;
677 int start, end, idx, has_mods = 0;
678 int p_on = 0, g_on = 0;
684 /* First get event specifier */
687 if (strchr(":^*$", command[offs + 1])) {
690 * "!:" is shorthand for "!!:".
691 * "!^", "!*" and "!$" are shorthand for
692 * "!!:^", "!!:*" and "!!:$" respectively.
694 str[0] = str[1] = '!';
696 ptr = get_history_event(str, &idx, 0);
697 idx = (command[offs + 1] == ':')? 1:0;
700 if (command[offs + 1] == '#') {
701 /* use command so far */
702 if ((aptr = el_calloc(offs + 1, sizeof(*aptr)))
705 (void)strncpy(aptr, command, offs);
711 qchar = (offs > 0 && command[offs - 1] == '"')? '"':0;
712 ptr = get_history_event(command + offs, &idx, qchar);
714 has_mods = command[offs + (size_t)idx] == ':';
717 if (ptr == NULL && aptr == NULL)
721 *result = strdup(aptr ? aptr : ptr);
729 cmd = command + offs + idx + 1;
731 /* Now parse any word designators */
733 if (*cmd == '%') /* last word matched by ?pat? */
734 tmp = strdup(last_search_match? last_search_match:"");
735 else if (strchr("^*$-0123456789", *cmd)) {
738 start = end = 1, cmd++;
739 else if (*cmd == '$')
741 else if (*cmd == '*')
743 else if (*cmd == '-' || isdigit((unsigned char) *cmd)) {
745 while (*cmd && '0' <= *cmd && *cmd <= '9')
746 start = start * 10 + *cmd++ - '0';
749 if (isdigit((unsigned char) cmd[1])) {
752 while (*cmd && '0' <= *cmd && *cmd <= '9')
753 end = end * 10 + *cmd++ - '0';
754 } else if (cmd[1] == '$') {
761 } else if (*cmd == '*')
766 tmp = history_arg_extract(start, end, aptr? aptr:ptr);
768 (void)fprintf(rl_outstream, "%s: Bad word specifier",
769 command + offs + idx);
775 tmp = strdup(aptr? aptr:ptr);
780 if (*cmd == '\0' || ((size_t)(cmd - (command + offs)) >= cmdlen)) {
785 for (; *cmd; cmd++) {
788 else if (*cmd == 'h') { /* remove trailing path */
789 if ((aptr = strrchr(tmp, '/')) != NULL)
791 } else if (*cmd == 't') { /* remove leading path */
792 if ((aptr = strrchr(tmp, '/')) != NULL) {
793 aptr = strdup(aptr + 1);
797 } else if (*cmd == 'r') { /* remove trailing suffix */
798 if ((aptr = strrchr(tmp, '.')) != NULL)
800 } else if (*cmd == 'e') { /* remove all but suffix */
801 if ((aptr = strrchr(tmp, '.')) != NULL) {
806 } else if (*cmd == 'p') /* print only */
808 else if (*cmd == 'g')
810 else if (*cmd == 's' || *cmd == '&') {
811 char *what, *with, delim;
812 size_t len, from_len;
815 if (*cmd == '&' && (from == NULL || to == NULL))
817 else if (*cmd == 's') {
818 delim = *(++cmd), cmd++;
820 what = el_realloc(from, size * sizeof(*what));
827 for (; *cmd && *cmd != delim; cmd++) {
828 if (*cmd == '\\' && cmd[1] == delim)
832 nwhat = el_realloc(what,
849 from = strdup(search);
860 cmd++; /* shift after delim */
865 with = el_realloc(to, size * sizeof(*with));
872 from_len = strlen(from);
873 for (; *cmd && *cmd != delim; cmd++) {
874 if (len + from_len + 1 >= size) {
876 size += from_len + 1;
877 nwith = el_realloc(with,
878 size * sizeof(*nwith));
888 (void)strcpy(&with[len], from);
893 && (*(cmd + 1) == delim
894 || *(cmd + 1) == '&'))
902 aptr = _rl_compat_sub(tmp, from, to, g_on);
916 * csh-style history expansion
919 history_expand(char *str, char **output)
925 if (h == NULL || e == NULL)
928 if (history_expansion_char == 0) {
929 *output = strdup(str);
934 if (str[0] == history_subst_char) {
935 /* ^foo^foo2^ is equivalent to !!:s^foo^foo2^ */
936 *output = el_calloc(strlen(str) + 4 + 1, sizeof(**output));
939 (*output)[0] = (*output)[1] = history_expansion_char;
942 (void)strcpy((*output) + 4, str);
945 *output = strdup(str);
950 #define ADD_STRING(what, len, fr) \
952 if (idx + len + 1 > size) { \
953 char *nresult = el_realloc(result, \
954 (size += len + 1) * sizeof(*nresult)); \
955 if (nresult == NULL) { \
957 if (/*CONSTCOND*/fr) \
963 (void)strncpy(&result[idx], what, len); \
965 result[idx] = '\0'; \
971 for (i = 0; str[i];) {
972 int qchar, loop_again;
973 size_t len, start, j;
979 for (; str[j]; j++) {
980 if (str[j] == '\\' &&
981 str[j + 1] == history_expansion_char) {
982 len = strlen(&str[j + 1]) + 1;
983 memmove(&str[j], &str[j + 1], len);
987 if (isspace((unsigned char) str[j])
991 if (str[j] == history_expansion_char
992 && !strchr(history_no_expand_chars, str[j + 1])
993 && (!history_inhibit_expansion_function ||
994 (*history_inhibit_expansion_function)(str,
999 if (str[j] && loop_again) {
1001 qchar = (j > 0 && str[j - 1] == '"' )? '"':0;
1003 if (str[j] == history_expansion_char)
1009 ADD_STRING(&str[start], len, 0);
1011 if (str[i] == '\0' || str[i] != history_expansion_char) {
1013 ADD_STRING(&str[i], len, 0);
1020 ret = _history_expand_command (str, i, (j - i), &tmp);
1021 if (ret > 0 && tmp) {
1023 ADD_STRING(tmp, len, 1);
1032 /* ret is 2 for "print only" option */
1034 add_history(result);
1036 /* gdb 4.11 has been shipped with readline, where */
1037 /* history_expand() returned -1 when the line */
1038 /* should not be executed; in readline 2.1+ */
1039 /* it should return 2 in such a case */
1050 * Return a string consisting of arguments of "str" from "start" to "end".
1053 history_arg_extract(int start, int end, const char *str)
1056 char **arr, *result = NULL;
1058 arr = history_tokenize(str);
1061 if (arr && *arr == NULL)
1064 for (max = 0; arr[max]; max++)
1073 end = (int)max + end + 1;
1077 if (start < 0 || end < 0 || (size_t)start > max ||
1078 (size_t)end > max || start > end)
1081 for (i = (size_t)start, len = 0; i <= (size_t)end; i++)
1082 len += strlen(arr[i]) + 1;
1084 result = el_calloc(len, sizeof(*result));
1088 for (i = (size_t)start, len = 0; i <= (size_t)end; i++) {
1089 (void)strcpy(result + len, arr[i]);
1090 len += strlen(arr[i]);
1091 if (i < (size_t)end)
1092 result[len++] = ' ';
1097 for (i = 0; arr[i]; i++)
1105 * Parse the string into individual tokens,
1106 * similar to how shell would do it.
1109 history_tokenize(const char *str)
1111 int size = 1, idx = 0, i, start;
1113 char **result = NULL, *temp, delim = '\0';
1115 for (i = 0; str[i];) {
1116 while (isspace((unsigned char) str[i]))
1120 if (str[i] == '\\') {
1121 if (str[i+1] != '\0')
1123 } else if (str[i] == delim)
1126 (isspace((unsigned char) str[i]) ||
1127 strchr("()<>;&|$", str[i])))
1129 else if (!delim && strchr("'`\"", str[i]))
1135 if (idx + 2 >= size) {
1138 nresult = el_realloc(result, (size_t)size * sizeof(*nresult));
1139 if (nresult == NULL) {
1145 len = (size_t)i - (size_t)start;
1146 temp = el_calloc(len + 1, sizeof(*temp));
1148 for (i = 0; i < idx; i++)
1153 (void)strncpy(temp, &str[start], len);
1155 result[idx++] = temp;
1165 * limit size of history record to ``max'' events
1168 stifle_history(int max)
1173 if (h == NULL || e == NULL)
1176 if (history(h, &ev, H_SETSIZE, max) == 0) {
1177 max_input_history = max;
1178 if (history_length > max)
1179 history_base = history_length - max;
1180 while (history_length > max) {
1181 he = remove_history(0);
1183 el_free((void *)(unsigned long)he->line);
1191 * "unlimit" size of history - set the limit to maximum allowed int value
1194 unstifle_history(void)
1199 history(h, &ev, H_SETSIZE, INT_MAX);
1200 omax = max_input_history;
1201 max_input_history = INT_MAX;
1202 return omax; /* some value _must_ be returned */
1207 history_is_stifled(void)
1210 /* cannot return true answer */
1211 return max_input_history != INT_MAX;
1214 static const char _history_tmp_template[] = "/tmp/.historyXXXXXX";
1217 history_truncate_file (const char *filename, int nlines)
1221 char template[sizeof(_history_tmp_template)];
1229 if (filename == NULL && (filename = _default_history_file()) == NULL)
1231 if ((fp = fopen(filename, "r+")) == NULL)
1233 strcpy(template, _history_tmp_template);
1234 if ((fd = mkstemp(template)) == -1) {
1239 if ((tp = fdopen(fd, "r+")) == NULL) {
1246 if (fread(buf, sizeof(buf), (size_t)1, fp) != 1) {
1251 if (fseeko(fp, (off_t)sizeof(buf) * count, SEEK_SET) ==
1256 left = (ssize_t)fread(buf, (size_t)1, sizeof(buf), fp);
1264 } else if (fwrite(buf, (size_t)left, (size_t)1, tp)
1272 if (fwrite(buf, sizeof(buf), (size_t)1, tp) != 1) {
1280 cp = buf + left - 1;
1284 while (--cp >= buf) {
1286 if (--nlines == 0) {
1287 if (++cp >= buf + sizeof(buf)) {
1295 if (nlines <= 0 || count == 0)
1298 if (fseeko(tp, (off_t)sizeof(buf) * count, SEEK_SET) < 0) {
1302 if (fread(buf, sizeof(buf), (size_t)1, tp) != 1) {
1310 cp = buf + sizeof(buf);
1313 if (ret || nlines > 0)
1316 if (fseeko(fp, (off_t)0, SEEK_SET) == (off_t)-1) {
1321 if (fseeko(tp, (off_t)sizeof(buf) * count + (cp - buf), SEEK_SET) ==
1328 if ((left = (ssize_t)fread(buf, (size_t)1, sizeof(buf), tp)) == 0) {
1333 if (fwrite(buf, (size_t)left, (size_t)1, fp) != 1) {
1339 if((off = ftello(fp)) > 0)
1340 (void)ftruncate(fileno(fp), off);
1353 * read history from a file given
1356 read_history(const char *filename)
1360 if (h == NULL || e == NULL)
1362 if (filename == NULL && (filename = _default_history_file()) == NULL)
1365 if (history(h, &ev, H_LOAD, filename) == -1)
1366 return errno ? errno : EINVAL;
1367 if (history(h, &ev, H_GETSIZE) == 0)
1368 history_length = ev.num;
1369 if (history_length < 0)
1376 * write history to a file given
1379 write_history(const char *filename)
1383 if (h == NULL || e == NULL)
1385 if (filename == NULL && (filename = _default_history_file()) == NULL)
1387 return history(h, &ev, H_SAVE, filename) == -1 ?
1388 (errno ? errno : EINVAL) : 0;
1392 append_history(int n, const char *filename)
1397 if (h == NULL || e == NULL)
1399 if (filename == NULL && (filename = _default_history_file()) == NULL)
1402 if ((fp = fopen(filename, "a")) == NULL)
1405 if (history(h, &ev, H_NSAVE_FP, (size_t)n, fp) == -1) {
1406 int serrno = errno ? errno : EINVAL;
1415 * returns history ``num''th event
1417 * returned pointer points to static variable
1420 history_get(int num)
1422 static HIST_ENTRY she;
1426 if (h == NULL || e == NULL)
1429 if (num < history_base)
1432 /* save current position */
1433 if (history(h, &ev, H_CURR) != 0)
1438 * use H_DELDATA to set to nth history (without delete) by passing
1439 * (void **)-1 -- as in history_set_pos
1441 if (history(h, &ev, H_DELDATA, num - history_base, (void **)-1) != 0)
1444 /* get current entry */
1445 if (history(h, &ev, H_CURR) != 0)
1447 if (history(h, &ev, H_NEXT_EVDATA, ev.num, &she.data) != 0)
1451 /* restore pointer to where it was */
1452 (void)history(h, &ev, H_SET, curr_num);
1457 /* restore pointer to where it was */
1458 (void)history(h, &ev, H_SET, curr_num);
1464 * add the line to history table
1467 add_history(const char *line)
1471 if (h == NULL || e == NULL)
1474 if (history(h, &ev, H_ENTER, line) == -1)
1477 (void)history(h, &ev, H_GETSIZE);
1478 if (ev.num == history_length)
1482 history_length = ev.num;
1489 * remove the specified entry from the history list and return it.
1492 remove_history(int num)
1497 if (h == NULL || e == NULL)
1500 if ((he = el_malloc(sizeof(*he))) == NULL)
1503 if (history(h, &ev, H_DELDATA, num, &he->data) != 0) {
1509 if (history(h, &ev, H_GETSIZE) == 0)
1510 history_length = ev.num;
1517 * replace the line and data of the num-th entry
1520 replace_history_entry(int num, const char *line, histdata_t data)
1526 if (h == NULL || e == NULL)
1529 /* save current position */
1530 if (history(h, &ev, H_CURR) != 0)
1534 /* start from the oldest */
1535 if (history(h, &ev, H_LAST) != 0)
1536 return NULL; /* error */
1538 if ((he = el_malloc(sizeof(*he))) == NULL)
1541 /* look forwards for event matching specified offset */
1542 if (history(h, &ev, H_NEXT_EVDATA, num, &he->data))
1545 he->line = strdup(ev.str);
1546 if (he->line == NULL)
1549 if (history(h, &ev, H_REPLACE, line, data))
1552 /* restore pointer to where it was */
1553 if (history(h, &ev, H_SET, curr_num))
1563 * clear the history list - delete all entries
1570 if (h == NULL || e == NULL)
1573 (void)history(h, &ev, H_CLEAR);
1574 history_offset = history_length = 0;
1579 * returns offset of the current history event
1584 return history_offset;
1587 static HIST_ENTRY **_history_listp;
1588 static HIST_ENTRY *_history_list;
1594 HIST_ENTRY **nlp, *nl;
1597 if (history(h, &ev, H_LAST) != 0)
1600 if ((nlp = el_realloc(_history_listp,
1601 ((size_t)history_length + 1) * sizeof(*nlp))) == NULL)
1603 _history_listp = nlp;
1605 if ((nl = el_realloc(_history_list,
1606 (size_t)history_length * sizeof(*nl))) == NULL)
1612 _history_listp[i] = &_history_list[i];
1613 _history_list[i].line = ev.str;
1614 _history_list[i].data = NULL;
1615 if (i++ == history_length)
1617 } while (history(h, &ev, H_PREV) == 0);
1618 _history_listp[i] = NULL;
1619 return _history_listp;
1623 * returns current history event or NULL if there is no such event
1626 current_history(void)
1630 if (history(h, &ev, H_PREV_EVENT, history_offset + 1) != 0)
1633 rl_he.line = ev.str;
1640 * returns total number of bytes history events' data are using
1643 history_total_bytes(void)
1649 if (history(h, &ev, H_CURR) != 0)
1653 (void)history(h, &ev, H_FIRST);
1656 size += strlen(ev.str) * sizeof(*ev.str);
1657 while (history(h, &ev, H_NEXT) == 0);
1659 /* get to the same position as before */
1660 history(h, &ev, H_PREV_EVENT, curr_num);
1667 * sets the position in the history list to ``pos''
1670 history_set_pos(int pos)
1672 if (pos >= history_length || pos < 0)
1675 history_offset = pos;
1681 * returns previous event in history and shifts pointer accordingly
1682 * Note that readline and editline define directions in opposite ways.
1685 previous_history(void)
1689 if (history_offset == 0)
1692 if (history(h, &ev, H_LAST) != 0)
1696 return current_history();
1701 * returns next event in history and shifts pointer accordingly
1708 if (history_offset >= history_length)
1711 if (history(h, &ev, H_LAST) != 0)
1715 return current_history();
1720 * searches for first history event containing the str
1723 history_search(const char *str, int direction)
1729 if (history(h, &ev, H_CURR) != 0)
1734 if ((strp = strstr(ev.str, str)) != NULL)
1735 return (int)(strp - ev.str);
1736 if (history(h, &ev, direction < 0 ? H_NEXT:H_PREV) != 0)
1739 (void)history(h, &ev, H_SET, curr_num);
1745 * searches for first history event beginning with str
1748 history_search_prefix(const char *str, int direction)
1752 return (history(h, &ev, direction < 0 ?
1753 H_PREV_STR : H_NEXT_STR, str));
1758 * search for event in history containing str, starting at offset
1759 * abs(pos); continue backward, if pos<0, forward otherwise
1763 history_search_pos(const char *str,
1764 int direction __attribute__((__unused__)), int pos)
1769 off = (pos > 0) ? pos : -pos;
1770 pos = (pos > 0) ? 1 : -1;
1772 if (history(h, &ev, H_CURR) != 0)
1776 if (!history_set_pos(off) || history(h, &ev, H_CURR) != 0)
1780 if (strstr(ev.str, str))
1782 if (history(h, &ev, (pos < 0) ? H_PREV : H_NEXT) != 0)
1786 /* set "current" pointer back to previous state */
1787 (void)history(h, &ev,
1788 pos < 0 ? H_NEXT_EVENT : H_PREV_EVENT, curr_num);
1794 /********************************/
1795 /* completion functions */
1798 tilde_expand(char *name)
1800 return fn_tilde_expand(name);
1804 filename_completion_function(const char *name, int state)
1806 return fn_filename_completion_function(name, state);
1810 * a completion generator for usernames; returns _first_ username
1811 * which starts with supplied text
1812 * text contains a partial username preceded by random character
1813 * (usually '~'); state resets search from start (??? should we do that anyway)
1814 * it's the caller's responsibility to free the returned value
1817 username_completion_function(const char *text, int state)
1819 #if defined(HAVE_GETPW_R_POSIX) || defined(HAVE_GETPW_R_DRAFT)
1820 struct passwd pwres;
1823 struct passwd *pass = NULL;
1825 if (text[0] == '\0')
1835 #if defined(HAVE_GETPW_R_POSIX) || defined(HAVE_GETPW_R_DRAFT)
1836 getpwent_r(&pwres, pwbuf, sizeof(pwbuf), &pass) == 0 && pass != NULL
1838 (pass = getpwent()) != NULL
1840 && text[0] == pass->pw_name[0]
1841 && strcmp(text, pass->pw_name) == 0)
1848 return strdup(pass->pw_name);
1853 * el-compatible wrapper to send TSTP on ^Z
1856 static unsigned char
1857 _el_rl_tstp(EditLine *el __attribute__((__unused__)), int ch __attribute__((__unused__)))
1859 (void)kill(0, SIGTSTP);
1865 _rl_completion_append_character_function(const char *dummy
1866 __attribute__((__unused__)))
1869 buf[0] = (char)rl_completion_append_character;
1876 * Display list of strings in columnar format on readline's output stream.
1877 * 'matches' is list of strings, 'len' is number of strings in 'matches',
1878 * 'max' is maximum length of string in 'matches'.
1881 rl_display_match_list(char **matches, int len, int max)
1884 fn_display_match_list(e, matches, (size_t)len, (size_t)max,
1885 _rl_completion_append_character_function);
1889 * complete word at current point
1893 rl_complete(int ignore __attribute__((__unused__)), int invoking_key)
1895 static ct_buffer_t wbreak_conv, sprefix_conv;
1896 const char *breakchars;
1898 if (h == NULL || e == NULL)
1901 if (rl_inhibit_completion) {
1903 arr[0] = (char)invoking_key;
1905 el_insertstr(e, arr);
1909 if (rl_completion_word_break_hook != NULL)
1910 breakchars = (*rl_completion_word_break_hook)();
1912 breakchars = rl_basic_word_break_characters;
1916 /* Just look at how many global variables modify this operation! */
1917 return fn_complete(e,
1918 (rl_compentry_func_t *)rl_completion_entry_function,
1919 rl_attempted_completion_function,
1920 ct_decode_string(rl_basic_word_break_characters, &wbreak_conv),
1921 ct_decode_string(breakchars, &sprefix_conv),
1922 _rl_completion_append_character_function,
1923 (size_t)rl_completion_query_items,
1924 &rl_completion_type, &rl_attempted_completion_over,
1925 &rl_point, &rl_end);
1932 static unsigned char
1933 _el_rl_complete(EditLine *el __attribute__((__unused__)), int ch)
1935 return (unsigned char)rl_complete(0, ch);
1939 * misc other functions
1943 * bind key c to readline-type function func
1946 rl_bind_key(int c, rl_command_func_t *func)
1950 if (h == NULL || e == NULL)
1953 if (func == rl_insert) {
1954 /* XXX notice there is no range checking of ``c'' */
1955 e->el_map.key[c] = ED_INSERT;
1963 * read one key from input - handles chars pushed back
1964 * to input stream also
1969 char fooarr[2 * sizeof(int)];
1971 if (e == NULL || h == NULL)
1974 return el_getc(e, fooarr);
1979 * reset the terminal
1983 rl_reset_terminal(const char *p __attribute__((__unused__)))
1986 if (h == NULL || e == NULL)
1994 * insert character ``c'' back into input stream, ``count'' times
1997 rl_insert(int count, int c)
2001 if (h == NULL || e == NULL)
2004 /* XXX - int -> char conversion can lose on multichars */
2008 for (; count > 0; count--)
2015 rl_insert_text(const char *text)
2017 if (!text || *text == 0)
2020 if (h == NULL || e == NULL)
2023 if (el_insertstr(e, text) < 0)
2025 return (int)strlen(text);
2030 rl_newline(int count __attribute__((__unused__)),
2031 int c __attribute__((__unused__)))
2034 * Readline-4.0 appears to ignore the args.
2036 return rl_insert(1, '\n');
2040 static unsigned char
2041 rl_bind_wrapper(EditLine *el __attribute__((__unused__)), unsigned char c)
2050 /* If rl_done was set by the above call, deal with it here */
2058 rl_add_defun(const char *name, rl_command_func_t *fun, int c)
2061 if ((size_t)c >= sizeof(map) / sizeof(map[0]) || c < 0)
2063 map[(unsigned char)c] = fun;
2064 el_set(e, EL_ADDFN, name, name, rl_bind_wrapper);
2065 vis(dest, c, VIS_WHITE|VIS_NOSLASH, 0);
2066 el_set(e, EL_BIND, dest, name, NULL);
2071 rl_callback_read_char(void)
2073 int count = 0, done = 0;
2074 const char *buf = el_gets(e, &count);
2077 if (buf == NULL || count-- <= 0)
2079 if (count == 0 && buf[0] == e->el_tty.t_c[TS_IO][C_EOF])
2081 if (buf[count] == '\n' || buf[count] == '\r')
2084 if (done && rl_linefunc != NULL) {
2085 el_set(e, EL_UNBUFFERED, 0);
2087 if ((wbuf = strdup(buf)) != NULL)
2091 (*(void (*)(const char *))rl_linefunc)(wbuf);
2092 el_set(e, EL_UNBUFFERED, 1);
2097 rl_callback_handler_install(const char *prompt, rl_vcpfunc_t *linefunc)
2102 (void)rl_set_prompt(prompt);
2103 rl_linefunc = linefunc;
2104 el_set(e, EL_UNBUFFERED, 1);
2108 rl_callback_handler_remove(void)
2119 a[0] = (char)e->el_tty.t_c[TS_IO][C_REPRINT];
2125 rl_get_previous_history(int count, int key)
2137 rl_prep_terminal(int meta_flag __attribute__((__unused__)))
2139 el_set(e, EL_PREP_TERM, 1);
2143 rl_deprep_terminal(void)
2145 el_set(e, EL_PREP_TERM, 0);
2149 rl_read_init_file(const char *s)
2151 return el_source(e, s);
2155 rl_parse_and_bind(const char *line)
2161 tok = tok_init(NULL);
2162 tok_str(tok, line, &argc, &argv);
2163 argc = el_parse(e, argc, argv);
2165 return argc ? 1 : 0;
2169 rl_variable_bind(const char *var, const char *value)
2172 * The proper return value is undocument, but this is what the
2173 * readline source seems to do.
2175 return el_set(e, EL_BIND, "", var, value, NULL) == -1 ? 1 : 0;
2179 rl_stuff_char(int c)
2185 el_insertstr(e, buf);
2190 _rl_event_read_char(EditLine *el, wchar_t *wc)
2194 ssize_t num_read = 0;
2198 while (rl_event_hook) {
2202 #if defined(FIONREAD)
2203 if (ioctl(el->el_infd, FIONREAD, &n) < 0)
2206 num_read = read(el->el_infd, &ch, (size_t)1);
2209 #elif defined(F_SETFL) && defined(O_NDELAY)
2210 if ((n = fcntl(el->el_infd, F_GETFL, 0)) < 0)
2212 if (fcntl(el->el_infd, F_SETFL, n|O_NDELAY) < 0)
2214 num_read = read(el->el_infd, &ch, 1);
2215 if (fcntl(el->el_infd, F_SETFL, n))
2218 /* not non-blocking, but what you gonna do? */
2219 num_read = read(el->el_infd, &ch, 1);
2223 if (num_read < 0 && errno == EAGAIN)
2230 el_set(el, EL_GETCFN, EL_BUILTIN_GETCFN);
2232 return (int)num_read;
2236 _rl_update_pos(void)
2238 const LineInfo *li = el_line(e);
2240 rl_point = (int)(li->cursor - li->buffer);
2241 rl_end = (int)(li->lastchar - li->buffer);
2242 rl_line_buffer[rl_end] = '\0';
2246 rl_get_screen_size(int *rows, int *cols)
2249 el_get(e, EL_GETTC, "li", rows);
2251 el_get(e, EL_GETTC, "co", cols);
2255 rl_set_screen_size(int rows, int cols)
2258 (void)snprintf(buf, sizeof(buf), "%d", rows);
2259 el_set(e, EL_SETTC, "li", buf, NULL);
2260 (void)snprintf(buf, sizeof(buf), "%d", cols);
2261 el_set(e, EL_SETTC, "co", buf, NULL);
2265 rl_completion_matches(const char *str, rl_compentry_func_t *fun)
2267 size_t len, max, i, j, min;
2268 char **list, *match, *a, *b;
2272 if ((list = el_calloc(max, sizeof(*list))) == NULL)
2275 while ((match = (*fun)(str, (int)(len - 1))) != NULL) {
2276 list[len++] = match;
2280 if ((nl = el_realloc(list, max * sizeof(*nl))) == NULL)
2289 if ((list[0] = strdup(list[1])) == NULL)
2293 qsort(&list[1], len - 1, sizeof(*list),
2294 (int (*)(const void *, const void *)) strcmp);
2296 for (i = 1, a = list[i]; i < len - 1; i++, a = b) {
2298 for (j = 0; a[j] && a[j] == b[j]; j++)
2303 if (min == 0 && *str) {
2304 if ((list[0] = strdup(str)) == NULL)
2307 if ((list[0] = el_calloc(min + 1, sizeof(*list[0]))) == NULL)
2309 (void)memcpy(list[0], list[1], min);
2310 list[0][min] = '\0';
2320 rl_filename_completion_function (const char *text, int state)
2322 return fn_filename_completion_function(text, state);
2326 rl_forced_update_display(void)
2328 el_set(e, EL_REFRESH);
2332 _rl_abort_internal(void)
2340 _rl_qsort_string_compare(char **s1, char **s2)
2342 return strcoll(*s1, *s2);
2346 history_get_history_state(void)
2350 if ((hs = el_malloc(sizeof(*hs))) == NULL)
2352 hs->length = history_length;
2358 rl_kill_text(int from __attribute__((__unused__)),
2359 int to __attribute__((__unused__)))
2365 rl_make_bare_keymap(void)
2378 rl_set_keymap(Keymap k __attribute__((__unused__)))
2384 rl_generic_bind(int type __attribute__((__unused__)),
2385 const char * keyseq __attribute__((__unused__)),
2386 const char * data __attribute__((__unused__)),
2387 Keymap k __attribute__((__unused__)))
2394 rl_bind_key_in_map(int key __attribute__((__unused__)),
2395 rl_command_func_t *fun __attribute__((__unused__)),
2396 Keymap k __attribute__((__unused__)))
2401 /* unsupported, but needed by python */
2403 rl_cleanup_after_signal(void)
2408 rl_on_new_line(void)
2414 rl_free_line_state(void)
2420 rl_set_keyboard_input_timeout(int u __attribute__((__unused__)))
2426 rl_resize_terminal(void)
2432 rl_reset_after_signal(void)
2434 if (rl_prep_term_function)
2435 (*rl_prep_term_function)();
2439 rl_echo_signal_char(int sig)
2441 int c = tty_get_signal_character(e, sig);