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