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