1 /* $NetBSD: readline.c,v 1.106 2012/10/12 23:35:02 christos Exp $ */
4 * Copyright (c) 1997 The NetBSD Foundation, Inc.
7 * This code is derived from software contributed to The NetBSD Foundation
10 * Redistribution and use in source and binary forms, with or without
11 * modification, are permitted provided that the following conditions
13 * 1. Redistributions of source code must retain the above copyright
14 * notice, this list of conditions and the following disclaimer.
15 * 2. Redistributions in binary form must reproduce the above copyright
16 * notice, this list of conditions and the following disclaimer in the
17 * documentation and/or other materials provided with the distribution.
19 * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
20 * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
21 * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
22 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
23 * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
24 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
25 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
26 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
27 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
28 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
29 * POSSIBILITY OF SUCH DAMAGE.
33 #if !defined(lint) && !defined(SCCSID)
34 __RCSID("$NetBSD: readline.c,v 1.106 2012/10/12 23:35:02 christos Exp $");
35 #endif /* not lint && not SCCSID */
37 #include <sys/types.h>
52 #include "editline/readline.h"
54 #include "fcns.h" /* for EL_NUM_FCNS */
56 #include "filecomplete.h"
58 #if !defined(SIZE_T_MAX)
59 # define SIZE_T_MAX (size_t)(-1)
62 void rl_prep_terminal(int);
63 void rl_deprep_terminal(void);
65 /* for rl_complete() */
68 /* see comment at the #ifdef for sense of this */
69 /* #define GDB_411_HACK */
71 /* readline compatibility stuff - look at readline sources/documentation */
72 /* to see what these variables mean */
73 const char *rl_library_version = "EditLine wrapper";
74 int rl_readline_version = RL_READLINE_VERSION;
75 static char empty[] = { '\0' };
76 static char expand_chars[] = { ' ', '\t', '\n', '=', '(', '\0' };
77 static char break_chars[] = { ' ', '\t', '\n', '"', '\\', '\'', '`', '@', '$',
78 '>', '<', '=', ';', '|', '&', '{', '(', '\0' };
79 char *rl_readline_name = empty;
80 FILE *rl_instream = NULL;
81 FILE *rl_outstream = NULL;
84 char *rl_line_buffer = NULL;
85 VCPFunction *rl_linefunc = NULL;
87 VFunction *rl_event_hook = NULL;
88 KEYMAP_ENTRY_ARRAY emacs_standard_keymap,
92 int history_base = 1; /* probably never subject to change */
93 int history_length = 0;
94 int max_input_history = 0;
95 char history_expansion_char = '!';
96 char history_subst_char = '^';
97 char *history_no_expand_chars = expand_chars;
98 Function *history_inhibit_expansion_function = NULL;
99 char *history_arg_extract(int start, int end, const char *str);
101 int rl_inhibit_completion = 0;
102 int rl_attempted_completion_over = 0;
103 char *rl_basic_word_break_characters = break_chars;
104 char *rl_completer_word_break_characters = NULL;
105 char *rl_completer_quote_characters = NULL;
106 Function *rl_completion_entry_function = NULL;
107 char *(*rl_completion_word_break_hook)(void) = NULL;
108 CPPFunction *rl_attempted_completion_function = NULL;
109 Function *rl_pre_input_hook = NULL;
110 Function *rl_startup1_hook = NULL;
111 int (*rl_getc_function)(FILE *) = NULL;
112 char *rl_terminal_name = NULL;
113 int rl_already_prompted = 0;
114 int rl_filename_completion_desired = 0;
115 int rl_ignore_completion_duplicates = 0;
116 int rl_catch_signals = 1;
117 int readline_echoing_p = 1;
118 int _rl_print_completions_horizontally = 0;
119 VFunction *rl_redisplay_function = NULL;
120 Function *rl_startup_hook = NULL;
121 VFunction *rl_completion_display_matches_hook = NULL;
122 VFunction *rl_prep_term_function = (VFunction *)rl_prep_terminal;
123 VFunction *rl_deprep_term_function = (VFunction *)rl_deprep_terminal;
124 KEYMAP_ENTRY_ARRAY emacs_meta_keymap;
127 * The current prompt string.
129 char *rl_prompt = NULL;
131 * This is set to character indicating type of completion being done by
132 * rl_complete_internal(); this is available for application completion
135 int rl_completion_type = 0;
138 * If more than this number of items results from query for possible
139 * completions, we ask user if they are sure to really display the list.
141 int rl_completion_query_items = 100;
144 * List of characters which are word break characters, but should be left
145 * in the parsed text when it is passed to the completion function.
146 * Shell uses this to help determine what kind of completing to do.
148 char *rl_special_prefixes = NULL;
151 * This is the character appended to the completed words if at the end of
152 * the line. Default is ' ' (a space).
154 int rl_completion_append_character = ' ';
156 /* stuff below is used internally by libedit for readline emulation */
158 static History *h = NULL;
159 static EditLine *e = NULL;
160 static Function *map[256];
161 static jmp_buf topbuf;
163 /* internal functions */
164 static unsigned char _el_rl_complete(EditLine *, int);
165 static unsigned char _el_rl_tstp(EditLine *, int);
166 static char *_get_prompt(EditLine *);
167 static int _getc_function(EditLine *, char *);
168 static HIST_ENTRY *_move_history(int);
169 static int _history_expand_command(const char *, size_t, size_t,
171 static char *_rl_compat_sub(const char *, const char *,
173 static int _rl_event_read_char(EditLine *, char *);
174 static void _rl_update_pos(void);
179 _get_prompt(EditLine *el __attribute__((__unused__)))
181 rl_already_prompted = 1;
187 * generic function for moving around history
190 _move_history(int op)
193 static HIST_ENTRY rl_he;
195 if (history(h, &ev, op) != 0)
206 * read one key from user defined input function
210 _getc_function(EditLine *el __attribute__((__unused__)), char *c)
214 i = (*rl_getc_function)(NULL);
222 _resize_fun(EditLine *el, void *a)
228 /* a cheesy way to get rid of const cast. */
229 *ap = memchr(li->buffer, *li->buffer, (size_t)1);
233 _default_history_file(void)
236 static char path[PATH_MAX];
240 if ((p = getpwuid(getuid())) == NULL)
242 (void)snprintf(path, sizeof(path), "%s/.history", p->pw_dir);
247 * READLINE compatibility stuff
254 rl_set_prompt(const char *prompt)
260 if (rl_prompt != NULL && strcmp(rl_prompt, prompt) == 0)
264 rl_prompt = strdup(prompt);
265 if (rl_prompt == NULL)
268 while ((p = strchr(rl_prompt, RL_PROMPT_END_IGNORE)) != NULL)
269 *p = RL_PROMPT_START_IGNORE;
275 * initialize rl compat stuff
292 rl_outstream = stdout;
295 * See if we don't really want to run the editor
297 if (tcgetattr(fileno(rl_instream), &t) != -1 && (t.c_lflag & ECHO) == 0)
300 e = el_init(rl_readline_name, rl_instream, rl_outstream, stderr);
303 el_set(e, EL_EDITMODE, 0);
309 history(h, &ev, H_SETSIZE, INT_MAX); /* unlimited */
311 max_input_history = INT_MAX;
312 el_set(e, EL_HIST, history, h);
314 /* Setup resize function */
315 el_set(e, EL_RESIZE, _resize_fun, &rl_line_buffer);
317 /* setup getc function if valid */
318 if (rl_getc_function)
319 el_set(e, EL_GETCFN, _getc_function);
321 /* for proper prompt printing in readline() */
322 if (rl_set_prompt("") == -1) {
327 el_set(e, EL_PROMPT, _get_prompt, RL_PROMPT_START_IGNORE);
328 el_set(e, EL_SIGNAL, rl_catch_signals);
330 /* set default mode to "emacs"-style and read setting afterwards */
331 /* so this can be overriden */
332 el_set(e, EL_EDITOR, "emacs");
333 if (rl_terminal_name != NULL)
334 el_set(e, EL_TERMINAL, rl_terminal_name);
336 el_get(e, EL_TERMINAL, &rl_terminal_name);
339 * Word completion - this has to go AFTER rebinding keys
342 el_set(e, EL_ADDFN, "rl_complete",
343 "ReadLine compatible completion function",
345 el_set(e, EL_BIND, "^I", "rl_complete", NULL);
348 * Send TSTP when ^Z is pressed.
350 el_set(e, EL_ADDFN, "rl_tstp",
351 "ReadLine compatible suspend function",
353 el_set(e, EL_BIND, "^Z", "rl_tstp", NULL);
355 /* read settings from configuration file */
359 * Unfortunately, some applications really do use rl_point
360 * and rl_line_buffer directly.
362 _resize_fun(e, &rl_line_buffer);
366 (*rl_startup_hook)(NULL, 0);
373 * read one line from input stream and return it, chomping
374 * trailing newline (if there is any)
377 readline(const char *p)
380 const char * volatile prompt = p;
384 static int used_event_hook;
386 if (e == NULL || h == NULL)
391 (void)setjmp(topbuf);
393 /* update prompt accordingly to what has been passed */
394 if (rl_set_prompt(prompt) == -1)
397 if (rl_pre_input_hook)
398 (*rl_pre_input_hook)(NULL, 0);
400 if (rl_event_hook && !(e->el_flags&NO_TTY)) {
401 el_set(e, EL_GETCFN, _rl_event_read_char);
405 if (!rl_event_hook && used_event_hook) {
406 el_set(e, EL_GETCFN, EL_BUILTIN_GETCFN);
410 rl_already_prompted = 0;
412 /* get one line from input stream */
413 ret = el_gets(e, &count);
415 if (ret && count > 0) {
422 if (buf[lastidx] == '\n')
427 history(h, &ev, H_GETSIZE);
428 history_length = ev.num;
438 * is normally called before application starts to use
439 * history expansion functions
444 if (h == NULL || e == NULL)
450 * substitute ``what'' with ``with'', returning resulting string; if
451 * globally == 1, substitutes all occurrences of what, otherwise only the
455 _rl_compat_sub(const char *str, const char *what, const char *with,
460 size_t len, with_len, what_len;
463 with_len = strlen(with);
464 what_len = strlen(what);
466 /* calculate length we need for result */
469 if (*s == *what && !strncmp(s, what, what_len)) {
470 len += with_len - what_len;
477 r = result = el_malloc((len + 1) * sizeof(*r));
482 if (*s == *what && !strncmp(s, what, what_len)) {
483 (void)strncpy(r, with, with_len);
497 static char *last_search_pat; /* last !?pat[?] search pattern */
498 static char *last_search_match; /* last !?pat[?] that matched */
501 get_history_event(const char *cmd, int *cindex, int qchar)
503 int idx, sign, sub, num, begin, ret;
510 if (cmd[idx++] != history_expansion_char)
513 /* find out which event to take */
514 if (cmd[idx] == history_expansion_char || cmd[idx] == '\0') {
515 if (history(h, &ev, H_FIRST) != 0)
517 *cindex = cmd[idx]? (idx + 1):idx;
521 if (cmd[idx] == '-') {
526 if ('0' <= cmd[idx] && cmd[idx] <= '9') {
530 while (cmd[idx] && '0' <= cmd[idx] && cmd[idx] <= '9') {
531 num = num * 10 + cmd[idx] - '0';
535 num = history_length - num + 1;
537 if (!(rl_he = history_get(num)))
544 if (cmd[idx] == '?') {
550 if (cmd[idx] == '\n')
552 if (sub && cmd[idx] == '?')
554 if (!sub && (cmd[idx] == ':' || cmd[idx] == ' '
555 || cmd[idx] == '\t' || cmd[idx] == qchar))
559 len = (size_t)idx - (size_t)begin;
560 if (sub && cmd[idx] == '?')
562 if (sub && len == 0 && last_search_pat && *last_search_pat)
563 pat = last_search_pat;
567 if ((pat = el_malloc((len + 1) * sizeof(*pat))) == NULL)
569 (void)strncpy(pat, cmd + begin, len);
573 if (history(h, &ev, H_CURR) != 0) {
574 if (pat != last_search_pat)
581 if (pat != last_search_pat) {
583 el_free(last_search_pat);
584 last_search_pat = pat;
586 ret = history_search(pat, -1);
588 ret = history_search_prefix(pat, -1);
591 /* restore to end of list on failed search */
592 history(h, &ev, H_FIRST);
593 (void)fprintf(rl_outstream, "%s: Event not found\n", pat);
594 if (pat != last_search_pat)
600 if (last_search_match && last_search_match != pat)
601 el_free(last_search_match);
602 last_search_match = pat;
605 if (pat != last_search_pat)
608 if (history(h, &ev, H_CURR) != 0)
613 /* roll back to original position */
614 (void)history(h, &ev, H_SET, num);
620 * the real function doing history expansion - takes as argument command
621 * to do and data upon which the command should be executed
622 * does expansion the way I've understood readline documentation
624 * returns 0 if data was not modified, 1 if it was and 2 if the string
625 * should be only printed and not executed; in case of error,
626 * returns -1 and *result points to NULL
627 * it's callers responsibility to free() string returned in *result
630 _history_expand_command(const char *command, size_t offs, size_t cmdlen,
633 char *tmp, *search = NULL, *aptr;
634 const char *ptr, *cmd;
635 static char *from = NULL, *to = NULL;
636 int start, end, idx, has_mods = 0;
637 int p_on = 0, g_on = 0;
643 /* First get event specifier */
646 if (strchr(":^*$", command[offs + 1])) {
649 * "!:" is shorthand for "!!:".
650 * "!^", "!*" and "!$" are shorthand for
651 * "!!:^", "!!:*" and "!!:$" respectively.
653 str[0] = str[1] = '!';
655 ptr = get_history_event(str, &idx, 0);
656 idx = (command[offs + 1] == ':')? 1:0;
659 if (command[offs + 1] == '#') {
660 /* use command so far */
661 if ((aptr = el_malloc((offs + 1) * sizeof(*aptr)))
664 (void)strncpy(aptr, command, offs);
670 qchar = (offs > 0 && command[offs - 1] == '"')? '"':0;
671 ptr = get_history_event(command + offs, &idx, qchar);
673 has_mods = command[offs + (size_t)idx] == ':';
676 if (ptr == NULL && aptr == NULL)
680 *result = strdup(aptr ? aptr : ptr);
688 cmd = command + offs + idx + 1;
690 /* Now parse any word designators */
692 if (*cmd == '%') /* last word matched by ?pat? */
693 tmp = strdup(last_search_match? last_search_match:"");
694 else if (strchr("^*$-0123456789", *cmd)) {
697 start = end = 1, cmd++;
698 else if (*cmd == '$')
700 else if (*cmd == '*')
702 else if (*cmd == '-' || isdigit((unsigned char) *cmd)) {
704 while (*cmd && '0' <= *cmd && *cmd <= '9')
705 start = start * 10 + *cmd++ - '0';
708 if (isdigit((unsigned char) cmd[1])) {
711 while (*cmd && '0' <= *cmd && *cmd <= '9')
712 end = end * 10 + *cmd++ - '0';
713 } else if (cmd[1] == '$') {
720 } else if (*cmd == '*')
725 tmp = history_arg_extract(start, end, aptr? aptr:ptr);
727 (void)fprintf(rl_outstream, "%s: Bad word specifier",
728 command + offs + idx);
734 tmp = strdup(aptr? aptr:ptr);
739 if (*cmd == '\0' || ((size_t)(cmd - (command + offs)) >= cmdlen)) {
744 for (; *cmd; cmd++) {
747 else if (*cmd == 'h') { /* remove trailing path */
748 if ((aptr = strrchr(tmp, '/')) != NULL)
750 } else if (*cmd == 't') { /* remove leading path */
751 if ((aptr = strrchr(tmp, '/')) != NULL) {
752 aptr = strdup(aptr + 1);
756 } else if (*cmd == 'r') { /* remove trailing suffix */
757 if ((aptr = strrchr(tmp, '.')) != NULL)
759 } else if (*cmd == 'e') { /* remove all but suffix */
760 if ((aptr = strrchr(tmp, '.')) != NULL) {
765 } else if (*cmd == 'p') /* print only */
767 else if (*cmd == 'g')
769 else if (*cmd == 's' || *cmd == '&') {
770 char *what, *with, delim;
771 size_t len, from_len;
774 if (*cmd == '&' && (from == NULL || to == NULL))
776 else if (*cmd == 's') {
777 delim = *(++cmd), cmd++;
779 what = el_realloc(from, size * sizeof(*what));
786 for (; *cmd && *cmd != delim; cmd++) {
787 if (*cmd == '\\' && cmd[1] == delim)
791 nwhat = el_realloc(what,
808 from = strdup(search);
819 cmd++; /* shift after delim */
824 with = el_realloc(to, size * sizeof(*with));
831 from_len = strlen(from);
832 for (; *cmd && *cmd != delim; cmd++) {
833 if (len + from_len + 1 >= size) {
835 size += from_len + 1;
836 nwith = el_realloc(with,
837 size * sizeof(*nwith));
847 (void)strcpy(&with[len], from);
852 && (*(cmd + 1) == delim
853 || *(cmd + 1) == '&'))
861 aptr = _rl_compat_sub(tmp, from, to, g_on);
875 * csh-style history expansion
878 history_expand(char *str, char **output)
884 if (h == NULL || e == NULL)
887 if (history_expansion_char == 0) {
888 *output = strdup(str);
893 if (str[0] == history_subst_char) {
894 /* ^foo^foo2^ is equivalent to !!:s^foo^foo2^ */
895 *output = el_malloc((strlen(str) + 4 + 1) * sizeof(**output));
898 (*output)[0] = (*output)[1] = history_expansion_char;
901 (void)strcpy((*output) + 4, str);
904 *output = strdup(str);
909 #define ADD_STRING(what, len, fr) \
911 if (idx + len + 1 > size) { \
912 char *nresult = el_realloc(result, \
913 (size += len + 1) * sizeof(*nresult)); \
914 if (nresult == NULL) { \
916 if (/*CONSTCOND*/fr) \
922 (void)strncpy(&result[idx], what, len); \
924 result[idx] = '\0'; \
930 for (i = 0; str[i];) {
931 int qchar, loop_again;
932 size_t len, start, j;
938 for (; str[j]; j++) {
939 if (str[j] == '\\' &&
940 str[j + 1] == history_expansion_char) {
941 (void)strcpy(&str[j], &str[j + 1]);
945 if (isspace((unsigned char) str[j])
949 if (str[j] == history_expansion_char
950 && !strchr(history_no_expand_chars, str[j + 1])
951 && (!history_inhibit_expansion_function ||
952 (*history_inhibit_expansion_function)(str,
957 if (str[j] && loop_again) {
959 qchar = (j > 0 && str[j - 1] == '"' )? '"':0;
961 if (str[j] == history_expansion_char)
967 ADD_STRING(&str[start], len, 0);
969 if (str[i] == '\0' || str[i] != history_expansion_char) {
971 ADD_STRING(&str[i], len, 0);
978 ret = _history_expand_command (str, i, (j - i), &tmp);
979 if (ret > 0 && tmp) {
981 ADD_STRING(tmp, len, 1);
990 /* ret is 2 for "print only" option */
994 /* gdb 4.11 has been shipped with readline, where */
995 /* history_expand() returned -1 when the line */
996 /* should not be executed; in readline 2.1+ */
997 /* it should return 2 in such a case */
1008 * Return a string consisting of arguments of "str" from "start" to "end".
1011 history_arg_extract(int start, int end, const char *str)
1014 char **arr, *result = NULL;
1016 arr = history_tokenize(str);
1019 if (arr && *arr == NULL)
1022 for (max = 0; arr[max]; max++)
1031 end = (int)max + end + 1;
1035 if (start < 0 || end < 0 || (size_t)start > max ||
1036 (size_t)end > max || start > end)
1039 for (i = (size_t)start, len = 0; i <= (size_t)end; i++)
1040 len += strlen(arr[i]) + 1;
1042 result = el_malloc(len * sizeof(*result));
1046 for (i = (size_t)start, len = 0; i <= (size_t)end; i++) {
1047 (void)strcpy(result + len, arr[i]);
1048 len += strlen(arr[i]);
1049 if (i < (size_t)end)
1050 result[len++] = ' ';
1055 for (i = 0; arr[i]; i++)
1063 * Parse the string into individual tokens,
1064 * similar to how shell would do it.
1067 history_tokenize(const char *str)
1069 int size = 1, idx = 0, i, start;
1071 char **result = NULL, *temp, delim = '\0';
1073 for (i = 0; str[i];) {
1074 while (isspace((unsigned char) str[i]))
1078 if (str[i] == '\\') {
1079 if (str[i+1] != '\0')
1081 } else if (str[i] == delim)
1084 (isspace((unsigned char) str[i]) ||
1085 strchr("()<>;&|$", str[i])))
1087 else if (!delim && strchr("'`\"", str[i]))
1093 if (idx + 2 >= size) {
1096 nresult = el_realloc(result, (size_t)size * sizeof(*nresult));
1097 if (nresult == NULL) {
1103 len = (size_t)i - (size_t)start;
1104 temp = el_malloc((size_t)(len + 1) * sizeof(*temp));
1106 for (i = 0; i < idx; i++)
1111 (void)strncpy(temp, &str[start], len);
1113 result[idx++] = temp;
1123 * limit size of history record to ``max'' events
1126 stifle_history(int max)
1130 if (h == NULL || e == NULL)
1133 if (history(h, &ev, H_SETSIZE, max) == 0)
1134 max_input_history = max;
1139 * "unlimit" size of history - set the limit to maximum allowed int value
1142 unstifle_history(void)
1147 history(h, &ev, H_SETSIZE, INT_MAX);
1148 omax = max_input_history;
1149 max_input_history = INT_MAX;
1150 return omax; /* some value _must_ be returned */
1155 history_is_stifled(void)
1158 /* cannot return true answer */
1159 return max_input_history != INT_MAX;
1162 static const char _history_tmp_template[] = "/tmp/.historyXXXXXX";
1165 history_truncate_file (const char *filename, int nlines)
1169 char template[sizeof(_history_tmp_template)];
1177 if (filename == NULL && (filename = _default_history_file()) == NULL)
1179 if ((fp = fopen(filename, "r+")) == NULL)
1181 strcpy(template, _history_tmp_template);
1182 if ((fd = mkstemp(template)) == -1) {
1187 if ((tp = fdopen(fd, "r+")) == NULL) {
1194 if (fread(buf, sizeof(buf), (size_t)1, fp) != 1) {
1199 if (fseeko(fp, (off_t)sizeof(buf) * count, SEEK_SET) ==
1204 left = (ssize_t)fread(buf, (size_t)1, sizeof(buf), fp);
1212 } else if (fwrite(buf, (size_t)left, (size_t)1, tp)
1220 if (fwrite(buf, sizeof(buf), (size_t)1, tp) != 1) {
1228 cp = buf + left - 1;
1232 while (--cp >= buf) {
1234 if (--nlines == 0) {
1235 if (++cp >= buf + sizeof(buf)) {
1243 if (nlines <= 0 || count == 0)
1246 if (fseeko(tp, (off_t)sizeof(buf) * count, SEEK_SET) < 0) {
1250 if (fread(buf, sizeof(buf), (size_t)1, tp) != 1) {
1258 cp = buf + sizeof(buf);
1261 if (ret || nlines > 0)
1264 if (fseeko(fp, (off_t)0, SEEK_SET) == (off_t)-1) {
1269 if (fseeko(tp, (off_t)sizeof(buf) * count + (cp - buf), SEEK_SET) ==
1276 if ((left = (ssize_t)fread(buf, (size_t)1, sizeof(buf), tp)) == 0) {
1281 if (fwrite(buf, (size_t)left, (size_t)1, fp) != 1) {
1287 if((off = ftello(fp)) > 0)
1288 (void)ftruncate(fileno(fp), off);
1301 * read history from a file given
1304 read_history(const char *filename)
1308 if (h == NULL || e == NULL)
1310 if (filename == NULL && (filename = _default_history_file()) == NULL)
1312 return history(h, &ev, H_LOAD, filename) == -1 ?
1313 (errno ? errno : EINVAL) : 0;
1318 * write history to a file given
1321 write_history(const char *filename)
1325 if (h == NULL || e == NULL)
1327 if (filename == NULL && (filename = _default_history_file()) == NULL)
1329 return history(h, &ev, H_SAVE, filename) == -1 ?
1330 (errno ? errno : EINVAL) : 0;
1335 * returns history ``num''th event
1337 * returned pointer points to static variable
1340 history_get(int num)
1342 static HIST_ENTRY she;
1346 if (h == NULL || e == NULL)
1349 /* save current position */
1350 if (history(h, &ev, H_CURR) != 0)
1354 /* start from the oldest */
1355 if (history(h, &ev, H_LAST) != 0)
1356 return NULL; /* error */
1358 /* look forwards for event matching specified offset */
1359 if (history(h, &ev, H_NEXT_EVDATA, num, &she.data))
1364 /* restore pointer to where it was */
1365 (void)history(h, &ev, H_SET, curr_num);
1372 * add the line to history table
1375 add_history(const char *line)
1382 if (h == NULL || e == NULL)
1385 (void)history(h, &ev, H_ENTER, line);
1386 if (history(h, &ev, H_GETSIZE) == 0)
1387 history_length = ev.num;
1389 return !(history_length > 0); /* return 0 if all is okay */
1394 * remove the specified entry from the history list and return it.
1397 remove_history(int num)
1402 if (h == NULL || e == NULL)
1405 if ((he = el_malloc(sizeof(*he))) == NULL)
1408 if (history(h, &ev, H_DELDATA, num, &he->data) != 0) {
1414 if (history(h, &ev, H_GETSIZE) == 0)
1415 history_length = ev.num;
1422 * replace the line and data of the num-th entry
1425 replace_history_entry(int num, const char *line, histdata_t data)
1431 if (h == NULL || e == NULL)
1434 /* save current position */
1435 if (history(h, &ev, H_CURR) != 0)
1439 /* start from the oldest */
1440 if (history(h, &ev, H_LAST) != 0)
1441 return NULL; /* error */
1443 if ((he = el_malloc(sizeof(*he))) == NULL)
1446 /* look forwards for event matching specified offset */
1447 if (history(h, &ev, H_NEXT_EVDATA, num, &he->data))
1450 he->line = strdup(ev.str);
1451 if (he->line == NULL)
1454 if (history(h, &ev, H_REPLACE, line, data))
1457 /* restore pointer to where it was */
1458 if (history(h, &ev, H_SET, curr_num))
1468 * clear the history list - delete all entries
1475 (void)history(h, &ev, H_CLEAR);
1481 * returns offset of the current history event
1489 if (history(h, &ev, H_CURR) != 0)
1493 (void)history(h, &ev, H_FIRST);
1495 while (ev.num != curr_num && history(h, &ev, H_NEXT) == 0)
1503 * returns current history event or NULL if there is no such event
1506 current_history(void)
1509 return _move_history(H_CURR);
1514 * returns total number of bytes history events' data are using
1517 history_total_bytes(void)
1523 if (history(h, &ev, H_CURR) != 0)
1527 (void)history(h, &ev, H_FIRST);
1530 size += strlen(ev.str) * sizeof(*ev.str);
1531 while (history(h, &ev, H_NEXT) == 0);
1533 /* get to the same position as before */
1534 history(h, &ev, H_PREV_EVENT, curr_num);
1541 * sets the position in the history list to ``pos''
1544 history_set_pos(int pos)
1549 if (pos >= history_length || pos < 0)
1552 (void)history(h, &ev, H_CURR);
1556 * use H_DELDATA to set to nth history (without delete) by passing
1559 if (history(h, &ev, H_DELDATA, pos, (void **)-1)) {
1560 (void)history(h, &ev, H_SET, curr_num);
1568 * returns previous event in history and shifts pointer accordingly
1571 previous_history(void)
1574 return _move_history(H_PREV);
1579 * returns next event in history and shifts pointer accordingly
1585 return _move_history(H_NEXT);
1590 * searches for first history event containing the str
1593 history_search(const char *str, int direction)
1599 if (history(h, &ev, H_CURR) != 0)
1604 if ((strp = strstr(ev.str, str)) != NULL)
1605 return (int)(strp - ev.str);
1606 if (history(h, &ev, direction < 0 ? H_NEXT:H_PREV) != 0)
1609 (void)history(h, &ev, H_SET, curr_num);
1615 * searches for first history event beginning with str
1618 history_search_prefix(const char *str, int direction)
1622 return (history(h, &ev, direction < 0 ?
1623 H_PREV_STR : H_NEXT_STR, str));
1628 * search for event in history containing str, starting at offset
1629 * abs(pos); continue backward, if pos<0, forward otherwise
1633 history_search_pos(const char *str,
1634 int direction __attribute__((__unused__)), int pos)
1639 off = (pos > 0) ? pos : -pos;
1640 pos = (pos > 0) ? 1 : -1;
1642 if (history(h, &ev, H_CURR) != 0)
1646 if (history_set_pos(off) != 0 || history(h, &ev, H_CURR) != 0)
1650 if (strstr(ev.str, str))
1652 if (history(h, &ev, (pos < 0) ? H_PREV : H_NEXT) != 0)
1656 /* set "current" pointer back to previous state */
1657 (void)history(h, &ev,
1658 pos < 0 ? H_NEXT_EVENT : H_PREV_EVENT, curr_num);
1664 /********************************/
1665 /* completion functions */
1668 tilde_expand(char *name)
1670 return fn_tilde_expand(name);
1674 filename_completion_function(const char *name, int state)
1676 return fn_filename_completion_function(name, state);
1680 * a completion generator for usernames; returns _first_ username
1681 * which starts with supplied text
1682 * text contains a partial username preceded by random character
1683 * (usually '~'); state resets search from start (??? should we do that anyway)
1684 * it's callers responsibility to free returned value
1687 username_completion_function(const char *text, int state)
1689 struct passwd *pass = NULL;
1691 if (text[0] == '\0')
1701 (pass = getpwent()) != NULL
1702 && text[0] == pass->pw_name[0]
1703 && strcmp(text, pass->pw_name) == 0)
1710 return strdup(pass->pw_name);
1715 * el-compatible wrapper to send TSTP on ^Z
1718 static unsigned char
1719 _el_rl_tstp(EditLine *el __attribute__((__unused__)), int ch __attribute__((__unused__)))
1721 (void)kill(0, SIGTSTP);
1726 * Display list of strings in columnar format on readline's output stream.
1727 * 'matches' is list of strings, 'len' is number of strings in 'matches',
1728 * 'max' is maximum length of string in 'matches'.
1731 rl_display_match_list(char **matches, int len, int max)
1734 fn_display_match_list(e, matches, (size_t)len, (size_t)max);
1739 _rl_completion_append_character_function(const char *dummy
1740 __attribute__((__unused__)))
1743 buf[0] = (char)rl_completion_append_character;
1750 * complete word at current point
1754 rl_complete(int ignore __attribute__((__unused__)), int invoking_key)
1757 static ct_buffer_t wbreak_conv, sprefix_conv;
1761 if (h == NULL || e == NULL)
1764 if (rl_inhibit_completion) {
1766 arr[0] = (char)invoking_key;
1768 el_insertstr(e, arr);
1772 if (rl_completion_word_break_hook != NULL)
1773 breakchars = (*rl_completion_word_break_hook)();
1775 breakchars = rl_basic_word_break_characters;
1777 /* Just look at how many global variables modify this operation! */
1778 return fn_complete(e,
1779 (CPFunction *)rl_completion_entry_function,
1780 rl_attempted_completion_function,
1781 ct_decode_string(rl_basic_word_break_characters, &wbreak_conv),
1782 ct_decode_string(breakchars, &sprefix_conv),
1783 _rl_completion_append_character_function,
1784 (size_t)rl_completion_query_items,
1785 &rl_completion_type, &rl_attempted_completion_over,
1786 &rl_point, &rl_end);
1793 static unsigned char
1794 _el_rl_complete(EditLine *el __attribute__((__unused__)), int ch)
1796 return (unsigned char)rl_complete(0, ch);
1800 * misc other functions
1804 * bind key c to readline-type function func
1807 rl_bind_key(int c, rl_command_func_t *func)
1811 if (h == NULL || e == NULL)
1814 if (func == rl_insert) {
1815 /* XXX notice there is no range checking of ``c'' */
1816 e->el_map.key[c] = ED_INSERT;
1824 * read one key from input - handles chars pushed back
1825 * to input stream also
1830 char fooarr[2 * sizeof(int)];
1832 if (e == NULL || h == NULL)
1835 return el_getc(e, fooarr);
1840 * reset the terminal
1844 rl_reset_terminal(const char *p __attribute__((__unused__)))
1847 if (h == NULL || e == NULL)
1854 * insert character ``c'' back into input stream, ``count'' times
1857 rl_insert(int count, int c)
1861 if (h == NULL || e == NULL)
1864 /* XXX - int -> char conversion can lose on multichars */
1868 for (; count > 0; count--)
1875 rl_insert_text(const char *text)
1877 if (!text || *text == 0)
1880 if (h == NULL || e == NULL)
1883 if (el_insertstr(e, text) < 0)
1885 return (int)strlen(text);
1890 rl_newline(int count __attribute__((__unused__)),
1891 int c __attribute__((__unused__)))
1894 * Readline-4.0 appears to ignore the args.
1896 return rl_insert(1, '\n');
1900 static unsigned char
1901 rl_bind_wrapper(EditLine *el __attribute__((__unused__)), unsigned char c)
1910 /* If rl_done was set by the above call, deal with it here */
1918 rl_add_defun(const char *name, Function *fun, int c)
1921 if ((size_t)c >= sizeof(map) / sizeof(map[0]) || c < 0)
1923 map[(unsigned char)c] = fun;
1924 el_set(e, EL_ADDFN, name, name, rl_bind_wrapper);
1925 vis(dest, c, VIS_WHITE|VIS_NOSLASH, 0);
1926 el_set(e, EL_BIND, dest, name, NULL);
1931 rl_callback_read_char(void)
1933 int count = 0, done = 0;
1934 const char *buf = el_gets(e, &count);
1937 if (buf == NULL || count-- <= 0)
1939 if (count == 0 && buf[0] == e->el_tty.t_c[TS_IO][C_EOF])
1941 if (buf[count] == '\n' || buf[count] == '\r')
1944 if (done && rl_linefunc != NULL) {
1945 el_set(e, EL_UNBUFFERED, 0);
1947 if ((wbuf = strdup(buf)) != NULL)
1951 (*(void (*)(const char *))rl_linefunc)(wbuf);
1952 //el_set(e, EL_UNBUFFERED, 1);
1957 rl_callback_handler_install(const char *prompt, VCPFunction *linefunc)
1962 (void)rl_set_prompt(prompt);
1963 rl_linefunc = linefunc;
1964 el_set(e, EL_UNBUFFERED, 1);
1968 rl_callback_handler_remove(void)
1970 el_set(e, EL_UNBUFFERED, 0);
1978 a[0] = (char)e->el_tty.t_c[TS_IO][C_REPRINT];
1984 rl_get_previous_history(int count, int key)
1996 rl_prep_terminal(int meta_flag __attribute__((__unused__)))
1998 el_set(e, EL_PREP_TERM, 1);
2002 rl_deprep_terminal(void)
2004 el_set(e, EL_PREP_TERM, 0);
2008 rl_read_init_file(const char *s)
2010 return el_source(e, s);
2014 rl_parse_and_bind(const char *line)
2020 tok = tok_init(NULL);
2021 tok_str(tok, line, &argc, &argv);
2022 argc = el_parse(e, argc, argv);
2024 return argc ? 1 : 0;
2028 rl_variable_bind(const char *var, const char *value)
2031 * The proper return value is undocument, but this is what the
2032 * readline source seems to do.
2034 return el_set(e, EL_BIND, "", var, value, NULL) == -1 ? 1 : 0;
2038 rl_stuff_char(int c)
2044 el_insertstr(e, buf);
2048 _rl_event_read_char(EditLine *el, char *cp)
2051 ssize_t num_read = 0;
2054 while (rl_event_hook) {
2058 #if defined(FIONREAD)
2059 if (ioctl(el->el_infd, FIONREAD, &n) < 0)
2062 num_read = read(el->el_infd, cp, (size_t)1);
2065 #elif defined(F_SETFL) && defined(O_NDELAY)
2066 if ((n = fcntl(el->el_infd, F_GETFL, 0)) < 0)
2068 if (fcntl(el->el_infd, F_SETFL, n|O_NDELAY) < 0)
2070 num_read = read(el->el_infd, cp, 1);
2071 if (fcntl(el->el_infd, F_SETFL, n))
2074 /* not non-blocking, but what you gonna do? */
2075 num_read = read(el->el_infd, cp, 1);
2079 if (num_read < 0 && errno == EAGAIN)
2086 el_set(el, EL_GETCFN, EL_BUILTIN_GETCFN);
2087 return (int)num_read;
2091 _rl_update_pos(void)
2093 const LineInfo *li = el_line(e);
2095 rl_point = (int)(li->cursor - li->buffer);
2096 rl_end = (int)(li->lastchar - li->buffer);
2100 rl_get_screen_size(int *rows, int *cols)
2103 el_get(e, EL_GETTC, "li", rows, NULL);
2105 el_get(e, EL_GETTC, "co", cols, NULL);
2109 rl_set_screen_size(int rows, int cols)
2112 (void)snprintf(buf, sizeof(buf), "%d", rows);
2113 el_set(e, EL_SETTC, "li", buf, NULL);
2114 (void)snprintf(buf, sizeof(buf), "%d", cols);
2115 el_set(e, EL_SETTC, "co", buf, NULL);
2119 rl_completion_matches(const char *str, rl_compentry_func_t *fun)
2121 size_t len, max, i, j, min;
2122 char **list, *match, *a, *b;
2126 if ((list = el_malloc(max * sizeof(*list))) == NULL)
2129 while ((match = (*fun)(str, (int)(len - 1))) != NULL) {
2130 list[len++] = match;
2134 if ((nl = el_realloc(list, max * sizeof(*nl))) == NULL)
2143 if ((list[0] = strdup(list[1])) == NULL)
2147 qsort(&list[1], len - 1, sizeof(*list),
2148 (int (*)(const void *, const void *)) strcmp);
2150 for (i = 1, a = list[i]; i < len - 1; i++, a = b) {
2152 for (j = 0; a[j] && a[j] == b[j]; j++)
2157 if (min == 0 && *str) {
2158 if ((list[0] = strdup(str)) == NULL)
2161 if ((list[0] = el_malloc((min + 1) * sizeof(*list[0]))) == NULL)
2163 (void)memcpy(list[0], list[1], min);
2164 list[0][min] = '\0';
2174 rl_filename_completion_function (const char *text, int state)
2176 return fn_filename_completion_function(text, state);
2180 rl_forced_update_display(void)
2182 el_set(e, EL_REFRESH);
2186 _rl_abort_internal(void)
2194 _rl_qsort_string_compare(char **s1, char **s2)
2196 return strcoll(*s1, *s2);
2200 history_get_history_state(void)
2204 if ((hs = el_malloc(sizeof(*hs))) == NULL)
2206 hs->length = history_length;
2212 rl_kill_text(int from __attribute__((__unused__)),
2213 int to __attribute__((__unused__)))
2219 rl_make_bare_keymap(void)
2232 rl_set_keymap(Keymap k __attribute__((__unused__)))
2238 rl_generic_bind(int type __attribute__((__unused__)),
2239 const char * keyseq __attribute__((__unused__)),
2240 const char * data __attribute__((__unused__)),
2241 Keymap k __attribute__((__unused__)))
2248 rl_bind_key_in_map(int key __attribute__((__unused__)),
2249 rl_command_func_t *fun __attribute__((__unused__)),
2250 Keymap k __attribute__((__unused__)))
2255 /* unsupported, but needed by python */
2257 rl_cleanup_after_signal(void)
2262 rl_on_new_line(void)
2268 rl_free_line_state(void)