1 /* $NetBSD: readline.c,v 1.115 2015/04/01 15:23:15 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.115 2015/04/01 15:23:15 christos Exp $");
35 #endif /* not lint && not SCCSID */
36 #include <sys/cdefs.h>
37 __FBSDID("$FreeBSD$");
39 #include <sys/types.h>
54 #include "readline/readline.h"
56 #include "fcns.h" /* for EL_NUM_FCNS */
58 #include "filecomplete.h"
60 void rl_prep_terminal(int);
61 void rl_deprep_terminal(void);
63 /* for rl_complete() */
66 /* see comment at the #ifdef for sense of this */
67 /* #define GDB_411_HACK */
69 /* readline compatibility stuff - look at readline sources/documentation */
70 /* to see what these variables mean */
71 const char *rl_library_version = "EditLine wrapper";
72 int rl_readline_version = RL_READLINE_VERSION;
73 static char empty[] = { '\0' };
74 static char expand_chars[] = { ' ', '\t', '\n', '=', '(', '\0' };
75 static char break_chars[] = { ' ', '\t', '\n', '"', '\\', '\'', '`', '@', '$',
76 '>', '<', '=', ';', '|', '&', '{', '(', '\0' };
77 char *rl_readline_name = empty;
78 FILE *rl_instream = NULL;
79 FILE *rl_outstream = NULL;
82 char *rl_line_buffer = NULL;
83 VCPFunction *rl_linefunc = NULL;
85 VFunction *rl_event_hook = NULL;
86 KEYMAP_ENTRY_ARRAY emacs_standard_keymap,
90 * The following is not implemented; we always catch signals in the
91 * libedit fashion: set handlers on entry to el_gets() and clear them
92 * on the way out. This simplistic approach works for most cases; if
93 * it does not work for your application, please let us know.
95 int rl_catch_signals = 1;
96 int rl_catch_sigwinch = 1;
98 int history_base = 1; /* probably never subject to change */
99 int history_length = 0;
100 int max_input_history = 0;
101 char history_expansion_char = '!';
102 char history_subst_char = '^';
103 char *history_no_expand_chars = expand_chars;
104 Function *history_inhibit_expansion_function = NULL;
105 char *history_arg_extract(int start, int end, const char *str);
107 int rl_inhibit_completion = 0;
108 int rl_attempted_completion_over = 0;
109 char *rl_basic_word_break_characters = break_chars;
110 char *rl_completer_word_break_characters = NULL;
111 char *rl_completer_quote_characters = NULL;
112 Function *rl_completion_entry_function = NULL;
113 char *(*rl_completion_word_break_hook)(void) = NULL;
114 CPPFunction *rl_attempted_completion_function = NULL;
115 Function *rl_pre_input_hook = NULL;
116 Function *rl_startup1_hook = NULL;
117 int (*rl_getc_function)(FILE *) = NULL;
118 char *rl_terminal_name = NULL;
119 int rl_already_prompted = 0;
120 int rl_filename_completion_desired = 0;
121 int rl_ignore_completion_duplicates = 0;
122 int readline_echoing_p = 1;
123 int _rl_print_completions_horizontally = 0;
124 VFunction *rl_redisplay_function = NULL;
125 Function *rl_startup_hook = NULL;
126 VFunction *rl_completion_display_matches_hook = NULL;
127 VFunction *rl_prep_term_function = (VFunction *)rl_prep_terminal;
128 VFunction *rl_deprep_term_function = (VFunction *)rl_deprep_terminal;
129 KEYMAP_ENTRY_ARRAY emacs_meta_keymap;
132 * The current prompt string.
134 char *rl_prompt = NULL;
136 * This is set to character indicating type of completion being done by
137 * rl_complete_internal(); this is available for application completion
140 int rl_completion_type = 0;
143 * If more than this number of items results from query for possible
144 * completions, we ask user if they are sure to really display the list.
146 int rl_completion_query_items = 100;
149 * List of characters which are word break characters, but should be left
150 * in the parsed text when it is passed to the completion function.
151 * Shell uses this to help determine what kind of completing to do.
153 char *rl_special_prefixes = NULL;
156 * This is the character appended to the completed words if at the end of
157 * the line. Default is ' ' (a space).
159 int rl_completion_append_character = ' ';
161 /* stuff below is used internally by libedit for readline emulation */
163 static History *h = NULL;
164 static EditLine *e = NULL;
165 static Function *map[256];
166 static jmp_buf topbuf;
168 /* internal functions */
169 static unsigned char _el_rl_complete(EditLine *, int);
170 static unsigned char _el_rl_tstp(EditLine *, int);
171 static char *_get_prompt(EditLine *);
172 static int _getc_function(EditLine *, char *);
173 static HIST_ENTRY *_move_history(int);
174 static int _history_expand_command(const char *, size_t, size_t,
176 static char *_rl_compat_sub(const char *, const char *,
178 static int _rl_event_read_char(EditLine *, char *);
179 static void _rl_update_pos(void);
184 _get_prompt(EditLine *el __attribute__((__unused__)))
186 rl_already_prompted = 1;
192 * generic function for moving around history
195 _move_history(int op)
198 static HIST_ENTRY rl_he;
200 if (history(h, &ev, op) != 0)
211 * read one key from user defined input function
215 _getc_function(EditLine *el __attribute__((__unused__)), char *c)
219 i = (*rl_getc_function)(NULL);
227 _resize_fun(EditLine *el, void *a)
233 /* a cheesy way to get rid of const cast. */
234 *ap = memchr(li->buffer, *li->buffer, (size_t)1);
238 _default_history_file(void)
247 if ((p = getpwuid(getuid())) == NULL)
250 len = strlen(p->pw_dir) + sizeof("/.history");
251 if ((path = malloc(len)) == NULL)
254 (void)snprintf(path, len, "%s/.history", p->pw_dir);
259 * READLINE compatibility stuff
266 rl_set_prompt(const char *prompt)
272 if (rl_prompt != NULL && strcmp(rl_prompt, prompt) == 0)
276 rl_prompt = strdup(prompt);
277 if (rl_prompt == NULL)
280 while ((p = strchr(rl_prompt, RL_PROMPT_END_IGNORE)) != NULL)
281 *p = RL_PROMPT_START_IGNORE;
287 * initialize rl compat stuff
304 rl_outstream = stdout;
307 * See if we don't really want to run the editor
309 if (tcgetattr(fileno(rl_instream), &t) != -1 && (t.c_lflag & ECHO) == 0)
312 e = el_init(rl_readline_name, rl_instream, rl_outstream, stderr);
315 el_set(e, EL_EDITMODE, 0);
321 history(h, &ev, H_SETSIZE, INT_MAX); /* unlimited */
323 max_input_history = INT_MAX;
324 el_set(e, EL_HIST, history, h);
326 /* Setup resize function */
327 el_set(e, EL_RESIZE, _resize_fun, &rl_line_buffer);
329 /* setup getc function if valid */
330 if (rl_getc_function)
331 el_set(e, EL_GETCFN, _getc_function);
333 /* for proper prompt printing in readline() */
334 if (rl_set_prompt("") == -1) {
339 el_set(e, EL_PROMPT, _get_prompt, RL_PROMPT_START_IGNORE);
340 el_set(e, EL_SIGNAL, rl_catch_signals);
342 /* set default mode to "emacs"-style and read setting afterwards */
343 /* so this can be overridden */
344 el_set(e, EL_EDITOR, "emacs");
345 if (rl_terminal_name != NULL)
346 el_set(e, EL_TERMINAL, rl_terminal_name);
348 el_get(e, EL_TERMINAL, &rl_terminal_name);
351 * Word completion - this has to go AFTER rebinding keys
354 el_set(e, EL_ADDFN, "rl_complete",
355 "ReadLine compatible completion function",
357 el_set(e, EL_BIND, "^I", "rl_complete", NULL);
360 * Send TSTP when ^Z is pressed.
362 el_set(e, EL_ADDFN, "rl_tstp",
363 "ReadLine compatible suspend function",
365 el_set(e, EL_BIND, "^Z", "rl_tstp", NULL);
368 * Set some readline compatible key-bindings.
370 el_set(e, EL_BIND, "^R", "em-inc-search-prev", NULL);
373 * Allow the use of Home/End keys.
375 el_set(e, EL_BIND, "\\e[1~", "ed-move-to-beg", NULL);
376 el_set(e, EL_BIND, "\\e[4~", "ed-move-to-end", NULL);
377 el_set(e, EL_BIND, "\\e[7~", "ed-move-to-beg", NULL);
378 el_set(e, EL_BIND, "\\e[8~", "ed-move-to-end", NULL);
379 el_set(e, EL_BIND, "\\e[H", "ed-move-to-beg", NULL);
380 el_set(e, EL_BIND, "\\e[F", "ed-move-to-end", NULL);
383 * Allow the use of the Delete/Insert keys.
385 el_set(e, EL_BIND, "\\e[3~", "ed-delete-next-char", NULL);
386 el_set(e, EL_BIND, "\\e[2~", "ed-quoted-insert", NULL);
389 * Ctrl-left-arrow and Ctrl-right-arrow for word moving.
391 el_set(e, EL_BIND, "\\e[1;5C", "em-next-word", NULL);
392 el_set(e, EL_BIND, "\\e[1;5D", "ed-prev-word", NULL);
393 el_set(e, EL_BIND, "\\e[5C", "em-next-word", NULL);
394 el_set(e, EL_BIND, "\\e[5D", "ed-prev-word", NULL);
395 el_set(e, EL_BIND, "\\e\\e[C", "em-next-word", NULL);
396 el_set(e, EL_BIND, "\\e\\e[D", "ed-prev-word", NULL);
398 /* read settings from configuration file */
402 * Unfortunately, some applications really do use rl_point
403 * and rl_line_buffer directly.
405 _resize_fun(e, &rl_line_buffer);
409 (*rl_startup_hook)(NULL, 0);
416 * read one line from input stream and return it, chomping
417 * trailing newline (if there is any)
420 readline(const char *p)
423 const char * volatile prompt = p;
427 static int used_event_hook;
429 if (e == NULL || h == NULL)
434 (void)setjmp(topbuf);
436 /* update prompt accordingly to what has been passed */
437 if (rl_set_prompt(prompt) == -1)
440 if (rl_pre_input_hook)
441 (*rl_pre_input_hook)(NULL, 0);
443 if (rl_event_hook && !(e->el_flags&NO_TTY)) {
444 el_set(e, EL_GETCFN, _rl_event_read_char);
448 if (!rl_event_hook && used_event_hook) {
449 el_set(e, EL_GETCFN, EL_BUILTIN_GETCFN);
453 rl_already_prompted = 0;
455 /* get one line from input stream */
456 ret = el_gets(e, &count);
458 if (ret && count > 0) {
465 if (buf[lastidx] == '\n')
470 history(h, &ev, H_GETSIZE);
471 history_length = ev.num;
481 * is normally called before application starts to use
482 * history expansion functions
487 if (h == NULL || e == NULL)
493 * substitute ``what'' with ``with'', returning resulting string; if
494 * globally == 1, substitutes all occurrences of what, otherwise only the
498 _rl_compat_sub(const char *str, const char *what, const char *with,
503 size_t len, with_len, what_len;
506 with_len = strlen(with);
507 what_len = strlen(what);
509 /* calculate length we need for result */
512 if (*s == *what && !strncmp(s, what, what_len)) {
513 len += with_len - what_len;
520 r = result = el_malloc((len + 1) * sizeof(*r));
525 if (*s == *what && !strncmp(s, what, what_len)) {
526 (void)strncpy(r, with, with_len);
540 static char *last_search_pat; /* last !?pat[?] search pattern */
541 static char *last_search_match; /* last !?pat[?] that matched */
544 get_history_event(const char *cmd, int *cindex, int qchar)
546 int idx, sign, sub, num, begin, ret;
553 if (cmd[idx++] != history_expansion_char)
556 /* find out which event to take */
557 if (cmd[idx] == history_expansion_char || cmd[idx] == '\0') {
558 if (history(h, &ev, H_FIRST) != 0)
560 *cindex = cmd[idx]? (idx + 1):idx;
564 if (cmd[idx] == '-') {
569 if ('0' <= cmd[idx] && cmd[idx] <= '9') {
573 while (cmd[idx] && '0' <= cmd[idx] && cmd[idx] <= '9') {
574 num = num * 10 + cmd[idx] - '0';
578 num = history_length - num + 1;
580 if (!(rl_he = history_get(num)))
587 if (cmd[idx] == '?') {
593 if (cmd[idx] == '\n')
595 if (sub && cmd[idx] == '?')
597 if (!sub && (cmd[idx] == ':' || cmd[idx] == ' '
598 || cmd[idx] == '\t' || cmd[idx] == qchar))
602 len = (size_t)idx - (size_t)begin;
603 if (sub && cmd[idx] == '?')
605 if (sub && len == 0 && last_search_pat && *last_search_pat)
606 pat = last_search_pat;
610 if ((pat = el_malloc((len + 1) * sizeof(*pat))) == NULL)
612 (void)strncpy(pat, cmd + begin, len);
616 if (history(h, &ev, H_CURR) != 0) {
617 if (pat != last_search_pat)
624 if (pat != last_search_pat) {
626 el_free(last_search_pat);
627 last_search_pat = pat;
629 ret = history_search(pat, -1);
631 ret = history_search_prefix(pat, -1);
634 /* restore to end of list on failed search */
635 history(h, &ev, H_FIRST);
636 (void)fprintf(rl_outstream, "%s: Event not found\n", pat);
637 if (pat != last_search_pat)
643 if (last_search_match && last_search_match != pat)
644 el_free(last_search_match);
645 last_search_match = pat;
648 if (pat != last_search_pat)
651 if (history(h, &ev, H_CURR) != 0)
656 /* roll back to original position */
657 (void)history(h, &ev, H_SET, num);
663 * the real function doing history expansion - takes as argument command
664 * to do and data upon which the command should be executed
665 * does expansion the way I've understood readline documentation
667 * returns 0 if data was not modified, 1 if it was and 2 if the string
668 * should be only printed and not executed; in case of error,
669 * returns -1 and *result points to NULL
670 * it's the caller's responsibility to free() the string returned in *result
673 _history_expand_command(const char *command, size_t offs, size_t cmdlen,
676 char *tmp, *search = NULL, *aptr;
677 const char *ptr, *cmd;
678 static char *from = NULL, *to = NULL;
679 int start, end, idx, has_mods = 0;
680 int p_on = 0, g_on = 0;
686 /* First get event specifier */
689 if (strchr(":^*$", command[offs + 1])) {
692 * "!:" is shorthand for "!!:".
693 * "!^", "!*" and "!$" are shorthand for
694 * "!!:^", "!!:*" and "!!:$" respectively.
696 str[0] = str[1] = '!';
698 ptr = get_history_event(str, &idx, 0);
699 idx = (command[offs + 1] == ':')? 1:0;
702 if (command[offs + 1] == '#') {
703 /* use command so far */
704 if ((aptr = el_malloc((offs + 1) * sizeof(*aptr)))
707 (void)strncpy(aptr, command, offs);
713 qchar = (offs > 0 && command[offs - 1] == '"')? '"':0;
714 ptr = get_history_event(command + offs, &idx, qchar);
716 has_mods = command[offs + (size_t)idx] == ':';
719 if (ptr == NULL && aptr == NULL)
723 *result = strdup(aptr ? aptr : ptr);
731 cmd = command + offs + idx + 1;
733 /* Now parse any word designators */
735 if (*cmd == '%') /* last word matched by ?pat? */
736 tmp = strdup(last_search_match? last_search_match:"");
737 else if (strchr("^*$-0123456789", *cmd)) {
740 start = end = 1, cmd++;
741 else if (*cmd == '$')
743 else if (*cmd == '*')
745 else if (*cmd == '-' || isdigit((unsigned char) *cmd)) {
747 while (*cmd && '0' <= *cmd && *cmd <= '9')
748 start = start * 10 + *cmd++ - '0';
751 if (isdigit((unsigned char) cmd[1])) {
754 while (*cmd && '0' <= *cmd && *cmd <= '9')
755 end = end * 10 + *cmd++ - '0';
756 } else if (cmd[1] == '$') {
763 } else if (*cmd == '*')
768 tmp = history_arg_extract(start, end, aptr? aptr:ptr);
770 (void)fprintf(rl_outstream, "%s: Bad word specifier",
771 command + offs + idx);
777 tmp = strdup(aptr? aptr:ptr);
782 if (*cmd == '\0' || ((size_t)(cmd - (command + offs)) >= cmdlen)) {
787 for (; *cmd; cmd++) {
790 else if (*cmd == 'h') { /* remove trailing path */
791 if ((aptr = strrchr(tmp, '/')) != NULL)
793 } else if (*cmd == 't') { /* remove leading path */
794 if ((aptr = strrchr(tmp, '/')) != NULL) {
795 aptr = strdup(aptr + 1);
799 } else if (*cmd == 'r') { /* remove trailing suffix */
800 if ((aptr = strrchr(tmp, '.')) != NULL)
802 } else if (*cmd == 'e') { /* remove all but suffix */
803 if ((aptr = strrchr(tmp, '.')) != NULL) {
808 } else if (*cmd == 'p') /* print only */
810 else if (*cmd == 'g')
812 else if (*cmd == 's' || *cmd == '&') {
813 char *what, *with, delim;
814 size_t len, from_len;
817 if (*cmd == '&' && (from == NULL || to == NULL))
819 else if (*cmd == 's') {
820 delim = *(++cmd), cmd++;
822 what = el_realloc(from, size * sizeof(*what));
829 for (; *cmd && *cmd != delim; cmd++) {
830 if (*cmd == '\\' && cmd[1] == delim)
834 nwhat = el_realloc(what,
851 from = strdup(search);
862 cmd++; /* shift after delim */
867 with = el_realloc(to, size * sizeof(*with));
874 from_len = strlen(from);
875 for (; *cmd && *cmd != delim; cmd++) {
876 if (len + from_len + 1 >= size) {
878 size += from_len + 1;
879 nwith = el_realloc(with,
880 size * sizeof(*nwith));
890 (void)strcpy(&with[len], from);
895 && (*(cmd + 1) == delim
896 || *(cmd + 1) == '&'))
904 aptr = _rl_compat_sub(tmp, from, to, g_on);
918 * csh-style history expansion
921 history_expand(char *str, char **output)
927 if (h == NULL || e == NULL)
930 if (history_expansion_char == 0) {
931 *output = strdup(str);
936 if (str[0] == history_subst_char) {
937 /* ^foo^foo2^ is equivalent to !!:s^foo^foo2^ */
938 *output = el_malloc((strlen(str) + 4 + 1) * sizeof(**output));
941 (*output)[0] = (*output)[1] = history_expansion_char;
944 (void)strcpy((*output) + 4, str);
947 *output = strdup(str);
952 #define ADD_STRING(what, len, fr) \
954 if (idx + len + 1 > size) { \
955 char *nresult = el_realloc(result, \
956 (size += len + 1) * sizeof(*nresult)); \
957 if (nresult == NULL) { \
959 if (/*CONSTCOND*/fr) \
965 (void)strncpy(&result[idx], what, len); \
967 result[idx] = '\0'; \
973 for (i = 0; str[i];) {
974 int qchar, loop_again;
975 size_t len, start, j;
981 for (; str[j]; j++) {
982 if (str[j] == '\\' &&
983 str[j + 1] == history_expansion_char) {
984 len = strlen(&str[j + 1]) + 1;
985 memmove(&str[j], &str[j + 1], len);
989 if (isspace((unsigned char) str[j])
993 if (str[j] == history_expansion_char
994 && !strchr(history_no_expand_chars, str[j + 1])
995 && (!history_inhibit_expansion_function ||
996 (*history_inhibit_expansion_function)(str,
1001 if (str[j] && loop_again) {
1003 qchar = (j > 0 && str[j - 1] == '"' )? '"':0;
1005 if (str[j] == history_expansion_char)
1011 ADD_STRING(&str[start], len, 0);
1013 if (str[i] == '\0' || str[i] != history_expansion_char) {
1015 ADD_STRING(&str[i], len, 0);
1022 ret = _history_expand_command (str, i, (j - i), &tmp);
1023 if (ret > 0 && tmp) {
1025 ADD_STRING(tmp, len, 1);
1034 /* ret is 2 for "print only" option */
1036 add_history(result);
1038 /* gdb 4.11 has been shipped with readline, where */
1039 /* history_expand() returned -1 when the line */
1040 /* should not be executed; in readline 2.1+ */
1041 /* it should return 2 in such a case */
1052 * Return a string consisting of arguments of "str" from "start" to "end".
1055 history_arg_extract(int start, int end, const char *str)
1058 char **arr, *result = NULL;
1060 arr = history_tokenize(str);
1063 if (arr && *arr == NULL)
1066 for (max = 0; arr[max]; max++)
1075 end = (int)max + end + 1;
1079 if (start < 0 || end < 0 || (size_t)start > max ||
1080 (size_t)end > max || start > end)
1083 for (i = (size_t)start, len = 0; i <= (size_t)end; i++)
1084 len += strlen(arr[i]) + 1;
1086 result = el_malloc(len * sizeof(*result));
1090 for (i = (size_t)start, len = 0; i <= (size_t)end; i++) {
1091 (void)strcpy(result + len, arr[i]);
1092 len += strlen(arr[i]);
1093 if (i < (size_t)end)
1094 result[len++] = ' ';
1099 for (i = 0; arr[i]; i++)
1107 * Parse the string into individual tokens,
1108 * similar to how shell would do it.
1111 history_tokenize(const char *str)
1113 int size = 1, idx = 0, i, start;
1115 char **result = NULL, *temp, delim = '\0';
1117 for (i = 0; str[i];) {
1118 while (isspace((unsigned char) str[i]))
1122 if (str[i] == '\\') {
1123 if (str[i+1] != '\0')
1125 } else if (str[i] == delim)
1128 (isspace((unsigned char) str[i]) ||
1129 strchr("()<>;&|$", str[i])))
1131 else if (!delim && strchr("'`\"", str[i]))
1137 if (idx + 2 >= size) {
1140 nresult = el_realloc(result, (size_t)size * sizeof(*nresult));
1141 if (nresult == NULL) {
1147 len = (size_t)i - (size_t)start;
1148 temp = el_malloc((size_t)(len + 1) * sizeof(*temp));
1150 for (i = 0; i < idx; i++)
1155 (void)strncpy(temp, &str[start], len);
1157 result[idx++] = temp;
1167 * limit size of history record to ``max'' events
1170 stifle_history(int max)
1174 if (h == NULL || e == NULL)
1177 if (history(h, &ev, H_SETSIZE, max) == 0)
1178 max_input_history = max;
1183 * "unlimit" size of history - set the limit to maximum allowed int value
1186 unstifle_history(void)
1191 history(h, &ev, H_SETSIZE, INT_MAX);
1192 omax = max_input_history;
1193 max_input_history = INT_MAX;
1194 return omax; /* some value _must_ be returned */
1199 history_is_stifled(void)
1202 /* cannot return true answer */
1203 return max_input_history != INT_MAX;
1206 static const char _history_tmp_template[] = "/tmp/.historyXXXXXX";
1209 history_truncate_file (const char *filename, int nlines)
1213 char template[sizeof(_history_tmp_template)];
1221 if (filename == NULL && (filename = _default_history_file()) == NULL)
1223 if ((fp = fopen(filename, "r+")) == NULL)
1225 strcpy(template, _history_tmp_template);
1226 if ((fd = mkstemp(template)) == -1) {
1231 if ((tp = fdopen(fd, "r+")) == NULL) {
1238 if (fread(buf, sizeof(buf), (size_t)1, fp) != 1) {
1243 if (fseeko(fp, (off_t)sizeof(buf) * count, SEEK_SET) ==
1248 left = (ssize_t)fread(buf, (size_t)1, sizeof(buf), fp);
1256 } else if (fwrite(buf, (size_t)left, (size_t)1, tp)
1264 if (fwrite(buf, sizeof(buf), (size_t)1, tp) != 1) {
1272 cp = buf + left - 1;
1276 while (--cp >= buf) {
1278 if (--nlines == 0) {
1279 if (++cp >= buf + sizeof(buf)) {
1287 if (nlines <= 0 || count == 0)
1290 if (fseeko(tp, (off_t)sizeof(buf) * count, SEEK_SET) < 0) {
1294 if (fread(buf, sizeof(buf), (size_t)1, tp) != 1) {
1302 cp = buf + sizeof(buf);
1305 if (ret || nlines > 0)
1308 if (fseeko(fp, (off_t)0, SEEK_SET) == (off_t)-1) {
1313 if (fseeko(tp, (off_t)sizeof(buf) * count + (cp - buf), SEEK_SET) ==
1320 if ((left = (ssize_t)fread(buf, (size_t)1, sizeof(buf), tp)) == 0) {
1325 if (fwrite(buf, (size_t)left, (size_t)1, fp) != 1) {
1331 if((off = ftello(fp)) > 0)
1332 (void)ftruncate(fileno(fp), off);
1345 * read history from a file given
1348 read_history(const char *filename)
1352 if (h == NULL || e == NULL)
1354 if (filename == NULL && (filename = _default_history_file()) == NULL)
1356 return history(h, &ev, H_LOAD, filename) == -1 ?
1357 (errno ? errno : EINVAL) : 0;
1362 * write history to a file given
1365 write_history(const char *filename)
1369 if (h == NULL || e == NULL)
1371 if (filename == NULL && (filename = _default_history_file()) == NULL)
1373 return history(h, &ev, H_SAVE, filename) == -1 ?
1374 (errno ? errno : EINVAL) : 0;
1379 * returns history ``num''th event
1381 * returned pointer points to static variable
1384 history_get(int num)
1386 static HIST_ENTRY she;
1390 if (h == NULL || e == NULL)
1393 /* save current position */
1394 if (history(h, &ev, H_CURR) != 0)
1398 /* start from the oldest */
1399 if (history(h, &ev, H_LAST) != 0)
1400 return NULL; /* error */
1402 /* look forwards for event matching specified offset */
1403 if (history(h, &ev, H_NEXT_EVDATA, num, &she.data))
1408 /* restore pointer to where it was */
1409 (void)history(h, &ev, H_SET, curr_num);
1416 * add the line to history table
1419 add_history(const char *line)
1426 if (h == NULL || e == NULL)
1429 (void)history(h, &ev, H_ENTER, line);
1430 if (history(h, &ev, H_GETSIZE) == 0)
1431 history_length = ev.num;
1433 return !(history_length > 0); /* return 0 if all is okay */
1438 * remove the specified entry from the history list and return it.
1441 remove_history(int num)
1446 if (h == NULL || e == NULL)
1449 if ((he = el_malloc(sizeof(*he))) == NULL)
1452 if (history(h, &ev, H_DELDATA, num, &he->data) != 0) {
1458 if (history(h, &ev, H_GETSIZE) == 0)
1459 history_length = ev.num;
1466 * replace the line and data of the num-th entry
1469 replace_history_entry(int num, const char *line, histdata_t data)
1475 if (h == NULL || e == NULL)
1478 /* save current position */
1479 if (history(h, &ev, H_CURR) != 0)
1483 /* start from the oldest */
1484 if (history(h, &ev, H_LAST) != 0)
1485 return NULL; /* error */
1487 if ((he = el_malloc(sizeof(*he))) == NULL)
1490 /* look forwards for event matching specified offset */
1491 if (history(h, &ev, H_NEXT_EVDATA, num, &he->data))
1494 he->line = strdup(ev.str);
1495 if (he->line == NULL)
1498 if (history(h, &ev, H_REPLACE, line, data))
1501 /* restore pointer to where it was */
1502 if (history(h, &ev, H_SET, curr_num))
1512 * clear the history list - delete all entries
1519 if (h == NULL || e == NULL)
1522 (void)history(h, &ev, H_CLEAR);
1528 * returns offset of the current history event
1536 if (history(h, &ev, H_CURR) != 0)
1540 (void)history(h, &ev, H_FIRST);
1542 while (ev.num != curr_num && history(h, &ev, H_NEXT) == 0)
1550 * returns current history event or NULL if there is no such event
1553 current_history(void)
1556 return _move_history(H_CURR);
1561 * returns total number of bytes history events' data are using
1564 history_total_bytes(void)
1570 if (history(h, &ev, H_CURR) != 0)
1574 (void)history(h, &ev, H_FIRST);
1577 size += strlen(ev.str) * sizeof(*ev.str);
1578 while (history(h, &ev, H_NEXT) == 0);
1580 /* get to the same position as before */
1581 history(h, &ev, H_PREV_EVENT, curr_num);
1588 * sets the position in the history list to ``pos''
1591 history_set_pos(int pos)
1596 if (pos >= history_length || pos < 0)
1599 (void)history(h, &ev, H_CURR);
1603 * use H_DELDATA to set to nth history (without delete) by passing
1606 if (history(h, &ev, H_DELDATA, pos, (void **)-1)) {
1607 (void)history(h, &ev, H_SET, curr_num);
1615 * returns previous event in history and shifts pointer accordingly
1618 previous_history(void)
1621 return _move_history(H_PREV);
1626 * returns next event in history and shifts pointer accordingly
1632 return _move_history(H_NEXT);
1637 * searches for first history event containing the str
1640 history_search(const char *str, int direction)
1646 if (history(h, &ev, H_CURR) != 0)
1651 if ((strp = strstr(ev.str, str)) != NULL)
1652 return (int)(strp - ev.str);
1653 if (history(h, &ev, direction < 0 ? H_NEXT:H_PREV) != 0)
1656 (void)history(h, &ev, H_SET, curr_num);
1662 * searches for first history event beginning with str
1665 history_search_prefix(const char *str, int direction)
1669 return (history(h, &ev, direction < 0 ?
1670 H_PREV_STR : H_NEXT_STR, str));
1675 * search for event in history containing str, starting at offset
1676 * abs(pos); continue backward, if pos<0, forward otherwise
1680 history_search_pos(const char *str,
1681 int direction __attribute__((__unused__)), int pos)
1686 off = (pos > 0) ? pos : -pos;
1687 pos = (pos > 0) ? 1 : -1;
1689 if (history(h, &ev, H_CURR) != 0)
1693 if (history_set_pos(off) != 0 || history(h, &ev, H_CURR) != 0)
1697 if (strstr(ev.str, str))
1699 if (history(h, &ev, (pos < 0) ? H_PREV : H_NEXT) != 0)
1703 /* set "current" pointer back to previous state */
1704 (void)history(h, &ev,
1705 pos < 0 ? H_NEXT_EVENT : H_PREV_EVENT, curr_num);
1711 /********************************/
1712 /* completion functions */
1715 tilde_expand(char *name)
1717 return fn_tilde_expand(name);
1721 filename_completion_function(const char *name, int state)
1723 return fn_filename_completion_function(name, state);
1727 * a completion generator for usernames; returns _first_ username
1728 * which starts with supplied text
1729 * text contains a partial username preceded by random character
1730 * (usually '~'); state resets search from start (??? should we do that anyway)
1731 * it's the caller's responsibility to free the returned value
1734 username_completion_function(const char *text, int state)
1736 #if defined(HAVE_GETPW_R_POSIX) || defined(HAVE_GETPW_R_DRAFT)
1737 struct passwd pwres;
1740 struct passwd *pass = NULL;
1742 if (text[0] == '\0')
1752 #if defined(HAVE_GETPW_R_POSIX) || defined(HAVE_GETPW_R_DRAFT)
1753 getpwent_r(&pwres, pwbuf, sizeof(pwbuf), &pass) == 0 && pass != NULL
1755 (pass = getpwent()) != NULL
1757 && text[0] == pass->pw_name[0]
1758 && strcmp(text, pass->pw_name) == 0)
1765 return strdup(pass->pw_name);
1770 * el-compatible wrapper to send TSTP on ^Z
1773 static unsigned char
1774 _el_rl_tstp(EditLine *el __attribute__((__unused__)), int ch __attribute__((__unused__)))
1776 (void)kill(0, SIGTSTP);
1781 * Display list of strings in columnar format on readline's output stream.
1782 * 'matches' is list of strings, 'len' is number of strings in 'matches',
1783 * 'max' is maximum length of string in 'matches'.
1786 rl_display_match_list(char **matches, int len, int max)
1789 fn_display_match_list(e, matches, (size_t)len, (size_t)max);
1794 _rl_completion_append_character_function(const char *dummy
1795 __attribute__((__unused__)))
1798 buf[0] = (char)rl_completion_append_character;
1805 * complete word at current point
1809 rl_complete(int ignore __attribute__((__unused__)), int invoking_key)
1812 static ct_buffer_t wbreak_conv, sprefix_conv;
1816 if (h == NULL || e == NULL)
1819 if (rl_inhibit_completion) {
1821 arr[0] = (char)invoking_key;
1823 el_insertstr(e, arr);
1827 if (rl_completion_word_break_hook != NULL)
1828 breakchars = (*rl_completion_word_break_hook)();
1830 breakchars = rl_basic_word_break_characters;
1832 /* Just look at how many global variables modify this operation! */
1833 return fn_complete(e,
1834 (CPFunction *)rl_completion_entry_function,
1835 rl_attempted_completion_function,
1836 ct_decode_string(rl_basic_word_break_characters, &wbreak_conv),
1837 ct_decode_string(breakchars, &sprefix_conv),
1838 _rl_completion_append_character_function,
1839 (size_t)rl_completion_query_items,
1840 &rl_completion_type, &rl_attempted_completion_over,
1841 &rl_point, &rl_end, NULL, NULL, NULL);
1848 static unsigned char
1849 _el_rl_complete(EditLine *el __attribute__((__unused__)), int ch)
1851 return (unsigned char)rl_complete(0, ch);
1855 * misc other functions
1859 * bind key c to readline-type function func
1862 rl_bind_key(int c, rl_command_func_t *func)
1866 if (h == NULL || e == NULL)
1869 if (func == rl_insert) {
1870 /* XXX notice there is no range checking of ``c'' */
1871 e->el_map.key[c] = ED_INSERT;
1879 * read one key from input - handles chars pushed back
1880 * to input stream also
1885 char fooarr[2 * sizeof(int)];
1887 if (e == NULL || h == NULL)
1890 return el_getc(e, fooarr);
1895 * reset the terminal
1899 rl_reset_terminal(const char *p __attribute__((__unused__)))
1902 if (h == NULL || e == NULL)
1909 * insert character ``c'' back into input stream, ``count'' times
1912 rl_insert(int count, int c)
1916 if (h == NULL || e == NULL)
1919 /* XXX - int -> char conversion can lose on multichars */
1923 for (; count > 0; count--)
1930 rl_insert_text(const char *text)
1932 if (!text || *text == 0)
1935 if (h == NULL || e == NULL)
1938 if (el_insertstr(e, text) < 0)
1940 return (int)strlen(text);
1945 rl_newline(int count __attribute__((__unused__)),
1946 int c __attribute__((__unused__)))
1949 * Readline-4.0 appears to ignore the args.
1951 return rl_insert(1, '\n');
1955 static unsigned char
1956 rl_bind_wrapper(EditLine *el __attribute__((__unused__)), unsigned char c)
1965 /* If rl_done was set by the above call, deal with it here */
1973 rl_add_defun(const char *name, Function *fun, int c)
1976 if ((size_t)c >= sizeof(map) / sizeof(map[0]) || c < 0)
1978 map[(unsigned char)c] = fun;
1979 el_set(e, EL_ADDFN, name, name, rl_bind_wrapper);
1980 vis(dest, c, VIS_WHITE|VIS_NOSLASH, 0);
1981 el_set(e, EL_BIND, dest, name, NULL);
1986 rl_callback_read_char(void)
1988 int count = 0, done = 0;
1989 const char *buf = el_gets(e, &count);
1992 if (buf == NULL || count-- <= 0)
1994 if (count == 0 && buf[0] == e->el_tty.t_c[TS_IO][C_EOF])
1996 if (buf[count] == '\n' || buf[count] == '\r')
1999 if (done && rl_linefunc != NULL) {
2000 el_set(e, EL_UNBUFFERED, 0);
2002 if ((wbuf = strdup(buf)) != NULL)
2006 (*(void (*)(const char *))rl_linefunc)(wbuf);
2007 el_set(e, EL_UNBUFFERED, 1);
2012 rl_callback_handler_install(const char *prompt, VCPFunction *linefunc)
2017 (void)rl_set_prompt(prompt);
2018 rl_linefunc = linefunc;
2019 el_set(e, EL_UNBUFFERED, 1);
2023 rl_callback_handler_remove(void)
2025 el_set(e, EL_UNBUFFERED, 0);
2033 a[0] = (char)e->el_tty.t_c[TS_IO][C_REPRINT];
2039 rl_get_previous_history(int count, int key)
2051 rl_prep_terminal(int meta_flag __attribute__((__unused__)))
2053 el_set(e, EL_PREP_TERM, 1);
2057 rl_deprep_terminal(void)
2059 el_set(e, EL_PREP_TERM, 0);
2063 rl_read_init_file(const char *s)
2065 return el_source(e, s);
2069 rl_parse_and_bind(const char *line)
2075 tok = tok_init(NULL);
2076 tok_str(tok, line, &argc, &argv);
2077 argc = el_parse(e, argc, argv);
2079 return argc ? 1 : 0;
2083 rl_variable_bind(const char *var, const char *value)
2086 * The proper return value is undocument, but this is what the
2087 * readline source seems to do.
2089 return el_set(e, EL_BIND, "", var, value, NULL) == -1 ? 1 : 0;
2093 rl_stuff_char(int c)
2099 el_insertstr(e, buf);
2103 _rl_event_read_char(EditLine *el, char *cp)
2106 ssize_t num_read = 0;
2109 while (rl_event_hook) {
2113 #if defined(FIONREAD)
2114 if (ioctl(el->el_infd, FIONREAD, &n) < 0)
2117 num_read = read(el->el_infd, cp, (size_t)1);
2120 #elif defined(F_SETFL) && defined(O_NDELAY)
2121 if ((n = fcntl(el->el_infd, F_GETFL, 0)) < 0)
2123 if (fcntl(el->el_infd, F_SETFL, n|O_NDELAY) < 0)
2125 num_read = read(el->el_infd, cp, 1);
2126 if (fcntl(el->el_infd, F_SETFL, n))
2129 /* not non-blocking, but what you gonna do? */
2130 num_read = read(el->el_infd, cp, 1);
2134 if (num_read < 0 && errno == EAGAIN)
2141 el_set(el, EL_GETCFN, EL_BUILTIN_GETCFN);
2142 return (int)num_read;
2146 _rl_update_pos(void)
2148 const LineInfo *li = el_line(e);
2150 rl_point = (int)(li->cursor - li->buffer);
2151 rl_end = (int)(li->lastchar - li->buffer);
2155 rl_get_screen_size(int *rows, int *cols)
2158 el_get(e, EL_GETTC, "li", rows, (void *)0);
2160 el_get(e, EL_GETTC, "co", cols, (void *)0);
2164 rl_set_screen_size(int rows, int cols)
2167 (void)snprintf(buf, sizeof(buf), "%d", rows);
2168 el_set(e, EL_SETTC, "li", buf, NULL);
2169 (void)snprintf(buf, sizeof(buf), "%d", cols);
2170 el_set(e, EL_SETTC, "co", buf, NULL);
2174 rl_completion_matches(const char *str, rl_compentry_func_t *fun)
2176 size_t len, max, i, j, min;
2177 char **list, *match, *a, *b;
2181 if ((list = el_malloc(max * sizeof(*list))) == NULL)
2184 while ((match = (*fun)(str, (int)(len - 1))) != NULL) {
2185 list[len++] = match;
2189 if ((nl = el_realloc(list, max * sizeof(*nl))) == NULL)
2198 if ((list[0] = strdup(list[1])) == NULL)
2202 qsort(&list[1], len - 1, sizeof(*list),
2203 (int (*)(const void *, const void *)) strcmp);
2205 for (i = 1, a = list[i]; i < len - 1; i++, a = b) {
2207 for (j = 0; a[j] && a[j] == b[j]; j++)
2212 if (min == 0 && *str) {
2213 if ((list[0] = strdup(str)) == NULL)
2216 if ((list[0] = el_malloc((min + 1) * sizeof(*list[0]))) == NULL)
2218 (void)memcpy(list[0], list[1], min);
2219 list[0][min] = '\0';
2229 rl_filename_completion_function (const char *text, int state)
2231 return fn_filename_completion_function(text, state);
2235 rl_forced_update_display(void)
2237 el_set(e, EL_REFRESH);
2241 _rl_abort_internal(void)
2249 _rl_qsort_string_compare(char **s1, char **s2)
2251 return strcoll(*s1, *s2);
2255 history_get_history_state(void)
2259 if ((hs = el_malloc(sizeof(*hs))) == NULL)
2261 hs->length = history_length;
2267 rl_kill_text(int from __attribute__((__unused__)),
2268 int to __attribute__((__unused__)))
2274 rl_make_bare_keymap(void)
2287 rl_set_keymap(Keymap k __attribute__((__unused__)))
2293 rl_generic_bind(int type __attribute__((__unused__)),
2294 const char * keyseq __attribute__((__unused__)),
2295 const char * data __attribute__((__unused__)),
2296 Keymap k __attribute__((__unused__)))
2303 rl_bind_key_in_map(int key __attribute__((__unused__)),
2304 rl_command_func_t *fun __attribute__((__unused__)),
2305 Keymap k __attribute__((__unused__)))
2310 /* unsupported, but needed by python */
2312 rl_cleanup_after_signal(void)
2317 rl_on_new_line(void)
2323 rl_free_line_state(void)