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)
1366 if (h == NULL || e == NULL)
1369 wline = ct_decode_string(line, &conv);
1371 (void)FUNW(history)(h, &ev, H_ENTER, wline);
1372 if (FUNW(history)(h, &ev, H_GETSIZE) == 0)
1373 history_length = ev.num;
1375 return (!(history_length > 0)); /* return 0 if all is okay */
1380 * remove the specified entry from the history list and return it.
1383 remove_history(int num)
1388 if (h == NULL || e == NULL)
1391 if ((he = malloc(sizeof(*he))) == NULL)
1394 if (FUNW(history)(h, &ev, H_DELDATA, num, &he->data) != 0) {
1399 he->line = ct_encode_string(ev.str, &conv);
1400 if (FUNW(history)(h, &ev, H_GETSIZE) == 0)
1401 history_length = ev.num;
1408 * replace the line and data of the num-th entry
1411 replace_history_entry(int num, const char *line, histdata_t data)
1417 if (h == NULL || e == NULL)
1420 /* save current position */
1421 if (FUNW(history)(h, &ev, H_CURR) != 0)
1425 /* start from the oldest */
1426 if (FUNW(history)(h, &ev, H_LAST) != 0)
1427 return NULL; /* error */
1429 if ((he = malloc(sizeof(*he))) == NULL)
1432 /* look forwards for event matching specified offset */
1433 if (FUNW(history)(h, &ev, H_NEXT_EVDATA, num, &he->data))
1436 he->line = strdup(ct_encode_string(ev.str, &e->el_scratch));
1437 if (he->line == NULL)
1440 if (FUNW(history)(h, &ev, H_REPLACE, line, data))
1443 /* restore pointer to where it was */
1444 if (FUNW(history)(h, &ev, H_SET, curr_num))
1454 * clear the history list - delete all entries
1461 (void)FUNW(history)(h, &ev, H_CLEAR);
1467 * returns offset of the current history event
1475 if (FUNW(history)(h, &ev, H_CURR) != 0)
1479 (void)FUNW(history)(h, &ev, H_FIRST);
1481 while (ev.num != curr_num && FUNW(history)(h, &ev, H_NEXT) == 0)
1489 * returns current history event or NULL if there is no such event
1492 current_history(void)
1495 return (_move_history(H_CURR));
1500 * returns total number of bytes history events' data are using
1503 history_total_bytes(void)
1509 if (FUNW(history)(h, &ev, H_CURR) != 0)
1513 (void)FUNW(history)(h, &ev, H_FIRST);
1516 size += Strlen(ev.str) * sizeof(*ev.str);
1517 while (FUNW(history)(h, &ev, H_NEXT) == 0);
1519 /* get to the same position as before */
1520 FUNW(history)(h, &ev, H_PREV_EVENT, curr_num);
1527 * sets the position in the history list to ``pos''
1530 history_set_pos(int pos)
1535 if (pos >= history_length || pos < 0)
1538 (void)FUNW(history)(h, &ev, H_CURR);
1542 * use H_DELDATA to set to nth history (without delete) by passing
1545 if (FUNW(history)(h, &ev, H_DELDATA, pos, (void **)-1)) {
1546 (void)FUNW(history)(h, &ev, H_SET, curr_num);
1554 * returns previous event in history and shifts pointer accordingly
1557 previous_history(void)
1560 return (_move_history(H_PREV));
1565 * returns next event in history and shifts pointer accordingly
1571 return (_move_history(H_NEXT));
1576 * searches for first history event containing the str
1579 history_search(const char *str, int direction)
1586 if (FUNW(history)(h, &ev, H_CURR) != 0)
1590 wstr = ct_decode_string(str, &conv);
1592 if ((strp = Strstr(ev.str, wstr)) != NULL)
1593 return (int) (strp - ev.str);
1594 if (FUNW(history)(h, &ev, direction < 0 ? H_NEXT:H_PREV) != 0)
1597 (void)FUNW(history)(h, &ev, H_SET, curr_num);
1603 * searches for first history event beginning with str
1606 history_search_prefix(const char *str, int direction)
1610 return (FUNW(history)(h, &ev, direction < 0 ?
1611 H_PREV_STR : H_NEXT_STR, str));
1616 * search for event in history containing str, starting at offset
1617 * abs(pos); continue backward, if pos<0, forward otherwise
1621 history_search_pos(const char *str,
1622 int direction __attribute__((__unused__)), int pos)
1628 off = (pos > 0) ? pos : -pos;
1629 pos = (pos > 0) ? 1 : -1;
1631 if (FUNW(history)(h, &ev, H_CURR) != 0)
1635 if (history_set_pos(off) != 0 || FUNW(history)(h, &ev, H_CURR) != 0)
1638 wstr = ct_decode_string(str, &conv);
1640 if (Strstr(ev.str, wstr))
1642 if (FUNW(history)(h, &ev, (pos < 0) ? H_PREV : H_NEXT) != 0)
1646 /* set "current" pointer back to previous state */
1647 (void)FUNW(history)(h, &ev,
1648 pos < 0 ? H_NEXT_EVENT : H_PREV_EVENT, curr_num);
1654 /********************************/
1655 /* completion functions */
1658 tilde_expand(char *name)
1660 return fn_tilde_expand(name);
1664 filename_completion_function(const char *name, int state)
1666 return fn_filename_completion_function(name, state);
1670 * a completion generator for usernames; returns _first_ username
1671 * which starts with supplied text
1672 * text contains a partial username preceded by random character
1673 * (usually '~'); state is ignored
1674 * it's callers responsibility to free returned value
1677 username_completion_function(const char *text, int state)
1679 struct passwd *pwd, pwres;
1682 if (text[0] == '\0')
1691 while (getpwent_r(&pwres, pwbuf, sizeof(pwbuf), &pwd) == 0
1692 && pwd != NULL && text[0] == pwd->pw_name[0]
1693 && strcmp(text, pwd->pw_name) == 0);
1699 return strdup(pwd->pw_name);
1704 * el-compatible wrapper to send TSTP on ^Z
1707 static unsigned char
1708 _el_rl_tstp(EditLine *el __attribute__((__unused__)), int ch __attribute__((__unused__)))
1710 (void)kill(0, SIGTSTP);
1715 * Display list of strings in columnar format on readline's output stream.
1716 * 'matches' is list of strings, 'len' is number of strings in 'matches',
1717 * 'max' is maximum length of string in 'matches'.
1720 rl_display_match_list(char **matches, int len, int max)
1723 fn_display_match_list(e, matches, (size_t)len, (size_t)max);
1728 _rl_completion_append_character_function(const char *dummy
1729 __attribute__((__unused__)))
1732 buf[0] = rl_completion_append_character;
1739 * complete word at current point
1743 rl_complete(int ignore __attribute__((__unused__)), int invoking_key)
1746 static ct_buffer_t wbreak_conv, sprefix_conv;
1749 if (h == NULL || e == NULL)
1752 if (rl_inhibit_completion) {
1754 arr[0] = (char)invoking_key;
1756 el_insertstr(e, arr);
1757 return (CC_REFRESH);
1760 /* Just look at how many global variables modify this operation! */
1761 return fn_complete(e,
1762 (CPFunction *)rl_completion_entry_function,
1763 rl_attempted_completion_function,
1764 ct_decode_string(rl_basic_word_break_characters, &wbreak_conv),
1765 ct_decode_string(rl_special_prefixes, &sprefix_conv),
1766 _rl_completion_append_character_function,
1767 (size_t)rl_completion_query_items,
1768 &rl_completion_type, &rl_attempted_completion_over,
1769 &rl_point, &rl_end, NULL, NULL, NULL);
1774 static unsigned char
1775 _el_rl_complete(EditLine *el __attribute__((__unused__)), int ch)
1777 return (unsigned char)rl_complete(0, ch);
1781 * misc other functions
1785 * bind key c to readline-type function func
1788 rl_bind_key(int c, rl_command_func_t *func)
1792 if (h == NULL || e == NULL)
1795 if (func == rl_insert) {
1796 /* XXX notice there is no range checking of ``c'' */
1797 e->el_map.key[c] = ED_INSERT;
1805 * read one key from input - handles chars pushed back
1806 * to input stream also
1811 char fooarr[2 * sizeof(int)];
1813 if (e == NULL || h == NULL)
1816 return (el_getc(e, fooarr));
1821 * reset the terminal
1825 rl_reset_terminal(const char *p __attribute__((__unused__)))
1828 if (h == NULL || e == NULL)
1835 * insert character ``c'' back into input stream, ``count'' times
1838 rl_insert(int count, int c)
1842 if (h == NULL || e == NULL)
1845 /* XXX - int -> char conversion can lose on multichars */
1849 for (; count > 0; count--)
1856 rl_insert_text(const char *text)
1858 if (!text || *text == 0)
1861 if (h == NULL || e == NULL)
1864 if (el_insertstr(e, text) < 0)
1866 return (int)strlen(text);
1871 rl_newline(int count, int c)
1874 * Readline-4.0 appears to ignore the args.
1876 return rl_insert(1, '\n');
1880 static unsigned char
1881 rl_bind_wrapper(EditLine *el, unsigned char c)
1890 /* If rl_done was set by the above call, deal with it here */
1898 rl_add_defun(const char *name, Function *fun, int c)
1901 if ((size_t)c >= sizeof(map) / sizeof(map[0]) || c < 0)
1903 map[(unsigned char)c] = fun;
1904 el_set(e, EL_ADDFN, name, name, rl_bind_wrapper);
1905 vis(dest, c, VIS_WHITE|VIS_NOSLASH, 0);
1906 el_set(e, EL_BIND, dest, name);
1911 rl_callback_read_char()
1913 int count = 0, done = 0;
1914 const char *buf = el_gets(e, &count);
1917 if (buf == NULL || count-- <= 0)
1919 if (count == 0 && buf[0] == e->el_tty.t_c[TS_IO][C_EOF])
1921 if (buf[count] == '\n' || buf[count] == '\r')
1924 if (done && rl_linefunc != NULL) {
1925 el_set(e, EL_UNBUFFERED, 0);
1927 if ((wbuf = strdup(buf)) != NULL)
1931 (*(void (*)(const char *))rl_linefunc)(wbuf);
1932 //el_set(e, EL_UNBUFFERED, 1);
1937 rl_callback_handler_install(const char *prompt, VCPFunction *linefunc)
1942 (void)rl_set_prompt(prompt);
1943 rl_linefunc = linefunc;
1944 el_set(e, EL_UNBUFFERED, 1);
1948 rl_callback_handler_remove(void)
1950 el_set(e, EL_UNBUFFERED, 0);
1958 a[0] = e->el_tty.t_c[TS_IO][C_REPRINT];
1964 rl_get_previous_history(int count, int key)
1976 rl_prep_terminal(int meta_flag)
1978 el_set(e, EL_PREP_TERM, 1);
1982 rl_deprep_terminal(void)
1984 el_set(e, EL_PREP_TERM, 0);
1988 rl_read_init_file(const char *s)
1990 return(el_source(e, s));
1994 rl_parse_and_bind(const char *line)
2000 tok = tok_init(NULL);
2001 tok_str(tok, line, &argc, &argv);
2002 argc = el_parse(e, argc, argv);
2004 return (argc ? 1 : 0);
2008 rl_variable_bind(const char *var, const char *value)
2011 * The proper return value is undocument, but this is what the
2012 * readline source seems to do.
2014 return ((el_set(e, EL_BIND, "", var, value) == -1) ? 1 : 0);
2018 rl_stuff_char(int c)
2024 el_insertstr(e, buf);
2028 _rl_event_read_char(EditLine *el, char *cp)
2031 ssize_t num_read = 0;
2034 while (rl_event_hook) {
2038 #if defined(FIONREAD)
2039 if (ioctl(el->el_infd, FIONREAD, &n) < 0)
2042 num_read = read(el->el_infd, cp, 1);
2045 #elif defined(F_SETFL) && defined(O_NDELAY)
2046 if ((n = fcntl(el->el_infd, F_GETFL, 0)) < 0)
2048 if (fcntl(el->el_infd, F_SETFL, n|O_NDELAY) < 0)
2050 num_read = read(el->el_infd, cp, 1);
2051 if (fcntl(el->el_infd, F_SETFL, n))
2054 /* not non-blocking, but what you gonna do? */
2055 num_read = read(el->el_infd, cp, 1);
2059 if (num_read < 0 && errno == EAGAIN)
2066 el_set(el, EL_GETCFN, EL_BUILTIN_GETCFN);
2067 return (int)num_read;
2071 _rl_update_pos(void)
2073 const LineInfo *li = el_line(e);
2075 rl_point = (int)(li->cursor - li->buffer);
2076 rl_end = (int)(li->lastchar - li->buffer);
2080 rl_get_screen_size(int *rows, int *cols)
2083 el_get(e, EL_GETTC, "li", rows);
2085 el_get(e, EL_GETTC, "co", cols);
2089 rl_set_screen_size(int rows, int cols)
2092 (void)snprintf(buf, sizeof(buf), "%d", rows);
2093 el_set(e, EL_SETTC, "li", buf);
2094 (void)snprintf(buf, sizeof(buf), "%d", cols);
2095 el_set(e, EL_SETTC, "co", buf);
2099 rl_completion_matches(const char *str, rl_compentry_func_t *fun)
2101 size_t len, max, i, j, min;
2102 char **list, *match, *a, *b;
2106 if ((list = malloc(max * sizeof(*list))) == NULL)
2109 while ((match = (*fun)(str, (int)(len - 1))) != NULL) {
2110 list[len++] = match;
2114 if ((nl = realloc(list, max * sizeof(*nl))) == NULL)
2123 if ((list[0] = strdup(list[1])) == NULL)
2127 qsort(&list[1], len - 1, sizeof(*list),
2128 (int (*)(const void *, const void *)) strcmp);
2130 for (i = 1, a = list[i]; i < len - 1; i++, a = b) {
2132 for (j = 0; a[j] && a[j] == b[j]; j++)
2137 if (min == 0 && *str) {
2138 if ((list[0] = strdup(str)) == NULL)
2141 if ((list[0] = malloc(min + 1)) == NULL)
2143 (void)memcpy(list[0], list[1], min);
2144 list[0][min] = '\0';
2154 rl_filename_completion_function (const char *text, int state)
2156 return fn_filename_completion_function(text, state);
2160 rl_forced_update_display(void)
2162 el_set(e, EL_REFRESH);
2166 _rl_abort_internal(void)
2174 _rl_qsort_string_compare(char **s1, char **s2)
2176 return strcoll(*s1, *s2);
2180 history_get_history_state(void)
2184 if ((hs = malloc(sizeof(HISTORY_STATE))) == NULL)
2186 hs->length = history_length;
2192 rl_kill_text(int from, int to)
2198 rl_make_bare_keymap(void)
2211 rl_set_keymap(Keymap k)
2217 rl_generic_bind(int type, const char * keyseq, const char * data, Keymap k)
2224 rl_bind_key_in_map(int key, rl_command_func_t *fun, Keymap k)
2229 /* unsupported, but needed by python */
2231 rl_cleanup_after_signal(void)
2236 rl_on_new_line(void)