1 /* $NetBSD: readline.c,v 1.113 2014/10/18 08:33:23 snj 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.113 2014/10/18 08:33:23 snj 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);
367 /* read settings from configuration file */
371 * Unfortunately, some applications really do use rl_point
372 * and rl_line_buffer directly.
374 _resize_fun(e, &rl_line_buffer);
378 (*rl_startup_hook)(NULL, 0);
385 * read one line from input stream and return it, chomping
386 * trailing newline (if there is any)
389 readline(const char *p)
392 const char * volatile prompt = p;
396 static int used_event_hook;
398 if (e == NULL || h == NULL)
403 (void)setjmp(topbuf);
405 /* update prompt accordingly to what has been passed */
406 if (rl_set_prompt(prompt) == -1)
409 if (rl_pre_input_hook)
410 (*rl_pre_input_hook)(NULL, 0);
412 if (rl_event_hook && !(e->el_flags&NO_TTY)) {
413 el_set(e, EL_GETCFN, _rl_event_read_char);
417 if (!rl_event_hook && used_event_hook) {
418 el_set(e, EL_GETCFN, EL_BUILTIN_GETCFN);
422 rl_already_prompted = 0;
424 /* get one line from input stream */
425 ret = el_gets(e, &count);
427 if (ret && count > 0) {
434 if (buf[lastidx] == '\n')
439 history(h, &ev, H_GETSIZE);
440 history_length = ev.num;
450 * is normally called before application starts to use
451 * history expansion functions
456 if (h == NULL || e == NULL)
462 * substitute ``what'' with ``with'', returning resulting string; if
463 * globally == 1, substitutes all occurrences of what, otherwise only the
467 _rl_compat_sub(const char *str, const char *what, const char *with,
472 size_t len, with_len, what_len;
475 with_len = strlen(with);
476 what_len = strlen(what);
478 /* calculate length we need for result */
481 if (*s == *what && !strncmp(s, what, what_len)) {
482 len += with_len - what_len;
489 r = result = el_malloc((len + 1) * sizeof(*r));
494 if (*s == *what && !strncmp(s, what, what_len)) {
495 (void)strncpy(r, with, with_len);
509 static char *last_search_pat; /* last !?pat[?] search pattern */
510 static char *last_search_match; /* last !?pat[?] that matched */
513 get_history_event(const char *cmd, int *cindex, int qchar)
515 int idx, sign, sub, num, begin, ret;
522 if (cmd[idx++] != history_expansion_char)
525 /* find out which event to take */
526 if (cmd[idx] == history_expansion_char || cmd[idx] == '\0') {
527 if (history(h, &ev, H_FIRST) != 0)
529 *cindex = cmd[idx]? (idx + 1):idx;
533 if (cmd[idx] == '-') {
538 if ('0' <= cmd[idx] && cmd[idx] <= '9') {
542 while (cmd[idx] && '0' <= cmd[idx] && cmd[idx] <= '9') {
543 num = num * 10 + cmd[idx] - '0';
547 num = history_length - num + 1;
549 if (!(rl_he = history_get(num)))
556 if (cmd[idx] == '?') {
562 if (cmd[idx] == '\n')
564 if (sub && cmd[idx] == '?')
566 if (!sub && (cmd[idx] == ':' || cmd[idx] == ' '
567 || cmd[idx] == '\t' || cmd[idx] == qchar))
571 len = (size_t)idx - (size_t)begin;
572 if (sub && cmd[idx] == '?')
574 if (sub && len == 0 && last_search_pat && *last_search_pat)
575 pat = last_search_pat;
579 if ((pat = el_malloc((len + 1) * sizeof(*pat))) == NULL)
581 (void)strncpy(pat, cmd + begin, len);
585 if (history(h, &ev, H_CURR) != 0) {
586 if (pat != last_search_pat)
593 if (pat != last_search_pat) {
595 el_free(last_search_pat);
596 last_search_pat = pat;
598 ret = history_search(pat, -1);
600 ret = history_search_prefix(pat, -1);
603 /* restore to end of list on failed search */
604 history(h, &ev, H_FIRST);
605 (void)fprintf(rl_outstream, "%s: Event not found\n", pat);
606 if (pat != last_search_pat)
612 if (last_search_match && last_search_match != pat)
613 el_free(last_search_match);
614 last_search_match = pat;
617 if (pat != last_search_pat)
620 if (history(h, &ev, H_CURR) != 0)
625 /* roll back to original position */
626 (void)history(h, &ev, H_SET, num);
632 * the real function doing history expansion - takes as argument command
633 * to do and data upon which the command should be executed
634 * does expansion the way I've understood readline documentation
636 * returns 0 if data was not modified, 1 if it was and 2 if the string
637 * should be only printed and not executed; in case of error,
638 * returns -1 and *result points to NULL
639 * it's the caller's responsibility to free() the string returned in *result
642 _history_expand_command(const char *command, size_t offs, size_t cmdlen,
645 char *tmp, *search = NULL, *aptr;
646 const char *ptr, *cmd;
647 static char *from = NULL, *to = NULL;
648 int start, end, idx, has_mods = 0;
649 int p_on = 0, g_on = 0;
655 /* First get event specifier */
658 if (strchr(":^*$", command[offs + 1])) {
661 * "!:" is shorthand for "!!:".
662 * "!^", "!*" and "!$" are shorthand for
663 * "!!:^", "!!:*" and "!!:$" respectively.
665 str[0] = str[1] = '!';
667 ptr = get_history_event(str, &idx, 0);
668 idx = (command[offs + 1] == ':')? 1:0;
671 if (command[offs + 1] == '#') {
672 /* use command so far */
673 if ((aptr = el_malloc((offs + 1) * sizeof(*aptr)))
676 (void)strncpy(aptr, command, offs);
682 qchar = (offs > 0 && command[offs - 1] == '"')? '"':0;
683 ptr = get_history_event(command + offs, &idx, qchar);
685 has_mods = command[offs + (size_t)idx] == ':';
688 if (ptr == NULL && aptr == NULL)
692 *result = strdup(aptr ? aptr : ptr);
700 cmd = command + offs + idx + 1;
702 /* Now parse any word designators */
704 if (*cmd == '%') /* last word matched by ?pat? */
705 tmp = strdup(last_search_match? last_search_match:"");
706 else if (strchr("^*$-0123456789", *cmd)) {
709 start = end = 1, cmd++;
710 else if (*cmd == '$')
712 else if (*cmd == '*')
714 else if (*cmd == '-' || isdigit((unsigned char) *cmd)) {
716 while (*cmd && '0' <= *cmd && *cmd <= '9')
717 start = start * 10 + *cmd++ - '0';
720 if (isdigit((unsigned char) cmd[1])) {
723 while (*cmd && '0' <= *cmd && *cmd <= '9')
724 end = end * 10 + *cmd++ - '0';
725 } else if (cmd[1] == '$') {
732 } else if (*cmd == '*')
737 tmp = history_arg_extract(start, end, aptr? aptr:ptr);
739 (void)fprintf(rl_outstream, "%s: Bad word specifier",
740 command + offs + idx);
746 tmp = strdup(aptr? aptr:ptr);
751 if (*cmd == '\0' || ((size_t)(cmd - (command + offs)) >= cmdlen)) {
756 for (; *cmd; cmd++) {
759 else if (*cmd == 'h') { /* remove trailing path */
760 if ((aptr = strrchr(tmp, '/')) != NULL)
762 } else if (*cmd == 't') { /* remove leading path */
763 if ((aptr = strrchr(tmp, '/')) != NULL) {
764 aptr = strdup(aptr + 1);
768 } else if (*cmd == 'r') { /* remove trailing suffix */
769 if ((aptr = strrchr(tmp, '.')) != NULL)
771 } else if (*cmd == 'e') { /* remove all but suffix */
772 if ((aptr = strrchr(tmp, '.')) != NULL) {
777 } else if (*cmd == 'p') /* print only */
779 else if (*cmd == 'g')
781 else if (*cmd == 's' || *cmd == '&') {
782 char *what, *with, delim;
783 size_t len, from_len;
786 if (*cmd == '&' && (from == NULL || to == NULL))
788 else if (*cmd == 's') {
789 delim = *(++cmd), cmd++;
791 what = el_realloc(from, size * sizeof(*what));
798 for (; *cmd && *cmd != delim; cmd++) {
799 if (*cmd == '\\' && cmd[1] == delim)
803 nwhat = el_realloc(what,
820 from = strdup(search);
831 cmd++; /* shift after delim */
836 with = el_realloc(to, size * sizeof(*with));
843 from_len = strlen(from);
844 for (; *cmd && *cmd != delim; cmd++) {
845 if (len + from_len + 1 >= size) {
847 size += from_len + 1;
848 nwith = el_realloc(with,
849 size * sizeof(*nwith));
859 (void)strcpy(&with[len], from);
864 && (*(cmd + 1) == delim
865 || *(cmd + 1) == '&'))
873 aptr = _rl_compat_sub(tmp, from, to, g_on);
887 * csh-style history expansion
890 history_expand(char *str, char **output)
896 if (h == NULL || e == NULL)
899 if (history_expansion_char == 0) {
900 *output = strdup(str);
905 if (str[0] == history_subst_char) {
906 /* ^foo^foo2^ is equivalent to !!:s^foo^foo2^ */
907 *output = el_malloc((strlen(str) + 4 + 1) * sizeof(**output));
910 (*output)[0] = (*output)[1] = history_expansion_char;
913 (void)strcpy((*output) + 4, str);
916 *output = strdup(str);
921 #define ADD_STRING(what, len, fr) \
923 if (idx + len + 1 > size) { \
924 char *nresult = el_realloc(result, \
925 (size += len + 1) * sizeof(*nresult)); \
926 if (nresult == NULL) { \
928 if (/*CONSTCOND*/fr) \
934 (void)strncpy(&result[idx], what, len); \
936 result[idx] = '\0'; \
942 for (i = 0; str[i];) {
943 int qchar, loop_again;
944 size_t len, start, j;
950 for (; str[j]; j++) {
951 if (str[j] == '\\' &&
952 str[j + 1] == history_expansion_char) {
953 (void)strcpy(&str[j], &str[j + 1]);
957 if (isspace((unsigned char) str[j])
961 if (str[j] == history_expansion_char
962 && !strchr(history_no_expand_chars, str[j + 1])
963 && (!history_inhibit_expansion_function ||
964 (*history_inhibit_expansion_function)(str,
969 if (str[j] && loop_again) {
971 qchar = (j > 0 && str[j - 1] == '"' )? '"':0;
973 if (str[j] == history_expansion_char)
979 ADD_STRING(&str[start], len, 0);
981 if (str[i] == '\0' || str[i] != history_expansion_char) {
983 ADD_STRING(&str[i], len, 0);
990 ret = _history_expand_command (str, i, (j - i), &tmp);
991 if (ret > 0 && tmp) {
993 ADD_STRING(tmp, len, 1);
1002 /* ret is 2 for "print only" option */
1004 add_history(result);
1006 /* gdb 4.11 has been shipped with readline, where */
1007 /* history_expand() returned -1 when the line */
1008 /* should not be executed; in readline 2.1+ */
1009 /* it should return 2 in such a case */
1020 * Return a string consisting of arguments of "str" from "start" to "end".
1023 history_arg_extract(int start, int end, const char *str)
1026 char **arr, *result = NULL;
1028 arr = history_tokenize(str);
1031 if (arr && *arr == NULL)
1034 for (max = 0; arr[max]; max++)
1043 end = (int)max + end + 1;
1047 if (start < 0 || end < 0 || (size_t)start > max ||
1048 (size_t)end > max || start > end)
1051 for (i = (size_t)start, len = 0; i <= (size_t)end; i++)
1052 len += strlen(arr[i]) + 1;
1054 result = el_malloc(len * sizeof(*result));
1058 for (i = (size_t)start, len = 0; i <= (size_t)end; i++) {
1059 (void)strcpy(result + len, arr[i]);
1060 len += strlen(arr[i]);
1061 if (i < (size_t)end)
1062 result[len++] = ' ';
1067 for (i = 0; arr[i]; i++)
1075 * Parse the string into individual tokens,
1076 * similar to how shell would do it.
1079 history_tokenize(const char *str)
1081 int size = 1, idx = 0, i, start;
1083 char **result = NULL, *temp, delim = '\0';
1085 for (i = 0; str[i];) {
1086 while (isspace((unsigned char) str[i]))
1090 if (str[i] == '\\') {
1091 if (str[i+1] != '\0')
1093 } else if (str[i] == delim)
1096 (isspace((unsigned char) str[i]) ||
1097 strchr("()<>;&|$", str[i])))
1099 else if (!delim && strchr("'`\"", str[i]))
1105 if (idx + 2 >= size) {
1108 nresult = el_realloc(result, (size_t)size * sizeof(*nresult));
1109 if (nresult == NULL) {
1115 len = (size_t)i - (size_t)start;
1116 temp = el_malloc((size_t)(len + 1) * sizeof(*temp));
1118 for (i = 0; i < idx; i++)
1123 (void)strncpy(temp, &str[start], len);
1125 result[idx++] = temp;
1135 * limit size of history record to ``max'' events
1138 stifle_history(int max)
1142 if (h == NULL || e == NULL)
1145 if (history(h, &ev, H_SETSIZE, max) == 0)
1146 max_input_history = max;
1151 * "unlimit" size of history - set the limit to maximum allowed int value
1154 unstifle_history(void)
1159 history(h, &ev, H_SETSIZE, INT_MAX);
1160 omax = max_input_history;
1161 max_input_history = INT_MAX;
1162 return omax; /* some value _must_ be returned */
1167 history_is_stifled(void)
1170 /* cannot return true answer */
1171 return max_input_history != INT_MAX;
1174 static const char _history_tmp_template[] = "/tmp/.historyXXXXXX";
1177 history_truncate_file (const char *filename, int nlines)
1181 char template[sizeof(_history_tmp_template)];
1189 if (filename == NULL && (filename = _default_history_file()) == NULL)
1191 if ((fp = fopen(filename, "r+")) == NULL)
1193 strcpy(template, _history_tmp_template);
1194 if ((fd = mkstemp(template)) == -1) {
1199 if ((tp = fdopen(fd, "r+")) == NULL) {
1206 if (fread(buf, sizeof(buf), (size_t)1, fp) != 1) {
1211 if (fseeko(fp, (off_t)sizeof(buf) * count, SEEK_SET) ==
1216 left = (ssize_t)fread(buf, (size_t)1, sizeof(buf), fp);
1224 } else if (fwrite(buf, (size_t)left, (size_t)1, tp)
1232 if (fwrite(buf, sizeof(buf), (size_t)1, tp) != 1) {
1240 cp = buf + left - 1;
1244 while (--cp >= buf) {
1246 if (--nlines == 0) {
1247 if (++cp >= buf + sizeof(buf)) {
1255 if (nlines <= 0 || count == 0)
1258 if (fseeko(tp, (off_t)sizeof(buf) * count, SEEK_SET) < 0) {
1262 if (fread(buf, sizeof(buf), (size_t)1, tp) != 1) {
1270 cp = buf + sizeof(buf);
1273 if (ret || nlines > 0)
1276 if (fseeko(fp, (off_t)0, SEEK_SET) == (off_t)-1) {
1281 if (fseeko(tp, (off_t)sizeof(buf) * count + (cp - buf), SEEK_SET) ==
1288 if ((left = (ssize_t)fread(buf, (size_t)1, sizeof(buf), tp)) == 0) {
1293 if (fwrite(buf, (size_t)left, (size_t)1, fp) != 1) {
1299 if((off = ftello(fp)) > 0)
1300 (void)ftruncate(fileno(fp), off);
1313 * read history from a file given
1316 read_history(const char *filename)
1320 if (h == NULL || e == NULL)
1322 if (filename == NULL && (filename = _default_history_file()) == NULL)
1324 return history(h, &ev, H_LOAD, filename) == -1 ?
1325 (errno ? errno : EINVAL) : 0;
1330 * write history to a file given
1333 write_history(const char *filename)
1337 if (h == NULL || e == NULL)
1339 if (filename == NULL && (filename = _default_history_file()) == NULL)
1341 return history(h, &ev, H_SAVE, filename) == -1 ?
1342 (errno ? errno : EINVAL) : 0;
1347 * returns history ``num''th event
1349 * returned pointer points to static variable
1352 history_get(int num)
1354 static HIST_ENTRY she;
1358 if (h == NULL || e == NULL)
1361 /* save current position */
1362 if (history(h, &ev, H_CURR) != 0)
1366 /* start from the oldest */
1367 if (history(h, &ev, H_LAST) != 0)
1368 return NULL; /* error */
1370 /* look forwards for event matching specified offset */
1371 if (history(h, &ev, H_NEXT_EVDATA, num, &she.data))
1376 /* restore pointer to where it was */
1377 (void)history(h, &ev, H_SET, curr_num);
1384 * add the line to history table
1387 add_history(const char *line)
1394 if (h == NULL || e == NULL)
1397 (void)history(h, &ev, H_ENTER, line);
1398 if (history(h, &ev, H_GETSIZE) == 0)
1399 history_length = ev.num;
1401 return !(history_length > 0); /* return 0 if all is okay */
1406 * remove the specified entry from the history list and return it.
1409 remove_history(int num)
1414 if (h == NULL || e == NULL)
1417 if ((he = el_malloc(sizeof(*he))) == NULL)
1420 if (history(h, &ev, H_DELDATA, num, &he->data) != 0) {
1426 if (history(h, &ev, H_GETSIZE) == 0)
1427 history_length = ev.num;
1434 * replace the line and data of the num-th entry
1437 replace_history_entry(int num, const char *line, histdata_t data)
1443 if (h == NULL || e == NULL)
1446 /* save current position */
1447 if (history(h, &ev, H_CURR) != 0)
1451 /* start from the oldest */
1452 if (history(h, &ev, H_LAST) != 0)
1453 return NULL; /* error */
1455 if ((he = el_malloc(sizeof(*he))) == NULL)
1458 /* look forwards for event matching specified offset */
1459 if (history(h, &ev, H_NEXT_EVDATA, num, &he->data))
1462 he->line = strdup(ev.str);
1463 if (he->line == NULL)
1466 if (history(h, &ev, H_REPLACE, line, data))
1469 /* restore pointer to where it was */
1470 if (history(h, &ev, H_SET, curr_num))
1480 * clear the history list - delete all entries
1487 if (h == NULL || e == NULL)
1490 (void)history(h, &ev, H_CLEAR);
1496 * returns offset of the current history event
1504 if (history(h, &ev, H_CURR) != 0)
1508 (void)history(h, &ev, H_FIRST);
1510 while (ev.num != curr_num && history(h, &ev, H_NEXT) == 0)
1518 * returns current history event or NULL if there is no such event
1521 current_history(void)
1524 return _move_history(H_CURR);
1529 * returns total number of bytes history events' data are using
1532 history_total_bytes(void)
1538 if (history(h, &ev, H_CURR) != 0)
1542 (void)history(h, &ev, H_FIRST);
1545 size += strlen(ev.str) * sizeof(*ev.str);
1546 while (history(h, &ev, H_NEXT) == 0);
1548 /* get to the same position as before */
1549 history(h, &ev, H_PREV_EVENT, curr_num);
1556 * sets the position in the history list to ``pos''
1559 history_set_pos(int pos)
1564 if (pos >= history_length || pos < 0)
1567 (void)history(h, &ev, H_CURR);
1571 * use H_DELDATA to set to nth history (without delete) by passing
1574 if (history(h, &ev, H_DELDATA, pos, (void **)-1)) {
1575 (void)history(h, &ev, H_SET, curr_num);
1583 * returns previous event in history and shifts pointer accordingly
1586 previous_history(void)
1589 return _move_history(H_PREV);
1594 * returns next event in history and shifts pointer accordingly
1600 return _move_history(H_NEXT);
1605 * searches for first history event containing the str
1608 history_search(const char *str, int direction)
1614 if (history(h, &ev, H_CURR) != 0)
1619 if ((strp = strstr(ev.str, str)) != NULL)
1620 return (int)(strp - ev.str);
1621 if (history(h, &ev, direction < 0 ? H_NEXT:H_PREV) != 0)
1624 (void)history(h, &ev, H_SET, curr_num);
1630 * searches for first history event beginning with str
1633 history_search_prefix(const char *str, int direction)
1637 return (history(h, &ev, direction < 0 ?
1638 H_PREV_STR : H_NEXT_STR, str));
1643 * search for event in history containing str, starting at offset
1644 * abs(pos); continue backward, if pos<0, forward otherwise
1648 history_search_pos(const char *str,
1649 int direction __attribute__((__unused__)), int pos)
1654 off = (pos > 0) ? pos : -pos;
1655 pos = (pos > 0) ? 1 : -1;
1657 if (history(h, &ev, H_CURR) != 0)
1661 if (history_set_pos(off) != 0 || history(h, &ev, H_CURR) != 0)
1665 if (strstr(ev.str, str))
1667 if (history(h, &ev, (pos < 0) ? H_PREV : H_NEXT) != 0)
1671 /* set "current" pointer back to previous state */
1672 (void)history(h, &ev,
1673 pos < 0 ? H_NEXT_EVENT : H_PREV_EVENT, curr_num);
1679 /********************************/
1680 /* completion functions */
1683 tilde_expand(char *name)
1685 return fn_tilde_expand(name);
1689 filename_completion_function(const char *name, int state)
1691 return fn_filename_completion_function(name, state);
1695 * a completion generator for usernames; returns _first_ username
1696 * which starts with supplied text
1697 * text contains a partial username preceded by random character
1698 * (usually '~'); state resets search from start (??? should we do that anyway)
1699 * it's the caller's responsibility to free the returned value
1702 username_completion_function(const char *text, int state)
1704 #if defined(HAVE_GETPW_R_POSIX) || defined(HAVE_GETPW_R_DRAFT)
1705 struct passwd pwres;
1708 struct passwd *pass = NULL;
1710 if (text[0] == '\0')
1720 #if defined(HAVE_GETPW_R_POSIX) || defined(HAVE_GETPW_R_DRAFT)
1721 getpwent_r(&pwres, pwbuf, sizeof(pwbuf), &pass) == 0 && pass != NULL
1723 (pass = getpwent()) != NULL
1725 && text[0] == pass->pw_name[0]
1726 && strcmp(text, pass->pw_name) == 0)
1733 return strdup(pass->pw_name);
1738 * el-compatible wrapper to send TSTP on ^Z
1741 static unsigned char
1742 _el_rl_tstp(EditLine *el __attribute__((__unused__)), int ch __attribute__((__unused__)))
1744 (void)kill(0, SIGTSTP);
1749 * Display list of strings in columnar format on readline's output stream.
1750 * 'matches' is list of strings, 'len' is number of strings in 'matches',
1751 * 'max' is maximum length of string in 'matches'.
1754 rl_display_match_list(char **matches, int len, int max)
1757 fn_display_match_list(e, matches, (size_t)len, (size_t)max);
1762 _rl_completion_append_character_function(const char *dummy
1763 __attribute__((__unused__)))
1766 buf[0] = (char)rl_completion_append_character;
1773 * complete word at current point
1777 rl_complete(int ignore __attribute__((__unused__)), int invoking_key)
1780 static ct_buffer_t wbreak_conv, sprefix_conv;
1784 if (h == NULL || e == NULL)
1787 if (rl_inhibit_completion) {
1789 arr[0] = (char)invoking_key;
1791 el_insertstr(e, arr);
1795 if (rl_completion_word_break_hook != NULL)
1796 breakchars = (*rl_completion_word_break_hook)();
1798 breakchars = rl_basic_word_break_characters;
1800 /* Just look at how many global variables modify this operation! */
1801 return fn_complete(e,
1802 (CPFunction *)rl_completion_entry_function,
1803 rl_attempted_completion_function,
1804 ct_decode_string(rl_basic_word_break_characters, &wbreak_conv),
1805 ct_decode_string(breakchars, &sprefix_conv),
1806 _rl_completion_append_character_function,
1807 (size_t)rl_completion_query_items,
1808 &rl_completion_type, &rl_attempted_completion_over,
1809 &rl_point, &rl_end, NULL, NULL, NULL);
1816 static unsigned char
1817 _el_rl_complete(EditLine *el __attribute__((__unused__)), int ch)
1819 return (unsigned char)rl_complete(0, ch);
1823 * misc other functions
1827 * bind key c to readline-type function func
1830 rl_bind_key(int c, rl_command_func_t *func)
1834 if (h == NULL || e == NULL)
1837 if (func == rl_insert) {
1838 /* XXX notice there is no range checking of ``c'' */
1839 e->el_map.key[c] = ED_INSERT;
1847 * read one key from input - handles chars pushed back
1848 * to input stream also
1853 char fooarr[2 * sizeof(int)];
1855 if (e == NULL || h == NULL)
1858 return el_getc(e, fooarr);
1863 * reset the terminal
1867 rl_reset_terminal(const char *p __attribute__((__unused__)))
1870 if (h == NULL || e == NULL)
1877 * insert character ``c'' back into input stream, ``count'' times
1880 rl_insert(int count, int c)
1884 if (h == NULL || e == NULL)
1887 /* XXX - int -> char conversion can lose on multichars */
1891 for (; count > 0; count--)
1898 rl_insert_text(const char *text)
1900 if (!text || *text == 0)
1903 if (h == NULL || e == NULL)
1906 if (el_insertstr(e, text) < 0)
1908 return (int)strlen(text);
1913 rl_newline(int count __attribute__((__unused__)),
1914 int c __attribute__((__unused__)))
1917 * Readline-4.0 appears to ignore the args.
1919 return rl_insert(1, '\n');
1923 static unsigned char
1924 rl_bind_wrapper(EditLine *el __attribute__((__unused__)), unsigned char c)
1933 /* If rl_done was set by the above call, deal with it here */
1941 rl_add_defun(const char *name, Function *fun, int c)
1944 if ((size_t)c >= sizeof(map) / sizeof(map[0]) || c < 0)
1946 map[(unsigned char)c] = fun;
1947 el_set(e, EL_ADDFN, name, name, rl_bind_wrapper);
1948 vis(dest, c, VIS_WHITE|VIS_NOSLASH, 0);
1949 el_set(e, EL_BIND, dest, name, NULL);
1954 rl_callback_read_char(void)
1956 int count = 0, done = 0;
1957 const char *buf = el_gets(e, &count);
1960 if (buf == NULL || count-- <= 0)
1962 if (count == 0 && buf[0] == e->el_tty.t_c[TS_IO][C_EOF])
1964 if (buf[count] == '\n' || buf[count] == '\r')
1967 if (done && rl_linefunc != NULL) {
1968 el_set(e, EL_UNBUFFERED, 0);
1970 if ((wbuf = strdup(buf)) != NULL)
1974 (*(void (*)(const char *))rl_linefunc)(wbuf);
1975 el_set(e, EL_UNBUFFERED, 1);
1980 rl_callback_handler_install(const char *prompt, VCPFunction *linefunc)
1985 (void)rl_set_prompt(prompt);
1986 rl_linefunc = linefunc;
1987 el_set(e, EL_UNBUFFERED, 1);
1991 rl_callback_handler_remove(void)
1993 el_set(e, EL_UNBUFFERED, 0);
2001 a[0] = (char)e->el_tty.t_c[TS_IO][C_REPRINT];
2007 rl_get_previous_history(int count, int key)
2019 rl_prep_terminal(int meta_flag __attribute__((__unused__)))
2021 el_set(e, EL_PREP_TERM, 1);
2025 rl_deprep_terminal(void)
2027 el_set(e, EL_PREP_TERM, 0);
2031 rl_read_init_file(const char *s)
2033 return el_source(e, s);
2037 rl_parse_and_bind(const char *line)
2043 tok = tok_init(NULL);
2044 tok_str(tok, line, &argc, &argv);
2045 argc = el_parse(e, argc, argv);
2047 return argc ? 1 : 0;
2051 rl_variable_bind(const char *var, const char *value)
2054 * The proper return value is undocument, but this is what the
2055 * readline source seems to do.
2057 return el_set(e, EL_BIND, "", var, value, NULL) == -1 ? 1 : 0;
2061 rl_stuff_char(int c)
2067 el_insertstr(e, buf);
2071 _rl_event_read_char(EditLine *el, char *cp)
2074 ssize_t num_read = 0;
2077 while (rl_event_hook) {
2081 #if defined(FIONREAD)
2082 if (ioctl(el->el_infd, FIONREAD, &n) < 0)
2085 num_read = read(el->el_infd, cp, (size_t)1);
2088 #elif defined(F_SETFL) && defined(O_NDELAY)
2089 if ((n = fcntl(el->el_infd, F_GETFL, 0)) < 0)
2091 if (fcntl(el->el_infd, F_SETFL, n|O_NDELAY) < 0)
2093 num_read = read(el->el_infd, cp, 1);
2094 if (fcntl(el->el_infd, F_SETFL, n))
2097 /* not non-blocking, but what you gonna do? */
2098 num_read = read(el->el_infd, cp, 1);
2102 if (num_read < 0 && errno == EAGAIN)
2109 el_set(el, EL_GETCFN, EL_BUILTIN_GETCFN);
2110 return (int)num_read;
2114 _rl_update_pos(void)
2116 const LineInfo *li = el_line(e);
2118 rl_point = (int)(li->cursor - li->buffer);
2119 rl_end = (int)(li->lastchar - li->buffer);
2123 rl_get_screen_size(int *rows, int *cols)
2126 el_get(e, EL_GETTC, "li", rows, (void *)0);
2128 el_get(e, EL_GETTC, "co", cols, (void *)0);
2132 rl_set_screen_size(int rows, int cols)
2135 (void)snprintf(buf, sizeof(buf), "%d", rows);
2136 el_set(e, EL_SETTC, "li", buf, NULL);
2137 (void)snprintf(buf, sizeof(buf), "%d", cols);
2138 el_set(e, EL_SETTC, "co", buf, NULL);
2142 rl_completion_matches(const char *str, rl_compentry_func_t *fun)
2144 size_t len, max, i, j, min;
2145 char **list, *match, *a, *b;
2149 if ((list = el_malloc(max * sizeof(*list))) == NULL)
2152 while ((match = (*fun)(str, (int)(len - 1))) != NULL) {
2153 list[len++] = match;
2157 if ((nl = el_realloc(list, max * sizeof(*nl))) == NULL)
2166 if ((list[0] = strdup(list[1])) == NULL)
2170 qsort(&list[1], len - 1, sizeof(*list),
2171 (int (*)(const void *, const void *)) strcmp);
2173 for (i = 1, a = list[i]; i < len - 1; i++, a = b) {
2175 for (j = 0; a[j] && a[j] == b[j]; j++)
2180 if (min == 0 && *str) {
2181 if ((list[0] = strdup(str)) == NULL)
2184 if ((list[0] = el_malloc((min + 1) * sizeof(*list[0]))) == NULL)
2186 (void)memcpy(list[0], list[1], min);
2187 list[0][min] = '\0';
2197 rl_filename_completion_function (const char *text, int state)
2199 return fn_filename_completion_function(text, state);
2203 rl_forced_update_display(void)
2205 el_set(e, EL_REFRESH);
2209 _rl_abort_internal(void)
2217 _rl_qsort_string_compare(char **s1, char **s2)
2219 return strcoll(*s1, *s2);
2223 history_get_history_state(void)
2227 if ((hs = el_malloc(sizeof(*hs))) == NULL)
2229 hs->length = history_length;
2235 rl_kill_text(int from __attribute__((__unused__)),
2236 int to __attribute__((__unused__)))
2242 rl_make_bare_keymap(void)
2255 rl_set_keymap(Keymap k __attribute__((__unused__)))
2261 rl_generic_bind(int type __attribute__((__unused__)),
2262 const char * keyseq __attribute__((__unused__)),
2263 const char * data __attribute__((__unused__)),
2264 Keymap k __attribute__((__unused__)))
2271 rl_bind_key_in_map(int key __attribute__((__unused__)),
2272 rl_command_func_t *fun __attribute__((__unused__)),
2273 Keymap k __attribute__((__unused__)))
2278 /* unsupported, but needed by python */
2280 rl_cleanup_after_signal(void)
2285 rl_on_new_line(void)
2291 rl_free_line_state(void)