1 /* $NetBSD: readline.c,v 1.174 2022/04/08 20:11:31 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.174 2022/04/08 20:11:31 christos Exp $");
35 #endif /* not lint && not SCCSID */
37 #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 const 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 rl_hook_func_t *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 const char *rl_basic_word_break_characters = break_chars;
110 char *rl_completer_word_break_characters = NULL;
111 const char *rl_completer_quote_characters = NULL;
112 const char *rl_basic_quote_characters = "\"'";
113 rl_compentry_func_t *rl_completion_entry_function = NULL;
114 char *(*rl_completion_word_break_hook)(void) = NULL;
115 rl_completion_func_t *rl_attempted_completion_function = NULL;
116 rl_hook_func_t *rl_pre_input_hook = NULL;
117 rl_hook_func_t *rl_startup1_hook = NULL;
118 int (*rl_getc_function)(FILE *) = NULL;
119 char *rl_terminal_name = NULL;
120 int rl_already_prompted = 0;
121 int rl_filename_completion_desired = 0;
122 int rl_ignore_completion_duplicates = 0;
123 int readline_echoing_p = 1;
124 int _rl_print_completions_horizontally = 0;
125 VFunction *rl_redisplay_function = NULL;
126 rl_hook_func_t *rl_startup_hook = NULL;
127 VFunction *rl_completion_display_matches_hook = NULL;
128 VFunction *rl_prep_term_function = (VFunction *)rl_prep_terminal;
129 VFunction *rl_deprep_term_function = (VFunction *)rl_deprep_terminal;
130 KEYMAP_ENTRY_ARRAY emacs_meta_keymap;
131 unsigned long rl_readline_state = RL_STATE_NONE;
132 int _rl_complete_mark_directories;
133 rl_icppfunc_t *rl_directory_completion_hook;
134 int rl_completion_suppress_append;
135 int rl_sort_completion_matches;
136 int _rl_completion_prefix_display_length;
138 int history_max_entries;
139 char *rl_display_prompt;
140 int rl_erase_empty_line;
143 * The current prompt string.
145 char *rl_prompt = NULL;
146 char *rl_prompt_saved = NULL;
148 * This is set to character indicating type of completion being done by
149 * rl_complete_internal(); this is available for application completion
152 int rl_completion_type = 0;
155 * If more than this number of items results from query for possible
156 * completions, we ask user if they are sure to really display the list.
158 int rl_completion_query_items = 100;
161 * List of characters which are word break characters, but should be left
162 * in the parsed text when it is passed to the completion function.
163 * Shell uses this to help determine what kind of completing to do.
165 const char *rl_special_prefixes = NULL;
168 * This is the character appended to the completed words if at the end of
169 * the line. Default is ' ' (a space).
171 int rl_completion_append_character = ' ';
173 /* stuff below is used internally by libedit for readline emulation */
175 static History *h = NULL;
176 static EditLine *e = NULL;
177 static rl_command_func_t *map[256];
178 static jmp_buf topbuf;
180 /* internal functions */
181 static unsigned char _el_rl_complete(EditLine *, int);
182 static unsigned char _el_rl_tstp(EditLine *, int);
183 static char *_get_prompt(EditLine *);
184 static int _getc_function(EditLine *, wchar_t *);
185 static int _history_expand_command(const char *, size_t, size_t,
187 static char *_rl_compat_sub(const char *, const char *,
189 static int _rl_event_read_char(EditLine *, wchar_t *);
190 static void _rl_update_pos(void);
192 static HIST_ENTRY rl_he;
196 _get_prompt(EditLine *el __attribute__((__unused__)))
198 rl_already_prompted = 1;
204 * read one key from user defined input function
208 _getc_function(EditLine *el __attribute__((__unused__)), wchar_t *c)
212 i = (*rl_getc_function)(rl_instream);
220 _resize_fun(EditLine *el, void *a)
230 _default_history_file(void)
239 if ((p = getpwuid(getuid())) == NULL)
242 len = strlen(p->pw_dir) + sizeof("/.history");
243 if ((path = malloc(len)) == NULL)
246 (void)snprintf(path, len, "%s/.history", p->pw_dir);
251 * READLINE compatibility stuff
258 rl_set_prompt(const char *prompt)
264 if (rl_prompt != NULL && strcmp(rl_prompt, prompt) == 0)
268 rl_prompt = strdup(prompt);
269 if (rl_prompt == NULL)
272 while ((p = strchr(rl_prompt, RL_PROMPT_END_IGNORE)) != NULL) {
273 /* Remove adjacent end/start markers to avoid double-escapes. */
274 if (p[1] == RL_PROMPT_START_IGNORE) {
275 memmove(p, p + 2, 1 + strlen(p + 2));
277 *p = RL_PROMPT_START_IGNORE;
287 rl_prompt_saved = strdup(rl_prompt);
291 rl_restore_prompt(void)
293 if (!rl_prompt_saved)
295 rl_prompt = rl_prompt_saved;
296 rl_prompt_saved = NULL;
300 * initialize rl compat stuff
314 RL_UNSETSTATE(RL_STATE_DONE);
319 rl_outstream = stdout;
322 * See if we don't really want to run the editor
324 if (tcgetattr(fileno(rl_instream), &t) != -1 && (t.c_lflag & ECHO) == 0)
327 e = el_init_internal(rl_readline_name, rl_instream, rl_outstream,
328 stderr, fileno(rl_instream), fileno(rl_outstream), fileno(stderr),
332 el_set(e, EL_EDITMODE, 0);
338 history(h, &ev, H_SETSIZE, INT_MAX); /* unlimited */
340 max_input_history = INT_MAX;
341 el_set(e, EL_HIST, history, h);
343 /* Setup resize function */
344 el_set(e, EL_RESIZE, _resize_fun, &rl_line_buffer);
346 /* setup getc function if valid */
347 if (rl_getc_function)
348 el_set(e, EL_GETCFN, _getc_function);
350 /* for proper prompt printing in readline() */
351 if (rl_set_prompt("") == -1) {
356 el_set(e, EL_PROMPT_ESC, _get_prompt, RL_PROMPT_START_IGNORE);
357 el_set(e, EL_SIGNAL, rl_catch_signals);
359 /* set default mode to "emacs"-style and read setting afterwards */
360 /* so this can be overridden */
361 el_set(e, EL_EDITOR, "emacs");
362 if (rl_terminal_name != NULL)
363 el_set(e, EL_TERMINAL, rl_terminal_name);
365 el_get(e, EL_TERMINAL, &rl_terminal_name);
368 * Word completion - this has to go AFTER rebinding keys
371 el_set(e, EL_ADDFN, "rl_complete",
372 "ReadLine compatible completion function",
374 el_set(e, EL_BIND, "^I", "rl_complete", NULL);
377 * Send TSTP when ^Z is pressed.
379 el_set(e, EL_ADDFN, "rl_tstp",
380 "ReadLine compatible suspend function",
382 el_set(e, EL_BIND, "^Z", "rl_tstp", NULL);
385 * Set some readline compatible key-bindings.
387 el_set(e, EL_BIND, "^R", "em-inc-search-prev", NULL);
390 * Allow the use of Home/End keys.
392 el_set(e, EL_BIND, "\\e[1~", "ed-move-to-beg", NULL);
393 el_set(e, EL_BIND, "\\e[4~", "ed-move-to-end", NULL);
394 el_set(e, EL_BIND, "\\e[7~", "ed-move-to-beg", NULL);
395 el_set(e, EL_BIND, "\\e[8~", "ed-move-to-end", NULL);
396 el_set(e, EL_BIND, "\\e[H", "ed-move-to-beg", NULL);
397 el_set(e, EL_BIND, "\\e[F", "ed-move-to-end", NULL);
400 * Allow the use of the Delete/Insert keys.
402 el_set(e, EL_BIND, "\\e[3~", "ed-delete-next-char", NULL);
403 el_set(e, EL_BIND, "\\e[2~", "ed-quoted-insert", NULL);
406 * Ctrl-left-arrow and Ctrl-right-arrow for word moving.
408 el_set(e, EL_BIND, "\\e[1;5C", "em-next-word", NULL);
409 el_set(e, EL_BIND, "\\e[1;5D", "ed-prev-word", NULL);
410 el_set(e, EL_BIND, "\\e[5C", "em-next-word", NULL);
411 el_set(e, EL_BIND, "\\e[5D", "ed-prev-word", NULL);
412 el_set(e, EL_BIND, "\\e\\e[C", "em-next-word", NULL);
413 el_set(e, EL_BIND, "\\e\\e[D", "ed-prev-word", NULL);
415 /* read settings from configuration file */
419 * Unfortunately, some applications really do use rl_point
420 * and rl_line_buffer directly.
422 _resize_fun(e, &rl_line_buffer);
425 tty_end(e, TCSADRAIN);
432 * read one line from input stream and return it, chomping
433 * trailing newline (if there is any)
436 readline(const char *p)
439 const char * volatile prompt = p;
443 static int used_event_hook;
445 if (e == NULL || h == NULL)
447 if (rl_startup_hook) {
448 (*rl_startup_hook)();
455 (void)setjmp(topbuf);
458 /* update prompt accordingly to what has been passed */
459 if (rl_set_prompt(prompt) == -1)
462 if (rl_pre_input_hook)
463 (*rl_pre_input_hook)();
465 if (rl_event_hook && !(e->el_flags & NO_TTY)) {
466 el_set(e, EL_GETCFN, _rl_event_read_char);
470 if (!rl_event_hook && used_event_hook) {
471 el_set(e, EL_GETCFN, EL_BUILTIN_GETCFN);
475 rl_already_prompted = 0;
477 /* get one line from input stream */
478 ret = el_gets(e, &count);
480 if (ret && count > 0) {
484 buf[strcspn(buf, "\n")] = '\0';
488 history(h, &ev, H_GETSIZE);
489 history_length = ev.num;
492 tty_end(e, TCSADRAIN);
501 * is normally called before application starts to use
502 * history expansion functions
507 if (h == NULL || e == NULL)
509 history_offset = history_length;
514 * substitute ``what'' with ``with'', returning resulting string; if
515 * globally == 1, substitutes all occurrences of what, otherwise only the
519 _rl_compat_sub(const char *str, const char *what, const char *with,
524 size_t len, with_len, what_len;
527 with_len = strlen(with);
528 what_len = strlen(what);
530 /* calculate length we need for result */
533 if (*s == *what && !strncmp(s, what, what_len)) {
534 len += with_len - what_len;
541 r = result = el_calloc(len + 1, sizeof(*r));
546 if (*s == *what && !strncmp(s, what, what_len)) {
547 memcpy(r, with, with_len);
561 static char *last_search_pat; /* last !?pat[?] search pattern */
562 static char *last_search_match; /* last !?pat[?] that matched */
565 get_history_event(const char *cmd, int *cindex, int qchar)
567 int idx, sign, sub, num, begin, ret;
574 if (cmd[idx++] != history_expansion_char)
577 /* find out which event to take */
578 if (cmd[idx] == history_expansion_char || cmd[idx] == '\0') {
579 if (history(h, &ev, H_FIRST) != 0)
581 *cindex = cmd[idx]? (idx + 1):idx;
585 if (cmd[idx] == '-') {
590 if ('0' <= cmd[idx] && cmd[idx] <= '9') {
594 while (cmd[idx] && '0' <= cmd[idx] && cmd[idx] <= '9') {
595 num = num * 10 + cmd[idx] - '0';
599 num = history_length - num + history_base;
601 if (!(he = history_get(num)))
608 if (cmd[idx] == '?') {
614 if (cmd[idx] == '\n')
616 if (sub && cmd[idx] == '?')
618 if (!sub && (cmd[idx] == ':' || cmd[idx] == ' '
619 || cmd[idx] == '\t' || cmd[idx] == qchar))
623 len = (size_t)idx - (size_t)begin;
624 if (sub && cmd[idx] == '?')
626 if (sub && len == 0 && last_search_pat && *last_search_pat)
627 pat = last_search_pat;
631 if ((pat = el_calloc(len + 1, sizeof(*pat))) == NULL)
633 (void)strlcpy(pat, cmd + begin, len + 1);
636 if (history(h, &ev, H_CURR) != 0) {
637 if (pat != last_search_pat)
644 if (pat != last_search_pat) {
645 el_free(last_search_pat);
646 last_search_pat = pat;
648 ret = history_search(pat, -1);
650 ret = history_search_prefix(pat, -1);
653 /* restore to end of list on failed search */
654 history(h, &ev, H_FIRST);
655 (void)fprintf(rl_outstream, "%s: Event not found\n", pat);
656 if (pat != last_search_pat)
662 el_free(last_search_match);
663 last_search_match = strdup(pat);
666 if (pat != last_search_pat)
669 if (history(h, &ev, H_CURR) != 0)
674 /* roll back to original position */
675 (void)history(h, &ev, H_SET, num);
681 getfrom(const char **cmdp, char **fromp, const char *search, int delim)
685 const char *cmd = *cmdp;
686 char *what = el_realloc(*fromp, size * sizeof(*what));
692 for (; *cmd && *cmd != delim; cmd++) {
693 if (*cmd == '\\' && cmd[1] == delim)
695 if (len - 1 >= size) {
697 nwhat = el_realloc(what, (size <<= 1) * sizeof(*nwhat));
715 *fromp = strdup(search);
716 if (*fromp == NULL) {
730 cmd++; /* shift after delim */
742 getto(const char **cmdp, char **top, const char *from, int delim)
746 size_t from_len = strlen(from);
747 const char *cmd = *cmdp;
748 char *with = el_realloc(*top, size * sizeof(*with));
753 for (; *cmd && *cmd != delim; cmd++) {
754 if (len + from_len + 1 >= size) {
756 size += from_len + 1;
757 nwith = el_realloc(with, size * sizeof(*nwith));
764 strcpy(&with[len], from);
768 if (*cmd == '\\' && (*(cmd + 1) == delim || *(cmd + 1) == '&'))
787 replace(char **tmp, int c)
790 if ((aptr = strrchr(*tmp, c)) == NULL)
792 aptr = strdup(aptr + 1); // XXX: check
798 * the real function doing history expansion - takes as argument command
799 * to do and data upon which the command should be executed
800 * does expansion the way I've understood readline documentation
802 * returns 0 if data was not modified, 1 if it was and 2 if the string
803 * should be only printed and not executed; in case of error,
804 * returns -1 and *result points to NULL
805 * it's the caller's responsibility to free() the string returned in *result
808 _history_expand_command(const char *command, size_t offs, size_t cmdlen,
811 char *tmp, *search = NULL, *aptr, delim;
812 const char *ptr, *cmd;
813 static char *from = NULL, *to = NULL;
814 int start, end, idx, has_mods = 0;
815 int p_on = 0, g_on = 0, ev;
821 /* First get event specifier */
824 if (strchr(":^*$", command[offs + 1])) {
827 * "!:" is shorthand for "!!:".
828 * "!^", "!*" and "!$" are shorthand for
829 * "!!:^", "!!:*" and "!!:$" respectively.
831 str[0] = str[1] = '!';
833 ptr = get_history_event(str, &idx, 0);
834 idx = (command[offs + 1] == ':')? 1:0;
837 if (command[offs + 1] == '#') {
838 /* use command so far */
839 if ((aptr = el_calloc(offs + 1, sizeof(*aptr)))
842 (void)strlcpy(aptr, command, offs + 1);
847 qchar = (offs > 0 && command[offs - 1] == '"')
849 ptr = get_history_event(command + offs, &idx, qchar);
851 has_mods = command[offs + (size_t)idx] == ':';
854 if (ptr == NULL && aptr == NULL)
858 *result = strdup(aptr ? aptr : ptr);
866 cmd = command + offs + idx + 1;
868 /* Now parse any word designators */
870 if (*cmd == '%') /* last word matched by ?pat? */
871 tmp = strdup(last_search_match ? last_search_match : "");
872 else if (strchr("^*$-0123456789", *cmd)) {
875 start = end = 1, cmd++;
876 else if (*cmd == '$')
878 else if (*cmd == '*')
880 else if (*cmd == '-' || isdigit((unsigned char) *cmd)) {
882 while (*cmd && '0' <= *cmd && *cmd <= '9')
883 start = start * 10 + *cmd++ - '0';
886 if (isdigit((unsigned char) cmd[1])) {
889 while (*cmd && '0' <= *cmd && *cmd <= '9')
890 end = end * 10 + *cmd++ - '0';
891 } else if (cmd[1] == '$') {
898 } else if (*cmd == '*')
903 tmp = history_arg_extract(start, end, aptr? aptr:ptr);
905 (void)fprintf(rl_outstream, "%s: Bad word specifier",
906 command + offs + idx);
912 tmp = strdup(aptr? aptr:ptr);
917 if (*cmd == '\0' || ((size_t)(cmd - (command + offs)) >= cmdlen)) {
922 for (; *cmd; cmd++) {
926 case 'h': /* remove trailing path */
927 if ((aptr = strrchr(tmp, '/')) != NULL)
930 case 't': /* remove leading path */
933 case 'r': /* remove trailing suffix */
934 if ((aptr = strrchr(tmp, '.')) != NULL)
937 case 'e': /* remove all but suffix */
940 case 'p': /* print only */
947 if (from == NULL || to == NULL)
953 if (delim == '\0' || *++cmd == '\0')
955 if ((ev = getfrom(&cmd, &from, search, delim)) != 1)
957 if ((ev = getto(&cmd, &to, from, delim)) != 1)
959 aptr = _rl_compat_sub(tmp, from, to, g_on);
979 * csh-style history expansion
982 history_expand(char *str, char **output)
988 if (h == NULL || e == NULL)
991 if (history_expansion_char == 0) {
992 *output = strdup(str);
997 if (str[0] == history_subst_char) {
998 /* ^foo^foo2^ is equivalent to !!:s^foo^foo2^ */
999 *output = el_calloc(strlen(str) + 4 + 1, sizeof(**output));
1000 if (*output == NULL)
1002 (*output)[0] = (*output)[1] = history_expansion_char;
1005 (void)strcpy((*output) + 4, str);
1008 *output = strdup(str);
1009 if (*output == NULL)
1013 #define ADD_STRING(what, len, fr) \
1015 if (idx + len + 1 > size) { \
1016 char *nresult = el_realloc(result, \
1017 (size += len + 1) * sizeof(*nresult)); \
1018 if (nresult == NULL) { \
1025 (void)strlcpy(&result[idx], what, len + 1); \
1032 for (i = 0; str[i];) {
1033 int qchar, loop_again;
1034 size_t len, start, j;
1040 for (; str[j]; j++) {
1041 if (str[j] == '\\' &&
1042 str[j + 1] == history_expansion_char) {
1043 len = strlen(&str[j + 1]) + 1;
1044 memmove(&str[j], &str[j + 1], len);
1048 if (isspace((unsigned char) str[j])
1052 if (str[j] == history_expansion_char
1053 && !strchr(history_no_expand_chars, str[j + 1])
1054 && (!history_inhibit_expansion_function ||
1055 (*history_inhibit_expansion_function)(str,
1060 if (str[j] && loop_again) {
1062 qchar = (j > 0 && str[j - 1] == '"' )? '"':0;
1064 if (str[j] == history_expansion_char)
1070 ADD_STRING(&str[start], len, NULL);
1072 if (str[i] == '\0' || str[i] != history_expansion_char) {
1074 ADD_STRING(&str[i], len, NULL);
1081 ret = _history_expand_command (str, i, (j - i), &tmp);
1082 if (ret > 0 && tmp) {
1084 ADD_STRING(tmp, len, tmp);
1093 /* ret is 2 for "print only" option */
1095 add_history(result);
1097 /* gdb 4.11 has been shipped with readline, where */
1098 /* history_expand() returned -1 when the line */
1099 /* should not be executed; in readline 2.1+ */
1100 /* it should return 2 in such a case */
1111 * Return a string consisting of arguments of "str" from "start" to "end".
1114 history_arg_extract(int start, int end, const char *str)
1117 char **arr, *result = NULL;
1119 arr = history_tokenize(str);
1122 if (arr && *arr == NULL)
1125 for (max = 0; arr[max]; max++)
1134 end = (int)max + end + 1;
1138 if (start < 0 || end < 0 || (size_t)start > max ||
1139 (size_t)end > max || start > end)
1142 for (i = (size_t)start, len = 0; i <= (size_t)end; i++)
1143 len += strlen(arr[i]) + 1;
1145 result = el_calloc(len, sizeof(*result));
1149 for (i = (size_t)start, len = 0; i <= (size_t)end; i++) {
1150 (void)strcpy(result + len, arr[i]);
1151 len += strlen(arr[i]);
1152 if (i < (size_t)end)
1153 result[len++] = ' ';
1158 for (i = 0; arr[i]; i++)
1166 * Parse the string into individual tokens,
1167 * similar to how shell would do it.
1170 history_tokenize(const char *str)
1172 int size = 1, idx = 0, i, start;
1174 char **result = NULL, *temp, delim = '\0';
1176 for (i = 0; str[i];) {
1177 while (isspace((unsigned char) str[i]))
1181 if (str[i] == '\\') {
1182 if (str[i+1] != '\0')
1184 } else if (str[i] == delim)
1187 (isspace((unsigned char) str[i]) ||
1188 strchr("()<>;&|$", str[i])))
1190 else if (!delim && strchr("'`\"", str[i]))
1196 if (idx + 2 >= size) {
1199 nresult = el_realloc(result, (size_t)size * sizeof(*nresult));
1200 if (nresult == NULL) {
1206 len = (size_t)i - (size_t)start;
1207 temp = el_calloc(len + 1, sizeof(*temp));
1209 for (i = 0; i < idx; i++)
1214 (void)strlcpy(temp, &str[start], len + 1);
1215 result[idx++] = temp;
1225 * limit size of history record to ``max'' events
1228 stifle_history(int max)
1233 if (h == NULL || e == NULL)
1236 if (history(h, &ev, H_SETSIZE, max) == 0) {
1237 max_input_history = max;
1238 if (history_length > max)
1239 history_base = history_length - max;
1240 while (history_length > max) {
1241 he = remove_history(0);
1243 el_free((void *)(unsigned long)he->line);
1251 * "unlimit" size of history - set the limit to maximum allowed int value
1254 unstifle_history(void)
1259 history(h, &ev, H_SETSIZE, INT_MAX);
1260 omax = max_input_history;
1261 max_input_history = INT_MAX;
1262 return omax; /* some value _must_ be returned */
1267 history_is_stifled(void)
1270 /* cannot return true answer */
1271 return max_input_history != INT_MAX;
1274 static const char _history_tmp_template[] = "/tmp/.historyXXXXXX";
1277 history_truncate_file (const char *filename, int nlines)
1281 char template[sizeof(_history_tmp_template)];
1289 if (filename == NULL && (filename = _default_history_file()) == NULL)
1291 if ((fp = fopen(filename, "r+")) == NULL)
1293 strcpy(template, _history_tmp_template);
1294 if ((fd = mkstemp(template)) == -1) {
1299 if ((tp = fdopen(fd, "r+")) == NULL) {
1306 if (fread(buf, sizeof(buf), (size_t)1, fp) != 1) {
1311 if (fseeko(fp, (off_t)sizeof(buf) * count, SEEK_SET) ==
1316 left = (ssize_t)fread(buf, (size_t)1, sizeof(buf), fp);
1324 } else if (fwrite(buf, (size_t)left, (size_t)1, tp)
1332 if (fwrite(buf, sizeof(buf), (size_t)1, tp) != 1) {
1340 cp = buf + left - 1;
1344 while (--cp >= buf) {
1346 if (--nlines == 0) {
1347 if (++cp >= buf + sizeof(buf)) {
1355 if (nlines <= 0 || count == 0)
1358 if (fseeko(tp, (off_t)sizeof(buf) * count, SEEK_SET) < 0) {
1362 if (fread(buf, sizeof(buf), (size_t)1, tp) != 1) {
1370 cp = buf + sizeof(buf);
1373 if (ret || nlines > 0)
1376 if (fseeko(fp, (off_t)0, SEEK_SET) == (off_t)-1) {
1381 if (fseeko(tp, (off_t)sizeof(buf) * count + (cp - buf), SEEK_SET) ==
1388 if ((left = (ssize_t)fread(buf, (size_t)1, sizeof(buf), tp)) == 0) {
1393 if (fwrite(buf, (size_t)left, (size_t)1, fp) != 1) {
1399 if((off = ftello(fp)) > 0)
1400 (void)ftruncate(fileno(fp), off);
1413 * read history from a file given
1416 read_history(const char *filename)
1420 if (h == NULL || e == NULL)
1422 if (filename == NULL && (filename = _default_history_file()) == NULL)
1425 if (history(h, &ev, H_LOAD, filename) == -1)
1426 return errno ? errno : EINVAL;
1427 if (history(h, &ev, H_GETSIZE) == 0)
1428 history_length = ev.num;
1429 if (history_length < 0)
1436 * write history to a file given
1439 write_history(const char *filename)
1443 if (h == NULL || e == NULL)
1445 if (filename == NULL && (filename = _default_history_file()) == NULL)
1447 return history(h, &ev, H_SAVE, filename) == -1 ?
1448 (errno ? errno : EINVAL) : 0;
1452 append_history(int n, const char *filename)
1457 if (h == NULL || e == NULL)
1459 if (filename == NULL && (filename = _default_history_file()) == NULL)
1462 if ((fp = fopen(filename, "a")) == NULL)
1465 if (history(h, &ev, H_NSAVE_FP, (size_t)n, fp) == -1) {
1466 int serrno = errno ? errno : EINVAL;
1475 * returns history ``num''th event
1477 * returned pointer points to static variable
1480 history_get(int num)
1482 static HIST_ENTRY she;
1486 if (h == NULL || e == NULL)
1489 if (num < history_base)
1492 /* save current position */
1493 if (history(h, &ev, H_CURR) != 0)
1498 * use H_DELDATA to set to nth history (without delete) by passing
1499 * (void **)-1 -- as in history_set_pos
1501 if (history(h, &ev, H_DELDATA, num - history_base, (void **)-1) != 0)
1504 /* get current entry */
1505 if (history(h, &ev, H_CURR) != 0)
1507 if (history(h, &ev, H_NEXT_EVDATA, ev.num, &she.data) != 0)
1511 /* restore pointer to where it was */
1512 (void)history(h, &ev, H_SET, curr_num);
1517 /* restore pointer to where it was */
1518 (void)history(h, &ev, H_SET, curr_num);
1524 * add the line to history table
1527 add_history(const char *line)
1531 if (h == NULL || e == NULL)
1534 if (history(h, &ev, H_ENTER, line) == -1)
1537 (void)history(h, &ev, H_GETSIZE);
1538 if (ev.num == history_length)
1542 history_length = ev.num;
1549 * remove the specified entry from the history list and return it.
1552 remove_history(int num)
1557 if (h == NULL || e == NULL)
1560 if ((he = el_malloc(sizeof(*he))) == NULL)
1563 if (history(h, &ev, H_DELDATA, num, &he->data) != 0) {
1569 if (history(h, &ev, H_GETSIZE) == 0)
1570 history_length = ev.num;
1577 * replace the line and data of the num-th entry
1580 replace_history_entry(int num, const char *line, histdata_t data)
1586 if (h == NULL || e == NULL)
1589 /* save current position */
1590 if (history(h, &ev, H_CURR) != 0)
1594 /* start from the oldest */
1595 if (history(h, &ev, H_LAST) != 0)
1596 return NULL; /* error */
1598 if ((he = el_malloc(sizeof(*he))) == NULL)
1601 /* look forwards for event matching specified offset */
1602 if (history(h, &ev, H_NEXT_EVDATA, num, &he->data))
1605 he->line = strdup(ev.str);
1606 if (he->line == NULL)
1609 if (history(h, &ev, H_REPLACE, line, data))
1612 /* restore pointer to where it was */
1613 if (history(h, &ev, H_SET, curr_num))
1623 * clear the history list - delete all entries
1630 if (h == NULL || e == NULL)
1633 (void)history(h, &ev, H_CLEAR);
1634 history_offset = history_length = 0;
1639 * returns offset of the current history event
1644 return history_offset;
1647 static HIST_ENTRY **_history_listp;
1648 static HIST_ENTRY *_history_list;
1654 HIST_ENTRY **nlp, *nl;
1657 if (history(h, &ev, H_LAST) != 0)
1660 if ((nlp = el_realloc(_history_listp,
1661 ((size_t)history_length + 1) * sizeof(*nlp))) == NULL)
1663 _history_listp = nlp;
1665 if ((nl = el_realloc(_history_list,
1666 (size_t)history_length * sizeof(*nl))) == NULL)
1672 _history_listp[i] = &_history_list[i];
1673 _history_list[i].line = ev.str;
1674 _history_list[i].data = NULL;
1675 if (i++ == history_length)
1677 } while (history(h, &ev, H_PREV) == 0);
1678 _history_listp[i] = NULL;
1679 return _history_listp;
1683 * returns current history event or NULL if there is no such event
1686 current_history(void)
1690 if (history(h, &ev, H_PREV_EVENT, history_offset + 1) != 0)
1693 rl_he.line = ev.str;
1700 * returns total number of bytes history events' data are using
1703 history_total_bytes(void)
1709 if (history(h, &ev, H_CURR) != 0)
1713 (void)history(h, &ev, H_FIRST);
1716 size += strlen(ev.str) * sizeof(*ev.str);
1717 while (history(h, &ev, H_NEXT) == 0);
1719 /* get to the same position as before */
1720 history(h, &ev, H_PREV_EVENT, curr_num);
1727 * sets the position in the history list to ``pos''
1730 history_set_pos(int pos)
1732 if (pos >= history_length || pos < 0)
1735 history_offset = pos;
1741 * returns previous event in history and shifts pointer accordingly
1742 * Note that readline and editline define directions in opposite ways.
1745 previous_history(void)
1749 if (history_offset == 0)
1752 if (history(h, &ev, H_LAST) != 0)
1756 return current_history();
1761 * returns next event in history and shifts pointer accordingly
1768 if (history_offset >= history_length)
1771 if (history(h, &ev, H_LAST) != 0)
1775 return current_history();
1780 * searches for first history event containing the str
1783 history_search(const char *str, int direction)
1789 if (history(h, &ev, H_CURR) != 0)
1794 if ((strp = strstr(ev.str, str)) != NULL)
1795 return (int)(strp - ev.str);
1796 if (history(h, &ev, direction < 0 ? H_NEXT:H_PREV) != 0)
1799 (void)history(h, &ev, H_SET, curr_num);
1805 * searches for first history event beginning with str
1808 history_search_prefix(const char *str, int direction)
1812 return (history(h, &ev, direction < 0 ?
1813 H_PREV_STR : H_NEXT_STR, str));
1818 * search for event in history containing str, starting at offset
1819 * abs(pos); continue backward, if pos<0, forward otherwise
1823 history_search_pos(const char *str,
1824 int direction __attribute__((__unused__)), int pos)
1829 off = (pos > 0) ? pos : -pos;
1830 pos = (pos > 0) ? 1 : -1;
1832 if (history(h, &ev, H_CURR) != 0)
1836 if (!history_set_pos(off) || history(h, &ev, H_CURR) != 0)
1840 if (strstr(ev.str, str))
1842 if (history(h, &ev, (pos < 0) ? H_PREV : H_NEXT) != 0)
1846 /* set "current" pointer back to previous state */
1847 (void)history(h, &ev,
1848 pos < 0 ? H_NEXT_EVENT : H_PREV_EVENT, curr_num);
1854 /********************************/
1855 /* completion functions */
1858 tilde_expand(char *name)
1860 return fn_tilde_expand(name);
1864 filename_completion_function(const char *name, int state)
1866 return fn_filename_completion_function(name, state);
1870 * a completion generator for usernames; returns _first_ username
1871 * which starts with supplied text
1872 * text contains a partial username preceded by random character
1873 * (usually '~'); state resets search from start (??? should we do that anyway)
1874 * it's the caller's responsibility to free the returned value
1877 username_completion_function(const char *text, int state)
1879 #if defined(HAVE_GETPW_R_POSIX) || defined(HAVE_GETPW_R_DRAFT)
1880 struct passwd pwres;
1883 struct passwd *pass = NULL;
1885 if (text[0] == '\0')
1895 #if defined(HAVE_GETPW_R_POSIX) || defined(HAVE_GETPW_R_DRAFT)
1896 getpwent_r(&pwres, pwbuf, sizeof(pwbuf), &pass) == 0 && pass != NULL
1898 (pass = getpwent()) != NULL
1900 && text[0] == pass->pw_name[0]
1901 && strcmp(text, pass->pw_name) == 0)
1908 return strdup(pass->pw_name);
1913 * el-compatible wrapper to send TSTP on ^Z
1916 static unsigned char
1917 _el_rl_tstp(EditLine *el __attribute__((__unused__)), int ch __attribute__((__unused__)))
1919 (void)kill(0, SIGTSTP);
1925 _rl_completion_append_character_function(const char *dummy
1926 __attribute__((__unused__)))
1929 buf[0] = (char)rl_completion_append_character;
1936 * Display list of strings in columnar format on readline's output stream.
1937 * 'matches' is list of strings, 'len' is number of strings in 'matches',
1938 * 'max' is maximum length of string in 'matches'.
1941 rl_display_match_list(char **matches, int len, int max)
1944 fn_display_match_list(e, matches, (size_t)len, (size_t)max,
1945 _rl_completion_append_character_function);
1949 * complete word at current point
1953 rl_complete(int ignore __attribute__((__unused__)), int invoking_key)
1955 static ct_buffer_t wbreak_conv, sprefix_conv;
1956 const char *breakchars;
1958 if (h == NULL || e == NULL)
1961 if (rl_inhibit_completion) {
1963 arr[0] = (char)invoking_key;
1965 el_insertstr(e, arr);
1969 if (rl_completion_word_break_hook != NULL)
1970 breakchars = (*rl_completion_word_break_hook)();
1972 breakchars = rl_basic_word_break_characters;
1976 /* Just look at how many global variables modify this operation! */
1977 return fn_complete(e,
1978 (rl_compentry_func_t *)rl_completion_entry_function,
1979 rl_attempted_completion_function,
1980 ct_decode_string(rl_basic_word_break_characters, &wbreak_conv),
1981 ct_decode_string(breakchars, &sprefix_conv),
1982 _rl_completion_append_character_function,
1983 (size_t)rl_completion_query_items,
1984 &rl_completion_type, &rl_attempted_completion_over,
1985 &rl_point, &rl_end);
1992 static unsigned char
1993 _el_rl_complete(EditLine *el __attribute__((__unused__)), int ch)
1995 return (unsigned char)rl_complete(0, ch);
1999 * misc other functions
2003 * bind key c to readline-type function func
2006 rl_bind_key(int c, rl_command_func_t *func)
2010 if (h == NULL || e == NULL)
2013 if (func == rl_insert) {
2014 /* XXX notice there is no range checking of ``c'' */
2015 e->el_map.key[c] = ED_INSERT;
2023 * read one key from input - handles chars pushed back
2024 * to input stream also
2029 char fooarr[2 * sizeof(int)];
2031 if (e == NULL || h == NULL)
2034 return el_getc(e, fooarr);
2039 * reset the terminal
2043 rl_reset_terminal(const char *p __attribute__((__unused__)))
2046 if (h == NULL || e == NULL)
2054 * insert character ``c'' back into input stream, ``count'' times
2057 rl_insert(int count, int c)
2061 if (h == NULL || e == NULL)
2064 /* XXX - int -> char conversion can lose on multichars */
2068 for (; count > 0; count--)
2075 rl_insert_text(const char *text)
2077 if (!text || *text == 0)
2080 if (h == NULL || e == NULL)
2083 if (el_insertstr(e, text) < 0)
2085 return (int)strlen(text);
2090 rl_newline(int count __attribute__((__unused__)),
2091 int c __attribute__((__unused__)))
2094 * Readline-4.0 appears to ignore the args.
2096 return rl_insert(1, '\n');
2100 static unsigned char
2101 rl_bind_wrapper(EditLine *el __attribute__((__unused__)), unsigned char c)
2110 /* If rl_done was set by the above call, deal with it here */
2118 rl_add_defun(const char *name, rl_command_func_t *fun, int c)
2121 if ((size_t)c >= sizeof(map) / sizeof(map[0]) || c < 0)
2123 map[(unsigned char)c] = fun;
2124 el_set(e, EL_ADDFN, name, name, rl_bind_wrapper);
2125 vis(dest, c, VIS_WHITE|VIS_NOSLASH, 0);
2126 el_set(e, EL_BIND, dest, name, NULL);
2131 rl_callback_read_char(void)
2133 int count = 0, done = 0;
2134 const char *buf = el_gets(e, &count);
2137 el_set(e, EL_UNBUFFERED, 1);
2138 if (buf == NULL || count-- <= 0)
2140 if (count == 0 && buf[0] == e->el_tty.t_c[TS_IO][C_EOF])
2142 if (buf[count] == '\n' || buf[count] == '\r')
2145 if (done && rl_linefunc != NULL) {
2146 el_set(e, EL_UNBUFFERED, 0);
2148 if ((wbuf = strdup(buf)) != NULL)
2150 RL_SETSTATE(RL_STATE_DONE);
2153 (*(void (*)(const char *))rl_linefunc)(wbuf);
2159 rl_callback_handler_install(const char *prompt, rl_vcpfunc_t *linefunc)
2164 (void)rl_set_prompt(prompt);
2165 rl_linefunc = linefunc;
2166 el_set(e, EL_UNBUFFERED, 1);
2170 rl_callback_handler_remove(void)
2172 el_set(e, EL_UNBUFFERED, 0);
2180 a[0] = (char)e->el_tty.t_c[TS_IO][C_REPRINT];
2183 rl_forced_update_display();
2187 rl_get_previous_history(int count, int key)
2199 rl_prep_terminal(int meta_flag __attribute__((__unused__)))
2201 el_set(e, EL_PREP_TERM, 1);
2205 rl_deprep_terminal(void)
2207 el_set(e, EL_PREP_TERM, 0);
2211 rl_read_init_file(const char *s)
2213 return el_source(e, s);
2217 rl_parse_and_bind(const char *line)
2223 tok = tok_init(NULL);
2224 tok_str(tok, line, &argc, &argv);
2225 argc = el_parse(e, argc, argv);
2227 return argc ? 1 : 0;
2231 rl_variable_bind(const char *var, const char *value)
2234 * The proper return value is undocument, but this is what the
2235 * readline source seems to do.
2237 return el_set(e, EL_BIND, "", var, value, NULL) == -1 ? 1 : 0;
2241 rl_stuff_char(int c)
2247 el_insertstr(e, buf);
2252 _rl_event_read_char(EditLine *el, wchar_t *wc)
2256 ssize_t num_read = 0;
2260 while (rl_event_hook) {
2264 #if defined(FIONREAD)
2265 if (ioctl(el->el_infd, FIONREAD, &n) < 0)
2268 num_read = read(el->el_infd, &ch, (size_t)1);
2271 #elif defined(F_SETFL) && defined(O_NDELAY)
2272 if ((n = fcntl(el->el_infd, F_GETFL, 0)) < 0)
2274 if (fcntl(el->el_infd, F_SETFL, n|O_NDELAY) < 0)
2276 num_read = read(el->el_infd, &ch, 1);
2277 if (fcntl(el->el_infd, F_SETFL, n))
2280 /* not non-blocking, but what you gonna do? */
2281 num_read = read(el->el_infd, &ch, 1);
2285 if (num_read < 0 && errno == EAGAIN)
2292 el_set(el, EL_GETCFN, EL_BUILTIN_GETCFN);
2294 return (int)num_read;
2298 _rl_update_pos(void)
2300 const LineInfo *li = el_line(e);
2302 rl_point = (int)(li->cursor - li->buffer);
2303 rl_end = (int)(li->lastchar - li->buffer);
2304 rl_line_buffer[rl_end] = '\0';
2308 rl_copy_text(int from, int to)
2314 if (h == NULL || e == NULL)
2322 if (li->buffer + from > li->lastchar)
2323 from = (int)(li->lastchar - li->buffer);
2325 if (li->buffer + to > li->lastchar)
2326 to = (int)(li->lastchar - li->buffer);
2328 len = (size_t)(to - from);
2329 out = el_malloc((size_t)len + 1);
2330 (void)strlcpy(out, li->buffer + from , len);
2336 rl_replace_line(const char * text, int clear_undo __attribute__((__unused__)))
2338 if (!text || *text == 0)
2341 if (h == NULL || e == NULL)
2344 el_replacestr(e, text);
2348 rl_delete_text(int start, int end)
2351 if (h == NULL || e == NULL)
2354 return el_deletestr1(e, start, end);
2358 rl_get_screen_size(int *rows, int *cols)
2361 el_get(e, EL_GETTC, "li", rows);
2363 el_get(e, EL_GETTC, "co", cols);
2366 #define MAX_MESSAGE 160
2368 rl_message(const char *format, ...)
2370 char msg[MAX_MESSAGE];
2373 va_start(args, format);
2374 vsnprintf(msg, sizeof(msg), format, args);
2378 rl_forced_update_display();
2382 rl_set_screen_size(int rows, int cols)
2385 (void)snprintf(buf, sizeof(buf), "%d", rows);
2386 el_set(e, EL_SETTC, "li", buf, NULL);
2387 (void)snprintf(buf, sizeof(buf), "%d", cols);
2388 el_set(e, EL_SETTC, "co", buf, NULL);
2392 rl_completion_matches(const char *str, rl_compentry_func_t *fun)
2394 size_t len, max, i, j, min;
2395 char **list, *match, *a, *b;
2399 if ((list = el_calloc(max, sizeof(*list))) == NULL)
2402 while ((match = (*fun)(str, (int)(len - 1))) != NULL) {
2403 list[len++] = match;
2407 if ((nl = el_realloc(list, max * sizeof(*nl))) == NULL)
2416 if ((list[0] = strdup(list[1])) == NULL)
2420 qsort(&list[1], len - 1, sizeof(*list),
2421 (int (*)(const void *, const void *)) strcmp);
2423 for (i = 1, a = list[i]; i < len - 1; i++, a = b) {
2425 for (j = 0; a[j] && a[j] == b[j]; j++)
2430 if (min == 0 && *str) {
2431 if ((list[0] = strdup(str)) == NULL)
2434 if ((list[0] = el_calloc(min + 1, sizeof(*list[0]))) == NULL)
2436 (void)memcpy(list[0], list[1], min);
2437 list[0][min] = '\0';
2447 rl_filename_completion_function (const char *text, int state)
2449 return fn_filename_completion_function(text, state);
2453 rl_forced_update_display(void)
2455 el_set(e, EL_REFRESH);
2459 _rl_abort_internal(void)
2467 _rl_qsort_string_compare(char **s1, char **s2)
2469 return strcoll(*s1, *s2);
2473 history_get_history_state(void)
2477 if ((hs = el_malloc(sizeof(*hs))) == NULL)
2479 hs->length = history_length;
2485 rl_kill_text(int from __attribute__((__unused__)),
2486 int to __attribute__((__unused__)))
2492 rl_make_bare_keymap(void)
2505 rl_set_keymap(Keymap k __attribute__((__unused__)))
2511 rl_generic_bind(int type __attribute__((__unused__)),
2512 const char * keyseq __attribute__((__unused__)),
2513 const char * data __attribute__((__unused__)),
2514 Keymap k __attribute__((__unused__)))
2521 rl_bind_key_in_map(int key __attribute__((__unused__)),
2522 rl_command_func_t *fun __attribute__((__unused__)),
2523 Keymap k __attribute__((__unused__)))
2529 rl_set_key(const char *keyseq __attribute__((__unused__)),
2530 rl_command_func_t *function __attribute__((__unused__)),
2531 Keymap k __attribute__((__unused__)))
2536 /* unsupported, but needed by python */
2538 rl_cleanup_after_signal(void)
2543 rl_on_new_line(void)
2549 rl_free_line_state(void)
2555 rl_set_keyboard_input_timeout(int u __attribute__((__unused__)))
2561 rl_resize_terminal(void)
2567 rl_reset_after_signal(void)
2569 if (rl_prep_term_function)
2570 (*rl_prep_term_function)();
2574 rl_echo_signal_char(int sig)
2576 int c = tty_get_signal_character(e, sig);
2585 re_putc(e, '\n', 0);
2592 re_putc(e, '\a', 0);
2597 rl_abort(int count, int key)
2599 return count && key ? 0 : 0;
2603 rl_set_keymap_name(const char *name, Keymap k)
2605 return name && k ? 0 : 0;
2609 free_history_entry(HIST_ENTRY *he)
2611 return he ? NULL : NULL;
2615 _rl_erase_entire_line(void)