1 /* $NetBSD: readline.c,v 1.168 2021/09/10 18:51:36 rillig 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.168 2021/09/10 18:51:36 rillig 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 const char *rl_basic_quote_characters = "\"'";
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;
130 unsigned long rl_readline_state;
131 int _rl_complete_mark_directories;
132 rl_icppfunc_t *rl_directory_completion_hook;
133 int rl_completion_suppress_append;
134 int rl_sort_completion_matches;
135 int _rl_completion_prefix_display_length;
137 int history_max_entries;
138 char *rl_display_prompt;
141 * The current prompt string.
143 char *rl_prompt = NULL;
145 * This is set to character indicating type of completion being done by
146 * rl_complete_internal(); this is available for application completion
149 int rl_completion_type = 0;
152 * If more than this number of items results from query for possible
153 * completions, we ask user if they are sure to really display the list.
155 int rl_completion_query_items = 100;
158 * List of characters which are word break characters, but should be left
159 * in the parsed text when it is passed to the completion function.
160 * Shell uses this to help determine what kind of completing to do.
162 const char *rl_special_prefixes = NULL;
165 * This is the character appended to the completed words if at the end of
166 * the line. Default is ' ' (a space).
168 int rl_completion_append_character = ' ';
170 /* stuff below is used internally by libedit for readline emulation */
172 static History *h = NULL;
173 static EditLine *e = NULL;
174 static rl_command_func_t *map[256];
175 static jmp_buf topbuf;
177 /* internal functions */
178 static unsigned char _el_rl_complete(EditLine *, int);
179 static unsigned char _el_rl_tstp(EditLine *, int);
180 static char *_get_prompt(EditLine *);
181 static int _getc_function(EditLine *, wchar_t *);
182 static int _history_expand_command(const char *, size_t, size_t,
184 static char *_rl_compat_sub(const char *, const char *,
186 static int _rl_event_read_char(EditLine *, wchar_t *);
187 static void _rl_update_pos(void);
189 static HIST_ENTRY rl_he;
193 _get_prompt(EditLine *el __attribute__((__unused__)))
195 rl_already_prompted = 1;
201 * read one key from user defined input function
205 _getc_function(EditLine *el __attribute__((__unused__)), wchar_t *c)
209 i = (*rl_getc_function)(rl_instream);
217 _resize_fun(EditLine *el, void *a)
227 _default_history_file(void)
236 if ((p = getpwuid(getuid())) == NULL)
239 len = strlen(p->pw_dir) + sizeof("/.history");
240 if ((path = malloc(len)) == NULL)
243 (void)snprintf(path, len, "%s/.history", p->pw_dir);
248 * READLINE compatibility stuff
255 rl_set_prompt(const char *prompt)
261 if (rl_prompt != NULL && strcmp(rl_prompt, prompt) == 0)
265 rl_prompt = strdup(prompt);
266 if (rl_prompt == NULL)
269 while ((p = strchr(rl_prompt, RL_PROMPT_END_IGNORE)) != NULL) {
270 /* Remove adjacent end/start markers to avoid double-escapes. */
271 if (p[1] == RL_PROMPT_START_IGNORE) {
272 memmove(p, p + 2, 1 + strlen(p + 2));
274 *p = RL_PROMPT_START_IGNORE;
282 * initialize rl compat stuff
299 rl_outstream = stdout;
302 * See if we don't really want to run the editor
304 if (tcgetattr(fileno(rl_instream), &t) != -1 && (t.c_lflag & ECHO) == 0)
307 e = el_init_internal(rl_readline_name, rl_instream, rl_outstream,
308 stderr, fileno(rl_instream), fileno(rl_outstream), fileno(stderr),
312 el_set(e, EL_EDITMODE, 0);
318 history(h, &ev, H_SETSIZE, INT_MAX); /* unlimited */
320 max_input_history = INT_MAX;
321 el_set(e, EL_HIST, history, h);
323 /* Setup resize function */
324 el_set(e, EL_RESIZE, _resize_fun, &rl_line_buffer);
326 /* setup getc function if valid */
327 if (rl_getc_function)
328 el_set(e, EL_GETCFN, _getc_function);
330 /* for proper prompt printing in readline() */
331 if (rl_set_prompt("") == -1) {
336 el_set(e, EL_PROMPT_ESC, _get_prompt, RL_PROMPT_START_IGNORE);
337 el_set(e, EL_SIGNAL, rl_catch_signals);
339 /* set default mode to "emacs"-style and read setting afterwards */
340 /* so this can be overridden */
341 el_set(e, EL_EDITOR, "emacs");
342 if (rl_terminal_name != NULL)
343 el_set(e, EL_TERMINAL, rl_terminal_name);
345 el_get(e, EL_TERMINAL, &rl_terminal_name);
348 * Word completion - this has to go AFTER rebinding keys
351 el_set(e, EL_ADDFN, "rl_complete",
352 "ReadLine compatible completion function",
354 el_set(e, EL_BIND, "^I", "rl_complete", NULL);
357 * Send TSTP when ^Z is pressed.
359 el_set(e, EL_ADDFN, "rl_tstp",
360 "ReadLine compatible suspend function",
362 el_set(e, EL_BIND, "^Z", "rl_tstp", NULL);
365 * Set some readline compatible key-bindings.
367 el_set(e, EL_BIND, "^R", "em-inc-search-prev", NULL);
370 * Allow the use of Home/End keys.
372 el_set(e, EL_BIND, "\\e[1~", "ed-move-to-beg", NULL);
373 el_set(e, EL_BIND, "\\e[4~", "ed-move-to-end", NULL);
374 el_set(e, EL_BIND, "\\e[7~", "ed-move-to-beg", NULL);
375 el_set(e, EL_BIND, "\\e[8~", "ed-move-to-end", NULL);
376 el_set(e, EL_BIND, "\\e[H", "ed-move-to-beg", NULL);
377 el_set(e, EL_BIND, "\\e[F", "ed-move-to-end", NULL);
380 * Allow the use of the Delete/Insert keys.
382 el_set(e, EL_BIND, "\\e[3~", "ed-delete-next-char", NULL);
383 el_set(e, EL_BIND, "\\e[2~", "ed-quoted-insert", NULL);
386 * Ctrl-left-arrow and Ctrl-right-arrow for word moving.
388 el_set(e, EL_BIND, "\\e[1;5C", "em-next-word", NULL);
389 el_set(e, EL_BIND, "\\e[1;5D", "ed-prev-word", NULL);
390 el_set(e, EL_BIND, "\\e[5C", "em-next-word", NULL);
391 el_set(e, EL_BIND, "\\e[5D", "ed-prev-word", NULL);
392 el_set(e, EL_BIND, "\\e\\e[C", "em-next-word", NULL);
393 el_set(e, EL_BIND, "\\e\\e[D", "ed-prev-word", NULL);
395 /* read settings from configuration file */
399 * Unfortunately, some applications really do use rl_point
400 * and rl_line_buffer directly.
402 _resize_fun(e, &rl_line_buffer);
405 tty_end(e, TCSADRAIN);
412 * read one line from input stream and return it, chomping
413 * trailing newline (if there is any)
416 readline(const char *p)
419 const char * volatile prompt = p;
423 static int used_event_hook;
425 if (e == NULL || h == NULL)
427 if (rl_startup_hook) {
428 (*rl_startup_hook)(NULL, 0);
435 (void)setjmp(topbuf);
438 /* update prompt accordingly to what has been passed */
439 if (rl_set_prompt(prompt) == -1)
442 if (rl_pre_input_hook)
443 (*rl_pre_input_hook)(NULL, 0);
445 if (rl_event_hook && !(e->el_flags & NO_TTY)) {
446 el_set(e, EL_GETCFN, _rl_event_read_char);
450 if (!rl_event_hook && used_event_hook) {
451 el_set(e, EL_GETCFN, EL_BUILTIN_GETCFN);
455 rl_already_prompted = 0;
457 /* get one line from input stream */
458 ret = el_gets(e, &count);
460 if (ret && count > 0) {
464 buf[strcspn(buf, "\n")] = '\0';
468 history(h, &ev, H_GETSIZE);
469 history_length = ev.num;
472 tty_end(e, TCSADRAIN);
481 * is normally called before application starts to use
482 * history expansion functions
487 if (h == NULL || e == NULL)
489 history_offset = history_length;
494 * substitute ``what'' with ``with'', returning resulting string; if
495 * globally == 1, substitutes all occurrences of what, otherwise only the
499 _rl_compat_sub(const char *str, const char *what, const char *with,
504 size_t len, with_len, what_len;
507 with_len = strlen(with);
508 what_len = strlen(what);
510 /* calculate length we need for result */
513 if (*s == *what && !strncmp(s, what, what_len)) {
514 len += with_len - what_len;
521 r = result = el_calloc(len + 1, sizeof(*r));
526 if (*s == *what && !strncmp(s, what, what_len)) {
527 memcpy(r, with, with_len);
541 static char *last_search_pat; /* last !?pat[?] search pattern */
542 static char *last_search_match; /* last !?pat[?] that matched */
545 get_history_event(const char *cmd, int *cindex, int qchar)
547 int idx, sign, sub, num, begin, ret;
554 if (cmd[idx++] != history_expansion_char)
557 /* find out which event to take */
558 if (cmd[idx] == history_expansion_char || cmd[idx] == '\0') {
559 if (history(h, &ev, H_FIRST) != 0)
561 *cindex = cmd[idx]? (idx + 1):idx;
565 if (cmd[idx] == '-') {
570 if ('0' <= cmd[idx] && cmd[idx] <= '9') {
574 while (cmd[idx] && '0' <= cmd[idx] && cmd[idx] <= '9') {
575 num = num * 10 + cmd[idx] - '0';
579 num = history_length - num + history_base;
581 if (!(he = history_get(num)))
588 if (cmd[idx] == '?') {
594 if (cmd[idx] == '\n')
596 if (sub && cmd[idx] == '?')
598 if (!sub && (cmd[idx] == ':' || cmd[idx] == ' '
599 || cmd[idx] == '\t' || cmd[idx] == qchar))
603 len = (size_t)idx - (size_t)begin;
604 if (sub && cmd[idx] == '?')
606 if (sub && len == 0 && last_search_pat && *last_search_pat)
607 pat = last_search_pat;
611 if ((pat = el_calloc(len + 1, sizeof(*pat))) == NULL)
613 (void)strlcpy(pat, cmd + begin, len + 1);
616 if (history(h, &ev, H_CURR) != 0) {
617 if (pat != last_search_pat)
624 if (pat != last_search_pat) {
625 el_free(last_search_pat);
626 last_search_pat = pat;
628 ret = history_search(pat, -1);
630 ret = history_search_prefix(pat, -1);
633 /* restore to end of list on failed search */
634 history(h, &ev, H_FIRST);
635 (void)fprintf(rl_outstream, "%s: Event not found\n", pat);
636 if (pat != last_search_pat)
642 el_free(last_search_match);
643 last_search_match = strdup(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 getfrom(const char **cmdp, char **fromp, const char *search, int delim)
665 const char *cmd = *cmdp;
666 char *what = el_realloc(*fromp, size * sizeof(*what));
672 for (; *cmd && *cmd != delim; cmd++) {
673 if (*cmd == '\\' && cmd[1] == delim)
675 if (len - 1 >= size) {
677 nwhat = el_realloc(what, (size <<= 1) * sizeof(*nwhat));
695 *fromp = strdup(search);
696 if (*fromp == NULL) {
710 cmd++; /* shift after delim */
722 getto(const char **cmdp, char **top, const char *from, int delim)
726 size_t from_len = strlen(from);
727 const char *cmd = *cmdp;
728 char *with = el_realloc(*top, size * sizeof(*with));
733 for (; *cmd && *cmd != delim; cmd++) {
734 if (len + from_len + 1 >= size) {
736 size += from_len + 1;
737 nwith = el_realloc(with, size * sizeof(*nwith));
744 strcpy(&with[len], from);
748 if (*cmd == '\\' && (*(cmd + 1) == delim || *(cmd + 1) == '&'))
767 replace(char **tmp, int c)
770 if ((aptr = strrchr(*tmp, c)) == NULL)
772 aptr = strdup(aptr + 1); // XXX: check
778 * the real function doing history expansion - takes as argument command
779 * to do and data upon which the command should be executed
780 * does expansion the way I've understood readline documentation
782 * returns 0 if data was not modified, 1 if it was and 2 if the string
783 * should be only printed and not executed; in case of error,
784 * returns -1 and *result points to NULL
785 * it's the caller's responsibility to free() the string returned in *result
788 _history_expand_command(const char *command, size_t offs, size_t cmdlen,
791 char *tmp, *search = NULL, *aptr, delim;
792 const char *ptr, *cmd;
793 static char *from = NULL, *to = NULL;
794 int start, end, idx, has_mods = 0;
795 int p_on = 0, g_on = 0, ev;
801 /* First get event specifier */
804 if (strchr(":^*$", command[offs + 1])) {
807 * "!:" is shorthand for "!!:".
808 * "!^", "!*" and "!$" are shorthand for
809 * "!!:^", "!!:*" and "!!:$" respectively.
811 str[0] = str[1] = '!';
813 ptr = get_history_event(str, &idx, 0);
814 idx = (command[offs + 1] == ':')? 1:0;
817 if (command[offs + 1] == '#') {
818 /* use command so far */
819 if ((aptr = el_calloc(offs + 1, sizeof(*aptr)))
822 (void)strlcpy(aptr, command, offs + 1);
827 qchar = (offs > 0 && command[offs - 1] == '"')
829 ptr = get_history_event(command + offs, &idx, qchar);
831 has_mods = command[offs + (size_t)idx] == ':';
834 if (ptr == NULL && aptr == NULL)
838 *result = strdup(aptr ? aptr : ptr);
846 cmd = command + offs + idx + 1;
848 /* Now parse any word designators */
850 if (*cmd == '%') /* last word matched by ?pat? */
851 tmp = strdup(last_search_match ? last_search_match : "");
852 else if (strchr("^*$-0123456789", *cmd)) {
855 start = end = 1, cmd++;
856 else if (*cmd == '$')
858 else if (*cmd == '*')
860 else if (*cmd == '-' || isdigit((unsigned char) *cmd)) {
862 while (*cmd && '0' <= *cmd && *cmd <= '9')
863 start = start * 10 + *cmd++ - '0';
866 if (isdigit((unsigned char) cmd[1])) {
869 while (*cmd && '0' <= *cmd && *cmd <= '9')
870 end = end * 10 + *cmd++ - '0';
871 } else if (cmd[1] == '$') {
878 } else if (*cmd == '*')
883 tmp = history_arg_extract(start, end, aptr? aptr:ptr);
885 (void)fprintf(rl_outstream, "%s: Bad word specifier",
886 command + offs + idx);
892 tmp = strdup(aptr? aptr:ptr);
897 if (*cmd == '\0' || ((size_t)(cmd - (command + offs)) >= cmdlen)) {
902 for (; *cmd; cmd++) {
906 case 'h': /* remove trailing path */
907 if ((aptr = strrchr(tmp, '/')) != NULL)
910 case 't': /* remove leading path */
913 case 'r': /* remove trailing suffix */
914 if ((aptr = strrchr(tmp, '.')) != NULL)
917 case 'e': /* remove all but suffix */
920 case 'p': /* print only */
927 if (from == NULL || to == NULL)
933 if (delim == '\0' || *++cmd == '\0')
935 if ((ev = getfrom(&cmd, &from, search, delim)) != 1)
937 if ((ev = getto(&cmd, &to, from, delim)) != 1)
939 aptr = _rl_compat_sub(tmp, from, to, g_on);
959 * csh-style history expansion
962 history_expand(char *str, char **output)
968 if (h == NULL || e == NULL)
971 if (history_expansion_char == 0) {
972 *output = strdup(str);
977 if (str[0] == history_subst_char) {
978 /* ^foo^foo2^ is equivalent to !!:s^foo^foo2^ */
979 *output = el_calloc(strlen(str) + 4 + 1, sizeof(**output));
982 (*output)[0] = (*output)[1] = history_expansion_char;
985 (void)strcpy((*output) + 4, str);
988 *output = strdup(str);
993 #define ADD_STRING(what, len, fr) \
995 if (idx + len + 1 > size) { \
996 char *nresult = el_realloc(result, \
997 (size += len + 1) * sizeof(*nresult)); \
998 if (nresult == NULL) { \
1005 (void)strlcpy(&result[idx], what, len + 1); \
1012 for (i = 0; str[i];) {
1013 int qchar, loop_again;
1014 size_t len, start, j;
1020 for (; str[j]; j++) {
1021 if (str[j] == '\\' &&
1022 str[j + 1] == history_expansion_char) {
1023 len = strlen(&str[j + 1]) + 1;
1024 memmove(&str[j], &str[j + 1], len);
1028 if (isspace((unsigned char) str[j])
1032 if (str[j] == history_expansion_char
1033 && !strchr(history_no_expand_chars, str[j + 1])
1034 && (!history_inhibit_expansion_function ||
1035 (*history_inhibit_expansion_function)(str,
1040 if (str[j] && loop_again) {
1042 qchar = (j > 0 && str[j - 1] == '"' )? '"':0;
1044 if (str[j] == history_expansion_char)
1050 ADD_STRING(&str[start], len, NULL);
1052 if (str[i] == '\0' || str[i] != history_expansion_char) {
1054 ADD_STRING(&str[i], len, NULL);
1061 ret = _history_expand_command (str, i, (j - i), &tmp);
1062 if (ret > 0 && tmp) {
1064 ADD_STRING(tmp, len, tmp);
1073 /* ret is 2 for "print only" option */
1075 add_history(result);
1077 /* gdb 4.11 has been shipped with readline, where */
1078 /* history_expand() returned -1 when the line */
1079 /* should not be executed; in readline 2.1+ */
1080 /* it should return 2 in such a case */
1091 * Return a string consisting of arguments of "str" from "start" to "end".
1094 history_arg_extract(int start, int end, const char *str)
1097 char **arr, *result = NULL;
1099 arr = history_tokenize(str);
1102 if (arr && *arr == NULL)
1105 for (max = 0; arr[max]; max++)
1114 end = (int)max + end + 1;
1118 if (start < 0 || end < 0 || (size_t)start > max ||
1119 (size_t)end > max || start > end)
1122 for (i = (size_t)start, len = 0; i <= (size_t)end; i++)
1123 len += strlen(arr[i]) + 1;
1125 result = el_calloc(len, sizeof(*result));
1129 for (i = (size_t)start, len = 0; i <= (size_t)end; i++) {
1130 (void)strcpy(result + len, arr[i]);
1131 len += strlen(arr[i]);
1132 if (i < (size_t)end)
1133 result[len++] = ' ';
1138 for (i = 0; arr[i]; i++)
1146 * Parse the string into individual tokens,
1147 * similar to how shell would do it.
1150 history_tokenize(const char *str)
1152 int size = 1, idx = 0, i, start;
1154 char **result = NULL, *temp, delim = '\0';
1156 for (i = 0; str[i];) {
1157 while (isspace((unsigned char) str[i]))
1161 if (str[i] == '\\') {
1162 if (str[i+1] != '\0')
1164 } else if (str[i] == delim)
1167 (isspace((unsigned char) str[i]) ||
1168 strchr("()<>;&|$", str[i])))
1170 else if (!delim && strchr("'`\"", str[i]))
1176 if (idx + 2 >= size) {
1179 nresult = el_realloc(result, (size_t)size * sizeof(*nresult));
1180 if (nresult == NULL) {
1186 len = (size_t)i - (size_t)start;
1187 temp = el_calloc(len + 1, sizeof(*temp));
1189 for (i = 0; i < idx; i++)
1194 (void)strlcpy(temp, &str[start], len + 1);
1195 result[idx++] = temp;
1205 * limit size of history record to ``max'' events
1208 stifle_history(int max)
1213 if (h == NULL || e == NULL)
1216 if (history(h, &ev, H_SETSIZE, max) == 0) {
1217 max_input_history = max;
1218 if (history_length > max)
1219 history_base = history_length - max;
1220 while (history_length > max) {
1221 he = remove_history(0);
1223 el_free((void *)(unsigned long)he->line);
1231 * "unlimit" size of history - set the limit to maximum allowed int value
1234 unstifle_history(void)
1239 history(h, &ev, H_SETSIZE, INT_MAX);
1240 omax = max_input_history;
1241 max_input_history = INT_MAX;
1242 return omax; /* some value _must_ be returned */
1247 history_is_stifled(void)
1250 /* cannot return true answer */
1251 return max_input_history != INT_MAX;
1254 static const char _history_tmp_template[] = "/tmp/.historyXXXXXX";
1257 history_truncate_file (const char *filename, int nlines)
1261 char template[sizeof(_history_tmp_template)];
1269 if (filename == NULL && (filename = _default_history_file()) == NULL)
1271 if ((fp = fopen(filename, "r+")) == NULL)
1273 strcpy(template, _history_tmp_template);
1274 if ((fd = mkstemp(template)) == -1) {
1279 if ((tp = fdopen(fd, "r+")) == NULL) {
1286 if (fread(buf, sizeof(buf), (size_t)1, fp) != 1) {
1291 if (fseeko(fp, (off_t)sizeof(buf) * count, SEEK_SET) ==
1296 left = (ssize_t)fread(buf, (size_t)1, sizeof(buf), fp);
1304 } else if (fwrite(buf, (size_t)left, (size_t)1, tp)
1312 if (fwrite(buf, sizeof(buf), (size_t)1, tp) != 1) {
1320 cp = buf + left - 1;
1324 while (--cp >= buf) {
1326 if (--nlines == 0) {
1327 if (++cp >= buf + sizeof(buf)) {
1335 if (nlines <= 0 || count == 0)
1338 if (fseeko(tp, (off_t)sizeof(buf) * count, SEEK_SET) < 0) {
1342 if (fread(buf, sizeof(buf), (size_t)1, tp) != 1) {
1350 cp = buf + sizeof(buf);
1353 if (ret || nlines > 0)
1356 if (fseeko(fp, (off_t)0, SEEK_SET) == (off_t)-1) {
1361 if (fseeko(tp, (off_t)sizeof(buf) * count + (cp - buf), SEEK_SET) ==
1368 if ((left = (ssize_t)fread(buf, (size_t)1, sizeof(buf), tp)) == 0) {
1373 if (fwrite(buf, (size_t)left, (size_t)1, fp) != 1) {
1379 if((off = ftello(fp)) > 0)
1380 (void)ftruncate(fileno(fp), off);
1393 * read history from a file given
1396 read_history(const char *filename)
1400 if (h == NULL || e == NULL)
1402 if (filename == NULL && (filename = _default_history_file()) == NULL)
1405 if (history(h, &ev, H_LOAD, filename) == -1)
1406 return errno ? errno : EINVAL;
1407 if (history(h, &ev, H_GETSIZE) == 0)
1408 history_length = ev.num;
1409 if (history_length < 0)
1416 * write history to a file given
1419 write_history(const char *filename)
1423 if (h == NULL || e == NULL)
1425 if (filename == NULL && (filename = _default_history_file()) == NULL)
1427 return history(h, &ev, H_SAVE, filename) == -1 ?
1428 (errno ? errno : EINVAL) : 0;
1432 append_history(int n, const char *filename)
1437 if (h == NULL || e == NULL)
1439 if (filename == NULL && (filename = _default_history_file()) == NULL)
1442 if ((fp = fopen(filename, "a")) == NULL)
1445 if (history(h, &ev, H_NSAVE_FP, (size_t)n, fp) == -1) {
1446 int serrno = errno ? errno : EINVAL;
1455 * returns history ``num''th event
1457 * returned pointer points to static variable
1460 history_get(int num)
1462 static HIST_ENTRY she;
1466 if (h == NULL || e == NULL)
1469 if (num < history_base)
1472 /* save current position */
1473 if (history(h, &ev, H_CURR) != 0)
1478 * use H_DELDATA to set to nth history (without delete) by passing
1479 * (void **)-1 -- as in history_set_pos
1481 if (history(h, &ev, H_DELDATA, num - history_base, (void **)-1) != 0)
1484 /* get current entry */
1485 if (history(h, &ev, H_CURR) != 0)
1487 if (history(h, &ev, H_NEXT_EVDATA, ev.num, &she.data) != 0)
1491 /* restore pointer to where it was */
1492 (void)history(h, &ev, H_SET, curr_num);
1497 /* restore pointer to where it was */
1498 (void)history(h, &ev, H_SET, curr_num);
1504 * add the line to history table
1507 add_history(const char *line)
1511 if (h == NULL || e == NULL)
1514 if (history(h, &ev, H_ENTER, line) == -1)
1517 (void)history(h, &ev, H_GETSIZE);
1518 if (ev.num == history_length)
1522 history_length = ev.num;
1529 * remove the specified entry from the history list and return it.
1532 remove_history(int num)
1537 if (h == NULL || e == NULL)
1540 if ((he = el_malloc(sizeof(*he))) == NULL)
1543 if (history(h, &ev, H_DELDATA, num, &he->data) != 0) {
1549 if (history(h, &ev, H_GETSIZE) == 0)
1550 history_length = ev.num;
1557 * replace the line and data of the num-th entry
1560 replace_history_entry(int num, const char *line, histdata_t data)
1566 if (h == NULL || e == NULL)
1569 /* save current position */
1570 if (history(h, &ev, H_CURR) != 0)
1574 /* start from the oldest */
1575 if (history(h, &ev, H_LAST) != 0)
1576 return NULL; /* error */
1578 if ((he = el_malloc(sizeof(*he))) == NULL)
1581 /* look forwards for event matching specified offset */
1582 if (history(h, &ev, H_NEXT_EVDATA, num, &he->data))
1585 he->line = strdup(ev.str);
1586 if (he->line == NULL)
1589 if (history(h, &ev, H_REPLACE, line, data))
1592 /* restore pointer to where it was */
1593 if (history(h, &ev, H_SET, curr_num))
1603 * clear the history list - delete all entries
1610 if (h == NULL || e == NULL)
1613 (void)history(h, &ev, H_CLEAR);
1614 history_offset = history_length = 0;
1619 * returns offset of the current history event
1624 return history_offset;
1627 static HIST_ENTRY **_history_listp;
1628 static HIST_ENTRY *_history_list;
1634 HIST_ENTRY **nlp, *nl;
1637 if (history(h, &ev, H_LAST) != 0)
1640 if ((nlp = el_realloc(_history_listp,
1641 ((size_t)history_length + 1) * sizeof(*nlp))) == NULL)
1643 _history_listp = nlp;
1645 if ((nl = el_realloc(_history_list,
1646 (size_t)history_length * sizeof(*nl))) == NULL)
1652 _history_listp[i] = &_history_list[i];
1653 _history_list[i].line = ev.str;
1654 _history_list[i].data = NULL;
1655 if (i++ == history_length)
1657 } while (history(h, &ev, H_PREV) == 0);
1658 _history_listp[i] = NULL;
1659 return _history_listp;
1663 * returns current history event or NULL if there is no such event
1666 current_history(void)
1670 if (history(h, &ev, H_PREV_EVENT, history_offset + 1) != 0)
1673 rl_he.line = ev.str;
1680 * returns total number of bytes history events' data are using
1683 history_total_bytes(void)
1689 if (history(h, &ev, H_CURR) != 0)
1693 (void)history(h, &ev, H_FIRST);
1696 size += strlen(ev.str) * sizeof(*ev.str);
1697 while (history(h, &ev, H_NEXT) == 0);
1699 /* get to the same position as before */
1700 history(h, &ev, H_PREV_EVENT, curr_num);
1707 * sets the position in the history list to ``pos''
1710 history_set_pos(int pos)
1712 if (pos >= history_length || pos < 0)
1715 history_offset = pos;
1721 * returns previous event in history and shifts pointer accordingly
1722 * Note that readline and editline define directions in opposite ways.
1725 previous_history(void)
1729 if (history_offset == 0)
1732 if (history(h, &ev, H_LAST) != 0)
1736 return current_history();
1741 * returns next event in history and shifts pointer accordingly
1748 if (history_offset >= history_length)
1751 if (history(h, &ev, H_LAST) != 0)
1755 return current_history();
1760 * searches for first history event containing the str
1763 history_search(const char *str, int direction)
1769 if (history(h, &ev, H_CURR) != 0)
1774 if ((strp = strstr(ev.str, str)) != NULL)
1775 return (int)(strp - ev.str);
1776 if (history(h, &ev, direction < 0 ? H_NEXT:H_PREV) != 0)
1779 (void)history(h, &ev, H_SET, curr_num);
1785 * searches for first history event beginning with str
1788 history_search_prefix(const char *str, int direction)
1792 return (history(h, &ev, direction < 0 ?
1793 H_PREV_STR : H_NEXT_STR, str));
1798 * search for event in history containing str, starting at offset
1799 * abs(pos); continue backward, if pos<0, forward otherwise
1803 history_search_pos(const char *str,
1804 int direction __attribute__((__unused__)), int pos)
1809 off = (pos > 0) ? pos : -pos;
1810 pos = (pos > 0) ? 1 : -1;
1812 if (history(h, &ev, H_CURR) != 0)
1816 if (!history_set_pos(off) || history(h, &ev, H_CURR) != 0)
1820 if (strstr(ev.str, str))
1822 if (history(h, &ev, (pos < 0) ? H_PREV : H_NEXT) != 0)
1826 /* set "current" pointer back to previous state */
1827 (void)history(h, &ev,
1828 pos < 0 ? H_NEXT_EVENT : H_PREV_EVENT, curr_num);
1834 /********************************/
1835 /* completion functions */
1838 tilde_expand(char *name)
1840 return fn_tilde_expand(name);
1844 filename_completion_function(const char *name, int state)
1846 return fn_filename_completion_function(name, state);
1850 * a completion generator for usernames; returns _first_ username
1851 * which starts with supplied text
1852 * text contains a partial username preceded by random character
1853 * (usually '~'); state resets search from start (??? should we do that anyway)
1854 * it's the caller's responsibility to free the returned value
1857 username_completion_function(const char *text, int state)
1859 #if defined(HAVE_GETPW_R_POSIX) || defined(HAVE_GETPW_R_DRAFT)
1860 struct passwd pwres;
1863 struct passwd *pass = NULL;
1865 if (text[0] == '\0')
1875 #if defined(HAVE_GETPW_R_POSIX) || defined(HAVE_GETPW_R_DRAFT)
1876 getpwent_r(&pwres, pwbuf, sizeof(pwbuf), &pass) == 0 && pass != NULL
1878 (pass = getpwent()) != NULL
1880 && text[0] == pass->pw_name[0]
1881 && strcmp(text, pass->pw_name) == 0)
1888 return strdup(pass->pw_name);
1893 * el-compatible wrapper to send TSTP on ^Z
1896 static unsigned char
1897 _el_rl_tstp(EditLine *el __attribute__((__unused__)), int ch __attribute__((__unused__)))
1899 (void)kill(0, SIGTSTP);
1905 _rl_completion_append_character_function(const char *dummy
1906 __attribute__((__unused__)))
1909 buf[0] = (char)rl_completion_append_character;
1916 * Display list of strings in columnar format on readline's output stream.
1917 * 'matches' is list of strings, 'len' is number of strings in 'matches',
1918 * 'max' is maximum length of string in 'matches'.
1921 rl_display_match_list(char **matches, int len, int max)
1924 fn_display_match_list(e, matches, (size_t)len, (size_t)max,
1925 _rl_completion_append_character_function);
1929 * complete word at current point
1933 rl_complete(int ignore __attribute__((__unused__)), int invoking_key)
1935 static ct_buffer_t wbreak_conv, sprefix_conv;
1936 const char *breakchars;
1938 if (h == NULL || e == NULL)
1941 if (rl_inhibit_completion) {
1943 arr[0] = (char)invoking_key;
1945 el_insertstr(e, arr);
1949 if (rl_completion_word_break_hook != NULL)
1950 breakchars = (*rl_completion_word_break_hook)();
1952 breakchars = rl_basic_word_break_characters;
1956 /* Just look at how many global variables modify this operation! */
1957 return fn_complete(e,
1958 (rl_compentry_func_t *)rl_completion_entry_function,
1959 rl_attempted_completion_function,
1960 ct_decode_string(rl_basic_word_break_characters, &wbreak_conv),
1961 ct_decode_string(breakchars, &sprefix_conv),
1962 _rl_completion_append_character_function,
1963 (size_t)rl_completion_query_items,
1964 &rl_completion_type, &rl_attempted_completion_over,
1965 &rl_point, &rl_end);
1972 static unsigned char
1973 _el_rl_complete(EditLine *el __attribute__((__unused__)), int ch)
1975 return (unsigned char)rl_complete(0, ch);
1979 * misc other functions
1983 * bind key c to readline-type function func
1986 rl_bind_key(int c, rl_command_func_t *func)
1990 if (h == NULL || e == NULL)
1993 if (func == rl_insert) {
1994 /* XXX notice there is no range checking of ``c'' */
1995 e->el_map.key[c] = ED_INSERT;
2003 * read one key from input - handles chars pushed back
2004 * to input stream also
2009 char fooarr[2 * sizeof(int)];
2011 if (e == NULL || h == NULL)
2014 return el_getc(e, fooarr);
2019 * reset the terminal
2023 rl_reset_terminal(const char *p __attribute__((__unused__)))
2026 if (h == NULL || e == NULL)
2034 * insert character ``c'' back into input stream, ``count'' times
2037 rl_insert(int count, int c)
2041 if (h == NULL || e == NULL)
2044 /* XXX - int -> char conversion can lose on multichars */
2048 for (; count > 0; count--)
2055 rl_insert_text(const char *text)
2057 if (!text || *text == 0)
2060 if (h == NULL || e == NULL)
2063 if (el_insertstr(e, text) < 0)
2065 return (int)strlen(text);
2070 rl_newline(int count __attribute__((__unused__)),
2071 int c __attribute__((__unused__)))
2074 * Readline-4.0 appears to ignore the args.
2076 return rl_insert(1, '\n');
2080 static unsigned char
2081 rl_bind_wrapper(EditLine *el __attribute__((__unused__)), unsigned char c)
2090 /* If rl_done was set by the above call, deal with it here */
2098 rl_add_defun(const char *name, rl_command_func_t *fun, int c)
2101 if ((size_t)c >= sizeof(map) / sizeof(map[0]) || c < 0)
2103 map[(unsigned char)c] = fun;
2104 el_set(e, EL_ADDFN, name, name, rl_bind_wrapper);
2105 vis(dest, c, VIS_WHITE|VIS_NOSLASH, 0);
2106 el_set(e, EL_BIND, dest, name, NULL);
2111 rl_callback_read_char(void)
2113 int count = 0, done = 0;
2114 const char *buf = el_gets(e, &count);
2117 el_set(e, EL_UNBUFFERED, 1);
2118 if (buf == NULL || count-- <= 0)
2120 if (count == 0 && buf[0] == e->el_tty.t_c[TS_IO][C_EOF])
2122 if (buf[count] == '\n' || buf[count] == '\r')
2125 if (done && rl_linefunc != NULL) {
2126 el_set(e, EL_UNBUFFERED, 0);
2128 if ((wbuf = strdup(buf)) != NULL)
2132 (*(void (*)(const char *))rl_linefunc)(wbuf);
2137 rl_callback_handler_install(const char *prompt, rl_vcpfunc_t *linefunc)
2142 (void)rl_set_prompt(prompt);
2143 rl_linefunc = linefunc;
2144 el_set(e, EL_UNBUFFERED, 1);
2148 rl_callback_handler_remove(void)
2150 el_set(e, EL_UNBUFFERED, 0);
2158 a[0] = (char)e->el_tty.t_c[TS_IO][C_REPRINT];
2164 rl_get_previous_history(int count, int key)
2176 rl_prep_terminal(int meta_flag __attribute__((__unused__)))
2178 el_set(e, EL_PREP_TERM, 1);
2182 rl_deprep_terminal(void)
2184 el_set(e, EL_PREP_TERM, 0);
2188 rl_read_init_file(const char *s)
2190 return el_source(e, s);
2194 rl_parse_and_bind(const char *line)
2200 tok = tok_init(NULL);
2201 tok_str(tok, line, &argc, &argv);
2202 argc = el_parse(e, argc, argv);
2204 return argc ? 1 : 0;
2208 rl_variable_bind(const char *var, const char *value)
2211 * The proper return value is undocument, but this is what the
2212 * readline source seems to do.
2214 return el_set(e, EL_BIND, "", var, value, NULL) == -1 ? 1 : 0;
2218 rl_stuff_char(int c)
2224 el_insertstr(e, buf);
2229 _rl_event_read_char(EditLine *el, wchar_t *wc)
2233 ssize_t num_read = 0;
2237 while (rl_event_hook) {
2241 #if defined(FIONREAD)
2242 if (ioctl(el->el_infd, FIONREAD, &n) < 0)
2245 num_read = read(el->el_infd, &ch, (size_t)1);
2248 #elif defined(F_SETFL) && defined(O_NDELAY)
2249 if ((n = fcntl(el->el_infd, F_GETFL, 0)) < 0)
2251 if (fcntl(el->el_infd, F_SETFL, n|O_NDELAY) < 0)
2253 num_read = read(el->el_infd, &ch, 1);
2254 if (fcntl(el->el_infd, F_SETFL, n))
2257 /* not non-blocking, but what you gonna do? */
2258 num_read = read(el->el_infd, &ch, 1);
2262 if (num_read < 0 && errno == EAGAIN)
2269 el_set(el, EL_GETCFN, EL_BUILTIN_GETCFN);
2271 return (int)num_read;
2275 _rl_update_pos(void)
2277 const LineInfo *li = el_line(e);
2279 rl_point = (int)(li->cursor - li->buffer);
2280 rl_end = (int)(li->lastchar - li->buffer);
2281 rl_line_buffer[rl_end] = '\0';
2285 rl_get_screen_size(int *rows, int *cols)
2288 el_get(e, EL_GETTC, "li", rows);
2290 el_get(e, EL_GETTC, "co", cols);
2294 rl_set_screen_size(int rows, int cols)
2297 (void)snprintf(buf, sizeof(buf), "%d", rows);
2298 el_set(e, EL_SETTC, "li", buf, NULL);
2299 (void)snprintf(buf, sizeof(buf), "%d", cols);
2300 el_set(e, EL_SETTC, "co", buf, NULL);
2304 rl_completion_matches(const char *str, rl_compentry_func_t *fun)
2306 size_t len, max, i, j, min;
2307 char **list, *match, *a, *b;
2311 if ((list = el_calloc(max, sizeof(*list))) == NULL)
2314 while ((match = (*fun)(str, (int)(len - 1))) != NULL) {
2315 list[len++] = match;
2319 if ((nl = el_realloc(list, max * sizeof(*nl))) == NULL)
2328 if ((list[0] = strdup(list[1])) == NULL)
2332 qsort(&list[1], len - 1, sizeof(*list),
2333 (int (*)(const void *, const void *)) strcmp);
2335 for (i = 1, a = list[i]; i < len - 1; i++, a = b) {
2337 for (j = 0; a[j] && a[j] == b[j]; j++)
2342 if (min == 0 && *str) {
2343 if ((list[0] = strdup(str)) == NULL)
2346 if ((list[0] = el_calloc(min + 1, sizeof(*list[0]))) == NULL)
2348 (void)memcpy(list[0], list[1], min);
2349 list[0][min] = '\0';
2359 rl_filename_completion_function (const char *text, int state)
2361 return fn_filename_completion_function(text, state);
2365 rl_forced_update_display(void)
2367 el_set(e, EL_REFRESH);
2371 _rl_abort_internal(void)
2379 _rl_qsort_string_compare(char **s1, char **s2)
2381 return strcoll(*s1, *s2);
2385 history_get_history_state(void)
2389 if ((hs = el_malloc(sizeof(*hs))) == NULL)
2391 hs->length = history_length;
2397 rl_kill_text(int from __attribute__((__unused__)),
2398 int to __attribute__((__unused__)))
2404 rl_make_bare_keymap(void)
2417 rl_set_keymap(Keymap k __attribute__((__unused__)))
2423 rl_generic_bind(int type __attribute__((__unused__)),
2424 const char * keyseq __attribute__((__unused__)),
2425 const char * data __attribute__((__unused__)),
2426 Keymap k __attribute__((__unused__)))
2433 rl_bind_key_in_map(int key __attribute__((__unused__)),
2434 rl_command_func_t *fun __attribute__((__unused__)),
2435 Keymap k __attribute__((__unused__)))
2440 /* unsupported, but needed by python */
2442 rl_cleanup_after_signal(void)
2447 rl_on_new_line(void)
2453 rl_free_line_state(void)
2459 rl_set_keyboard_input_timeout(int u __attribute__((__unused__)))
2465 rl_resize_terminal(void)
2471 rl_reset_after_signal(void)
2473 if (rl_prep_term_function)
2474 (*rl_prep_term_function)();
2478 rl_echo_signal_char(int sig)
2480 int c = tty_get_signal_character(e, sig);
2489 re_putc(e, '\n', 0);
2496 re_putc(e, '\a', 0);
2501 rl_abort(int count, int key)
2503 return count && key ? 0 : 0;
2507 rl_set_keymap_name(const char *name, Keymap k)
2509 return name && k ? 0 : 0;
2513 free_history_entry(HIST_ENTRY *he)
2515 return he ? NULL : NULL;
2519 _rl_erase_entire_line(void)