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