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