1 /* $NetBSD: readline.c,v 1.90 2010/08/04 20:29:18 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.
32 #include <sys/cdefs.h>
33 __RCSID("$NetBSD: readline.c,v 1.90 2010/08/04 20:29:18 christos Exp $");
34 __FBSDID("$FreeBSD$");
36 #include <sys/types.h>
51 #include "readline/readline.h"
54 #include "fcns.h" /* for EL_NUM_FCNS */
56 #include "filecomplete.h"
58 void rl_prep_terminal(int);
59 void rl_deprep_terminal(void);
61 /* for rl_complete() */
64 /* see comment at the #ifdef for sense of this */
65 /* #define GDB_411_HACK */
67 /* readline compatibility stuff - look at readline sources/documentation */
68 /* to see what these variables mean */
69 const char *rl_library_version = "EditLine wrapper";
70 int rl_readline_version = RL_READLINE_VERSION;
71 static char empty[] = { '\0' };
72 static char expand_chars[] = { ' ', '\t', '\n', '=', '(', '\0' };
73 static char break_chars[] = { ' ', '\t', '\n', '"', '\\', '\'', '`', '@', '$',
74 '>', '<', '=', ';', '|', '&', '{', '(', '\0' };
75 char *rl_readline_name = empty;
76 FILE *rl_instream = NULL;
77 FILE *rl_outstream = NULL;
80 char *rl_line_buffer = NULL;
81 VCPFunction *rl_linefunc = NULL;
83 VFunction *rl_event_hook = NULL;
84 KEYMAP_ENTRY_ARRAY emacs_standard_keymap,
88 int history_base = 1; /* probably never subject to change */
89 int history_length = 0;
90 int max_input_history = 0;
91 char history_expansion_char = '!';
92 char history_subst_char = '^';
93 char *history_no_expand_chars = expand_chars;
94 Function *history_inhibit_expansion_function = NULL;
95 char *history_arg_extract(int start, int end, const char *str);
97 int rl_inhibit_completion = 0;
98 int rl_attempted_completion_over = 0;
99 char *rl_basic_word_break_characters = break_chars;
100 char *rl_completer_word_break_characters = NULL;
101 char *rl_completer_quote_characters = NULL;
102 Function *rl_completion_entry_function = NULL;
103 CPPFunction *rl_attempted_completion_function = NULL;
104 Function *rl_pre_input_hook = NULL;
105 Function *rl_startup1_hook = NULL;
106 int (*rl_getc_function)(FILE *) = NULL;
107 char *rl_terminal_name = NULL;
108 int rl_already_prompted = 0;
109 int rl_filename_completion_desired = 0;
110 int rl_ignore_completion_duplicates = 0;
111 int rl_catch_signals = 1;
112 int readline_echoing_p = 1;
113 int _rl_print_completions_horizontally = 0;
114 VFunction *rl_redisplay_function = NULL;
115 Function *rl_startup_hook = NULL;
116 VFunction *rl_completion_display_matches_hook = NULL;
117 VFunction *rl_prep_term_function = (VFunction *)rl_prep_terminal;
118 VFunction *rl_deprep_term_function = (VFunction *)rl_deprep_terminal;
119 KEYMAP_ENTRY_ARRAY emacs_meta_keymap;
122 static ct_buffer_t conv;
126 * The current prompt string.
128 char *rl_prompt = NULL;
130 * This is set to character indicating type of completion being done by
131 * rl_complete_internal(); this is available for application completion
134 int rl_completion_type = 0;
137 * If more than this number of items results from query for possible
138 * completions, we ask user if they are sure to really display the list.
140 int rl_completion_query_items = 100;
143 * List of characters which are word break characters, but should be left
144 * in the parsed text when it is passed to the completion function.
145 * Shell uses this to help determine what kind of completing to do.
147 char *rl_special_prefixes = NULL;
150 * This is the character appended to the completed words if at the end of
151 * the line. Default is ' ' (a space).
153 int rl_completion_append_character = ' ';
155 /* stuff below is used internally by libedit for readline emulation */
157 static TYPE(History) *h = NULL;
158 static EditLine *e = NULL;
159 static Function *map[256];
160 static jmp_buf topbuf;
162 /* internal functions */
163 static unsigned char _el_rl_complete(EditLine *, int);
164 static unsigned char _el_rl_tstp(EditLine *, int);
165 static char *_get_prompt(EditLine *);
166 static int _getc_function(EditLine *, char *);
167 static HIST_ENTRY *_move_history(int);
168 static int _history_expand_command(const char *, size_t, size_t,
170 static char *_rl_compat_sub(const char *, const char *,
172 static int _rl_event_read_char(EditLine *, char *);
173 static void _rl_update_pos(void);
178 _get_prompt(EditLine *el __attribute__((__unused__)))
180 rl_already_prompted = 1;
186 * generic function for moving around history
189 _move_history(int op)
192 static HIST_ENTRY rl_he;
194 if (FUNW(history)(h, &ev, op) != 0)
195 return (HIST_ENTRY *) NULL;
197 rl_he.line = ct_encode_string(ev.str, &conv);
205 * read one key from user defined input function
209 _getc_function(EditLine *el, char *c)
213 i = (*rl_getc_function)(NULL);
220 static const char _dothistory[] = "/.history";
223 _default_history_file(void)
226 static char path[PATH_MAX];
230 if ((p = getpwuid(getuid())) == NULL)
232 strlcpy(path, p->pw_dir, PATH_MAX);
233 strlcat(path, _dothistory, PATH_MAX);
238 * READLINE compatibility stuff
245 rl_set_prompt(const char *prompt)
251 if (rl_prompt != NULL && strcmp(rl_prompt, prompt) == 0)
255 rl_prompt = strdup(prompt);
256 if (rl_prompt == NULL)
259 while ((p = strchr(rl_prompt, RL_PROMPT_END_IGNORE)) != NULL)
260 *p = RL_PROMPT_START_IGNORE;
266 * initialize rl compat stuff
284 rl_outstream = stdout;
287 * See if we don't really want to run the editor
289 if (tcgetattr(fileno(rl_instream), &t) != -1 && (t.c_lflag & ECHO) == 0)
292 e = el_init(rl_readline_name, rl_instream, rl_outstream, stderr);
295 FUN(el,set)(e, EL_EDITMODE, 0);
297 h = FUN(history,init)();
301 FUNW(history)(h, &ev, H_SETSIZE, INT_MAX); /* unlimited */
303 max_input_history = INT_MAX;
304 el_set(e, EL_HIST, history, h);
306 /* setup getc function if valid */
307 if (rl_getc_function)
308 el_set(e, EL_GETCFN, _getc_function);
310 /* for proper prompt printing in readline() */
311 if (rl_set_prompt("") == -1) {
316 el_set(e, EL_PROMPT, _get_prompt, RL_PROMPT_START_IGNORE);
317 el_set(e, EL_SIGNAL, rl_catch_signals);
319 /* set default mode to "emacs"-style and read setting afterwards */
320 /* so this can be overriden */
321 el_set(e, EL_EDITOR, "emacs");
322 if (rl_terminal_name != NULL)
323 el_set(e, EL_TERMINAL, rl_terminal_name);
325 el_get(e, EL_TERMINAL, &rl_terminal_name);
328 * Word completion - this has to go AFTER rebinding keys
331 el_set(e, EL_ADDFN, "rl_complete",
332 "ReadLine compatible completion function",
334 el_set(e, EL_BIND, "^I", "rl_complete", NULL);
337 * Send TSTP when ^Z is pressed.
339 el_set(e, EL_ADDFN, "rl_tstp",
340 "ReadLine compatible suspend function",
342 el_set(e, EL_BIND, "^Z", "rl_tstp", NULL);
344 /* read settings from configuration file */
348 * Unfortunately, some applications really do use rl_point
349 * and rl_line_buffer directly.
352 /* a cheesy way to get rid of const cast. */
353 rl_line_buffer = memchr(li->buffer, *li->buffer, 1);
357 (*rl_startup_hook)(NULL, 0);
364 * read one line from input stream and return it, chomping
365 * trailing newline (if there is any)
368 readline(const char *p)
371 const char * volatile prompt = p;
375 static int used_event_hook;
377 if (e == NULL || h == NULL)
382 (void)setjmp(topbuf);
384 /* update prompt accordingly to what has been passed */
385 if (rl_set_prompt(prompt) == -1)
388 if (rl_pre_input_hook)
389 (*rl_pre_input_hook)(NULL, 0);
391 if (rl_event_hook && !(e->el_flags&NO_TTY)) {
392 el_set(e, EL_GETCFN, _rl_event_read_char);
396 if (!rl_event_hook && used_event_hook) {
397 el_set(e, EL_GETCFN, EL_BUILTIN_GETCFN);
401 rl_already_prompted = 0;
403 /* get one line from input stream */
404 ret = el_gets(e, &count);
406 if (ret && count > 0) {
413 if (buf[lastidx] == '\n')
418 FUNW(history)(h, &ev, H_GETSIZE);
419 history_length = ev.num;
429 * is normally called before application starts to use
430 * history expansion functions
435 if (h == NULL || e == NULL)
441 * substitute ``what'' with ``with'', returning resulting string; if
442 * globally == 1, substitutes all occurrences of what, otherwise only the
446 _rl_compat_sub(const char *str, const char *what, const char *with,
451 size_t len, with_len, what_len;
454 with_len = strlen(with);
455 what_len = strlen(what);
457 /* calculate length we need for result */
460 if (*s == *what && !strncmp(s, what, what_len)) {
461 len += with_len - what_len;
468 r = result = malloc(len + 1);
473 if (*s == *what && !strncmp(s, what, what_len)) {
474 (void)strncpy(r, with, with_len);
488 static char *last_search_pat; /* last !?pat[?] search pattern */
489 static char *last_search_match; /* last !?pat[?] that matched */
492 get_history_event(const char *cmd, int *cindex, int qchar)
494 int idx, sign, sub, num, begin, ret;
501 if (cmd[idx++] != history_expansion_char)
504 /* find out which event to take */
505 if (cmd[idx] == history_expansion_char || cmd[idx] == '\0') {
506 if (FUNW(history)(h, &ev, H_FIRST) != 0)
508 *cindex = cmd[idx]? (idx + 1):idx;
509 return ct_encode_string(ev.str, &conv);
512 if (cmd[idx] == '-') {
517 if ('0' <= cmd[idx] && cmd[idx] <= '9') {
521 while (cmd[idx] && '0' <= cmd[idx] && cmd[idx] <= '9') {
522 num = num * 10 + cmd[idx] - '0';
526 num = history_length - num + 1;
528 if (!(rl_he = history_get(num)))
535 if (cmd[idx] == '?') {
541 if (cmd[idx] == '\n')
543 if (sub && cmd[idx] == '?')
545 if (!sub && (cmd[idx] == ':' || cmd[idx] == ' '
546 || cmd[idx] == '\t' || cmd[idx] == qchar))
551 if (sub && cmd[idx] == '?')
553 if (sub && len == 0 && last_search_pat && *last_search_pat)
554 pat = last_search_pat;
558 if ((pat = malloc(len + 1)) == NULL)
560 (void)strncpy(pat, cmd + begin, len);
564 if (FUNW(history)(h, &ev, H_CURR) != 0) {
565 if (pat != last_search_pat)
572 if (pat != last_search_pat) {
574 free(last_search_pat);
575 last_search_pat = pat;
577 ret = history_search(pat, -1);
579 ret = history_search_prefix(pat, -1);
582 /* restore to end of list on failed search */
583 FUNW(history)(h, &ev, H_FIRST);
584 (void)fprintf(rl_outstream, "%s: Event not found\n", pat);
585 if (pat != last_search_pat)
591 if (last_search_match && last_search_match != pat)
592 free(last_search_match);
593 last_search_match = pat;
596 if (pat != last_search_pat)
599 if (FUNW(history)(h, &ev, H_CURR) != 0)
602 rptr = ct_encode_string(ev.str, &conv);
604 /* roll back to original position */
605 (void)FUNW(history)(h, &ev, H_SET, num);
611 * the real function doing history expansion - takes as argument command
612 * to do and data upon which the command should be executed
613 * does expansion the way I've understood readline documentation
615 * returns 0 if data was not modified, 1 if it was and 2 if the string
616 * should be only printed and not executed; in case of error,
617 * returns -1 and *result points to NULL
618 * it's callers responsibility to free() string returned in *result
621 _history_expand_command(const char *command, size_t offs, size_t cmdlen,
624 char *tmp, *search = NULL, *aptr;
625 const char *ptr, *cmd;
626 static char *from = NULL, *to = NULL;
627 int start, end, idx, has_mods = 0;
628 int p_on = 0, g_on = 0;
634 /* First get event specifier */
637 if (strchr(":^*$", command[offs + 1])) {
640 * "!:" is shorthand for "!!:".
641 * "!^", "!*" and "!$" are shorthand for
642 * "!!:^", "!!:*" and "!!:$" respectively.
644 str[0] = str[1] = '!';
646 ptr = get_history_event(str, &idx, 0);
647 idx = (command[offs + 1] == ':')? 1:0;
650 if (command[offs + 1] == '#') {
651 /* use command so far */
652 if ((aptr = malloc(offs + 1)) == NULL)
654 (void)strncpy(aptr, command, offs);
660 qchar = (offs > 0 && command[offs - 1] == '"')? '"':0;
661 ptr = get_history_event(command + offs, &idx, qchar);
663 has_mods = command[offs + idx] == ':';
666 if (ptr == NULL && aptr == NULL)
670 *result = strdup(aptr ? aptr : ptr);
678 cmd = command + offs + idx + 1;
680 /* Now parse any word designators */
682 if (*cmd == '%') /* last word matched by ?pat? */
683 tmp = strdup(last_search_match? last_search_match:"");
684 else if (strchr("^*$-0123456789", *cmd)) {
687 start = end = 1, cmd++;
688 else if (*cmd == '$')
690 else if (*cmd == '*')
692 else if (*cmd == '-' || isdigit((unsigned char) *cmd)) {
694 while (*cmd && '0' <= *cmd && *cmd <= '9')
695 start = start * 10 + *cmd++ - '0';
698 if (isdigit((unsigned char) cmd[1])) {
701 while (*cmd && '0' <= *cmd && *cmd <= '9')
702 end = end * 10 + *cmd++ - '0';
703 } else if (cmd[1] == '$') {
710 } else if (*cmd == '*')
715 tmp = history_arg_extract(start, end, aptr? aptr:ptr);
717 (void)fprintf(rl_outstream, "%s: Bad word specifier",
718 command + offs + idx);
724 tmp = strdup(aptr? aptr:ptr);
729 if (*cmd == '\0' || ((size_t)(cmd - (command + offs)) >= cmdlen)) {
734 for (; *cmd; cmd++) {
737 else if (*cmd == 'h') { /* remove trailing path */
738 if ((aptr = strrchr(tmp, '/')) != NULL)
740 } else if (*cmd == 't') { /* remove leading path */
741 if ((aptr = strrchr(tmp, '/')) != NULL) {
742 aptr = strdup(aptr + 1);
746 } else if (*cmd == 'r') { /* remove trailing suffix */
747 if ((aptr = strrchr(tmp, '.')) != NULL)
749 } else if (*cmd == 'e') { /* remove all but suffix */
750 if ((aptr = strrchr(tmp, '.')) != NULL) {
755 } else if (*cmd == 'p') /* print only */
757 else if (*cmd == 'g')
759 else if (*cmd == 's' || *cmd == '&') {
760 char *what, *with, delim;
761 size_t len, from_len;
764 if (*cmd == '&' && (from == NULL || to == NULL))
766 else if (*cmd == 's') {
767 delim = *(++cmd), cmd++;
769 what = realloc(from, size);
776 for (; *cmd && *cmd != delim; cmd++) {
777 if (*cmd == '\\' && cmd[1] == delim)
781 nwhat = realloc(what,
797 from = strdup(search);
808 cmd++; /* shift after delim */
813 with = realloc(to, size);
820 from_len = strlen(from);
821 for (; *cmd && *cmd != delim; cmd++) {
822 if (len + from_len + 1 >= size) {
824 size += from_len + 1;
825 nwith = realloc(with, size);
835 (void)strcpy(&with[len], from);
840 && (*(cmd + 1) == delim
841 || *(cmd + 1) == '&'))
849 aptr = _rl_compat_sub(tmp, from, to, g_on);
863 * csh-style history expansion
866 history_expand(char *str, char **output)
872 if (h == NULL || e == NULL)
875 if (history_expansion_char == 0) {
876 *output = strdup(str);
881 if (str[0] == history_subst_char) {
882 /* ^foo^foo2^ is equivalent to !!:s^foo^foo2^ */
883 *output = malloc(strlen(str) + 4 + 1);
886 (*output)[0] = (*output)[1] = history_expansion_char;
889 (void)strcpy((*output) + 4, str);
892 *output = strdup(str);
897 #define ADD_STRING(what, len, fr) \
899 if (idx + len + 1 > size) { \
900 char *nresult = realloc(result, (size += len + 1));\
901 if (nresult == NULL) { \
903 if (/*CONSTCOND*/fr) \
909 (void)strncpy(&result[idx], what, len); \
911 result[idx] = '\0'; \
917 for (i = 0; str[i];) {
918 int qchar, loop_again;
919 size_t len, start, j;
925 for (; str[j]; j++) {
926 if (str[j] == '\\' &&
927 str[j + 1] == history_expansion_char) {
928 (void)strcpy(&str[j], &str[j + 1]);
932 if (isspace((unsigned char) str[j])
936 if (str[j] == history_expansion_char
937 && !strchr(history_no_expand_chars, str[j + 1])
938 && (!history_inhibit_expansion_function ||
939 (*history_inhibit_expansion_function)(str,
944 if (str[j] && loop_again) {
946 qchar = (j > 0 && str[j - 1] == '"' )? '"':0;
948 if (str[j] == history_expansion_char)
954 ADD_STRING(&str[start], len, 0);
956 if (str[i] == '\0' || str[i] != history_expansion_char) {
958 ADD_STRING(&str[i], len, 0);
965 ret = _history_expand_command (str, i, (j - i), &tmp);
966 if (ret > 0 && tmp) {
968 ADD_STRING(tmp, len, 1);
977 /* ret is 2 for "print only" option */
981 /* gdb 4.11 has been shipped with readline, where */
982 /* history_expand() returned -1 when the line */
983 /* should not be executed; in readline 2.1+ */
984 /* it should return 2 in such a case */
995 * Return a string consisting of arguments of "str" from "start" to "end".
998 history_arg_extract(int start, int end, const char *str)
1001 char **arr, *result = NULL;
1003 arr = history_tokenize(str);
1006 if (arr && *arr == NULL)
1009 for (max = 0; arr[max]; max++)
1018 end = (int)max + end + 1;
1022 if (start < 0 || end < 0 || (size_t)start > max ||
1023 (size_t)end > max || start > end)
1026 for (i = start, len = 0; i <= (size_t)end; i++)
1027 len += strlen(arr[i]) + 1;
1029 result = malloc(len);
1033 for (i = start, len = 0; i <= (size_t)end; i++) {
1034 (void)strcpy(result + len, arr[i]);
1035 len += strlen(arr[i]);
1036 if (i < (size_t)end)
1037 result[len++] = ' ';
1042 for (i = 0; arr[i]; i++)
1050 * Parse the string into individual tokens,
1051 * similar to how shell would do it.
1054 history_tokenize(const char *str)
1056 int size = 1, idx = 0, i, start;
1058 char **result = NULL, *temp, delim = '\0';
1060 for (i = 0; str[i];) {
1061 while (isspace((unsigned char) str[i]))
1065 if (str[i] == '\\') {
1066 if (str[i+1] != '\0')
1068 } else if (str[i] == delim)
1071 (isspace((unsigned char) str[i]) ||
1072 strchr("()<>;&|$", str[i])))
1074 else if (!delim && strchr("'`\"", str[i]))
1080 if (idx + 2 >= size) {
1083 nresult = realloc(result, size * sizeof(char *));
1084 if (nresult == NULL) {
1091 temp = malloc(len + 1);
1093 for (i = 0; i < idx; i++)
1098 (void)strncpy(temp, &str[start], len);
1100 result[idx++] = temp;
1110 * limit size of history record to ``max'' events
1113 stifle_history(int max)
1117 if (h == NULL || e == NULL)
1120 if (FUNW(history)(h, &ev, H_SETSIZE, max) == 0)
1121 max_input_history = max;
1126 * "unlimit" size of history - set the limit to maximum allowed int value
1129 unstifle_history(void)
1134 FUNW(history)(h, &ev, H_SETSIZE, INT_MAX);
1135 omax = max_input_history;
1136 max_input_history = INT_MAX;
1137 return (omax); /* some value _must_ be returned */
1142 history_is_stifled(void)
1145 /* cannot return true answer */
1146 return (max_input_history != INT_MAX);
1149 static const char _history_tmp_template[] = "/tmp/.historyXXXXXX";
1152 history_truncate_file (const char *filename, int nlines)
1156 char template[sizeof(_history_tmp_template)];
1164 if (filename == NULL && (filename = _default_history_file()) == NULL)
1166 if ((fp = fopen(filename, "r+")) == NULL)
1168 strcpy(template, _history_tmp_template);
1169 if ((fd = mkstemp(template)) == -1) {
1174 if ((tp = fdopen(fd, "r+")) == NULL) {
1181 if (fread(buf, sizeof(buf), 1, fp) != 1) {
1186 if (fseeko(fp, (off_t)sizeof(buf) * count, SEEK_SET) ==
1191 left = fread(buf, 1, sizeof(buf), fp);
1199 } else if (fwrite(buf, (size_t)left, 1, tp) != 1) {
1206 if (fwrite(buf, sizeof(buf), 1, tp) != 1) {
1214 cp = buf + left - 1;
1218 while (--cp >= buf) {
1220 if (--nlines == 0) {
1221 if (++cp >= buf + sizeof(buf)) {
1229 if (nlines <= 0 || count == 0)
1232 if (fseeko(tp, (off_t)sizeof(buf) * count, SEEK_SET) < 0) {
1236 if (fread(buf, sizeof(buf), 1, tp) != 1) {
1244 cp = buf + sizeof(buf);
1247 if (ret || nlines > 0)
1250 if (fseeko(fp, 0, SEEK_SET) == (off_t)-1) {
1255 if (fseeko(tp, (off_t)sizeof(buf) * count + (cp - buf), SEEK_SET) ==
1262 if ((left = fread(buf, 1, sizeof(buf), tp)) == 0) {
1267 if (fwrite(buf, (size_t)left, 1, fp) != 1) {
1273 if((off = ftello(fp)) > 0)
1274 (void)ftruncate(fileno(fp), off);
1287 * read history from a file given
1290 read_history(const char *filename)
1294 if (h == NULL || e == NULL)
1296 if (filename == NULL && (filename = _default_history_file()) == NULL)
1298 return (FUNW(history)(h, &ev, H_LOAD, filename) == -1 ?
1299 (errno ? errno : EINVAL) : 0);
1304 * write history to a file given
1307 write_history(const char *filename)
1311 if (h == NULL || e == NULL)
1313 if (filename == NULL && (filename = _default_history_file()) == NULL)
1315 return (FUNW(history)(h, &ev, H_SAVE, filename) == -1 ?
1316 (errno ? errno : EINVAL) : 0);
1321 * returns history ``num''th event
1323 * returned pointer points to static variable
1326 history_get(int num)
1328 static HIST_ENTRY she;
1332 if (h == NULL || e == NULL)
1335 /* save current position */
1336 if (FUNW(history)(h, &ev, H_CURR) != 0)
1340 /* start from the oldest */
1341 if (FUNW(history)(h, &ev, H_LAST) != 0)
1342 return (NULL); /* error */
1344 /* look forwards for event matching specified offset */
1345 if (FUNW(history)(h, &ev, H_NEXT_EVDATA, num, &she.data))
1348 she.line = ct_encode_string(ev.str, &conv);
1350 /* restore pointer to where it was */
1351 (void)FUNW(history)(h, &ev, H_SET, curr_num);
1358 * add the line to history table
1361 add_history(const char *line)
1369 if (h == NULL || e == NULL)
1372 wline = ct_decode_string(line, &conv);
1374 (void)FUNW(history)(h, &ev, H_ENTER, wline);
1375 if (FUNW(history)(h, &ev, H_GETSIZE) == 0)
1376 history_length = ev.num;
1378 return (!(history_length > 0)); /* return 0 if all is okay */
1383 * remove the specified entry from the history list and return it.
1386 remove_history(int num)
1391 if (h == NULL || e == NULL)
1394 if ((he = malloc(sizeof(*he))) == NULL)
1397 if (FUNW(history)(h, &ev, H_DELDATA, num, &he->data) != 0) {
1402 he->line = ct_encode_string(ev.str, &conv);
1403 if (FUNW(history)(h, &ev, H_GETSIZE) == 0)
1404 history_length = ev.num;
1411 * replace the line and data of the num-th entry
1414 replace_history_entry(int num, const char *line, histdata_t data)
1420 if (h == NULL || e == NULL)
1423 /* save current position */
1424 if (FUNW(history)(h, &ev, H_CURR) != 0)
1428 /* start from the oldest */
1429 if (FUNW(history)(h, &ev, H_LAST) != 0)
1430 return NULL; /* error */
1432 if ((he = malloc(sizeof(*he))) == NULL)
1435 /* look forwards for event matching specified offset */
1436 if (FUNW(history)(h, &ev, H_NEXT_EVDATA, num, &he->data))
1439 he->line = strdup(ct_encode_string(ev.str, &e->el_scratch));
1440 if (he->line == NULL)
1443 if (FUNW(history)(h, &ev, H_REPLACE, line, data))
1446 /* restore pointer to where it was */
1447 if (FUNW(history)(h, &ev, H_SET, curr_num))
1457 * clear the history list - delete all entries
1464 (void)FUNW(history)(h, &ev, H_CLEAR);
1470 * returns offset of the current history event
1478 if (FUNW(history)(h, &ev, H_CURR) != 0)
1482 (void)FUNW(history)(h, &ev, H_FIRST);
1484 while (ev.num != curr_num && FUNW(history)(h, &ev, H_NEXT) == 0)
1492 * returns current history event or NULL if there is no such event
1495 current_history(void)
1498 return (_move_history(H_CURR));
1503 * returns total number of bytes history events' data are using
1506 history_total_bytes(void)
1512 if (FUNW(history)(h, &ev, H_CURR) != 0)
1516 (void)FUNW(history)(h, &ev, H_FIRST);
1519 size += Strlen(ev.str) * sizeof(*ev.str);
1520 while (FUNW(history)(h, &ev, H_NEXT) == 0);
1522 /* get to the same position as before */
1523 FUNW(history)(h, &ev, H_PREV_EVENT, curr_num);
1530 * sets the position in the history list to ``pos''
1533 history_set_pos(int pos)
1538 if (pos >= history_length || pos < 0)
1541 (void)FUNW(history)(h, &ev, H_CURR);
1545 * use H_DELDATA to set to nth history (without delete) by passing
1548 if (FUNW(history)(h, &ev, H_DELDATA, pos, (void **)-1)) {
1549 (void)FUNW(history)(h, &ev, H_SET, curr_num);
1557 * returns previous event in history and shifts pointer accordingly
1560 previous_history(void)
1563 return (_move_history(H_PREV));
1568 * returns next event in history and shifts pointer accordingly
1574 return (_move_history(H_NEXT));
1579 * searches for first history event containing the str
1582 history_search(const char *str, int direction)
1589 if (FUNW(history)(h, &ev, H_CURR) != 0)
1593 wstr = ct_decode_string(str, &conv);
1595 if ((strp = Strstr(ev.str, wstr)) != NULL)
1596 return (int) (strp - ev.str);
1597 if (FUNW(history)(h, &ev, direction < 0 ? H_NEXT:H_PREV) != 0)
1600 (void)FUNW(history)(h, &ev, H_SET, curr_num);
1606 * searches for first history event beginning with str
1609 history_search_prefix(const char *str, int direction)
1613 return (FUNW(history)(h, &ev, direction < 0 ?
1614 H_PREV_STR : H_NEXT_STR, str));
1619 * search for event in history containing str, starting at offset
1620 * abs(pos); continue backward, if pos<0, forward otherwise
1624 history_search_pos(const char *str,
1625 int direction __attribute__((__unused__)), int pos)
1631 off = (pos > 0) ? pos : -pos;
1632 pos = (pos > 0) ? 1 : -1;
1634 if (FUNW(history)(h, &ev, H_CURR) != 0)
1638 if (history_set_pos(off) != 0 || FUNW(history)(h, &ev, H_CURR) != 0)
1641 wstr = ct_decode_string(str, &conv);
1643 if (Strstr(ev.str, wstr))
1645 if (FUNW(history)(h, &ev, (pos < 0) ? H_PREV : H_NEXT) != 0)
1649 /* set "current" pointer back to previous state */
1650 (void)FUNW(history)(h, &ev,
1651 pos < 0 ? H_NEXT_EVENT : H_PREV_EVENT, curr_num);
1657 /********************************/
1658 /* completion functions */
1661 tilde_expand(char *name)
1663 return fn_tilde_expand(name);
1667 filename_completion_function(const char *name, int state)
1669 return fn_filename_completion_function(name, state);
1673 * a completion generator for usernames; returns _first_ username
1674 * which starts with supplied text
1675 * text contains a partial username preceded by random character
1676 * (usually '~'); state is ignored
1677 * it's callers responsibility to free returned value
1680 username_completion_function(const char *text, int state)
1682 struct passwd *pwd, pwres;
1685 if (text[0] == '\0')
1694 while (getpwent_r(&pwres, pwbuf, sizeof(pwbuf), &pwd) == 0
1695 && pwd != NULL && text[0] == pwd->pw_name[0]
1696 && strcmp(text, pwd->pw_name) == 0);
1702 return strdup(pwd->pw_name);
1707 * el-compatible wrapper to send TSTP on ^Z
1710 static unsigned char
1711 _el_rl_tstp(EditLine *el __attribute__((__unused__)), int ch __attribute__((__unused__)))
1713 (void)kill(0, SIGTSTP);
1718 * Display list of strings in columnar format on readline's output stream.
1719 * 'matches' is list of strings, 'len' is number of strings in 'matches',
1720 * 'max' is maximum length of string in 'matches'.
1723 rl_display_match_list(char **matches, int len, int max)
1726 fn_display_match_list(e, matches, (size_t)len, (size_t)max);
1731 _rl_completion_append_character_function(const char *dummy
1732 __attribute__((__unused__)))
1735 buf[0] = rl_completion_append_character;
1742 * complete word at current point
1746 rl_complete(int ignore __attribute__((__unused__)), int invoking_key)
1749 static ct_buffer_t wbreak_conv, sprefix_conv;
1752 if (h == NULL || e == NULL)
1755 if (rl_inhibit_completion) {
1757 arr[0] = (char)invoking_key;
1759 el_insertstr(e, arr);
1760 return (CC_REFRESH);
1763 /* Just look at how many global variables modify this operation! */
1764 return fn_complete(e,
1765 (CPFunction *)rl_completion_entry_function,
1766 rl_attempted_completion_function,
1767 ct_decode_string(rl_basic_word_break_characters, &wbreak_conv),
1768 ct_decode_string(rl_special_prefixes, &sprefix_conv),
1769 _rl_completion_append_character_function,
1770 (size_t)rl_completion_query_items,
1771 &rl_completion_type, &rl_attempted_completion_over,
1772 &rl_point, &rl_end, NULL, NULL, NULL);
1777 static unsigned char
1778 _el_rl_complete(EditLine *el __attribute__((__unused__)), int ch)
1780 return (unsigned char)rl_complete(0, ch);
1784 * misc other functions
1788 * bind key c to readline-type function func
1791 rl_bind_key(int c, rl_command_func_t *func)
1795 if (h == NULL || e == NULL)
1798 if (func == rl_insert) {
1799 /* XXX notice there is no range checking of ``c'' */
1800 e->el_map.key[c] = ED_INSERT;
1808 * read one key from input - handles chars pushed back
1809 * to input stream also
1814 char fooarr[2 * sizeof(int)];
1816 if (e == NULL || h == NULL)
1819 return (el_getc(e, fooarr));
1824 * reset the terminal
1828 rl_reset_terminal(const char *p __attribute__((__unused__)))
1831 if (h == NULL || e == NULL)
1838 * insert character ``c'' back into input stream, ``count'' times
1841 rl_insert(int count, int c)
1845 if (h == NULL || e == NULL)
1848 /* XXX - int -> char conversion can lose on multichars */
1852 for (; count > 0; count--)
1859 rl_insert_text(const char *text)
1861 if (!text || *text == 0)
1864 if (h == NULL || e == NULL)
1867 if (el_insertstr(e, text) < 0)
1869 return (int)strlen(text);
1874 rl_newline(int count, int c)
1877 * Readline-4.0 appears to ignore the args.
1879 return rl_insert(1, '\n');
1883 static unsigned char
1884 rl_bind_wrapper(EditLine *el, unsigned char c)
1893 /* If rl_done was set by the above call, deal with it here */
1901 rl_add_defun(const char *name, Function *fun, int c)
1904 if ((size_t)c >= sizeof(map) / sizeof(map[0]) || c < 0)
1906 map[(unsigned char)c] = fun;
1907 el_set(e, EL_ADDFN, name, name, rl_bind_wrapper);
1908 vis(dest, c, VIS_WHITE|VIS_NOSLASH, 0);
1909 el_set(e, EL_BIND, dest, name);
1914 rl_callback_read_char()
1916 int count = 0, done = 0;
1917 const char *buf = el_gets(e, &count);
1920 if (buf == NULL || count-- <= 0)
1922 if (count == 0 && buf[0] == e->el_tty.t_c[TS_IO][C_EOF])
1924 if (buf[count] == '\n' || buf[count] == '\r')
1927 if (done && rl_linefunc != NULL) {
1928 el_set(e, EL_UNBUFFERED, 0);
1930 if ((wbuf = strdup(buf)) != NULL)
1934 (*(void (*)(const char *))rl_linefunc)(wbuf);
1935 //el_set(e, EL_UNBUFFERED, 1);
1940 rl_callback_handler_install(const char *prompt, VCPFunction *linefunc)
1945 (void)rl_set_prompt(prompt);
1946 rl_linefunc = linefunc;
1947 el_set(e, EL_UNBUFFERED, 1);
1951 rl_callback_handler_remove(void)
1953 el_set(e, EL_UNBUFFERED, 0);
1961 a[0] = e->el_tty.t_c[TS_IO][C_REPRINT];
1967 rl_get_previous_history(int count, int key)
1979 rl_prep_terminal(int meta_flag)
1981 el_set(e, EL_PREP_TERM, 1);
1985 rl_deprep_terminal(void)
1987 el_set(e, EL_PREP_TERM, 0);
1991 rl_read_init_file(const char *s)
1993 return(el_source(e, s));
1997 rl_parse_and_bind(const char *line)
2003 tok = tok_init(NULL);
2004 tok_str(tok, line, &argc, &argv);
2005 argc = el_parse(e, argc, argv);
2007 return (argc ? 1 : 0);
2011 rl_variable_bind(const char *var, const char *value)
2014 * The proper return value is undocument, but this is what the
2015 * readline source seems to do.
2017 return ((el_set(e, EL_BIND, "", var, value) == -1) ? 1 : 0);
2021 rl_stuff_char(int c)
2027 el_insertstr(e, buf);
2031 _rl_event_read_char(EditLine *el, char *cp)
2034 ssize_t num_read = 0;
2037 while (rl_event_hook) {
2041 #if defined(FIONREAD)
2042 if (ioctl(el->el_infd, FIONREAD, &n) < 0)
2045 num_read = read(el->el_infd, cp, 1);
2048 #elif defined(F_SETFL) && defined(O_NDELAY)
2049 if ((n = fcntl(el->el_infd, F_GETFL, 0)) < 0)
2051 if (fcntl(el->el_infd, F_SETFL, n|O_NDELAY) < 0)
2053 num_read = read(el->el_infd, cp, 1);
2054 if (fcntl(el->el_infd, F_SETFL, n))
2057 /* not non-blocking, but what you gonna do? */
2058 num_read = read(el->el_infd, cp, 1);
2062 if (num_read < 0 && errno == EAGAIN)
2069 el_set(el, EL_GETCFN, EL_BUILTIN_GETCFN);
2070 return (int)num_read;
2074 _rl_update_pos(void)
2076 const LineInfo *li = el_line(e);
2078 rl_point = (int)(li->cursor - li->buffer);
2079 rl_end = (int)(li->lastchar - li->buffer);
2083 rl_get_screen_size(int *rows, int *cols)
2086 el_get(e, EL_GETTC, "li", rows);
2088 el_get(e, EL_GETTC, "co", cols);
2092 rl_set_screen_size(int rows, int cols)
2095 (void)snprintf(buf, sizeof(buf), "%d", rows);
2096 el_set(e, EL_SETTC, "li", buf);
2097 (void)snprintf(buf, sizeof(buf), "%d", cols);
2098 el_set(e, EL_SETTC, "co", buf);
2102 rl_completion_matches(const char *str, rl_compentry_func_t *fun)
2104 size_t len, max, i, j, min;
2105 char **list, *match, *a, *b;
2109 if ((list = malloc(max * sizeof(*list))) == NULL)
2112 while ((match = (*fun)(str, (int)(len - 1))) != NULL) {
2113 list[len++] = match;
2117 if ((nl = realloc(list, max * sizeof(*nl))) == NULL)
2126 if ((list[0] = strdup(list[1])) == NULL)
2130 qsort(&list[1], len - 1, sizeof(*list),
2131 (int (*)(const void *, const void *)) strcmp);
2133 for (i = 1, a = list[i]; i < len - 1; i++, a = b) {
2135 for (j = 0; a[j] && a[j] == b[j]; j++)
2140 if (min == 0 && *str) {
2141 if ((list[0] = strdup(str)) == NULL)
2144 if ((list[0] = malloc(min + 1)) == NULL)
2146 (void)memcpy(list[0], list[1], min);
2147 list[0][min] = '\0';
2157 rl_filename_completion_function (const char *text, int state)
2159 return fn_filename_completion_function(text, state);
2163 rl_forced_update_display(void)
2165 el_set(e, EL_REFRESH);
2169 _rl_abort_internal(void)
2177 _rl_qsort_string_compare(char **s1, char **s2)
2179 return strcoll(*s1, *s2);
2183 history_get_history_state(void)
2187 if ((hs = malloc(sizeof(HISTORY_STATE))) == NULL)
2189 hs->length = history_length;
2195 rl_kill_text(int from, int to)
2201 rl_make_bare_keymap(void)
2214 rl_set_keymap(Keymap k)
2220 rl_generic_bind(int type, const char * keyseq, const char * data, Keymap k)
2227 rl_bind_key_in_map(int key, rl_command_func_t *fun, Keymap k)
2232 /* unsupported, but needed by python */
2234 rl_cleanup_after_signal(void)
2239 rl_on_new_line(void)