kernel - Implement sbrk(), change low-address mmap hinting
[dragonfly.git] / contrib / libedit / src / readline.c
blobe744448e4ddc779e27b7939b09c484a238c3b02b
1 /* $NetBSD: readline.c,v 1.114 2015/03/24 21:29:52 christos Exp $ */
3 /*-
4 * Copyright (c) 1997 The NetBSD Foundation, Inc.
5 * All rights reserved.
7 * This code is derived from software contributed to The NetBSD Foundation
8 * by Jaromir Dolecek.
10 * Redistribution and use in source and binary forms, with or without
11 * modification, are permitted provided that the following conditions
12 * are met:
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 "config.h"
33 #if !defined(lint) && !defined(SCCSID)
34 __RCSID("$NetBSD: readline.c,v 1.114 2015/03/24 21:29:52 christos Exp $");
35 #endif /* not lint && not SCCSID */
37 #include <sys/types.h>
38 #include <sys/stat.h>
39 #include <stdio.h>
40 #include <dirent.h>
41 #include <string.h>
42 #include <pwd.h>
43 #include <ctype.h>
44 #include <stdlib.h>
45 #include <unistd.h>
46 #include <limits.h>
47 #include <errno.h>
48 #include <fcntl.h>
49 #include <setjmp.h>
50 #include <vis.h>
52 #include "editline/readline.h"
53 #include "el.h"
54 #include "fcns.h" /* for EL_NUM_FCNS */
55 #include "histedit.h"
56 #include "filecomplete.h"
58 #if !defined(SIZE_T_MAX)
59 # define SIZE_T_MAX (size_t)(-1)
60 #endif
62 void rl_prep_terminal(int);
63 void rl_deprep_terminal(void);
65 /* for rl_complete() */
66 #define TAB '\r'
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;
82 int rl_point = 0;
83 int rl_end = 0;
84 char *rl_line_buffer = NULL;
85 VCPFunction *rl_linefunc = NULL;
86 int rl_done = 0;
87 VFunction *rl_event_hook = NULL;
88 KEYMAP_ENTRY_ARRAY emacs_standard_keymap,
89 emacs_meta_keymap,
90 emacs_ctlx_keymap;
92 * The following is not implemented; we always catch signals in the
93 * libedit fashion: set handlers on entry to el_gets() and clear them
94 * on the way out. This simplistic approach works for most cases; if
95 * it does not work for your application, please let us know.
97 int rl_catch_signals = 1;
98 int rl_catch_sigwinch = 1;
100 int history_base = 1; /* probably never subject to change */
101 int history_length = 0;
102 int max_input_history = 0;
103 char history_expansion_char = '!';
104 char history_subst_char = '^';
105 char *history_no_expand_chars = expand_chars;
106 Function *history_inhibit_expansion_function = NULL;
107 char *history_arg_extract(int start, int end, const char *str);
109 int rl_inhibit_completion = 0;
110 int rl_attempted_completion_over = 0;
111 char *rl_basic_word_break_characters = break_chars;
112 char *rl_completer_word_break_characters = NULL;
113 char *rl_completer_quote_characters = NULL;
114 Function *rl_completion_entry_function = NULL;
115 char *(*rl_completion_word_break_hook)(void) = NULL;
116 CPPFunction *rl_attempted_completion_function = NULL;
117 Function *rl_pre_input_hook = NULL;
118 Function *rl_startup1_hook = NULL;
119 int (*rl_getc_function)(FILE *) = NULL;
120 char *rl_terminal_name = NULL;
121 int rl_already_prompted = 0;
122 int rl_filename_completion_desired = 0;
123 int rl_ignore_completion_duplicates = 0;
124 int readline_echoing_p = 1;
125 int _rl_print_completions_horizontally = 0;
126 VFunction *rl_redisplay_function = NULL;
127 Function *rl_startup_hook = NULL;
128 VFunction *rl_completion_display_matches_hook = NULL;
129 VFunction *rl_prep_term_function = (VFunction *)rl_prep_terminal;
130 VFunction *rl_deprep_term_function = (VFunction *)rl_deprep_terminal;
131 KEYMAP_ENTRY_ARRAY emacs_meta_keymap;
134 * The current prompt string.
136 char *rl_prompt = NULL;
138 * This is set to character indicating type of completion being done by
139 * rl_complete_internal(); this is available for application completion
140 * functions.
142 int rl_completion_type = 0;
145 * If more than this number of items results from query for possible
146 * completions, we ask user if they are sure to really display the list.
148 int rl_completion_query_items = 100;
151 * List of characters which are word break characters, but should be left
152 * in the parsed text when it is passed to the completion function.
153 * Shell uses this to help determine what kind of completing to do.
155 char *rl_special_prefixes = NULL;
158 * This is the character appended to the completed words if at the end of
159 * the line. Default is ' ' (a space).
161 int rl_completion_append_character = ' ';
163 /* stuff below is used internally by libedit for readline emulation */
165 static History *h = NULL;
166 static EditLine *e = NULL;
167 static Function *map[256];
168 static jmp_buf topbuf;
170 /* internal functions */
171 static unsigned char _el_rl_complete(EditLine *, int);
172 static unsigned char _el_rl_tstp(EditLine *, int);
173 static char *_get_prompt(EditLine *);
174 static int _getc_function(EditLine *, char *);
175 static HIST_ENTRY *_move_history(int);
176 static int _history_expand_command(const char *, size_t, size_t,
177 char **);
178 static char *_rl_compat_sub(const char *, const char *,
179 const char *, int);
180 static int _rl_event_read_char(EditLine *, char *);
181 static void _rl_update_pos(void);
184 /* ARGSUSED */
185 static char *
186 _get_prompt(EditLine *el __attribute__((__unused__)))
188 rl_already_prompted = 1;
189 return rl_prompt;
194 * generic function for moving around history
196 static HIST_ENTRY *
197 _move_history(int op)
199 HistEvent ev;
200 static HIST_ENTRY rl_he;
202 if (history(h, &ev, op) != 0)
203 return NULL;
205 rl_he.line = ev.str;
206 rl_he.data = NULL;
208 return &rl_he;
213 * read one key from user defined input function
215 static int
216 /*ARGSUSED*/
217 _getc_function(EditLine *el __attribute__((__unused__)), char *c)
219 int i;
221 i = (*rl_getc_function)(NULL);
222 if (i == -1)
223 return 0;
224 *c = (char)i;
225 return 1;
228 static void
229 _resize_fun(EditLine *el, void *a)
231 const LineInfo *li;
232 char **ap = a;
234 li = el_line(el);
235 /* a cheesy way to get rid of const cast. */
236 *ap = memchr(li->buffer, *li->buffer, (size_t)1);
239 static const char *
240 _default_history_file(void)
242 struct passwd *p;
243 static char *path;
244 size_t len;
246 if (path)
247 return path;
249 if ((p = getpwuid(getuid())) == NULL)
250 return NULL;
252 len = strlen(p->pw_dir) + sizeof("/.history");
253 if ((path = malloc(len)) == NULL)
254 return NULL;
256 (void)snprintf(path, len, "%s/.history", p->pw_dir);
257 return path;
261 * READLINE compatibility stuff
265 * Set the prompt
268 rl_set_prompt(const char *prompt)
270 char *p;
272 if (!prompt)
273 prompt = "";
274 if (rl_prompt != NULL && strcmp(rl_prompt, prompt) == 0)
275 return 0;
276 if (rl_prompt)
277 el_free(rl_prompt);
278 rl_prompt = strdup(prompt);
279 if (rl_prompt == NULL)
280 return -1;
282 while ((p = strchr(rl_prompt, RL_PROMPT_END_IGNORE)) != NULL)
283 *p = RL_PROMPT_START_IGNORE;
285 return 0;
289 * initialize rl compat stuff
292 rl_initialize(void)
294 HistEvent ev;
295 int editmode = 1;
296 struct termios t;
298 if (e != NULL)
299 el_end(e);
300 if (h != NULL)
301 history_end(h);
303 if (!rl_instream)
304 rl_instream = stdin;
305 if (!rl_outstream)
306 rl_outstream = stdout;
309 * See if we don't really want to run the editor
311 if (tcgetattr(fileno(rl_instream), &t) != -1 && (t.c_lflag & ECHO) == 0)
312 editmode = 0;
314 e = el_init(rl_readline_name, rl_instream, rl_outstream, stderr);
316 if (!editmode)
317 el_set(e, EL_EDITMODE, 0);
319 h = history_init();
320 if (!e || !h)
321 return -1;
323 history(h, &ev, H_SETSIZE, INT_MAX); /* unlimited */
324 history_length = 0;
325 max_input_history = INT_MAX;
326 el_set(e, EL_HIST, history, h);
328 /* Setup resize function */
329 el_set(e, EL_RESIZE, _resize_fun, &rl_line_buffer);
331 /* setup getc function if valid */
332 if (rl_getc_function)
333 el_set(e, EL_GETCFN, _getc_function);
335 /* for proper prompt printing in readline() */
336 if (rl_set_prompt("") == -1) {
337 history_end(h);
338 el_end(e);
339 return -1;
341 el_set(e, EL_PROMPT, _get_prompt, RL_PROMPT_START_IGNORE);
342 el_set(e, EL_SIGNAL, rl_catch_signals);
344 /* set default mode to "emacs"-style and read setting afterwards */
345 /* so this can be overridden */
346 el_set(e, EL_EDITOR, "emacs");
347 if (rl_terminal_name != NULL)
348 el_set(e, EL_TERMINAL, rl_terminal_name);
349 else
350 el_get(e, EL_TERMINAL, &rl_terminal_name);
353 * Word completion - this has to go AFTER rebinding keys
354 * to emacs-style.
356 el_set(e, EL_ADDFN, "rl_complete",
357 "ReadLine compatible completion function",
358 _el_rl_complete);
359 el_set(e, EL_BIND, "^I", "rl_complete", NULL);
362 * Send TSTP when ^Z is pressed.
364 el_set(e, EL_ADDFN, "rl_tstp",
365 "ReadLine compatible suspend function",
366 _el_rl_tstp);
367 el_set(e, EL_BIND, "^Z", "rl_tstp", NULL);
370 * Set some readline compatible key-bindings.
372 el_set(e, EL_BIND, "^R", "em-inc-search-prev", NULL);
375 * Allow the use of Home/End keys.
377 el_set(e, EL_BIND, "\\e[1~", "ed-move-to-beg", NULL);
378 el_set(e, EL_BIND, "\\e[4~", "ed-move-to-end", NULL);
379 el_set(e, EL_BIND, "\\e[7~", "ed-move-to-beg", NULL);
380 el_set(e, EL_BIND, "\\e[8~", "ed-move-to-end", NULL);
381 el_set(e, EL_BIND, "\\e[H", "ed-move-to-beg", NULL);
382 el_set(e, EL_BIND, "\\e[F", "ed-move-to-end", NULL);
385 * Allow the use of the Delete/Insert keys.
387 el_set(e, EL_BIND, "\\e[3~", "ed-delete-next-char", NULL);
388 el_set(e, EL_BIND, "\\e[2~", "ed-quoted-insert", NULL);
391 * Ctrl-left-arrow and Ctrl-right-arrow for word moving.
393 el_set(e, EL_BIND, "\\e[1;5C", "em-next-word", NULL);
394 el_set(e, EL_BIND, "\\e[1;5D", "ed-prev-word", NULL);
395 el_set(e, EL_BIND, "\\e[5C", "em-next-word", NULL);
396 el_set(e, EL_BIND, "\\e[5D", "ed-prev-word", NULL);
397 el_set(e, EL_BIND, "\\e\\e[C", "em-next-word", NULL);
398 el_set(e, EL_BIND, "\\e\\e[D", "ed-prev-word", NULL);
400 /* read settings from configuration file */
401 el_source(e, NULL);
404 * Unfortunately, some applications really do use rl_point
405 * and rl_line_buffer directly.
407 _resize_fun(e, &rl_line_buffer);
408 _rl_update_pos();
410 if (rl_startup_hook)
411 (*rl_startup_hook)(NULL, 0);
413 return 0;
418 * read one line from input stream and return it, chomping
419 * trailing newline (if there is any)
421 char *
422 readline(const char *p)
424 HistEvent ev;
425 const char * volatile prompt = p;
426 int count;
427 const char *ret;
428 char *buf;
429 static int used_event_hook;
431 if (e == NULL || h == NULL)
432 rl_initialize();
434 rl_done = 0;
436 (void)setjmp(topbuf);
438 /* update prompt accordingly to what has been passed */
439 if (rl_set_prompt(prompt) == -1)
440 return NULL;
442 if (rl_pre_input_hook)
443 (*rl_pre_input_hook)(NULL, 0);
445 if (rl_event_hook && !(e->el_flags&NO_TTY)) {
446 el_set(e, EL_GETCFN, _rl_event_read_char);
447 used_event_hook = 1;
450 if (!rl_event_hook && used_event_hook) {
451 el_set(e, EL_GETCFN, EL_BUILTIN_GETCFN);
452 used_event_hook = 0;
455 rl_already_prompted = 0;
457 /* get one line from input stream */
458 ret = el_gets(e, &count);
460 if (ret && count > 0) {
461 int lastidx;
463 buf = strdup(ret);
464 if (buf == NULL)
465 return NULL;
466 lastidx = count - 1;
467 if (buf[lastidx] == '\n')
468 buf[lastidx] = '\0';
469 } else
470 buf = NULL;
472 history(h, &ev, H_GETSIZE);
473 history_length = ev.num;
475 return buf;
479 * history functions
483 * is normally called before application starts to use
484 * history expansion functions
486 void
487 using_history(void)
489 if (h == NULL || e == NULL)
490 rl_initialize();
495 * substitute ``what'' with ``with'', returning resulting string; if
496 * globally == 1, substitutes all occurrences of what, otherwise only the
497 * first one
499 static char *
500 _rl_compat_sub(const char *str, const char *what, const char *with,
501 int globally)
503 const char *s;
504 char *r, *result;
505 size_t len, with_len, what_len;
507 len = strlen(str);
508 with_len = strlen(with);
509 what_len = strlen(what);
511 /* calculate length we need for result */
512 s = str;
513 while (*s) {
514 if (*s == *what && !strncmp(s, what, what_len)) {
515 len += with_len - what_len;
516 if (!globally)
517 break;
518 s += what_len;
519 } else
520 s++;
522 r = result = el_malloc((len + 1) * sizeof(*r));
523 if (result == NULL)
524 return NULL;
525 s = str;
526 while (*s) {
527 if (*s == *what && !strncmp(s, what, what_len)) {
528 (void)strncpy(r, with, with_len);
529 r += with_len;
530 s += what_len;
531 if (!globally) {
532 (void)strcpy(r, s);
533 return result;
535 } else
536 *r++ = *s++;
538 *r = '\0';
539 return result;
542 static char *last_search_pat; /* last !?pat[?] search pattern */
543 static char *last_search_match; /* last !?pat[?] that matched */
545 const char *
546 get_history_event(const char *cmd, int *cindex, int qchar)
548 int idx, sign, sub, num, begin, ret;
549 size_t len;
550 char *pat;
551 const char *rptr;
552 HistEvent ev;
554 idx = *cindex;
555 if (cmd[idx++] != history_expansion_char)
556 return NULL;
558 /* find out which event to take */
559 if (cmd[idx] == history_expansion_char || cmd[idx] == '\0') {
560 if (history(h, &ev, H_FIRST) != 0)
561 return NULL;
562 *cindex = cmd[idx]? (idx + 1):idx;
563 return ev.str;
565 sign = 0;
566 if (cmd[idx] == '-') {
567 sign = 1;
568 idx++;
571 if ('0' <= cmd[idx] && cmd[idx] <= '9') {
572 HIST_ENTRY *rl_he;
574 num = 0;
575 while (cmd[idx] && '0' <= cmd[idx] && cmd[idx] <= '9') {
576 num = num * 10 + cmd[idx] - '0';
577 idx++;
579 if (sign)
580 num = history_length - num + 1;
582 if (!(rl_he = history_get(num)))
583 return NULL;
585 *cindex = idx;
586 return rl_he->line;
588 sub = 0;
589 if (cmd[idx] == '?') {
590 sub = 1;
591 idx++;
593 begin = idx;
594 while (cmd[idx]) {
595 if (cmd[idx] == '\n')
596 break;
597 if (sub && cmd[idx] == '?')
598 break;
599 if (!sub && (cmd[idx] == ':' || cmd[idx] == ' '
600 || cmd[idx] == '\t' || cmd[idx] == qchar))
601 break;
602 idx++;
604 len = (size_t)idx - (size_t)begin;
605 if (sub && cmd[idx] == '?')
606 idx++;
607 if (sub && len == 0 && last_search_pat && *last_search_pat)
608 pat = last_search_pat;
609 else if (len == 0)
610 return NULL;
611 else {
612 if ((pat = el_malloc((len + 1) * sizeof(*pat))) == NULL)
613 return NULL;
614 (void)strncpy(pat, cmd + begin, len);
615 pat[len] = '\0';
618 if (history(h, &ev, H_CURR) != 0) {
619 if (pat != last_search_pat)
620 el_free(pat);
621 return NULL;
623 num = ev.num;
625 if (sub) {
626 if (pat != last_search_pat) {
627 if (last_search_pat)
628 el_free(last_search_pat);
629 last_search_pat = pat;
631 ret = history_search(pat, -1);
632 } else
633 ret = history_search_prefix(pat, -1);
635 if (ret == -1) {
636 /* restore to end of list on failed search */
637 history(h, &ev, H_FIRST);
638 (void)fprintf(rl_outstream, "%s: Event not found\n", pat);
639 if (pat != last_search_pat)
640 el_free(pat);
641 return NULL;
644 if (sub && len) {
645 if (last_search_match && last_search_match != pat)
646 el_free(last_search_match);
647 last_search_match = pat;
650 if (pat != last_search_pat)
651 el_free(pat);
653 if (history(h, &ev, H_CURR) != 0)
654 return NULL;
655 *cindex = idx;
656 rptr = ev.str;
658 /* roll back to original position */
659 (void)history(h, &ev, H_SET, num);
661 return rptr;
665 * the real function doing history expansion - takes as argument command
666 * to do and data upon which the command should be executed
667 * does expansion the way I've understood readline documentation
669 * returns 0 if data was not modified, 1 if it was and 2 if the string
670 * should be only printed and not executed; in case of error,
671 * returns -1 and *result points to NULL
672 * it's the caller's responsibility to free() the string returned in *result
674 static int
675 _history_expand_command(const char *command, size_t offs, size_t cmdlen,
676 char **result)
678 char *tmp, *search = NULL, *aptr;
679 const char *ptr, *cmd;
680 static char *from = NULL, *to = NULL;
681 int start, end, idx, has_mods = 0;
682 int p_on = 0, g_on = 0;
684 *result = NULL;
685 aptr = NULL;
686 ptr = NULL;
688 /* First get event specifier */
689 idx = 0;
691 if (strchr(":^*$", command[offs + 1])) {
692 char str[4];
694 * "!:" is shorthand for "!!:".
695 * "!^", "!*" and "!$" are shorthand for
696 * "!!:^", "!!:*" and "!!:$" respectively.
698 str[0] = str[1] = '!';
699 str[2] = '0';
700 ptr = get_history_event(str, &idx, 0);
701 idx = (command[offs + 1] == ':')? 1:0;
702 has_mods = 1;
703 } else {
704 if (command[offs + 1] == '#') {
705 /* use command so far */
706 if ((aptr = el_malloc((offs + 1) * sizeof(*aptr)))
707 == NULL)
708 return -1;
709 (void)strncpy(aptr, command, offs);
710 aptr[offs] = '\0';
711 idx = 1;
712 } else {
713 int qchar;
715 qchar = (offs > 0 && command[offs - 1] == '"')? '"':0;
716 ptr = get_history_event(command + offs, &idx, qchar);
718 has_mods = command[offs + (size_t)idx] == ':';
721 if (ptr == NULL && aptr == NULL)
722 return -1;
724 if (!has_mods) {
725 *result = strdup(aptr ? aptr : ptr);
726 if (aptr)
727 el_free(aptr);
728 if (*result == NULL)
729 return -1;
730 return 1;
733 cmd = command + offs + idx + 1;
735 /* Now parse any word designators */
737 if (*cmd == '%') /* last word matched by ?pat? */
738 tmp = strdup(last_search_match? last_search_match:"");
739 else if (strchr("^*$-0123456789", *cmd)) {
740 start = end = -1;
741 if (*cmd == '^')
742 start = end = 1, cmd++;
743 else if (*cmd == '$')
744 start = -1, cmd++;
745 else if (*cmd == '*')
746 start = 1, cmd++;
747 else if (*cmd == '-' || isdigit((unsigned char) *cmd)) {
748 start = 0;
749 while (*cmd && '0' <= *cmd && *cmd <= '9')
750 start = start * 10 + *cmd++ - '0';
752 if (*cmd == '-') {
753 if (isdigit((unsigned char) cmd[1])) {
754 cmd++;
755 end = 0;
756 while (*cmd && '0' <= *cmd && *cmd <= '9')
757 end = end * 10 + *cmd++ - '0';
758 } else if (cmd[1] == '$') {
759 cmd += 2;
760 end = -1;
761 } else {
762 cmd++;
763 end = -2;
765 } else if (*cmd == '*')
766 end = -1, cmd++;
767 else
768 end = start;
770 tmp = history_arg_extract(start, end, aptr? aptr:ptr);
771 if (tmp == NULL) {
772 (void)fprintf(rl_outstream, "%s: Bad word specifier",
773 command + offs + idx);
774 if (aptr)
775 el_free(aptr);
776 return -1;
778 } else
779 tmp = strdup(aptr? aptr:ptr);
781 if (aptr)
782 el_free(aptr);
784 if (*cmd == '\0' || ((size_t)(cmd - (command + offs)) >= cmdlen)) {
785 *result = tmp;
786 return 1;
789 for (; *cmd; cmd++) {
790 if (*cmd == ':')
791 continue;
792 else if (*cmd == 'h') { /* remove trailing path */
793 if ((aptr = strrchr(tmp, '/')) != NULL)
794 *aptr = '\0';
795 } else if (*cmd == 't') { /* remove leading path */
796 if ((aptr = strrchr(tmp, '/')) != NULL) {
797 aptr = strdup(aptr + 1);
798 el_free(tmp);
799 tmp = aptr;
801 } else if (*cmd == 'r') { /* remove trailing suffix */
802 if ((aptr = strrchr(tmp, '.')) != NULL)
803 *aptr = '\0';
804 } else if (*cmd == 'e') { /* remove all but suffix */
805 if ((aptr = strrchr(tmp, '.')) != NULL) {
806 aptr = strdup(aptr);
807 el_free(tmp);
808 tmp = aptr;
810 } else if (*cmd == 'p') /* print only */
811 p_on = 1;
812 else if (*cmd == 'g')
813 g_on = 2;
814 else if (*cmd == 's' || *cmd == '&') {
815 char *what, *with, delim;
816 size_t len, from_len;
817 size_t size;
819 if (*cmd == '&' && (from == NULL || to == NULL))
820 continue;
821 else if (*cmd == 's') {
822 delim = *(++cmd), cmd++;
823 size = 16;
824 what = el_realloc(from, size * sizeof(*what));
825 if (what == NULL) {
826 el_free(from);
827 el_free(tmp);
828 return 0;
830 len = 0;
831 for (; *cmd && *cmd != delim; cmd++) {
832 if (*cmd == '\\' && cmd[1] == delim)
833 cmd++;
834 if (len >= size) {
835 char *nwhat;
836 nwhat = el_realloc(what,
837 (size <<= 1) *
838 sizeof(*nwhat));
839 if (nwhat == NULL) {
840 el_free(what);
841 el_free(tmp);
842 return 0;
844 what = nwhat;
846 what[len++] = *cmd;
848 what[len] = '\0';
849 from = what;
850 if (*what == '\0') {
851 el_free(what);
852 if (search) {
853 from = strdup(search);
854 if (from == NULL) {
855 el_free(tmp);
856 return 0;
858 } else {
859 from = NULL;
860 el_free(tmp);
861 return -1;
864 cmd++; /* shift after delim */
865 if (!*cmd)
866 continue;
868 size = 16;
869 with = el_realloc(to, size * sizeof(*with));
870 if (with == NULL) {
871 el_free(to);
872 el_free(tmp);
873 return -1;
875 len = 0;
876 from_len = strlen(from);
877 for (; *cmd && *cmd != delim; cmd++) {
878 if (len + from_len + 1 >= size) {
879 char *nwith;
880 size += from_len + 1;
881 nwith = el_realloc(with,
882 size * sizeof(*nwith));
883 if (nwith == NULL) {
884 el_free(with);
885 el_free(tmp);
886 return -1;
888 with = nwith;
890 if (*cmd == '&') {
891 /* safe */
892 (void)strcpy(&with[len], from);
893 len += from_len;
894 continue;
896 if (*cmd == '\\'
897 && (*(cmd + 1) == delim
898 || *(cmd + 1) == '&'))
899 cmd++;
900 with[len++] = *cmd;
902 with[len] = '\0';
903 to = with;
906 aptr = _rl_compat_sub(tmp, from, to, g_on);
907 if (aptr) {
908 el_free(tmp);
909 tmp = aptr;
911 g_on = 0;
914 *result = tmp;
915 return p_on? 2:1;
920 * csh-style history expansion
923 history_expand(char *str, char **output)
925 int ret = 0;
926 size_t idx, i, size;
927 char *tmp, *result;
929 if (h == NULL || e == NULL)
930 rl_initialize();
932 if (history_expansion_char == 0) {
933 *output = strdup(str);
934 return 0;
937 *output = NULL;
938 if (str[0] == history_subst_char) {
939 /* ^foo^foo2^ is equivalent to !!:s^foo^foo2^ */
940 *output = el_malloc((strlen(str) + 4 + 1) * sizeof(**output));
941 if (*output == NULL)
942 return 0;
943 (*output)[0] = (*output)[1] = history_expansion_char;
944 (*output)[2] = ':';
945 (*output)[3] = 's';
946 (void)strcpy((*output) + 4, str);
947 str = *output;
948 } else {
949 *output = strdup(str);
950 if (*output == NULL)
951 return 0;
954 #define ADD_STRING(what, len, fr) \
956 if (idx + len + 1 > size) { \
957 char *nresult = el_realloc(result, \
958 (size += len + 1) * sizeof(*nresult)); \
959 if (nresult == NULL) { \
960 el_free(*output); \
961 if (/*CONSTCOND*/fr) \
962 el_free(tmp); \
963 return 0; \
965 result = nresult; \
967 (void)strncpy(&result[idx], what, len); \
968 idx += len; \
969 result[idx] = '\0'; \
972 result = NULL;
973 size = idx = 0;
974 tmp = NULL;
975 for (i = 0; str[i];) {
976 int qchar, loop_again;
977 size_t len, start, j;
979 qchar = 0;
980 loop_again = 1;
981 start = j = i;
982 loop:
983 for (; str[j]; j++) {
984 if (str[j] == '\\' &&
985 str[j + 1] == history_expansion_char) {
986 (void)strcpy(&str[j], &str[j + 1]);
987 continue;
989 if (!loop_again) {
990 if (isspace((unsigned char) str[j])
991 || str[j] == qchar)
992 break;
994 if (str[j] == history_expansion_char
995 && !strchr(history_no_expand_chars, str[j + 1])
996 && (!history_inhibit_expansion_function ||
997 (*history_inhibit_expansion_function)(str,
998 (int)j) == 0))
999 break;
1002 if (str[j] && loop_again) {
1003 i = j;
1004 qchar = (j > 0 && str[j - 1] == '"' )? '"':0;
1005 j++;
1006 if (str[j] == history_expansion_char)
1007 j++;
1008 loop_again = 0;
1009 goto loop;
1011 len = i - start;
1012 ADD_STRING(&str[start], len, 0);
1014 if (str[i] == '\0' || str[i] != history_expansion_char) {
1015 len = j - i;
1016 ADD_STRING(&str[i], len, 0);
1017 if (start == 0)
1018 ret = 0;
1019 else
1020 ret = 1;
1021 break;
1023 ret = _history_expand_command (str, i, (j - i), &tmp);
1024 if (ret > 0 && tmp) {
1025 len = strlen(tmp);
1026 ADD_STRING(tmp, len, 1);
1028 if (tmp) {
1029 el_free(tmp);
1030 tmp = NULL;
1032 i = j;
1035 /* ret is 2 for "print only" option */
1036 if (ret == 2) {
1037 add_history(result);
1038 #ifdef GDB_411_HACK
1039 /* gdb 4.11 has been shipped with readline, where */
1040 /* history_expand() returned -1 when the line */
1041 /* should not be executed; in readline 2.1+ */
1042 /* it should return 2 in such a case */
1043 ret = -1;
1044 #endif
1046 el_free(*output);
1047 *output = result;
1049 return ret;
1053 * Return a string consisting of arguments of "str" from "start" to "end".
1055 char *
1056 history_arg_extract(int start, int end, const char *str)
1058 size_t i, len, max;
1059 char **arr, *result = NULL;
1061 arr = history_tokenize(str);
1062 if (!arr)
1063 return NULL;
1064 if (arr && *arr == NULL)
1065 goto out;
1067 for (max = 0; arr[max]; max++)
1068 continue;
1069 max--;
1071 if (start == '$')
1072 start = (int)max;
1073 if (end == '$')
1074 end = (int)max;
1075 if (end < 0)
1076 end = (int)max + end + 1;
1077 if (start < 0)
1078 start = end;
1080 if (start < 0 || end < 0 || (size_t)start > max ||
1081 (size_t)end > max || start > end)
1082 goto out;
1084 for (i = (size_t)start, len = 0; i <= (size_t)end; i++)
1085 len += strlen(arr[i]) + 1;
1086 len++;
1087 result = el_malloc(len * sizeof(*result));
1088 if (result == NULL)
1089 goto out;
1091 for (i = (size_t)start, len = 0; i <= (size_t)end; i++) {
1092 (void)strcpy(result + len, arr[i]);
1093 len += strlen(arr[i]);
1094 if (i < (size_t)end)
1095 result[len++] = ' ';
1097 result[len] = '\0';
1099 out:
1100 for (i = 0; arr[i]; i++)
1101 el_free(arr[i]);
1102 el_free(arr);
1104 return result;
1108 * Parse the string into individual tokens,
1109 * similar to how shell would do it.
1111 char **
1112 history_tokenize(const char *str)
1114 int size = 1, idx = 0, i, start;
1115 size_t len;
1116 char **result = NULL, *temp, delim = '\0';
1118 for (i = 0; str[i];) {
1119 while (isspace((unsigned char) str[i]))
1120 i++;
1121 start = i;
1122 for (; str[i];) {
1123 if (str[i] == '\\') {
1124 if (str[i+1] != '\0')
1125 i++;
1126 } else if (str[i] == delim)
1127 delim = '\0';
1128 else if (!delim &&
1129 (isspace((unsigned char) str[i]) ||
1130 strchr("()<>;&|$", str[i])))
1131 break;
1132 else if (!delim && strchr("'`\"", str[i]))
1133 delim = str[i];
1134 if (str[i])
1135 i++;
1138 if (idx + 2 >= size) {
1139 char **nresult;
1140 size <<= 1;
1141 nresult = el_realloc(result, (size_t)size * sizeof(*nresult));
1142 if (nresult == NULL) {
1143 el_free(result);
1144 return NULL;
1146 result = nresult;
1148 len = (size_t)i - (size_t)start;
1149 temp = el_malloc((size_t)(len + 1) * sizeof(*temp));
1150 if (temp == NULL) {
1151 for (i = 0; i < idx; i++)
1152 el_free(result[i]);
1153 el_free(result);
1154 return NULL;
1156 (void)strncpy(temp, &str[start], len);
1157 temp[len] = '\0';
1158 result[idx++] = temp;
1159 result[idx] = NULL;
1160 if (str[i])
1161 i++;
1163 return result;
1168 * limit size of history record to ``max'' events
1170 void
1171 stifle_history(int max)
1173 HistEvent ev;
1175 if (h == NULL || e == NULL)
1176 rl_initialize();
1178 if (history(h, &ev, H_SETSIZE, max) == 0)
1179 max_input_history = max;
1184 * "unlimit" size of history - set the limit to maximum allowed int value
1187 unstifle_history(void)
1189 HistEvent ev;
1190 int omax;
1192 history(h, &ev, H_SETSIZE, INT_MAX);
1193 omax = max_input_history;
1194 max_input_history = INT_MAX;
1195 return omax; /* some value _must_ be returned */
1200 history_is_stifled(void)
1203 /* cannot return true answer */
1204 return max_input_history != INT_MAX;
1207 static const char _history_tmp_template[] = "/tmp/.historyXXXXXX";
1210 history_truncate_file (const char *filename, int nlines)
1212 int ret = 0;
1213 FILE *fp, *tp;
1214 char template[sizeof(_history_tmp_template)];
1215 char buf[4096];
1216 int fd;
1217 char *cp;
1218 off_t off;
1219 int count = 0;
1220 ssize_t left = 0;
1222 if (filename == NULL && (filename = _default_history_file()) == NULL)
1223 return errno;
1224 if ((fp = fopen(filename, "r+")) == NULL)
1225 return errno;
1226 strcpy(template, _history_tmp_template);
1227 if ((fd = mkstemp(template)) == -1) {
1228 ret = errno;
1229 goto out1;
1232 if ((tp = fdopen(fd, "r+")) == NULL) {
1233 close(fd);
1234 ret = errno;
1235 goto out2;
1238 for(;;) {
1239 if (fread(buf, sizeof(buf), (size_t)1, fp) != 1) {
1240 if (ferror(fp)) {
1241 ret = errno;
1242 break;
1244 if (fseeko(fp, (off_t)sizeof(buf) * count, SEEK_SET) ==
1245 (off_t)-1) {
1246 ret = errno;
1247 break;
1249 left = (ssize_t)fread(buf, (size_t)1, sizeof(buf), fp);
1250 if (ferror(fp)) {
1251 ret = errno;
1252 break;
1254 if (left == 0) {
1255 count--;
1256 left = sizeof(buf);
1257 } else if (fwrite(buf, (size_t)left, (size_t)1, tp)
1258 != 1) {
1259 ret = errno;
1260 break;
1262 fflush(tp);
1263 break;
1265 if (fwrite(buf, sizeof(buf), (size_t)1, tp) != 1) {
1266 ret = errno;
1267 break;
1269 count++;
1271 if (ret)
1272 goto out3;
1273 cp = buf + left - 1;
1274 if(*cp != '\n')
1275 cp++;
1276 for(;;) {
1277 while (--cp >= buf) {
1278 if (*cp == '\n') {
1279 if (--nlines == 0) {
1280 if (++cp >= buf + sizeof(buf)) {
1281 count++;
1282 cp = buf;
1284 break;
1288 if (nlines <= 0 || count == 0)
1289 break;
1290 count--;
1291 if (fseeko(tp, (off_t)sizeof(buf) * count, SEEK_SET) < 0) {
1292 ret = errno;
1293 break;
1295 if (fread(buf, sizeof(buf), (size_t)1, tp) != 1) {
1296 if (ferror(tp)) {
1297 ret = errno;
1298 break;
1300 ret = EAGAIN;
1301 break;
1303 cp = buf + sizeof(buf);
1306 if (ret || nlines > 0)
1307 goto out3;
1309 if (fseeko(fp, (off_t)0, SEEK_SET) == (off_t)-1) {
1310 ret = errno;
1311 goto out3;
1314 if (fseeko(tp, (off_t)sizeof(buf) * count + (cp - buf), SEEK_SET) ==
1315 (off_t)-1) {
1316 ret = errno;
1317 goto out3;
1320 for(;;) {
1321 if ((left = (ssize_t)fread(buf, (size_t)1, sizeof(buf), tp)) == 0) {
1322 if (ferror(fp))
1323 ret = errno;
1324 break;
1326 if (fwrite(buf, (size_t)left, (size_t)1, fp) != 1) {
1327 ret = errno;
1328 break;
1331 fflush(fp);
1332 if((off = ftello(fp)) > 0)
1333 (void)ftruncate(fileno(fp), off);
1334 out3:
1335 fclose(tp);
1336 out2:
1337 unlink(template);
1338 out1:
1339 fclose(fp);
1341 return ret;
1346 * read history from a file given
1349 read_history(const char *filename)
1351 HistEvent ev;
1353 if (h == NULL || e == NULL)
1354 rl_initialize();
1355 if (filename == NULL && (filename = _default_history_file()) == NULL)
1356 return errno;
1357 return history(h, &ev, H_LOAD, filename) == -1 ?
1358 (errno ? errno : EINVAL) : 0;
1363 * write history to a file given
1366 write_history(const char *filename)
1368 HistEvent ev;
1370 if (h == NULL || e == NULL)
1371 rl_initialize();
1372 if (filename == NULL && (filename = _default_history_file()) == NULL)
1373 return errno;
1374 return history(h, &ev, H_SAVE, filename) == -1 ?
1375 (errno ? errno : EINVAL) : 0;
1380 * returns history ``num''th event
1382 * returned pointer points to static variable
1384 HIST_ENTRY *
1385 history_get(int num)
1387 static HIST_ENTRY she;
1388 HistEvent ev;
1389 int curr_num;
1391 if (h == NULL || e == NULL)
1392 rl_initialize();
1394 /* save current position */
1395 if (history(h, &ev, H_CURR) != 0)
1396 return NULL;
1397 curr_num = ev.num;
1399 /* start from the oldest */
1400 if (history(h, &ev, H_LAST) != 0)
1401 return NULL; /* error */
1403 /* look forwards for event matching specified offset */
1404 if (history(h, &ev, H_NEXT_EVDATA, num, &she.data))
1405 return NULL;
1407 she.line = ev.str;
1409 /* restore pointer to where it was */
1410 (void)history(h, &ev, H_SET, curr_num);
1412 return &she;
1417 * add the line to history table
1420 add_history(const char *line)
1422 HistEvent ev;
1424 if (line == NULL)
1425 return 0;
1427 if (h == NULL || e == NULL)
1428 rl_initialize();
1430 (void)history(h, &ev, H_ENTER, line);
1431 if (history(h, &ev, H_GETSIZE) == 0)
1432 history_length = ev.num;
1434 return !(history_length > 0); /* return 0 if all is okay */
1439 * remove the specified entry from the history list and return it.
1441 HIST_ENTRY *
1442 remove_history(int num)
1444 HIST_ENTRY *he;
1445 HistEvent ev;
1447 if (h == NULL || e == NULL)
1448 rl_initialize();
1450 if ((he = el_malloc(sizeof(*he))) == NULL)
1451 return NULL;
1453 if (history(h, &ev, H_DELDATA, num, &he->data) != 0) {
1454 el_free(he);
1455 return NULL;
1458 he->line = ev.str;
1459 if (history(h, &ev, H_GETSIZE) == 0)
1460 history_length = ev.num;
1462 return he;
1467 * replace the line and data of the num-th entry
1469 HIST_ENTRY *
1470 replace_history_entry(int num, const char *line, histdata_t data)
1472 HIST_ENTRY *he;
1473 HistEvent ev;
1474 int curr_num;
1476 if (h == NULL || e == NULL)
1477 rl_initialize();
1479 /* save current position */
1480 if (history(h, &ev, H_CURR) != 0)
1481 return NULL;
1482 curr_num = ev.num;
1484 /* start from the oldest */
1485 if (history(h, &ev, H_LAST) != 0)
1486 return NULL; /* error */
1488 if ((he = el_malloc(sizeof(*he))) == NULL)
1489 return NULL;
1491 /* look forwards for event matching specified offset */
1492 if (history(h, &ev, H_NEXT_EVDATA, num, &he->data))
1493 goto out;
1495 he->line = strdup(ev.str);
1496 if (he->line == NULL)
1497 goto out;
1499 if (history(h, &ev, H_REPLACE, line, data))
1500 goto out;
1502 /* restore pointer to where it was */
1503 if (history(h, &ev, H_SET, curr_num))
1504 goto out;
1506 return he;
1507 out:
1508 el_free(he);
1509 return NULL;
1513 * clear the history list - delete all entries
1515 void
1516 clear_history(void)
1518 HistEvent ev;
1520 if (h == NULL || e == NULL)
1521 rl_initialize();
1523 (void)history(h, &ev, H_CLEAR);
1524 history_length = 0;
1529 * returns offset of the current history event
1532 where_history(void)
1534 HistEvent ev;
1535 int curr_num, off;
1537 if (history(h, &ev, H_CURR) != 0)
1538 return 0;
1539 curr_num = ev.num;
1541 (void)history(h, &ev, H_FIRST);
1542 off = 1;
1543 while (ev.num != curr_num && history(h, &ev, H_NEXT) == 0)
1544 off++;
1546 return off;
1551 * returns current history event or NULL if there is no such event
1553 HIST_ENTRY *
1554 current_history(void)
1557 return _move_history(H_CURR);
1562 * returns total number of bytes history events' data are using
1565 history_total_bytes(void)
1567 HistEvent ev;
1568 int curr_num;
1569 size_t size;
1571 if (history(h, &ev, H_CURR) != 0)
1572 return -1;
1573 curr_num = ev.num;
1575 (void)history(h, &ev, H_FIRST);
1576 size = 0;
1578 size += strlen(ev.str) * sizeof(*ev.str);
1579 while (history(h, &ev, H_NEXT) == 0);
1581 /* get to the same position as before */
1582 history(h, &ev, H_PREV_EVENT, curr_num);
1584 return (int)size;
1589 * sets the position in the history list to ``pos''
1592 history_set_pos(int pos)
1594 HistEvent ev;
1595 int curr_num;
1597 if (pos >= history_length || pos < 0)
1598 return -1;
1600 (void)history(h, &ev, H_CURR);
1601 curr_num = ev.num;
1604 * use H_DELDATA to set to nth history (without delete) by passing
1605 * (void **)-1
1607 if (history(h, &ev, H_DELDATA, pos, (void **)-1)) {
1608 (void)history(h, &ev, H_SET, curr_num);
1609 return -1;
1611 return 0;
1616 * returns previous event in history and shifts pointer accordingly
1618 HIST_ENTRY *
1619 previous_history(void)
1622 return _move_history(H_PREV);
1627 * returns next event in history and shifts pointer accordingly
1629 HIST_ENTRY *
1630 next_history(void)
1633 return _move_history(H_NEXT);
1638 * searches for first history event containing the str
1641 history_search(const char *str, int direction)
1643 HistEvent ev;
1644 const char *strp;
1645 int curr_num;
1647 if (history(h, &ev, H_CURR) != 0)
1648 return -1;
1649 curr_num = ev.num;
1651 for (;;) {
1652 if ((strp = strstr(ev.str, str)) != NULL)
1653 return (int)(strp - ev.str);
1654 if (history(h, &ev, direction < 0 ? H_NEXT:H_PREV) != 0)
1655 break;
1657 (void)history(h, &ev, H_SET, curr_num);
1658 return -1;
1663 * searches for first history event beginning with str
1666 history_search_prefix(const char *str, int direction)
1668 HistEvent ev;
1670 return (history(h, &ev, direction < 0 ?
1671 H_PREV_STR : H_NEXT_STR, str));
1676 * search for event in history containing str, starting at offset
1677 * abs(pos); continue backward, if pos<0, forward otherwise
1679 /* ARGSUSED */
1681 history_search_pos(const char *str,
1682 int direction __attribute__((__unused__)), int pos)
1684 HistEvent ev;
1685 int curr_num, off;
1687 off = (pos > 0) ? pos : -pos;
1688 pos = (pos > 0) ? 1 : -1;
1690 if (history(h, &ev, H_CURR) != 0)
1691 return -1;
1692 curr_num = ev.num;
1694 if (history_set_pos(off) != 0 || history(h, &ev, H_CURR) != 0)
1695 return -1;
1697 for (;;) {
1698 if (strstr(ev.str, str))
1699 return off;
1700 if (history(h, &ev, (pos < 0) ? H_PREV : H_NEXT) != 0)
1701 break;
1704 /* set "current" pointer back to previous state */
1705 (void)history(h, &ev,
1706 pos < 0 ? H_NEXT_EVENT : H_PREV_EVENT, curr_num);
1708 return -1;
1712 /********************************/
1713 /* completion functions */
1715 char *
1716 tilde_expand(char *name)
1718 return fn_tilde_expand(name);
1721 char *
1722 filename_completion_function(const char *name, int state)
1724 return fn_filename_completion_function(name, state);
1728 * a completion generator for usernames; returns _first_ username
1729 * which starts with supplied text
1730 * text contains a partial username preceded by random character
1731 * (usually '~'); state resets search from start (??? should we do that anyway)
1732 * it's the caller's responsibility to free the returned value
1734 char *
1735 username_completion_function(const char *text, int state)
1737 struct passwd *pass = NULL;
1739 if (text[0] == '\0')
1740 return NULL;
1742 if (*text == '~')
1743 text++;
1745 if (state == 0)
1746 setpwent();
1748 while (
1749 (pass = getpwent()) != NULL
1750 && text[0] == pass->pw_name[0]
1751 && strcmp(text, pass->pw_name) == 0)
1752 continue;
1754 if (pass == NULL) {
1755 endpwent();
1756 return NULL;
1758 return strdup(pass->pw_name);
1763 * el-compatible wrapper to send TSTP on ^Z
1765 /* ARGSUSED */
1766 static unsigned char
1767 _el_rl_tstp(EditLine *el __attribute__((__unused__)), int ch __attribute__((__unused__)))
1769 (void)kill(0, SIGTSTP);
1770 return CC_NORM;
1774 * Display list of strings in columnar format on readline's output stream.
1775 * 'matches' is list of strings, 'len' is number of strings in 'matches',
1776 * 'max' is maximum length of string in 'matches'.
1778 void
1779 rl_display_match_list(char **matches, int len, int max)
1782 fn_display_match_list(e, matches, (size_t)len, (size_t)max);
1785 static const char *
1786 /*ARGSUSED*/
1787 _rl_completion_append_character_function(const char *dummy
1788 __attribute__((__unused__)))
1790 static char buf[2];
1791 buf[0] = (char)rl_completion_append_character;
1792 buf[1] = '\0';
1793 return buf;
1798 * complete word at current point
1800 /* ARGSUSED */
1802 rl_complete(int ignore __attribute__((__unused__)), int invoking_key)
1804 #ifdef WIDECHAR
1805 static ct_buffer_t wbreak_conv, sprefix_conv;
1806 #endif
1807 char *breakchars;
1809 if (h == NULL || e == NULL)
1810 rl_initialize();
1812 if (rl_inhibit_completion) {
1813 char arr[2];
1814 arr[0] = (char)invoking_key;
1815 arr[1] = '\0';
1816 el_insertstr(e, arr);
1817 return CC_REFRESH;
1820 if (rl_completion_word_break_hook != NULL)
1821 breakchars = (*rl_completion_word_break_hook)();
1822 else
1823 breakchars = rl_basic_word_break_characters;
1825 /* Just look at how many global variables modify this operation! */
1826 return fn_complete(e,
1827 (CPFunction *)rl_completion_entry_function,
1828 rl_attempted_completion_function,
1829 ct_decode_string(rl_basic_word_break_characters, &wbreak_conv),
1830 ct_decode_string(breakchars, &sprefix_conv),
1831 _rl_completion_append_character_function,
1832 (size_t)rl_completion_query_items,
1833 &rl_completion_type, &rl_attempted_completion_over,
1834 &rl_point, &rl_end);
1840 /* ARGSUSED */
1841 static unsigned char
1842 _el_rl_complete(EditLine *el __attribute__((__unused__)), int ch)
1844 return (unsigned char)rl_complete(0, ch);
1848 * misc other functions
1852 * bind key c to readline-type function func
1855 rl_bind_key(int c, rl_command_func_t *func)
1857 int retval = -1;
1859 if (h == NULL || e == NULL)
1860 rl_initialize();
1862 if (func == rl_insert) {
1863 /* XXX notice there is no range checking of ``c'' */
1864 e->el_map.key[c] = ED_INSERT;
1865 retval = 0;
1867 return retval;
1872 * read one key from input - handles chars pushed back
1873 * to input stream also
1876 rl_read_key(void)
1878 char fooarr[2 * sizeof(int)];
1880 if (e == NULL || h == NULL)
1881 rl_initialize();
1883 return el_getc(e, fooarr);
1888 * reset the terminal
1890 /* ARGSUSED */
1891 void
1892 rl_reset_terminal(const char *p __attribute__((__unused__)))
1895 if (h == NULL || e == NULL)
1896 rl_initialize();
1897 el_reset(e);
1902 * insert character ``c'' back into input stream, ``count'' times
1905 rl_insert(int count, int c)
1907 char arr[2];
1909 if (h == NULL || e == NULL)
1910 rl_initialize();
1912 /* XXX - int -> char conversion can lose on multichars */
1913 arr[0] = (char)c;
1914 arr[1] = '\0';
1916 for (; count > 0; count--)
1917 el_push(e, arr);
1919 return 0;
1923 rl_insert_text(const char *text)
1925 if (!text || *text == 0)
1926 return 0;
1928 if (h == NULL || e == NULL)
1929 rl_initialize();
1931 if (el_insertstr(e, text) < 0)
1932 return 0;
1933 return (int)strlen(text);
1936 /*ARGSUSED*/
1938 rl_newline(int count __attribute__((__unused__)),
1939 int c __attribute__((__unused__)))
1942 * Readline-4.0 appears to ignore the args.
1944 return rl_insert(1, '\n');
1947 /*ARGSUSED*/
1948 static unsigned char
1949 rl_bind_wrapper(EditLine *el __attribute__((__unused__)), unsigned char c)
1951 if (map[c] == NULL)
1952 return CC_ERROR;
1954 _rl_update_pos();
1956 (*map[c])(NULL, c);
1958 /* If rl_done was set by the above call, deal with it here */
1959 if (rl_done)
1960 return CC_EOF;
1962 return CC_NORM;
1966 rl_add_defun(const char *name, Function *fun, int c)
1968 char dest[8];
1969 if ((size_t)c >= sizeof(map) / sizeof(map[0]) || c < 0)
1970 return -1;
1971 map[(unsigned char)c] = fun;
1972 el_set(e, EL_ADDFN, name, name, rl_bind_wrapper);
1973 vis(dest, c, VIS_WHITE|VIS_NOSLASH, 0);
1974 el_set(e, EL_BIND, dest, name, NULL);
1975 return 0;
1978 void
1979 rl_callback_read_char(void)
1981 int count = 0, done = 0;
1982 const char *buf = el_gets(e, &count);
1983 char *wbuf;
1985 if (buf == NULL || count-- <= 0)
1986 return;
1987 if (count == 0 && buf[0] == e->el_tty.t_c[TS_IO][C_EOF])
1988 done = 1;
1989 if (buf[count] == '\n' || buf[count] == '\r')
1990 done = 2;
1992 if (done && rl_linefunc != NULL) {
1993 el_set(e, EL_UNBUFFERED, 0);
1994 if (done == 2) {
1995 if ((wbuf = strdup(buf)) != NULL)
1996 wbuf[count] = '\0';
1997 } else
1998 wbuf = NULL;
1999 (*(void (*)(const char *))rl_linefunc)(wbuf);
2000 el_set(e, EL_UNBUFFERED, 1);
2004 void
2005 rl_callback_handler_install(const char *prompt, VCPFunction *linefunc)
2007 if (e == NULL) {
2008 rl_initialize();
2010 (void)rl_set_prompt(prompt);
2011 rl_linefunc = linefunc;
2012 el_set(e, EL_UNBUFFERED, 1);
2015 void
2016 rl_callback_handler_remove(void)
2018 el_set(e, EL_UNBUFFERED, 0);
2019 rl_linefunc = NULL;
2022 void
2023 rl_redisplay(void)
2025 char a[2];
2026 a[0] = (char)e->el_tty.t_c[TS_IO][C_REPRINT];
2027 a[1] = '\0';
2028 el_push(e, a);
2032 rl_get_previous_history(int count, int key)
2034 char a[2];
2035 a[0] = (char)key;
2036 a[1] = '\0';
2037 while (count--)
2038 el_push(e, a);
2039 return 0;
2042 void
2043 /*ARGSUSED*/
2044 rl_prep_terminal(int meta_flag __attribute__((__unused__)))
2046 el_set(e, EL_PREP_TERM, 1);
2049 void
2050 rl_deprep_terminal(void)
2052 el_set(e, EL_PREP_TERM, 0);
2056 rl_read_init_file(const char *s)
2058 return el_source(e, s);
2062 rl_parse_and_bind(const char *line)
2064 const char **argv;
2065 int argc;
2066 Tokenizer *tok;
2068 tok = tok_init(NULL);
2069 tok_str(tok, line, &argc, &argv);
2070 argc = el_parse(e, argc, argv);
2071 tok_end(tok);
2072 return argc ? 1 : 0;
2076 rl_variable_bind(const char *var, const char *value)
2079 * The proper return value is undocument, but this is what the
2080 * readline source seems to do.
2082 return el_set(e, EL_BIND, "", var, value, NULL) == -1 ? 1 : 0;
2085 void
2086 rl_stuff_char(int c)
2088 char buf[2];
2090 buf[0] = (char)c;
2091 buf[1] = '\0';
2092 el_insertstr(e, buf);
2095 static int
2096 _rl_event_read_char(EditLine *el, char *cp)
2098 int n;
2099 ssize_t num_read = 0;
2101 *cp = '\0';
2102 while (rl_event_hook) {
2104 (*rl_event_hook)();
2106 #if defined(FIONREAD)
2107 if (ioctl(el->el_infd, FIONREAD, &n) < 0)
2108 return -1;
2109 if (n)
2110 num_read = read(el->el_infd, cp, (size_t)1);
2111 else
2112 num_read = 0;
2113 #elif defined(F_SETFL) && defined(O_NDELAY)
2114 if ((n = fcntl(el->el_infd, F_GETFL, 0)) < 0)
2115 return -1;
2116 if (fcntl(el->el_infd, F_SETFL, n|O_NDELAY) < 0)
2117 return -1;
2118 num_read = read(el->el_infd, cp, 1);
2119 if (fcntl(el->el_infd, F_SETFL, n))
2120 return -1;
2121 #else
2122 /* not non-blocking, but what you gonna do? */
2123 num_read = read(el->el_infd, cp, 1);
2124 return -1;
2125 #endif
2127 if (num_read < 0 && errno == EAGAIN)
2128 continue;
2129 if (num_read == 0)
2130 continue;
2131 break;
2133 if (!rl_event_hook)
2134 el_set(el, EL_GETCFN, EL_BUILTIN_GETCFN);
2135 return (int)num_read;
2138 static void
2139 _rl_update_pos(void)
2141 const LineInfo *li = el_line(e);
2143 rl_point = (int)(li->cursor - li->buffer);
2144 rl_end = (int)(li->lastchar - li->buffer);
2147 void
2148 rl_get_screen_size(int *rows, int *cols)
2150 if (rows)
2151 el_get(e, EL_GETTC, "li", rows, (void *)0);
2152 if (cols)
2153 el_get(e, EL_GETTC, "co", cols, (void *)0);
2156 void
2157 rl_set_screen_size(int rows, int cols)
2159 char buf[64];
2160 (void)snprintf(buf, sizeof(buf), "%d", rows);
2161 el_set(e, EL_SETTC, "li", buf, NULL);
2162 (void)snprintf(buf, sizeof(buf), "%d", cols);
2163 el_set(e, EL_SETTC, "co", buf, NULL);
2166 char **
2167 rl_completion_matches(const char *str, rl_compentry_func_t *fun)
2169 size_t len, max, i, j, min;
2170 char **list, *match, *a, *b;
2172 len = 1;
2173 max = 10;
2174 if ((list = el_malloc(max * sizeof(*list))) == NULL)
2175 return NULL;
2177 while ((match = (*fun)(str, (int)(len - 1))) != NULL) {
2178 list[len++] = match;
2179 if (len == max) {
2180 char **nl;
2181 max += 10;
2182 if ((nl = el_realloc(list, max * sizeof(*nl))) == NULL)
2183 goto out;
2184 list = nl;
2187 if (len == 1)
2188 goto out;
2189 list[len] = NULL;
2190 if (len == 2) {
2191 if ((list[0] = strdup(list[1])) == NULL)
2192 goto out;
2193 return list;
2195 qsort(&list[1], len - 1, sizeof(*list),
2196 (int (*)(const void *, const void *)) strcmp);
2197 min = SIZE_T_MAX;
2198 for (i = 1, a = list[i]; i < len - 1; i++, a = b) {
2199 b = list[i + 1];
2200 for (j = 0; a[j] && a[j] == b[j]; j++)
2201 continue;
2202 if (min > j)
2203 min = j;
2205 if (min == 0 && *str) {
2206 if ((list[0] = strdup(str)) == NULL)
2207 goto out;
2208 } else {
2209 if ((list[0] = el_malloc((min + 1) * sizeof(*list[0]))) == NULL)
2210 goto out;
2211 (void)memcpy(list[0], list[1], min);
2212 list[0][min] = '\0';
2214 return list;
2216 out:
2217 el_free(list);
2218 return NULL;
2221 char *
2222 rl_filename_completion_function (const char *text, int state)
2224 return fn_filename_completion_function(text, state);
2227 void
2228 rl_forced_update_display(void)
2230 el_set(e, EL_REFRESH);
2234 _rl_abort_internal(void)
2236 el_beep(e);
2237 longjmp(topbuf, 1);
2238 /*NOTREACHED*/
2242 _rl_qsort_string_compare(char **s1, char **s2)
2244 return strcoll(*s1, *s2);
2247 HISTORY_STATE *
2248 history_get_history_state(void)
2250 HISTORY_STATE *hs;
2252 if ((hs = el_malloc(sizeof(*hs))) == NULL)
2253 return NULL;
2254 hs->length = history_length;
2255 return hs;
2259 /*ARGSUSED*/
2260 rl_kill_text(int from __attribute__((__unused__)),
2261 int to __attribute__((__unused__)))
2263 return 0;
2266 Keymap
2267 rl_make_bare_keymap(void)
2269 return NULL;
2272 Keymap
2273 rl_get_keymap(void)
2275 return NULL;
2278 void
2279 /*ARGSUSED*/
2280 rl_set_keymap(Keymap k __attribute__((__unused__)))
2285 /*ARGSUSED*/
2286 rl_generic_bind(int type __attribute__((__unused__)),
2287 const char * keyseq __attribute__((__unused__)),
2288 const char * data __attribute__((__unused__)),
2289 Keymap k __attribute__((__unused__)))
2291 return 0;
2295 /*ARGSUSED*/
2296 rl_bind_key_in_map(int key __attribute__((__unused__)),
2297 rl_command_func_t *fun __attribute__((__unused__)),
2298 Keymap k __attribute__((__unused__)))
2300 return 0;
2303 /* unsupported, but needed by python */
2304 void
2305 rl_cleanup_after_signal(void)
2310 rl_on_new_line(void)
2312 return 0;
2315 void
2316 rl_free_line_state(void)