Titan Core Initial Contribution
[deliverable/titan.core.git] / mctr2 / editline / libedit / src / readline.c
CommitLineData
970ed795
EL
1/* $NetBSD: readline.c,v 1.89 2010/04/15 00:57:33 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.89 2010/04/15 00:57:33 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#include <vis.h>
51#include "editline/readline.h"
52#include "el.h"
53#include "fcns.h" /* for EL_NUM_FCNS */
54#include "histedit.h"
55#include "filecomplete.h"
56
57#if !defined(SIZE_T_MAX)
58# define SIZE_T_MAX (size_t)(-1)
59#endif
60
61void rl_prep_terminal(int);
62void 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 */
72const char *rl_library_version = "EditLine wrapper";
73int rl_readline_version = RL_READLINE_VERSION;
74static char empty[] = { '\0' };
75static char expand_chars[] = { ' ', '\t', '\n', '=', '(', '\0' };
76static char break_chars[] = { ' ', '\t', '\n', '"', '\\', '\'', '`', '@', '$',
77 '>', '<', '=', ';', '|', '&', '{', '(', '\0' };
78char *rl_readline_name = empty;
79FILE *rl_instream = NULL;
80FILE *rl_outstream = NULL;
81int rl_point = 0;
82int rl_end = 0;
83char *rl_line_buffer = NULL;
84VCPFunction *rl_linefunc = NULL;
85int rl_done = 0;
86VFunction *rl_event_hook = NULL;
87KEYMAP_ENTRY_ARRAY emacs_standard_keymap,
88 emacs_meta_keymap,
89 emacs_ctlx_keymap;
90
91int history_base = 1; /* probably never subject to change */
92int history_length = 0;
93int max_input_history = 0;
94char history_expansion_char = '!';
95char history_subst_char = '^';
96char *history_no_expand_chars = expand_chars;
97Function *history_inhibit_expansion_function = NULL;
98char *history_arg_extract(int start, int end, const char *str);
99
100int rl_inhibit_completion = 0;
101int rl_attempted_completion_over = 0;
102char *rl_basic_word_break_characters = break_chars;
103char *rl_completer_word_break_characters = NULL;
104char *rl_completer_quote_characters = NULL;
105Function *rl_completion_entry_function = NULL;
106CPPFunction *rl_attempted_completion_function = NULL;
107Function *rl_pre_input_hook = NULL;
108Function *rl_startup1_hook = NULL;
109int (*rl_getc_function)(FILE *) = NULL;
110char *rl_terminal_name = NULL;
111int rl_already_prompted = 0;
112int rl_filename_completion_desired = 0;
113int rl_ignore_completion_duplicates = 0;
114int rl_catch_signals = 1;
115int readline_echoing_p = 1;
116int _rl_print_completions_horizontally = 0;
117VFunction *rl_redisplay_function = NULL;
118Function *rl_startup_hook = NULL;
119VFunction *rl_completion_display_matches_hook = NULL;
120VFunction *rl_prep_term_function = (VFunction *)rl_prep_terminal;
121VFunction *rl_deprep_term_function = (VFunction *)rl_deprep_terminal;
122KEYMAP_ENTRY_ARRAY emacs_meta_keymap;
123
124#ifdef WIDECHAR
125static ct_buffer_t conv;
126#endif
127
128/*
129 * The current prompt string.
130 */
131char *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 */
137int 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 */
143int 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 */
150char *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 */
156int rl_completion_append_character = ' ';
157
158/* stuff below is used internally by libedit for readline emulation */
159
160static TYPE(History) *h = NULL;
161static EditLine *e = NULL;
162static Function *map[256];
163static jmp_buf topbuf;
164
165/* internal functions */
166static unsigned char _el_rl_complete(EditLine *, int);
167static unsigned char _el_rl_tstp(EditLine *, int);
168static char *_get_prompt(EditLine *);
169static int _getc_function(EditLine *, char *);
170static HIST_ENTRY *_move_history(int);
171static int _history_expand_command(const char *, size_t, size_t,
172 char **);
173static char *_rl_compat_sub(const char *, const char *,
174 const char *, int);
175static int _rl_event_read_char(EditLine *, char *);
176static void _rl_update_pos(void);
177
178
179/* ARGSUSED */
180static 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 */
191static 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 */
210static int
211/*ARGSUSED*/
212_getc_function(EditLine *el __attribute__((__unused__)), char *c)
213{
214 int i;
215
216 i = (*rl_getc_function)(NULL);
217 if (i == -1)
218 return 0;
219 *c = i;
220 return 1;
221}
222
223static const char _dothistory[] = "/.history";
224
225static 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 */
247int
248rl_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 */
271int
272rl_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 */
370char *
371readline(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 */
435void
436using_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 */
448static 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
491static char *last_search_pat; /* last !?pat[?] search pattern */
492static char *last_search_match; /* last !?pat[?] that matched */
493
494const char *
495get_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 */
623static 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 */
868int
869history_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;
927loop:
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*/
1000char *
1001history_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
1044out:
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 */
1056char **
1057history_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 */
1115void
1116stifle_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 */
1131int
1132unstifle_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
1144int
1145history_is_stifled(void)
1146{
1147
1148 /* cannot return true answer */
1149 return (max_input_history != INT_MAX);
1150}
1151
1152static const char _history_tmp_template[] = "/tmp/.historyXXXXXX";
1153
1154int
1155history_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);
1278out3:
1279 fclose(tp);
1280out2:
1281 unlink(template);
1282out1:
1283 fclose(fp);
1284
1285 return ret;
1286}
1287
1288
1289/*
1290 * read history from a file given
1291 */
1292int
1293read_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 ?
1302 (errno ? errno : EINVAL) : 0);
1303}
1304
1305
1306/*
1307 * write history to a file given
1308 */
1309int
1310write_history(const char *filename)
1311{
1312 TYPE(HistEvent) ev;
1313
1314 if (h == NULL || e == NULL)
1315 rl_initialize();
1316 if (filename == NULL && (filename = _default_history_file()) == NULL)
1317 return errno;
1318 return (FUNW(history)(h, &ev, H_SAVE, filename) == -1 ?
1319 (errno ? errno : EINVAL) : 0);
1320}
1321
1322
1323/*
1324 * returns history ``num''th event
1325 *
1326 * returned pointer points to static variable
1327 */
1328HIST_ENTRY *
1329history_get(int num)
1330{
1331 static HIST_ENTRY she;
1332 TYPE(HistEvent) ev;
1333 int curr_num;
1334
1335 if (h == NULL || e == NULL)
1336 rl_initialize();
1337
1338 /* save current position */
1339 if (FUNW(history)(h, &ev, H_CURR) != 0)
1340 return (NULL);
1341 curr_num = ev.num;
1342
1343 /* start from the oldest */
1344 if (FUNW(history)(h, &ev, H_LAST) != 0)
1345 return (NULL); /* error */
1346
1347 /* look forwards for event matching specified offset */
1348 if (FUNW(history)(h, &ev, H_NEXT_EVDATA, num, &she.data))
1349 return (NULL);
1350
1351 she.line = ct_encode_string(ev.str, &conv);
1352
1353 /* restore pointer to where it was */
1354 (void)FUNW(history)(h, &ev, H_SET, curr_num);
1355
1356 return (&she);
1357}
1358
1359
1360/*
1361 * add the line to history table
1362 */
1363int
1364add_history(const char *line)
1365{
1366 TYPE(HistEvent) ev;
1367 const Char *wline;
1368
1369 if (h == NULL || e == NULL)
1370 rl_initialize();
1371
1372 wline = ct_decode_string(line, &conv);
1373
1374 (void)FUNW(history)(h, &ev, H_ENTER, wline);
1375 if (FUNW(history)(h, &ev, H_GETSIZE) == 0)
1376 history_length = ev.num;
1377
1378 return (!(history_length > 0)); /* return 0 if all is okay */
1379}
1380
1381
1382/*
1383 * remove the specified entry from the history list and return it.
1384 */
1385HIST_ENTRY *
1386remove_history(int num)
1387{
1388 HIST_ENTRY *he;
1389 TYPE(HistEvent) ev;
1390
1391 if (h == NULL || e == NULL)
1392 rl_initialize();
1393
1394 if ((he = malloc(sizeof(*he))) == NULL)
1395 return NULL;
1396
1397 if (FUNW(history)(h, &ev, H_DELDATA, num, &he->data) != 0) {
1398 free(he);
1399 return NULL;
1400 }
1401
1402 he->line = ct_encode_string(ev.str, &conv);
1403 if (FUNW(history)(h, &ev, H_GETSIZE) == 0)
1404 history_length = ev.num;
1405
1406 return he;
1407}
1408
1409
1410/*
1411 * replace the line and data of the num-th entry
1412 */
1413HIST_ENTRY *
1414replace_history_entry(int num, const char *line, histdata_t data)
1415{
1416 HIST_ENTRY *he;
1417 TYPE(HistEvent) ev;
1418 int curr_num;
1419
1420 if (h == NULL || e == NULL)
1421 rl_initialize();
1422
1423 /* save current position */
1424 if (FUNW(history)(h, &ev, H_CURR) != 0)
1425 return NULL;
1426 curr_num = ev.num;
1427
1428 /* start from the oldest */
1429 if (FUNW(history)(h, &ev, H_LAST) != 0)
1430 return NULL; /* error */
1431
1432 if ((he = malloc(sizeof(*he))) == NULL)
1433 return NULL;
1434
1435 /* look forwards for event matching specified offset */
1436 if (FUNW(history)(h, &ev, H_NEXT_EVDATA, num, &he->data))
1437 goto out;
1438
1439 he->line = strdup(ct_encode_string(ev.str, &e->el_scratch));
1440 if (he->line == NULL)
1441 goto out;
1442
1443 if (FUNW(history)(h, &ev, H_REPLACE, line, data))
1444 goto out;
1445
1446 /* restore pointer to where it was */
1447 if (FUNW(history)(h, &ev, H_SET, curr_num))
1448 goto out;
1449
1450 return he;
1451out:
1452 free(he);
1453 return NULL;
1454}
1455
1456/*
1457 * clear the history list - delete all entries
1458 */
1459void
1460clear_history(void)
1461{
1462 TYPE(HistEvent) ev;
1463
1464 (void)FUNW(history)(h, &ev, H_CLEAR);
1465 history_length = 0;
1466}
1467
1468
1469/*
1470 * returns offset of the current history event
1471 */
1472int
1473where_history(void)
1474{
1475 TYPE(HistEvent) ev;
1476 int curr_num, off;
1477
1478 if (FUNW(history)(h, &ev, H_CURR) != 0)
1479 return (0);
1480 curr_num = ev.num;
1481
1482 (void)FUNW(history)(h, &ev, H_FIRST);
1483 off = 1;
1484 while (ev.num != curr_num && FUNW(history)(h, &ev, H_NEXT) == 0)
1485 off++;
1486
1487 return (off);
1488}
1489
1490
1491/*
1492 * returns current history event or NULL if there is no such event
1493 */
1494HIST_ENTRY *
1495current_history(void)
1496{
1497
1498 return (_move_history(H_CURR));
1499}
1500
1501
1502/*
1503 * returns total number of bytes history events' data are using
1504 */
1505int
1506history_total_bytes(void)
1507{
1508 TYPE(HistEvent) ev;
1509 int curr_num;
1510 size_t size;
1511
1512 if (FUNW(history)(h, &ev, H_CURR) != 0)
1513 return (-1);
1514 curr_num = ev.num;
1515
1516 (void)FUNW(history)(h, &ev, H_FIRST);
1517 size = 0;
1518 do
1519 size += Strlen(ev.str) * sizeof(*ev.str);
1520 while (FUNW(history)(h, &ev, H_NEXT) == 0);
1521
1522 /* get to the same position as before */
1523 FUNW(history)(h, &ev, H_PREV_EVENT, curr_num);
1524
1525 return (int)(size);
1526}
1527
1528
1529/*
1530 * sets the position in the history list to ``pos''
1531 */
1532int
1533history_set_pos(int pos)
1534{
1535 TYPE(HistEvent) ev;
1536 int curr_num;
1537
1538 if (pos >= history_length || pos < 0)
1539 return (-1);
1540
1541 (void)FUNW(history)(h, &ev, H_CURR);
1542 curr_num = ev.num;
1543
1544 /*
1545 * use H_DELDATA to set to nth history (without delete) by passing
1546 * (void **)-1
1547 */
1548 if (FUNW(history)(h, &ev, H_DELDATA, pos, (void **)-1)) {
1549 (void)FUNW(history)(h, &ev, H_SET, curr_num);
1550 return(-1);
1551 }
1552 return (0);
1553}
1554
1555
1556/*
1557 * returns previous event in history and shifts pointer accordingly
1558 */
1559HIST_ENTRY *
1560previous_history(void)
1561{
1562
1563 return (_move_history(H_PREV));
1564}
1565
1566
1567/*
1568 * returns next event in history and shifts pointer accordingly
1569 */
1570HIST_ENTRY *
1571next_history(void)
1572{
1573
1574 return (_move_history(H_NEXT));
1575}
1576
1577
1578/*
1579 * searches for first history event containing the str
1580 */
1581int
1582history_search(const char *str, int direction)
1583{
1584 TYPE(HistEvent) ev;
1585 const Char *strp;
1586 const Char *wstr;
1587 int curr_num;
1588
1589 if (FUNW(history)(h, &ev, H_CURR) != 0)
1590 return (-1);
1591 curr_num = ev.num;
1592
1593 wstr = ct_decode_string(str, &conv);
1594 for (;;) {
1595 if ((strp = Strstr(ev.str, wstr)) != NULL)
1596 return (int) (strp - ev.str);
1597 if (FUNW(history)(h, &ev, direction < 0 ? H_NEXT:H_PREV) != 0)
1598 break;
1599 }
1600 (void)FUNW(history)(h, &ev, H_SET, curr_num);
1601 return (-1);
1602}
1603
1604
1605/*
1606 * searches for first history event beginning with str
1607 */
1608int
1609history_search_prefix(const char *str, int direction)
1610{
1611 TYPE(HistEvent) ev;
1612
1613 return (FUNW(history)(h, &ev, direction < 0 ?
1614 H_PREV_STR : H_NEXT_STR, str));
1615}
1616
1617
1618/*
1619 * search for event in history containing str, starting at offset
1620 * abs(pos); continue backward, if pos<0, forward otherwise
1621 */
1622/* ARGSUSED */
1623int
1624history_search_pos(const char *str,
1625 int direction __attribute__((__unused__)), int pos)
1626{
1627 TYPE(HistEvent) ev;
1628 int curr_num, off;
1629 const Char *wstr;
1630
1631 off = (pos > 0) ? pos : -pos;
1632 pos = (pos > 0) ? 1 : -1;
1633
1634 if (FUNW(history)(h, &ev, H_CURR) != 0)
1635 return (-1);
1636 curr_num = ev.num;
1637
1638 if (history_set_pos(off) != 0 || FUNW(history)(h, &ev, H_CURR) != 0)
1639 return (-1);
1640
1641 wstr = ct_decode_string(str, &conv);
1642 for (;;) {
1643 if (Strstr(ev.str, wstr))
1644 return (off);
1645 if (FUNW(history)(h, &ev, (pos < 0) ? H_PREV : H_NEXT) != 0)
1646 break;
1647 }
1648
1649 /* set "current" pointer back to previous state */
1650 (void)FUNW(history)(h, &ev,
1651 pos < 0 ? H_NEXT_EVENT : H_PREV_EVENT, curr_num);
1652
1653 return (-1);
1654}
1655
1656
1657/********************************/
1658/* completion functions */
1659
1660char *
1661tilde_expand(char *name)
1662{
1663 return fn_tilde_expand(name);
1664}
1665
1666char *
1667filename_completion_function(const char *name, int state)
1668{
1669 return fn_filename_completion_function(name, state);
1670}
1671
1672/*
1673 * a completion generator for usernames; returns _first_ username
1674 * which starts with supplied text
1675 * text contains a partial username preceded by random character
1676 * (usually '~'); state is ignored
1677 * it's callers responsibility to free returned value
1678 */
1679char *
1680username_completion_function(const char *text, int state)
1681{
1682 struct passwd *pwd;
1683
1684 if (text[0] == '\0')
1685 return (NULL);
1686
1687 if (*text == '~')
1688 text++;
1689
1690 if (state == 0)
1691 setpwent();
1692
1693 while ((pwd = getpwent())
1694 && pwd != NULL && text[0] == pwd->pw_name[0]
1695 && strcmp(text, pwd->pw_name) == 0);
1696
1697 if (pwd == NULL) {
1698 endpwent();
1699 return NULL;
1700 }
1701 return strdup(pwd->pw_name);
1702}
1703
1704
1705/*
1706 * el-compatible wrapper to send TSTP on ^Z
1707 */
1708/* ARGSUSED */
1709static unsigned char
1710_el_rl_tstp(EditLine *el __attribute__((__unused__)), int ch __attribute__((__unused__)))
1711{
1712 (void)kill(0, SIGTSTP);
1713 return CC_NORM;
1714}
1715
1716/*
1717 * Display list of strings in columnar format on readline's output stream.
1718 * 'matches' is list of strings, 'len' is number of strings in 'matches',
1719 * 'max' is maximum length of string in 'matches'.
1720 */
1721void
1722rl_display_match_list(char **matches, int len, int max)
1723{
1724
1725 fn_display_match_list(e, matches, (size_t)len, (size_t)max);
1726}
1727
1728static const char *
1729/*ARGSUSED*/
1730_rl_completion_append_character_function(const char *dummy
1731 __attribute__((__unused__)))
1732{
1733 static char buf[2];
1734 buf[0] = rl_completion_append_character;
1735 buf[1] = '\0';
1736 return buf;
1737}
1738
1739
1740/*
1741 * complete word at current point
1742 */
1743/* ARGSUSED */
1744int
1745rl_complete(int ignore __attribute__((__unused__)), int invoking_key)
1746{
1747#ifdef WIDECHAR
1748 static ct_buffer_t wbreak_conv, sprefix_conv;
1749#endif
1750
1751 if (h == NULL || e == NULL)
1752 rl_initialize();
1753
1754 if (rl_inhibit_completion) {
1755 char arr[2];
1756 arr[0] = (char)invoking_key;
1757 arr[1] = '\0';
1758 el_insertstr(e, arr);
1759 return (CC_REFRESH);
1760 }
1761
1762 /* Just look at how many global variables modify this operation! */
1763 return fn_complete(e,
1764 (CPFunction *)rl_completion_entry_function,
1765 rl_attempted_completion_function,
1766 ct_decode_string(rl_basic_word_break_characters, &wbreak_conv),
1767 ct_decode_string(rl_special_prefixes, &sprefix_conv),
1768 _rl_completion_append_character_function,
1769 (size_t)rl_completion_query_items,
1770 &rl_completion_type, &rl_attempted_completion_over,
1771 &rl_point, &rl_end);
1772}
1773
1774
1775/* ARGSUSED */
1776static unsigned char
1777_el_rl_complete(EditLine *el __attribute__((__unused__)), int ch)
1778{
1779 return (unsigned char)rl_complete(0, ch);
1780}
1781
1782/*
1783 * misc other functions
1784 */
1785
1786/*
1787 * bind key c to readline-type function func
1788 */
1789int
1790rl_bind_key(int c, rl_command_func_t *func)
1791{
1792 int retval = -1;
1793
1794 if (h == NULL || e == NULL)
1795 rl_initialize();
1796
1797 if (func == rl_insert) {
1798 /* XXX notice there is no range checking of ``c'' */
1799 e->el_map.key[c] = ED_INSERT;
1800 retval = 0;
1801 }
1802 return (retval);
1803}
1804
1805
1806/*
1807 * read one key from input - handles chars pushed back
1808 * to input stream also
1809 */
1810int
1811rl_read_key(void)
1812{
1813 char fooarr[2 * sizeof(int)];
1814
1815 if (e == NULL || h == NULL)
1816 rl_initialize();
1817
1818 return (el_getc(e, fooarr));
1819}
1820
1821
1822/*
1823 * reset the terminal
1824 */
1825/* ARGSUSED */
1826void
1827rl_reset_terminal(const char *p __attribute__((__unused__)))
1828{
1829
1830 if (h == NULL || e == NULL)
1831 rl_initialize();
1832 el_reset(e);
1833}
1834
1835
1836/*
1837 * insert character ``c'' back into input stream, ``count'' times
1838 */
1839int
1840rl_insert(int count, int c)
1841{
1842 char arr[2];
1843
1844 if (h == NULL || e == NULL)
1845 rl_initialize();
1846
1847 /* XXX - int -> char conversion can lose on multichars */
1848 arr[0] = c;
1849 arr[1] = '\0';
1850
1851 for (; count > 0; count--)
1852 el_push(e, arr);
1853
1854 return (0);
1855}
1856
1857int
1858rl_insert_text(const char *text)
1859{
1860 if (!text || *text == 0)
1861 return (0);
1862
1863 if (h == NULL || e == NULL)
1864 rl_initialize();
1865
1866 if (el_insertstr(e, text) < 0)
1867 return (0);
1868 return (int)strlen(text);
1869}
1870
1871/*ARGSUSED*/
1872int
1873rl_newline(int count __attribute__((__unused__)), int c __attribute__((__unused__)))
1874{
1875 /*
1876 * Readline-4.0 appears to ignore the args.
1877 */
1878 return rl_insert(1, '\n');
1879}
1880
1881/*ARGSUSED*/
1882static unsigned char
1883rl_bind_wrapper(EditLine *el __attribute__((__unused__)), unsigned char c)
1884{
1885 if (map[c] == NULL)
1886 return CC_ERROR;
1887
1888 _rl_update_pos();
1889
1890 (*map[c])(NULL, c);
1891
1892 /* If rl_done was set by the above call, deal with it here */
1893 if (rl_done)
1894 return CC_EOF;
1895
1896 return CC_NORM;
1897}
1898
1899int
1900rl_add_defun(const char *name, Function *fun, int c)
1901{
1902 char dest[8];
1903 if ((size_t)c >= sizeof(map) / sizeof(map[0]) || c < 0)
1904 return -1;
1905 map[(unsigned char)c] = fun;
1906 el_set(e, EL_ADDFN, name, name, rl_bind_wrapper);
1907 vis(dest, c, VIS_WHITE|VIS_NOSLASH, 0);
1908 el_set(e, EL_BIND, dest, name);
1909 return 0;
1910}
1911
1912void
1913rl_callback_read_char()
1914{
1915 int count = 0, done = 0;
1916 const char *buf = el_gets(e, &count);
1917 char *wbuf;
1918
1919 if (buf == NULL || count-- <= 0)
1920 return;
1921 if (count == 0 && buf[0] == e->el_tty.t_c[TS_IO][C_EOF])
1922 done = 1;
1923 if (buf[count] == '\n' || buf[count] == '\r')
1924 done = 2;
1925
1926 if (done && rl_linefunc != NULL) {
1927 el_set(e, EL_UNBUFFERED, 0);
1928 if (done == 2) {
1929 if ((wbuf = strdup(buf)) != NULL)
1930 wbuf[count] = '\0';
1931 } else
1932 wbuf = NULL;
1933 (*(void (*)(const char *))rl_linefunc)(wbuf);
1934 //el_set(e, EL_UNBUFFERED, 1);
1935 }
1936}
1937
1938void
1939rl_callback_handler_install(const char *prompt, VCPFunction *linefunc)
1940{
1941 if (e == NULL) {
1942 rl_initialize();
1943 }
1944 (void)rl_set_prompt(prompt);
1945 rl_linefunc = linefunc;
1946 el_set(e, EL_UNBUFFERED, 1);
1947}
1948
1949void
1950rl_callback_handler_remove(void)
1951{
1952 el_set(e, EL_UNBUFFERED, 0);
1953 rl_linefunc = NULL;
1954}
1955
1956void
1957rl_redisplay(void)
1958{
1959 char a[2];
1960 a[0] = e->el_tty.t_c[TS_IO][C_REPRINT];
1961 a[1] = '\0';
1962 el_push(e, a);
1963}
1964
1965int
1966rl_get_previous_history(int count, int key)
1967{
1968 char a[2];
1969 a[0] = key;
1970 a[1] = '\0';
1971 while (count--)
1972 el_push(e, a);
1973 return 0;
1974}
1975
1976void
1977/*ARGSUSED*/
1978rl_prep_terminal(int meta_flag __attribute__((__unused__)))
1979{
1980 el_set(e, EL_PREP_TERM, 1);
1981}
1982
1983void
1984rl_deprep_terminal(void)
1985{
1986 el_set(e, EL_PREP_TERM, 0);
1987}
1988
1989int
1990rl_read_init_file(const char *s)
1991{
1992 return(el_source(e, s));
1993}
1994
1995int
1996rl_parse_and_bind(const char *line)
1997{
1998 const char **argv;
1999 int argc;
2000 Tokenizer *tok;
2001
2002 tok = tok_init(NULL);
2003 tok_str(tok, line, &argc, &argv);
2004 argc = el_parse(e, argc, argv);
2005 tok_end(tok);
2006 return (argc ? 1 : 0);
2007}
2008
2009int
2010rl_variable_bind(const char *var, const char *value)
2011{
2012 /*
2013 * The proper return value is undocument, but this is what the
2014 * readline source seems to do.
2015 */
2016 return ((el_set(e, EL_BIND, "", var, value) == -1) ? 1 : 0);
2017}
2018
2019void
2020rl_stuff_char(int c)
2021{
2022 char buf[2];
2023
2024 buf[0] = c;
2025 buf[1] = '\0';
2026 el_insertstr(e, buf);
2027}
2028
2029static int
2030_rl_event_read_char(EditLine *el, char *cp)
2031{
2032 int n;
2033 ssize_t num_read = 0;
2034
2035 *cp = '\0';
2036 while (rl_event_hook) {
2037
2038 (*rl_event_hook)();
2039
2040#if defined(FIONREAD)
2041 if (ioctl(el->el_infd, FIONREAD, &n) < 0)
2042 return(-1);
2043 if (n)
2044 num_read = read(el->el_infd, cp, 1);
2045 else
2046 num_read = 0;
2047#elif defined(F_SETFL) && defined(O_NDELAY)
2048 if ((n = fcntl(el->el_infd, F_GETFL, 0)) < 0)
2049 return(-1);
2050 if (fcntl(el->el_infd, F_SETFL, n|O_NDELAY) < 0)
2051 return(-1);
2052 num_read = read(el->el_infd, cp, 1);
2053 if (fcntl(el->el_infd, F_SETFL, n))
2054 return(-1);
2055#else
2056 /* not non-blocking, but what you gonna do? */
2057 num_read = read(el->el_infd, cp, 1);
2058 return(-1);
2059#endif
2060
2061 if (num_read < 0 && errno == EAGAIN)
2062 continue;
2063 if (num_read == 0)
2064 continue;
2065 break;
2066 }
2067 if (!rl_event_hook)
2068 el_set(el, EL_GETCFN, EL_BUILTIN_GETCFN);
2069 return (int)num_read;
2070}
2071
2072static void
2073_rl_update_pos(void)
2074{
2075 const LineInfo *li = el_line(e);
2076
2077 rl_point = (int)(li->cursor - li->buffer);
2078 rl_end = (int)(li->lastchar - li->buffer);
2079}
2080
2081void
2082rl_get_screen_size(int *rows, int *cols)
2083{
2084 if (rows)
2085 el_get(e, EL_GETTC, "li", rows);
2086 if (cols)
2087 el_get(e, EL_GETTC, "co", cols);
2088}
2089
2090void
2091rl_set_screen_size(int rows, int cols)
2092{
2093 char buf[64];
2094 (void)snprintf(buf, sizeof(buf), "%d", rows);
2095 el_set(e, EL_SETTC, "li", buf);
2096 (void)snprintf(buf, sizeof(buf), "%d", cols);
2097 el_set(e, EL_SETTC, "co", buf);
2098}
2099
2100char **
2101rl_completion_matches(const char *str, rl_compentry_func_t *fun)
2102{
2103 size_t len, max, i, j, min;
2104 char **list, *match, *a, *b;
2105
2106 len = 1;
2107 max = 10;
2108 if ((list = malloc(max * sizeof(*list))) == NULL)
2109 return NULL;
2110
2111 while ((match = (*fun)(str, (int)(len - 1))) != NULL) {
2112 list[len++] = match;
2113 if (len == max) {
2114 char **nl;
2115 max += 10;
2116 if ((nl = realloc(list, max * sizeof(*nl))) == NULL)
2117 goto out;
2118 list = nl;
2119 }
2120 }
2121 if (len == 1)
2122 goto out;
2123 list[len] = NULL;
2124 if (len == 2) {
2125 if ((list[0] = strdup(list[1])) == NULL)
2126 goto out;
2127 return list;
2128 }
2129 qsort(&list[1], len - 1, sizeof(*list),
2130 (int (*)(const void *, const void *)) strcmp);
2131 min = SIZE_T_MAX;
2132 for (i = 1, a = list[i]; i < len - 1; i++, a = b) {
2133 b = list[i + 1];
2134 for (j = 0; a[j] && a[j] == b[j]; j++)
2135 continue;
2136 if (min > j)
2137 min = j;
2138 }
2139 if (min == 0 && *str) {
2140 if ((list[0] = strdup(str)) == NULL)
2141 goto out;
2142 } else {
2143 if ((list[0] = malloc(min + 1)) == NULL)
2144 goto out;
2145 (void)memcpy(list[0], list[1], min);
2146 list[0][min] = '\0';
2147 }
2148 return list;
2149
2150out:
2151 free(list);
2152 return NULL;
2153}
2154
2155char *
2156rl_filename_completion_function (const char *text, int state)
2157{
2158 return fn_filename_completion_function(text, state);
2159}
2160
2161void
2162rl_forced_update_display(void)
2163{
2164 el_set(e, EL_REFRESH);
2165}
2166
2167int
2168_rl_abort_internal(void)
2169{
2170 el_beep(e);
2171 longjmp(topbuf, 1);
2172 /*NOTREACHED*/
2173}
2174
2175int
2176_rl_qsort_string_compare(char **s1, char **s2)
2177{
2178 return strcoll(*s1, *s2);
2179}
2180
2181HISTORY_STATE *
2182history_get_history_state(void)
2183{
2184 HISTORY_STATE *hs;
2185
2186 if ((hs = malloc(sizeof(HISTORY_STATE))) == NULL)
2187 return (NULL);
2188 hs->length = history_length;
2189 return (hs);
2190}
2191
2192int
2193/*ARGSUSED*/
2194rl_kill_text(int from __attribute__((__unused__)), int to __attribute__((__unused__)))
2195{
2196 return 0;
2197}
2198
2199Keymap
2200rl_make_bare_keymap(void)
2201{
2202 return NULL;
2203}
2204
2205Keymap
2206rl_get_keymap(void)
2207{
2208 return NULL;
2209}
2210
2211void
2212/*ARGSUSED*/
2213rl_set_keymap(Keymap k __attribute__((__unused__)))
2214{
2215}
2216
2217int
2218/*ARGSUSED*/
2219rl_generic_bind(int type __attribute__((__unused__)), const char * keyseq __attribute__((__unused__)), const char * data __attribute__((__unused__)), Keymap k __attribute__((__unused__)))
2220{
2221 return 0;
2222}
2223
2224int
2225/*ARGSUSED*/
2226rl_bind_key_in_map(int key __attribute__((__unused__)), rl_command_func_t *fun __attribute__((__unused__)), Keymap k __attribute__((__unused__)))
2227{
2228 return 0;
2229}
2230
2231/* unsupported, but needed by python */
2232void
2233rl_cleanup_after_signal(void)
2234{
2235}
This page took 0.112996 seconds and 5 git commands to generate.