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