1 /* $NetBSD: readline.c,v 1.126 2016/02/24 17:13:22 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.126 2016/02/24 17:13:22 christos Exp $");
35 #endif /* not lint && not SCCSID */
36 #include <sys/cdefs.h>
37 __FBSDID("$FreeBSD$");
39 #include <sys/types.h>
55 #include "readline/readline.h"
57 #include "filecomplete.h"
59 void rl_prep_terminal(int);
60 void rl_deprep_terminal(void);
62 /* for rl_complete() */
65 /* see comment at the #ifdef for sense of this */
66 /* #define GDB_411_HACK */
68 /* readline compatibility stuff - look at readline sources/documentation */
69 /* to see what these variables mean */
70 const char *rl_library_version = "EditLine wrapper";
71 int rl_readline_version = RL_READLINE_VERSION;
72 static char empty[] = { '\0' };
73 static char expand_chars[] = { ' ', '\t', '\n', '=', '(', '\0' };
74 static char break_chars[] = { ' ', '\t', '\n', '"', '\\', '\'', '`', '@', '$',
75 '>', '<', '=', ';', '|', '&', '{', '(', '\0' };
76 char *rl_readline_name = empty;
77 FILE *rl_instream = NULL;
78 FILE *rl_outstream = NULL;
81 char *rl_line_buffer = NULL;
82 rl_vcpfunc_t *rl_linefunc = NULL;
84 VFunction *rl_event_hook = NULL;
85 KEYMAP_ENTRY_ARRAY emacs_standard_keymap,
89 * The following is not implemented; we always catch signals in the
90 * libedit fashion: set handlers on entry to el_gets() and clear them
91 * on the way out. This simplistic approach works for most cases; if
92 * it does not work for your application, please let us know.
94 int rl_catch_signals = 1;
95 int rl_catch_sigwinch = 1;
97 int history_base = 1; /* probably never subject to change */
98 int history_length = 0;
99 int 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 char *rl_basic_word_break_characters = break_chars;
109 char *rl_completer_word_break_characters = NULL;
110 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 VFunction *rl_completion_display_matches_hook = NULL;
126 VFunction *rl_prep_term_function = (VFunction *)rl_prep_terminal;
127 VFunction *rl_deprep_term_function = (VFunction *)rl_deprep_terminal;
128 KEYMAP_ENTRY_ARRAY emacs_meta_keymap;
131 * The current prompt string.
133 char *rl_prompt = NULL;
135 * This is set to character indicating type of completion being done by
136 * rl_complete_internal(); this is available for application completion
139 int rl_completion_type = 0;
142 * If more than this number of items results from query for possible
143 * completions, we ask user if they are sure to really display the list.
145 int rl_completion_query_items = 100;
148 * List of characters which are word break characters, but should be left
149 * in the parsed text when it is passed to the completion function.
150 * Shell uses this to help determine what kind of completing to do.
152 char *rl_special_prefixes = NULL;
155 * This is the character appended to the completed words if at the end of
156 * the line. Default is ' ' (a space).
158 int rl_completion_append_character = ' ';
160 /* stuff below is used internally by libedit for readline emulation */
162 static History *h = NULL;
163 static EditLine *e = NULL;
164 static rl_command_func_t *map[256];
165 static jmp_buf topbuf;
167 /* internal functions */
168 static unsigned char _el_rl_complete(EditLine *, int);
169 static unsigned char _el_rl_tstp(EditLine *, int);
170 static char *_get_prompt(EditLine *);
171 static int _getc_function(EditLine *, wchar_t *);
172 static HIST_ENTRY *_move_history(int);
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);
183 _get_prompt(EditLine *el __attribute__((__unused__)))
185 rl_already_prompted = 1;
191 * generic function for moving around history
194 _move_history(int op)
197 static HIST_ENTRY rl_he;
199 if (history(h, &ev, op) != 0)
210 * read one key from user defined input function
214 _getc_function(EditLine *el __attribute__((__unused__)), wchar_t *c)
218 i = (*rl_getc_function)(NULL);
226 _resize_fun(EditLine *el, void *a)
232 /* a cheesy way to get rid of const cast. */
233 *ap = memchr(li->buffer, *li->buffer, (size_t)1);
237 _default_history_file(void)
246 if ((p = getpwuid(getuid())) == NULL)
249 len = strlen(p->pw_dir) + sizeof("/.history");
250 if ((path = malloc(len)) == NULL)
253 (void)snprintf(path, len, "%s/.history", p->pw_dir);
258 * READLINE compatibility stuff
265 rl_set_prompt(const char *prompt)
271 if (rl_prompt != NULL && strcmp(rl_prompt, prompt) == 0)
275 rl_prompt = strdup(prompt);
276 if (rl_prompt == NULL)
279 while ((p = strchr(rl_prompt, RL_PROMPT_END_IGNORE)) != NULL)
280 *p = RL_PROMPT_START_IGNORE;
286 * initialize rl compat stuff
303 rl_outstream = stdout;
306 * See if we don't really want to run the editor
308 if (tcgetattr(fileno(rl_instream), &t) != -1 && (t.c_lflag & ECHO) == 0)
311 e = el_init(rl_readline_name, rl_instream, rl_outstream, stderr);
314 el_set(e, EL_EDITMODE, 0);
320 history(h, &ev, H_SETSIZE, INT_MAX); /* unlimited */
322 max_input_history = INT_MAX;
323 el_set(e, EL_HIST, history, h);
325 /* Setup resize function */
326 el_set(e, EL_RESIZE, _resize_fun, &rl_line_buffer);
328 /* setup getc function if valid */
329 if (rl_getc_function)
330 el_set(e, EL_GETCFN, _getc_function);
332 /* for proper prompt printing in readline() */
333 if (rl_set_prompt("") == -1) {
338 el_set(e, EL_PROMPT, _get_prompt, RL_PROMPT_START_IGNORE);
339 el_set(e, EL_SIGNAL, rl_catch_signals);
341 /* set default mode to "emacs"-style and read setting afterwards */
342 /* so this can be overridden */
343 el_set(e, EL_EDITOR, "emacs");
344 if (rl_terminal_name != NULL)
345 el_set(e, EL_TERMINAL, rl_terminal_name);
347 el_get(e, EL_TERMINAL, &rl_terminal_name);
350 * Word completion - this has to go AFTER rebinding keys
353 el_set(e, EL_ADDFN, "rl_complete",
354 "ReadLine compatible completion function",
356 el_set(e, EL_BIND, "^I", "rl_complete", NULL);
359 * Send TSTP when ^Z is pressed.
361 el_set(e, EL_ADDFN, "rl_tstp",
362 "ReadLine compatible suspend function",
364 el_set(e, EL_BIND, "^Z", "rl_tstp", NULL);
367 * Set some readline compatible key-bindings.
369 el_set(e, EL_BIND, "^R", "em-inc-search-prev", NULL);
372 * Allow the use of Home/End keys.
374 el_set(e, EL_BIND, "\\e[1~", "ed-move-to-beg", NULL);
375 el_set(e, EL_BIND, "\\e[4~", "ed-move-to-end", NULL);
376 el_set(e, EL_BIND, "\\e[7~", "ed-move-to-beg", NULL);
377 el_set(e, EL_BIND, "\\e[8~", "ed-move-to-end", NULL);
378 el_set(e, EL_BIND, "\\e[H", "ed-move-to-beg", NULL);
379 el_set(e, EL_BIND, "\\e[F", "ed-move-to-end", NULL);
382 * Allow the use of the Delete/Insert keys.
384 el_set(e, EL_BIND, "\\e[3~", "ed-delete-next-char", NULL);
385 el_set(e, EL_BIND, "\\e[2~", "ed-quoted-insert", NULL);
388 * Ctrl-left-arrow and Ctrl-right-arrow for word moving.
390 el_set(e, EL_BIND, "\\e[1;5C", "em-next-word", NULL);
391 el_set(e, EL_BIND, "\\e[1;5D", "ed-prev-word", NULL);
392 el_set(e, EL_BIND, "\\e[5C", "em-next-word", NULL);
393 el_set(e, EL_BIND, "\\e[5D", "ed-prev-word", NULL);
394 el_set(e, EL_BIND, "\\e\\e[C", "em-next-word", NULL);
395 el_set(e, EL_BIND, "\\e\\e[D", "ed-prev-word", NULL);
397 /* read settings from configuration file */
401 * Unfortunately, some applications really do use rl_point
402 * and rl_line_buffer directly.
404 _resize_fun(e, &rl_line_buffer);
408 (*rl_startup_hook)(NULL, 0);
415 * read one line from input stream and return it, chomping
416 * trailing newline (if there is any)
419 readline(const char *p)
422 const char * volatile prompt = p;
426 static int used_event_hook;
428 if (e == NULL || h == NULL)
433 (void)setjmp(topbuf);
435 /* update prompt accordingly to what has been passed */
436 if (rl_set_prompt(prompt) == -1)
439 if (rl_pre_input_hook)
440 (*rl_pre_input_hook)(NULL, 0);
442 if (rl_event_hook && !(e->el_flags&NO_TTY)) {
443 el_set(e, EL_GETCFN, _rl_event_read_char);
447 if (!rl_event_hook && used_event_hook) {
448 el_set(e, EL_GETCFN, EL_BUILTIN_GETCFN);
452 rl_already_prompted = 0;
454 /* get one line from input stream */
455 ret = el_gets(e, &count);
457 if (ret && count > 0) {
464 if (buf[lastidx] == '\n')
469 history(h, &ev, H_GETSIZE);
470 history_length = ev.num;
480 * is normally called before application starts to use
481 * history expansion functions
486 if (h == NULL || e == NULL)
492 * substitute ``what'' with ``with'', returning resulting string; if
493 * globally == 1, substitutes all occurrences of what, otherwise only the
497 _rl_compat_sub(const char *str, const char *what, const char *with,
502 size_t len, with_len, what_len;
505 with_len = strlen(with);
506 what_len = strlen(what);
508 /* calculate length we need for result */
511 if (*s == *what && !strncmp(s, what, what_len)) {
512 len += with_len - what_len;
519 r = result = el_malloc((len + 1) * sizeof(*r));
524 if (*s == *what && !strncmp(s, what, what_len)) {
525 (void)strncpy(r, with, with_len);
539 static char *last_search_pat; /* last !?pat[?] search pattern */
540 static char *last_search_match; /* last !?pat[?] that matched */
543 get_history_event(const char *cmd, int *cindex, int qchar)
545 int idx, sign, sub, num, begin, ret;
552 if (cmd[idx++] != history_expansion_char)
555 /* find out which event to take */
556 if (cmd[idx] == history_expansion_char || cmd[idx] == '\0') {
557 if (history(h, &ev, H_FIRST) != 0)
559 *cindex = cmd[idx]? (idx + 1):idx;
563 if (cmd[idx] == '-') {
568 if ('0' <= cmd[idx] && cmd[idx] <= '9') {
572 while (cmd[idx] && '0' <= cmd[idx] && cmd[idx] <= '9') {
573 num = num * 10 + cmd[idx] - '0';
577 num = history_length - num + 1;
579 if (!(rl_he = history_get(num)))
586 if (cmd[idx] == '?') {
592 if (cmd[idx] == '\n')
594 if (sub && cmd[idx] == '?')
596 if (!sub && (cmd[idx] == ':' || cmd[idx] == ' '
597 || cmd[idx] == '\t' || cmd[idx] == qchar))
601 len = (size_t)idx - (size_t)begin;
602 if (sub && cmd[idx] == '?')
604 if (sub && len == 0 && last_search_pat && *last_search_pat)
605 pat = last_search_pat;
609 if ((pat = el_malloc((len + 1) * sizeof(*pat))) == NULL)
611 (void)strncpy(pat, cmd + begin, len);
615 if (history(h, &ev, H_CURR) != 0) {
616 if (pat != last_search_pat)
623 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 if (last_search_match && last_search_match != pat)
643 el_free(last_search_match);
644 last_search_match = pat;
647 if (pat != last_search_pat)
650 if (history(h, &ev, H_CURR) != 0)
655 /* roll back to original position */
656 (void)history(h, &ev, H_SET, num);
662 * the real function doing history expansion - takes as argument command
663 * to do and data upon which the command should be executed
664 * does expansion the way I've understood readline documentation
666 * returns 0 if data was not modified, 1 if it was and 2 if the string
667 * should be only printed and not executed; in case of error,
668 * returns -1 and *result points to NULL
669 * it's the caller's responsibility to free() the string returned in *result
672 _history_expand_command(const char *command, size_t offs, size_t cmdlen,
675 char *tmp, *search = NULL, *aptr;
676 const char *ptr, *cmd;
677 static char *from = NULL, *to = NULL;
678 int start, end, idx, has_mods = 0;
679 int p_on = 0, g_on = 0;
685 /* First get event specifier */
688 if (strchr(":^*$", command[offs + 1])) {
691 * "!:" is shorthand for "!!:".
692 * "!^", "!*" and "!$" are shorthand for
693 * "!!:^", "!!:*" and "!!:$" respectively.
695 str[0] = str[1] = '!';
697 ptr = get_history_event(str, &idx, 0);
698 idx = (command[offs + 1] == ':')? 1:0;
701 if (command[offs + 1] == '#') {
702 /* use command so far */
703 if ((aptr = el_malloc((offs + 1) * sizeof(*aptr)))
706 (void)strncpy(aptr, command, offs);
712 qchar = (offs > 0 && command[offs - 1] == '"')? '"':0;
713 ptr = get_history_event(command + offs, &idx, qchar);
715 has_mods = command[offs + (size_t)idx] == ':';
718 if (ptr == NULL && aptr == NULL)
722 *result = strdup(aptr ? aptr : ptr);
730 cmd = command + offs + idx + 1;
732 /* Now parse any word designators */
734 if (*cmd == '%') /* last word matched by ?pat? */
735 tmp = strdup(last_search_match? last_search_match:"");
736 else if (strchr("^*$-0123456789", *cmd)) {
739 start = end = 1, cmd++;
740 else if (*cmd == '$')
742 else if (*cmd == '*')
744 else if (*cmd == '-' || isdigit((unsigned char) *cmd)) {
746 while (*cmd && '0' <= *cmd && *cmd <= '9')
747 start = start * 10 + *cmd++ - '0';
750 if (isdigit((unsigned char) cmd[1])) {
753 while (*cmd && '0' <= *cmd && *cmd <= '9')
754 end = end * 10 + *cmd++ - '0';
755 } else if (cmd[1] == '$') {
762 } else if (*cmd == '*')
767 tmp = history_arg_extract(start, end, aptr? aptr:ptr);
769 (void)fprintf(rl_outstream, "%s: Bad word specifier",
770 command + offs + idx);
776 tmp = strdup(aptr? aptr:ptr);
781 if (*cmd == '\0' || ((size_t)(cmd - (command + offs)) >= cmdlen)) {
786 for (; *cmd; cmd++) {
789 else if (*cmd == 'h') { /* remove trailing path */
790 if ((aptr = strrchr(tmp, '/')) != NULL)
792 } else if (*cmd == 't') { /* remove leading path */
793 if ((aptr = strrchr(tmp, '/')) != NULL) {
794 aptr = strdup(aptr + 1);
798 } else if (*cmd == 'r') { /* remove trailing suffix */
799 if ((aptr = strrchr(tmp, '.')) != NULL)
801 } else if (*cmd == 'e') { /* remove all but suffix */
802 if ((aptr = strrchr(tmp, '.')) != NULL) {
807 } else if (*cmd == 'p') /* print only */
809 else if (*cmd == 'g')
811 else if (*cmd == 's' || *cmd == '&') {
812 char *what, *with, delim;
813 size_t len, from_len;
816 if (*cmd == '&' && (from == NULL || to == NULL))
818 else if (*cmd == 's') {
819 delim = *(++cmd), cmd++;
821 what = el_realloc(from, size * sizeof(*what));
828 for (; *cmd && *cmd != delim; cmd++) {
829 if (*cmd == '\\' && cmd[1] == delim)
833 nwhat = el_realloc(what,
850 from = strdup(search);
861 cmd++; /* shift after delim */
866 with = el_realloc(to, size * sizeof(*with));
873 from_len = strlen(from);
874 for (; *cmd && *cmd != delim; cmd++) {
875 if (len + from_len + 1 >= size) {
877 size += from_len + 1;
878 nwith = el_realloc(with,
879 size * sizeof(*nwith));
889 (void)strcpy(&with[len], from);
894 && (*(cmd + 1) == delim
895 || *(cmd + 1) == '&'))
903 aptr = _rl_compat_sub(tmp, from, to, g_on);
917 * csh-style history expansion
920 history_expand(char *str, char **output)
926 if (h == NULL || e == NULL)
929 if (history_expansion_char == 0) {
930 *output = strdup(str);
935 if (str[0] == history_subst_char) {
936 /* ^foo^foo2^ is equivalent to !!:s^foo^foo2^ */
937 *output = el_malloc((strlen(str) + 4 + 1) * sizeof(**output));
940 (*output)[0] = (*output)[1] = history_expansion_char;
943 (void)strcpy((*output) + 4, str);
946 *output = strdup(str);
951 #define ADD_STRING(what, len, fr) \
953 if (idx + len + 1 > size) { \
954 char *nresult = el_realloc(result, \
955 (size += len + 1) * sizeof(*nresult)); \
956 if (nresult == NULL) { \
958 if (/*CONSTCOND*/fr) \
964 (void)strncpy(&result[idx], what, len); \
966 result[idx] = '\0'; \
972 for (i = 0; str[i];) {
973 int qchar, loop_again;
974 size_t len, start, j;
980 for (; str[j]; j++) {
981 if (str[j] == '\\' &&
982 str[j + 1] == history_expansion_char) {
983 len = strlen(&str[j + 1]) + 1;
984 memmove(&str[j], &str[j + 1], len);
988 if (isspace((unsigned char) str[j])
992 if (str[j] == history_expansion_char
993 && !strchr(history_no_expand_chars, str[j + 1])
994 && (!history_inhibit_expansion_function ||
995 (*history_inhibit_expansion_function)(str,
1000 if (str[j] && loop_again) {
1002 qchar = (j > 0 && str[j - 1] == '"' )? '"':0;
1004 if (str[j] == history_expansion_char)
1010 ADD_STRING(&str[start], len, 0);
1012 if (str[i] == '\0' || str[i] != history_expansion_char) {
1014 ADD_STRING(&str[i], len, 0);
1021 ret = _history_expand_command (str, i, (j - i), &tmp);
1022 if (ret > 0 && tmp) {
1024 ADD_STRING(tmp, len, 1);
1033 /* ret is 2 for "print only" option */
1035 add_history(result);
1037 /* gdb 4.11 has been shipped with readline, where */
1038 /* history_expand() returned -1 when the line */
1039 /* should not be executed; in readline 2.1+ */
1040 /* it should return 2 in such a case */
1051 * Return a string consisting of arguments of "str" from "start" to "end".
1054 history_arg_extract(int start, int end, const char *str)
1057 char **arr, *result = NULL;
1059 arr = history_tokenize(str);
1062 if (arr && *arr == NULL)
1065 for (max = 0; arr[max]; max++)
1074 end = (int)max + end + 1;
1078 if (start < 0 || end < 0 || (size_t)start > max ||
1079 (size_t)end > max || start > end)
1082 for (i = (size_t)start, len = 0; i <= (size_t)end; i++)
1083 len += strlen(arr[i]) + 1;
1085 result = el_malloc(len * sizeof(*result));
1089 for (i = (size_t)start, len = 0; i <= (size_t)end; i++) {
1090 (void)strcpy(result + len, arr[i]);
1091 len += strlen(arr[i]);
1092 if (i < (size_t)end)
1093 result[len++] = ' ';
1098 for (i = 0; arr[i]; i++)
1106 * Parse the string into individual tokens,
1107 * similar to how shell would do it.
1110 history_tokenize(const char *str)
1112 int size = 1, idx = 0, i, start;
1114 char **result = NULL, *temp, delim = '\0';
1116 for (i = 0; str[i];) {
1117 while (isspace((unsigned char) str[i]))
1121 if (str[i] == '\\') {
1122 if (str[i+1] != '\0')
1124 } else if (str[i] == delim)
1127 (isspace((unsigned char) str[i]) ||
1128 strchr("()<>;&|$", str[i])))
1130 else if (!delim && strchr("'`\"", str[i]))
1136 if (idx + 2 >= size) {
1139 nresult = el_realloc(result, (size_t)size * sizeof(*nresult));
1140 if (nresult == NULL) {
1146 len = (size_t)i - (size_t)start;
1147 temp = el_malloc((size_t)(len + 1) * sizeof(*temp));
1149 for (i = 0; i < idx; i++)
1154 (void)strncpy(temp, &str[start], len);
1156 result[idx++] = temp;
1166 * limit size of history record to ``max'' events
1169 stifle_history(int max)
1173 if (h == NULL || e == NULL)
1176 if (history(h, &ev, H_SETSIZE, max) == 0)
1177 max_input_history = max;
1182 * "unlimit" size of history - set the limit to maximum allowed int value
1185 unstifle_history(void)
1190 history(h, &ev, H_SETSIZE, INT_MAX);
1191 omax = max_input_history;
1192 max_input_history = INT_MAX;
1193 return omax; /* some value _must_ be returned */
1198 history_is_stifled(void)
1201 /* cannot return true answer */
1202 return max_input_history != INT_MAX;
1205 static const char _history_tmp_template[] = "/tmp/.historyXXXXXX";
1208 history_truncate_file (const char *filename, int nlines)
1212 char template[sizeof(_history_tmp_template)];
1220 if (filename == NULL && (filename = _default_history_file()) == NULL)
1222 if ((fp = fopen(filename, "r+")) == NULL)
1224 strcpy(template, _history_tmp_template);
1225 if ((fd = mkstemp(template)) == -1) {
1230 if ((tp = fdopen(fd, "r+")) == NULL) {
1237 if (fread(buf, sizeof(buf), (size_t)1, fp) != 1) {
1242 if (fseeko(fp, (off_t)sizeof(buf) * count, SEEK_SET) ==
1247 left = (ssize_t)fread(buf, (size_t)1, sizeof(buf), fp);
1255 } else if (fwrite(buf, (size_t)left, (size_t)1, tp)
1263 if (fwrite(buf, sizeof(buf), (size_t)1, tp) != 1) {
1271 cp = buf + left - 1;
1275 while (--cp >= buf) {
1277 if (--nlines == 0) {
1278 if (++cp >= buf + sizeof(buf)) {
1286 if (nlines <= 0 || count == 0)
1289 if (fseeko(tp, (off_t)sizeof(buf) * count, SEEK_SET) < 0) {
1293 if (fread(buf, sizeof(buf), (size_t)1, tp) != 1) {
1301 cp = buf + sizeof(buf);
1304 if (ret || nlines > 0)
1307 if (fseeko(fp, (off_t)0, SEEK_SET) == (off_t)-1) {
1312 if (fseeko(tp, (off_t)sizeof(buf) * count + (cp - buf), SEEK_SET) ==
1319 if ((left = (ssize_t)fread(buf, (size_t)1, sizeof(buf), tp)) == 0) {
1324 if (fwrite(buf, (size_t)left, (size_t)1, fp) != 1) {
1330 if((off = ftello(fp)) > 0)
1331 (void)ftruncate(fileno(fp), off);
1344 * read history from a file given
1347 read_history(const char *filename)
1351 if (h == NULL || e == NULL)
1353 if (filename == NULL && (filename = _default_history_file()) == NULL)
1355 return history(h, &ev, H_LOAD, filename) == -1 ?
1356 (errno ? errno : EINVAL) : 0;
1361 * write history to a file given
1364 write_history(const char *filename)
1368 if (h == NULL || e == NULL)
1370 if (filename == NULL && (filename = _default_history_file()) == NULL)
1372 return history(h, &ev, H_SAVE, filename) == -1 ?
1373 (errno ? errno : EINVAL) : 0;
1378 * returns history ``num''th event
1380 * returned pointer points to static variable
1383 history_get(int num)
1385 static HIST_ENTRY she;
1389 if (h == NULL || e == NULL)
1392 /* save current position */
1393 if (history(h, &ev, H_CURR) != 0)
1397 /* start from the oldest */
1398 if (history(h, &ev, H_LAST) != 0)
1399 return NULL; /* error */
1401 /* look forwards for event matching specified offset */
1402 if (history(h, &ev, H_NEXT_EVDATA, num, &she.data))
1407 /* restore pointer to where it was */
1408 (void)history(h, &ev, H_SET, curr_num);
1415 * add the line to history table
1418 add_history(const char *line)
1425 if (h == NULL || e == NULL)
1428 (void)history(h, &ev, H_ENTER, line);
1429 if (history(h, &ev, H_GETSIZE) == 0)
1430 history_length = ev.num;
1432 return !(history_length > 0); /* return 0 if all is okay */
1437 * remove the specified entry from the history list and return it.
1440 remove_history(int num)
1445 if (h == NULL || e == NULL)
1448 if ((he = el_malloc(sizeof(*he))) == NULL)
1451 if (history(h, &ev, H_DELDATA, num, &he->data) != 0) {
1457 if (history(h, &ev, H_GETSIZE) == 0)
1458 history_length = ev.num;
1465 * replace the line and data of the num-th entry
1468 replace_history_entry(int num, const char *line, histdata_t data)
1474 if (h == NULL || e == NULL)
1477 /* save current position */
1478 if (history(h, &ev, H_CURR) != 0)
1482 /* start from the oldest */
1483 if (history(h, &ev, H_LAST) != 0)
1484 return NULL; /* error */
1486 if ((he = el_malloc(sizeof(*he))) == NULL)
1489 /* look forwards for event matching specified offset */
1490 if (history(h, &ev, H_NEXT_EVDATA, num, &he->data))
1493 he->line = strdup(ev.str);
1494 if (he->line == NULL)
1497 if (history(h, &ev, H_REPLACE, line, data))
1500 /* restore pointer to where it was */
1501 if (history(h, &ev, H_SET, curr_num))
1511 * clear the history list - delete all entries
1518 if (h == NULL || e == NULL)
1521 (void)history(h, &ev, H_CLEAR);
1527 * returns offset of the current history event
1535 if (history(h, &ev, H_CURR) != 0)
1539 (void)history(h, &ev, H_FIRST);
1541 while (ev.num != curr_num && history(h, &ev, H_NEXT) == 0)
1549 * returns current history event or NULL if there is no such event
1552 current_history(void)
1555 return _move_history(H_CURR);
1560 * returns total number of bytes history events' data are using
1563 history_total_bytes(void)
1569 if (history(h, &ev, H_CURR) != 0)
1573 (void)history(h, &ev, H_FIRST);
1576 size += strlen(ev.str) * sizeof(*ev.str);
1577 while (history(h, &ev, H_NEXT) == 0);
1579 /* get to the same position as before */
1580 history(h, &ev, H_PREV_EVENT, curr_num);
1587 * sets the position in the history list to ``pos''
1590 history_set_pos(int pos)
1595 if (pos >= history_length || pos < 0)
1598 (void)history(h, &ev, H_CURR);
1602 * use H_DELDATA to set to nth history (without delete) by passing
1605 if (history(h, &ev, H_DELDATA, pos, (void **)-1)) {
1606 (void)history(h, &ev, H_SET, curr_num);
1614 * returns previous event in history and shifts pointer accordingly
1617 previous_history(void)
1620 return _move_history(H_PREV);
1625 * returns next event in history and shifts pointer accordingly
1631 return _move_history(H_NEXT);
1636 * searches for first history event containing the str
1639 history_search(const char *str, int direction)
1645 if (history(h, &ev, H_CURR) != 0)
1650 if ((strp = strstr(ev.str, str)) != NULL)
1651 return (int)(strp - ev.str);
1652 if (history(h, &ev, direction < 0 ? H_NEXT:H_PREV) != 0)
1655 (void)history(h, &ev, H_SET, curr_num);
1661 * searches for first history event beginning with str
1664 history_search_prefix(const char *str, int direction)
1668 return (history(h, &ev, direction < 0 ?
1669 H_PREV_STR : H_NEXT_STR, str));
1674 * search for event in history containing str, starting at offset
1675 * abs(pos); continue backward, if pos<0, forward otherwise
1679 history_search_pos(const char *str,
1680 int direction __attribute__((__unused__)), int pos)
1685 off = (pos > 0) ? pos : -pos;
1686 pos = (pos > 0) ? 1 : -1;
1688 if (history(h, &ev, H_CURR) != 0)
1692 if (history_set_pos(off) != 0 || history(h, &ev, H_CURR) != 0)
1696 if (strstr(ev.str, str))
1698 if (history(h, &ev, (pos < 0) ? H_PREV : H_NEXT) != 0)
1702 /* set "current" pointer back to previous state */
1703 (void)history(h, &ev,
1704 pos < 0 ? H_NEXT_EVENT : H_PREV_EVENT, curr_num);
1710 /********************************/
1711 /* completion functions */
1714 tilde_expand(char *name)
1716 return fn_tilde_expand(name);
1720 filename_completion_function(const char *name, int state)
1722 return fn_filename_completion_function(name, state);
1726 * a completion generator for usernames; returns _first_ username
1727 * which starts with supplied text
1728 * text contains a partial username preceded by random character
1729 * (usually '~'); state resets search from start (??? should we do that anyway)
1730 * it's the caller's responsibility to free the returned value
1733 username_completion_function(const char *text, int state)
1735 #if defined(HAVE_GETPW_R_POSIX) || defined(HAVE_GETPW_R_DRAFT)
1736 struct passwd pwres;
1739 struct passwd *pass = NULL;
1741 if (text[0] == '\0')
1751 #if defined(HAVE_GETPW_R_POSIX) || defined(HAVE_GETPW_R_DRAFT)
1752 getpwent_r(&pwres, pwbuf, sizeof(pwbuf), &pass) == 0 && pass != NULL
1754 (pass = getpwent()) != NULL
1756 && text[0] == pass->pw_name[0]
1757 && strcmp(text, pass->pw_name) == 0)
1764 return strdup(pass->pw_name);
1769 * el-compatible wrapper to send TSTP on ^Z
1772 static unsigned char
1773 _el_rl_tstp(EditLine *el __attribute__((__unused__)), int ch __attribute__((__unused__)))
1775 (void)kill(0, SIGTSTP);
1780 * Display list of strings in columnar format on readline's output stream.
1781 * 'matches' is list of strings, 'len' is number of strings in 'matches',
1782 * 'max' is maximum length of string in 'matches'.
1785 rl_display_match_list(char **matches, int len, int max)
1788 fn_display_match_list(e, matches, (size_t)len, (size_t)max);
1793 _rl_completion_append_character_function(const char *dummy
1794 __attribute__((__unused__)))
1797 buf[0] = (char)rl_completion_append_character;
1804 * complete word at current point
1808 rl_complete(int ignore __attribute__((__unused__)), int invoking_key)
1811 static ct_buffer_t wbreak_conv, sprefix_conv;
1815 if (h == NULL || e == NULL)
1818 if (rl_inhibit_completion) {
1820 arr[0] = (char)invoking_key;
1822 el_insertstr(e, arr);
1826 if (rl_completion_word_break_hook != NULL)
1827 breakchars = (*rl_completion_word_break_hook)();
1829 breakchars = rl_basic_word_break_characters;
1833 /* Just look at how many global variables modify this operation! */
1834 return fn_complete(e,
1835 (rl_compentry_func_t *)rl_completion_entry_function,
1836 rl_attempted_completion_function,
1837 ct_decode_string(rl_basic_word_break_characters, &wbreak_conv),
1838 ct_decode_string(breakchars, &sprefix_conv),
1839 _rl_completion_append_character_function,
1840 (size_t)rl_completion_query_items,
1841 &rl_completion_type, &rl_attempted_completion_over,
1842 &rl_point, &rl_end, NULL, NULL, NULL);
1849 static unsigned char
1850 _el_rl_complete(EditLine *el __attribute__((__unused__)), int ch)
1852 return (unsigned char)rl_complete(0, ch);
1856 * misc other functions
1860 * bind key c to readline-type function func
1863 rl_bind_key(int c, rl_command_func_t *func)
1867 if (h == NULL || e == NULL)
1870 if (func == rl_insert) {
1871 /* XXX notice there is no range checking of ``c'' */
1872 e->el_map.key[c] = ED_INSERT;
1880 * read one key from input - handles chars pushed back
1881 * to input stream also
1886 char fooarr[2 * sizeof(int)];
1888 if (e == NULL || h == NULL)
1891 return el_getc(e, fooarr);
1896 * reset the terminal
1900 rl_reset_terminal(const char *p __attribute__((__unused__)))
1903 if (h == NULL || e == NULL)
1910 * insert character ``c'' back into input stream, ``count'' times
1913 rl_insert(int count, int c)
1917 if (h == NULL || e == NULL)
1920 /* XXX - int -> char conversion can lose on multichars */
1924 for (; count > 0; count--)
1931 rl_insert_text(const char *text)
1933 if (!text || *text == 0)
1936 if (h == NULL || e == NULL)
1939 if (el_insertstr(e, text) < 0)
1941 return (int)strlen(text);
1946 rl_newline(int count __attribute__((__unused__)),
1947 int c __attribute__((__unused__)))
1950 * Readline-4.0 appears to ignore the args.
1952 return rl_insert(1, '\n');
1956 static unsigned char
1957 rl_bind_wrapper(EditLine *el __attribute__((__unused__)), unsigned char c)
1966 /* If rl_done was set by the above call, deal with it here */
1974 rl_add_defun(const char *name, rl_command_func_t *fun, int c)
1977 if ((size_t)c >= sizeof(map) / sizeof(map[0]) || c < 0)
1979 map[(unsigned char)c] = fun;
1980 el_set(e, EL_ADDFN, name, name, rl_bind_wrapper);
1981 vis(dest, c, VIS_WHITE|VIS_NOSLASH, 0);
1982 el_set(e, EL_BIND, dest, name, NULL);
1987 rl_callback_read_char(void)
1989 int count = 0, done = 0;
1990 const char *buf = el_gets(e, &count);
1993 if (buf == NULL || count-- <= 0)
1995 if (count == 0 && buf[0] == e->el_tty.t_c[TS_IO][C_EOF])
1997 if (buf[count] == '\n' || buf[count] == '\r')
2000 if (done && rl_linefunc != NULL) {
2001 el_set(e, EL_UNBUFFERED, 0);
2003 if ((wbuf = strdup(buf)) != NULL)
2007 (*(void (*)(const char *))rl_linefunc)(wbuf);
2008 el_set(e, EL_UNBUFFERED, 1);
2013 rl_callback_handler_install(const char *prompt, rl_vcpfunc_t *linefunc)
2018 (void)rl_set_prompt(prompt);
2019 rl_linefunc = linefunc;
2020 el_set(e, EL_UNBUFFERED, 1);
2024 rl_callback_handler_remove(void)
2026 el_set(e, EL_UNBUFFERED, 0);
2034 a[0] = (char)e->el_tty.t_c[TS_IO][C_REPRINT];
2040 rl_get_previous_history(int count, int key)
2052 rl_prep_terminal(int meta_flag __attribute__((__unused__)))
2054 el_set(e, EL_PREP_TERM, 1);
2058 rl_deprep_terminal(void)
2060 el_set(e, EL_PREP_TERM, 0);
2064 rl_read_init_file(const char *s)
2066 return el_source(e, s);
2070 rl_parse_and_bind(const char *line)
2076 tok = tok_init(NULL);
2077 tok_str(tok, line, &argc, &argv);
2078 argc = el_parse(e, argc, argv);
2080 return argc ? 1 : 0;
2084 rl_variable_bind(const char *var, const char *value)
2087 * The proper return value is undocument, but this is what the
2088 * readline source seems to do.
2090 return el_set(e, EL_BIND, "", var, value, NULL) == -1 ? 1 : 0;
2094 rl_stuff_char(int c)
2100 el_insertstr(e, buf);
2104 _rl_event_read_char(EditLine *el, wchar_t *wc)
2108 ssize_t num_read = 0;
2112 while (rl_event_hook) {
2116 #if defined(FIONREAD)
2117 if (ioctl(el->el_infd, FIONREAD, &n) < 0)
2120 num_read = read(el->el_infd, &ch, (size_t)1);
2123 #elif defined(F_SETFL) && defined(O_NDELAY)
2124 if ((n = fcntl(el->el_infd, F_GETFL, 0)) < 0)
2126 if (fcntl(el->el_infd, F_SETFL, n|O_NDELAY) < 0)
2128 num_read = read(el->el_infd, &ch, 1);
2129 if (fcntl(el->el_infd, F_SETFL, n))
2132 /* not non-blocking, but what you gonna do? */
2133 num_read = read(el->el_infd, &ch, 1);
2137 if (num_read < 0 && errno == EAGAIN)
2144 el_set(el, EL_GETCFN, EL_BUILTIN_GETCFN);
2146 return (int)num_read;
2150 _rl_update_pos(void)
2152 const LineInfo *li = el_line(e);
2154 rl_point = (int)(li->cursor - li->buffer);
2155 rl_end = (int)(li->lastchar - li->buffer);
2159 rl_get_screen_size(int *rows, int *cols)
2162 el_get(e, EL_GETTC, "li", rows, (void *)0);
2164 el_get(e, EL_GETTC, "co", cols, (void *)0);
2168 rl_set_screen_size(int rows, int cols)
2171 (void)snprintf(buf, sizeof(buf), "%d", rows);
2172 el_set(e, EL_SETTC, "li", buf, NULL);
2173 (void)snprintf(buf, sizeof(buf), "%d", cols);
2174 el_set(e, EL_SETTC, "co", buf, NULL);
2178 rl_completion_matches(const char *str, rl_compentry_func_t *fun)
2180 size_t len, max, i, j, min;
2181 char **list, *match, *a, *b;
2185 if ((list = el_malloc(max * sizeof(*list))) == NULL)
2188 while ((match = (*fun)(str, (int)(len - 1))) != NULL) {
2189 list[len++] = match;
2193 if ((nl = el_realloc(list, max * sizeof(*nl))) == NULL)
2202 if ((list[0] = strdup(list[1])) == NULL)
2206 qsort(&list[1], len - 1, sizeof(*list),
2207 (int (*)(const void *, const void *)) strcmp);
2209 for (i = 1, a = list[i]; i < len - 1; i++, a = b) {
2211 for (j = 0; a[j] && a[j] == b[j]; j++)
2216 if (min == 0 && *str) {
2217 if ((list[0] = strdup(str)) == NULL)
2220 if ((list[0] = el_malloc((min + 1) * sizeof(*list[0]))) == NULL)
2222 (void)memcpy(list[0], list[1], min);
2223 list[0][min] = '\0';
2233 rl_filename_completion_function (const char *text, int state)
2235 return fn_filename_completion_function(text, state);
2239 rl_forced_update_display(void)
2241 el_set(e, EL_REFRESH);
2245 _rl_abort_internal(void)
2253 _rl_qsort_string_compare(char **s1, char **s2)
2255 return strcoll(*s1, *s2);
2259 history_get_history_state(void)
2263 if ((hs = el_malloc(sizeof(*hs))) == NULL)
2265 hs->length = history_length;
2271 rl_kill_text(int from __attribute__((__unused__)),
2272 int to __attribute__((__unused__)))
2278 rl_make_bare_keymap(void)
2291 rl_set_keymap(Keymap k __attribute__((__unused__)))
2297 rl_generic_bind(int type __attribute__((__unused__)),
2298 const char * keyseq __attribute__((__unused__)),
2299 const char * data __attribute__((__unused__)),
2300 Keymap k __attribute__((__unused__)))
2307 rl_bind_key_in_map(int key __attribute__((__unused__)),
2308 rl_command_func_t *fun __attribute__((__unused__)),
2309 Keymap k __attribute__((__unused__)))
2314 /* unsupported, but needed by python */
2316 rl_cleanup_after_signal(void)
2321 rl_on_new_line(void)
2327 rl_free_line_state(void)
2333 rl_set_keyboard_input_timeout(int u __attribute__((__unused__)))