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