1 /* $NetBSD: readline.c,v 1.114 2015/03/24 21:29:52 christos Exp $ */
4 * Copyright (c) 1997 The NetBSD Foundation, Inc.
7 * This code is derived from software contributed to The NetBSD Foundation
10 * Redistribution and use in source and binary forms, with or without
11 * modification, are permitted provided that the following conditions
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.
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.
33 #if !defined(lint) && !defined(SCCSID)
34 __RCSID("$NetBSD: readline.c,v 1.114 2015/03/24 21:29:52 christos Exp $");
35 #endif /* not lint && not SCCSID */
37 #include <sys/types.h>
52 #include "editline/readline.h"
54 #include "fcns.h" /* for EL_NUM_FCNS */
56 #include "filecomplete.h"
58 #if !defined(SIZE_T_MAX)
59 # define SIZE_T_MAX (size_t)(-1)
62 void rl_prep_terminal(int);
63 void rl_deprep_terminal(void);
65 /* for rl_complete() */
68 /* see comment at the #ifdef for sense of this */
69 /* #define GDB_411_HACK */
71 /* readline compatibility stuff - look at readline sources/documentation */
72 /* to see what these variables mean */
73 const char *rl_library_version
= "EditLine wrapper";
74 int rl_readline_version
= RL_READLINE_VERSION
;
75 static char empty
[] = { '\0' };
76 static char expand_chars
[] = { ' ', '\t', '\n', '=', '(', '\0' };
77 static char break_chars
[] = { ' ', '\t', '\n', '"', '\\', '\'', '`', '@', '$',
78 '>', '<', '=', ';', '|', '&', '{', '(', '\0' };
79 char *rl_readline_name
= empty
;
80 FILE *rl_instream
= NULL
;
81 FILE *rl_outstream
= NULL
;
84 char *rl_line_buffer
= NULL
;
85 VCPFunction
*rl_linefunc
= NULL
;
87 VFunction
*rl_event_hook
= NULL
;
88 KEYMAP_ENTRY_ARRAY emacs_standard_keymap
,
92 * The following is not implemented; we always catch signals in the
93 * libedit fashion: set handlers on entry to el_gets() and clear them
94 * on the way out. This simplistic approach works for most cases; if
95 * it does not work for your application, please let us know.
97 int rl_catch_signals
= 1;
98 int rl_catch_sigwinch
= 1;
100 int history_base
= 1; /* probably never subject to change */
101 int history_length
= 0;
102 int max_input_history
= 0;
103 char history_expansion_char
= '!';
104 char history_subst_char
= '^';
105 char *history_no_expand_chars
= expand_chars
;
106 Function
*history_inhibit_expansion_function
= NULL
;
107 char *history_arg_extract(int start
, int end
, const char *str
);
109 int rl_inhibit_completion
= 0;
110 int rl_attempted_completion_over
= 0;
111 char *rl_basic_word_break_characters
= break_chars
;
112 char *rl_completer_word_break_characters
= NULL
;
113 char *rl_completer_quote_characters
= NULL
;
114 Function
*rl_completion_entry_function
= NULL
;
115 char *(*rl_completion_word_break_hook
)(void) = NULL
;
116 CPPFunction
*rl_attempted_completion_function
= NULL
;
117 Function
*rl_pre_input_hook
= NULL
;
118 Function
*rl_startup1_hook
= NULL
;
119 int (*rl_getc_function
)(FILE *) = NULL
;
120 char *rl_terminal_name
= NULL
;
121 int rl_already_prompted
= 0;
122 int rl_filename_completion_desired
= 0;
123 int rl_ignore_completion_duplicates
= 0;
124 int readline_echoing_p
= 1;
125 int _rl_print_completions_horizontally
= 0;
126 VFunction
*rl_redisplay_function
= NULL
;
127 Function
*rl_startup_hook
= NULL
;
128 VFunction
*rl_completion_display_matches_hook
= NULL
;
129 VFunction
*rl_prep_term_function
= (VFunction
*)rl_prep_terminal
;
130 VFunction
*rl_deprep_term_function
= (VFunction
*)rl_deprep_terminal
;
131 KEYMAP_ENTRY_ARRAY emacs_meta_keymap
;
134 * The current prompt string.
136 char *rl_prompt
= NULL
;
138 * This is set to character indicating type of completion being done by
139 * rl_complete_internal(); this is available for application completion
142 int rl_completion_type
= 0;
145 * If more than this number of items results from query for possible
146 * completions, we ask user if they are sure to really display the list.
148 int rl_completion_query_items
= 100;
151 * List of characters which are word break characters, but should be left
152 * in the parsed text when it is passed to the completion function.
153 * Shell uses this to help determine what kind of completing to do.
155 char *rl_special_prefixes
= NULL
;
158 * This is the character appended to the completed words if at the end of
159 * the line. Default is ' ' (a space).
161 int rl_completion_append_character
= ' ';
163 /* stuff below is used internally by libedit for readline emulation */
165 static History
*h
= NULL
;
166 static EditLine
*e
= NULL
;
167 static Function
*map
[256];
168 static jmp_buf topbuf
;
170 /* internal functions */
171 static unsigned char _el_rl_complete(EditLine
*, int);
172 static unsigned char _el_rl_tstp(EditLine
*, int);
173 static char *_get_prompt(EditLine
*);
174 static int _getc_function(EditLine
*, char *);
175 static HIST_ENTRY
*_move_history(int);
176 static int _history_expand_command(const char *, size_t, size_t,
178 static char *_rl_compat_sub(const char *, const char *,
180 static int _rl_event_read_char(EditLine
*, char *);
181 static void _rl_update_pos(void);
186 _get_prompt(EditLine
*el
__attribute__((__unused__
)))
188 rl_already_prompted
= 1;
194 * generic function for moving around history
197 _move_history(int op
)
200 static HIST_ENTRY rl_he
;
202 if (history(h
, &ev
, op
) != 0)
213 * read one key from user defined input function
217 _getc_function(EditLine
*el
__attribute__((__unused__
)), char *c
)
221 i
= (*rl_getc_function
)(NULL
);
229 _resize_fun(EditLine
*el
, void *a
)
235 /* a cheesy way to get rid of const cast. */
236 *ap
= memchr(li
->buffer
, *li
->buffer
, (size_t)1);
240 _default_history_file(void)
249 if ((p
= getpwuid(getuid())) == NULL
)
252 len
= strlen(p
->pw_dir
) + sizeof("/.history");
253 if ((path
= malloc(len
)) == NULL
)
256 (void)snprintf(path
, len
, "%s/.history", p
->pw_dir
);
261 * READLINE compatibility stuff
268 rl_set_prompt(const char *prompt
)
274 if (rl_prompt
!= NULL
&& strcmp(rl_prompt
, prompt
) == 0)
278 rl_prompt
= strdup(prompt
);
279 if (rl_prompt
== NULL
)
282 while ((p
= strchr(rl_prompt
, RL_PROMPT_END_IGNORE
)) != NULL
)
283 *p
= RL_PROMPT_START_IGNORE
;
289 * initialize rl compat stuff
306 rl_outstream
= stdout
;
309 * See if we don't really want to run the editor
311 if (tcgetattr(fileno(rl_instream
), &t
) != -1 && (t
.c_lflag
& ECHO
) == 0)
314 e
= el_init(rl_readline_name
, rl_instream
, rl_outstream
, stderr
);
317 el_set(e
, EL_EDITMODE
, 0);
323 history(h
, &ev
, H_SETSIZE
, INT_MAX
); /* unlimited */
325 max_input_history
= INT_MAX
;
326 el_set(e
, EL_HIST
, history
, h
);
328 /* Setup resize function */
329 el_set(e
, EL_RESIZE
, _resize_fun
, &rl_line_buffer
);
331 /* setup getc function if valid */
332 if (rl_getc_function
)
333 el_set(e
, EL_GETCFN
, _getc_function
);
335 /* for proper prompt printing in readline() */
336 if (rl_set_prompt("") == -1) {
341 el_set(e
, EL_PROMPT
, _get_prompt
, RL_PROMPT_START_IGNORE
);
342 el_set(e
, EL_SIGNAL
, rl_catch_signals
);
344 /* set default mode to "emacs"-style and read setting afterwards */
345 /* so this can be overridden */
346 el_set(e
, EL_EDITOR
, "emacs");
347 if (rl_terminal_name
!= NULL
)
348 el_set(e
, EL_TERMINAL
, rl_terminal_name
);
350 el_get(e
, EL_TERMINAL
, &rl_terminal_name
);
353 * Word completion - this has to go AFTER rebinding keys
356 el_set(e
, EL_ADDFN
, "rl_complete",
357 "ReadLine compatible completion function",
359 el_set(e
, EL_BIND
, "^I", "rl_complete", NULL
);
362 * Send TSTP when ^Z is pressed.
364 el_set(e
, EL_ADDFN
, "rl_tstp",
365 "ReadLine compatible suspend function",
367 el_set(e
, EL_BIND
, "^Z", "rl_tstp", NULL
);
370 * Set some readline compatible key-bindings.
372 el_set(e
, EL_BIND
, "^R", "em-inc-search-prev", NULL
);
375 * Allow the use of Home/End keys.
377 el_set(e
, EL_BIND
, "\\e[1~", "ed-move-to-beg", NULL
);
378 el_set(e
, EL_BIND
, "\\e[4~", "ed-move-to-end", NULL
);
379 el_set(e
, EL_BIND
, "\\e[7~", "ed-move-to-beg", NULL
);
380 el_set(e
, EL_BIND
, "\\e[8~", "ed-move-to-end", NULL
);
381 el_set(e
, EL_BIND
, "\\e[H", "ed-move-to-beg", NULL
);
382 el_set(e
, EL_BIND
, "\\e[F", "ed-move-to-end", NULL
);
385 * Allow the use of the Delete/Insert keys.
387 el_set(e
, EL_BIND
, "\\e[3~", "ed-delete-next-char", NULL
);
388 el_set(e
, EL_BIND
, "\\e[2~", "ed-quoted-insert", NULL
);
391 * Ctrl-left-arrow and Ctrl-right-arrow for word moving.
393 el_set(e
, EL_BIND
, "\\e[1;5C", "em-next-word", NULL
);
394 el_set(e
, EL_BIND
, "\\e[1;5D", "ed-prev-word", NULL
);
395 el_set(e
, EL_BIND
, "\\e[5C", "em-next-word", NULL
);
396 el_set(e
, EL_BIND
, "\\e[5D", "ed-prev-word", NULL
);
397 el_set(e
, EL_BIND
, "\\e\\e[C", "em-next-word", NULL
);
398 el_set(e
, EL_BIND
, "\\e\\e[D", "ed-prev-word", NULL
);
400 /* read settings from configuration file */
404 * Unfortunately, some applications really do use rl_point
405 * and rl_line_buffer directly.
407 _resize_fun(e
, &rl_line_buffer
);
411 (*rl_startup_hook
)(NULL
, 0);
418 * read one line from input stream and return it, chomping
419 * trailing newline (if there is any)
422 readline(const char *p
)
425 const char * volatile prompt
= p
;
429 static int used_event_hook
;
431 if (e
== NULL
|| h
== NULL
)
436 (void)setjmp(topbuf
);
438 /* update prompt accordingly to what has been passed */
439 if (rl_set_prompt(prompt
) == -1)
442 if (rl_pre_input_hook
)
443 (*rl_pre_input_hook
)(NULL
, 0);
445 if (rl_event_hook
&& !(e
->el_flags
&NO_TTY
)) {
446 el_set(e
, EL_GETCFN
, _rl_event_read_char
);
450 if (!rl_event_hook
&& used_event_hook
) {
451 el_set(e
, EL_GETCFN
, EL_BUILTIN_GETCFN
);
455 rl_already_prompted
= 0;
457 /* get one line from input stream */
458 ret
= el_gets(e
, &count
);
460 if (ret
&& count
> 0) {
467 if (buf
[lastidx
] == '\n')
472 history(h
, &ev
, H_GETSIZE
);
473 history_length
= ev
.num
;
483 * is normally called before application starts to use
484 * history expansion functions
489 if (h
== NULL
|| e
== NULL
)
495 * substitute ``what'' with ``with'', returning resulting string; if
496 * globally == 1, substitutes all occurrences of what, otherwise only the
500 _rl_compat_sub(const char *str
, const char *what
, const char *with
,
505 size_t len
, with_len
, what_len
;
508 with_len
= strlen(with
);
509 what_len
= strlen(what
);
511 /* calculate length we need for result */
514 if (*s
== *what
&& !strncmp(s
, what
, what_len
)) {
515 len
+= with_len
- what_len
;
522 r
= result
= el_malloc((len
+ 1) * sizeof(*r
));
527 if (*s
== *what
&& !strncmp(s
, what
, what_len
)) {
528 (void)strncpy(r
, with
, with_len
);
542 static char *last_search_pat
; /* last !?pat[?] search pattern */
543 static char *last_search_match
; /* last !?pat[?] that matched */
546 get_history_event(const char *cmd
, int *cindex
, int qchar
)
548 int idx
, sign
, sub
, num
, begin
, ret
;
555 if (cmd
[idx
++] != history_expansion_char
)
558 /* find out which event to take */
559 if (cmd
[idx
] == history_expansion_char
|| cmd
[idx
] == '\0') {
560 if (history(h
, &ev
, H_FIRST
) != 0)
562 *cindex
= cmd
[idx
]? (idx
+ 1):idx
;
566 if (cmd
[idx
] == '-') {
571 if ('0' <= cmd
[idx
] && cmd
[idx
] <= '9') {
575 while (cmd
[idx
] && '0' <= cmd
[idx
] && cmd
[idx
] <= '9') {
576 num
= num
* 10 + cmd
[idx
] - '0';
580 num
= history_length
- num
+ 1;
582 if (!(rl_he
= history_get(num
)))
589 if (cmd
[idx
] == '?') {
595 if (cmd
[idx
] == '\n')
597 if (sub
&& cmd
[idx
] == '?')
599 if (!sub
&& (cmd
[idx
] == ':' || cmd
[idx
] == ' '
600 || cmd
[idx
] == '\t' || cmd
[idx
] == qchar
))
604 len
= (size_t)idx
- (size_t)begin
;
605 if (sub
&& cmd
[idx
] == '?')
607 if (sub
&& len
== 0 && last_search_pat
&& *last_search_pat
)
608 pat
= last_search_pat
;
612 if ((pat
= el_malloc((len
+ 1) * sizeof(*pat
))) == NULL
)
614 (void)strncpy(pat
, cmd
+ begin
, len
);
618 if (history(h
, &ev
, H_CURR
) != 0) {
619 if (pat
!= last_search_pat
)
626 if (pat
!= last_search_pat
) {
628 el_free(last_search_pat
);
629 last_search_pat
= pat
;
631 ret
= history_search(pat
, -1);
633 ret
= history_search_prefix(pat
, -1);
636 /* restore to end of list on failed search */
637 history(h
, &ev
, H_FIRST
);
638 (void)fprintf(rl_outstream
, "%s: Event not found\n", pat
);
639 if (pat
!= last_search_pat
)
645 if (last_search_match
&& last_search_match
!= pat
)
646 el_free(last_search_match
);
647 last_search_match
= pat
;
650 if (pat
!= last_search_pat
)
653 if (history(h
, &ev
, H_CURR
) != 0)
658 /* roll back to original position */
659 (void)history(h
, &ev
, H_SET
, num
);
665 * the real function doing history expansion - takes as argument command
666 * to do and data upon which the command should be executed
667 * does expansion the way I've understood readline documentation
669 * returns 0 if data was not modified, 1 if it was and 2 if the string
670 * should be only printed and not executed; in case of error,
671 * returns -1 and *result points to NULL
672 * it's the caller's responsibility to free() the string returned in *result
675 _history_expand_command(const char *command
, size_t offs
, size_t cmdlen
,
678 char *tmp
, *search
= NULL
, *aptr
;
679 const char *ptr
, *cmd
;
680 static char *from
= NULL
, *to
= NULL
;
681 int start
, end
, idx
, has_mods
= 0;
682 int p_on
= 0, g_on
= 0;
688 /* First get event specifier */
691 if (strchr(":^*$", command
[offs
+ 1])) {
694 * "!:" is shorthand for "!!:".
695 * "!^", "!*" and "!$" are shorthand for
696 * "!!:^", "!!:*" and "!!:$" respectively.
698 str
[0] = str
[1] = '!';
700 ptr
= get_history_event(str
, &idx
, 0);
701 idx
= (command
[offs
+ 1] == ':')? 1:0;
704 if (command
[offs
+ 1] == '#') {
705 /* use command so far */
706 if ((aptr
= el_malloc((offs
+ 1) * sizeof(*aptr
)))
709 (void)strncpy(aptr
, command
, offs
);
715 qchar
= (offs
> 0 && command
[offs
- 1] == '"')? '"':0;
716 ptr
= get_history_event(command
+ offs
, &idx
, qchar
);
718 has_mods
= command
[offs
+ (size_t)idx
] == ':';
721 if (ptr
== NULL
&& aptr
== NULL
)
725 *result
= strdup(aptr
? aptr
: ptr
);
733 cmd
= command
+ offs
+ idx
+ 1;
735 /* Now parse any word designators */
737 if (*cmd
== '%') /* last word matched by ?pat? */
738 tmp
= strdup(last_search_match
? last_search_match
:"");
739 else if (strchr("^*$-0123456789", *cmd
)) {
742 start
= end
= 1, cmd
++;
743 else if (*cmd
== '$')
745 else if (*cmd
== '*')
747 else if (*cmd
== '-' || isdigit((unsigned char) *cmd
)) {
749 while (*cmd
&& '0' <= *cmd
&& *cmd
<= '9')
750 start
= start
* 10 + *cmd
++ - '0';
753 if (isdigit((unsigned char) cmd
[1])) {
756 while (*cmd
&& '0' <= *cmd
&& *cmd
<= '9')
757 end
= end
* 10 + *cmd
++ - '0';
758 } else if (cmd
[1] == '$') {
765 } else if (*cmd
== '*')
770 tmp
= history_arg_extract(start
, end
, aptr
? aptr
:ptr
);
772 (void)fprintf(rl_outstream
, "%s: Bad word specifier",
773 command
+ offs
+ idx
);
779 tmp
= strdup(aptr
? aptr
:ptr
);
784 if (*cmd
== '\0' || ((size_t)(cmd
- (command
+ offs
)) >= cmdlen
)) {
789 for (; *cmd
; cmd
++) {
792 else if (*cmd
== 'h') { /* remove trailing path */
793 if ((aptr
= strrchr(tmp
, '/')) != NULL
)
795 } else if (*cmd
== 't') { /* remove leading path */
796 if ((aptr
= strrchr(tmp
, '/')) != NULL
) {
797 aptr
= strdup(aptr
+ 1);
801 } else if (*cmd
== 'r') { /* remove trailing suffix */
802 if ((aptr
= strrchr(tmp
, '.')) != NULL
)
804 } else if (*cmd
== 'e') { /* remove all but suffix */
805 if ((aptr
= strrchr(tmp
, '.')) != NULL
) {
810 } else if (*cmd
== 'p') /* print only */
812 else if (*cmd
== 'g')
814 else if (*cmd
== 's' || *cmd
== '&') {
815 char *what
, *with
, delim
;
816 size_t len
, from_len
;
819 if (*cmd
== '&' && (from
== NULL
|| to
== NULL
))
821 else if (*cmd
== 's') {
822 delim
= *(++cmd
), cmd
++;
824 what
= el_realloc(from
, size
* sizeof(*what
));
831 for (; *cmd
&& *cmd
!= delim
; cmd
++) {
832 if (*cmd
== '\\' && cmd
[1] == delim
)
836 nwhat
= el_realloc(what
,
853 from
= strdup(search
);
864 cmd
++; /* shift after delim */
869 with
= el_realloc(to
, size
* sizeof(*with
));
876 from_len
= strlen(from
);
877 for (; *cmd
&& *cmd
!= delim
; cmd
++) {
878 if (len
+ from_len
+ 1 >= size
) {
880 size
+= from_len
+ 1;
881 nwith
= el_realloc(with
,
882 size
* sizeof(*nwith
));
892 (void)strcpy(&with
[len
], from
);
897 && (*(cmd
+ 1) == delim
898 || *(cmd
+ 1) == '&'))
906 aptr
= _rl_compat_sub(tmp
, from
, to
, g_on
);
920 * csh-style history expansion
923 history_expand(char *str
, char **output
)
929 if (h
== NULL
|| e
== NULL
)
932 if (history_expansion_char
== 0) {
933 *output
= strdup(str
);
938 if (str
[0] == history_subst_char
) {
939 /* ^foo^foo2^ is equivalent to !!:s^foo^foo2^ */
940 *output
= el_malloc((strlen(str
) + 4 + 1) * sizeof(**output
));
943 (*output
)[0] = (*output
)[1] = history_expansion_char
;
946 (void)strcpy((*output
) + 4, str
);
949 *output
= strdup(str
);
954 #define ADD_STRING(what, len, fr) \
956 if (idx + len + 1 > size) { \
957 char *nresult = el_realloc(result, \
958 (size += len + 1) * sizeof(*nresult)); \
959 if (nresult == NULL) { \
961 if (/*CONSTCOND*/fr) \
967 (void)strncpy(&result[idx], what, len); \
969 result[idx] = '\0'; \
975 for (i
= 0; str
[i
];) {
976 int qchar
, loop_again
;
977 size_t len
, start
, j
;
983 for (; str
[j
]; j
++) {
984 if (str
[j
] == '\\' &&
985 str
[j
+ 1] == history_expansion_char
) {
986 (void)strcpy(&str
[j
], &str
[j
+ 1]);
990 if (isspace((unsigned char) str
[j
])
994 if (str
[j
] == history_expansion_char
995 && !strchr(history_no_expand_chars
, str
[j
+ 1])
996 && (!history_inhibit_expansion_function
||
997 (*history_inhibit_expansion_function
)(str
,
1002 if (str
[j
] && loop_again
) {
1004 qchar
= (j
> 0 && str
[j
- 1] == '"' )? '"':0;
1006 if (str
[j
] == history_expansion_char
)
1012 ADD_STRING(&str
[start
], len
, 0);
1014 if (str
[i
] == '\0' || str
[i
] != history_expansion_char
) {
1016 ADD_STRING(&str
[i
], len
, 0);
1023 ret
= _history_expand_command (str
, i
, (j
- i
), &tmp
);
1024 if (ret
> 0 && tmp
) {
1026 ADD_STRING(tmp
, len
, 1);
1035 /* ret is 2 for "print only" option */
1037 add_history(result
);
1039 /* gdb 4.11 has been shipped with readline, where */
1040 /* history_expand() returned -1 when the line */
1041 /* should not be executed; in readline 2.1+ */
1042 /* it should return 2 in such a case */
1053 * Return a string consisting of arguments of "str" from "start" to "end".
1056 history_arg_extract(int start
, int end
, const char *str
)
1059 char **arr
, *result
= NULL
;
1061 arr
= history_tokenize(str
);
1064 if (arr
&& *arr
== NULL
)
1067 for (max
= 0; arr
[max
]; max
++)
1076 end
= (int)max
+ end
+ 1;
1080 if (start
< 0 || end
< 0 || (size_t)start
> max
||
1081 (size_t)end
> max
|| start
> end
)
1084 for (i
= (size_t)start
, len
= 0; i
<= (size_t)end
; i
++)
1085 len
+= strlen(arr
[i
]) + 1;
1087 result
= el_malloc(len
* sizeof(*result
));
1091 for (i
= (size_t)start
, len
= 0; i
<= (size_t)end
; i
++) {
1092 (void)strcpy(result
+ len
, arr
[i
]);
1093 len
+= strlen(arr
[i
]);
1094 if (i
< (size_t)end
)
1095 result
[len
++] = ' ';
1100 for (i
= 0; arr
[i
]; i
++)
1108 * Parse the string into individual tokens,
1109 * similar to how shell would do it.
1112 history_tokenize(const char *str
)
1114 int size
= 1, idx
= 0, i
, start
;
1116 char **result
= NULL
, *temp
, delim
= '\0';
1118 for (i
= 0; str
[i
];) {
1119 while (isspace((unsigned char) str
[i
]))
1123 if (str
[i
] == '\\') {
1124 if (str
[i
+1] != '\0')
1126 } else if (str
[i
] == delim
)
1129 (isspace((unsigned char) str
[i
]) ||
1130 strchr("()<>;&|$", str
[i
])))
1132 else if (!delim
&& strchr("'`\"", str
[i
]))
1138 if (idx
+ 2 >= size
) {
1141 nresult
= el_realloc(result
, (size_t)size
* sizeof(*nresult
));
1142 if (nresult
== NULL
) {
1148 len
= (size_t)i
- (size_t)start
;
1149 temp
= el_malloc((size_t)(len
+ 1) * sizeof(*temp
));
1151 for (i
= 0; i
< idx
; i
++)
1156 (void)strncpy(temp
, &str
[start
], len
);
1158 result
[idx
++] = temp
;
1168 * limit size of history record to ``max'' events
1171 stifle_history(int max
)
1175 if (h
== NULL
|| e
== NULL
)
1178 if (history(h
, &ev
, H_SETSIZE
, max
) == 0)
1179 max_input_history
= max
;
1184 * "unlimit" size of history - set the limit to maximum allowed int value
1187 unstifle_history(void)
1192 history(h
, &ev
, H_SETSIZE
, INT_MAX
);
1193 omax
= max_input_history
;
1194 max_input_history
= INT_MAX
;
1195 return omax
; /* some value _must_ be returned */
1200 history_is_stifled(void)
1203 /* cannot return true answer */
1204 return max_input_history
!= INT_MAX
;
1207 static const char _history_tmp_template
[] = "/tmp/.historyXXXXXX";
1210 history_truncate_file (const char *filename
, int nlines
)
1214 char template[sizeof(_history_tmp_template
)];
1222 if (filename
== NULL
&& (filename
= _default_history_file()) == NULL
)
1224 if ((fp
= fopen(filename
, "r+")) == NULL
)
1226 strcpy(template, _history_tmp_template
);
1227 if ((fd
= mkstemp(template)) == -1) {
1232 if ((tp
= fdopen(fd
, "r+")) == NULL
) {
1239 if (fread(buf
, sizeof(buf
), (size_t)1, fp
) != 1) {
1244 if (fseeko(fp
, (off_t
)sizeof(buf
) * count
, SEEK_SET
) ==
1249 left
= (ssize_t
)fread(buf
, (size_t)1, sizeof(buf
), fp
);
1257 } else if (fwrite(buf
, (size_t)left
, (size_t)1, tp
)
1265 if (fwrite(buf
, sizeof(buf
), (size_t)1, tp
) != 1) {
1273 cp
= buf
+ left
- 1;
1277 while (--cp
>= buf
) {
1279 if (--nlines
== 0) {
1280 if (++cp
>= buf
+ sizeof(buf
)) {
1288 if (nlines
<= 0 || count
== 0)
1291 if (fseeko(tp
, (off_t
)sizeof(buf
) * count
, SEEK_SET
) < 0) {
1295 if (fread(buf
, sizeof(buf
), (size_t)1, tp
) != 1) {
1303 cp
= buf
+ sizeof(buf
);
1306 if (ret
|| nlines
> 0)
1309 if (fseeko(fp
, (off_t
)0, SEEK_SET
) == (off_t
)-1) {
1314 if (fseeko(tp
, (off_t
)sizeof(buf
) * count
+ (cp
- buf
), SEEK_SET
) ==
1321 if ((left
= (ssize_t
)fread(buf
, (size_t)1, sizeof(buf
), tp
)) == 0) {
1326 if (fwrite(buf
, (size_t)left
, (size_t)1, fp
) != 1) {
1332 if((off
= ftello(fp
)) > 0)
1333 (void)ftruncate(fileno(fp
), off
);
1346 * read history from a file given
1349 read_history(const char *filename
)
1353 if (h
== NULL
|| e
== NULL
)
1355 if (filename
== NULL
&& (filename
= _default_history_file()) == NULL
)
1357 return history(h
, &ev
, H_LOAD
, filename
) == -1 ?
1358 (errno
? errno
: EINVAL
) : 0;
1363 * write history to a file given
1366 write_history(const char *filename
)
1370 if (h
== NULL
|| e
== NULL
)
1372 if (filename
== NULL
&& (filename
= _default_history_file()) == NULL
)
1374 return history(h
, &ev
, H_SAVE
, filename
) == -1 ?
1375 (errno
? errno
: EINVAL
) : 0;
1380 * returns history ``num''th event
1382 * returned pointer points to static variable
1385 history_get(int num
)
1387 static HIST_ENTRY she
;
1391 if (h
== NULL
|| e
== NULL
)
1394 /* save current position */
1395 if (history(h
, &ev
, H_CURR
) != 0)
1399 /* start from the oldest */
1400 if (history(h
, &ev
, H_LAST
) != 0)
1401 return NULL
; /* error */
1403 /* look forwards for event matching specified offset */
1404 if (history(h
, &ev
, H_NEXT_EVDATA
, num
, &she
.data
))
1409 /* restore pointer to where it was */
1410 (void)history(h
, &ev
, H_SET
, curr_num
);
1417 * add the line to history table
1420 add_history(const char *line
)
1427 if (h
== NULL
|| e
== NULL
)
1430 (void)history(h
, &ev
, H_ENTER
, line
);
1431 if (history(h
, &ev
, H_GETSIZE
) == 0)
1432 history_length
= ev
.num
;
1434 return !(history_length
> 0); /* return 0 if all is okay */
1439 * remove the specified entry from the history list and return it.
1442 remove_history(int num
)
1447 if (h
== NULL
|| e
== NULL
)
1450 if ((he
= el_malloc(sizeof(*he
))) == NULL
)
1453 if (history(h
, &ev
, H_DELDATA
, num
, &he
->data
) != 0) {
1459 if (history(h
, &ev
, H_GETSIZE
) == 0)
1460 history_length
= ev
.num
;
1467 * replace the line and data of the num-th entry
1470 replace_history_entry(int num
, const char *line
, histdata_t data
)
1476 if (h
== NULL
|| e
== NULL
)
1479 /* save current position */
1480 if (history(h
, &ev
, H_CURR
) != 0)
1484 /* start from the oldest */
1485 if (history(h
, &ev
, H_LAST
) != 0)
1486 return NULL
; /* error */
1488 if ((he
= el_malloc(sizeof(*he
))) == NULL
)
1491 /* look forwards for event matching specified offset */
1492 if (history(h
, &ev
, H_NEXT_EVDATA
, num
, &he
->data
))
1495 he
->line
= strdup(ev
.str
);
1496 if (he
->line
== NULL
)
1499 if (history(h
, &ev
, H_REPLACE
, line
, data
))
1502 /* restore pointer to where it was */
1503 if (history(h
, &ev
, H_SET
, curr_num
))
1513 * clear the history list - delete all entries
1520 if (h
== NULL
|| e
== NULL
)
1523 (void)history(h
, &ev
, H_CLEAR
);
1529 * returns offset of the current history event
1537 if (history(h
, &ev
, H_CURR
) != 0)
1541 (void)history(h
, &ev
, H_FIRST
);
1543 while (ev
.num
!= curr_num
&& history(h
, &ev
, H_NEXT
) == 0)
1551 * returns current history event or NULL if there is no such event
1554 current_history(void)
1557 return _move_history(H_CURR
);
1562 * returns total number of bytes history events' data are using
1565 history_total_bytes(void)
1571 if (history(h
, &ev
, H_CURR
) != 0)
1575 (void)history(h
, &ev
, H_FIRST
);
1578 size
+= strlen(ev
.str
) * sizeof(*ev
.str
);
1579 while (history(h
, &ev
, H_NEXT
) == 0);
1581 /* get to the same position as before */
1582 history(h
, &ev
, H_PREV_EVENT
, curr_num
);
1589 * sets the position in the history list to ``pos''
1592 history_set_pos(int pos
)
1597 if (pos
>= history_length
|| pos
< 0)
1600 (void)history(h
, &ev
, H_CURR
);
1604 * use H_DELDATA to set to nth history (without delete) by passing
1607 if (history(h
, &ev
, H_DELDATA
, pos
, (void **)-1)) {
1608 (void)history(h
, &ev
, H_SET
, curr_num
);
1616 * returns previous event in history and shifts pointer accordingly
1619 previous_history(void)
1622 return _move_history(H_PREV
);
1627 * returns next event in history and shifts pointer accordingly
1633 return _move_history(H_NEXT
);
1638 * searches for first history event containing the str
1641 history_search(const char *str
, int direction
)
1647 if (history(h
, &ev
, H_CURR
) != 0)
1652 if ((strp
= strstr(ev
.str
, str
)) != NULL
)
1653 return (int)(strp
- ev
.str
);
1654 if (history(h
, &ev
, direction
< 0 ? H_NEXT
:H_PREV
) != 0)
1657 (void)history(h
, &ev
, H_SET
, curr_num
);
1663 * searches for first history event beginning with str
1666 history_search_prefix(const char *str
, int direction
)
1670 return (history(h
, &ev
, direction
< 0 ?
1671 H_PREV_STR
: H_NEXT_STR
, str
));
1676 * search for event in history containing str, starting at offset
1677 * abs(pos); continue backward, if pos<0, forward otherwise
1681 history_search_pos(const char *str
,
1682 int direction
__attribute__((__unused__
)), int pos
)
1687 off
= (pos
> 0) ? pos
: -pos
;
1688 pos
= (pos
> 0) ? 1 : -1;
1690 if (history(h
, &ev
, H_CURR
) != 0)
1694 if (history_set_pos(off
) != 0 || history(h
, &ev
, H_CURR
) != 0)
1698 if (strstr(ev
.str
, str
))
1700 if (history(h
, &ev
, (pos
< 0) ? H_PREV
: H_NEXT
) != 0)
1704 /* set "current" pointer back to previous state */
1705 (void)history(h
, &ev
,
1706 pos
< 0 ? H_NEXT_EVENT
: H_PREV_EVENT
, curr_num
);
1712 /********************************/
1713 /* completion functions */
1716 tilde_expand(char *name
)
1718 return fn_tilde_expand(name
);
1722 filename_completion_function(const char *name
, int state
)
1724 return fn_filename_completion_function(name
, state
);
1728 * a completion generator for usernames; returns _first_ username
1729 * which starts with supplied text
1730 * text contains a partial username preceded by random character
1731 * (usually '~'); state resets search from start (??? should we do that anyway)
1732 * it's the caller's responsibility to free the returned value
1735 username_completion_function(const char *text
, int state
)
1737 struct passwd
*pass
= NULL
;
1739 if (text
[0] == '\0')
1749 (pass
= getpwent()) != NULL
1750 && text
[0] == pass
->pw_name
[0]
1751 && strcmp(text
, pass
->pw_name
) == 0)
1758 return strdup(pass
->pw_name
);
1763 * el-compatible wrapper to send TSTP on ^Z
1766 static unsigned char
1767 _el_rl_tstp(EditLine
*el
__attribute__((__unused__
)), int ch
__attribute__((__unused__
)))
1769 (void)kill(0, SIGTSTP
);
1774 * Display list of strings in columnar format on readline's output stream.
1775 * 'matches' is list of strings, 'len' is number of strings in 'matches',
1776 * 'max' is maximum length of string in 'matches'.
1779 rl_display_match_list(char **matches
, int len
, int max
)
1782 fn_display_match_list(e
, matches
, (size_t)len
, (size_t)max
);
1787 _rl_completion_append_character_function(const char *dummy
1788 __attribute__((__unused__
)))
1791 buf
[0] = (char)rl_completion_append_character
;
1798 * complete word at current point
1802 rl_complete(int ignore
__attribute__((__unused__
)), int invoking_key
)
1805 static ct_buffer_t wbreak_conv
, sprefix_conv
;
1809 if (h
== NULL
|| e
== NULL
)
1812 if (rl_inhibit_completion
) {
1814 arr
[0] = (char)invoking_key
;
1816 el_insertstr(e
, arr
);
1820 if (rl_completion_word_break_hook
!= NULL
)
1821 breakchars
= (*rl_completion_word_break_hook
)();
1823 breakchars
= rl_basic_word_break_characters
;
1825 /* Just look at how many global variables modify this operation! */
1826 return fn_complete(e
,
1827 (CPFunction
*)rl_completion_entry_function
,
1828 rl_attempted_completion_function
,
1829 ct_decode_string(rl_basic_word_break_characters
, &wbreak_conv
),
1830 ct_decode_string(breakchars
, &sprefix_conv
),
1831 _rl_completion_append_character_function
,
1832 (size_t)rl_completion_query_items
,
1833 &rl_completion_type
, &rl_attempted_completion_over
,
1834 &rl_point
, &rl_end
);
1841 static unsigned char
1842 _el_rl_complete(EditLine
*el
__attribute__((__unused__
)), int ch
)
1844 return (unsigned char)rl_complete(0, ch
);
1848 * misc other functions
1852 * bind key c to readline-type function func
1855 rl_bind_key(int c
, rl_command_func_t
*func
)
1859 if (h
== NULL
|| e
== NULL
)
1862 if (func
== rl_insert
) {
1863 /* XXX notice there is no range checking of ``c'' */
1864 e
->el_map
.key
[c
] = ED_INSERT
;
1872 * read one key from input - handles chars pushed back
1873 * to input stream also
1878 char fooarr
[2 * sizeof(int)];
1880 if (e
== NULL
|| h
== NULL
)
1883 return el_getc(e
, fooarr
);
1888 * reset the terminal
1892 rl_reset_terminal(const char *p
__attribute__((__unused__
)))
1895 if (h
== NULL
|| e
== NULL
)
1902 * insert character ``c'' back into input stream, ``count'' times
1905 rl_insert(int count
, int c
)
1909 if (h
== NULL
|| e
== NULL
)
1912 /* XXX - int -> char conversion can lose on multichars */
1916 for (; count
> 0; count
--)
1923 rl_insert_text(const char *text
)
1925 if (!text
|| *text
== 0)
1928 if (h
== NULL
|| e
== NULL
)
1931 if (el_insertstr(e
, text
) < 0)
1933 return (int)strlen(text
);
1938 rl_newline(int count
__attribute__((__unused__
)),
1939 int c
__attribute__((__unused__
)))
1942 * Readline-4.0 appears to ignore the args.
1944 return rl_insert(1, '\n');
1948 static unsigned char
1949 rl_bind_wrapper(EditLine
*el
__attribute__((__unused__
)), unsigned char c
)
1958 /* If rl_done was set by the above call, deal with it here */
1966 rl_add_defun(const char *name
, Function
*fun
, int c
)
1969 if ((size_t)c
>= sizeof(map
) / sizeof(map
[0]) || c
< 0)
1971 map
[(unsigned char)c
] = fun
;
1972 el_set(e
, EL_ADDFN
, name
, name
, rl_bind_wrapper
);
1973 vis(dest
, c
, VIS_WHITE
|VIS_NOSLASH
, 0);
1974 el_set(e
, EL_BIND
, dest
, name
, NULL
);
1979 rl_callback_read_char(void)
1981 int count
= 0, done
= 0;
1982 const char *buf
= el_gets(e
, &count
);
1985 if (buf
== NULL
|| count
-- <= 0)
1987 if (count
== 0 && buf
[0] == e
->el_tty
.t_c
[TS_IO
][C_EOF
])
1989 if (buf
[count
] == '\n' || buf
[count
] == '\r')
1992 if (done
&& rl_linefunc
!= NULL
) {
1993 el_set(e
, EL_UNBUFFERED
, 0);
1995 if ((wbuf
= strdup(buf
)) != NULL
)
1999 (*(void (*)(const char *))rl_linefunc
)(wbuf
);
2000 el_set(e
, EL_UNBUFFERED
, 1);
2005 rl_callback_handler_install(const char *prompt
, VCPFunction
*linefunc
)
2010 (void)rl_set_prompt(prompt
);
2011 rl_linefunc
= linefunc
;
2012 el_set(e
, EL_UNBUFFERED
, 1);
2016 rl_callback_handler_remove(void)
2018 el_set(e
, EL_UNBUFFERED
, 0);
2026 a
[0] = (char)e
->el_tty
.t_c
[TS_IO
][C_REPRINT
];
2032 rl_get_previous_history(int count
, int key
)
2044 rl_prep_terminal(int meta_flag
__attribute__((__unused__
)))
2046 el_set(e
, EL_PREP_TERM
, 1);
2050 rl_deprep_terminal(void)
2052 el_set(e
, EL_PREP_TERM
, 0);
2056 rl_read_init_file(const char *s
)
2058 return el_source(e
, s
);
2062 rl_parse_and_bind(const char *line
)
2068 tok
= tok_init(NULL
);
2069 tok_str(tok
, line
, &argc
, &argv
);
2070 argc
= el_parse(e
, argc
, argv
);
2072 return argc
? 1 : 0;
2076 rl_variable_bind(const char *var
, const char *value
)
2079 * The proper return value is undocument, but this is what the
2080 * readline source seems to do.
2082 return el_set(e
, EL_BIND
, "", var
, value
, NULL
) == -1 ? 1 : 0;
2086 rl_stuff_char(int c
)
2092 el_insertstr(e
, buf
);
2096 _rl_event_read_char(EditLine
*el
, char *cp
)
2099 ssize_t num_read
= 0;
2102 while (rl_event_hook
) {
2106 #if defined(FIONREAD)
2107 if (ioctl(el
->el_infd
, FIONREAD
, &n
) < 0)
2110 num_read
= read(el
->el_infd
, cp
, (size_t)1);
2113 #elif defined(F_SETFL) && defined(O_NDELAY)
2114 if ((n
= fcntl(el
->el_infd
, F_GETFL
, 0)) < 0)
2116 if (fcntl(el
->el_infd
, F_SETFL
, n
|O_NDELAY
) < 0)
2118 num_read
= read(el
->el_infd
, cp
, 1);
2119 if (fcntl(el
->el_infd
, F_SETFL
, n
))
2122 /* not non-blocking, but what you gonna do? */
2123 num_read
= read(el
->el_infd
, cp
, 1);
2127 if (num_read
< 0 && errno
== EAGAIN
)
2134 el_set(el
, EL_GETCFN
, EL_BUILTIN_GETCFN
);
2135 return (int)num_read
;
2139 _rl_update_pos(void)
2141 const LineInfo
*li
= el_line(e
);
2143 rl_point
= (int)(li
->cursor
- li
->buffer
);
2144 rl_end
= (int)(li
->lastchar
- li
->buffer
);
2148 rl_get_screen_size(int *rows
, int *cols
)
2151 el_get(e
, EL_GETTC
, "li", rows
, (void *)0);
2153 el_get(e
, EL_GETTC
, "co", cols
, (void *)0);
2157 rl_set_screen_size(int rows
, int cols
)
2160 (void)snprintf(buf
, sizeof(buf
), "%d", rows
);
2161 el_set(e
, EL_SETTC
, "li", buf
, NULL
);
2162 (void)snprintf(buf
, sizeof(buf
), "%d", cols
);
2163 el_set(e
, EL_SETTC
, "co", buf
, NULL
);
2167 rl_completion_matches(const char *str
, rl_compentry_func_t
*fun
)
2169 size_t len
, max
, i
, j
, min
;
2170 char **list
, *match
, *a
, *b
;
2174 if ((list
= el_malloc(max
* sizeof(*list
))) == NULL
)
2177 while ((match
= (*fun
)(str
, (int)(len
- 1))) != NULL
) {
2178 list
[len
++] = match
;
2182 if ((nl
= el_realloc(list
, max
* sizeof(*nl
))) == NULL
)
2191 if ((list
[0] = strdup(list
[1])) == NULL
)
2195 qsort(&list
[1], len
- 1, sizeof(*list
),
2196 (int (*)(const void *, const void *)) strcmp
);
2198 for (i
= 1, a
= list
[i
]; i
< len
- 1; i
++, a
= b
) {
2200 for (j
= 0; a
[j
] && a
[j
] == b
[j
]; j
++)
2205 if (min
== 0 && *str
) {
2206 if ((list
[0] = strdup(str
)) == NULL
)
2209 if ((list
[0] = el_malloc((min
+ 1) * sizeof(*list
[0]))) == NULL
)
2211 (void)memcpy(list
[0], list
[1], min
);
2212 list
[0][min
] = '\0';
2222 rl_filename_completion_function (const char *text
, int state
)
2224 return fn_filename_completion_function(text
, state
);
2228 rl_forced_update_display(void)
2230 el_set(e
, EL_REFRESH
);
2234 _rl_abort_internal(void)
2242 _rl_qsort_string_compare(char **s1
, char **s2
)
2244 return strcoll(*s1
, *s2
);
2248 history_get_history_state(void)
2252 if ((hs
= el_malloc(sizeof(*hs
))) == NULL
)
2254 hs
->length
= history_length
;
2260 rl_kill_text(int from
__attribute__((__unused__
)),
2261 int to
__attribute__((__unused__
)))
2267 rl_make_bare_keymap(void)
2280 rl_set_keymap(Keymap k
__attribute__((__unused__
)))
2286 rl_generic_bind(int type
__attribute__((__unused__
)),
2287 const char * keyseq
__attribute__((__unused__
)),
2288 const char * data
__attribute__((__unused__
)),
2289 Keymap k
__attribute__((__unused__
)))
2296 rl_bind_key_in_map(int key
__attribute__((__unused__
)),
2297 rl_command_func_t
*fun
__attribute__((__unused__
)),
2298 Keymap k
__attribute__((__unused__
)))
2303 /* unsupported, but needed by python */
2305 rl_cleanup_after_signal(void)
2310 rl_on_new_line(void)
2316 rl_free_line_state(void)