readline.c revision 1.166 1 /* $NetBSD: readline.c,v 1.166 2021/09/09 20:25:30 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.166 2021/09/09 20:25:30 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 el_free(last_search_pat);
628 last_search_pat = pat;
629 }
630 ret = history_search(pat, -1);
631 } else
632 ret = history_search_prefix(pat, -1);
633
634 if (ret == -1) {
635 /* restore to end of list on failed search */
636 history(h, &ev, H_FIRST);
637 (void)fprintf(rl_outstream, "%s: Event not found\n", pat);
638 if (pat != last_search_pat)
639 el_free(pat);
640 return NULL;
641 }
642
643 if (sub && len) {
644 el_free(last_search_match);
645 last_search_match = strdup(pat);
646 }
647
648 if (pat != last_search_pat)
649 el_free(pat);
650
651 if (history(h, &ev, H_CURR) != 0)
652 return NULL;
653 *cindex = idx;
654 rptr = ev.str;
655
656 /* roll back to original position */
657 (void)history(h, &ev, H_SET, num);
658
659 return rptr;
660 }
661
662 static int
663 getfrom(const char **cmdp, char **fromp, const char *search, int delim)
664 {
665 size_t size = 16;
666 size_t len = 0;
667 const char *cmd = *cmdp;
668 char *what = el_realloc(*fromp, size * sizeof(*what));
669 if (what == NULL){
670 el_free(*fromp);
671 *fromp = NULL;
672 return 0;
673 }
674 for (; *cmd && *cmd != delim; cmd++) {
675 if (*cmd == '\\' && cmd[1] == delim)
676 cmd++;
677 if (len - 1 >= size) {
678 char *nwhat;
679 nwhat = el_realloc(what, (size <<= 1) * sizeof(*nwhat));
680 if (nwhat == NULL) {
681 el_free(what);
682 el_free(*fromp);
683 *cmdp = cmd;
684 *fromp = NULL;
685 return 0;
686 }
687 what = nwhat;
688 }
689 what[len++] = *cmd;
690 }
691 what[len] = '\0';
692 *fromp = what;
693 *cmdp = cmd;
694 if (*what == '\0') {
695 el_free(what);
696 if (search) {
697 *fromp = strdup(search);
698 if (*fromp == NULL) {
699 return 0;
700 }
701 } else {
702 *fromp = NULL;
703 return -1;
704 }
705 }
706 if (!*cmd) {
707 el_free(what);
708 *fromp = NULL;
709 return -1;
710 }
711
712 cmd++; /* shift after delim */
713 *cmdp = cmd;
714
715 if (!*cmd) {
716 el_free(what);
717 *fromp = NULL;
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 *top = NULL;
732 if (with == NULL)
733 goto out;
734
735 for (; *cmd && *cmd != delim; cmd++) {
736 if (len + from_len + 1 >= size) {
737 char *nwith;
738 size += from_len + 1;
739 nwith = el_realloc(with, size * sizeof(*nwith));
740 if (nwith == NULL)
741 goto out;
742 with = nwith;
743 }
744 if (*cmd == '&') {
745 /* safe */
746 strcpy(&with[len], from);
747 len += from_len;
748 continue;
749 }
750 if (*cmd == '\\' && (*(cmd + 1) == delim || *(cmd + 1) == '&'))
751 cmd++;
752 with[len++] = *cmd;
753 }
754 if (!*cmd)
755 goto out;
756 with[len] = '\0';
757 *top = with;
758 *cmdp = cmd;
759 return 1;
760 out:
761 el_free(with);
762 el_free(*top);
763 *top = NULL;
764 *cmdp = cmd;
765 return -1;
766 }
767
768 static void
769 replace(char **tmp, int c)
770 {
771 char *aptr;
772 if ((aptr = strrchr(*tmp, c)) == NULL)
773 return;
774 aptr = strdup(aptr + 1); // XXX: check
775 el_free(*tmp);
776 *tmp = aptr;
777 }
778
779 /*
780 * the real function doing history expansion - takes as argument command
781 * to do and data upon which the command should be executed
782 * does expansion the way I've understood readline documentation
783 *
784 * returns 0 if data was not modified, 1 if it was and 2 if the string
785 * should be only printed and not executed; in case of error,
786 * returns -1 and *result points to NULL
787 * it's the caller's responsibility to free() the string returned in *result
788 */
789 static int
790 _history_expand_command(const char *command, size_t offs, size_t cmdlen,
791 char **result)
792 {
793 char *tmp, *search = NULL, *aptr, delim;
794 const char *ptr, *cmd;
795 static char *from = NULL, *to = NULL;
796 int start, end, idx, has_mods = 0;
797 int p_on = 0, g_on = 0, ev;
798
799 *result = NULL;
800 aptr = NULL;
801 ptr = NULL;
802
803 /* First get event specifier */
804 idx = 0;
805
806 if (strchr(":^*$", command[offs + 1])) {
807 char str[4];
808 /*
809 * "!:" is shorthand for "!!:".
810 * "!^", "!*" and "!$" are shorthand for
811 * "!!:^", "!!:*" and "!!:$" respectively.
812 */
813 str[0] = str[1] = '!';
814 str[2] = '0';
815 ptr = get_history_event(str, &idx, 0);
816 idx = (command[offs + 1] == ':')? 1:0;
817 has_mods = 1;
818 } else {
819 if (command[offs + 1] == '#') {
820 /* use command so far */
821 if ((aptr = el_calloc(offs + 1, sizeof(*aptr)))
822 == NULL)
823 return -1;
824 (void)strlcpy(aptr, command, offs + 1);
825 idx = 1;
826 } else {
827 int qchar;
828
829 qchar = (offs > 0 && command[offs - 1] == '"')? '"':0;
830 ptr = get_history_event(command + offs, &idx, qchar);
831 }
832 has_mods = command[offs + (size_t)idx] == ':';
833 }
834
835 if (ptr == NULL && aptr == NULL)
836 return -1;
837
838 if (!has_mods) {
839 *result = strdup(aptr ? aptr : ptr);
840 if (aptr)
841 el_free(aptr);
842 if (*result == NULL)
843 return -1;
844 return 1;
845 }
846
847 cmd = command + offs + idx + 1;
848
849 /* Now parse any word designators */
850
851 if (*cmd == '%') /* last word matched by ?pat? */
852 tmp = strdup(last_search_match ? last_search_match : "");
853 else if (strchr("^*$-0123456789", *cmd)) {
854 start = end = -1;
855 if (*cmd == '^')
856 start = end = 1, cmd++;
857 else if (*cmd == '$')
858 start = -1, cmd++;
859 else if (*cmd == '*')
860 start = 1, cmd++;
861 else if (*cmd == '-' || isdigit((unsigned char) *cmd)) {
862 start = 0;
863 while (*cmd && '0' <= *cmd && *cmd <= '9')
864 start = start * 10 + *cmd++ - '0';
865
866 if (*cmd == '-') {
867 if (isdigit((unsigned char) cmd[1])) {
868 cmd++;
869 end = 0;
870 while (*cmd && '0' <= *cmd && *cmd <= '9')
871 end = end * 10 + *cmd++ - '0';
872 } else if (cmd[1] == '$') {
873 cmd += 2;
874 end = -1;
875 } else {
876 cmd++;
877 end = -2;
878 }
879 } else if (*cmd == '*')
880 end = -1, cmd++;
881 else
882 end = start;
883 }
884 tmp = history_arg_extract(start, end, aptr? aptr:ptr);
885 if (tmp == NULL) {
886 (void)fprintf(rl_outstream, "%s: Bad word specifier",
887 command + offs + idx);
888 if (aptr)
889 el_free(aptr);
890 return -1;
891 }
892 } else
893 tmp = strdup(aptr? aptr:ptr);
894
895 if (aptr)
896 el_free(aptr);
897
898 if (*cmd == '\0' || ((size_t)(cmd - (command + offs)) >= cmdlen)) {
899 *result = tmp;
900 return 1;
901 }
902
903 for (; *cmd; cmd++) {
904 switch (*cmd) {
905 case ':':
906 continue;
907 case 'h': /* remove trailing path */
908 if ((aptr = strrchr(tmp, '/')) != NULL)
909 *aptr = '\0';
910 continue;
911 case 't': /* remove leading path */
912 replace(&tmp, '/');
913 continue;
914 case 'r': /* remove trailing suffix */
915 if ((aptr = strrchr(tmp, '.')) != NULL)
916 *aptr = '\0';
917 continue;
918 case 'e': /* remove all but suffix */
919 replace(&tmp, '.');
920 continue;
921 case 'p': /* print only */
922 p_on = 1;
923 continue;
924 case 'g':
925 g_on = 2;
926 continue;
927 case '&':
928 if (from == NULL || to == NULL)
929 continue;
930 /*FALLTHROUGH*/
931 case 's':
932 ev = -1;
933 delim = *++cmd;
934 if (delim == '\0' || *++cmd == '\0')
935 goto out;
936 if ((ev = getfrom(&cmd, &from, search, delim)) != 1)
937 goto out;
938 if ((ev = getto(&cmd, &to, from, delim)) != 1)
939 goto out;
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 cmd--;
947 continue;
948 }
949 }
950 *result = tmp;
951 return p_on ? 2 : 1;
952 out:
953 el_free(tmp);
954 return ev;
955
956 }
957
958
959 /*
960 * csh-style history expansion
961 */
962 int
963 history_expand(char *str, char **output)
964 {
965 int ret = 0;
966 size_t idx, i, size;
967 char *tmp, *result;
968
969 if (h == NULL || e == NULL)
970 rl_initialize();
971
972 if (history_expansion_char == 0) {
973 *output = strdup(str);
974 return 0;
975 }
976
977 *output = NULL;
978 if (str[0] == history_subst_char) {
979 /* ^foo^foo2^ is equivalent to !!:s^foo^foo2^ */
980 *output = el_calloc(strlen(str) + 4 + 1, sizeof(**output));
981 if (*output == NULL)
982 return 0;
983 (*output)[0] = (*output)[1] = history_expansion_char;
984 (*output)[2] = ':';
985 (*output)[3] = 's';
986 (void)strcpy((*output) + 4, str);
987 str = *output;
988 } else {
989 *output = strdup(str);
990 if (*output == NULL)
991 return 0;
992 }
993
994 #define ADD_STRING(what, len, fr) \
995 { \
996 if (idx + len + 1 > size) { \
997 char *nresult = el_realloc(result, \
998 (size += len + 1) * sizeof(*nresult)); \
999 if (nresult == NULL) { \
1000 el_free(*output); \
1001 el_free(fr); \
1002 return 0; \
1003 } \
1004 result = nresult; \
1005 } \
1006 (void)strlcpy(&result[idx], what, len + 1); \
1007 idx += len; \
1008 }
1009
1010 result = NULL;
1011 size = idx = 0;
1012 tmp = NULL;
1013 for (i = 0; str[i];) {
1014 int qchar, loop_again;
1015 size_t len, start, j;
1016
1017 qchar = 0;
1018 loop_again = 1;
1019 start = j = i;
1020 loop:
1021 for (; str[j]; j++) {
1022 if (str[j] == '\\' &&
1023 str[j + 1] == history_expansion_char) {
1024 len = strlen(&str[j + 1]) + 1;
1025 memmove(&str[j], &str[j + 1], len);
1026 continue;
1027 }
1028 if (!loop_again) {
1029 if (isspace((unsigned char) str[j])
1030 || str[j] == qchar)
1031 break;
1032 }
1033 if (str[j] == history_expansion_char
1034 && !strchr(history_no_expand_chars, str[j + 1])
1035 && (!history_inhibit_expansion_function ||
1036 (*history_inhibit_expansion_function)(str,
1037 (int)j) == 0))
1038 break;
1039 }
1040
1041 if (str[j] && loop_again) {
1042 i = j;
1043 qchar = (j > 0 && str[j - 1] == '"' )? '"':0;
1044 j++;
1045 if (str[j] == history_expansion_char)
1046 j++;
1047 loop_again = 0;
1048 goto loop;
1049 }
1050 len = i - start;
1051 ADD_STRING(&str[start], len, NULL);
1052
1053 if (str[i] == '\0' || str[i] != history_expansion_char) {
1054 len = j - i;
1055 ADD_STRING(&str[i], len, NULL);
1056 if (start == 0)
1057 ret = 0;
1058 else
1059 ret = 1;
1060 break;
1061 }
1062 ret = _history_expand_command (str, i, (j - i), &tmp);
1063 if (ret > 0 && tmp) {
1064 len = strlen(tmp);
1065 ADD_STRING(tmp, len, tmp);
1066 }
1067 if (tmp) {
1068 el_free(tmp);
1069 tmp = NULL;
1070 }
1071 i = j;
1072 }
1073
1074 /* ret is 2 for "print only" option */
1075 if (ret == 2) {
1076 add_history(result);
1077 #ifdef GDB_411_HACK
1078 /* gdb 4.11 has been shipped with readline, where */
1079 /* history_expand() returned -1 when the line */
1080 /* should not be executed; in readline 2.1+ */
1081 /* it should return 2 in such a case */
1082 ret = -1;
1083 #endif
1084 }
1085 el_free(*output);
1086 *output = result;
1087
1088 return ret;
1089 }
1090
1091 /*
1092 * Return a string consisting of arguments of "str" from "start" to "end".
1093 */
1094 char *
1095 history_arg_extract(int start, int end, const char *str)
1096 {
1097 size_t i, len, max;
1098 char **arr, *result = NULL;
1099
1100 arr = history_tokenize(str);
1101 if (!arr)
1102 return NULL;
1103 if (arr && *arr == NULL)
1104 goto out;
1105
1106 for (max = 0; arr[max]; max++)
1107 continue;
1108 max--;
1109
1110 if (start == '$')
1111 start = (int)max;
1112 if (end == '$')
1113 end = (int)max;
1114 if (end < 0)
1115 end = (int)max + end + 1;
1116 if (start < 0)
1117 start = end;
1118
1119 if (start < 0 || end < 0 || (size_t)start > max ||
1120 (size_t)end > max || start > end)
1121 goto out;
1122
1123 for (i = (size_t)start, len = 0; i <= (size_t)end; i++)
1124 len += strlen(arr[i]) + 1;
1125 len++;
1126 result = el_calloc(len, sizeof(*result));
1127 if (result == NULL)
1128 goto out;
1129
1130 for (i = (size_t)start, len = 0; i <= (size_t)end; i++) {
1131 (void)strcpy(result + len, arr[i]);
1132 len += strlen(arr[i]);
1133 if (i < (size_t)end)
1134 result[len++] = ' ';
1135 }
1136 result[len] = '\0';
1137
1138 out:
1139 for (i = 0; arr[i]; i++)
1140 el_free(arr[i]);
1141 el_free(arr);
1142
1143 return result;
1144 }
1145
1146 /*
1147 * Parse the string into individual tokens,
1148 * similar to how shell would do it.
1149 */
1150 char **
1151 history_tokenize(const char *str)
1152 {
1153 int size = 1, idx = 0, i, start;
1154 size_t len;
1155 char **result = NULL, *temp, delim = '\0';
1156
1157 for (i = 0; str[i];) {
1158 while (isspace((unsigned char) str[i]))
1159 i++;
1160 start = i;
1161 for (; str[i];) {
1162 if (str[i] == '\\') {
1163 if (str[i+1] != '\0')
1164 i++;
1165 } else if (str[i] == delim)
1166 delim = '\0';
1167 else if (!delim &&
1168 (isspace((unsigned char) str[i]) ||
1169 strchr("()<>;&|$", str[i])))
1170 break;
1171 else if (!delim && strchr("'`\"", str[i]))
1172 delim = str[i];
1173 if (str[i])
1174 i++;
1175 }
1176
1177 if (idx + 2 >= size) {
1178 char **nresult;
1179 size <<= 1;
1180 nresult = el_realloc(result, (size_t)size * sizeof(*nresult));
1181 if (nresult == NULL) {
1182 el_free(result);
1183 return NULL;
1184 }
1185 result = nresult;
1186 }
1187 len = (size_t)i - (size_t)start;
1188 temp = el_calloc(len + 1, sizeof(*temp));
1189 if (temp == NULL) {
1190 for (i = 0; i < idx; i++)
1191 el_free(result[i]);
1192 el_free(result);
1193 return NULL;
1194 }
1195 (void)strlcpy(temp, &str[start], len + 1);
1196 result[idx++] = temp;
1197 result[idx] = NULL;
1198 if (str[i])
1199 i++;
1200 }
1201 return result;
1202 }
1203
1204
1205 /*
1206 * limit size of history record to ``max'' events
1207 */
1208 void
1209 stifle_history(int max)
1210 {
1211 HistEvent ev;
1212 HIST_ENTRY *he;
1213
1214 if (h == NULL || e == NULL)
1215 rl_initialize();
1216
1217 if (history(h, &ev, H_SETSIZE, max) == 0) {
1218 max_input_history = max;
1219 if (history_length > max)
1220 history_base = history_length - max;
1221 while (history_length > max) {
1222 he = remove_history(0);
1223 el_free(he->data);
1224 el_free((void *)(unsigned long)he->line);
1225 el_free(he);
1226 }
1227 }
1228 }
1229
1230
1231 /*
1232 * "unlimit" size of history - set the limit to maximum allowed int value
1233 */
1234 int
1235 unstifle_history(void)
1236 {
1237 HistEvent ev;
1238 int omax;
1239
1240 history(h, &ev, H_SETSIZE, INT_MAX);
1241 omax = max_input_history;
1242 max_input_history = INT_MAX;
1243 return omax; /* some value _must_ be returned */
1244 }
1245
1246
1247 int
1248 history_is_stifled(void)
1249 {
1250
1251 /* cannot return true answer */
1252 return max_input_history != INT_MAX;
1253 }
1254
1255 static const char _history_tmp_template[] = "/tmp/.historyXXXXXX";
1256
1257 int
1258 history_truncate_file (const char *filename, int nlines)
1259 {
1260 int ret = 0;
1261 FILE *fp, *tp;
1262 char template[sizeof(_history_tmp_template)];
1263 char buf[4096];
1264 int fd;
1265 char *cp;
1266 off_t off;
1267 int count = 0;
1268 ssize_t left = 0;
1269
1270 if (filename == NULL && (filename = _default_history_file()) == NULL)
1271 return errno;
1272 if ((fp = fopen(filename, "r+")) == NULL)
1273 return errno;
1274 strcpy(template, _history_tmp_template);
1275 if ((fd = mkstemp(template)) == -1) {
1276 ret = errno;
1277 goto out1;
1278 }
1279
1280 if ((tp = fdopen(fd, "r+")) == NULL) {
1281 close(fd);
1282 ret = errno;
1283 goto out2;
1284 }
1285
1286 for(;;) {
1287 if (fread(buf, sizeof(buf), (size_t)1, fp) != 1) {
1288 if (ferror(fp)) {
1289 ret = errno;
1290 break;
1291 }
1292 if (fseeko(fp, (off_t)sizeof(buf) * count, SEEK_SET) ==
1293 (off_t)-1) {
1294 ret = errno;
1295 break;
1296 }
1297 left = (ssize_t)fread(buf, (size_t)1, sizeof(buf), fp);
1298 if (ferror(fp)) {
1299 ret = errno;
1300 break;
1301 }
1302 if (left == 0) {
1303 count--;
1304 left = sizeof(buf);
1305 } else if (fwrite(buf, (size_t)left, (size_t)1, tp)
1306 != 1) {
1307 ret = errno;
1308 break;
1309 }
1310 fflush(tp);
1311 break;
1312 }
1313 if (fwrite(buf, sizeof(buf), (size_t)1, tp) != 1) {
1314 ret = errno;
1315 break;
1316 }
1317 count++;
1318 }
1319 if (ret)
1320 goto out3;
1321 cp = buf + left - 1;
1322 if(*cp != '\n')
1323 cp++;
1324 for(;;) {
1325 while (--cp >= buf) {
1326 if (*cp == '\n') {
1327 if (--nlines == 0) {
1328 if (++cp >= buf + sizeof(buf)) {
1329 count++;
1330 cp = buf;
1331 }
1332 break;
1333 }
1334 }
1335 }
1336 if (nlines <= 0 || count == 0)
1337 break;
1338 count--;
1339 if (fseeko(tp, (off_t)sizeof(buf) * count, SEEK_SET) < 0) {
1340 ret = errno;
1341 break;
1342 }
1343 if (fread(buf, sizeof(buf), (size_t)1, tp) != 1) {
1344 if (ferror(tp)) {
1345 ret = errno;
1346 break;
1347 }
1348 ret = EAGAIN;
1349 break;
1350 }
1351 cp = buf + sizeof(buf);
1352 }
1353
1354 if (ret || nlines > 0)
1355 goto out3;
1356
1357 if (fseeko(fp, (off_t)0, SEEK_SET) == (off_t)-1) {
1358 ret = errno;
1359 goto out3;
1360 }
1361
1362 if (fseeko(tp, (off_t)sizeof(buf) * count + (cp - buf), SEEK_SET) ==
1363 (off_t)-1) {
1364 ret = errno;
1365 goto out3;
1366 }
1367
1368 for(;;) {
1369 if ((left = (ssize_t)fread(buf, (size_t)1, sizeof(buf), tp)) == 0) {
1370 if (ferror(fp))
1371 ret = errno;
1372 break;
1373 }
1374 if (fwrite(buf, (size_t)left, (size_t)1, fp) != 1) {
1375 ret = errno;
1376 break;
1377 }
1378 }
1379 fflush(fp);
1380 if((off = ftello(fp)) > 0)
1381 (void)ftruncate(fileno(fp), off);
1382 out3:
1383 fclose(tp);
1384 out2:
1385 unlink(template);
1386 out1:
1387 fclose(fp);
1388
1389 return ret;
1390 }
1391
1392
1393 /*
1394 * read history from a file given
1395 */
1396 int
1397 read_history(const char *filename)
1398 {
1399 HistEvent ev;
1400
1401 if (h == NULL || e == NULL)
1402 rl_initialize();
1403 if (filename == NULL && (filename = _default_history_file()) == NULL)
1404 return errno;
1405 errno = 0;
1406 if (history(h, &ev, H_LOAD, filename) == -1)
1407 return errno ? errno : EINVAL;
1408 if (history(h, &ev, H_GETSIZE) == 0)
1409 history_length = ev.num;
1410 if (history_length < 0)
1411 return EINVAL;
1412 return 0;
1413 }
1414
1415
1416 /*
1417 * write history to a file given
1418 */
1419 int
1420 write_history(const char *filename)
1421 {
1422 HistEvent ev;
1423
1424 if (h == NULL || e == NULL)
1425 rl_initialize();
1426 if (filename == NULL && (filename = _default_history_file()) == NULL)
1427 return errno;
1428 return history(h, &ev, H_SAVE, filename) == -1 ?
1429 (errno ? errno : EINVAL) : 0;
1430 }
1431
1432 int
1433 append_history(int n, const char *filename)
1434 {
1435 HistEvent ev;
1436 FILE *fp;
1437
1438 if (h == NULL || e == NULL)
1439 rl_initialize();
1440 if (filename == NULL && (filename = _default_history_file()) == NULL)
1441 return errno;
1442
1443 if ((fp = fopen(filename, "a")) == NULL)
1444 return errno;
1445
1446 if (history(h, &ev, H_NSAVE_FP, (size_t)n, fp) == -1) {
1447 int serrno = errno ? errno : EINVAL;
1448 fclose(fp);
1449 return serrno;
1450 }
1451 fclose(fp);
1452 return 0;
1453 }
1454
1455 /*
1456 * returns history ``num''th event
1457 *
1458 * returned pointer points to static variable
1459 */
1460 HIST_ENTRY *
1461 history_get(int num)
1462 {
1463 static HIST_ENTRY she;
1464 HistEvent ev;
1465 int curr_num;
1466
1467 if (h == NULL || e == NULL)
1468 rl_initialize();
1469
1470 if (num < history_base)
1471 return NULL;
1472
1473 /* save current position */
1474 if (history(h, &ev, H_CURR) != 0)
1475 return NULL;
1476 curr_num = ev.num;
1477
1478 /*
1479 * use H_DELDATA to set to nth history (without delete) by passing
1480 * (void **)-1 -- as in history_set_pos
1481 */
1482 if (history(h, &ev, H_DELDATA, num - history_base, (void **)-1) != 0)
1483 goto out;
1484
1485 /* get current entry */
1486 if (history(h, &ev, H_CURR) != 0)
1487 goto out;
1488 if (history(h, &ev, H_NEXT_EVDATA, ev.num, &she.data) != 0)
1489 goto out;
1490 she.line = ev.str;
1491
1492 /* restore pointer to where it was */
1493 (void)history(h, &ev, H_SET, curr_num);
1494
1495 return &she;
1496
1497 out:
1498 /* restore pointer to where it was */
1499 (void)history(h, &ev, H_SET, curr_num);
1500 return NULL;
1501 }
1502
1503
1504 /*
1505 * add the line to history table
1506 */
1507 int
1508 add_history(const char *line)
1509 {
1510 HistEvent ev;
1511
1512 if (h == NULL || e == NULL)
1513 rl_initialize();
1514
1515 if (history(h, &ev, H_ENTER, line) == -1)
1516 return 0;
1517
1518 (void)history(h, &ev, H_GETSIZE);
1519 if (ev.num == history_length)
1520 history_base++;
1521 else {
1522 history_offset++;
1523 history_length = ev.num;
1524 }
1525 return 0;
1526 }
1527
1528
1529 /*
1530 * remove the specified entry from the history list and return it.
1531 */
1532 HIST_ENTRY *
1533 remove_history(int num)
1534 {
1535 HIST_ENTRY *he;
1536 HistEvent ev;
1537
1538 if (h == NULL || e == NULL)
1539 rl_initialize();
1540
1541 if ((he = el_malloc(sizeof(*he))) == NULL)
1542 return NULL;
1543
1544 if (history(h, &ev, H_DELDATA, num, &he->data) != 0) {
1545 el_free(he);
1546 return NULL;
1547 }
1548
1549 he->line = ev.str;
1550 if (history(h, &ev, H_GETSIZE) == 0)
1551 history_length = ev.num;
1552
1553 return he;
1554 }
1555
1556
1557 /*
1558 * replace the line and data of the num-th entry
1559 */
1560 HIST_ENTRY *
1561 replace_history_entry(int num, const char *line, histdata_t data)
1562 {
1563 HIST_ENTRY *he;
1564 HistEvent ev;
1565 int curr_num;
1566
1567 if (h == NULL || e == NULL)
1568 rl_initialize();
1569
1570 /* save current position */
1571 if (history(h, &ev, H_CURR) != 0)
1572 return NULL;
1573 curr_num = ev.num;
1574
1575 /* start from the oldest */
1576 if (history(h, &ev, H_LAST) != 0)
1577 return NULL; /* error */
1578
1579 if ((he = el_malloc(sizeof(*he))) == NULL)
1580 return NULL;
1581
1582 /* look forwards for event matching specified offset */
1583 if (history(h, &ev, H_NEXT_EVDATA, num, &he->data))
1584 goto out;
1585
1586 he->line = strdup(ev.str);
1587 if (he->line == NULL)
1588 goto out;
1589
1590 if (history(h, &ev, H_REPLACE, line, data))
1591 goto out;
1592
1593 /* restore pointer to where it was */
1594 if (history(h, &ev, H_SET, curr_num))
1595 goto out;
1596
1597 return he;
1598 out:
1599 el_free(he);
1600 return NULL;
1601 }
1602
1603 /*
1604 * clear the history list - delete all entries
1605 */
1606 void
1607 clear_history(void)
1608 {
1609 HistEvent ev;
1610
1611 if (h == NULL || e == NULL)
1612 rl_initialize();
1613
1614 (void)history(h, &ev, H_CLEAR);
1615 history_offset = history_length = 0;
1616 }
1617
1618
1619 /*
1620 * returns offset of the current history event
1621 */
1622 int
1623 where_history(void)
1624 {
1625 return history_offset;
1626 }
1627
1628 static HIST_ENTRY **_history_listp;
1629 static HIST_ENTRY *_history_list;
1630
1631 HIST_ENTRY **
1632 history_list(void)
1633 {
1634 HistEvent ev;
1635 HIST_ENTRY **nlp, *nl;
1636 int i;
1637
1638 if (history(h, &ev, H_LAST) != 0)
1639 return NULL;
1640
1641 if ((nlp = el_realloc(_history_listp,
1642 ((size_t)history_length + 1) * sizeof(*nlp))) == NULL)
1643 return NULL;
1644 _history_listp = nlp;
1645
1646 if ((nl = el_realloc(_history_list,
1647 (size_t)history_length * sizeof(*nl))) == NULL)
1648 return NULL;
1649 _history_list = nl;
1650
1651 i = 0;
1652 do {
1653 _history_listp[i] = &_history_list[i];
1654 _history_list[i].line = ev.str;
1655 _history_list[i].data = NULL;
1656 if (i++ == history_length)
1657 abort();
1658 } while (history(h, &ev, H_PREV) == 0);
1659 _history_listp[i] = NULL;
1660 return _history_listp;
1661 }
1662
1663 /*
1664 * returns current history event or NULL if there is no such event
1665 */
1666 HIST_ENTRY *
1667 current_history(void)
1668 {
1669 HistEvent ev;
1670
1671 if (history(h, &ev, H_PREV_EVENT, history_offset + 1) != 0)
1672 return NULL;
1673
1674 rl_he.line = ev.str;
1675 rl_he.data = NULL;
1676 return &rl_he;
1677 }
1678
1679
1680 /*
1681 * returns total number of bytes history events' data are using
1682 */
1683 int
1684 history_total_bytes(void)
1685 {
1686 HistEvent ev;
1687 int curr_num;
1688 size_t size;
1689
1690 if (history(h, &ev, H_CURR) != 0)
1691 return -1;
1692 curr_num = ev.num;
1693
1694 (void)history(h, &ev, H_FIRST);
1695 size = 0;
1696 do
1697 size += strlen(ev.str) * sizeof(*ev.str);
1698 while (history(h, &ev, H_NEXT) == 0);
1699
1700 /* get to the same position as before */
1701 history(h, &ev, H_PREV_EVENT, curr_num);
1702
1703 return (int)size;
1704 }
1705
1706
1707 /*
1708 * sets the position in the history list to ``pos''
1709 */
1710 int
1711 history_set_pos(int pos)
1712 {
1713 if (pos >= history_length || pos < 0)
1714 return 0;
1715
1716 history_offset = pos;
1717 return 1;
1718 }
1719
1720
1721 /*
1722 * returns previous event in history and shifts pointer accordingly
1723 * Note that readline and editline define directions in opposite ways.
1724 */
1725 HIST_ENTRY *
1726 previous_history(void)
1727 {
1728 HistEvent ev;
1729
1730 if (history_offset == 0)
1731 return NULL;
1732
1733 if (history(h, &ev, H_LAST) != 0)
1734 return NULL;
1735
1736 history_offset--;
1737 return current_history();
1738 }
1739
1740
1741 /*
1742 * returns next event in history and shifts pointer accordingly
1743 */
1744 HIST_ENTRY *
1745 next_history(void)
1746 {
1747 HistEvent ev;
1748
1749 if (history_offset >= history_length)
1750 return NULL;
1751
1752 if (history(h, &ev, H_LAST) != 0)
1753 return NULL;
1754
1755 history_offset++;
1756 return current_history();
1757 }
1758
1759
1760 /*
1761 * searches for first history event containing the str
1762 */
1763 int
1764 history_search(const char *str, int direction)
1765 {
1766 HistEvent ev;
1767 const char *strp;
1768 int curr_num;
1769
1770 if (history(h, &ev, H_CURR) != 0)
1771 return -1;
1772 curr_num = ev.num;
1773
1774 for (;;) {
1775 if ((strp = strstr(ev.str, str)) != NULL)
1776 return (int)(strp - ev.str);
1777 if (history(h, &ev, direction < 0 ? H_NEXT:H_PREV) != 0)
1778 break;
1779 }
1780 (void)history(h, &ev, H_SET, curr_num);
1781 return -1;
1782 }
1783
1784
1785 /*
1786 * searches for first history event beginning with str
1787 */
1788 int
1789 history_search_prefix(const char *str, int direction)
1790 {
1791 HistEvent ev;
1792
1793 return (history(h, &ev, direction < 0 ?
1794 H_PREV_STR : H_NEXT_STR, str));
1795 }
1796
1797
1798 /*
1799 * search for event in history containing str, starting at offset
1800 * abs(pos); continue backward, if pos<0, forward otherwise
1801 */
1802 /* ARGSUSED */
1803 int
1804 history_search_pos(const char *str,
1805 int direction __attribute__((__unused__)), int pos)
1806 {
1807 HistEvent ev;
1808 int curr_num, off;
1809
1810 off = (pos > 0) ? pos : -pos;
1811 pos = (pos > 0) ? 1 : -1;
1812
1813 if (history(h, &ev, H_CURR) != 0)
1814 return -1;
1815 curr_num = ev.num;
1816
1817 if (!history_set_pos(off) || history(h, &ev, H_CURR) != 0)
1818 return -1;
1819
1820 for (;;) {
1821 if (strstr(ev.str, str))
1822 return off;
1823 if (history(h, &ev, (pos < 0) ? H_PREV : H_NEXT) != 0)
1824 break;
1825 }
1826
1827 /* set "current" pointer back to previous state */
1828 (void)history(h, &ev,
1829 pos < 0 ? H_NEXT_EVENT : H_PREV_EVENT, curr_num);
1830
1831 return -1;
1832 }
1833
1834
1835 /********************************/
1836 /* completion functions */
1837
1838 char *
1839 tilde_expand(char *name)
1840 {
1841 return fn_tilde_expand(name);
1842 }
1843
1844 char *
1845 filename_completion_function(const char *name, int state)
1846 {
1847 return fn_filename_completion_function(name, state);
1848 }
1849
1850 /*
1851 * a completion generator for usernames; returns _first_ username
1852 * which starts with supplied text
1853 * text contains a partial username preceded by random character
1854 * (usually '~'); state resets search from start (??? should we do that anyway)
1855 * it's the caller's responsibility to free the returned value
1856 */
1857 char *
1858 username_completion_function(const char *text, int state)
1859 {
1860 #if defined(HAVE_GETPW_R_POSIX) || defined(HAVE_GETPW_R_DRAFT)
1861 struct passwd pwres;
1862 char pwbuf[1024];
1863 #endif
1864 struct passwd *pass = NULL;
1865
1866 if (text[0] == '\0')
1867 return NULL;
1868
1869 if (*text == '~')
1870 text++;
1871
1872 if (state == 0)
1873 setpwent();
1874
1875 while (
1876 #if defined(HAVE_GETPW_R_POSIX) || defined(HAVE_GETPW_R_DRAFT)
1877 getpwent_r(&pwres, pwbuf, sizeof(pwbuf), &pass) == 0 && pass != NULL
1878 #else
1879 (pass = getpwent()) != NULL
1880 #endif
1881 && text[0] == pass->pw_name[0]
1882 && strcmp(text, pass->pw_name) == 0)
1883 continue;
1884
1885 if (pass == NULL) {
1886 endpwent();
1887 return NULL;
1888 }
1889 return strdup(pass->pw_name);
1890 }
1891
1892
1893 /*
1894 * el-compatible wrapper to send TSTP on ^Z
1895 */
1896 /* ARGSUSED */
1897 static unsigned char
1898 _el_rl_tstp(EditLine *el __attribute__((__unused__)), int ch __attribute__((__unused__)))
1899 {
1900 (void)kill(0, SIGTSTP);
1901 return CC_NORM;
1902 }
1903
1904 static const char *
1905 /*ARGSUSED*/
1906 _rl_completion_append_character_function(const char *dummy
1907 __attribute__((__unused__)))
1908 {
1909 static char buf[2];
1910 buf[0] = (char)rl_completion_append_character;
1911 buf[1] = '\0';
1912 return buf;
1913 }
1914
1915
1916 /*
1917 * Display list of strings in columnar format on readline's output stream.
1918 * 'matches' is list of strings, 'len' is number of strings in 'matches',
1919 * 'max' is maximum length of string in 'matches'.
1920 */
1921 void
1922 rl_display_match_list(char **matches, int len, int max)
1923 {
1924
1925 fn_display_match_list(e, matches, (size_t)len, (size_t)max,
1926 _rl_completion_append_character_function);
1927 }
1928
1929 /*
1930 * complete word at current point
1931 */
1932 /* ARGSUSED */
1933 int
1934 rl_complete(int ignore __attribute__((__unused__)), int invoking_key)
1935 {
1936 static ct_buffer_t wbreak_conv, sprefix_conv;
1937 const char *breakchars;
1938
1939 if (h == NULL || e == NULL)
1940 rl_initialize();
1941
1942 if (rl_inhibit_completion) {
1943 char arr[2];
1944 arr[0] = (char)invoking_key;
1945 arr[1] = '\0';
1946 el_insertstr(e, arr);
1947 return CC_REFRESH;
1948 }
1949
1950 if (rl_completion_word_break_hook != NULL)
1951 breakchars = (*rl_completion_word_break_hook)();
1952 else
1953 breakchars = rl_basic_word_break_characters;
1954
1955 _rl_update_pos();
1956
1957 /* Just look at how many global variables modify this operation! */
1958 return fn_complete(e,
1959 (rl_compentry_func_t *)rl_completion_entry_function,
1960 rl_attempted_completion_function,
1961 ct_decode_string(rl_basic_word_break_characters, &wbreak_conv),
1962 ct_decode_string(breakchars, &sprefix_conv),
1963 _rl_completion_append_character_function,
1964 (size_t)rl_completion_query_items,
1965 &rl_completion_type, &rl_attempted_completion_over,
1966 &rl_point, &rl_end);
1967
1968
1969 }
1970
1971
1972 /* ARGSUSED */
1973 static unsigned char
1974 _el_rl_complete(EditLine *el __attribute__((__unused__)), int ch)
1975 {
1976 return (unsigned char)rl_complete(0, ch);
1977 }
1978
1979 /*
1980 * misc other functions
1981 */
1982
1983 /*
1984 * bind key c to readline-type function func
1985 */
1986 int
1987 rl_bind_key(int c, rl_command_func_t *func)
1988 {
1989 int retval = -1;
1990
1991 if (h == NULL || e == NULL)
1992 rl_initialize();
1993
1994 if (func == rl_insert) {
1995 /* XXX notice there is no range checking of ``c'' */
1996 e->el_map.key[c] = ED_INSERT;
1997 retval = 0;
1998 }
1999 return retval;
2000 }
2001
2002
2003 /*
2004 * read one key from input - handles chars pushed back
2005 * to input stream also
2006 */
2007 int
2008 rl_read_key(void)
2009 {
2010 char fooarr[2 * sizeof(int)];
2011
2012 if (e == NULL || h == NULL)
2013 rl_initialize();
2014
2015 return el_getc(e, fooarr);
2016 }
2017
2018
2019 /*
2020 * reset the terminal
2021 */
2022 /* ARGSUSED */
2023 int
2024 rl_reset_terminal(const char *p __attribute__((__unused__)))
2025 {
2026
2027 if (h == NULL || e == NULL)
2028 rl_initialize();
2029 el_reset(e);
2030 return 0;
2031 }
2032
2033
2034 /*
2035 * insert character ``c'' back into input stream, ``count'' times
2036 */
2037 int
2038 rl_insert(int count, int c)
2039 {
2040 char arr[2];
2041
2042 if (h == NULL || e == NULL)
2043 rl_initialize();
2044
2045 /* XXX - int -> char conversion can lose on multichars */
2046 arr[0] = (char)c;
2047 arr[1] = '\0';
2048
2049 for (; count > 0; count--)
2050 el_push(e, arr);
2051
2052 return 0;
2053 }
2054
2055 int
2056 rl_insert_text(const char *text)
2057 {
2058 if (!text || *text == 0)
2059 return 0;
2060
2061 if (h == NULL || e == NULL)
2062 rl_initialize();
2063
2064 if (el_insertstr(e, text) < 0)
2065 return 0;
2066 return (int)strlen(text);
2067 }
2068
2069 /*ARGSUSED*/
2070 int
2071 rl_newline(int count __attribute__((__unused__)),
2072 int c __attribute__((__unused__)))
2073 {
2074 /*
2075 * Readline-4.0 appears to ignore the args.
2076 */
2077 return rl_insert(1, '\n');
2078 }
2079
2080 /*ARGSUSED*/
2081 static unsigned char
2082 rl_bind_wrapper(EditLine *el __attribute__((__unused__)), unsigned char c)
2083 {
2084 if (map[c] == NULL)
2085 return CC_ERROR;
2086
2087 _rl_update_pos();
2088
2089 (*map[c])(1, c);
2090
2091 /* If rl_done was set by the above call, deal with it here */
2092 if (rl_done)
2093 return CC_EOF;
2094
2095 return CC_NORM;
2096 }
2097
2098 int
2099 rl_add_defun(const char *name, rl_command_func_t *fun, int c)
2100 {
2101 char dest[8];
2102 if ((size_t)c >= sizeof(map) / sizeof(map[0]) || c < 0)
2103 return -1;
2104 map[(unsigned char)c] = fun;
2105 el_set(e, EL_ADDFN, name, name, rl_bind_wrapper);
2106 vis(dest, c, VIS_WHITE|VIS_NOSLASH, 0);
2107 el_set(e, EL_BIND, dest, name, NULL);
2108 return 0;
2109 }
2110
2111 void
2112 rl_callback_read_char(void)
2113 {
2114 int count = 0, done = 0;
2115 const char *buf = el_gets(e, &count);
2116 char *wbuf;
2117
2118 el_set(e, EL_UNBUFFERED, 1);
2119 if (buf == NULL || count-- <= 0)
2120 return;
2121 if (count == 0 && buf[0] == e->el_tty.t_c[TS_IO][C_EOF])
2122 done = 1;
2123 if (buf[count] == '\n' || buf[count] == '\r')
2124 done = 2;
2125
2126 if (done && rl_linefunc != NULL) {
2127 el_set(e, EL_UNBUFFERED, 0);
2128 if (done == 2) {
2129 if ((wbuf = strdup(buf)) != NULL)
2130 wbuf[count] = '\0';
2131 } else
2132 wbuf = NULL;
2133 (*(void (*)(const char *))rl_linefunc)(wbuf);
2134 }
2135 }
2136
2137 void
2138 rl_callback_handler_install(const char *prompt, rl_vcpfunc_t *linefunc)
2139 {
2140 if (e == NULL) {
2141 rl_initialize();
2142 }
2143 (void)rl_set_prompt(prompt);
2144 rl_linefunc = linefunc;
2145 el_set(e, EL_UNBUFFERED, 1);
2146 }
2147
2148 void
2149 rl_callback_handler_remove(void)
2150 {
2151 el_set(e, EL_UNBUFFERED, 0);
2152 rl_linefunc = NULL;
2153 }
2154
2155 void
2156 rl_redisplay(void)
2157 {
2158 char a[2];
2159 a[0] = (char)e->el_tty.t_c[TS_IO][C_REPRINT];
2160 a[1] = '\0';
2161 el_push(e, a);
2162 }
2163
2164 int
2165 rl_get_previous_history(int count, int key)
2166 {
2167 char a[2];
2168 a[0] = (char)key;
2169 a[1] = '\0';
2170 while (count--)
2171 el_push(e, a);
2172 return 0;
2173 }
2174
2175 void
2176 /*ARGSUSED*/
2177 rl_prep_terminal(int meta_flag __attribute__((__unused__)))
2178 {
2179 el_set(e, EL_PREP_TERM, 1);
2180 }
2181
2182 void
2183 rl_deprep_terminal(void)
2184 {
2185 el_set(e, EL_PREP_TERM, 0);
2186 }
2187
2188 int
2189 rl_read_init_file(const char *s)
2190 {
2191 return el_source(e, s);
2192 }
2193
2194 int
2195 rl_parse_and_bind(const char *line)
2196 {
2197 const char **argv;
2198 int argc;
2199 Tokenizer *tok;
2200
2201 tok = tok_init(NULL);
2202 tok_str(tok, line, &argc, &argv);
2203 argc = el_parse(e, argc, argv);
2204 tok_end(tok);
2205 return argc ? 1 : 0;
2206 }
2207
2208 int
2209 rl_variable_bind(const char *var, const char *value)
2210 {
2211 /*
2212 * The proper return value is undocument, but this is what the
2213 * readline source seems to do.
2214 */
2215 return el_set(e, EL_BIND, "", var, value, NULL) == -1 ? 1 : 0;
2216 }
2217
2218 int
2219 rl_stuff_char(int c)
2220 {
2221 char buf[2];
2222
2223 buf[0] = (char)c;
2224 buf[1] = '\0';
2225 el_insertstr(e, buf);
2226 return 1;
2227 }
2228
2229 static int
2230 _rl_event_read_char(EditLine *el, wchar_t *wc)
2231 {
2232 char ch;
2233 int n;
2234 ssize_t num_read = 0;
2235
2236 ch = '\0';
2237 *wc = L'\0';
2238 while (rl_event_hook) {
2239
2240 (*rl_event_hook)();
2241
2242 #if defined(FIONREAD)
2243 if (ioctl(el->el_infd, FIONREAD, &n) < 0)
2244 return -1;
2245 if (n)
2246 num_read = read(el->el_infd, &ch, (size_t)1);
2247 else
2248 num_read = 0;
2249 #elif defined(F_SETFL) && defined(O_NDELAY)
2250 if ((n = fcntl(el->el_infd, F_GETFL, 0)) < 0)
2251 return -1;
2252 if (fcntl(el->el_infd, F_SETFL, n|O_NDELAY) < 0)
2253 return -1;
2254 num_read = read(el->el_infd, &ch, 1);
2255 if (fcntl(el->el_infd, F_SETFL, n))
2256 return -1;
2257 #else
2258 /* not non-blocking, but what you gonna do? */
2259 num_read = read(el->el_infd, &ch, 1);
2260 return -1;
2261 #endif
2262
2263 if (num_read < 0 && errno == EAGAIN)
2264 continue;
2265 if (num_read == 0)
2266 continue;
2267 break;
2268 }
2269 if (!rl_event_hook)
2270 el_set(el, EL_GETCFN, EL_BUILTIN_GETCFN);
2271 *wc = (wchar_t)ch;
2272 return (int)num_read;
2273 }
2274
2275 static void
2276 _rl_update_pos(void)
2277 {
2278 const LineInfo *li = el_line(e);
2279
2280 rl_point = (int)(li->cursor - li->buffer);
2281 rl_end = (int)(li->lastchar - li->buffer);
2282 rl_line_buffer[rl_end] = '\0';
2283 }
2284
2285 void
2286 rl_get_screen_size(int *rows, int *cols)
2287 {
2288 if (rows)
2289 el_get(e, EL_GETTC, "li", rows);
2290 if (cols)
2291 el_get(e, EL_GETTC, "co", cols);
2292 }
2293
2294 void
2295 rl_set_screen_size(int rows, int cols)
2296 {
2297 char buf[64];
2298 (void)snprintf(buf, sizeof(buf), "%d", rows);
2299 el_set(e, EL_SETTC, "li", buf, NULL);
2300 (void)snprintf(buf, sizeof(buf), "%d", cols);
2301 el_set(e, EL_SETTC, "co", buf, NULL);
2302 }
2303
2304 char **
2305 rl_completion_matches(const char *str, rl_compentry_func_t *fun)
2306 {
2307 size_t len, max, i, j, min;
2308 char **list, *match, *a, *b;
2309
2310 len = 1;
2311 max = 10;
2312 if ((list = el_calloc(max, sizeof(*list))) == NULL)
2313 return NULL;
2314
2315 while ((match = (*fun)(str, (int)(len - 1))) != NULL) {
2316 list[len++] = match;
2317 if (len == max) {
2318 char **nl;
2319 max += 10;
2320 if ((nl = el_realloc(list, max * sizeof(*nl))) == NULL)
2321 goto out;
2322 list = nl;
2323 }
2324 }
2325 if (len == 1)
2326 goto out;
2327 list[len] = NULL;
2328 if (len == 2) {
2329 if ((list[0] = strdup(list[1])) == NULL)
2330 goto out;
2331 return list;
2332 }
2333 qsort(&list[1], len - 1, sizeof(*list),
2334 (int (*)(const void *, const void *)) strcmp);
2335 min = SIZE_MAX;
2336 for (i = 1, a = list[i]; i < len - 1; i++, a = b) {
2337 b = list[i + 1];
2338 for (j = 0; a[j] && a[j] == b[j]; j++)
2339 continue;
2340 if (min > j)
2341 min = j;
2342 }
2343 if (min == 0 && *str) {
2344 if ((list[0] = strdup(str)) == NULL)
2345 goto out;
2346 } else {
2347 if ((list[0] = el_calloc(min + 1, sizeof(*list[0]))) == NULL)
2348 goto out;
2349 (void)memcpy(list[0], list[1], min);
2350 list[0][min] = '\0';
2351 }
2352 return list;
2353
2354 out:
2355 el_free(list);
2356 return NULL;
2357 }
2358
2359 char *
2360 rl_filename_completion_function (const char *text, int state)
2361 {
2362 return fn_filename_completion_function(text, state);
2363 }
2364
2365 void
2366 rl_forced_update_display(void)
2367 {
2368 el_set(e, EL_REFRESH);
2369 }
2370
2371 int
2372 _rl_abort_internal(void)
2373 {
2374 el_beep(e);
2375 longjmp(topbuf, 1);
2376 /*NOTREACHED*/
2377 }
2378
2379 int
2380 _rl_qsort_string_compare(char **s1, char **s2)
2381 {
2382 return strcoll(*s1, *s2);
2383 }
2384
2385 HISTORY_STATE *
2386 history_get_history_state(void)
2387 {
2388 HISTORY_STATE *hs;
2389
2390 if ((hs = el_malloc(sizeof(*hs))) == NULL)
2391 return NULL;
2392 hs->length = history_length;
2393 return hs;
2394 }
2395
2396 int
2397 /*ARGSUSED*/
2398 rl_kill_text(int from __attribute__((__unused__)),
2399 int to __attribute__((__unused__)))
2400 {
2401 return 0;
2402 }
2403
2404 Keymap
2405 rl_make_bare_keymap(void)
2406 {
2407 return NULL;
2408 }
2409
2410 Keymap
2411 rl_get_keymap(void)
2412 {
2413 return NULL;
2414 }
2415
2416 void
2417 /*ARGSUSED*/
2418 rl_set_keymap(Keymap k __attribute__((__unused__)))
2419 {
2420 }
2421
2422 int
2423 /*ARGSUSED*/
2424 rl_generic_bind(int type __attribute__((__unused__)),
2425 const char * keyseq __attribute__((__unused__)),
2426 const char * data __attribute__((__unused__)),
2427 Keymap k __attribute__((__unused__)))
2428 {
2429 return 0;
2430 }
2431
2432 int
2433 /*ARGSUSED*/
2434 rl_bind_key_in_map(int key __attribute__((__unused__)),
2435 rl_command_func_t *fun __attribute__((__unused__)),
2436 Keymap k __attribute__((__unused__)))
2437 {
2438 return 0;
2439 }
2440
2441 /* unsupported, but needed by python */
2442 void
2443 rl_cleanup_after_signal(void)
2444 {
2445 }
2446
2447 int
2448 rl_on_new_line(void)
2449 {
2450 return 0;
2451 }
2452
2453 void
2454 rl_free_line_state(void)
2455 {
2456 }
2457
2458 int
2459 /*ARGSUSED*/
2460 rl_set_keyboard_input_timeout(int u __attribute__((__unused__)))
2461 {
2462 return 0;
2463 }
2464
2465 void
2466 rl_resize_terminal(void)
2467 {
2468 el_resize(e);
2469 }
2470
2471 void
2472 rl_reset_after_signal(void)
2473 {
2474 if (rl_prep_term_function)
2475 (*rl_prep_term_function)();
2476 }
2477
2478 void
2479 rl_echo_signal_char(int sig)
2480 {
2481 int c = tty_get_signal_character(e, sig);
2482 if (c == -1)
2483 return;
2484 re_putc(e, c, 0);
2485 }
2486
2487 int
2488 rl_crlf(void)
2489 {
2490 re_putc(e, '\n', 0);
2491 return 0;
2492 }
2493
2494 int
2495 rl_ding(void)
2496 {
2497 re_putc(e, '\a', 0);
2498 return 0;
2499 }
2500
2501 int
2502 rl_abort(int count, int key)
2503 {
2504 return count && key ? 0 : 0;
2505 }
2506
2507 int
2508 rl_set_keymap_name(const char *name, Keymap k)
2509 {
2510 return name && k ? 0 : 0;
2511 }
2512
2513 histdata_t
2514 free_history_entry(HIST_ENTRY *he)
2515 {
2516 return he ? NULL : NULL;
2517 }
2518
2519 void
2520 _rl_erase_entire_line(void)
2521 {
2522 }
2523