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