1 /* $NetBSD: readline.c,v 1.139 2016/10/28 18:32:26 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.139 2016/10/28 18:32:26 christos Exp $");
35 #endif /* not lint && not SCCSID */
37 #include <sys/types.h>
53 #include "readline/readline.h"
56 #include "filecomplete.h"
58 void rl_prep_terminal(int);
59 void rl_deprep_terminal(void);
61 /* for rl_complete() */
64 /* see comment at the #ifdef for sense of this */
65 /* #define GDB_411_HACK */
67 /* readline compatibility stuff - look at readline sources/documentation */
68 /* to see what these variables mean */
69 const char *rl_library_version
= "EditLine wrapper";
70 int rl_readline_version
= RL_READLINE_VERSION
;
71 static char empty
[] = { '\0' };
72 static char expand_chars
[] = { ' ', '\t', '\n', '=', '(', '\0' };
73 static char break_chars
[] = { ' ', '\t', '\n', '"', '\\', '\'', '`', '@', '$',
74 '>', '<', '=', ';', '|', '&', '{', '(', '\0' };
75 char *rl_readline_name
= empty
;
76 FILE *rl_instream
= NULL
;
77 FILE *rl_outstream
= NULL
;
80 char *rl_line_buffer
= NULL
;
81 rl_vcpfunc_t
*rl_linefunc
= NULL
;
83 VFunction
*rl_event_hook
= NULL
;
84 KEYMAP_ENTRY_ARRAY emacs_standard_keymap
,
88 * The following is not implemented; we always catch signals in the
89 * libedit fashion: set handlers on entry to el_gets() and clear them
90 * on the way out. This simplistic approach works for most cases; if
91 * it does not work for your application, please let us know.
93 int rl_catch_signals
= 1;
94 int rl_catch_sigwinch
= 1;
96 int history_base
= 1; /* probably never subject to change */
97 int history_length
= 0;
98 int history_offset
= 0;
99 int max_input_history
= 0;
100 char history_expansion_char
= '!';
101 char history_subst_char
= '^';
102 char *history_no_expand_chars
= expand_chars
;
103 Function
*history_inhibit_expansion_function
= NULL
;
104 char *history_arg_extract(int start
, int end
, const char *str
);
106 int rl_inhibit_completion
= 0;
107 int rl_attempted_completion_over
= 0;
108 char *rl_basic_word_break_characters
= break_chars
;
109 char *rl_completer_word_break_characters
= NULL
;
110 char *rl_completer_quote_characters
= NULL
;
111 rl_compentry_func_t
*rl_completion_entry_function
= NULL
;
112 char *(*rl_completion_word_break_hook
)(void) = NULL
;
113 rl_completion_func_t
*rl_attempted_completion_function
= NULL
;
114 Function
*rl_pre_input_hook
= NULL
;
115 Function
*rl_startup1_hook
= NULL
;
116 int (*rl_getc_function
)(FILE *) = NULL
;
117 char *rl_terminal_name
= NULL
;
118 int rl_already_prompted
= 0;
119 int rl_filename_completion_desired
= 0;
120 int rl_ignore_completion_duplicates
= 0;
121 int readline_echoing_p
= 1;
122 int _rl_print_completions_horizontally
= 0;
123 VFunction
*rl_redisplay_function
= NULL
;
124 Function
*rl_startup_hook
= NULL
;
125 VFunction
*rl_completion_display_matches_hook
= NULL
;
126 VFunction
*rl_prep_term_function
= (VFunction
*)rl_prep_terminal
;
127 VFunction
*rl_deprep_term_function
= (VFunction
*)rl_deprep_terminal
;
128 KEYMAP_ENTRY_ARRAY emacs_meta_keymap
;
131 * The current prompt string.
133 char *rl_prompt
= NULL
;
135 * This is set to character indicating type of completion being done by
136 * rl_complete_internal(); this is available for application completion
139 int rl_completion_type
= 0;
142 * If more than this number of items results from query for possible
143 * completions, we ask user if they are sure to really display the list.
145 int rl_completion_query_items
= 100;
148 * List of characters which are word break characters, but should be left
149 * in the parsed text when it is passed to the completion function.
150 * Shell uses this to help determine what kind of completing to do.
152 char *rl_special_prefixes
= NULL
;
155 * This is the character appended to the completed words if at the end of
156 * the line. Default is ' ' (a space).
158 int rl_completion_append_character
= ' ';
160 /* stuff below is used internally by libedit for readline emulation */
162 static History
*h
= NULL
;
163 static EditLine
*e
= NULL
;
164 static rl_command_func_t
*map
[256];
165 static jmp_buf topbuf
;
167 /* internal functions */
168 static unsigned char _el_rl_complete(EditLine
*, int);
169 static unsigned char _el_rl_tstp(EditLine
*, int);
170 static char *_get_prompt(EditLine
*);
171 static int _getc_function(EditLine
*, wchar_t *);
172 static int _history_expand_command(const char *, size_t, size_t,
174 static char *_rl_compat_sub(const char *, const char *,
176 static int _rl_event_read_char(EditLine
*, wchar_t *);
177 static void _rl_update_pos(void);
179 static HIST_ENTRY rl_he
;
183 _get_prompt(EditLine
*el
__attribute__((__unused__
)))
185 rl_already_prompted
= 1;
191 * read one key from user defined input function
195 _getc_function(EditLine
*el
__attribute__((__unused__
)), wchar_t *c
)
199 i
= (*rl_getc_function
)(rl_instream
);
207 _resize_fun(EditLine
*el
, void *a
)
213 /* a cheesy way to get rid of const cast. */
214 *ap
= memchr(li
->buffer
, *li
->buffer
, (size_t)1);
218 _default_history_file(void)
227 if ((p
= getpwuid(getuid())) == NULL
)
230 len
= strlen(p
->pw_dir
) + sizeof("/.history");
231 if ((path
= malloc(len
)) == NULL
)
234 (void)snprintf(path
, len
, "%s/.history", p
->pw_dir
);
239 * READLINE compatibility stuff
246 rl_set_prompt(const char *prompt
)
252 if (rl_prompt
!= NULL
&& strcmp(rl_prompt
, prompt
) == 0)
256 rl_prompt
= strdup(prompt
);
257 if (rl_prompt
== NULL
)
260 while ((p
= strchr(rl_prompt
, RL_PROMPT_END_IGNORE
)) != NULL
)
261 *p
= RL_PROMPT_START_IGNORE
;
267 * initialize rl compat stuff
284 rl_outstream
= stdout
;
287 * See if we don't really want to run the editor
289 if (tcgetattr(fileno(rl_instream
), &t
) != -1 && (t
.c_lflag
& ECHO
) == 0)
292 e
= el_init(rl_readline_name
, rl_instream
, rl_outstream
, stderr
);
295 el_set(e
, EL_EDITMODE
, 0);
301 history(h
, &ev
, H_SETSIZE
, INT_MAX
); /* unlimited */
303 max_input_history
= INT_MAX
;
304 el_set(e
, EL_HIST
, history
, h
);
306 /* Setup resize function */
307 el_set(e
, EL_RESIZE
, _resize_fun
, &rl_line_buffer
);
309 /* setup getc function if valid */
310 if (rl_getc_function
)
311 el_set(e
, EL_GETCFN
, _getc_function
);
313 /* for proper prompt printing in readline() */
314 if (rl_set_prompt("") == -1) {
319 el_set(e
, EL_PROMPT
, _get_prompt
, RL_PROMPT_START_IGNORE
);
320 el_set(e
, EL_SIGNAL
, rl_catch_signals
);
322 /* set default mode to "emacs"-style and read setting afterwards */
323 /* so this can be overridden */
324 el_set(e
, EL_EDITOR
, "emacs");
325 if (rl_terminal_name
!= NULL
)
326 el_set(e
, EL_TERMINAL
, rl_terminal_name
);
328 el_get(e
, EL_TERMINAL
, &rl_terminal_name
);
331 * Word completion - this has to go AFTER rebinding keys
334 el_set(e
, EL_ADDFN
, "rl_complete",
335 "ReadLine compatible completion function",
337 el_set(e
, EL_BIND
, "^I", "rl_complete", NULL
);
340 * Send TSTP when ^Z is pressed.
342 el_set(e
, EL_ADDFN
, "rl_tstp",
343 "ReadLine compatible suspend function",
345 el_set(e
, EL_BIND
, "^Z", "rl_tstp", NULL
);
348 * Set some readline compatible key-bindings.
350 el_set(e
, EL_BIND
, "^R", "em-inc-search-prev", NULL
);
353 * Allow the use of Home/End keys.
355 el_set(e
, EL_BIND
, "\\e[1~", "ed-move-to-beg", NULL
);
356 el_set(e
, EL_BIND
, "\\e[4~", "ed-move-to-end", NULL
);
357 el_set(e
, EL_BIND
, "\\e[7~", "ed-move-to-beg", NULL
);
358 el_set(e
, EL_BIND
, "\\e[8~", "ed-move-to-end", NULL
);
359 el_set(e
, EL_BIND
, "\\e[H", "ed-move-to-beg", NULL
);
360 el_set(e
, EL_BIND
, "\\e[F", "ed-move-to-end", NULL
);
363 * Allow the use of the Delete/Insert keys.
365 el_set(e
, EL_BIND
, "\\e[3~", "ed-delete-next-char", NULL
);
366 el_set(e
, EL_BIND
, "\\e[2~", "ed-quoted-insert", NULL
);
369 * Ctrl-left-arrow and Ctrl-right-arrow for word moving.
371 el_set(e
, EL_BIND
, "\\e[1;5C", "em-next-word", NULL
);
372 el_set(e
, EL_BIND
, "\\e[1;5D", "ed-prev-word", NULL
);
373 el_set(e
, EL_BIND
, "\\e[5C", "em-next-word", NULL
);
374 el_set(e
, EL_BIND
, "\\e[5D", "ed-prev-word", NULL
);
375 el_set(e
, EL_BIND
, "\\e\\e[C", "em-next-word", NULL
);
376 el_set(e
, EL_BIND
, "\\e\\e[D", "ed-prev-word", NULL
);
378 /* read settings from configuration file */
382 * Unfortunately, some applications really do use rl_point
383 * and rl_line_buffer directly.
385 _resize_fun(e
, &rl_line_buffer
);
389 (*rl_startup_hook
)(NULL
, 0);
396 * read one line from input stream and return it, chomping
397 * trailing newline (if there is any)
400 readline(const char *p
)
403 const char * volatile prompt
= p
;
407 static int used_event_hook
;
409 if (e
== NULL
|| h
== NULL
)
414 (void)setjmp(topbuf
);
416 /* update prompt accordingly to what has been passed */
417 if (rl_set_prompt(prompt
) == -1)
420 if (rl_pre_input_hook
)
421 (*rl_pre_input_hook
)(NULL
, 0);
423 if (rl_event_hook
&& !(e
->el_flags
&NO_TTY
)) {
424 el_set(e
, EL_GETCFN
, _rl_event_read_char
);
428 if (!rl_event_hook
&& used_event_hook
) {
429 el_set(e
, EL_GETCFN
, EL_BUILTIN_GETCFN
);
433 rl_already_prompted
= 0;
435 /* get one line from input stream */
436 ret
= el_gets(e
, &count
);
438 if (ret
&& count
> 0) {
445 if (buf
[lastidx
] == '\n')
450 history(h
, &ev
, H_GETSIZE
);
451 history_length
= ev
.num
;
461 * is normally called before application starts to use
462 * history expansion functions
467 if (h
== NULL
|| e
== NULL
)
469 history_offset
= history_length
;
474 * substitute ``what'' with ``with'', returning resulting string; if
475 * globally == 1, substitutes all occurrences of what, otherwise only the
479 _rl_compat_sub(const char *str
, const char *what
, const char *with
,
484 size_t len
, with_len
, what_len
;
487 with_len
= strlen(with
);
488 what_len
= strlen(what
);
490 /* calculate length we need for result */
493 if (*s
== *what
&& !strncmp(s
, what
, what_len
)) {
494 len
+= with_len
- what_len
;
501 r
= result
= el_malloc((len
+ 1) * sizeof(*r
));
506 if (*s
== *what
&& !strncmp(s
, what
, what_len
)) {
507 (void)strncpy(r
, with
, with_len
);
521 static char *last_search_pat
; /* last !?pat[?] search pattern */
522 static char *last_search_match
; /* last !?pat[?] that matched */
525 get_history_event(const char *cmd
, int *cindex
, int qchar
)
527 int idx
, sign
, sub
, num
, begin
, ret
;
534 if (cmd
[idx
++] != history_expansion_char
)
537 /* find out which event to take */
538 if (cmd
[idx
] == history_expansion_char
|| cmd
[idx
] == '\0') {
539 if (history(h
, &ev
, H_FIRST
) != 0)
541 *cindex
= cmd
[idx
]? (idx
+ 1):idx
;
545 if (cmd
[idx
] == '-') {
550 if ('0' <= cmd
[idx
] && cmd
[idx
] <= '9') {
554 while (cmd
[idx
] && '0' <= cmd
[idx
] && cmd
[idx
] <= '9') {
555 num
= num
* 10 + cmd
[idx
] - '0';
559 num
= history_length
- num
+ 1;
561 if (!(he
= history_get(num
)))
568 if (cmd
[idx
] == '?') {
574 if (cmd
[idx
] == '\n')
576 if (sub
&& cmd
[idx
] == '?')
578 if (!sub
&& (cmd
[idx
] == ':' || cmd
[idx
] == ' '
579 || cmd
[idx
] == '\t' || cmd
[idx
] == qchar
))
583 len
= (size_t)idx
- (size_t)begin
;
584 if (sub
&& cmd
[idx
] == '?')
586 if (sub
&& len
== 0 && last_search_pat
&& *last_search_pat
)
587 pat
= last_search_pat
;
591 if ((pat
= el_malloc((len
+ 1) * sizeof(*pat
))) == NULL
)
593 (void)strncpy(pat
, cmd
+ begin
, len
);
597 if (history(h
, &ev
, H_CURR
) != 0) {
598 if (pat
!= last_search_pat
)
605 if (pat
!= last_search_pat
) {
607 el_free(last_search_pat
);
608 last_search_pat
= pat
;
610 ret
= history_search(pat
, -1);
612 ret
= history_search_prefix(pat
, -1);
615 /* restore to end of list on failed search */
616 history(h
, &ev
, H_FIRST
);
617 (void)fprintf(rl_outstream
, "%s: Event not found\n", pat
);
618 if (pat
!= last_search_pat
)
624 if (last_search_match
&& last_search_match
!= pat
)
625 el_free(last_search_match
);
626 last_search_match
= pat
;
629 if (pat
!= last_search_pat
)
632 if (history(h
, &ev
, H_CURR
) != 0)
637 /* roll back to original position */
638 (void)history(h
, &ev
, H_SET
, num
);
644 * the real function doing history expansion - takes as argument command
645 * to do and data upon which the command should be executed
646 * does expansion the way I've understood readline documentation
648 * returns 0 if data was not modified, 1 if it was and 2 if the string
649 * should be only printed and not executed; in case of error,
650 * returns -1 and *result points to NULL
651 * it's the caller's responsibility to free() the string returned in *result
654 _history_expand_command(const char *command
, size_t offs
, size_t cmdlen
,
657 char *tmp
, *search
= NULL
, *aptr
;
658 const char *ptr
, *cmd
;
659 static char *from
= NULL
, *to
= NULL
;
660 int start
, end
, idx
, has_mods
= 0;
661 int p_on
= 0, g_on
= 0;
667 /* First get event specifier */
670 if (strchr(":^*$", command
[offs
+ 1])) {
673 * "!:" is shorthand for "!!:".
674 * "!^", "!*" and "!$" are shorthand for
675 * "!!:^", "!!:*" and "!!:$" respectively.
677 str
[0] = str
[1] = '!';
679 ptr
= get_history_event(str
, &idx
, 0);
680 idx
= (command
[offs
+ 1] == ':')? 1:0;
683 if (command
[offs
+ 1] == '#') {
684 /* use command so far */
685 if ((aptr
= el_malloc((offs
+ 1) * sizeof(*aptr
)))
688 (void)strncpy(aptr
, command
, offs
);
694 qchar
= (offs
> 0 && command
[offs
- 1] == '"')? '"':0;
695 ptr
= get_history_event(command
+ offs
, &idx
, qchar
);
697 has_mods
= command
[offs
+ (size_t)idx
] == ':';
700 if (ptr
== NULL
&& aptr
== NULL
)
704 *result
= strdup(aptr
? aptr
: ptr
);
712 cmd
= command
+ offs
+ idx
+ 1;
714 /* Now parse any word designators */
716 if (*cmd
== '%') /* last word matched by ?pat? */
717 tmp
= strdup(last_search_match
? last_search_match
:"");
718 else if (strchr("^*$-0123456789", *cmd
)) {
721 start
= end
= 1, cmd
++;
722 else if (*cmd
== '$')
724 else if (*cmd
== '*')
726 else if (*cmd
== '-' || isdigit((unsigned char) *cmd
)) {
728 while (*cmd
&& '0' <= *cmd
&& *cmd
<= '9')
729 start
= start
* 10 + *cmd
++ - '0';
732 if (isdigit((unsigned char) cmd
[1])) {
735 while (*cmd
&& '0' <= *cmd
&& *cmd
<= '9')
736 end
= end
* 10 + *cmd
++ - '0';
737 } else if (cmd
[1] == '$') {
744 } else if (*cmd
== '*')
749 tmp
= history_arg_extract(start
, end
, aptr
? aptr
:ptr
);
751 (void)fprintf(rl_outstream
, "%s: Bad word specifier",
752 command
+ offs
+ idx
);
758 tmp
= strdup(aptr
? aptr
:ptr
);
763 if (*cmd
== '\0' || ((size_t)(cmd
- (command
+ offs
)) >= cmdlen
)) {
768 for (; *cmd
; cmd
++) {
771 else if (*cmd
== 'h') { /* remove trailing path */
772 if ((aptr
= strrchr(tmp
, '/')) != NULL
)
774 } else if (*cmd
== 't') { /* remove leading path */
775 if ((aptr
= strrchr(tmp
, '/')) != NULL
) {
776 aptr
= strdup(aptr
+ 1);
780 } else if (*cmd
== 'r') { /* remove trailing suffix */
781 if ((aptr
= strrchr(tmp
, '.')) != NULL
)
783 } else if (*cmd
== 'e') { /* remove all but suffix */
784 if ((aptr
= strrchr(tmp
, '.')) != NULL
) {
789 } else if (*cmd
== 'p') /* print only */
791 else if (*cmd
== 'g')
793 else if (*cmd
== 's' || *cmd
== '&') {
794 char *what
, *with
, delim
;
795 size_t len
, from_len
;
798 if (*cmd
== '&' && (from
== NULL
|| to
== NULL
))
800 else if (*cmd
== 's') {
801 delim
= *(++cmd
), cmd
++;
803 what
= el_realloc(from
, size
* sizeof(*what
));
810 for (; *cmd
&& *cmd
!= delim
; cmd
++) {
811 if (*cmd
== '\\' && cmd
[1] == delim
)
815 nwhat
= el_realloc(what
,
832 from
= strdup(search
);
843 cmd
++; /* shift after delim */
848 with
= el_realloc(to
, size
* sizeof(*with
));
855 from_len
= strlen(from
);
856 for (; *cmd
&& *cmd
!= delim
; cmd
++) {
857 if (len
+ from_len
+ 1 >= size
) {
859 size
+= from_len
+ 1;
860 nwith
= el_realloc(with
,
861 size
* sizeof(*nwith
));
871 (void)strcpy(&with
[len
], from
);
876 && (*(cmd
+ 1) == delim
877 || *(cmd
+ 1) == '&'))
885 aptr
= _rl_compat_sub(tmp
, from
, to
, g_on
);
899 * csh-style history expansion
902 history_expand(char *str
, char **output
)
908 if (h
== NULL
|| e
== NULL
)
911 if (history_expansion_char
== 0) {
912 *output
= strdup(str
);
917 if (str
[0] == history_subst_char
) {
918 /* ^foo^foo2^ is equivalent to !!:s^foo^foo2^ */
919 *output
= el_malloc((strlen(str
) + 4 + 1) * sizeof(**output
));
922 (*output
)[0] = (*output
)[1] = history_expansion_char
;
925 (void)strcpy((*output
) + 4, str
);
928 *output
= strdup(str
);
933 #define ADD_STRING(what, len, fr) \
935 if (idx + len + 1 > size) { \
936 char *nresult = el_realloc(result, \
937 (size += len + 1) * sizeof(*nresult)); \
938 if (nresult == NULL) { \
940 if (/*CONSTCOND*/fr) \
946 (void)strncpy(&result[idx], what, len); \
948 result[idx] = '\0'; \
954 for (i
= 0; str
[i
];) {
955 int qchar
, loop_again
;
956 size_t len
, start
, j
;
962 for (; str
[j
]; j
++) {
963 if (str
[j
] == '\\' &&
964 str
[j
+ 1] == history_expansion_char
) {
965 len
= strlen(&str
[j
+ 1]) + 1;
966 memmove(&str
[j
], &str
[j
+ 1], len
);
970 if (isspace((unsigned char) str
[j
])
974 if (str
[j
] == history_expansion_char
975 && !strchr(history_no_expand_chars
, str
[j
+ 1])
976 && (!history_inhibit_expansion_function
||
977 (*history_inhibit_expansion_function
)(str
,
982 if (str
[j
] && loop_again
) {
984 qchar
= (j
> 0 && str
[j
- 1] == '"' )? '"':0;
986 if (str
[j
] == history_expansion_char
)
992 ADD_STRING(&str
[start
], len
, 0);
994 if (str
[i
] == '\0' || str
[i
] != history_expansion_char
) {
996 ADD_STRING(&str
[i
], len
, 0);
1003 ret
= _history_expand_command (str
, i
, (j
- i
), &tmp
);
1004 if (ret
> 0 && tmp
) {
1006 ADD_STRING(tmp
, len
, 1);
1015 /* ret is 2 for "print only" option */
1017 add_history(result
);
1019 /* gdb 4.11 has been shipped with readline, where */
1020 /* history_expand() returned -1 when the line */
1021 /* should not be executed; in readline 2.1+ */
1022 /* it should return 2 in such a case */
1033 * Return a string consisting of arguments of "str" from "start" to "end".
1036 history_arg_extract(int start
, int end
, const char *str
)
1039 char **arr
, *result
= NULL
;
1041 arr
= history_tokenize(str
);
1044 if (arr
&& *arr
== NULL
)
1047 for (max
= 0; arr
[max
]; max
++)
1056 end
= (int)max
+ end
+ 1;
1060 if (start
< 0 || end
< 0 || (size_t)start
> max
||
1061 (size_t)end
> max
|| start
> end
)
1064 for (i
= (size_t)start
, len
= 0; i
<= (size_t)end
; i
++)
1065 len
+= strlen(arr
[i
]) + 1;
1067 result
= el_malloc(len
* sizeof(*result
));
1071 for (i
= (size_t)start
, len
= 0; i
<= (size_t)end
; i
++) {
1072 (void)strcpy(result
+ len
, arr
[i
]);
1073 len
+= strlen(arr
[i
]);
1074 if (i
< (size_t)end
)
1075 result
[len
++] = ' ';
1080 for (i
= 0; arr
[i
]; i
++)
1088 * Parse the string into individual tokens,
1089 * similar to how shell would do it.
1092 history_tokenize(const char *str
)
1094 int size
= 1, idx
= 0, i
, start
;
1096 char **result
= NULL
, *temp
, delim
= '\0';
1098 for (i
= 0; str
[i
];) {
1099 while (isspace((unsigned char) str
[i
]))
1103 if (str
[i
] == '\\') {
1104 if (str
[i
+1] != '\0')
1106 } else if (str
[i
] == delim
)
1109 (isspace((unsigned char) str
[i
]) ||
1110 strchr("()<>;&|$", str
[i
])))
1112 else if (!delim
&& strchr("'`\"", str
[i
]))
1118 if (idx
+ 2 >= size
) {
1121 nresult
= el_realloc(result
, (size_t)size
* sizeof(*nresult
));
1122 if (nresult
== NULL
) {
1128 len
= (size_t)i
- (size_t)start
;
1129 temp
= el_malloc((size_t)(len
+ 1) * sizeof(*temp
));
1131 for (i
= 0; i
< idx
; i
++)
1136 (void)strncpy(temp
, &str
[start
], len
);
1138 result
[idx
++] = temp
;
1148 * limit size of history record to ``max'' events
1151 stifle_history(int max
)
1156 if (h
== NULL
|| e
== NULL
)
1159 if (history(h
, &ev
, H_SETSIZE
, max
) == 0) {
1160 max_input_history
= max
;
1161 if (history_length
> max
)
1162 history_base
= history_length
- max
;
1163 while (history_length
> max
) {
1164 he
= remove_history(0);
1166 el_free((void *)(unsigned long)he
->line
);
1174 * "unlimit" size of history - set the limit to maximum allowed int value
1177 unstifle_history(void)
1182 history(h
, &ev
, H_SETSIZE
, INT_MAX
);
1183 omax
= max_input_history
;
1184 max_input_history
= INT_MAX
;
1185 return omax
; /* some value _must_ be returned */
1190 history_is_stifled(void)
1193 /* cannot return true answer */
1194 return max_input_history
!= INT_MAX
;
1197 static const char _history_tmp_template
[] = "/tmp/.historyXXXXXX";
1200 history_truncate_file (const char *filename
, int nlines
)
1204 char template[sizeof(_history_tmp_template
)];
1212 if (filename
== NULL
&& (filename
= _default_history_file()) == NULL
)
1214 if ((fp
= fopen(filename
, "r+")) == NULL
)
1216 strcpy(template, _history_tmp_template
);
1217 if ((fd
= mkstemp(template)) == -1) {
1222 if ((tp
= fdopen(fd
, "r+")) == NULL
) {
1229 if (fread(buf
, sizeof(buf
), (size_t)1, fp
) != 1) {
1234 if (fseeko(fp
, (off_t
)sizeof(buf
) * count
, SEEK_SET
) ==
1239 left
= (ssize_t
)fread(buf
, (size_t)1, sizeof(buf
), fp
);
1247 } else if (fwrite(buf
, (size_t)left
, (size_t)1, tp
)
1255 if (fwrite(buf
, sizeof(buf
), (size_t)1, tp
) != 1) {
1263 cp
= buf
+ left
- 1;
1267 while (--cp
>= buf
) {
1269 if (--nlines
== 0) {
1270 if (++cp
>= buf
+ sizeof(buf
)) {
1278 if (nlines
<= 0 || count
== 0)
1281 if (fseeko(tp
, (off_t
)sizeof(buf
) * count
, SEEK_SET
) < 0) {
1285 if (fread(buf
, sizeof(buf
), (size_t)1, tp
) != 1) {
1293 cp
= buf
+ sizeof(buf
);
1296 if (ret
|| nlines
> 0)
1299 if (fseeko(fp
, (off_t
)0, SEEK_SET
) == (off_t
)-1) {
1304 if (fseeko(tp
, (off_t
)sizeof(buf
) * count
+ (cp
- buf
), SEEK_SET
) ==
1311 if ((left
= (ssize_t
)fread(buf
, (size_t)1, sizeof(buf
), tp
)) == 0) {
1316 if (fwrite(buf
, (size_t)left
, (size_t)1, fp
) != 1) {
1322 if((off
= ftello(fp
)) > 0)
1323 (void)ftruncate(fileno(fp
), off
);
1336 * read history from a file given
1339 read_history(const char *filename
)
1343 if (h
== NULL
|| e
== NULL
)
1345 if (filename
== NULL
&& (filename
= _default_history_file()) == NULL
)
1347 return history(h
, &ev
, H_LOAD
, filename
) == -1 ?
1348 (errno
? errno
: EINVAL
) : 0;
1353 * write history to a file given
1356 write_history(const char *filename
)
1360 if (h
== NULL
|| e
== NULL
)
1362 if (filename
== NULL
&& (filename
= _default_history_file()) == NULL
)
1364 return history(h
, &ev
, H_SAVE
, filename
) == -1 ?
1365 (errno
? errno
: EINVAL
) : 0;
1370 * returns history ``num''th event
1372 * returned pointer points to static variable
1375 history_get(int num
)
1377 static HIST_ENTRY she
;
1381 if (h
== NULL
|| e
== NULL
)
1384 if (num
< history_base
)
1387 /* save current position */
1388 if (history(h
, &ev
, H_CURR
) != 0)
1393 * use H_DELDATA to set to nth history (without delete) by passing
1394 * (void **)-1 -- as in history_set_pos
1396 if (history(h
, &ev
, H_DELDATA
, num
- history_base
, (void **)-1) != 0)
1399 /* get current entry */
1400 if (history(h
, &ev
, H_CURR
) != 0)
1402 if (history(h
, &ev
, H_NEXT_EVDATA
, ev
.num
, &she
.data
) != 0)
1406 /* restore pointer to where it was */
1407 (void)history(h
, &ev
, H_SET
, curr_num
);
1412 /* restore pointer to where it was */
1413 (void)history(h
, &ev
, H_SET
, curr_num
);
1419 * add the line to history table
1422 add_history(const char *line
)
1426 if (h
== NULL
|| e
== NULL
)
1429 if (history(h
, &ev
, H_ENTER
, line
) == -1)
1432 (void)history(h
, &ev
, H_GETSIZE
);
1433 if (ev
.num
== history_length
)
1436 history_length
= ev
.num
;
1442 * remove the specified entry from the history list and return it.
1445 remove_history(int num
)
1450 if (h
== NULL
|| e
== NULL
)
1453 if ((he
= el_malloc(sizeof(*he
))) == NULL
)
1456 if (history(h
, &ev
, H_DELDATA
, num
, &he
->data
) != 0) {
1462 if (history(h
, &ev
, H_GETSIZE
) == 0)
1463 history_length
= ev
.num
;
1470 * replace the line and data of the num-th entry
1473 replace_history_entry(int num
, const char *line
, histdata_t data
)
1479 if (h
== NULL
|| e
== NULL
)
1482 /* save current position */
1483 if (history(h
, &ev
, H_CURR
) != 0)
1487 /* start from the oldest */
1488 if (history(h
, &ev
, H_LAST
) != 0)
1489 return NULL
; /* error */
1491 if ((he
= el_malloc(sizeof(*he
))) == NULL
)
1494 /* look forwards for event matching specified offset */
1495 if (history(h
, &ev
, H_NEXT_EVDATA
, num
, &he
->data
))
1498 he
->line
= strdup(ev
.str
);
1499 if (he
->line
== NULL
)
1502 if (history(h
, &ev
, H_REPLACE
, line
, data
))
1505 /* restore pointer to where it was */
1506 if (history(h
, &ev
, H_SET
, curr_num
))
1516 * clear the history list - delete all entries
1523 if (h
== NULL
|| e
== NULL
)
1526 (void)history(h
, &ev
, H_CLEAR
);
1527 history_offset
= history_length
= 0;
1532 * returns offset of the current history event
1537 return history_offset
;
1540 static HIST_ENTRY
**_history_listp
;
1541 static HIST_ENTRY
*_history_list
;
1547 HIST_ENTRY
**nlp
, *nl
;
1550 if (history(h
, &ev
, H_LAST
) != 0)
1553 if ((nlp
= el_realloc(_history_listp
,
1554 (size_t)history_length
* sizeof(*nlp
))) == NULL
)
1556 _history_listp
= nlp
;
1558 if ((nl
= el_realloc(_history_list
,
1559 (size_t)history_length
* sizeof(*nl
))) == NULL
)
1565 _history_listp
[i
] = &_history_list
[i
];
1566 _history_list
[i
].line
= ev
.str
;
1567 _history_list
[i
].data
= NULL
;
1568 if (i
++ == history_length
)
1570 } while (history(h
, &ev
, H_PREV
) == 0);
1571 return _history_listp
;
1575 * returns current history event or NULL if there is no such event
1578 current_history(void)
1582 if (history(h
, &ev
, H_PREV_EVENT
, history_offset
+ 1) != 0)
1585 rl_he
.line
= ev
.str
;
1592 * returns total number of bytes history events' data are using
1595 history_total_bytes(void)
1601 if (history(h
, &ev
, H_CURR
) != 0)
1605 (void)history(h
, &ev
, H_FIRST
);
1608 size
+= strlen(ev
.str
) * sizeof(*ev
.str
);
1609 while (history(h
, &ev
, H_NEXT
) == 0);
1611 /* get to the same position as before */
1612 history(h
, &ev
, H_PREV_EVENT
, curr_num
);
1619 * sets the position in the history list to ``pos''
1622 history_set_pos(int pos
)
1624 if (pos
>= history_length
|| pos
< 0)
1627 history_offset
= pos
;
1633 * returns previous event in history and shifts pointer accordingly
1634 * Note that readline and editline define directions in opposite ways.
1637 previous_history(void)
1641 if (history_offset
== 0)
1644 if (history(h
, &ev
, H_LAST
) != 0)
1648 return current_history();
1653 * returns next event in history and shifts pointer accordingly
1660 if (history_offset
>= history_length
)
1663 if (history(h
, &ev
, H_LAST
) != 0)
1667 return current_history();
1672 * searches for first history event containing the str
1675 history_search(const char *str
, int direction
)
1681 if (history(h
, &ev
, H_CURR
) != 0)
1686 if ((strp
= strstr(ev
.str
, str
)) != NULL
)
1687 return (int)(strp
- ev
.str
);
1688 if (history(h
, &ev
, direction
< 0 ? H_NEXT
:H_PREV
) != 0)
1691 (void)history(h
, &ev
, H_SET
, curr_num
);
1697 * searches for first history event beginning with str
1700 history_search_prefix(const char *str
, int direction
)
1704 return (history(h
, &ev
, direction
< 0 ?
1705 H_PREV_STR
: H_NEXT_STR
, str
));
1710 * search for event in history containing str, starting at offset
1711 * abs(pos); continue backward, if pos<0, forward otherwise
1715 history_search_pos(const char *str
,
1716 int direction
__attribute__((__unused__
)), int pos
)
1721 off
= (pos
> 0) ? pos
: -pos
;
1722 pos
= (pos
> 0) ? 1 : -1;
1724 if (history(h
, &ev
, H_CURR
) != 0)
1728 if (!history_set_pos(off
) || history(h
, &ev
, H_CURR
) != 0)
1732 if (strstr(ev
.str
, str
))
1734 if (history(h
, &ev
, (pos
< 0) ? H_PREV
: H_NEXT
) != 0)
1738 /* set "current" pointer back to previous state */
1739 (void)history(h
, &ev
,
1740 pos
< 0 ? H_NEXT_EVENT
: H_PREV_EVENT
, curr_num
);
1746 /********************************/
1747 /* completion functions */
1750 tilde_expand(char *name
)
1752 return fn_tilde_expand(name
);
1756 filename_completion_function(const char *name
, int state
)
1758 return fn_filename_completion_function(name
, state
);
1762 * a completion generator for usernames; returns _first_ username
1763 * which starts with supplied text
1764 * text contains a partial username preceded by random character
1765 * (usually '~'); state resets search from start (??? should we do that anyway)
1766 * it's the caller's responsibility to free the returned value
1769 username_completion_function(const char *text
, int state
)
1771 #if defined(HAVE_GETPW_R_POSIX) || defined(HAVE_GETPW_R_DRAFT)
1772 struct passwd pwres
;
1775 struct passwd
*pass
= NULL
;
1777 if (text
[0] == '\0')
1787 (pass
= getpwent()) != NULL
1788 && text
[0] == pass
->pw_name
[0]
1789 && strcmp(text
, pass
->pw_name
) == 0)
1796 return strdup(pass
->pw_name
);
1801 * el-compatible wrapper to send TSTP on ^Z
1804 static unsigned char
1805 _el_rl_tstp(EditLine
*el
__attribute__((__unused__
)), int ch
__attribute__((__unused__
)))
1807 (void)kill(0, SIGTSTP
);
1812 * Display list of strings in columnar format on readline's output stream.
1813 * 'matches' is list of strings, 'len' is number of strings in 'matches',
1814 * 'max' is maximum length of string in 'matches'.
1817 rl_display_match_list(char **matches
, int len
, int max
)
1820 fn_display_match_list(e
, matches
, (size_t)len
, (size_t)max
);
1825 _rl_completion_append_character_function(const char *dummy
1826 __attribute__((__unused__
)))
1829 buf
[0] = (char)rl_completion_append_character
;
1836 * complete word at current point
1840 rl_complete(int ignore
__attribute__((__unused__
)), int invoking_key
)
1842 static ct_buffer_t wbreak_conv
, sprefix_conv
;
1845 if (h
== NULL
|| e
== NULL
)
1848 if (rl_inhibit_completion
) {
1850 arr
[0] = (char)invoking_key
;
1852 el_insertstr(e
, arr
);
1856 if (rl_completion_word_break_hook
!= NULL
)
1857 breakchars
= (*rl_completion_word_break_hook
)();
1859 breakchars
= rl_basic_word_break_characters
;
1863 /* Just look at how many global variables modify this operation! */
1864 return fn_complete(e
,
1865 (rl_compentry_func_t
*)rl_completion_entry_function
,
1866 rl_attempted_completion_function
,
1867 ct_decode_string(rl_basic_word_break_characters
, &wbreak_conv
),
1868 ct_decode_string(breakchars
, &sprefix_conv
),
1869 _rl_completion_append_character_function
,
1870 (size_t)rl_completion_query_items
,
1871 &rl_completion_type
, &rl_attempted_completion_over
,
1872 &rl_point
, &rl_end
);
1879 static unsigned char
1880 _el_rl_complete(EditLine
*el
__attribute__((__unused__
)), int ch
)
1882 return (unsigned char)rl_complete(0, ch
);
1886 * misc other functions
1890 * bind key c to readline-type function func
1893 rl_bind_key(int c
, rl_command_func_t
*func
)
1897 if (h
== NULL
|| e
== NULL
)
1900 if (func
== rl_insert
) {
1901 /* XXX notice there is no range checking of ``c'' */
1902 e
->el_map
.key
[c
] = ED_INSERT
;
1910 * read one key from input - handles chars pushed back
1911 * to input stream also
1916 char fooarr
[2 * sizeof(int)];
1918 if (e
== NULL
|| h
== NULL
)
1921 return el_getc(e
, fooarr
);
1926 * reset the terminal
1930 rl_reset_terminal(const char *p
__attribute__((__unused__
)))
1933 if (h
== NULL
|| e
== NULL
)
1940 * insert character ``c'' back into input stream, ``count'' times
1943 rl_insert(int count
, int c
)
1947 if (h
== NULL
|| e
== NULL
)
1950 /* XXX - int -> char conversion can lose on multichars */
1954 for (; count
> 0; count
--)
1961 rl_insert_text(const char *text
)
1963 if (!text
|| *text
== 0)
1966 if (h
== NULL
|| e
== NULL
)
1969 if (el_insertstr(e
, text
) < 0)
1971 return (int)strlen(text
);
1976 rl_newline(int count
__attribute__((__unused__
)),
1977 int c
__attribute__((__unused__
)))
1980 * Readline-4.0 appears to ignore the args.
1982 return rl_insert(1, '\n');
1986 static unsigned char
1987 rl_bind_wrapper(EditLine
*el
__attribute__((__unused__
)), unsigned char c
)
1996 /* If rl_done was set by the above call, deal with it here */
2004 rl_add_defun(const char *name
, rl_command_func_t
*fun
, int c
)
2007 if ((size_t)c
>= sizeof(map
) / sizeof(map
[0]) || c
< 0)
2009 map
[(unsigned char)c
] = fun
;
2010 el_set(e
, EL_ADDFN
, name
, name
, rl_bind_wrapper
);
2011 vis(dest
, c
, VIS_WHITE
|VIS_NOSLASH
, 0);
2012 el_set(e
, EL_BIND
, dest
, name
, NULL
);
2017 rl_callback_read_char(void)
2019 int count
= 0, done
= 0;
2020 const char *buf
= el_gets(e
, &count
);
2023 if (buf
== NULL
|| count
-- <= 0)
2025 if (count
== 0 && buf
[0] == e
->el_tty
.t_c
[TS_IO
][C_EOF
])
2027 if (buf
[count
] == '\n' || buf
[count
] == '\r')
2030 if (done
&& rl_linefunc
!= NULL
) {
2031 el_set(e
, EL_UNBUFFERED
, 0);
2033 if ((wbuf
= strdup(buf
)) != NULL
)
2037 (*(void (*)(const char *))rl_linefunc
)(wbuf
);
2038 el_set(e
, EL_UNBUFFERED
, 1);
2043 rl_callback_handler_install(const char *prompt
, rl_vcpfunc_t
*linefunc
)
2048 (void)rl_set_prompt(prompt
);
2049 rl_linefunc
= linefunc
;
2050 el_set(e
, EL_UNBUFFERED
, 1);
2054 rl_callback_handler_remove(void)
2056 el_set(e
, EL_UNBUFFERED
, 0);
2064 a
[0] = (char)e
->el_tty
.t_c
[TS_IO
][C_REPRINT
];
2070 rl_get_previous_history(int count
, int key
)
2082 rl_prep_terminal(int meta_flag
__attribute__((__unused__
)))
2084 el_set(e
, EL_PREP_TERM
, 1);
2088 rl_deprep_terminal(void)
2090 el_set(e
, EL_PREP_TERM
, 0);
2094 rl_read_init_file(const char *s
)
2096 return el_source(e
, s
);
2100 rl_parse_and_bind(const char *line
)
2106 tok
= tok_init(NULL
);
2107 tok_str(tok
, line
, &argc
, &argv
);
2108 argc
= el_parse(e
, argc
, argv
);
2110 return argc
? 1 : 0;
2114 rl_variable_bind(const char *var
, const char *value
)
2117 * The proper return value is undocument, but this is what the
2118 * readline source seems to do.
2120 return el_set(e
, EL_BIND
, "", var
, value
, NULL
) == -1 ? 1 : 0;
2124 rl_stuff_char(int c
)
2130 el_insertstr(e
, buf
);
2134 _rl_event_read_char(EditLine
*el
, wchar_t *wc
)
2138 ssize_t num_read
= 0;
2142 while (rl_event_hook
) {
2146 #if defined(FIONREAD)
2147 if (ioctl(el
->el_infd
, FIONREAD
, &n
) < 0)
2150 num_read
= read(el
->el_infd
, &ch
, (size_t)1);
2153 #elif defined(F_SETFL) && defined(O_NDELAY)
2154 if ((n
= fcntl(el
->el_infd
, F_GETFL
, 0)) < 0)
2156 if (fcntl(el
->el_infd
, F_SETFL
, n
|O_NDELAY
) < 0)
2158 num_read
= read(el
->el_infd
, &ch
, 1);
2159 if (fcntl(el
->el_infd
, F_SETFL
, n
))
2162 /* not non-blocking, but what you gonna do? */
2163 num_read
= read(el
->el_infd
, &ch
, 1);
2167 if (num_read
< 0 && errno
== EAGAIN
)
2174 el_set(el
, EL_GETCFN
, EL_BUILTIN_GETCFN
);
2176 return (int)num_read
;
2180 _rl_update_pos(void)
2182 const LineInfo
*li
= el_line(e
);
2184 rl_point
= (int)(li
->cursor
- li
->buffer
);
2185 rl_end
= (int)(li
->lastchar
- li
->buffer
);
2189 rl_get_screen_size(int *rows
, int *cols
)
2192 el_get(e
, EL_GETTC
, "li", rows
, (void *)0);
2194 el_get(e
, EL_GETTC
, "co", cols
, (void *)0);
2198 rl_set_screen_size(int rows
, int cols
)
2201 (void)snprintf(buf
, sizeof(buf
), "%d", rows
);
2202 el_set(e
, EL_SETTC
, "li", buf
, NULL
);
2203 (void)snprintf(buf
, sizeof(buf
), "%d", cols
);
2204 el_set(e
, EL_SETTC
, "co", buf
, NULL
);
2208 rl_completion_matches(const char *str
, rl_compentry_func_t
*fun
)
2210 size_t len
, max
, i
, j
, min
;
2211 char **list
, *match
, *a
, *b
;
2215 if ((list
= el_malloc(max
* sizeof(*list
))) == NULL
)
2218 while ((match
= (*fun
)(str
, (int)(len
- 1))) != NULL
) {
2219 list
[len
++] = match
;
2223 if ((nl
= el_realloc(list
, max
* sizeof(*nl
))) == NULL
)
2232 if ((list
[0] = strdup(list
[1])) == NULL
)
2236 qsort(&list
[1], len
- 1, sizeof(*list
),
2237 (int (*)(const void *, const void *)) strcmp
);
2239 for (i
= 1, a
= list
[i
]; i
< len
- 1; i
++, a
= b
) {
2241 for (j
= 0; a
[j
] && a
[j
] == b
[j
]; j
++)
2246 if (min
== 0 && *str
) {
2247 if ((list
[0] = strdup(str
)) == NULL
)
2250 if ((list
[0] = el_malloc((min
+ 1) * sizeof(*list
[0]))) == NULL
)
2252 (void)memcpy(list
[0], list
[1], min
);
2253 list
[0][min
] = '\0';
2263 rl_filename_completion_function (const char *text
, int state
)
2265 return fn_filename_completion_function(text
, state
);
2269 rl_forced_update_display(void)
2271 el_set(e
, EL_REFRESH
);
2275 _rl_abort_internal(void)
2283 _rl_qsort_string_compare(char **s1
, char **s2
)
2285 return strcoll(*s1
, *s2
);
2289 history_get_history_state(void)
2293 if ((hs
= el_malloc(sizeof(*hs
))) == NULL
)
2295 hs
->length
= history_length
;
2301 rl_kill_text(int from
__attribute__((__unused__
)),
2302 int to
__attribute__((__unused__
)))
2308 rl_make_bare_keymap(void)
2321 rl_set_keymap(Keymap k
__attribute__((__unused__
)))
2327 rl_generic_bind(int type
__attribute__((__unused__
)),
2328 const char * keyseq
__attribute__((__unused__
)),
2329 const char * data
__attribute__((__unused__
)),
2330 Keymap k
__attribute__((__unused__
)))
2337 rl_bind_key_in_map(int key
__attribute__((__unused__
)),
2338 rl_command_func_t
*fun
__attribute__((__unused__
)),
2339 Keymap k
__attribute__((__unused__
)))
2344 /* unsupported, but needed by python */
2346 rl_cleanup_after_signal(void)
2351 rl_on_new_line(void)
2357 rl_free_line_state(void)
2363 rl_set_keyboard_input_timeout(int u
__attribute__((__unused__
)))