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