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