1 /* $NetBSD: readline.c,v 1.100 2011/11/18 20:38:42 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.100 2011/11/18 20:38:42 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 CPPFunction *rl_attempted_completion_function = NULL;
108 Function *rl_pre_input_hook = NULL;
109 Function *rl_startup1_hook = NULL;
110 int (*rl_getc_function)(FILE *) = NULL;
111 char *rl_terminal_name = NULL;
112 int rl_already_prompted = 0;
113 int rl_filename_completion_desired = 0;
114 int rl_ignore_completion_duplicates = 0;
115 int rl_catch_signals = 1;
116 int readline_echoing_p = 1;
117 int _rl_print_completions_horizontally = 0;
118 VFunction *rl_redisplay_function = NULL;
119 Function *rl_startup_hook = NULL;
120 VFunction *rl_completion_display_matches_hook = NULL;
121 VFunction *rl_prep_term_function = (VFunction *)rl_prep_terminal;
122 VFunction *rl_deprep_term_function = (VFunction *)rl_deprep_terminal;
123 KEYMAP_ENTRY_ARRAY emacs_meta_keymap;
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 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 (history(h, &ev, op) != 0)
205 * read one key from user defined input function
209 _getc_function(EditLine *el __attribute__((__unused__)), char *c)
213 i = (*rl_getc_function)(NULL);
221 _resize_fun(EditLine *el, void *a)
227 /* a cheesy way to get rid of const cast. */
228 *ap = memchr(li->buffer, *li->buffer, (size_t)1);
232 _default_history_file(void)
235 static char path[PATH_MAX];
239 if ((p = getpwuid(getuid())) == NULL)
241 (void)snprintf(path, sizeof(path), "%s/.history", p->pw_dir);
246 * READLINE compatibility stuff
253 rl_set_prompt(const char *prompt)
259 if (rl_prompt != NULL && strcmp(rl_prompt, prompt) == 0)
263 rl_prompt = strdup(prompt);
264 if (rl_prompt == NULL)
267 while ((p = strchr(rl_prompt, RL_PROMPT_END_IGNORE)) != NULL)
268 *p = RL_PROMPT_START_IGNORE;
274 * initialize rl compat stuff
291 rl_outstream = stdout;
294 * See if we don't really want to run the editor
296 if (tcgetattr(fileno(rl_instream), &t) != -1 && (t.c_lflag & ECHO) == 0)
299 e = el_init(rl_readline_name, rl_instream, rl_outstream, stderr);
302 el_set(e, EL_EDITMODE, 0);
308 history(h, &ev, H_SETSIZE, INT_MAX); /* unlimited */
310 max_input_history = INT_MAX;
311 el_set(e, EL_HIST, history, h);
313 /* Setup resize function */
314 el_set(e, EL_RESIZE, _resize_fun, &rl_line_buffer);
316 /* setup getc function if valid */
317 if (rl_getc_function)
318 el_set(e, EL_GETCFN, _getc_function);
320 /* for proper prompt printing in readline() */
321 if (rl_set_prompt("") == -1) {
326 el_set(e, EL_PROMPT, _get_prompt, RL_PROMPT_START_IGNORE);
327 el_set(e, EL_SIGNAL, rl_catch_signals);
329 /* set default mode to "emacs"-style and read setting afterwards */
330 /* so this can be overriden */
331 el_set(e, EL_EDITOR, "emacs");
332 if (rl_terminal_name != NULL)
333 el_set(e, EL_TERMINAL, rl_terminal_name);
335 el_get(e, EL_TERMINAL, &rl_terminal_name);
338 * Word completion - this has to go AFTER rebinding keys
341 el_set(e, EL_ADDFN, "rl_complete",
342 "ReadLine compatible completion function",
344 el_set(e, EL_BIND, "^I", "rl_complete", NULL);
347 * Send TSTP when ^Z is pressed.
349 el_set(e, EL_ADDFN, "rl_tstp",
350 "ReadLine compatible suspend function",
352 el_set(e, EL_BIND, "^Z", "rl_tstp", NULL);
354 /* read settings from configuration file */
358 * Unfortunately, some applications really do use rl_point
359 * and rl_line_buffer directly.
361 _resize_fun(e, &rl_line_buffer);
365 (*rl_startup_hook)(NULL, 0);
372 * read one line from input stream and return it, chomping
373 * trailing newline (if there is any)
376 readline(const char *p)
379 const char * volatile prompt = p;
383 static int used_event_hook;
385 if (e == NULL || h == NULL)
390 (void)setjmp(topbuf);
392 /* update prompt accordingly to what has been passed */
393 if (rl_set_prompt(prompt) == -1)
396 if (rl_pre_input_hook)
397 (*rl_pre_input_hook)(NULL, 0);
399 if (rl_event_hook && !(e->el_flags&NO_TTY)) {
400 el_set(e, EL_GETCFN, _rl_event_read_char);
404 if (!rl_event_hook && used_event_hook) {
405 el_set(e, EL_GETCFN, EL_BUILTIN_GETCFN);
409 rl_already_prompted = 0;
411 /* get one line from input stream */
412 ret = el_gets(e, &count);
414 if (ret && count > 0) {
421 if (buf[lastidx] == '\n')
426 history(h, &ev, H_GETSIZE);
427 history_length = ev.num;
437 * is normally called before application starts to use
438 * history expansion functions
443 if (h == NULL || e == NULL)
449 * substitute ``what'' with ``with'', returning resulting string; if
450 * globally == 1, substitutes all occurrences of what, otherwise only the
454 _rl_compat_sub(const char *str, const char *what, const char *with,
459 size_t len, with_len, what_len;
462 with_len = strlen(with);
463 what_len = strlen(what);
465 /* calculate length we need for result */
468 if (*s == *what && !strncmp(s, what, what_len)) {
469 len += with_len - what_len;
476 r = result = el_malloc((len + 1) * sizeof(*r));
481 if (*s == *what && !strncmp(s, what, what_len)) {
482 (void)strncpy(r, with, with_len);
496 static char *last_search_pat; /* last !?pat[?] search pattern */
497 static char *last_search_match; /* last !?pat[?] that matched */
500 get_history_event(const char *cmd, int *cindex, int qchar)
502 int idx, sign, sub, num, begin, ret;
509 if (cmd[idx++] != history_expansion_char)
512 /* find out which event to take */
513 if (cmd[idx] == history_expansion_char || cmd[idx] == '\0') {
514 if (history(h, &ev, H_FIRST) != 0)
516 *cindex = cmd[idx]? (idx + 1):idx;
520 if (cmd[idx] == '-') {
525 if ('0' <= cmd[idx] && cmd[idx] <= '9') {
529 while (cmd[idx] && '0' <= cmd[idx] && cmd[idx] <= '9') {
530 num = num * 10 + cmd[idx] - '0';
534 num = history_length - num + 1;
536 if (!(rl_he = history_get(num)))
543 if (cmd[idx] == '?') {
549 if (cmd[idx] == '\n')
551 if (sub && cmd[idx] == '?')
553 if (!sub && (cmd[idx] == ':' || cmd[idx] == ' '
554 || cmd[idx] == '\t' || cmd[idx] == qchar))
558 len = (size_t)idx - (size_t)begin;
559 if (sub && cmd[idx] == '?')
561 if (sub && len == 0 && last_search_pat && *last_search_pat)
562 pat = last_search_pat;
566 if ((pat = el_malloc((len + 1) * sizeof(*pat))) == NULL)
568 (void)strncpy(pat, cmd + begin, len);
572 if (history(h, &ev, H_CURR) != 0) {
573 if (pat != last_search_pat)
580 if (pat != last_search_pat) {
582 el_free(last_search_pat);
583 last_search_pat = pat;
585 ret = history_search(pat, -1);
587 ret = history_search_prefix(pat, -1);
590 /* restore to end of list on failed search */
591 history(h, &ev, H_FIRST);
592 (void)fprintf(rl_outstream, "%s: Event not found\n", pat);
593 if (pat != last_search_pat)
599 if (last_search_match && last_search_match != pat)
600 el_free(last_search_match);
601 last_search_match = pat;
604 if (pat != last_search_pat)
607 if (history(h, &ev, H_CURR) != 0)
612 /* roll back to original position */
613 (void)history(h, &ev, H_SET, num);
619 * the real function doing history expansion - takes as argument command
620 * to do and data upon which the command should be executed
621 * does expansion the way I've understood readline documentation
623 * returns 0 if data was not modified, 1 if it was and 2 if the string
624 * should be only printed and not executed; in case of error,
625 * returns -1 and *result points to NULL
626 * it's callers responsibility to free() string returned in *result
629 _history_expand_command(const char *command, size_t offs, size_t cmdlen,
632 char *tmp, *search = NULL, *aptr;
633 const char *ptr, *cmd;
634 static char *from = NULL, *to = NULL;
635 int start, end, idx, has_mods = 0;
636 int p_on = 0, g_on = 0;
642 /* First get event specifier */
645 if (strchr(":^*$", command[offs + 1])) {
648 * "!:" is shorthand for "!!:".
649 * "!^", "!*" and "!$" are shorthand for
650 * "!!:^", "!!:*" and "!!:$" respectively.
652 str[0] = str[1] = '!';
654 ptr = get_history_event(str, &idx, 0);
655 idx = (command[offs + 1] == ':')? 1:0;
658 if (command[offs + 1] == '#') {
659 /* use command so far */
660 if ((aptr = el_malloc((offs + 1) * sizeof(*aptr)))
663 (void)strncpy(aptr, command, offs);
669 qchar = (offs > 0 && command[offs - 1] == '"')? '"':0;
670 ptr = get_history_event(command + offs, &idx, qchar);
672 has_mods = command[offs + (size_t)idx] == ':';
675 if (ptr == NULL && aptr == NULL)
679 *result = strdup(aptr ? aptr : ptr);
687 cmd = command + offs + idx + 1;
689 /* Now parse any word designators */
691 if (*cmd == '%') /* last word matched by ?pat? */
692 tmp = strdup(last_search_match? last_search_match:"");
693 else if (strchr("^*$-0123456789", *cmd)) {
696 start = end = 1, cmd++;
697 else if (*cmd == '$')
699 else if (*cmd == '*')
701 else if (*cmd == '-' || isdigit((unsigned char) *cmd)) {
703 while (*cmd && '0' <= *cmd && *cmd <= '9')
704 start = start * 10 + *cmd++ - '0';
707 if (isdigit((unsigned char) cmd[1])) {
710 while (*cmd && '0' <= *cmd && *cmd <= '9')
711 end = end * 10 + *cmd++ - '0';
712 } else if (cmd[1] == '$') {
719 } else if (*cmd == '*')
724 tmp = history_arg_extract(start, end, aptr? aptr:ptr);
726 (void)fprintf(rl_outstream, "%s: Bad word specifier",
727 command + offs + idx);
733 tmp = strdup(aptr? aptr:ptr);
738 if (*cmd == '\0' || ((size_t)(cmd - (command + offs)) >= cmdlen)) {
743 for (; *cmd; cmd++) {
746 else if (*cmd == 'h') { /* remove trailing path */
747 if ((aptr = strrchr(tmp, '/')) != NULL)
749 } else if (*cmd == 't') { /* remove leading path */
750 if ((aptr = strrchr(tmp, '/')) != NULL) {
751 aptr = strdup(aptr + 1);
755 } else if (*cmd == 'r') { /* remove trailing suffix */
756 if ((aptr = strrchr(tmp, '.')) != NULL)
758 } else if (*cmd == 'e') { /* remove all but suffix */
759 if ((aptr = strrchr(tmp, '.')) != NULL) {
764 } else if (*cmd == 'p') /* print only */
766 else if (*cmd == 'g')
768 else if (*cmd == 's' || *cmd == '&') {
769 char *what, *with, delim;
770 size_t len, from_len;
773 if (*cmd == '&' && (from == NULL || to == NULL))
775 else if (*cmd == 's') {
776 delim = *(++cmd), cmd++;
778 what = el_realloc(from, size * sizeof(*what));
785 for (; *cmd && *cmd != delim; cmd++) {
786 if (*cmd == '\\' && cmd[1] == delim)
790 nwhat = el_realloc(what,
807 from = strdup(search);
818 cmd++; /* shift after delim */
823 with = el_realloc(to, size * sizeof(*with));
830 from_len = strlen(from);
831 for (; *cmd && *cmd != delim; cmd++) {
832 if (len + from_len + 1 >= size) {
834 size += from_len + 1;
835 nwith = el_realloc(with,
836 size * sizeof(*nwith));
846 (void)strcpy(&with[len], from);
851 && (*(cmd + 1) == delim
852 || *(cmd + 1) == '&'))
860 aptr = _rl_compat_sub(tmp, from, to, g_on);
874 * csh-style history expansion
877 history_expand(char *str, char **output)
883 if (h == NULL || e == NULL)
886 if (history_expansion_char == 0) {
887 *output = strdup(str);
892 if (str[0] == history_subst_char) {
893 /* ^foo^foo2^ is equivalent to !!:s^foo^foo2^ */
894 *output = el_malloc((strlen(str) + 4 + 1) * sizeof(**output));
897 (*output)[0] = (*output)[1] = history_expansion_char;
900 (void)strcpy((*output) + 4, str);
903 *output = strdup(str);
908 #define ADD_STRING(what, len, fr) \
910 if (idx + len + 1 > size) { \
911 char *nresult = el_realloc(result, \
912 (size += len + 1) * sizeof(*nresult)); \
913 if (nresult == NULL) { \
915 if (/*CONSTCOND*/fr) \
921 (void)strncpy(&result[idx], what, len); \
923 result[idx] = '\0'; \
929 for (i = 0; str[i];) {
930 int qchar, loop_again;
931 size_t len, start, j;
937 for (; str[j]; j++) {
938 if (str[j] == '\\' &&
939 str[j + 1] == history_expansion_char) {
940 (void)strcpy(&str[j], &str[j + 1]);
944 if (isspace((unsigned char) str[j])
948 if (str[j] == history_expansion_char
949 && !strchr(history_no_expand_chars, str[j + 1])
950 && (!history_inhibit_expansion_function ||
951 (*history_inhibit_expansion_function)(str,
956 if (str[j] && loop_again) {
958 qchar = (j > 0 && str[j - 1] == '"' )? '"':0;
960 if (str[j] == history_expansion_char)
966 ADD_STRING(&str[start], len, 0);
968 if (str[i] == '\0' || str[i] != history_expansion_char) {
970 ADD_STRING(&str[i], len, 0);
977 ret = _history_expand_command (str, i, (j - i), &tmp);
978 if (ret > 0 && tmp) {
980 ADD_STRING(tmp, len, 1);
989 /* ret is 2 for "print only" option */
993 /* gdb 4.11 has been shipped with readline, where */
994 /* history_expand() returned -1 when the line */
995 /* should not be executed; in readline 2.1+ */
996 /* it should return 2 in such a case */
1007 * Return a string consisting of arguments of "str" from "start" to "end".
1010 history_arg_extract(int start, int end, const char *str)
1013 char **arr, *result = NULL;
1015 arr = history_tokenize(str);
1018 if (arr && *arr == NULL)
1021 for (max = 0; arr[max]; max++)
1030 end = (int)max + end + 1;
1034 if (start < 0 || end < 0 || (size_t)start > max ||
1035 (size_t)end > max || start > end)
1038 for (i = (size_t)start, len = 0; i <= (size_t)end; i++)
1039 len += strlen(arr[i]) + 1;
1041 result = el_malloc(len * sizeof(*result));
1045 for (i = (size_t)start, len = 0; i <= (size_t)end; i++) {
1046 (void)strcpy(result + len, arr[i]);
1047 len += strlen(arr[i]);
1048 if (i < (size_t)end)
1049 result[len++] = ' ';
1054 for (i = 0; arr[i]; i++)
1062 * Parse the string into individual tokens,
1063 * similar to how shell would do it.
1066 history_tokenize(const char *str)
1068 int size = 1, idx = 0, i, start;
1070 char **result = NULL, *temp, delim = '\0';
1072 for (i = 0; str[i];) {
1073 while (isspace((unsigned char) str[i]))
1077 if (str[i] == '\\') {
1078 if (str[i+1] != '\0')
1080 } else if (str[i] == delim)
1083 (isspace((unsigned char) str[i]) ||
1084 strchr("()<>;&|$", str[i])))
1086 else if (!delim && strchr("'`\"", str[i]))
1092 if (idx + 2 >= size) {
1095 nresult = el_realloc(result, (size_t)size * sizeof(*nresult));
1096 if (nresult == NULL) {
1102 len = (size_t)i - (size_t)start;
1103 temp = el_malloc((size_t)(len + 1) * sizeof(*temp));
1105 for (i = 0; i < idx; i++)
1110 (void)strncpy(temp, &str[start], len);
1112 result[idx++] = temp;
1122 * limit size of history record to ``max'' events
1125 stifle_history(int max)
1129 if (h == NULL || e == NULL)
1132 if (history(h, &ev, H_SETSIZE, max) == 0)
1133 max_input_history = max;
1138 * "unlimit" size of history - set the limit to maximum allowed int value
1141 unstifle_history(void)
1146 history(h, &ev, H_SETSIZE, INT_MAX);
1147 omax = max_input_history;
1148 max_input_history = INT_MAX;
1149 return omax; /* some value _must_ be returned */
1154 history_is_stifled(void)
1157 /* cannot return true answer */
1158 return max_input_history != INT_MAX;
1161 static const char _history_tmp_template[] = "/tmp/.historyXXXXXX";
1164 history_truncate_file (const char *filename, int nlines)
1168 char template[sizeof(_history_tmp_template)];
1176 if (filename == NULL && (filename = _default_history_file()) == NULL)
1178 if ((fp = fopen(filename, "r+")) == NULL)
1180 strcpy(template, _history_tmp_template);
1181 if ((fd = mkstemp(template)) == -1) {
1186 if ((tp = fdopen(fd, "r+")) == NULL) {
1193 if (fread(buf, sizeof(buf), (size_t)1, fp) != 1) {
1198 if (fseeko(fp, (off_t)sizeof(buf) * count, SEEK_SET) ==
1203 left = (ssize_t)fread(buf, (size_t)1, sizeof(buf), fp);
1211 } else if (fwrite(buf, (size_t)left, (size_t)1, tp)
1219 if (fwrite(buf, sizeof(buf), (size_t)1, tp) != 1) {
1227 cp = buf + left - 1;
1231 while (--cp >= buf) {
1233 if (--nlines == 0) {
1234 if (++cp >= buf + sizeof(buf)) {
1242 if (nlines <= 0 || count == 0)
1245 if (fseeko(tp, (off_t)sizeof(buf) * count, SEEK_SET) < 0) {
1249 if (fread(buf, sizeof(buf), (size_t)1, tp) != 1) {
1257 cp = buf + sizeof(buf);
1260 if (ret || nlines > 0)
1263 if (fseeko(fp, (off_t)0, SEEK_SET) == (off_t)-1) {
1268 if (fseeko(tp, (off_t)sizeof(buf) * count + (cp - buf), SEEK_SET) ==
1275 if ((left = (ssize_t)fread(buf, (size_t)1, sizeof(buf), tp)) == 0) {
1280 if (fwrite(buf, (size_t)left, (size_t)1, fp) != 1) {
1286 if((off = ftello(fp)) > 0)
1287 (void)ftruncate(fileno(fp), off);
1300 * read history from a file given
1303 read_history(const char *filename)
1307 if (h == NULL || e == NULL)
1309 if (filename == NULL && (filename = _default_history_file()) == NULL)
1311 return history(h, &ev, H_LOAD, filename) == -1 ?
1312 (errno ? errno : EINVAL) : 0;
1317 * write history to a file given
1320 write_history(const char *filename)
1324 if (h == NULL || e == NULL)
1326 if (filename == NULL && (filename = _default_history_file()) == NULL)
1328 return history(h, &ev, H_SAVE, filename) == -1 ?
1329 (errno ? errno : EINVAL) : 0;
1334 * returns history ``num''th event
1336 * returned pointer points to static variable
1339 history_get(int num)
1341 static HIST_ENTRY she;
1345 if (h == NULL || e == NULL)
1348 /* save current position */
1349 if (history(h, &ev, H_CURR) != 0)
1353 /* start from the oldest */
1354 if (history(h, &ev, H_LAST) != 0)
1355 return NULL; /* error */
1357 /* look forwards for event matching specified offset */
1358 if (history(h, &ev, H_NEXT_EVDATA, num, &she.data))
1363 /* restore pointer to where it was */
1364 (void)history(h, &ev, H_SET, curr_num);
1371 * add the line to history table
1374 add_history(const char *line)
1378 if (h == NULL || e == NULL)
1381 (void)history(h, &ev, H_ENTER, line);
1382 if (history(h, &ev, H_GETSIZE) == 0)
1383 history_length = ev.num;
1385 return !(history_length > 0); /* return 0 if all is okay */
1390 * remove the specified entry from the history list and return it.
1393 remove_history(int num)
1398 if (h == NULL || e == NULL)
1401 if ((he = el_malloc(sizeof(*he))) == NULL)
1404 if (history(h, &ev, H_DELDATA, num, &he->data) != 0) {
1410 if (history(h, &ev, H_GETSIZE) == 0)
1411 history_length = ev.num;
1418 * replace the line and data of the num-th entry
1421 replace_history_entry(int num, const char *line, histdata_t data)
1427 if (h == NULL || e == NULL)
1430 /* save current position */
1431 if (history(h, &ev, H_CURR) != 0)
1435 /* start from the oldest */
1436 if (history(h, &ev, H_LAST) != 0)
1437 return NULL; /* error */
1439 if ((he = el_malloc(sizeof(*he))) == NULL)
1442 /* look forwards for event matching specified offset */
1443 if (history(h, &ev, H_NEXT_EVDATA, num, &he->data))
1446 he->line = strdup(ev.str);
1447 if (he->line == NULL)
1450 if (history(h, &ev, H_REPLACE, line, data))
1453 /* restore pointer to where it was */
1454 if (history(h, &ev, H_SET, curr_num))
1464 * clear the history list - delete all entries
1471 (void)history(h, &ev, H_CLEAR);
1477 * returns offset of the current history event
1485 if (history(h, &ev, H_CURR) != 0)
1489 (void)history(h, &ev, H_FIRST);
1491 while (ev.num != curr_num && history(h, &ev, H_NEXT) == 0)
1499 * returns current history event or NULL if there is no such event
1502 current_history(void)
1505 return _move_history(H_CURR);
1510 * returns total number of bytes history events' data are using
1513 history_total_bytes(void)
1519 if (history(h, &ev, H_CURR) != 0)
1523 (void)history(h, &ev, H_FIRST);
1526 size += strlen(ev.str) * sizeof(*ev.str);
1527 while (history(h, &ev, H_NEXT) == 0);
1529 /* get to the same position as before */
1530 history(h, &ev, H_PREV_EVENT, curr_num);
1537 * sets the position in the history list to ``pos''
1540 history_set_pos(int pos)
1545 if (pos >= history_length || pos < 0)
1548 (void)history(h, &ev, H_CURR);
1552 * use H_DELDATA to set to nth history (without delete) by passing
1555 if (history(h, &ev, H_DELDATA, pos, (void **)-1)) {
1556 (void)history(h, &ev, H_SET, curr_num);
1564 * returns previous event in history and shifts pointer accordingly
1567 previous_history(void)
1570 return _move_history(H_PREV);
1575 * returns next event in history and shifts pointer accordingly
1581 return _move_history(H_NEXT);
1586 * searches for first history event containing the str
1589 history_search(const char *str, int direction)
1595 if (history(h, &ev, H_CURR) != 0)
1600 if ((strp = strstr(ev.str, str)) != NULL)
1601 return (int)(strp - ev.str);
1602 if (history(h, &ev, direction < 0 ? H_NEXT:H_PREV) != 0)
1605 (void)history(h, &ev, H_SET, curr_num);
1611 * searches for first history event beginning with str
1614 history_search_prefix(const char *str, int direction)
1618 return (history(h, &ev, direction < 0 ?
1619 H_PREV_STR : H_NEXT_STR, str));
1624 * search for event in history containing str, starting at offset
1625 * abs(pos); continue backward, if pos<0, forward otherwise
1629 history_search_pos(const char *str,
1630 int direction __attribute__((__unused__)), int pos)
1635 off = (pos > 0) ? pos : -pos;
1636 pos = (pos > 0) ? 1 : -1;
1638 if (history(h, &ev, H_CURR) != 0)
1642 if (history_set_pos(off) != 0 || history(h, &ev, H_CURR) != 0)
1646 if (strstr(ev.str, str))
1648 if (history(h, &ev, (pos < 0) ? H_PREV : H_NEXT) != 0)
1652 /* set "current" pointer back to previous state */
1653 (void)history(h, &ev,
1654 pos < 0 ? H_NEXT_EVENT : H_PREV_EVENT, curr_num);
1660 /********************************/
1661 /* completion functions */
1664 tilde_expand(char *name)
1666 return fn_tilde_expand(name);
1670 filename_completion_function(const char *name, int state)
1672 return fn_filename_completion_function(name, state);
1676 * a completion generator for usernames; returns _first_ username
1677 * which starts with supplied text
1678 * text contains a partial username preceded by random character
1679 * (usually '~'); state resets search from start (??? should we do that anyway)
1680 * it's callers responsibility to free returned value
1683 username_completion_function(const char *text, int state)
1685 struct passwd *pass = NULL;
1687 if (text[0] == '\0')
1697 (pass = getpwent()) != NULL
1698 && text[0] == pass->pw_name[0]
1699 && strcmp(text, pass->pw_name) == 0)
1706 return strdup(pass->pw_name);
1711 * el-compatible wrapper to send TSTP on ^Z
1714 static unsigned char
1715 _el_rl_tstp(EditLine *el __attribute__((__unused__)), int ch __attribute__((__unused__)))
1717 (void)kill(0, SIGTSTP);
1722 * Display list of strings in columnar format on readline's output stream.
1723 * 'matches' is list of strings, 'len' is number of strings in 'matches',
1724 * 'max' is maximum length of string in 'matches'.
1727 rl_display_match_list(char **matches, int len, int max)
1730 fn_display_match_list(e, matches, (size_t)len, (size_t)max);
1735 _rl_completion_append_character_function(const char *dummy
1736 __attribute__((__unused__)))
1739 buf[0] = (char)rl_completion_append_character;
1746 * complete word at current point
1750 rl_complete(int ignore __attribute__((__unused__)), int invoking_key)
1753 static ct_buffer_t wbreak_conv, sprefix_conv;
1756 if (h == NULL || e == NULL)
1759 if (rl_inhibit_completion) {
1761 arr[0] = (char)invoking_key;
1763 el_insertstr(e, arr);
1767 /* Just look at how many global variables modify this operation! */
1768 return fn_complete(e,
1769 (CPFunction *)rl_completion_entry_function,
1770 rl_attempted_completion_function,
1771 ct_decode_string(rl_basic_word_break_characters, &wbreak_conv),
1772 ct_decode_string(rl_special_prefixes, &sprefix_conv),
1773 _rl_completion_append_character_function,
1774 (size_t)rl_completion_query_items,
1775 &rl_completion_type, &rl_attempted_completion_over,
1776 &rl_point, &rl_end);
1783 static unsigned char
1784 _el_rl_complete(EditLine *el __attribute__((__unused__)), int ch)
1786 return (unsigned char)rl_complete(0, ch);
1790 * misc other functions
1794 * bind key c to readline-type function func
1797 rl_bind_key(int c, rl_command_func_t *func)
1801 if (h == NULL || e == NULL)
1804 if (func == rl_insert) {
1805 /* XXX notice there is no range checking of ``c'' */
1806 e->el_map.key[c] = ED_INSERT;
1814 * read one key from input - handles chars pushed back
1815 * to input stream also
1820 char fooarr[2 * sizeof(int)];
1822 if (e == NULL || h == NULL)
1825 return el_getc(e, fooarr);
1830 * reset the terminal
1834 rl_reset_terminal(const char *p __attribute__((__unused__)))
1837 if (h == NULL || e == NULL)
1844 * insert character ``c'' back into input stream, ``count'' times
1847 rl_insert(int count, int c)
1851 if (h == NULL || e == NULL)
1854 /* XXX - int -> char conversion can lose on multichars */
1858 for (; count > 0; count--)
1865 rl_insert_text(const char *text)
1867 if (!text || *text == 0)
1870 if (h == NULL || e == NULL)
1873 if (el_insertstr(e, text) < 0)
1875 return (int)strlen(text);
1880 rl_newline(int count __attribute__((__unused__)),
1881 int c __attribute__((__unused__)))
1884 * Readline-4.0 appears to ignore the args.
1886 return rl_insert(1, '\n');
1890 static unsigned char
1891 rl_bind_wrapper(EditLine *el __attribute__((__unused__)), unsigned char c)
1900 /* If rl_done was set by the above call, deal with it here */
1908 rl_add_defun(const char *name, Function *fun, int c)
1911 if ((size_t)c >= sizeof(map) / sizeof(map[0]) || c < 0)
1913 map[(unsigned char)c] = fun;
1914 el_set(e, EL_ADDFN, name, name, rl_bind_wrapper);
1915 vis(dest, c, VIS_WHITE|VIS_NOSLASH, 0);
1916 el_set(e, EL_BIND, dest, name);
1921 rl_callback_read_char()
1923 int count = 0, done = 0;
1924 const char *buf = el_gets(e, &count);
1927 if (buf == NULL || count-- <= 0)
1929 if (count == 0 && buf[0] == e->el_tty.t_c[TS_IO][C_EOF])
1931 if (buf[count] == '\n' || buf[count] == '\r')
1934 if (done && rl_linefunc != NULL) {
1935 el_set(e, EL_UNBUFFERED, 0);
1937 if ((wbuf = strdup(buf)) != NULL)
1941 (*(void (*)(const char *))rl_linefunc)(wbuf);
1942 //el_set(e, EL_UNBUFFERED, 1);
1947 rl_callback_handler_install(const char *prompt, VCPFunction *linefunc)
1952 (void)rl_set_prompt(prompt);
1953 rl_linefunc = linefunc;
1954 el_set(e, EL_UNBUFFERED, 1);
1958 rl_callback_handler_remove(void)
1960 el_set(e, EL_UNBUFFERED, 0);
1968 a[0] = (char)e->el_tty.t_c[TS_IO][C_REPRINT];
1974 rl_get_previous_history(int count, int key)
1986 rl_prep_terminal(int meta_flag __attribute__((__unused__)))
1988 el_set(e, EL_PREP_TERM, 1);
1992 rl_deprep_terminal(void)
1994 el_set(e, EL_PREP_TERM, 0);
1998 rl_read_init_file(const char *s)
2000 return el_source(e, s);
2004 rl_parse_and_bind(const char *line)
2010 tok = tok_init(NULL);
2011 tok_str(tok, line, &argc, &argv);
2012 argc = el_parse(e, argc, argv);
2014 return argc ? 1 : 0;
2018 rl_variable_bind(const char *var, const char *value)
2021 * The proper return value is undocument, but this is what the
2022 * readline source seems to do.
2024 return el_set(e, EL_BIND, "", var, value) == -1 ? 1 : 0;
2028 rl_stuff_char(int c)
2034 el_insertstr(e, buf);
2038 _rl_event_read_char(EditLine *el, char *cp)
2041 ssize_t num_read = 0;
2044 while (rl_event_hook) {
2048 #if defined(FIONREAD)
2049 if (ioctl(el->el_infd, FIONREAD, &n) < 0)
2052 num_read = read(el->el_infd, cp, (size_t)1);
2055 #elif defined(F_SETFL) && defined(O_NDELAY)
2056 if ((n = fcntl(el->el_infd, F_GETFL, 0)) < 0)
2058 if (fcntl(el->el_infd, F_SETFL, n|O_NDELAY) < 0)
2060 num_read = read(el->el_infd, cp, 1);
2061 if (fcntl(el->el_infd, F_SETFL, n))
2064 /* not non-blocking, but what you gonna do? */
2065 num_read = read(el->el_infd, cp, 1);
2069 if (num_read < 0 && errno == EAGAIN)
2076 el_set(el, EL_GETCFN, EL_BUILTIN_GETCFN);
2077 return (int)num_read;
2081 _rl_update_pos(void)
2083 const LineInfo *li = el_line(e);
2085 rl_point = (int)(li->cursor - li->buffer);
2086 rl_end = (int)(li->lastchar - li->buffer);
2090 rl_get_screen_size(int *rows, int *cols)
2093 el_get(e, EL_GETTC, "li", rows);
2095 el_get(e, EL_GETTC, "co", cols);
2099 rl_set_screen_size(int rows, int cols)
2102 (void)snprintf(buf, sizeof(buf), "%d", rows);
2103 el_set(e, EL_SETTC, "li", buf);
2104 (void)snprintf(buf, sizeof(buf), "%d", cols);
2105 el_set(e, EL_SETTC, "co", buf);
2109 rl_completion_matches(const char *str, rl_compentry_func_t *fun)
2111 size_t len, max, i, j, min;
2112 char **list, *match, *a, *b;
2116 if ((list = el_malloc(max * sizeof(*list))) == NULL)
2119 while ((match = (*fun)(str, (int)(len - 1))) != NULL) {
2120 list[len++] = match;
2124 if ((nl = el_realloc(list, max * sizeof(*nl))) == NULL)
2133 if ((list[0] = strdup(list[1])) == NULL)
2137 qsort(&list[1], len - 1, sizeof(*list),
2138 (int (*)(const void *, const void *)) strcmp);
2140 for (i = 1, a = list[i]; i < len - 1; i++, a = b) {
2142 for (j = 0; a[j] && a[j] == b[j]; j++)
2147 if (min == 0 && *str) {
2148 if ((list[0] = strdup(str)) == NULL)
2151 if ((list[0] = el_malloc((min + 1) * sizeof(*list[0]))) == NULL)
2153 (void)memcpy(list[0], list[1], min);
2154 list[0][min] = '\0';
2164 rl_filename_completion_function (const char *text, int state)
2166 return fn_filename_completion_function(text, state);
2170 rl_forced_update_display(void)
2172 el_set(e, EL_REFRESH);
2176 _rl_abort_internal(void)
2184 _rl_qsort_string_compare(char **s1, char **s2)
2186 return strcoll(*s1, *s2);
2190 history_get_history_state(void)
2194 if ((hs = el_malloc(sizeof(*hs))) == NULL)
2196 hs->length = history_length;
2202 rl_kill_text(int from __attribute__((__unused__)),
2203 int to __attribute__((__unused__)))
2209 rl_make_bare_keymap(void)
2222 rl_set_keymap(Keymap k __attribute__((__unused__)))
2228 rl_generic_bind(int type __attribute__((__unused__)),
2229 const char * keyseq __attribute__((__unused__)),
2230 const char * data __attribute__((__unused__)),
2231 Keymap k __attribute__((__unused__)))
2238 rl_bind_key_in_map(int key __attribute__((__unused__)),
2239 rl_command_func_t *fun __attribute__((__unused__)),
2240 Keymap k __attribute__((__unused__)))
2245 /* unsupported, but needed by python */
2247 rl_cleanup_after_signal(void)
2252 rl_on_new_line(void)