Restore unconditional use of getpwent vs. non-POSIX getpwent_r
[heimdal.git] / lib / libedit / src / readline.c
blob70ff6b03d2aae0251d8508402d5b76bf8e08072e
1 /* $NetBSD: readline.c,v 1.139 2016/10/28 18:32:26 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.139 2016/10/28 18:32:26 christos Exp $");
35 #endif /* not lint && not SCCSID */
37 #include <sys/types.h>
38 #include <sys/stat.h>
39 #include <ctype.h>
40 #include <dirent.h>
41 #include <errno.h>
42 #include <fcntl.h>
43 #include <limits.h>
44 #include <pwd.h>
45 #include <setjmp.h>
46 #include <stdint.h>
47 #include <stdio.h>
48 #include <stdlib.h>
49 #include <string.h>
50 #include <unistd.h>
51 #include <vis.h>
53 #include "readline/readline.h"
54 #include "el.h"
55 #include "fcns.h"
56 #include "filecomplete.h"
58 void rl_prep_terminal(int);
59 void rl_deprep_terminal(void);
61 /* for rl_complete() */
62 #define TAB '\r'
64 /* see comment at the #ifdef for sense of this */
65 /* #define GDB_411_HACK */
67 /* readline compatibility stuff - look at readline sources/documentation */
68 /* to see what these variables mean */
69 const char *rl_library_version = "EditLine wrapper";
70 int rl_readline_version = RL_READLINE_VERSION;
71 static char empty[] = { '\0' };
72 static char expand_chars[] = { ' ', '\t', '\n', '=', '(', '\0' };
73 static char break_chars[] = { ' ', '\t', '\n', '"', '\\', '\'', '`', '@', '$',
74 '>', '<', '=', ';', '|', '&', '{', '(', '\0' };
75 char *rl_readline_name = empty;
76 FILE *rl_instream = NULL;
77 FILE *rl_outstream = NULL;
78 int rl_point = 0;
79 int rl_end = 0;
80 char *rl_line_buffer = NULL;
81 rl_vcpfunc_t *rl_linefunc = NULL;
82 int rl_done = 0;
83 VFunction *rl_event_hook = NULL;
84 KEYMAP_ENTRY_ARRAY emacs_standard_keymap,
85 emacs_meta_keymap,
86 emacs_ctlx_keymap;
88 * The following is not implemented; we always catch signals in the
89 * libedit fashion: set handlers on entry to el_gets() and clear them
90 * on the way out. This simplistic approach works for most cases; if
91 * it does not work for your application, please let us know.
93 int rl_catch_signals = 1;
94 int rl_catch_sigwinch = 1;
96 int history_base = 1; /* probably never subject to change */
97 int history_length = 0;
98 int history_offset = 0;
99 int max_input_history = 0;
100 char history_expansion_char = '!';
101 char history_subst_char = '^';
102 char *history_no_expand_chars = expand_chars;
103 Function *history_inhibit_expansion_function = NULL;
104 char *history_arg_extract(int start, int end, const char *str);
106 int rl_inhibit_completion = 0;
107 int rl_attempted_completion_over = 0;
108 char *rl_basic_word_break_characters = break_chars;
109 char *rl_completer_word_break_characters = NULL;
110 char *rl_completer_quote_characters = NULL;
111 rl_compentry_func_t *rl_completion_entry_function = NULL;
112 char *(*rl_completion_word_break_hook)(void) = NULL;
113 rl_completion_func_t *rl_attempted_completion_function = NULL;
114 Function *rl_pre_input_hook = NULL;
115 Function *rl_startup1_hook = NULL;
116 int (*rl_getc_function)(FILE *) = NULL;
117 char *rl_terminal_name = NULL;
118 int rl_already_prompted = 0;
119 int rl_filename_completion_desired = 0;
120 int rl_ignore_completion_duplicates = 0;
121 int readline_echoing_p = 1;
122 int _rl_print_completions_horizontally = 0;
123 VFunction *rl_redisplay_function = NULL;
124 Function *rl_startup_hook = NULL;
125 VFunction *rl_completion_display_matches_hook = NULL;
126 VFunction *rl_prep_term_function = (VFunction *)rl_prep_terminal;
127 VFunction *rl_deprep_term_function = (VFunction *)rl_deprep_terminal;
128 KEYMAP_ENTRY_ARRAY emacs_meta_keymap;
131 * The current prompt string.
133 char *rl_prompt = NULL;
135 * This is set to character indicating type of completion being done by
136 * rl_complete_internal(); this is available for application completion
137 * functions.
139 int rl_completion_type = 0;
142 * If more than this number of items results from query for possible
143 * completions, we ask user if they are sure to really display the list.
145 int rl_completion_query_items = 100;
148 * List of characters which are word break characters, but should be left
149 * in the parsed text when it is passed to the completion function.
150 * Shell uses this to help determine what kind of completing to do.
152 char *rl_special_prefixes = NULL;
155 * This is the character appended to the completed words if at the end of
156 * the line. Default is ' ' (a space).
158 int rl_completion_append_character = ' ';
160 /* stuff below is used internally by libedit for readline emulation */
162 static History *h = NULL;
163 static EditLine *e = NULL;
164 static rl_command_func_t *map[256];
165 static jmp_buf topbuf;
167 /* internal functions */
168 static unsigned char _el_rl_complete(EditLine *, int);
169 static unsigned char _el_rl_tstp(EditLine *, int);
170 static char *_get_prompt(EditLine *);
171 static int _getc_function(EditLine *, wchar_t *);
172 static int _history_expand_command(const char *, size_t, size_t,
173 char **);
174 static char *_rl_compat_sub(const char *, const char *,
175 const char *, int);
176 static int _rl_event_read_char(EditLine *, wchar_t *);
177 static void _rl_update_pos(void);
179 static HIST_ENTRY rl_he;
181 /* ARGSUSED */
182 static char *
183 _get_prompt(EditLine *el __attribute__((__unused__)))
185 rl_already_prompted = 1;
186 return rl_prompt;
191 * read one key from user defined input function
193 static int
194 /*ARGSUSED*/
195 _getc_function(EditLine *el __attribute__((__unused__)), wchar_t *c)
197 int i;
199 i = (*rl_getc_function)(rl_instream);
200 if (i == -1)
201 return 0;
202 *c = (wchar_t)i;
203 return 1;
206 static void
207 _resize_fun(EditLine *el, void *a)
209 const LineInfo *li;
210 char **ap = a;
212 li = el_line(el);
213 /* a cheesy way to get rid of const cast. */
214 *ap = memchr(li->buffer, *li->buffer, (size_t)1);
217 static const char *
218 _default_history_file(void)
220 struct passwd *p;
221 static char *path;
222 size_t len;
224 if (path)
225 return path;
227 if ((p = getpwuid(getuid())) == NULL)
228 return NULL;
230 len = strlen(p->pw_dir) + sizeof("/.history");
231 if ((path = malloc(len)) == NULL)
232 return NULL;
234 (void)snprintf(path, len, "%s/.history", p->pw_dir);
235 return path;
239 * READLINE compatibility stuff
243 * Set the prompt
246 rl_set_prompt(const char *prompt)
248 char *p;
250 if (!prompt)
251 prompt = "";
252 if (rl_prompt != NULL && strcmp(rl_prompt, prompt) == 0)
253 return 0;
254 if (rl_prompt)
255 el_free(rl_prompt);
256 rl_prompt = strdup(prompt);
257 if (rl_prompt == NULL)
258 return -1;
260 while ((p = strchr(rl_prompt, RL_PROMPT_END_IGNORE)) != NULL)
261 *p = RL_PROMPT_START_IGNORE;
263 return 0;
267 * initialize rl compat stuff
270 rl_initialize(void)
272 HistEvent ev;
273 int editmode = 1;
274 struct termios t;
276 if (e != NULL)
277 el_end(e);
278 if (h != NULL)
279 history_end(h);
281 if (!rl_instream)
282 rl_instream = stdin;
283 if (!rl_outstream)
284 rl_outstream = stdout;
287 * See if we don't really want to run the editor
289 if (tcgetattr(fileno(rl_instream), &t) != -1 && (t.c_lflag & ECHO) == 0)
290 editmode = 0;
292 e = el_init(rl_readline_name, rl_instream, rl_outstream, stderr);
294 if (!editmode)
295 el_set(e, EL_EDITMODE, 0);
297 h = history_init();
298 if (!e || !h)
299 return -1;
301 history(h, &ev, H_SETSIZE, INT_MAX); /* unlimited */
302 history_length = 0;
303 max_input_history = INT_MAX;
304 el_set(e, EL_HIST, history, h);
306 /* Setup resize function */
307 el_set(e, EL_RESIZE, _resize_fun, &rl_line_buffer);
309 /* setup getc function if valid */
310 if (rl_getc_function)
311 el_set(e, EL_GETCFN, _getc_function);
313 /* for proper prompt printing in readline() */
314 if (rl_set_prompt("") == -1) {
315 history_end(h);
316 el_end(e);
317 return -1;
319 el_set(e, EL_PROMPT, _get_prompt, RL_PROMPT_START_IGNORE);
320 el_set(e, EL_SIGNAL, rl_catch_signals);
322 /* set default mode to "emacs"-style and read setting afterwards */
323 /* so this can be overridden */
324 el_set(e, EL_EDITOR, "emacs");
325 if (rl_terminal_name != NULL)
326 el_set(e, EL_TERMINAL, rl_terminal_name);
327 else
328 el_get(e, EL_TERMINAL, &rl_terminal_name);
331 * Word completion - this has to go AFTER rebinding keys
332 * to emacs-style.
334 el_set(e, EL_ADDFN, "rl_complete",
335 "ReadLine compatible completion function",
336 _el_rl_complete);
337 el_set(e, EL_BIND, "^I", "rl_complete", NULL);
340 * Send TSTP when ^Z is pressed.
342 el_set(e, EL_ADDFN, "rl_tstp",
343 "ReadLine compatible suspend function",
344 _el_rl_tstp);
345 el_set(e, EL_BIND, "^Z", "rl_tstp", NULL);
348 * Set some readline compatible key-bindings.
350 el_set(e, EL_BIND, "^R", "em-inc-search-prev", NULL);
353 * Allow the use of Home/End keys.
355 el_set(e, EL_BIND, "\\e[1~", "ed-move-to-beg", NULL);
356 el_set(e, EL_BIND, "\\e[4~", "ed-move-to-end", NULL);
357 el_set(e, EL_BIND, "\\e[7~", "ed-move-to-beg", NULL);
358 el_set(e, EL_BIND, "\\e[8~", "ed-move-to-end", NULL);
359 el_set(e, EL_BIND, "\\e[H", "ed-move-to-beg", NULL);
360 el_set(e, EL_BIND, "\\e[F", "ed-move-to-end", NULL);
363 * Allow the use of the Delete/Insert keys.
365 el_set(e, EL_BIND, "\\e[3~", "ed-delete-next-char", NULL);
366 el_set(e, EL_BIND, "\\e[2~", "ed-quoted-insert", NULL);
369 * Ctrl-left-arrow and Ctrl-right-arrow for word moving.
371 el_set(e, EL_BIND, "\\e[1;5C", "em-next-word", NULL);
372 el_set(e, EL_BIND, "\\e[1;5D", "ed-prev-word", NULL);
373 el_set(e, EL_BIND, "\\e[5C", "em-next-word", NULL);
374 el_set(e, EL_BIND, "\\e[5D", "ed-prev-word", NULL);
375 el_set(e, EL_BIND, "\\e\\e[C", "em-next-word", NULL);
376 el_set(e, EL_BIND, "\\e\\e[D", "ed-prev-word", NULL);
378 /* read settings from configuration file */
379 el_source(e, NULL);
382 * Unfortunately, some applications really do use rl_point
383 * and rl_line_buffer directly.
385 _resize_fun(e, &rl_line_buffer);
386 _rl_update_pos();
388 if (rl_startup_hook)
389 (*rl_startup_hook)(NULL, 0);
391 return 0;
396 * read one line from input stream and return it, chomping
397 * trailing newline (if there is any)
399 char *
400 readline(const char *p)
402 HistEvent ev;
403 const char * volatile prompt = p;
404 int count;
405 const char *ret;
406 char *buf;
407 static int used_event_hook;
409 if (e == NULL || h == NULL)
410 rl_initialize();
412 rl_done = 0;
414 (void)setjmp(topbuf);
416 /* update prompt accordingly to what has been passed */
417 if (rl_set_prompt(prompt) == -1)
418 return NULL;
420 if (rl_pre_input_hook)
421 (*rl_pre_input_hook)(NULL, 0);
423 if (rl_event_hook && !(e->el_flags&NO_TTY)) {
424 el_set(e, EL_GETCFN, _rl_event_read_char);
425 used_event_hook = 1;
428 if (!rl_event_hook && used_event_hook) {
429 el_set(e, EL_GETCFN, EL_BUILTIN_GETCFN);
430 used_event_hook = 0;
433 rl_already_prompted = 0;
435 /* get one line from input stream */
436 ret = el_gets(e, &count);
438 if (ret && count > 0) {
439 int lastidx;
441 buf = strdup(ret);
442 if (buf == NULL)
443 return NULL;
444 lastidx = count - 1;
445 if (buf[lastidx] == '\n')
446 buf[lastidx] = '\0';
447 } else
448 buf = NULL;
450 history(h, &ev, H_GETSIZE);
451 history_length = ev.num;
453 return buf;
457 * history functions
461 * is normally called before application starts to use
462 * history expansion functions
464 void
465 using_history(void)
467 if (h == NULL || e == NULL)
468 rl_initialize();
469 history_offset = history_length;
474 * substitute ``what'' with ``with'', returning resulting string; if
475 * globally == 1, substitutes all occurrences of what, otherwise only the
476 * first one
478 static char *
479 _rl_compat_sub(const char *str, const char *what, const char *with,
480 int globally)
482 const char *s;
483 char *r, *result;
484 size_t len, with_len, what_len;
486 len = strlen(str);
487 with_len = strlen(with);
488 what_len = strlen(what);
490 /* calculate length we need for result */
491 s = str;
492 while (*s) {
493 if (*s == *what && !strncmp(s, what, what_len)) {
494 len += with_len - what_len;
495 if (!globally)
496 break;
497 s += what_len;
498 } else
499 s++;
501 r = result = el_malloc((len + 1) * sizeof(*r));
502 if (result == NULL)
503 return NULL;
504 s = str;
505 while (*s) {
506 if (*s == *what && !strncmp(s, what, what_len)) {
507 (void)strncpy(r, with, with_len);
508 r += with_len;
509 s += what_len;
510 if (!globally) {
511 (void)strcpy(r, s);
512 return result;
514 } else
515 *r++ = *s++;
517 *r = '\0';
518 return result;
521 static char *last_search_pat; /* last !?pat[?] search pattern */
522 static char *last_search_match; /* last !?pat[?] that matched */
524 const char *
525 get_history_event(const char *cmd, int *cindex, int qchar)
527 int idx, sign, sub, num, begin, ret;
528 size_t len;
529 char *pat;
530 const char *rptr;
531 HistEvent ev;
533 idx = *cindex;
534 if (cmd[idx++] != history_expansion_char)
535 return NULL;
537 /* find out which event to take */
538 if (cmd[idx] == history_expansion_char || cmd[idx] == '\0') {
539 if (history(h, &ev, H_FIRST) != 0)
540 return NULL;
541 *cindex = cmd[idx]? (idx + 1):idx;
542 return ev.str;
544 sign = 0;
545 if (cmd[idx] == '-') {
546 sign = 1;
547 idx++;
550 if ('0' <= cmd[idx] && cmd[idx] <= '9') {
551 HIST_ENTRY *he;
553 num = 0;
554 while (cmd[idx] && '0' <= cmd[idx] && cmd[idx] <= '9') {
555 num = num * 10 + cmd[idx] - '0';
556 idx++;
558 if (sign)
559 num = history_length - num + 1;
561 if (!(he = history_get(num)))
562 return NULL;
564 *cindex = idx;
565 return he->line;
567 sub = 0;
568 if (cmd[idx] == '?') {
569 sub = 1;
570 idx++;
572 begin = idx;
573 while (cmd[idx]) {
574 if (cmd[idx] == '\n')
575 break;
576 if (sub && cmd[idx] == '?')
577 break;
578 if (!sub && (cmd[idx] == ':' || cmd[idx] == ' '
579 || cmd[idx] == '\t' || cmd[idx] == qchar))
580 break;
581 idx++;
583 len = (size_t)idx - (size_t)begin;
584 if (sub && cmd[idx] == '?')
585 idx++;
586 if (sub && len == 0 && last_search_pat && *last_search_pat)
587 pat = last_search_pat;
588 else if (len == 0)
589 return NULL;
590 else {
591 if ((pat = el_malloc((len + 1) * sizeof(*pat))) == NULL)
592 return NULL;
593 (void)strncpy(pat, cmd + begin, len);
594 pat[len] = '\0';
597 if (history(h, &ev, H_CURR) != 0) {
598 if (pat != last_search_pat)
599 el_free(pat);
600 return NULL;
602 num = ev.num;
604 if (sub) {
605 if (pat != last_search_pat) {
606 if (last_search_pat)
607 el_free(last_search_pat);
608 last_search_pat = pat;
610 ret = history_search(pat, -1);
611 } else
612 ret = history_search_prefix(pat, -1);
614 if (ret == -1) {
615 /* restore to end of list on failed search */
616 history(h, &ev, H_FIRST);
617 (void)fprintf(rl_outstream, "%s: Event not found\n", pat);
618 if (pat != last_search_pat)
619 el_free(pat);
620 return NULL;
623 if (sub && len) {
624 if (last_search_match && last_search_match != pat)
625 el_free(last_search_match);
626 last_search_match = pat;
629 if (pat != last_search_pat)
630 el_free(pat);
632 if (history(h, &ev, H_CURR) != 0)
633 return NULL;
634 *cindex = idx;
635 rptr = ev.str;
637 /* roll back to original position */
638 (void)history(h, &ev, H_SET, num);
640 return rptr;
644 * the real function doing history expansion - takes as argument command
645 * to do and data upon which the command should be executed
646 * does expansion the way I've understood readline documentation
648 * returns 0 if data was not modified, 1 if it was and 2 if the string
649 * should be only printed and not executed; in case of error,
650 * returns -1 and *result points to NULL
651 * it's the caller's responsibility to free() the string returned in *result
653 static int
654 _history_expand_command(const char *command, size_t offs, size_t cmdlen,
655 char **result)
657 char *tmp, *search = NULL, *aptr;
658 const char *ptr, *cmd;
659 static char *from = NULL, *to = NULL;
660 int start, end, idx, has_mods = 0;
661 int p_on = 0, g_on = 0;
663 *result = NULL;
664 aptr = NULL;
665 ptr = NULL;
667 /* First get event specifier */
668 idx = 0;
670 if (strchr(":^*$", command[offs + 1])) {
671 char str[4];
673 * "!:" is shorthand for "!!:".
674 * "!^", "!*" and "!$" are shorthand for
675 * "!!:^", "!!:*" and "!!:$" respectively.
677 str[0] = str[1] = '!';
678 str[2] = '0';
679 ptr = get_history_event(str, &idx, 0);
680 idx = (command[offs + 1] == ':')? 1:0;
681 has_mods = 1;
682 } else {
683 if (command[offs + 1] == '#') {
684 /* use command so far */
685 if ((aptr = el_malloc((offs + 1) * sizeof(*aptr)))
686 == NULL)
687 return -1;
688 (void)strncpy(aptr, command, offs);
689 aptr[offs] = '\0';
690 idx = 1;
691 } else {
692 int qchar;
694 qchar = (offs > 0 && command[offs - 1] == '"')? '"':0;
695 ptr = get_history_event(command + offs, &idx, qchar);
697 has_mods = command[offs + (size_t)idx] == ':';
700 if (ptr == NULL && aptr == NULL)
701 return -1;
703 if (!has_mods) {
704 *result = strdup(aptr ? aptr : ptr);
705 if (aptr)
706 el_free(aptr);
707 if (*result == NULL)
708 return -1;
709 return 1;
712 cmd = command + offs + idx + 1;
714 /* Now parse any word designators */
716 if (*cmd == '%') /* last word matched by ?pat? */
717 tmp = strdup(last_search_match? last_search_match:"");
718 else if (strchr("^*$-0123456789", *cmd)) {
719 start = end = -1;
720 if (*cmd == '^')
721 start = end = 1, cmd++;
722 else if (*cmd == '$')
723 start = -1, cmd++;
724 else if (*cmd == '*')
725 start = 1, cmd++;
726 else if (*cmd == '-' || isdigit((unsigned char) *cmd)) {
727 start = 0;
728 while (*cmd && '0' <= *cmd && *cmd <= '9')
729 start = start * 10 + *cmd++ - '0';
731 if (*cmd == '-') {
732 if (isdigit((unsigned char) cmd[1])) {
733 cmd++;
734 end = 0;
735 while (*cmd && '0' <= *cmd && *cmd <= '9')
736 end = end * 10 + *cmd++ - '0';
737 } else if (cmd[1] == '$') {
738 cmd += 2;
739 end = -1;
740 } else {
741 cmd++;
742 end = -2;
744 } else if (*cmd == '*')
745 end = -1, cmd++;
746 else
747 end = start;
749 tmp = history_arg_extract(start, end, aptr? aptr:ptr);
750 if (tmp == NULL) {
751 (void)fprintf(rl_outstream, "%s: Bad word specifier",
752 command + offs + idx);
753 if (aptr)
754 el_free(aptr);
755 return -1;
757 } else
758 tmp = strdup(aptr? aptr:ptr);
760 if (aptr)
761 el_free(aptr);
763 if (*cmd == '\0' || ((size_t)(cmd - (command + offs)) >= cmdlen)) {
764 *result = tmp;
765 return 1;
768 for (; *cmd; cmd++) {
769 if (*cmd == ':')
770 continue;
771 else if (*cmd == 'h') { /* remove trailing path */
772 if ((aptr = strrchr(tmp, '/')) != NULL)
773 *aptr = '\0';
774 } else if (*cmd == 't') { /* remove leading path */
775 if ((aptr = strrchr(tmp, '/')) != NULL) {
776 aptr = strdup(aptr + 1);
777 el_free(tmp);
778 tmp = aptr;
780 } else if (*cmd == 'r') { /* remove trailing suffix */
781 if ((aptr = strrchr(tmp, '.')) != NULL)
782 *aptr = '\0';
783 } else if (*cmd == 'e') { /* remove all but suffix */
784 if ((aptr = strrchr(tmp, '.')) != NULL) {
785 aptr = strdup(aptr);
786 el_free(tmp);
787 tmp = aptr;
789 } else if (*cmd == 'p') /* print only */
790 p_on = 1;
791 else if (*cmd == 'g')
792 g_on = 2;
793 else if (*cmd == 's' || *cmd == '&') {
794 char *what, *with, delim;
795 size_t len, from_len;
796 size_t size;
798 if (*cmd == '&' && (from == NULL || to == NULL))
799 continue;
800 else if (*cmd == 's') {
801 delim = *(++cmd), cmd++;
802 size = 16;
803 what = el_realloc(from, size * sizeof(*what));
804 if (what == NULL) {
805 el_free(from);
806 el_free(tmp);
807 return 0;
809 len = 0;
810 for (; *cmd && *cmd != delim; cmd++) {
811 if (*cmd == '\\' && cmd[1] == delim)
812 cmd++;
813 if (len >= size) {
814 char *nwhat;
815 nwhat = el_realloc(what,
816 (size <<= 1) *
817 sizeof(*nwhat));
818 if (nwhat == NULL) {
819 el_free(what);
820 el_free(tmp);
821 return 0;
823 what = nwhat;
825 what[len++] = *cmd;
827 what[len] = '\0';
828 from = what;
829 if (*what == '\0') {
830 el_free(what);
831 if (search) {
832 from = strdup(search);
833 if (from == NULL) {
834 el_free(tmp);
835 return 0;
837 } else {
838 from = NULL;
839 el_free(tmp);
840 return -1;
843 cmd++; /* shift after delim */
844 if (!*cmd)
845 continue;
847 size = 16;
848 with = el_realloc(to, size * sizeof(*with));
849 if (with == NULL) {
850 el_free(to);
851 el_free(tmp);
852 return -1;
854 len = 0;
855 from_len = strlen(from);
856 for (; *cmd && *cmd != delim; cmd++) {
857 if (len + from_len + 1 >= size) {
858 char *nwith;
859 size += from_len + 1;
860 nwith = el_realloc(with,
861 size * sizeof(*nwith));
862 if (nwith == NULL) {
863 el_free(with);
864 el_free(tmp);
865 return -1;
867 with = nwith;
869 if (*cmd == '&') {
870 /* safe */
871 (void)strcpy(&with[len], from);
872 len += from_len;
873 continue;
875 if (*cmd == '\\'
876 && (*(cmd + 1) == delim
877 || *(cmd + 1) == '&'))
878 cmd++;
879 with[len++] = *cmd;
881 with[len] = '\0';
882 to = with;
885 aptr = _rl_compat_sub(tmp, from, to, g_on);
886 if (aptr) {
887 el_free(tmp);
888 tmp = aptr;
890 g_on = 0;
893 *result = tmp;
894 return p_on? 2:1;
899 * csh-style history expansion
902 history_expand(char *str, char **output)
904 int ret = 0;
905 size_t idx, i, size;
906 char *tmp, *result;
908 if (h == NULL || e == NULL)
909 rl_initialize();
911 if (history_expansion_char == 0) {
912 *output = strdup(str);
913 return 0;
916 *output = NULL;
917 if (str[0] == history_subst_char) {
918 /* ^foo^foo2^ is equivalent to !!:s^foo^foo2^ */
919 *output = el_malloc((strlen(str) + 4 + 1) * sizeof(**output));
920 if (*output == NULL)
921 return 0;
922 (*output)[0] = (*output)[1] = history_expansion_char;
923 (*output)[2] = ':';
924 (*output)[3] = 's';
925 (void)strcpy((*output) + 4, str);
926 str = *output;
927 } else {
928 *output = strdup(str);
929 if (*output == NULL)
930 return 0;
933 #define ADD_STRING(what, len, fr) \
935 if (idx + len + 1 > size) { \
936 char *nresult = el_realloc(result, \
937 (size += len + 1) * sizeof(*nresult)); \
938 if (nresult == NULL) { \
939 el_free(*output); \
940 if (/*CONSTCOND*/fr) \
941 el_free(tmp); \
942 return 0; \
944 result = nresult; \
946 (void)strncpy(&result[idx], what, len); \
947 idx += len; \
948 result[idx] = '\0'; \
951 result = NULL;
952 size = idx = 0;
953 tmp = NULL;
954 for (i = 0; str[i];) {
955 int qchar, loop_again;
956 size_t len, start, j;
958 qchar = 0;
959 loop_again = 1;
960 start = j = i;
961 loop:
962 for (; str[j]; j++) {
963 if (str[j] == '\\' &&
964 str[j + 1] == history_expansion_char) {
965 len = strlen(&str[j + 1]) + 1;
966 memmove(&str[j], &str[j + 1], len);
967 continue;
969 if (!loop_again) {
970 if (isspace((unsigned char) str[j])
971 || str[j] == qchar)
972 break;
974 if (str[j] == history_expansion_char
975 && !strchr(history_no_expand_chars, str[j + 1])
976 && (!history_inhibit_expansion_function ||
977 (*history_inhibit_expansion_function)(str,
978 (int)j) == 0))
979 break;
982 if (str[j] && loop_again) {
983 i = j;
984 qchar = (j > 0 && str[j - 1] == '"' )? '"':0;
985 j++;
986 if (str[j] == history_expansion_char)
987 j++;
988 loop_again = 0;
989 goto loop;
991 len = i - start;
992 ADD_STRING(&str[start], len, 0);
994 if (str[i] == '\0' || str[i] != history_expansion_char) {
995 len = j - i;
996 ADD_STRING(&str[i], len, 0);
997 if (start == 0)
998 ret = 0;
999 else
1000 ret = 1;
1001 break;
1003 ret = _history_expand_command (str, i, (j - i), &tmp);
1004 if (ret > 0 && tmp) {
1005 len = strlen(tmp);
1006 ADD_STRING(tmp, len, 1);
1008 if (tmp) {
1009 el_free(tmp);
1010 tmp = NULL;
1012 i = j;
1015 /* ret is 2 for "print only" option */
1016 if (ret == 2) {
1017 add_history(result);
1018 #ifdef GDB_411_HACK
1019 /* gdb 4.11 has been shipped with readline, where */
1020 /* history_expand() returned -1 when the line */
1021 /* should not be executed; in readline 2.1+ */
1022 /* it should return 2 in such a case */
1023 ret = -1;
1024 #endif
1026 el_free(*output);
1027 *output = result;
1029 return ret;
1033 * Return a string consisting of arguments of "str" from "start" to "end".
1035 char *
1036 history_arg_extract(int start, int end, const char *str)
1038 size_t i, len, max;
1039 char **arr, *result = NULL;
1041 arr = history_tokenize(str);
1042 if (!arr)
1043 return NULL;
1044 if (arr && *arr == NULL)
1045 goto out;
1047 for (max = 0; arr[max]; max++)
1048 continue;
1049 max--;
1051 if (start == '$')
1052 start = (int)max;
1053 if (end == '$')
1054 end = (int)max;
1055 if (end < 0)
1056 end = (int)max + end + 1;
1057 if (start < 0)
1058 start = end;
1060 if (start < 0 || end < 0 || (size_t)start > max ||
1061 (size_t)end > max || start > end)
1062 goto out;
1064 for (i = (size_t)start, len = 0; i <= (size_t)end; i++)
1065 len += strlen(arr[i]) + 1;
1066 len++;
1067 result = el_malloc(len * sizeof(*result));
1068 if (result == NULL)
1069 goto out;
1071 for (i = (size_t)start, len = 0; i <= (size_t)end; i++) {
1072 (void)strcpy(result + len, arr[i]);
1073 len += strlen(arr[i]);
1074 if (i < (size_t)end)
1075 result[len++] = ' ';
1077 result[len] = '\0';
1079 out:
1080 for (i = 0; arr[i]; i++)
1081 el_free(arr[i]);
1082 el_free(arr);
1084 return result;
1088 * Parse the string into individual tokens,
1089 * similar to how shell would do it.
1091 char **
1092 history_tokenize(const char *str)
1094 int size = 1, idx = 0, i, start;
1095 size_t len;
1096 char **result = NULL, *temp, delim = '\0';
1098 for (i = 0; str[i];) {
1099 while (isspace((unsigned char) str[i]))
1100 i++;
1101 start = i;
1102 for (; str[i];) {
1103 if (str[i] == '\\') {
1104 if (str[i+1] != '\0')
1105 i++;
1106 } else if (str[i] == delim)
1107 delim = '\0';
1108 else if (!delim &&
1109 (isspace((unsigned char) str[i]) ||
1110 strchr("()<>;&|$", str[i])))
1111 break;
1112 else if (!delim && strchr("'`\"", str[i]))
1113 delim = str[i];
1114 if (str[i])
1115 i++;
1118 if (idx + 2 >= size) {
1119 char **nresult;
1120 size <<= 1;
1121 nresult = el_realloc(result, (size_t)size * sizeof(*nresult));
1122 if (nresult == NULL) {
1123 el_free(result);
1124 return NULL;
1126 result = nresult;
1128 len = (size_t)i - (size_t)start;
1129 temp = el_malloc((size_t)(len + 1) * sizeof(*temp));
1130 if (temp == NULL) {
1131 for (i = 0; i < idx; i++)
1132 el_free(result[i]);
1133 el_free(result);
1134 return NULL;
1136 (void)strncpy(temp, &str[start], len);
1137 temp[len] = '\0';
1138 result[idx++] = temp;
1139 result[idx] = NULL;
1140 if (str[i])
1141 i++;
1143 return result;
1148 * limit size of history record to ``max'' events
1150 void
1151 stifle_history(int max)
1153 HistEvent ev;
1154 HIST_ENTRY *he;
1156 if (h == NULL || e == NULL)
1157 rl_initialize();
1159 if (history(h, &ev, H_SETSIZE, max) == 0) {
1160 max_input_history = max;
1161 if (history_length > max)
1162 history_base = history_length - max;
1163 while (history_length > max) {
1164 he = remove_history(0);
1165 el_free(he->data);
1166 el_free((void *)(unsigned long)he->line);
1167 el_free(he);
1174 * "unlimit" size of history - set the limit to maximum allowed int value
1177 unstifle_history(void)
1179 HistEvent ev;
1180 int omax;
1182 history(h, &ev, H_SETSIZE, INT_MAX);
1183 omax = max_input_history;
1184 max_input_history = INT_MAX;
1185 return omax; /* some value _must_ be returned */
1190 history_is_stifled(void)
1193 /* cannot return true answer */
1194 return max_input_history != INT_MAX;
1197 static const char _history_tmp_template[] = "/tmp/.historyXXXXXX";
1200 history_truncate_file (const char *filename, int nlines)
1202 int ret = 0;
1203 FILE *fp, *tp;
1204 char template[sizeof(_history_tmp_template)];
1205 char buf[4096];
1206 int fd;
1207 char *cp;
1208 off_t off;
1209 int count = 0;
1210 ssize_t left = 0;
1212 if (filename == NULL && (filename = _default_history_file()) == NULL)
1213 return errno;
1214 if ((fp = fopen(filename, "r+")) == NULL)
1215 return errno;
1216 strcpy(template, _history_tmp_template);
1217 if ((fd = mkstemp(template)) == -1) {
1218 ret = errno;
1219 goto out1;
1222 if ((tp = fdopen(fd, "r+")) == NULL) {
1223 close(fd);
1224 ret = errno;
1225 goto out2;
1228 for(;;) {
1229 if (fread(buf, sizeof(buf), (size_t)1, fp) != 1) {
1230 if (ferror(fp)) {
1231 ret = errno;
1232 break;
1234 if (fseeko(fp, (off_t)sizeof(buf) * count, SEEK_SET) ==
1235 (off_t)-1) {
1236 ret = errno;
1237 break;
1239 left = (ssize_t)fread(buf, (size_t)1, sizeof(buf), fp);
1240 if (ferror(fp)) {
1241 ret = errno;
1242 break;
1244 if (left == 0) {
1245 count--;
1246 left = sizeof(buf);
1247 } else if (fwrite(buf, (size_t)left, (size_t)1, tp)
1248 != 1) {
1249 ret = errno;
1250 break;
1252 fflush(tp);
1253 break;
1255 if (fwrite(buf, sizeof(buf), (size_t)1, tp) != 1) {
1256 ret = errno;
1257 break;
1259 count++;
1261 if (ret)
1262 goto out3;
1263 cp = buf + left - 1;
1264 if(*cp != '\n')
1265 cp++;
1266 for(;;) {
1267 while (--cp >= buf) {
1268 if (*cp == '\n') {
1269 if (--nlines == 0) {
1270 if (++cp >= buf + sizeof(buf)) {
1271 count++;
1272 cp = buf;
1274 break;
1278 if (nlines <= 0 || count == 0)
1279 break;
1280 count--;
1281 if (fseeko(tp, (off_t)sizeof(buf) * count, SEEK_SET) < 0) {
1282 ret = errno;
1283 break;
1285 if (fread(buf, sizeof(buf), (size_t)1, tp) != 1) {
1286 if (ferror(tp)) {
1287 ret = errno;
1288 break;
1290 ret = EAGAIN;
1291 break;
1293 cp = buf + sizeof(buf);
1296 if (ret || nlines > 0)
1297 goto out3;
1299 if (fseeko(fp, (off_t)0, SEEK_SET) == (off_t)-1) {
1300 ret = errno;
1301 goto out3;
1304 if (fseeko(tp, (off_t)sizeof(buf) * count + (cp - buf), SEEK_SET) ==
1305 (off_t)-1) {
1306 ret = errno;
1307 goto out3;
1310 for(;;) {
1311 if ((left = (ssize_t)fread(buf, (size_t)1, sizeof(buf), tp)) == 0) {
1312 if (ferror(fp))
1313 ret = errno;
1314 break;
1316 if (fwrite(buf, (size_t)left, (size_t)1, fp) != 1) {
1317 ret = errno;
1318 break;
1321 fflush(fp);
1322 if((off = ftello(fp)) > 0)
1323 (void)ftruncate(fileno(fp), off);
1324 out3:
1325 fclose(tp);
1326 out2:
1327 unlink(template);
1328 out1:
1329 fclose(fp);
1331 return ret;
1336 * read history from a file given
1339 read_history(const char *filename)
1341 HistEvent ev;
1343 if (h == NULL || e == NULL)
1344 rl_initialize();
1345 if (filename == NULL && (filename = _default_history_file()) == NULL)
1346 return errno;
1347 return history(h, &ev, H_LOAD, filename) == -1 ?
1348 (errno ? errno : EINVAL) : 0;
1353 * write history to a file given
1356 write_history(const char *filename)
1358 HistEvent ev;
1360 if (h == NULL || e == NULL)
1361 rl_initialize();
1362 if (filename == NULL && (filename = _default_history_file()) == NULL)
1363 return errno;
1364 return history(h, &ev, H_SAVE, filename) == -1 ?
1365 (errno ? errno : EINVAL) : 0;
1370 * returns history ``num''th event
1372 * returned pointer points to static variable
1374 HIST_ENTRY *
1375 history_get(int num)
1377 static HIST_ENTRY she;
1378 HistEvent ev;
1379 int curr_num;
1381 if (h == NULL || e == NULL)
1382 rl_initialize();
1384 if (num < history_base)
1385 return NULL;
1387 /* save current position */
1388 if (history(h, &ev, H_CURR) != 0)
1389 return NULL;
1390 curr_num = ev.num;
1393 * use H_DELDATA to set to nth history (without delete) by passing
1394 * (void **)-1 -- as in history_set_pos
1396 if (history(h, &ev, H_DELDATA, num - history_base, (void **)-1) != 0)
1397 goto out;
1399 /* get current entry */
1400 if (history(h, &ev, H_CURR) != 0)
1401 goto out;
1402 if (history(h, &ev, H_NEXT_EVDATA, ev.num, &she.data) != 0)
1403 goto out;
1404 she.line = ev.str;
1406 /* restore pointer to where it was */
1407 (void)history(h, &ev, H_SET, curr_num);
1409 return &she;
1411 out:
1412 /* restore pointer to where it was */
1413 (void)history(h, &ev, H_SET, curr_num);
1414 return NULL;
1419 * add the line to history table
1422 add_history(const char *line)
1424 HistEvent ev;
1426 if (h == NULL || e == NULL)
1427 rl_initialize();
1429 if (history(h, &ev, H_ENTER, line) == -1)
1430 return 0;
1432 (void)history(h, &ev, H_GETSIZE);
1433 if (ev.num == history_length)
1434 history_base++;
1435 else
1436 history_length = ev.num;
1437 return 0;
1442 * remove the specified entry from the history list and return it.
1444 HIST_ENTRY *
1445 remove_history(int num)
1447 HIST_ENTRY *he;
1448 HistEvent ev;
1450 if (h == NULL || e == NULL)
1451 rl_initialize();
1453 if ((he = el_malloc(sizeof(*he))) == NULL)
1454 return NULL;
1456 if (history(h, &ev, H_DELDATA, num, &he->data) != 0) {
1457 el_free(he);
1458 return NULL;
1461 he->line = ev.str;
1462 if (history(h, &ev, H_GETSIZE) == 0)
1463 history_length = ev.num;
1465 return he;
1470 * replace the line and data of the num-th entry
1472 HIST_ENTRY *
1473 replace_history_entry(int num, const char *line, histdata_t data)
1475 HIST_ENTRY *he;
1476 HistEvent ev;
1477 int curr_num;
1479 if (h == NULL || e == NULL)
1480 rl_initialize();
1482 /* save current position */
1483 if (history(h, &ev, H_CURR) != 0)
1484 return NULL;
1485 curr_num = ev.num;
1487 /* start from the oldest */
1488 if (history(h, &ev, H_LAST) != 0)
1489 return NULL; /* error */
1491 if ((he = el_malloc(sizeof(*he))) == NULL)
1492 return NULL;
1494 /* look forwards for event matching specified offset */
1495 if (history(h, &ev, H_NEXT_EVDATA, num, &he->data))
1496 goto out;
1498 he->line = strdup(ev.str);
1499 if (he->line == NULL)
1500 goto out;
1502 if (history(h, &ev, H_REPLACE, line, data))
1503 goto out;
1505 /* restore pointer to where it was */
1506 if (history(h, &ev, H_SET, curr_num))
1507 goto out;
1509 return he;
1510 out:
1511 el_free(he);
1512 return NULL;
1516 * clear the history list - delete all entries
1518 void
1519 clear_history(void)
1521 HistEvent ev;
1523 if (h == NULL || e == NULL)
1524 rl_initialize();
1526 (void)history(h, &ev, H_CLEAR);
1527 history_offset = history_length = 0;
1532 * returns offset of the current history event
1535 where_history(void)
1537 return history_offset;
1540 static HIST_ENTRY **_history_listp;
1541 static HIST_ENTRY *_history_list;
1543 HIST_ENTRY **
1544 history_list(void)
1546 HistEvent ev;
1547 HIST_ENTRY **nlp, *nl;
1548 int i;
1550 if (history(h, &ev, H_LAST) != 0)
1551 return NULL;
1553 if ((nlp = el_realloc(_history_listp,
1554 (size_t)history_length * sizeof(*nlp))) == NULL)
1555 return NULL;
1556 _history_listp = nlp;
1558 if ((nl = el_realloc(_history_list,
1559 (size_t)history_length * sizeof(*nl))) == NULL)
1560 return NULL;
1561 _history_list = nl;
1563 i = 0;
1564 do {
1565 _history_listp[i] = &_history_list[i];
1566 _history_list[i].line = ev.str;
1567 _history_list[i].data = NULL;
1568 if (i++ == history_length)
1569 abort();
1570 } while (history(h, &ev, H_PREV) == 0);
1571 return _history_listp;
1575 * returns current history event or NULL if there is no such event
1577 HIST_ENTRY *
1578 current_history(void)
1580 HistEvent ev;
1582 if (history(h, &ev, H_PREV_EVENT, history_offset + 1) != 0)
1583 return NULL;
1585 rl_he.line = ev.str;
1586 rl_he.data = NULL;
1587 return &rl_he;
1592 * returns total number of bytes history events' data are using
1595 history_total_bytes(void)
1597 HistEvent ev;
1598 int curr_num;
1599 size_t size;
1601 if (history(h, &ev, H_CURR) != 0)
1602 return -1;
1603 curr_num = ev.num;
1605 (void)history(h, &ev, H_FIRST);
1606 size = 0;
1608 size += strlen(ev.str) * sizeof(*ev.str);
1609 while (history(h, &ev, H_NEXT) == 0);
1611 /* get to the same position as before */
1612 history(h, &ev, H_PREV_EVENT, curr_num);
1614 return (int)size;
1619 * sets the position in the history list to ``pos''
1622 history_set_pos(int pos)
1624 if (pos >= history_length || pos < 0)
1625 return 0;
1627 history_offset = pos;
1628 return 1;
1633 * returns previous event in history and shifts pointer accordingly
1634 * Note that readline and editline define directions in opposite ways.
1636 HIST_ENTRY *
1637 previous_history(void)
1639 HistEvent ev;
1641 if (history_offset == 0)
1642 return NULL;
1644 if (history(h, &ev, H_LAST) != 0)
1645 return NULL;
1647 history_offset--;
1648 return current_history();
1653 * returns next event in history and shifts pointer accordingly
1655 HIST_ENTRY *
1656 next_history(void)
1658 HistEvent ev;
1660 if (history_offset >= history_length)
1661 return NULL;
1663 if (history(h, &ev, H_LAST) != 0)
1664 return NULL;
1666 history_offset++;
1667 return current_history();
1672 * searches for first history event containing the str
1675 history_search(const char *str, int direction)
1677 HistEvent ev;
1678 const char *strp;
1679 int curr_num;
1681 if (history(h, &ev, H_CURR) != 0)
1682 return -1;
1683 curr_num = ev.num;
1685 for (;;) {
1686 if ((strp = strstr(ev.str, str)) != NULL)
1687 return (int)(strp - ev.str);
1688 if (history(h, &ev, direction < 0 ? H_NEXT:H_PREV) != 0)
1689 break;
1691 (void)history(h, &ev, H_SET, curr_num);
1692 return -1;
1697 * searches for first history event beginning with str
1700 history_search_prefix(const char *str, int direction)
1702 HistEvent ev;
1704 return (history(h, &ev, direction < 0 ?
1705 H_PREV_STR : H_NEXT_STR, str));
1710 * search for event in history containing str, starting at offset
1711 * abs(pos); continue backward, if pos<0, forward otherwise
1713 /* ARGSUSED */
1715 history_search_pos(const char *str,
1716 int direction __attribute__((__unused__)), int pos)
1718 HistEvent ev;
1719 int curr_num, off;
1721 off = (pos > 0) ? pos : -pos;
1722 pos = (pos > 0) ? 1 : -1;
1724 if (history(h, &ev, H_CURR) != 0)
1725 return -1;
1726 curr_num = ev.num;
1728 if (!history_set_pos(off) || history(h, &ev, H_CURR) != 0)
1729 return -1;
1731 for (;;) {
1732 if (strstr(ev.str, str))
1733 return off;
1734 if (history(h, &ev, (pos < 0) ? H_PREV : H_NEXT) != 0)
1735 break;
1738 /* set "current" pointer back to previous state */
1739 (void)history(h, &ev,
1740 pos < 0 ? H_NEXT_EVENT : H_PREV_EVENT, curr_num);
1742 return -1;
1746 /********************************/
1747 /* completion functions */
1749 char *
1750 tilde_expand(char *name)
1752 return fn_tilde_expand(name);
1755 char *
1756 filename_completion_function(const char *name, int state)
1758 return fn_filename_completion_function(name, state);
1762 * a completion generator for usernames; returns _first_ username
1763 * which starts with supplied text
1764 * text contains a partial username preceded by random character
1765 * (usually '~'); state resets search from start (??? should we do that anyway)
1766 * it's the caller's responsibility to free the returned value
1768 char *
1769 username_completion_function(const char *text, int state)
1771 #if defined(HAVE_GETPW_R_POSIX) || defined(HAVE_GETPW_R_DRAFT)
1772 struct passwd pwres;
1773 char pwbuf[1024];
1774 #endif
1775 struct passwd *pass = NULL;
1777 if (text[0] == '\0')
1778 return NULL;
1780 if (*text == '~')
1781 text++;
1783 if (state == 0)
1784 setpwent();
1786 while (
1787 (pass = getpwent()) != NULL
1788 && text[0] == pass->pw_name[0]
1789 && strcmp(text, pass->pw_name) == 0)
1790 continue;
1792 if (pass == NULL) {
1793 endpwent();
1794 return NULL;
1796 return strdup(pass->pw_name);
1801 * el-compatible wrapper to send TSTP on ^Z
1803 /* ARGSUSED */
1804 static unsigned char
1805 _el_rl_tstp(EditLine *el __attribute__((__unused__)), int ch __attribute__((__unused__)))
1807 (void)kill(0, SIGTSTP);
1808 return CC_NORM;
1812 * Display list of strings in columnar format on readline's output stream.
1813 * 'matches' is list of strings, 'len' is number of strings in 'matches',
1814 * 'max' is maximum length of string in 'matches'.
1816 void
1817 rl_display_match_list(char **matches, int len, int max)
1820 fn_display_match_list(e, matches, (size_t)len, (size_t)max);
1823 static const char *
1824 /*ARGSUSED*/
1825 _rl_completion_append_character_function(const char *dummy
1826 __attribute__((__unused__)))
1828 static char buf[2];
1829 buf[0] = (char)rl_completion_append_character;
1830 buf[1] = '\0';
1831 return buf;
1836 * complete word at current point
1838 /* ARGSUSED */
1840 rl_complete(int ignore __attribute__((__unused__)), int invoking_key)
1842 static ct_buffer_t wbreak_conv, sprefix_conv;
1843 char *breakchars;
1845 if (h == NULL || e == NULL)
1846 rl_initialize();
1848 if (rl_inhibit_completion) {
1849 char arr[2];
1850 arr[0] = (char)invoking_key;
1851 arr[1] = '\0';
1852 el_insertstr(e, arr);
1853 return CC_REFRESH;
1856 if (rl_completion_word_break_hook != NULL)
1857 breakchars = (*rl_completion_word_break_hook)();
1858 else
1859 breakchars = rl_basic_word_break_characters;
1861 _rl_update_pos();
1863 /* Just look at how many global variables modify this operation! */
1864 return fn_complete(e,
1865 (rl_compentry_func_t *)rl_completion_entry_function,
1866 rl_attempted_completion_function,
1867 ct_decode_string(rl_basic_word_break_characters, &wbreak_conv),
1868 ct_decode_string(breakchars, &sprefix_conv),
1869 _rl_completion_append_character_function,
1870 (size_t)rl_completion_query_items,
1871 &rl_completion_type, &rl_attempted_completion_over,
1872 &rl_point, &rl_end);
1878 /* ARGSUSED */
1879 static unsigned char
1880 _el_rl_complete(EditLine *el __attribute__((__unused__)), int ch)
1882 return (unsigned char)rl_complete(0, ch);
1886 * misc other functions
1890 * bind key c to readline-type function func
1893 rl_bind_key(int c, rl_command_func_t *func)
1895 int retval = -1;
1897 if (h == NULL || e == NULL)
1898 rl_initialize();
1900 if (func == rl_insert) {
1901 /* XXX notice there is no range checking of ``c'' */
1902 e->el_map.key[c] = ED_INSERT;
1903 retval = 0;
1905 return retval;
1910 * read one key from input - handles chars pushed back
1911 * to input stream also
1914 rl_read_key(void)
1916 char fooarr[2 * sizeof(int)];
1918 if (e == NULL || h == NULL)
1919 rl_initialize();
1921 return el_getc(e, fooarr);
1926 * reset the terminal
1928 /* ARGSUSED */
1929 void
1930 rl_reset_terminal(const char *p __attribute__((__unused__)))
1933 if (h == NULL || e == NULL)
1934 rl_initialize();
1935 el_reset(e);
1940 * insert character ``c'' back into input stream, ``count'' times
1943 rl_insert(int count, int c)
1945 char arr[2];
1947 if (h == NULL || e == NULL)
1948 rl_initialize();
1950 /* XXX - int -> char conversion can lose on multichars */
1951 arr[0] = (char)c;
1952 arr[1] = '\0';
1954 for (; count > 0; count--)
1955 el_push(e, arr);
1957 return 0;
1961 rl_insert_text(const char *text)
1963 if (!text || *text == 0)
1964 return 0;
1966 if (h == NULL || e == NULL)
1967 rl_initialize();
1969 if (el_insertstr(e, text) < 0)
1970 return 0;
1971 return (int)strlen(text);
1974 /*ARGSUSED*/
1976 rl_newline(int count __attribute__((__unused__)),
1977 int c __attribute__((__unused__)))
1980 * Readline-4.0 appears to ignore the args.
1982 return rl_insert(1, '\n');
1985 /*ARGSUSED*/
1986 static unsigned char
1987 rl_bind_wrapper(EditLine *el __attribute__((__unused__)), unsigned char c)
1989 if (map[c] == NULL)
1990 return CC_ERROR;
1992 _rl_update_pos();
1994 (*map[c])(1, c);
1996 /* If rl_done was set by the above call, deal with it here */
1997 if (rl_done)
1998 return CC_EOF;
2000 return CC_NORM;
2004 rl_add_defun(const char *name, rl_command_func_t *fun, int c)
2006 char dest[8];
2007 if ((size_t)c >= sizeof(map) / sizeof(map[0]) || c < 0)
2008 return -1;
2009 map[(unsigned char)c] = fun;
2010 el_set(e, EL_ADDFN, name, name, rl_bind_wrapper);
2011 vis(dest, c, VIS_WHITE|VIS_NOSLASH, 0);
2012 el_set(e, EL_BIND, dest, name, NULL);
2013 return 0;
2016 void
2017 rl_callback_read_char(void)
2019 int count = 0, done = 0;
2020 const char *buf = el_gets(e, &count);
2021 char *wbuf;
2023 if (buf == NULL || count-- <= 0)
2024 return;
2025 if (count == 0 && buf[0] == e->el_tty.t_c[TS_IO][C_EOF])
2026 done = 1;
2027 if (buf[count] == '\n' || buf[count] == '\r')
2028 done = 2;
2030 if (done && rl_linefunc != NULL) {
2031 el_set(e, EL_UNBUFFERED, 0);
2032 if (done == 2) {
2033 if ((wbuf = strdup(buf)) != NULL)
2034 wbuf[count] = '\0';
2035 } else
2036 wbuf = NULL;
2037 (*(void (*)(const char *))rl_linefunc)(wbuf);
2038 el_set(e, EL_UNBUFFERED, 1);
2042 void
2043 rl_callback_handler_install(const char *prompt, rl_vcpfunc_t *linefunc)
2045 if (e == NULL) {
2046 rl_initialize();
2048 (void)rl_set_prompt(prompt);
2049 rl_linefunc = linefunc;
2050 el_set(e, EL_UNBUFFERED, 1);
2053 void
2054 rl_callback_handler_remove(void)
2056 el_set(e, EL_UNBUFFERED, 0);
2057 rl_linefunc = NULL;
2060 void
2061 rl_redisplay(void)
2063 char a[2];
2064 a[0] = (char)e->el_tty.t_c[TS_IO][C_REPRINT];
2065 a[1] = '\0';
2066 el_push(e, a);
2070 rl_get_previous_history(int count, int key)
2072 char a[2];
2073 a[0] = (char)key;
2074 a[1] = '\0';
2075 while (count--)
2076 el_push(e, a);
2077 return 0;
2080 void
2081 /*ARGSUSED*/
2082 rl_prep_terminal(int meta_flag __attribute__((__unused__)))
2084 el_set(e, EL_PREP_TERM, 1);
2087 void
2088 rl_deprep_terminal(void)
2090 el_set(e, EL_PREP_TERM, 0);
2094 rl_read_init_file(const char *s)
2096 return el_source(e, s);
2100 rl_parse_and_bind(const char *line)
2102 const char **argv;
2103 int argc;
2104 Tokenizer *tok;
2106 tok = tok_init(NULL);
2107 tok_str(tok, line, &argc, &argv);
2108 argc = el_parse(e, argc, argv);
2109 tok_end(tok);
2110 return argc ? 1 : 0;
2114 rl_variable_bind(const char *var, const char *value)
2117 * The proper return value is undocument, but this is what the
2118 * readline source seems to do.
2120 return el_set(e, EL_BIND, "", var, value, NULL) == -1 ? 1 : 0;
2123 void
2124 rl_stuff_char(int c)
2126 char buf[2];
2128 buf[0] = (char)c;
2129 buf[1] = '\0';
2130 el_insertstr(e, buf);
2133 static int
2134 _rl_event_read_char(EditLine *el, wchar_t *wc)
2136 char ch;
2137 int n;
2138 ssize_t num_read = 0;
2140 ch = '\0';
2141 *wc = L'\0';
2142 while (rl_event_hook) {
2144 (*rl_event_hook)();
2146 #if defined(FIONREAD)
2147 if (ioctl(el->el_infd, FIONREAD, &n) < 0)
2148 return -1;
2149 if (n)
2150 num_read = read(el->el_infd, &ch, (size_t)1);
2151 else
2152 num_read = 0;
2153 #elif defined(F_SETFL) && defined(O_NDELAY)
2154 if ((n = fcntl(el->el_infd, F_GETFL, 0)) < 0)
2155 return -1;
2156 if (fcntl(el->el_infd, F_SETFL, n|O_NDELAY) < 0)
2157 return -1;
2158 num_read = read(el->el_infd, &ch, 1);
2159 if (fcntl(el->el_infd, F_SETFL, n))
2160 return -1;
2161 #else
2162 /* not non-blocking, but what you gonna do? */
2163 num_read = read(el->el_infd, &ch, 1);
2164 return -1;
2165 #endif
2167 if (num_read < 0 && errno == EAGAIN)
2168 continue;
2169 if (num_read == 0)
2170 continue;
2171 break;
2173 if (!rl_event_hook)
2174 el_set(el, EL_GETCFN, EL_BUILTIN_GETCFN);
2175 *wc = (wchar_t)ch;
2176 return (int)num_read;
2179 static void
2180 _rl_update_pos(void)
2182 const LineInfo *li = el_line(e);
2184 rl_point = (int)(li->cursor - li->buffer);
2185 rl_end = (int)(li->lastchar - li->buffer);
2188 void
2189 rl_get_screen_size(int *rows, int *cols)
2191 if (rows)
2192 el_get(e, EL_GETTC, "li", rows, (void *)0);
2193 if (cols)
2194 el_get(e, EL_GETTC, "co", cols, (void *)0);
2197 void
2198 rl_set_screen_size(int rows, int cols)
2200 char buf[64];
2201 (void)snprintf(buf, sizeof(buf), "%d", rows);
2202 el_set(e, EL_SETTC, "li", buf, NULL);
2203 (void)snprintf(buf, sizeof(buf), "%d", cols);
2204 el_set(e, EL_SETTC, "co", buf, NULL);
2207 char **
2208 rl_completion_matches(const char *str, rl_compentry_func_t *fun)
2210 size_t len, max, i, j, min;
2211 char **list, *match, *a, *b;
2213 len = 1;
2214 max = 10;
2215 if ((list = el_malloc(max * sizeof(*list))) == NULL)
2216 return NULL;
2218 while ((match = (*fun)(str, (int)(len - 1))) != NULL) {
2219 list[len++] = match;
2220 if (len == max) {
2221 char **nl;
2222 max += 10;
2223 if ((nl = el_realloc(list, max * sizeof(*nl))) == NULL)
2224 goto out;
2225 list = nl;
2228 if (len == 1)
2229 goto out;
2230 list[len] = NULL;
2231 if (len == 2) {
2232 if ((list[0] = strdup(list[1])) == NULL)
2233 goto out;
2234 return list;
2236 qsort(&list[1], len - 1, sizeof(*list),
2237 (int (*)(const void *, const void *)) strcmp);
2238 min = SIZE_MAX;
2239 for (i = 1, a = list[i]; i < len - 1; i++, a = b) {
2240 b = list[i + 1];
2241 for (j = 0; a[j] && a[j] == b[j]; j++)
2242 continue;
2243 if (min > j)
2244 min = j;
2246 if (min == 0 && *str) {
2247 if ((list[0] = strdup(str)) == NULL)
2248 goto out;
2249 } else {
2250 if ((list[0] = el_malloc((min + 1) * sizeof(*list[0]))) == NULL)
2251 goto out;
2252 (void)memcpy(list[0], list[1], min);
2253 list[0][min] = '\0';
2255 return list;
2257 out:
2258 el_free(list);
2259 return NULL;
2262 char *
2263 rl_filename_completion_function (const char *text, int state)
2265 return fn_filename_completion_function(text, state);
2268 void
2269 rl_forced_update_display(void)
2271 el_set(e, EL_REFRESH);
2275 _rl_abort_internal(void)
2277 el_beep(e);
2278 longjmp(topbuf, 1);
2279 /*NOTREACHED*/
2283 _rl_qsort_string_compare(char **s1, char **s2)
2285 return strcoll(*s1, *s2);
2288 HISTORY_STATE *
2289 history_get_history_state(void)
2291 HISTORY_STATE *hs;
2293 if ((hs = el_malloc(sizeof(*hs))) == NULL)
2294 return NULL;
2295 hs->length = history_length;
2296 return hs;
2300 /*ARGSUSED*/
2301 rl_kill_text(int from __attribute__((__unused__)),
2302 int to __attribute__((__unused__)))
2304 return 0;
2307 Keymap
2308 rl_make_bare_keymap(void)
2310 return NULL;
2313 Keymap
2314 rl_get_keymap(void)
2316 return NULL;
2319 void
2320 /*ARGSUSED*/
2321 rl_set_keymap(Keymap k __attribute__((__unused__)))
2326 /*ARGSUSED*/
2327 rl_generic_bind(int type __attribute__((__unused__)),
2328 const char * keyseq __attribute__((__unused__)),
2329 const char * data __attribute__((__unused__)),
2330 Keymap k __attribute__((__unused__)))
2332 return 0;
2336 /*ARGSUSED*/
2337 rl_bind_key_in_map(int key __attribute__((__unused__)),
2338 rl_command_func_t *fun __attribute__((__unused__)),
2339 Keymap k __attribute__((__unused__)))
2341 return 0;
2344 /* unsupported, but needed by python */
2345 void
2346 rl_cleanup_after_signal(void)
2351 rl_on_new_line(void)
2353 return 0;
2356 void
2357 rl_free_line_state(void)
2362 /*ARGSUSED*/
2363 rl_set_keyboard_input_timeout(int u __attribute__((__unused__)))
2365 return 0;