readline.c revision 1.167 1 /* $NetBSD: readline.c,v 1.167 2021/09/10 13:29:06 christos Exp $ */
2
3 /*-
4 * Copyright (c) 1997 The NetBSD Foundation, Inc.
5 * All rights reserved.
6 *
7 * This code is derived from software contributed to The NetBSD Foundation
8 * by Jaromir Dolecek.
9 *
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.
18 *
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.
30 */
31
32 #include "config.h"
33 #if !defined(lint) && !defined(SCCSID)
34 __RCSID("$NetBSD: readline.c,v 1.167 2021/09/10 13:29:06 christos Exp $");
35 #endif /* not lint && not SCCSID */
36
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>
52
53 #include "readline/readline.h"
54 #include "el.h"
55 #include "fcns.h"
56 #include "filecomplete.h"
57
58 void rl_prep_terminal(int);
59 void rl_deprep_terminal(void);
60
61 /* for rl_complete() */
62 #define TAB '\r'
63
64 /* see comment at the #ifdef for sense of this */
65 /* #define GDB_411_HACK */
66
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 const 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 rl_hook_func_t *rl_event_hook = NULL;
84 KEYMAP_ENTRY_ARRAY emacs_standard_keymap,
85 emacs_meta_keymap,
86 emacs_ctlx_keymap;
87 /*
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.
92 */
93 int rl_catch_signals = 1;
94 int rl_catch_sigwinch = 1;
95
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);
105
106 int rl_inhibit_completion = 0;
107 int rl_attempted_completion_over = 0;
108 const char *rl_basic_word_break_characters = break_chars;
109 char *rl_completer_word_break_characters = NULL;
110 const char *rl_completer_quote_characters = NULL;
111 const char *rl_basic_quote_characters = "\"'";
112 rl_compentry_func_t *rl_completion_entry_function = NULL;
113 char *(*rl_completion_word_break_hook)(void) = NULL;
114 rl_completion_func_t *rl_attempted_completion_function = NULL;
115 Function *rl_pre_input_hook = NULL;
116 Function *rl_startup1_hook = NULL;
117 int (*rl_getc_function)(FILE *) = NULL;
118 char *rl_terminal_name = NULL;
119 int rl_already_prompted = 0;
120 int rl_filename_completion_desired = 0;
121 int rl_ignore_completion_duplicates = 0;
122 int readline_echoing_p = 1;
123 int _rl_print_completions_horizontally = 0;
124 VFunction *rl_redisplay_function = NULL;
125 Function *rl_startup_hook = NULL;
126 VFunction *rl_completion_display_matches_hook = NULL;
127 VFunction *rl_prep_term_function = (VFunction *)rl_prep_terminal;
128 VFunction *rl_deprep_term_function = (VFunction *)rl_deprep_terminal;
129 KEYMAP_ENTRY_ARRAY emacs_meta_keymap;
130 unsigned long rl_readline_state;
131 int _rl_complete_mark_directories;
132 rl_icppfunc_t *rl_directory_completion_hook;
133 int rl_completion_suppress_append;
134 int rl_sort_completion_matches;
135 int _rl_completion_prefix_display_length;
136 int _rl_echoing_p;
137 int history_max_entries;
138 char *rl_display_prompt;
139
140 /*
141 * The current prompt string.
142 */
143 char *rl_prompt = NULL;
144 /*
145 * This is set to character indicating type of completion being done by
146 * rl_complete_internal(); this is available for application completion
147 * functions.
148 */
149 int rl_completion_type = 0;
150
151 /*
152 * If more than this number of items results from query for possible
153 * completions, we ask user if they are sure to really display the list.
154 */
155 int rl_completion_query_items = 100;
156
157 /*
158 * List of characters which are word break characters, but should be left
159 * in the parsed text when it is passed to the completion function.
160 * Shell uses this to help determine what kind of completing to do.
161 */
162 const char *rl_special_prefixes = NULL;
163
164 /*
165 * This is the character appended to the completed words if at the end of
166 * the line. Default is ' ' (a space).
167 */
168 int rl_completion_append_character = ' ';
169
170 /* stuff below is used internally by libedit for readline emulation */
171
172 static History *h = NULL;
173 static EditLine *e = NULL;
174 static rl_command_func_t *map[256];
175 static jmp_buf topbuf;
176
177 /* internal functions */
178 static unsigned char _el_rl_complete(EditLine *, int);
179 static unsigned char _el_rl_tstp(EditLine *, int);
180 static char *_get_prompt(EditLine *);
181 static int _getc_function(EditLine *, wchar_t *);
182 static int _history_expand_command(const char *, size_t, size_t,
183 char **);
184 static char *_rl_compat_sub(const char *, const char *,
185 const char *, int);
186 static int _rl_event_read_char(EditLine *, wchar_t *);
187 static void _rl_update_pos(void);
188
189 static HIST_ENTRY rl_he;
190
191 /* ARGSUSED */
192 static char *
193 _get_prompt(EditLine *el __attribute__((__unused__)))
194 {
195 rl_already_prompted = 1;
196 return rl_prompt;
197 }
198
199
200 /*
201 * read one key from user defined input function
202 */
203 static int
204 /*ARGSUSED*/
205 _getc_function(EditLine *el __attribute__((__unused__)), wchar_t *c)
206 {
207 int i;
208
209 i = (*rl_getc_function)(rl_instream);
210 if (i == -1)
211 return 0;
212 *c = (wchar_t)i;
213 return 1;
214 }
215
216 static void
217 _resize_fun(EditLine *el, void *a)
218 {
219 const LineInfo *li;
220 const char **ap = a;
221
222 li = el_line(el);
223 *ap = li->buffer;
224 }
225
226 static const char *
227 _default_history_file(void)
228 {
229 struct passwd *p;
230 static char *path;
231 size_t len;
232
233 if (path)
234 return path;
235
236 if ((p = getpwuid(getuid())) == NULL)
237 return NULL;
238
239 len = strlen(p->pw_dir) + sizeof("/.history");
240 if ((path = malloc(len)) == NULL)
241 return NULL;
242
243 (void)snprintf(path, len, "%s/.history", p->pw_dir);
244 return path;
245 }
246
247 /*
248 * READLINE compatibility stuff
249 */
250
251 /*
252 * Set the prompt
253 */
254 int
255 rl_set_prompt(const char *prompt)
256 {
257 char *p;
258
259 if (!prompt)
260 prompt = "";
261 if (rl_prompt != NULL && strcmp(rl_prompt, prompt) == 0)
262 return 0;
263 if (rl_prompt)
264 el_free(rl_prompt);
265 rl_prompt = strdup(prompt);
266 if (rl_prompt == NULL)
267 return -1;
268
269 while ((p = strchr(rl_prompt, RL_PROMPT_END_IGNORE)) != NULL) {
270 /* Remove adjacent end/start markers to avoid double-escapes. */
271 if (p[1] == RL_PROMPT_START_IGNORE) {
272 memmove(p, p + 2, 1 + strlen(p + 2));
273 } else {
274 *p = RL_PROMPT_START_IGNORE;
275 }
276 }
277
278 return 0;
279 }
280
281 /*
282 * initialize rl compat stuff
283 */
284 int
285 rl_initialize(void)
286 {
287 HistEvent ev;
288 int editmode = 1;
289 struct termios t;
290
291 if (e != NULL)
292 el_end(e);
293 if (h != NULL)
294 history_end(h);
295
296 if (!rl_instream)
297 rl_instream = stdin;
298 if (!rl_outstream)
299 rl_outstream = stdout;
300
301 /*
302 * See if we don't really want to run the editor
303 */
304 if (tcgetattr(fileno(rl_instream), &t) != -1 && (t.c_lflag & ECHO) == 0)
305 editmode = 0;
306
307 e = el_init_internal(rl_readline_name, rl_instream, rl_outstream,
308 stderr, fileno(rl_instream), fileno(rl_outstream), fileno(stderr),
309 NO_RESET);
310
311 if (!editmode)
312 el_set(e, EL_EDITMODE, 0);
313
314 h = history_init();
315 if (!e || !h)
316 return -1;
317
318 history(h, &ev, H_SETSIZE, INT_MAX); /* unlimited */
319 history_length = 0;
320 max_input_history = INT_MAX;
321 el_set(e, EL_HIST, history, h);
322
323 /* Setup resize function */
324 el_set(e, EL_RESIZE, _resize_fun, &rl_line_buffer);
325
326 /* setup getc function if valid */
327 if (rl_getc_function)
328 el_set(e, EL_GETCFN, _getc_function);
329
330 /* for proper prompt printing in readline() */
331 if (rl_set_prompt("") == -1) {
332 history_end(h);
333 el_end(e);
334 return -1;
335 }
336 el_set(e, EL_PROMPT_ESC, _get_prompt, RL_PROMPT_START_IGNORE);
337 el_set(e, EL_SIGNAL, rl_catch_signals);
338
339 /* set default mode to "emacs"-style and read setting afterwards */
340 /* so this can be overridden */
341 el_set(e, EL_EDITOR, "emacs");
342 if (rl_terminal_name != NULL)
343 el_set(e, EL_TERMINAL, rl_terminal_name);
344 else
345 el_get(e, EL_TERMINAL, &rl_terminal_name);
346
347 /*
348 * Word completion - this has to go AFTER rebinding keys
349 * to emacs-style.
350 */
351 el_set(e, EL_ADDFN, "rl_complete",
352 "ReadLine compatible completion function",
353 _el_rl_complete);
354 el_set(e, EL_BIND, "^I", "rl_complete", NULL);
355
356 /*
357 * Send TSTP when ^Z is pressed.
358 */
359 el_set(e, EL_ADDFN, "rl_tstp",
360 "ReadLine compatible suspend function",
361 _el_rl_tstp);
362 el_set(e, EL_BIND, "^Z", "rl_tstp", NULL);
363
364 /*
365 * Set some readline compatible key-bindings.
366 */
367 el_set(e, EL_BIND, "^R", "em-inc-search-prev", NULL);
368
369 /*
370 * Allow the use of Home/End keys.
371 */
372 el_set(e, EL_BIND, "\\e[1~", "ed-move-to-beg", NULL);
373 el_set(e, EL_BIND, "\\e[4~", "ed-move-to-end", NULL);
374 el_set(e, EL_BIND, "\\e[7~", "ed-move-to-beg", NULL);
375 el_set(e, EL_BIND, "\\e[8~", "ed-move-to-end", NULL);
376 el_set(e, EL_BIND, "\\e[H", "ed-move-to-beg", NULL);
377 el_set(e, EL_BIND, "\\e[F", "ed-move-to-end", NULL);
378
379 /*
380 * Allow the use of the Delete/Insert keys.
381 */
382 el_set(e, EL_BIND, "\\e[3~", "ed-delete-next-char", NULL);
383 el_set(e, EL_BIND, "\\e[2~", "ed-quoted-insert", NULL);
384
385 /*
386 * Ctrl-left-arrow and Ctrl-right-arrow for word moving.
387 */
388 el_set(e, EL_BIND, "\\e[1;5C", "em-next-word", NULL);
389 el_set(e, EL_BIND, "\\e[1;5D", "ed-prev-word", NULL);
390 el_set(e, EL_BIND, "\\e[5C", "em-next-word", NULL);
391 el_set(e, EL_BIND, "\\e[5D", "ed-prev-word", NULL);
392 el_set(e, EL_BIND, "\\e\\e[C", "em-next-word", NULL);
393 el_set(e, EL_BIND, "\\e\\e[D", "ed-prev-word", NULL);
394
395 /* read settings from configuration file */
396 el_source(e, NULL);
397
398 /*
399 * Unfortunately, some applications really do use rl_point
400 * and rl_line_buffer directly.
401 */
402 _resize_fun(e, &rl_line_buffer);
403 _rl_update_pos();
404
405 tty_end(e, TCSADRAIN);
406
407 return 0;
408 }
409
410
411 /*
412 * read one line from input stream and return it, chomping
413 * trailing newline (if there is any)
414 */
415 char *
416 readline(const char *p)
417 {
418 HistEvent ev;
419 const char * volatile prompt = p;
420 int count;
421 const char *ret;
422 char *buf;
423 static int used_event_hook;
424
425 if (e == NULL || h == NULL)
426 rl_initialize();
427 if (rl_startup_hook) {
428 (*rl_startup_hook)(NULL, 0);
429 }
430 tty_init(e);
431
432
433 rl_done = 0;
434
435 (void)setjmp(topbuf);
436 buf = NULL;
437
438 /* update prompt accordingly to what has been passed */
439 if (rl_set_prompt(prompt) == -1)
440 goto out;
441
442 if (rl_pre_input_hook)
443 (*rl_pre_input_hook)(NULL, 0);
444
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;
448 }
449
450 if (!rl_event_hook && used_event_hook) {
451 el_set(e, EL_GETCFN, EL_BUILTIN_GETCFN);
452 used_event_hook = 0;
453 }
454
455 rl_already_prompted = 0;
456
457 /* get one line from input stream */
458 ret = el_gets(e, &count);
459
460 if (ret && count > 0) {
461 buf = strdup(ret);
462 if (buf == NULL)
463 goto out;
464 buf[strcspn(buf, "\n")] = '\0';
465 } else
466 buf = NULL;
467
468 history(h, &ev, H_GETSIZE);
469 history_length = ev.num;
470
471 out:
472 tty_end(e, TCSADRAIN);
473 return buf;
474 }
475
476 /*
477 * history functions
478 */
479
480 /*
481 * is normally called before application starts to use
482 * history expansion functions
483 */
484 void
485 using_history(void)
486 {
487 if (h == NULL || e == NULL)
488 rl_initialize();
489 history_offset = history_length;
490 }
491
492
493 /*
494 * substitute ``what'' with ``with'', returning resulting string; if
495 * globally == 1, substitutes all occurrences of what, otherwise only the
496 * first one
497 */
498 static char *
499 _rl_compat_sub(const char *str, const char *what, const char *with,
500 int globally)
501 {
502 const char *s;
503 char *r, *result;
504 size_t len, with_len, what_len;
505
506 len = strlen(str);
507 with_len = strlen(with);
508 what_len = strlen(what);
509
510 /* calculate length we need for result */
511 s = str;
512 while (*s) {
513 if (*s == *what && !strncmp(s, what, what_len)) {
514 len += with_len - what_len;
515 if (!globally)
516 break;
517 s += what_len;
518 } else
519 s++;
520 }
521 r = result = el_calloc(len + 1, sizeof(*r));
522 if (result == NULL)
523 return NULL;
524 s = str;
525 while (*s) {
526 if (*s == *what && !strncmp(s, what, what_len)) {
527 memcpy(r, with, with_len);
528 r += with_len;
529 s += what_len;
530 if (!globally) {
531 (void)strcpy(r, s);
532 return result;
533 }
534 } else
535 *r++ = *s++;
536 }
537 *r = '\0';
538 return result;
539 }
540
541 static char *last_search_pat; /* last !?pat[?] search pattern */
542 static char *last_search_match; /* last !?pat[?] that matched */
543
544 const char *
545 get_history_event(const char *cmd, int *cindex, int qchar)
546 {
547 int idx, sign, sub, num, begin, ret;
548 size_t len;
549 char *pat;
550 const char *rptr;
551 HistEvent ev;
552
553 idx = *cindex;
554 if (cmd[idx++] != history_expansion_char)
555 return NULL;
556
557 /* find out which event to take */
558 if (cmd[idx] == history_expansion_char || cmd[idx] == '\0') {
559 if (history(h, &ev, H_FIRST) != 0)
560 return NULL;
561 *cindex = cmd[idx]? (idx + 1):idx;
562 return ev.str;
563 }
564 sign = 0;
565 if (cmd[idx] == '-') {
566 sign = 1;
567 idx++;
568 }
569
570 if ('0' <= cmd[idx] && cmd[idx] <= '9') {
571 HIST_ENTRY *he;
572
573 num = 0;
574 while (cmd[idx] && '0' <= cmd[idx] && cmd[idx] <= '9') {
575 num = num * 10 + cmd[idx] - '0';
576 idx++;
577 }
578 if (sign)
579 num = history_length - num + history_base;
580
581 if (!(he = history_get(num)))
582 return NULL;
583
584 *cindex = idx;
585 return he->line;
586 }
587 sub = 0;
588 if (cmd[idx] == '?') {
589 sub = 1;
590 idx++;
591 }
592 begin = idx;
593 while (cmd[idx]) {
594 if (cmd[idx] == '\n')
595 break;
596 if (sub && cmd[idx] == '?')
597 break;
598 if (!sub && (cmd[idx] == ':' || cmd[idx] == ' '
599 || cmd[idx] == '\t' || cmd[idx] == qchar))
600 break;
601 idx++;
602 }
603 len = (size_t)idx - (size_t)begin;
604 if (sub && cmd[idx] == '?')
605 idx++;
606 if (sub && len == 0 && last_search_pat && *last_search_pat)
607 pat = last_search_pat;
608 else if (len == 0)
609 return NULL;
610 else {
611 if ((pat = el_calloc(len + 1, sizeof(*pat))) == NULL)
612 return NULL;
613 (void)strlcpy(pat, cmd + begin, len + 1);
614 }
615
616 if (history(h, &ev, H_CURR) != 0) {
617 if (pat != last_search_pat)
618 el_free(pat);
619 return NULL;
620 }
621 num = ev.num;
622
623 if (sub) {
624 if (pat != last_search_pat) {
625 el_free(last_search_pat);
626 last_search_pat = pat;
627 }
628 ret = history_search(pat, -1);
629 } else
630 ret = history_search_prefix(pat, -1);
631
632 if (ret == -1) {
633 /* restore to end of list on failed search */
634 history(h, &ev, H_FIRST);
635 (void)fprintf(rl_outstream, "%s: Event not found\n", pat);
636 if (pat != last_search_pat)
637 el_free(pat);
638 return NULL;
639 }
640
641 if (sub && len) {
642 el_free(last_search_match);
643 last_search_match = strdup(pat);
644 }
645
646 if (pat != last_search_pat)
647 el_free(pat);
648
649 if (history(h, &ev, H_CURR) != 0)
650 return NULL;
651 *cindex = idx;
652 rptr = ev.str;
653
654 /* roll back to original position */
655 (void)history(h, &ev, H_SET, num);
656
657 return rptr;
658 }
659
660 static int
661 getfrom(const char **cmdp, char **fromp, const char *search, int delim)
662 {
663 size_t size = 16;
664 size_t len = 0;
665 const char *cmd = *cmdp;
666 char *what = el_realloc(*fromp, size * sizeof(*what));
667 if (what == NULL){
668 el_free(*fromp);
669 *fromp = NULL;
670 return 0;
671 }
672 for (; *cmd && *cmd != delim; cmd++) {
673 if (*cmd == '\\' && cmd[1] == delim)
674 cmd++;
675 if (len - 1 >= size) {
676 char *nwhat;
677 nwhat = el_realloc(what, (size <<= 1) * sizeof(*nwhat));
678 if (nwhat == NULL) {
679 el_free(what);
680 el_free(*fromp);
681 *cmdp = cmd;
682 *fromp = NULL;
683 return 0;
684 }
685 what = nwhat;
686 }
687 what[len++] = *cmd;
688 }
689 what[len] = '\0';
690 *fromp = what;
691 *cmdp = cmd;
692 if (*what == '\0') {
693 el_free(what);
694 if (search) {
695 *fromp = strdup(search);
696 if (*fromp == NULL) {
697 return 0;
698 }
699 } else {
700 *fromp = NULL;
701 return -1;
702 }
703 }
704 if (!*cmd) {
705 el_free(what);
706 *fromp = NULL;
707 return -1;
708 }
709
710 cmd++; /* shift after delim */
711 *cmdp = cmd;
712
713 if (!*cmd) {
714 el_free(what);
715 *fromp = NULL;
716 return -1;
717 }
718 return 1;
719 }
720
721 static int
722 getto(const char **cmdp, char **top, const char *from, int delim)
723 {
724 size_t size = 16;
725 size_t len = 0;
726 size_t from_len = strlen(from);
727 const char *cmd = *cmdp;
728 char *with = el_realloc(*top, size * sizeof(*with));
729 *top = NULL;
730 if (with == NULL)
731 goto out;
732
733 for (; *cmd && *cmd != delim; cmd++) {
734 if (len + from_len + 1 >= size) {
735 char *nwith;
736 size += from_len + 1;
737 nwith = el_realloc(with, size * sizeof(*nwith));
738 if (nwith == NULL)
739 goto out;
740 with = nwith;
741 }
742 if (*cmd == '&') {
743 /* safe */
744 strcpy(&with[len], from);
745 len += from_len;
746 continue;
747 }
748 if (*cmd == '\\' && (*(cmd + 1) == delim || *(cmd + 1) == '&'))
749 cmd++;
750 with[len++] = *cmd;
751 }
752 if (!*cmd)
753 goto out;
754 with[len] = '\0';
755 *top = with;
756 *cmdp = cmd;
757 return 1;
758 out:
759 el_free(with);
760 el_free(*top);
761 *top = NULL;
762 *cmdp = cmd;
763 return -1;
764 }
765
766 static void
767 replace(char **tmp, int c)
768 {
769 char *aptr;
770 if ((aptr = strrchr(*tmp, c)) == NULL)
771 return;
772 aptr = strdup(aptr + 1); // XXX: check
773 el_free(*tmp);
774 *tmp = aptr;
775 }
776
777 /*
778 * the real function doing history expansion - takes as argument command
779 * to do and data upon which the command should be executed
780 * does expansion the way I've understood readline documentation
781 *
782 * returns 0 if data was not modified, 1 if it was and 2 if the string
783 * should be only printed and not executed; in case of error,
784 * returns -1 and *result points to NULL
785 * it's the caller's responsibility to free() the string returned in *result
786 */
787 static int
788 _history_expand_command(const char *command, size_t offs, size_t cmdlen,
789 char **result)
790 {
791 char *tmp, *search = NULL, *aptr, delim;
792 const char *ptr, *cmd;
793 static char *from = NULL, *to = NULL;
794 int start, end, idx, has_mods = 0;
795 int p_on = 0, g_on = 0, ev;
796
797 *result = NULL;
798 aptr = NULL;
799 ptr = NULL;
800
801 /* First get event specifier */
802 idx = 0;
803
804 if (strchr(":^*$", command[offs + 1])) {
805 char str[4];
806 /*
807 * "!:" is shorthand for "!!:".
808 * "!^", "!*" and "!$" are shorthand for
809 * "!!:^", "!!:*" and "!!:$" respectively.
810 */
811 str[0] = str[1] = '!';
812 str[2] = '0';
813 ptr = get_history_event(str, &idx, 0);
814 idx = (command[offs + 1] == ':')? 1:0;
815 has_mods = 1;
816 } else {
817 if (command[offs + 1] == '#') {
818 /* use command so far */
819 if ((aptr = el_calloc(offs + 1, sizeof(*aptr)))
820 == NULL)
821 return -1;
822 (void)strlcpy(aptr, command, offs + 1);
823 idx = 1;
824 } else {
825 int qchar;
826
827 qchar = (offs > 0 && command[offs - 1] == '"')? '"':0;
828 ptr = get_history_event(command + offs, &idx, qchar);
829 }
830 has_mods = command[offs + (size_t)idx] == ':';
831 }
832
833 if (ptr == NULL && aptr == NULL)
834 return -1;
835
836 if (!has_mods) {
837 *result = strdup(aptr ? aptr : ptr);
838 if (aptr)
839 el_free(aptr);
840 if (*result == NULL)
841 return -1;
842 return 1;
843 }
844
845 cmd = command + offs + idx + 1;
846
847 /* Now parse any word designators */
848
849 if (*cmd == '%') /* last word matched by ?pat? */
850 tmp = strdup(last_search_match ? last_search_match : "");
851 else if (strchr("^*$-0123456789", *cmd)) {
852 start = end = -1;
853 if (*cmd == '^')
854 start = end = 1, cmd++;
855 else if (*cmd == '$')
856 start = -1, cmd++;
857 else if (*cmd == '*')
858 start = 1, cmd++;
859 else if (*cmd == '-' || isdigit((unsigned char) *cmd)) {
860 start = 0;
861 while (*cmd && '0' <= *cmd && *cmd <= '9')
862 start = start * 10 + *cmd++ - '0';
863
864 if (*cmd == '-') {
865 if (isdigit((unsigned char) cmd[1])) {
866 cmd++;
867 end = 0;
868 while (*cmd && '0' <= *cmd && *cmd <= '9')
869 end = end * 10 + *cmd++ - '0';
870 } else if (cmd[1] == '$') {
871 cmd += 2;
872 end = -1;
873 } else {
874 cmd++;
875 end = -2;
876 }
877 } else if (*cmd == '*')
878 end = -1, cmd++;
879 else
880 end = start;
881 }
882 tmp = history_arg_extract(start, end, aptr? aptr:ptr);
883 if (tmp == NULL) {
884 (void)fprintf(rl_outstream, "%s: Bad word specifier",
885 command + offs + idx);
886 if (aptr)
887 el_free(aptr);
888 return -1;
889 }
890 } else
891 tmp = strdup(aptr? aptr:ptr);
892
893 if (aptr)
894 el_free(aptr);
895
896 if (*cmd == '\0' || ((size_t)(cmd - (command + offs)) >= cmdlen)) {
897 *result = tmp;
898 return 1;
899 }
900
901 for (; *cmd; cmd++) {
902 switch (*cmd) {
903 case ':':
904 continue;
905 case 'h': /* remove trailing path */
906 if ((aptr = strrchr(tmp, '/')) != NULL)
907 *aptr = '\0';
908 continue;
909 case 't': /* remove leading path */
910 replace(&tmp, '/');
911 continue;
912 case 'r': /* remove trailing suffix */
913 if ((aptr = strrchr(tmp, '.')) != NULL)
914 *aptr = '\0';
915 continue;
916 case 'e': /* remove all but suffix */
917 replace(&tmp, '.');
918 continue;
919 case 'p': /* print only */
920 p_on = 1;
921 continue;
922 case 'g':
923 g_on = 2;
924 continue;
925 case '&':
926 if (from == NULL || to == NULL)
927 continue;
928 /*FALLTHROUGH*/
929 case 's':
930 ev = -1;
931 delim = *++cmd;
932 if (delim == '\0' || *++cmd == '\0')
933 goto out;
934 if ((ev = getfrom(&cmd, &from, search, delim)) != 1)
935 goto out;
936 if ((ev = getto(&cmd, &to, from, delim)) != 1)
937 goto out;
938 aptr = _rl_compat_sub(tmp, from, to, g_on);
939 if (aptr) {
940 el_free(tmp);
941 tmp = aptr;
942 }
943 g_on = 0;
944 cmd--;
945 continue;
946 }
947 }
948 *result = tmp;
949 return p_on ? 2 : 1;
950 out:
951 el_free(tmp);
952 return ev;
953
954 }
955
956
957 /*
958 * csh-style history expansion
959 */
960 int
961 history_expand(char *str, char **output)
962 {
963 int ret = 0;
964 size_t idx, i, size;
965 char *tmp, *result;
966
967 if (h == NULL || e == NULL)
968 rl_initialize();
969
970 if (history_expansion_char == 0) {
971 *output = strdup(str);
972 return 0;
973 }
974
975 *output = NULL;
976 if (str[0] == history_subst_char) {
977 /* ^foo^foo2^ is equivalent to !!:s^foo^foo2^ */
978 *output = el_calloc(strlen(str) + 4 + 1, sizeof(**output));
979 if (*output == NULL)
980 return 0;
981 (*output)[0] = (*output)[1] = history_expansion_char;
982 (*output)[2] = ':';
983 (*output)[3] = 's';
984 (void)strcpy((*output) + 4, str);
985 str = *output;
986 } else {
987 *output = strdup(str);
988 if (*output == NULL)
989 return 0;
990 }
991
992 #define ADD_STRING(what, len, fr) \
993 { \
994 if (idx + len + 1 > size) { \
995 char *nresult = el_realloc(result, \
996 (size += len + 1) * sizeof(*nresult)); \
997 if (nresult == NULL) { \
998 el_free(*output); \
999 el_free(fr); \
1000 return 0; \
1001 } \
1002 result = nresult; \
1003 } \
1004 (void)strlcpy(&result[idx], what, len + 1); \
1005 idx += len; \
1006 }
1007
1008 result = NULL;
1009 size = idx = 0;
1010 tmp = NULL;
1011 for (i = 0; str[i];) {
1012 int qchar, loop_again;
1013 size_t len, start, j;
1014
1015 qchar = 0;
1016 loop_again = 1;
1017 start = j = i;
1018 loop:
1019 for (; str[j]; j++) {
1020 if (str[j] == '\\' &&
1021 str[j + 1] == history_expansion_char) {
1022 len = strlen(&str[j + 1]) + 1;
1023 memmove(&str[j], &str[j + 1], len);
1024 continue;
1025 }
1026 if (!loop_again) {
1027 if (isspace((unsigned char) str[j])
1028 || str[j] == qchar)
1029 break;
1030 }
1031 if (str[j] == history_expansion_char
1032 && !strchr(history_no_expand_chars, str[j + 1])
1033 && (!history_inhibit_expansion_function ||
1034 (*history_inhibit_expansion_function)(str,
1035 (int)j) == 0))
1036 break;
1037 }
1038
1039 if (str[j] && loop_again) {
1040 i = j;
1041 qchar = (j > 0 && str[j - 1] == '"' )? '"':0;
1042 j++;
1043 if (str[j] == history_expansion_char)
1044 j++;
1045 loop_again = 0;
1046 goto loop;
1047 }
1048 len = i - start;
1049 ADD_STRING(&str[start], len, NULL);
1050
1051 if (str[i] == '\0' || str[i] != history_expansion_char) {
1052 len = j - i;
1053 ADD_STRING(&str[i], len, NULL);
1054 if (start == 0)
1055 ret = 0;
1056 else
1057 ret = 1;
1058 break;
1059 }
1060 ret = _history_expand_command (str, i, (j - i), &tmp);
1061 if (ret > 0 && tmp) {
1062 len = strlen(tmp);
1063 ADD_STRING(tmp, len, tmp);
1064 }
1065 if (tmp) {
1066 el_free(tmp);
1067 tmp = NULL;
1068 }
1069 i = j;
1070 }
1071
1072 /* ret is 2 for "print only" option */
1073 if (ret == 2) {
1074 add_history(result);
1075 #ifdef GDB_411_HACK
1076 /* gdb 4.11 has been shipped with readline, where */
1077 /* history_expand() returned -1 when the line */
1078 /* should not be executed; in readline 2.1+ */
1079 /* it should return 2 in such a case */
1080 ret = -1;
1081 #endif
1082 }
1083 el_free(*output);
1084 *output = result;
1085
1086 return ret;
1087 }
1088
1089 /*
1090 * Return a string consisting of arguments of "str" from "start" to "end".
1091 */
1092 char *
1093 history_arg_extract(int start, int end, const char *str)
1094 {
1095 size_t i, len, max;
1096 char **arr, *result = NULL;
1097
1098 arr = history_tokenize(str);
1099 if (!arr)
1100 return NULL;
1101 if (arr && *arr == NULL)
1102 goto out;
1103
1104 for (max = 0; arr[max]; max++)
1105 continue;
1106 max--;
1107
1108 if (start == '$')
1109 start = (int)max;
1110 if (end == '$')
1111 end = (int)max;
1112 if (end < 0)
1113 end = (int)max + end + 1;
1114 if (start < 0)
1115 start = end;
1116
1117 if (start < 0 || end < 0 || (size_t)start > max ||
1118 (size_t)end > max || start > end)
1119 goto out;
1120
1121 for (i = (size_t)start, len = 0; i <= (size_t)end; i++)
1122 len += strlen(arr[i]) + 1;
1123 len++;
1124 result = el_calloc(len, sizeof(*result));
1125 if (result == NULL)
1126 goto out;
1127
1128 for (i = (size_t)start, len = 0; i <= (size_t)end; i++) {
1129 (void)strcpy(result + len, arr[i]);
1130 len += strlen(arr[i]);
1131 if (i < (size_t)end)
1132 result[len++] = ' ';
1133 }
1134 result[len] = '\0';
1135
1136 out:
1137 for (i = 0; arr[i]; i++)
1138 el_free(arr[i]);
1139 el_free(arr);
1140
1141 return result;
1142 }
1143
1144 /*
1145 * Parse the string into individual tokens,
1146 * similar to how shell would do it.
1147 */
1148 char **
1149 history_tokenize(const char *str)
1150 {
1151 int size = 1, idx = 0, i, start;
1152 size_t len;
1153 char **result = NULL, *temp, delim = '\0';
1154
1155 for (i = 0; str[i];) {
1156 while (isspace((unsigned char) str[i]))
1157 i++;
1158 start = i;
1159 for (; str[i];) {
1160 if (str[i] == '\\') {
1161 if (str[i+1] != '\0')
1162 i++;
1163 } else if (str[i] == delim)
1164 delim = '\0';
1165 else if (!delim &&
1166 (isspace((unsigned char) str[i]) ||
1167 strchr("()<>;&|$", str[i])))
1168 break;
1169 else if (!delim && strchr("'`\"", str[i]))
1170 delim = str[i];
1171 if (str[i])
1172 i++;
1173 }
1174
1175 if (idx + 2 >= size) {
1176 char **nresult;
1177 size <<= 1;
1178 nresult = el_realloc(result, (size_t)size * sizeof(*nresult));
1179 if (nresult == NULL) {
1180 el_free(result);
1181 return NULL;
1182 }
1183 result = nresult;
1184 }
1185 len = (size_t)i - (size_t)start;
1186 temp = el_calloc(len + 1, sizeof(*temp));
1187 if (temp == NULL) {
1188 for (i = 0; i < idx; i++)
1189 el_free(result[i]);
1190 el_free(result);
1191 return NULL;
1192 }
1193 (void)strlcpy(temp, &str[start], len + 1);
1194 result[idx++] = temp;
1195 result[idx] = NULL;
1196 if (str[i])
1197 i++;
1198 }
1199 return result;
1200 }
1201
1202
1203 /*
1204 * limit size of history record to ``max'' events
1205 */
1206 void
1207 stifle_history(int max)
1208 {
1209 HistEvent ev;
1210 HIST_ENTRY *he;
1211
1212 if (h == NULL || e == NULL)
1213 rl_initialize();
1214
1215 if (history(h, &ev, H_SETSIZE, max) == 0) {
1216 max_input_history = max;
1217 if (history_length > max)
1218 history_base = history_length - max;
1219 while (history_length > max) {
1220 he = remove_history(0);
1221 el_free(he->data);
1222 el_free((void *)(unsigned long)he->line);
1223 el_free(he);
1224 }
1225 }
1226 }
1227
1228
1229 /*
1230 * "unlimit" size of history - set the limit to maximum allowed int value
1231 */
1232 int
1233 unstifle_history(void)
1234 {
1235 HistEvent ev;
1236 int omax;
1237
1238 history(h, &ev, H_SETSIZE, INT_MAX);
1239 omax = max_input_history;
1240 max_input_history = INT_MAX;
1241 return omax; /* some value _must_ be returned */
1242 }
1243
1244
1245 int
1246 history_is_stifled(void)
1247 {
1248
1249 /* cannot return true answer */
1250 return max_input_history != INT_MAX;
1251 }
1252
1253 static const char _history_tmp_template[] = "/tmp/.historyXXXXXX";
1254
1255 int
1256 history_truncate_file (const char *filename, int nlines)
1257 {
1258 int ret = 0;
1259 FILE *fp, *tp;
1260 char template[sizeof(_history_tmp_template)];
1261 char buf[4096];
1262 int fd;
1263 char *cp;
1264 off_t off;
1265 int count = 0;
1266 ssize_t left = 0;
1267
1268 if (filename == NULL && (filename = _default_history_file()) == NULL)
1269 return errno;
1270 if ((fp = fopen(filename, "r+")) == NULL)
1271 return errno;
1272 strcpy(template, _history_tmp_template);
1273 if ((fd = mkstemp(template)) == -1) {
1274 ret = errno;
1275 goto out1;
1276 }
1277
1278 if ((tp = fdopen(fd, "r+")) == NULL) {
1279 close(fd);
1280 ret = errno;
1281 goto out2;
1282 }
1283
1284 for(;;) {
1285 if (fread(buf, sizeof(buf), (size_t)1, fp) != 1) {
1286 if (ferror(fp)) {
1287 ret = errno;
1288 break;
1289 }
1290 if (fseeko(fp, (off_t)sizeof(buf) * count, SEEK_SET) ==
1291 (off_t)-1) {
1292 ret = errno;
1293 break;
1294 }
1295 left = (ssize_t)fread(buf, (size_t)1, sizeof(buf), fp);
1296 if (ferror(fp)) {
1297 ret = errno;
1298 break;
1299 }
1300 if (left == 0) {
1301 count--;
1302 left = sizeof(buf);
1303 } else if (fwrite(buf, (size_t)left, (size_t)1, tp)
1304 != 1) {
1305 ret = errno;
1306 break;
1307 }
1308 fflush(tp);
1309 break;
1310 }
1311 if (fwrite(buf, sizeof(buf), (size_t)1, tp) != 1) {
1312 ret = errno;
1313 break;
1314 }
1315 count++;
1316 }
1317 if (ret)
1318 goto out3;
1319 cp = buf + left - 1;
1320 if(*cp != '\n')
1321 cp++;
1322 for(;;) {
1323 while (--cp >= buf) {
1324 if (*cp == '\n') {
1325 if (--nlines == 0) {
1326 if (++cp >= buf + sizeof(buf)) {
1327 count++;
1328 cp = buf;
1329 }
1330 break;
1331 }
1332 }
1333 }
1334 if (nlines <= 0 || count == 0)
1335 break;
1336 count--;
1337 if (fseeko(tp, (off_t)sizeof(buf) * count, SEEK_SET) < 0) {
1338 ret = errno;
1339 break;
1340 }
1341 if (fread(buf, sizeof(buf), (size_t)1, tp) != 1) {
1342 if (ferror(tp)) {
1343 ret = errno;
1344 break;
1345 }
1346 ret = EAGAIN;
1347 break;
1348 }
1349 cp = buf + sizeof(buf);
1350 }
1351
1352 if (ret || nlines > 0)
1353 goto out3;
1354
1355 if (fseeko(fp, (off_t)0, SEEK_SET) == (off_t)-1) {
1356 ret = errno;
1357 goto out3;
1358 }
1359
1360 if (fseeko(tp, (off_t)sizeof(buf) * count + (cp - buf), SEEK_SET) ==
1361 (off_t)-1) {
1362 ret = errno;
1363 goto out3;
1364 }
1365
1366 for(;;) {
1367 if ((left = (ssize_t)fread(buf, (size_t)1, sizeof(buf), tp)) == 0) {
1368 if (ferror(fp))
1369 ret = errno;
1370 break;
1371 }
1372 if (fwrite(buf, (size_t)left, (size_t)1, fp) != 1) {
1373 ret = errno;
1374 break;
1375 }
1376 }
1377 fflush(fp);
1378 if((off = ftello(fp)) > 0)
1379 (void)ftruncate(fileno(fp), off);
1380 out3:
1381 fclose(tp);
1382 out2:
1383 unlink(template);
1384 out1:
1385 fclose(fp);
1386
1387 return ret;
1388 }
1389
1390
1391 /*
1392 * read history from a file given
1393 */
1394 int
1395 read_history(const char *filename)
1396 {
1397 HistEvent ev;
1398
1399 if (h == NULL || e == NULL)
1400 rl_initialize();
1401 if (filename == NULL && (filename = _default_history_file()) == NULL)
1402 return errno;
1403 errno = 0;
1404 if (history(h, &ev, H_LOAD, filename) == -1)
1405 return errno ? errno : EINVAL;
1406 if (history(h, &ev, H_GETSIZE) == 0)
1407 history_length = ev.num;
1408 if (history_length < 0)
1409 return EINVAL;
1410 return 0;
1411 }
1412
1413
1414 /*
1415 * write history to a file given
1416 */
1417 int
1418 write_history(const char *filename)
1419 {
1420 HistEvent ev;
1421
1422 if (h == NULL || e == NULL)
1423 rl_initialize();
1424 if (filename == NULL && (filename = _default_history_file()) == NULL)
1425 return errno;
1426 return history(h, &ev, H_SAVE, filename) == -1 ?
1427 (errno ? errno : EINVAL) : 0;
1428 }
1429
1430 int
1431 append_history(int n, const char *filename)
1432 {
1433 HistEvent ev;
1434 FILE *fp;
1435
1436 if (h == NULL || e == NULL)
1437 rl_initialize();
1438 if (filename == NULL && (filename = _default_history_file()) == NULL)
1439 return errno;
1440
1441 if ((fp = fopen(filename, "a")) == NULL)
1442 return errno;
1443
1444 if (history(h, &ev, H_NSAVE_FP, (size_t)n, fp) == -1) {
1445 int serrno = errno ? errno : EINVAL;
1446 fclose(fp);
1447 return serrno;
1448 }
1449 fclose(fp);
1450 return 0;
1451 }
1452
1453 /*
1454 * returns history ``num''th event
1455 *
1456 * returned pointer points to static variable
1457 */
1458 HIST_ENTRY *
1459 history_get(int num)
1460 {
1461 static HIST_ENTRY she;
1462 HistEvent ev;
1463 int curr_num;
1464
1465 if (h == NULL || e == NULL)
1466 rl_initialize();
1467
1468 if (num < history_base)
1469 return NULL;
1470
1471 /* save current position */
1472 if (history(h, &ev, H_CURR) != 0)
1473 return NULL;
1474 curr_num = ev.num;
1475
1476 /*
1477 * use H_DELDATA to set to nth history (without delete) by passing
1478 * (void **)-1 -- as in history_set_pos
1479 */
1480 if (history(h, &ev, H_DELDATA, num - history_base, (void **)-1) != 0)
1481 goto out;
1482
1483 /* get current entry */
1484 if (history(h, &ev, H_CURR) != 0)
1485 goto out;
1486 if (history(h, &ev, H_NEXT_EVDATA, ev.num, &she.data) != 0)
1487 goto out;
1488 she.line = ev.str;
1489
1490 /* restore pointer to where it was */
1491 (void)history(h, &ev, H_SET, curr_num);
1492
1493 return &she;
1494
1495 out:
1496 /* restore pointer to where it was */
1497 (void)history(h, &ev, H_SET, curr_num);
1498 return NULL;
1499 }
1500
1501
1502 /*
1503 * add the line to history table
1504 */
1505 int
1506 add_history(const char *line)
1507 {
1508 HistEvent ev;
1509
1510 if (h == NULL || e == NULL)
1511 rl_initialize();
1512
1513 if (history(h, &ev, H_ENTER, line) == -1)
1514 return 0;
1515
1516 (void)history(h, &ev, H_GETSIZE);
1517 if (ev.num == history_length)
1518 history_base++;
1519 else {
1520 history_offset++;
1521 history_length = ev.num;
1522 }
1523 return 0;
1524 }
1525
1526
1527 /*
1528 * remove the specified entry from the history list and return it.
1529 */
1530 HIST_ENTRY *
1531 remove_history(int num)
1532 {
1533 HIST_ENTRY *he;
1534 HistEvent ev;
1535
1536 if (h == NULL || e == NULL)
1537 rl_initialize();
1538
1539 if ((he = el_malloc(sizeof(*he))) == NULL)
1540 return NULL;
1541
1542 if (history(h, &ev, H_DELDATA, num, &he->data) != 0) {
1543 el_free(he);
1544 return NULL;
1545 }
1546
1547 he->line = ev.str;
1548 if (history(h, &ev, H_GETSIZE) == 0)
1549 history_length = ev.num;
1550
1551 return he;
1552 }
1553
1554
1555 /*
1556 * replace the line and data of the num-th entry
1557 */
1558 HIST_ENTRY *
1559 replace_history_entry(int num, const char *line, histdata_t data)
1560 {
1561 HIST_ENTRY *he;
1562 HistEvent ev;
1563 int curr_num;
1564
1565 if (h == NULL || e == NULL)
1566 rl_initialize();
1567
1568 /* save current position */
1569 if (history(h, &ev, H_CURR) != 0)
1570 return NULL;
1571 curr_num = ev.num;
1572
1573 /* start from the oldest */
1574 if (history(h, &ev, H_LAST) != 0)
1575 return NULL; /* error */
1576
1577 if ((he = el_malloc(sizeof(*he))) == NULL)
1578 return NULL;
1579
1580 /* look forwards for event matching specified offset */
1581 if (history(h, &ev, H_NEXT_EVDATA, num, &he->data))
1582 goto out;
1583
1584 he->line = strdup(ev.str);
1585 if (he->line == NULL)
1586 goto out;
1587
1588 if (history(h, &ev, H_REPLACE, line, data))
1589 goto out;
1590
1591 /* restore pointer to where it was */
1592 if (history(h, &ev, H_SET, curr_num))
1593 goto out;
1594
1595 return he;
1596 out:
1597 el_free(he);
1598 return NULL;
1599 }
1600
1601 /*
1602 * clear the history list - delete all entries
1603 */
1604 void
1605 clear_history(void)
1606 {
1607 HistEvent ev;
1608
1609 if (h == NULL || e == NULL)
1610 rl_initialize();
1611
1612 (void)history(h, &ev, H_CLEAR);
1613 history_offset = history_length = 0;
1614 }
1615
1616
1617 /*
1618 * returns offset of the current history event
1619 */
1620 int
1621 where_history(void)
1622 {
1623 return history_offset;
1624 }
1625
1626 static HIST_ENTRY **_history_listp;
1627 static HIST_ENTRY *_history_list;
1628
1629 HIST_ENTRY **
1630 history_list(void)
1631 {
1632 HistEvent ev;
1633 HIST_ENTRY **nlp, *nl;
1634 int i;
1635
1636 if (history(h, &ev, H_LAST) != 0)
1637 return NULL;
1638
1639 if ((nlp = el_realloc(_history_listp,
1640 ((size_t)history_length + 1) * sizeof(*nlp))) == NULL)
1641 return NULL;
1642 _history_listp = nlp;
1643
1644 if ((nl = el_realloc(_history_list,
1645 (size_t)history_length * sizeof(*nl))) == NULL)
1646 return NULL;
1647 _history_list = nl;
1648
1649 i = 0;
1650 do {
1651 _history_listp[i] = &_history_list[i];
1652 _history_list[i].line = ev.str;
1653 _history_list[i].data = NULL;
1654 if (i++ == history_length)
1655 abort();
1656 } while (history(h, &ev, H_PREV) == 0);
1657 _history_listp[i] = NULL;
1658 return _history_listp;
1659 }
1660
1661 /*
1662 * returns current history event or NULL if there is no such event
1663 */
1664 HIST_ENTRY *
1665 current_history(void)
1666 {
1667 HistEvent ev;
1668
1669 if (history(h, &ev, H_PREV_EVENT, history_offset + 1) != 0)
1670 return NULL;
1671
1672 rl_he.line = ev.str;
1673 rl_he.data = NULL;
1674 return &rl_he;
1675 }
1676
1677
1678 /*
1679 * returns total number of bytes history events' data are using
1680 */
1681 int
1682 history_total_bytes(void)
1683 {
1684 HistEvent ev;
1685 int curr_num;
1686 size_t size;
1687
1688 if (history(h, &ev, H_CURR) != 0)
1689 return -1;
1690 curr_num = ev.num;
1691
1692 (void)history(h, &ev, H_FIRST);
1693 size = 0;
1694 do
1695 size += strlen(ev.str) * sizeof(*ev.str);
1696 while (history(h, &ev, H_NEXT) == 0);
1697
1698 /* get to the same position as before */
1699 history(h, &ev, H_PREV_EVENT, curr_num);
1700
1701 return (int)size;
1702 }
1703
1704
1705 /*
1706 * sets the position in the history list to ``pos''
1707 */
1708 int
1709 history_set_pos(int pos)
1710 {
1711 if (pos >= history_length || pos < 0)
1712 return 0;
1713
1714 history_offset = pos;
1715 return 1;
1716 }
1717
1718
1719 /*
1720 * returns previous event in history and shifts pointer accordingly
1721 * Note that readline and editline define directions in opposite ways.
1722 */
1723 HIST_ENTRY *
1724 previous_history(void)
1725 {
1726 HistEvent ev;
1727
1728 if (history_offset == 0)
1729 return NULL;
1730
1731 if (history(h, &ev, H_LAST) != 0)
1732 return NULL;
1733
1734 history_offset--;
1735 return current_history();
1736 }
1737
1738
1739 /*
1740 * returns next event in history and shifts pointer accordingly
1741 */
1742 HIST_ENTRY *
1743 next_history(void)
1744 {
1745 HistEvent ev;
1746
1747 if (history_offset >= history_length)
1748 return NULL;
1749
1750 if (history(h, &ev, H_LAST) != 0)
1751 return NULL;
1752
1753 history_offset++;
1754 return current_history();
1755 }
1756
1757
1758 /*
1759 * searches for first history event containing the str
1760 */
1761 int
1762 history_search(const char *str, int direction)
1763 {
1764 HistEvent ev;
1765 const char *strp;
1766 int curr_num;
1767
1768 if (history(h, &ev, H_CURR) != 0)
1769 return -1;
1770 curr_num = ev.num;
1771
1772 for (;;) {
1773 if ((strp = strstr(ev.str, str)) != NULL)
1774 return (int)(strp - ev.str);
1775 if (history(h, &ev, direction < 0 ? H_NEXT:H_PREV) != 0)
1776 break;
1777 }
1778 (void)history(h, &ev, H_SET, curr_num);
1779 return -1;
1780 }
1781
1782
1783 /*
1784 * searches for first history event beginning with str
1785 */
1786 int
1787 history_search_prefix(const char *str, int direction)
1788 {
1789 HistEvent ev;
1790
1791 return (history(h, &ev, direction < 0 ?
1792 H_PREV_STR : H_NEXT_STR, str));
1793 }
1794
1795
1796 /*
1797 * search for event in history containing str, starting at offset
1798 * abs(pos); continue backward, if pos<0, forward otherwise
1799 */
1800 /* ARGSUSED */
1801 int
1802 history_search_pos(const char *str,
1803 int direction __attribute__((__unused__)), int pos)
1804 {
1805 HistEvent ev;
1806 int curr_num, off;
1807
1808 off = (pos > 0) ? pos : -pos;
1809 pos = (pos > 0) ? 1 : -1;
1810
1811 if (history(h, &ev, H_CURR) != 0)
1812 return -1;
1813 curr_num = ev.num;
1814
1815 if (!history_set_pos(off) || history(h, &ev, H_CURR) != 0)
1816 return -1;
1817
1818 for (;;) {
1819 if (strstr(ev.str, str))
1820 return off;
1821 if (history(h, &ev, (pos < 0) ? H_PREV : H_NEXT) != 0)
1822 break;
1823 }
1824
1825 /* set "current" pointer back to previous state */
1826 (void)history(h, &ev,
1827 pos < 0 ? H_NEXT_EVENT : H_PREV_EVENT, curr_num);
1828
1829 return -1;
1830 }
1831
1832
1833 /********************************/
1834 /* completion functions */
1835
1836 char *
1837 tilde_expand(char *name)
1838 {
1839 return fn_tilde_expand(name);
1840 }
1841
1842 char *
1843 filename_completion_function(const char *name, int state)
1844 {
1845 return fn_filename_completion_function(name, state);
1846 }
1847
1848 /*
1849 * a completion generator for usernames; returns _first_ username
1850 * which starts with supplied text
1851 * text contains a partial username preceded by random character
1852 * (usually '~'); state resets search from start (??? should we do that anyway)
1853 * it's the caller's responsibility to free the returned value
1854 */
1855 char *
1856 username_completion_function(const char *text, int state)
1857 {
1858 #if defined(HAVE_GETPW_R_POSIX) || defined(HAVE_GETPW_R_DRAFT)
1859 struct passwd pwres;
1860 char pwbuf[1024];
1861 #endif
1862 struct passwd *pass = NULL;
1863
1864 if (text[0] == '\0')
1865 return NULL;
1866
1867 if (*text == '~')
1868 text++;
1869
1870 if (state == 0)
1871 setpwent();
1872
1873 while (
1874 #if defined(HAVE_GETPW_R_POSIX) || defined(HAVE_GETPW_R_DRAFT)
1875 getpwent_r(&pwres, pwbuf, sizeof(pwbuf), &pass) == 0 && pass != NULL
1876 #else
1877 (pass = getpwent()) != NULL
1878 #endif
1879 && text[0] == pass->pw_name[0]
1880 && strcmp(text, pass->pw_name) == 0)
1881 continue;
1882
1883 if (pass == NULL) {
1884 endpwent();
1885 return NULL;
1886 }
1887 return strdup(pass->pw_name);
1888 }
1889
1890
1891 /*
1892 * el-compatible wrapper to send TSTP on ^Z
1893 */
1894 /* ARGSUSED */
1895 static unsigned char
1896 _el_rl_tstp(EditLine *el __attribute__((__unused__)), int ch __attribute__((__unused__)))
1897 {
1898 (void)kill(0, SIGTSTP);
1899 return CC_NORM;
1900 }
1901
1902 static const char *
1903 /*ARGSUSED*/
1904 _rl_completion_append_character_function(const char *dummy
1905 __attribute__((__unused__)))
1906 {
1907 static char buf[2];
1908 buf[0] = (char)rl_completion_append_character;
1909 buf[1] = '\0';
1910 return buf;
1911 }
1912
1913
1914 /*
1915 * Display list of strings in columnar format on readline's output stream.
1916 * 'matches' is list of strings, 'len' is number of strings in 'matches',
1917 * 'max' is maximum length of string in 'matches'.
1918 */
1919 void
1920 rl_display_match_list(char **matches, int len, int max)
1921 {
1922
1923 fn_display_match_list(e, matches, (size_t)len, (size_t)max,
1924 _rl_completion_append_character_function);
1925 }
1926
1927 /*
1928 * complete word at current point
1929 */
1930 /* ARGSUSED */
1931 int
1932 rl_complete(int ignore __attribute__((__unused__)), int invoking_key)
1933 {
1934 static ct_buffer_t wbreak_conv, sprefix_conv;
1935 const char *breakchars;
1936
1937 if (h == NULL || e == NULL)
1938 rl_initialize();
1939
1940 if (rl_inhibit_completion) {
1941 char arr[2];
1942 arr[0] = (char)invoking_key;
1943 arr[1] = '\0';
1944 el_insertstr(e, arr);
1945 return CC_REFRESH;
1946 }
1947
1948 if (rl_completion_word_break_hook != NULL)
1949 breakchars = (*rl_completion_word_break_hook)();
1950 else
1951 breakchars = rl_basic_word_break_characters;
1952
1953 _rl_update_pos();
1954
1955 /* Just look at how many global variables modify this operation! */
1956 return fn_complete(e,
1957 (rl_compentry_func_t *)rl_completion_entry_function,
1958 rl_attempted_completion_function,
1959 ct_decode_string(rl_basic_word_break_characters, &wbreak_conv),
1960 ct_decode_string(breakchars, &sprefix_conv),
1961 _rl_completion_append_character_function,
1962 (size_t)rl_completion_query_items,
1963 &rl_completion_type, &rl_attempted_completion_over,
1964 &rl_point, &rl_end);
1965
1966
1967 }
1968
1969
1970 /* ARGSUSED */
1971 static unsigned char
1972 _el_rl_complete(EditLine *el __attribute__((__unused__)), int ch)
1973 {
1974 return (unsigned char)rl_complete(0, ch);
1975 }
1976
1977 /*
1978 * misc other functions
1979 */
1980
1981 /*
1982 * bind key c to readline-type function func
1983 */
1984 int
1985 rl_bind_key(int c, rl_command_func_t *func)
1986 {
1987 int retval = -1;
1988
1989 if (h == NULL || e == NULL)
1990 rl_initialize();
1991
1992 if (func == rl_insert) {
1993 /* XXX notice there is no range checking of ``c'' */
1994 e->el_map.key[c] = ED_INSERT;
1995 retval = 0;
1996 }
1997 return retval;
1998 }
1999
2000
2001 /*
2002 * read one key from input - handles chars pushed back
2003 * to input stream also
2004 */
2005 int
2006 rl_read_key(void)
2007 {
2008 char fooarr[2 * sizeof(int)];
2009
2010 if (e == NULL || h == NULL)
2011 rl_initialize();
2012
2013 return el_getc(e, fooarr);
2014 }
2015
2016
2017 /*
2018 * reset the terminal
2019 */
2020 /* ARGSUSED */
2021 int
2022 rl_reset_terminal(const char *p __attribute__((__unused__)))
2023 {
2024
2025 if (h == NULL || e == NULL)
2026 rl_initialize();
2027 el_reset(e);
2028 return 0;
2029 }
2030
2031
2032 /*
2033 * insert character ``c'' back into input stream, ``count'' times
2034 */
2035 int
2036 rl_insert(int count, int c)
2037 {
2038 char arr[2];
2039
2040 if (h == NULL || e == NULL)
2041 rl_initialize();
2042
2043 /* XXX - int -> char conversion can lose on multichars */
2044 arr[0] = (char)c;
2045 arr[1] = '\0';
2046
2047 for (; count > 0; count--)
2048 el_push(e, arr);
2049
2050 return 0;
2051 }
2052
2053 int
2054 rl_insert_text(const char *text)
2055 {
2056 if (!text || *text == 0)
2057 return 0;
2058
2059 if (h == NULL || e == NULL)
2060 rl_initialize();
2061
2062 if (el_insertstr(e, text) < 0)
2063 return 0;
2064 return (int)strlen(text);
2065 }
2066
2067 /*ARGSUSED*/
2068 int
2069 rl_newline(int count __attribute__((__unused__)),
2070 int c __attribute__((__unused__)))
2071 {
2072 /*
2073 * Readline-4.0 appears to ignore the args.
2074 */
2075 return rl_insert(1, '\n');
2076 }
2077
2078 /*ARGSUSED*/
2079 static unsigned char
2080 rl_bind_wrapper(EditLine *el __attribute__((__unused__)), unsigned char c)
2081 {
2082 if (map[c] == NULL)
2083 return CC_ERROR;
2084
2085 _rl_update_pos();
2086
2087 (*map[c])(1, c);
2088
2089 /* If rl_done was set by the above call, deal with it here */
2090 if (rl_done)
2091 return CC_EOF;
2092
2093 return CC_NORM;
2094 }
2095
2096 int
2097 rl_add_defun(const char *name, rl_command_func_t *fun, int c)
2098 {
2099 char dest[8];
2100 if ((size_t)c >= sizeof(map) / sizeof(map[0]) || c < 0)
2101 return -1;
2102 map[(unsigned char)c] = fun;
2103 el_set(e, EL_ADDFN, name, name, rl_bind_wrapper);
2104 vis(dest, c, VIS_WHITE|VIS_NOSLASH, 0);
2105 el_set(e, EL_BIND, dest, name, NULL);
2106 return 0;
2107 }
2108
2109 void
2110 rl_callback_read_char(void)
2111 {
2112 int count = 0, done = 0;
2113 const char *buf = el_gets(e, &count);
2114 char *wbuf;
2115
2116 el_set(e, EL_UNBUFFERED, 1);
2117 if (buf == NULL || count-- <= 0)
2118 return;
2119 if (count == 0 && buf[0] == e->el_tty.t_c[TS_IO][C_EOF])
2120 done = 1;
2121 if (buf[count] == '\n' || buf[count] == '\r')
2122 done = 2;
2123
2124 if (done && rl_linefunc != NULL) {
2125 el_set(e, EL_UNBUFFERED, 0);
2126 if (done == 2) {
2127 if ((wbuf = strdup(buf)) != NULL)
2128 wbuf[count] = '\0';
2129 } else
2130 wbuf = NULL;
2131 (*(void (*)(const char *))rl_linefunc)(wbuf);
2132 }
2133 }
2134
2135 void
2136 rl_callback_handler_install(const char *prompt, rl_vcpfunc_t *linefunc)
2137 {
2138 if (e == NULL) {
2139 rl_initialize();
2140 }
2141 (void)rl_set_prompt(prompt);
2142 rl_linefunc = linefunc;
2143 el_set(e, EL_UNBUFFERED, 1);
2144 }
2145
2146 void
2147 rl_callback_handler_remove(void)
2148 {
2149 el_set(e, EL_UNBUFFERED, 0);
2150 rl_linefunc = NULL;
2151 }
2152
2153 void
2154 rl_redisplay(void)
2155 {
2156 char a[2];
2157 a[0] = (char)e->el_tty.t_c[TS_IO][C_REPRINT];
2158 a[1] = '\0';
2159 el_push(e, a);
2160 }
2161
2162 int
2163 rl_get_previous_history(int count, int key)
2164 {
2165 char a[2];
2166 a[0] = (char)key;
2167 a[1] = '\0';
2168 while (count--)
2169 el_push(e, a);
2170 return 0;
2171 }
2172
2173 void
2174 /*ARGSUSED*/
2175 rl_prep_terminal(int meta_flag __attribute__((__unused__)))
2176 {
2177 el_set(e, EL_PREP_TERM, 1);
2178 }
2179
2180 void
2181 rl_deprep_terminal(void)
2182 {
2183 el_set(e, EL_PREP_TERM, 0);
2184 }
2185
2186 int
2187 rl_read_init_file(const char *s)
2188 {
2189 return el_source(e, s);
2190 }
2191
2192 int
2193 rl_parse_and_bind(const char *line)
2194 {
2195 const char **argv;
2196 int argc;
2197 Tokenizer *tok;
2198
2199 tok = tok_init(NULL);
2200 tok_str(tok, line, &argc, &argv);
2201 argc = el_parse(e, argc, argv);
2202 tok_end(tok);
2203 return argc ? 1 : 0;
2204 }
2205
2206 int
2207 rl_variable_bind(const char *var, const char *value)
2208 {
2209 /*
2210 * The proper return value is undocument, but this is what the
2211 * readline source seems to do.
2212 */
2213 return el_set(e, EL_BIND, "", var, value, NULL) == -1 ? 1 : 0;
2214 }
2215
2216 int
2217 rl_stuff_char(int c)
2218 {
2219 char buf[2];
2220
2221 buf[0] = (char)c;
2222 buf[1] = '\0';
2223 el_insertstr(e, buf);
2224 return 1;
2225 }
2226
2227 static int
2228 _rl_event_read_char(EditLine *el, wchar_t *wc)
2229 {
2230 char ch;
2231 int n;
2232 ssize_t num_read = 0;
2233
2234 ch = '\0';
2235 *wc = L'\0';
2236 while (rl_event_hook) {
2237
2238 (*rl_event_hook)();
2239
2240 #if defined(FIONREAD)
2241 if (ioctl(el->el_infd, FIONREAD, &n) < 0)
2242 return -1;
2243 if (n)
2244 num_read = read(el->el_infd, &ch, (size_t)1);
2245 else
2246 num_read = 0;
2247 #elif defined(F_SETFL) && defined(O_NDELAY)
2248 if ((n = fcntl(el->el_infd, F_GETFL, 0)) < 0)
2249 return -1;
2250 if (fcntl(el->el_infd, F_SETFL, n|O_NDELAY) < 0)
2251 return -1;
2252 num_read = read(el->el_infd, &ch, 1);
2253 if (fcntl(el->el_infd, F_SETFL, n))
2254 return -1;
2255 #else
2256 /* not non-blocking, but what you gonna do? */
2257 num_read = read(el->el_infd, &ch, 1);
2258 return -1;
2259 #endif
2260
2261 if (num_read < 0 && errno == EAGAIN)
2262 continue;
2263 if (num_read == 0)
2264 continue;
2265 break;
2266 }
2267 if (!rl_event_hook)
2268 el_set(el, EL_GETCFN, EL_BUILTIN_GETCFN);
2269 *wc = (wchar_t)ch;
2270 return (int)num_read;
2271 }
2272
2273 static void
2274 _rl_update_pos(void)
2275 {
2276 const LineInfo *li = el_line(e);
2277
2278 rl_point = (int)(li->cursor - li->buffer);
2279 rl_end = (int)(li->lastchar - li->buffer);
2280 rl_line_buffer[rl_end] = '\0';
2281 }
2282
2283 void
2284 rl_get_screen_size(int *rows, int *cols)
2285 {
2286 if (rows)
2287 el_get(e, EL_GETTC, "li", rows);
2288 if (cols)
2289 el_get(e, EL_GETTC, "co", cols);
2290 }
2291
2292 void
2293 rl_set_screen_size(int rows, int cols)
2294 {
2295 char buf[64];
2296 (void)snprintf(buf, sizeof(buf), "%d", rows);
2297 el_set(e, EL_SETTC, "li", buf, NULL);
2298 (void)snprintf(buf, sizeof(buf), "%d", cols);
2299 el_set(e, EL_SETTC, "co", buf, NULL);
2300 }
2301
2302 char **
2303 rl_completion_matches(const char *str, rl_compentry_func_t *fun)
2304 {
2305 size_t len, max, i, j, min;
2306 char **list, *match, *a, *b;
2307
2308 len = 1;
2309 max = 10;
2310 if ((list = el_calloc(max, sizeof(*list))) == NULL)
2311 return NULL;
2312
2313 while ((match = (*fun)(str, (int)(len - 1))) != NULL) {
2314 list[len++] = match;
2315 if (len == max) {
2316 char **nl;
2317 max += 10;
2318 if ((nl = el_realloc(list, max * sizeof(*nl))) == NULL)
2319 goto out;
2320 list = nl;
2321 }
2322 }
2323 if (len == 1)
2324 goto out;
2325 list[len] = NULL;
2326 if (len == 2) {
2327 if ((list[0] = strdup(list[1])) == NULL)
2328 goto out;
2329 return list;
2330 }
2331 qsort(&list[1], len - 1, sizeof(*list),
2332 (int (*)(const void *, const void *)) strcmp);
2333 min = SIZE_MAX;
2334 for (i = 1, a = list[i]; i < len - 1; i++, a = b) {
2335 b = list[i + 1];
2336 for (j = 0; a[j] && a[j] == b[j]; j++)
2337 continue;
2338 if (min > j)
2339 min = j;
2340 }
2341 if (min == 0 && *str) {
2342 if ((list[0] = strdup(str)) == NULL)
2343 goto out;
2344 } else {
2345 if ((list[0] = el_calloc(min + 1, sizeof(*list[0]))) == NULL)
2346 goto out;
2347 (void)memcpy(list[0], list[1], min);
2348 list[0][min] = '\0';
2349 }
2350 return list;
2351
2352 out:
2353 el_free(list);
2354 return NULL;
2355 }
2356
2357 char *
2358 rl_filename_completion_function (const char *text, int state)
2359 {
2360 return fn_filename_completion_function(text, state);
2361 }
2362
2363 void
2364 rl_forced_update_display(void)
2365 {
2366 el_set(e, EL_REFRESH);
2367 }
2368
2369 int
2370 _rl_abort_internal(void)
2371 {
2372 el_beep(e);
2373 longjmp(topbuf, 1);
2374 /*NOTREACHED*/
2375 }
2376
2377 int
2378 _rl_qsort_string_compare(char **s1, char **s2)
2379 {
2380 return strcoll(*s1, *s2);
2381 }
2382
2383 HISTORY_STATE *
2384 history_get_history_state(void)
2385 {
2386 HISTORY_STATE *hs;
2387
2388 if ((hs = el_malloc(sizeof(*hs))) == NULL)
2389 return NULL;
2390 hs->length = history_length;
2391 return hs;
2392 }
2393
2394 int
2395 /*ARGSUSED*/
2396 rl_kill_text(int from __attribute__((__unused__)),
2397 int to __attribute__((__unused__)))
2398 {
2399 return 0;
2400 }
2401
2402 Keymap
2403 rl_make_bare_keymap(void)
2404 {
2405 return NULL;
2406 }
2407
2408 Keymap
2409 rl_get_keymap(void)
2410 {
2411 return NULL;
2412 }
2413
2414 void
2415 /*ARGSUSED*/
2416 rl_set_keymap(Keymap k __attribute__((__unused__)))
2417 {
2418 }
2419
2420 int
2421 /*ARGSUSED*/
2422 rl_generic_bind(int type __attribute__((__unused__)),
2423 const char * keyseq __attribute__((__unused__)),
2424 const char * data __attribute__((__unused__)),
2425 Keymap k __attribute__((__unused__)))
2426 {
2427 return 0;
2428 }
2429
2430 int
2431 /*ARGSUSED*/
2432 rl_bind_key_in_map(int key __attribute__((__unused__)),
2433 rl_command_func_t *fun __attribute__((__unused__)),
2434 Keymap k __attribute__((__unused__)))
2435 {
2436 return 0;
2437 }
2438
2439 /* unsupported, but needed by python */
2440 void
2441 rl_cleanup_after_signal(void)
2442 {
2443 }
2444
2445 int
2446 rl_on_new_line(void)
2447 {
2448 return 0;
2449 }
2450
2451 void
2452 rl_free_line_state(void)
2453 {
2454 }
2455
2456 int
2457 /*ARGSUSED*/
2458 rl_set_keyboard_input_timeout(int u __attribute__((__unused__)))
2459 {
2460 return 0;
2461 }
2462
2463 void
2464 rl_resize_terminal(void)
2465 {
2466 el_resize(e);
2467 }
2468
2469 void
2470 rl_reset_after_signal(void)
2471 {
2472 if (rl_prep_term_function)
2473 (*rl_prep_term_function)();
2474 }
2475
2476 void
2477 rl_echo_signal_char(int sig)
2478 {
2479 int c = tty_get_signal_character(e, sig);
2480 if (c == -1)
2481 return;
2482 re_putc(e, c, 0);
2483 }
2484
2485 int
2486 rl_crlf(void)
2487 {
2488 re_putc(e, '\n', 0);
2489 return 0;
2490 }
2491
2492 int
2493 rl_ding(void)
2494 {
2495 re_putc(e, '\a', 0);
2496 return 0;
2497 }
2498
2499 int
2500 rl_abort(int count, int key)
2501 {
2502 return count && key ? 0 : 0;
2503 }
2504
2505 int
2506 rl_set_keymap_name(const char *name, Keymap k)
2507 {
2508 return name && k ? 0 : 0;
2509 }
2510
2511 histdata_t
2512 free_history_entry(HIST_ENTRY *he)
2513 {
2514 return he ? NULL : NULL;
2515 }
2516
2517 void
2518 _rl_erase_entire_line(void)
2519 {
2520 }
2521