1 /* $NetBSD: readline.c,v 1.109 2013/08/28 08:05:21 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.109 2013/08/28 08:05:21 christos Exp $");
35 #endif /* not lint && not SCCSID */
37 #include <sys/types.h>
52 #include "readline/readline.h"
54 #include "fcns.h" /* for EL_NUM_FCNS */
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 VCPFunction
*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 max_input_history
= 0;
99 char history_expansion_char
= '!';
100 char history_subst_char
= '^';
101 char *history_no_expand_chars
= expand_chars
;
102 Function
*history_inhibit_expansion_function
= NULL
;
103 char *history_arg_extract(int start
, int end
, const char *str
);
105 int rl_inhibit_completion
= 0;
106 int rl_attempted_completion_over
= 0;
107 char *rl_basic_word_break_characters
= break_chars
;
108 char *rl_completer_word_break_characters
= NULL
;
109 char *rl_completer_quote_characters
= NULL
;
110 Function
*rl_completion_entry_function
= NULL
;
111 char *(*rl_completion_word_break_hook
)(void) = NULL
;
112 CPPFunction
*rl_attempted_completion_function
= NULL
;
113 Function
*rl_pre_input_hook
= NULL
;
114 Function
*rl_startup1_hook
= NULL
;
115 int (*rl_getc_function
)(FILE *) = NULL
;
116 char *rl_terminal_name
= NULL
;
117 int rl_already_prompted
= 0;
118 int rl_filename_completion_desired
= 0;
119 int rl_ignore_completion_duplicates
= 0;
120 int readline_echoing_p
= 1;
121 int _rl_print_completions_horizontally
= 0;
122 VFunction
*rl_redisplay_function
= NULL
;
123 Function
*rl_startup_hook
= NULL
;
124 VFunction
*rl_completion_display_matches_hook
= NULL
;
125 VFunction
*rl_prep_term_function
= (VFunction
*)rl_prep_terminal
;
126 VFunction
*rl_deprep_term_function
= (VFunction
*)rl_deprep_terminal
;
127 KEYMAP_ENTRY_ARRAY emacs_meta_keymap
;
130 * The current prompt string.
132 char *rl_prompt
= NULL
;
134 * This is set to character indicating type of completion being done by
135 * rl_complete_internal(); this is available for application completion
138 int rl_completion_type
= 0;
141 * If more than this number of items results from query for possible
142 * completions, we ask user if they are sure to really display the list.
144 int rl_completion_query_items
= 100;
147 * List of characters which are word break characters, but should be left
148 * in the parsed text when it is passed to the completion function.
149 * Shell uses this to help determine what kind of completing to do.
151 char *rl_special_prefixes
= NULL
;
154 * This is the character appended to the completed words if at the end of
155 * the line. Default is ' ' (a space).
157 int rl_completion_append_character
= ' ';
159 /* stuff below is used internally by libedit for readline emulation */
161 static History
*h
= NULL
;
162 static EditLine
*e
= NULL
;
163 static Function
*map
[256];
164 static jmp_buf topbuf
;
166 /* internal functions */
167 static unsigned char _el_rl_complete(EditLine
*, int);
168 static unsigned char _el_rl_tstp(EditLine
*, int);
169 static char *_get_prompt(EditLine
*);
170 static int _getc_function(EditLine
*, char *);
171 static HIST_ENTRY
*_move_history(int);
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
*, char *);
177 static void _rl_update_pos(void);
182 _get_prompt(EditLine
*el
__attribute__((__unused__
)))
184 rl_already_prompted
= 1;
190 * generic function for moving around history
193 _move_history(int op
)
196 static HIST_ENTRY rl_he
;
198 if (history(h
, &ev
, op
) != 0)
209 * read one key from user defined input function
213 _getc_function(EditLine
*el
__attribute__((__unused__
)), char *c
)
217 i
= (*rl_getc_function
)(NULL
);
225 _resize_fun(EditLine
*el
, void *a
)
231 /* a cheesy way to get rid of const cast. */
232 *ap
= memchr(li
->buffer
, *li
->buffer
, (size_t)1);
236 _default_history_file(void)
245 if ((p
= getpwuid(getuid())) == NULL
)
248 len
= strlen(p
->pw_dir
) + sizeof("/.history");
249 if ((path
= malloc(len
)) == NULL
)
252 (void)snprintf(path
, len
, "%s/.history", p
->pw_dir
);
257 * READLINE compatibility stuff
264 rl_set_prompt(const char *prompt
)
270 if (rl_prompt
!= NULL
&& strcmp(rl_prompt
, prompt
) == 0)
274 rl_prompt
= strdup(prompt
);
275 if (rl_prompt
== NULL
)
278 while ((p
= strchr(rl_prompt
, RL_PROMPT_END_IGNORE
)) != NULL
)
279 *p
= RL_PROMPT_START_IGNORE
;
285 * initialize rl compat stuff
302 rl_outstream
= stdout
;
305 * See if we don't really want to run the editor
307 if (tcgetattr(fileno(rl_instream
), &t
) != -1 && (t
.c_lflag
& ECHO
) == 0)
310 e
= el_init(rl_readline_name
, rl_instream
, rl_outstream
, stderr
);
313 el_set(e
, EL_EDITMODE
, 0);
319 history(h
, &ev
, H_SETSIZE
, INT_MAX
); /* unlimited */
321 max_input_history
= INT_MAX
;
322 el_set(e
, EL_HIST
, history
, h
);
324 /* Setup resize function */
325 el_set(e
, EL_RESIZE
, _resize_fun
, &rl_line_buffer
);
327 /* setup getc function if valid */
328 if (rl_getc_function
)
329 el_set(e
, EL_GETCFN
, _getc_function
);
331 /* for proper prompt printing in readline() */
332 if (rl_set_prompt("") == -1) {
337 el_set(e
, EL_PROMPT
, _get_prompt
, RL_PROMPT_START_IGNORE
);
338 el_set(e
, EL_SIGNAL
, rl_catch_signals
);
340 /* set default mode to "emacs"-style and read setting afterwards */
341 /* so this can be overriden */
342 el_set(e
, EL_EDITOR
, "emacs");
343 if (rl_terminal_name
!= NULL
)
344 el_set(e
, EL_TERMINAL
, rl_terminal_name
);
346 el_get(e
, EL_TERMINAL
, &rl_terminal_name
);
349 * Word completion - this has to go AFTER rebinding keys
352 el_set(e
, EL_ADDFN
, "rl_complete",
353 "ReadLine compatible completion function",
355 el_set(e
, EL_BIND
, "^I", "rl_complete", NULL
);
358 * Send TSTP when ^Z is pressed.
360 el_set(e
, EL_ADDFN
, "rl_tstp",
361 "ReadLine compatible suspend function",
363 el_set(e
, EL_BIND
, "^Z", "rl_tstp", NULL
);
365 /* read settings from configuration file */
369 * Unfortunately, some applications really do use rl_point
370 * and rl_line_buffer directly.
372 _resize_fun(e
, &rl_line_buffer
);
376 (*rl_startup_hook
)(NULL
, 0);
383 * read one line from input stream and return it, chomping
384 * trailing newline (if there is any)
387 readline(const char *p
)
390 const char * volatile prompt
= p
;
394 static int used_event_hook
;
396 if (e
== NULL
|| h
== NULL
)
401 (void)setjmp(topbuf
);
403 /* update prompt accordingly to what has been passed */
404 if (rl_set_prompt(prompt
) == -1)
407 if (rl_pre_input_hook
)
408 (*rl_pre_input_hook
)(NULL
, 0);
410 if (rl_event_hook
&& !(e
->el_flags
&NO_TTY
)) {
411 el_set(e
, EL_GETCFN
, _rl_event_read_char
);
415 if (!rl_event_hook
&& used_event_hook
) {
416 el_set(e
, EL_GETCFN
, EL_BUILTIN_GETCFN
);
420 rl_already_prompted
= 0;
422 /* get one line from input stream */
423 ret
= el_gets(e
, &count
);
425 if (ret
&& count
> 0) {
432 if (buf
[lastidx
] == '\n')
437 history(h
, &ev
, H_GETSIZE
);
438 history_length
= ev
.num
;
448 * is normally called before application starts to use
449 * history expansion functions
454 if (h
== NULL
|| e
== NULL
)
460 * substitute ``what'' with ``with'', returning resulting string; if
461 * globally == 1, substitutes all occurrences of what, otherwise only the
465 _rl_compat_sub(const char *str
, const char *what
, const char *with
,
470 size_t len
, with_len
, what_len
;
473 with_len
= strlen(with
);
474 what_len
= strlen(what
);
476 /* calculate length we need for result */
479 if (*s
== *what
&& !strncmp(s
, what
, what_len
)) {
480 len
+= with_len
- what_len
;
487 r
= result
= el_malloc((len
+ 1) * sizeof(*r
));
492 if (*s
== *what
&& !strncmp(s
, what
, what_len
)) {
493 (void)strncpy(r
, with
, with_len
);
507 static char *last_search_pat
; /* last !?pat[?] search pattern */
508 static char *last_search_match
; /* last !?pat[?] that matched */
511 get_history_event(const char *cmd
, int *cindex
, int qchar
)
513 int idx
, sign
, sub
, num
, begin
, ret
;
520 if (cmd
[idx
++] != history_expansion_char
)
523 /* find out which event to take */
524 if (cmd
[idx
] == history_expansion_char
|| cmd
[idx
] == '\0') {
525 if (history(h
, &ev
, H_FIRST
) != 0)
527 *cindex
= cmd
[idx
]? (idx
+ 1):idx
;
531 if (cmd
[idx
] == '-') {
536 if ('0' <= cmd
[idx
] && cmd
[idx
] <= '9') {
540 while (cmd
[idx
] && '0' <= cmd
[idx
] && cmd
[idx
] <= '9') {
541 num
= num
* 10 + cmd
[idx
] - '0';
545 num
= history_length
- num
+ 1;
547 if (!(rl_he
= history_get(num
)))
554 if (cmd
[idx
] == '?') {
560 if (cmd
[idx
] == '\n')
562 if (sub
&& cmd
[idx
] == '?')
564 if (!sub
&& (cmd
[idx
] == ':' || cmd
[idx
] == ' '
565 || cmd
[idx
] == '\t' || cmd
[idx
] == qchar
))
569 len
= (size_t)idx
- (size_t)begin
;
570 if (sub
&& cmd
[idx
] == '?')
572 if (sub
&& len
== 0 && last_search_pat
&& *last_search_pat
)
573 pat
= last_search_pat
;
577 if ((pat
= el_malloc((len
+ 1) * sizeof(*pat
))) == NULL
)
579 (void)strncpy(pat
, cmd
+ begin
, len
);
583 if (history(h
, &ev
, H_CURR
) != 0) {
584 if (pat
!= last_search_pat
)
591 if (pat
!= last_search_pat
) {
593 el_free(last_search_pat
);
594 last_search_pat
= pat
;
596 ret
= history_search(pat
, -1);
598 ret
= history_search_prefix(pat
, -1);
601 /* restore to end of list on failed search */
602 history(h
, &ev
, H_FIRST
);
603 (void)fprintf(rl_outstream
, "%s: Event not found\n", pat
);
604 if (pat
!= last_search_pat
)
610 if (last_search_match
&& last_search_match
!= pat
)
611 el_free(last_search_match
);
612 last_search_match
= pat
;
615 if (pat
!= last_search_pat
)
618 if (history(h
, &ev
, H_CURR
) != 0)
623 /* roll back to original position */
624 (void)history(h
, &ev
, H_SET
, num
);
630 * the real function doing history expansion - takes as argument command
631 * to do and data upon which the command should be executed
632 * does expansion the way I've understood readline documentation
634 * returns 0 if data was not modified, 1 if it was and 2 if the string
635 * should be only printed and not executed; in case of error,
636 * returns -1 and *result points to NULL
637 * it's callers responsibility to free() string returned in *result
640 _history_expand_command(const char *command
, size_t offs
, size_t cmdlen
,
643 char *tmp
, *search
= NULL
, *aptr
;
644 const char *ptr
, *cmd
;
645 static char *from
= NULL
, *to
= NULL
;
646 int start
, end
, idx
, has_mods
= 0;
647 int p_on
= 0, g_on
= 0;
653 /* First get event specifier */
656 if (strchr(":^*$", command
[offs
+ 1])) {
659 * "!:" is shorthand for "!!:".
660 * "!^", "!*" and "!$" are shorthand for
661 * "!!:^", "!!:*" and "!!:$" respectively.
663 str
[0] = str
[1] = '!';
665 ptr
= get_history_event(str
, &idx
, 0);
666 idx
= (command
[offs
+ 1] == ':')? 1:0;
669 if (command
[offs
+ 1] == '#') {
670 /* use command so far */
671 if ((aptr
= el_malloc((offs
+ 1) * sizeof(*aptr
)))
674 (void)strncpy(aptr
, command
, offs
);
680 qchar
= (offs
> 0 && command
[offs
- 1] == '"')? '"':0;
681 ptr
= get_history_event(command
+ offs
, &idx
, qchar
);
683 has_mods
= command
[offs
+ (size_t)idx
] == ':';
686 if (ptr
== NULL
&& aptr
== NULL
)
690 *result
= strdup(aptr
? aptr
: ptr
);
698 cmd
= command
+ offs
+ idx
+ 1;
700 /* Now parse any word designators */
702 if (*cmd
== '%') /* last word matched by ?pat? */
703 tmp
= strdup(last_search_match
? last_search_match
:"");
704 else if (strchr("^*$-0123456789", *cmd
)) {
707 start
= end
= 1, cmd
++;
708 else if (*cmd
== '$')
710 else if (*cmd
== '*')
712 else if (*cmd
== '-' || isdigit((unsigned char) *cmd
)) {
714 while (*cmd
&& '0' <= *cmd
&& *cmd
<= '9')
715 start
= start
* 10 + *cmd
++ - '0';
718 if (isdigit((unsigned char) cmd
[1])) {
721 while (*cmd
&& '0' <= *cmd
&& *cmd
<= '9')
722 end
= end
* 10 + *cmd
++ - '0';
723 } else if (cmd
[1] == '$') {
730 } else if (*cmd
== '*')
735 tmp
= history_arg_extract(start
, end
, aptr
? aptr
:ptr
);
737 (void)fprintf(rl_outstream
, "%s: Bad word specifier",
738 command
+ offs
+ idx
);
744 tmp
= strdup(aptr
? aptr
:ptr
);
749 if (*cmd
== '\0' || ((size_t)(cmd
- (command
+ offs
)) >= cmdlen
)) {
754 for (; *cmd
; cmd
++) {
757 else if (*cmd
== 'h') { /* remove trailing path */
758 if ((aptr
= strrchr(tmp
, '/')) != NULL
)
760 } else if (*cmd
== 't') { /* remove leading path */
761 if ((aptr
= strrchr(tmp
, '/')) != NULL
) {
762 aptr
= strdup(aptr
+ 1);
766 } else if (*cmd
== 'r') { /* remove trailing suffix */
767 if ((aptr
= strrchr(tmp
, '.')) != NULL
)
769 } else if (*cmd
== 'e') { /* remove all but suffix */
770 if ((aptr
= strrchr(tmp
, '.')) != NULL
) {
775 } else if (*cmd
== 'p') /* print only */
777 else if (*cmd
== 'g')
779 else if (*cmd
== 's' || *cmd
== '&') {
780 char *what
, *with
, delim
;
781 size_t len
, from_len
;
784 if (*cmd
== '&' && (from
== NULL
|| to
== NULL
))
786 else if (*cmd
== 's') {
787 delim
= *(++cmd
), cmd
++;
789 what
= el_realloc(from
, size
* sizeof(*what
));
796 for (; *cmd
&& *cmd
!= delim
; cmd
++) {
797 if (*cmd
== '\\' && cmd
[1] == delim
)
801 nwhat
= el_realloc(what
,
818 from
= strdup(search
);
829 cmd
++; /* shift after delim */
834 with
= el_realloc(to
, size
* sizeof(*with
));
841 from_len
= strlen(from
);
842 for (; *cmd
&& *cmd
!= delim
; cmd
++) {
843 if (len
+ from_len
+ 1 >= size
) {
845 size
+= from_len
+ 1;
846 nwith
= el_realloc(with
,
847 size
* sizeof(*nwith
));
857 (void)strcpy(&with
[len
], from
);
862 && (*(cmd
+ 1) == delim
863 || *(cmd
+ 1) == '&'))
871 aptr
= _rl_compat_sub(tmp
, from
, to
, g_on
);
885 * csh-style history expansion
888 history_expand(char *str
, char **output
)
894 if (h
== NULL
|| e
== NULL
)
897 if (history_expansion_char
== 0) {
898 *output
= strdup(str
);
903 if (str
[0] == history_subst_char
) {
904 /* ^foo^foo2^ is equivalent to !!:s^foo^foo2^ */
905 *output
= el_malloc((strlen(str
) + 4 + 1) * sizeof(**output
));
908 (*output
)[0] = (*output
)[1] = history_expansion_char
;
911 (void)strcpy((*output
) + 4, str
);
914 *output
= strdup(str
);
919 #define ADD_STRING(what, len, fr) \
921 if (idx + len + 1 > size) { \
922 char *nresult = el_realloc(result, \
923 (size += len + 1) * sizeof(*nresult)); \
924 if (nresult == NULL) { \
926 if (/*CONSTCOND*/fr) \
932 (void)strncpy(&result[idx], what, len); \
934 result[idx] = '\0'; \
940 for (i
= 0; str
[i
];) {
941 int qchar
, loop_again
;
942 size_t len
, start
, j
;
948 for (; str
[j
]; j
++) {
949 if (str
[j
] == '\\' &&
950 str
[j
+ 1] == history_expansion_char
) {
951 (void)strcpy(&str
[j
], &str
[j
+ 1]);
955 if (isspace((unsigned char) str
[j
])
959 if (str
[j
] == history_expansion_char
960 && !strchr(history_no_expand_chars
, str
[j
+ 1])
961 && (!history_inhibit_expansion_function
||
962 (*history_inhibit_expansion_function
)(str
,
967 if (str
[j
] && loop_again
) {
969 qchar
= (j
> 0 && str
[j
- 1] == '"' )? '"':0;
971 if (str
[j
] == history_expansion_char
)
977 ADD_STRING(&str
[start
], len
, 0);
979 if (str
[i
] == '\0' || str
[i
] != history_expansion_char
) {
981 ADD_STRING(&str
[i
], len
, 0);
988 ret
= _history_expand_command (str
, i
, (j
- i
), &tmp
);
989 if (ret
> 0 && tmp
) {
991 ADD_STRING(tmp
, len
, 1);
1000 /* ret is 2 for "print only" option */
1002 add_history(result
);
1004 /* gdb 4.11 has been shipped with readline, where */
1005 /* history_expand() returned -1 when the line */
1006 /* should not be executed; in readline 2.1+ */
1007 /* it should return 2 in such a case */
1018 * Return a string consisting of arguments of "str" from "start" to "end".
1021 history_arg_extract(int start
, int end
, const char *str
)
1024 char **arr
, *result
= NULL
;
1026 arr
= history_tokenize(str
);
1029 if (arr
&& *arr
== NULL
)
1032 for (max
= 0; arr
[max
]; max
++)
1041 end
= (int)max
+ end
+ 1;
1045 if (start
< 0 || end
< 0 || (size_t)start
> max
||
1046 (size_t)end
> max
|| start
> end
)
1049 for (i
= (size_t)start
, len
= 0; i
<= (size_t)end
; i
++)
1050 len
+= strlen(arr
[i
]) + 1;
1052 result
= el_malloc(len
* sizeof(*result
));
1056 for (i
= (size_t)start
, len
= 0; i
<= (size_t)end
; i
++) {
1057 (void)strcpy(result
+ len
, arr
[i
]);
1058 len
+= strlen(arr
[i
]);
1059 if (i
< (size_t)end
)
1060 result
[len
++] = ' ';
1065 for (i
= 0; arr
[i
]; i
++)
1073 * Parse the string into individual tokens,
1074 * similar to how shell would do it.
1077 history_tokenize(const char *str
)
1079 int size
= 1, idx
= 0, i
, start
;
1081 char **result
= NULL
, *temp
, delim
= '\0';
1083 for (i
= 0; str
[i
];) {
1084 while (isspace((unsigned char) str
[i
]))
1088 if (str
[i
] == '\\') {
1089 if (str
[i
+1] != '\0')
1091 } else if (str
[i
] == delim
)
1094 (isspace((unsigned char) str
[i
]) ||
1095 strchr("()<>;&|$", str
[i
])))
1097 else if (!delim
&& strchr("'`\"", str
[i
]))
1103 if (idx
+ 2 >= size
) {
1106 nresult
= el_realloc(result
, (size_t)size
* sizeof(*nresult
));
1107 if (nresult
== NULL
) {
1113 len
= (size_t)i
- (size_t)start
;
1114 temp
= el_malloc((size_t)(len
+ 1) * sizeof(*temp
));
1116 for (i
= 0; i
< idx
; i
++)
1121 (void)strncpy(temp
, &str
[start
], len
);
1123 result
[idx
++] = temp
;
1133 * limit size of history record to ``max'' events
1136 stifle_history(int max
)
1140 if (h
== NULL
|| e
== NULL
)
1143 if (history(h
, &ev
, H_SETSIZE
, max
) == 0)
1144 max_input_history
= max
;
1149 * "unlimit" size of history - set the limit to maximum allowed int value
1152 unstifle_history(void)
1157 history(h
, &ev
, H_SETSIZE
, INT_MAX
);
1158 omax
= max_input_history
;
1159 max_input_history
= INT_MAX
;
1160 return omax
; /* some value _must_ be returned */
1165 history_is_stifled(void)
1168 /* cannot return true answer */
1169 return max_input_history
!= INT_MAX
;
1172 static const char _history_tmp_template
[] = "/tmp/.historyXXXXXX";
1175 history_truncate_file (const char *filename
, int nlines
)
1179 char template[sizeof(_history_tmp_template
)];
1187 if (filename
== NULL
&& (filename
= _default_history_file()) == NULL
)
1189 if ((fp
= fopen(filename
, "r+")) == NULL
)
1191 strcpy(template, _history_tmp_template
);
1192 if ((fd
= mkstemp(template)) == -1) {
1197 if ((tp
= fdopen(fd
, "r+")) == NULL
) {
1204 if (fread(buf
, sizeof(buf
), (size_t)1, fp
) != 1) {
1209 if (fseeko(fp
, (off_t
)sizeof(buf
) * count
, SEEK_SET
) ==
1214 left
= (ssize_t
)fread(buf
, (size_t)1, sizeof(buf
), fp
);
1222 } else if (fwrite(buf
, (size_t)left
, (size_t)1, tp
)
1230 if (fwrite(buf
, sizeof(buf
), (size_t)1, tp
) != 1) {
1238 cp
= buf
+ left
- 1;
1242 while (--cp
>= buf
) {
1244 if (--nlines
== 0) {
1245 if (++cp
>= buf
+ sizeof(buf
)) {
1253 if (nlines
<= 0 || count
== 0)
1256 if (fseeko(tp
, (off_t
)sizeof(buf
) * count
, SEEK_SET
) < 0) {
1260 if (fread(buf
, sizeof(buf
), (size_t)1, tp
) != 1) {
1268 cp
= buf
+ sizeof(buf
);
1271 if (ret
|| nlines
> 0)
1274 if (fseeko(fp
, (off_t
)0, SEEK_SET
) == (off_t
)-1) {
1279 if (fseeko(tp
, (off_t
)sizeof(buf
) * count
+ (cp
- buf
), SEEK_SET
) ==
1286 if ((left
= (ssize_t
)fread(buf
, (size_t)1, sizeof(buf
), tp
)) == 0) {
1291 if (fwrite(buf
, (size_t)left
, (size_t)1, fp
) != 1) {
1297 if((off
= ftello(fp
)) > 0)
1298 (void)ftruncate(fileno(fp
), off
);
1311 * read history from a file given
1314 read_history(const char *filename
)
1318 if (h
== NULL
|| e
== NULL
)
1320 if (filename
== NULL
&& (filename
= _default_history_file()) == NULL
)
1322 return history(h
, &ev
, H_LOAD
, filename
) == -1 ?
1323 (errno
? errno
: EINVAL
) : 0;
1328 * write history to a file given
1331 write_history(const char *filename
)
1335 if (h
== NULL
|| e
== NULL
)
1337 if (filename
== NULL
&& (filename
= _default_history_file()) == NULL
)
1339 return history(h
, &ev
, H_SAVE
, filename
) == -1 ?
1340 (errno
? errno
: EINVAL
) : 0;
1345 * returns history ``num''th event
1347 * returned pointer points to static variable
1350 history_get(int num
)
1352 static HIST_ENTRY she
;
1356 if (h
== NULL
|| e
== NULL
)
1359 /* save current position */
1360 if (history(h
, &ev
, H_CURR
) != 0)
1364 /* start from the oldest */
1365 if (history(h
, &ev
, H_LAST
) != 0)
1366 return NULL
; /* error */
1368 /* look forwards for event matching specified offset */
1369 if (history(h
, &ev
, H_NEXT_EVDATA
, num
, &she
.data
))
1374 /* restore pointer to where it was */
1375 (void)history(h
, &ev
, H_SET
, curr_num
);
1382 * add the line to history table
1385 add_history(const char *line
)
1392 if (h
== NULL
|| e
== NULL
)
1395 (void)history(h
, &ev
, H_ENTER
, line
);
1396 if (history(h
, &ev
, H_GETSIZE
) == 0)
1397 history_length
= ev
.num
;
1399 return !(history_length
> 0); /* return 0 if all is okay */
1404 * remove the specified entry from the history list and return it.
1407 remove_history(int num
)
1412 if (h
== NULL
|| e
== NULL
)
1415 if ((he
= el_malloc(sizeof(*he
))) == NULL
)
1418 if (history(h
, &ev
, H_DELDATA
, num
, &he
->data
) != 0) {
1424 if (history(h
, &ev
, H_GETSIZE
) == 0)
1425 history_length
= ev
.num
;
1432 * replace the line and data of the num-th entry
1435 replace_history_entry(int num
, const char *line
, histdata_t data
)
1441 if (h
== NULL
|| e
== NULL
)
1444 /* save current position */
1445 if (history(h
, &ev
, H_CURR
) != 0)
1449 /* start from the oldest */
1450 if (history(h
, &ev
, H_LAST
) != 0)
1451 return NULL
; /* error */
1453 if ((he
= el_malloc(sizeof(*he
))) == NULL
)
1456 /* look forwards for event matching specified offset */
1457 if (history(h
, &ev
, H_NEXT_EVDATA
, num
, &he
->data
))
1460 he
->line
= strdup(ev
.str
);
1461 if (he
->line
== NULL
)
1464 if (history(h
, &ev
, H_REPLACE
, line
, data
))
1467 /* restore pointer to where it was */
1468 if (history(h
, &ev
, H_SET
, curr_num
))
1478 * clear the history list - delete all entries
1485 (void)history(h
, &ev
, H_CLEAR
);
1491 * returns offset of the current history event
1499 if (history(h
, &ev
, H_CURR
) != 0)
1503 (void)history(h
, &ev
, H_FIRST
);
1505 while (ev
.num
!= curr_num
&& history(h
, &ev
, H_NEXT
) == 0)
1513 * returns current history event or NULL if there is no such event
1516 current_history(void)
1519 return _move_history(H_CURR
);
1524 * returns total number of bytes history events' data are using
1527 history_total_bytes(void)
1533 if (history(h
, &ev
, H_CURR
) != 0)
1537 (void)history(h
, &ev
, H_FIRST
);
1540 size
+= strlen(ev
.str
) * sizeof(*ev
.str
);
1541 while (history(h
, &ev
, H_NEXT
) == 0);
1543 /* get to the same position as before */
1544 history(h
, &ev
, H_PREV_EVENT
, curr_num
);
1551 * sets the position in the history list to ``pos''
1554 history_set_pos(int pos
)
1559 if (pos
>= history_length
|| pos
< 0)
1562 (void)history(h
, &ev
, H_CURR
);
1566 * use H_DELDATA to set to nth history (without delete) by passing
1569 if (history(h
, &ev
, H_DELDATA
, pos
, (void **)-1)) {
1570 (void)history(h
, &ev
, H_SET
, curr_num
);
1578 * returns previous event in history and shifts pointer accordingly
1581 previous_history(void)
1584 return _move_history(H_PREV
);
1589 * returns next event in history and shifts pointer accordingly
1595 return _move_history(H_NEXT
);
1600 * searches for first history event containing the str
1603 history_search(const char *str
, int direction
)
1609 if (history(h
, &ev
, H_CURR
) != 0)
1614 if ((strp
= strstr(ev
.str
, str
)) != NULL
)
1615 return (int)(strp
- ev
.str
);
1616 if (history(h
, &ev
, direction
< 0 ? H_NEXT
:H_PREV
) != 0)
1619 (void)history(h
, &ev
, H_SET
, curr_num
);
1625 * searches for first history event beginning with str
1628 history_search_prefix(const char *str
, int direction
)
1632 return (history(h
, &ev
, direction
< 0 ?
1633 H_PREV_STR
: H_NEXT_STR
, str
));
1638 * search for event in history containing str, starting at offset
1639 * abs(pos); continue backward, if pos<0, forward otherwise
1643 history_search_pos(const char *str
,
1644 int direction
__attribute__((__unused__
)), int pos
)
1649 off
= (pos
> 0) ? pos
: -pos
;
1650 pos
= (pos
> 0) ? 1 : -1;
1652 if (history(h
, &ev
, H_CURR
) != 0)
1656 if (history_set_pos(off
) != 0 || history(h
, &ev
, H_CURR
) != 0)
1660 if (strstr(ev
.str
, str
))
1662 if (history(h
, &ev
, (pos
< 0) ? H_PREV
: H_NEXT
) != 0)
1666 /* set "current" pointer back to previous state */
1667 (void)history(h
, &ev
,
1668 pos
< 0 ? H_NEXT_EVENT
: H_PREV_EVENT
, curr_num
);
1674 /********************************/
1675 /* completion functions */
1678 tilde_expand(char *name
)
1680 return fn_tilde_expand(name
);
1684 filename_completion_function(const char *name
, int state
)
1686 return fn_filename_completion_function(name
, state
);
1690 * a completion generator for usernames; returns _first_ username
1691 * which starts with supplied text
1692 * text contains a partial username preceded by random character
1693 * (usually '~'); state resets search from start (??? should we do that anyway)
1694 * it's callers responsibility to free returned value
1697 username_completion_function(const char *text
, int state
)
1699 #if defined(HAVE_GETPW_R_POSIX) || defined(HAVE_GETPW_R_DRAFT)
1700 struct passwd pwres
;
1703 struct passwd
*pass
= NULL
;
1705 if (text
[0] == '\0')
1715 #if defined(HAVE_GETPW_R_POSIX) || defined(HAVE_GETPW_R_DRAFT)
1716 getpwent_r(&pwres
, pwbuf
, sizeof(pwbuf
), &pass
) == 0 && pass
!= NULL
1718 (pass
= getpwent()) != NULL
1720 && text
[0] == pass
->pw_name
[0]
1721 && strcmp(text
, pass
->pw_name
) == 0)
1728 return strdup(pass
->pw_name
);
1733 * el-compatible wrapper to send TSTP on ^Z
1736 static unsigned char
1737 _el_rl_tstp(EditLine
*el
__attribute__((__unused__
)), int ch
__attribute__((__unused__
)))
1739 (void)kill(0, SIGTSTP
);
1744 * Display list of strings in columnar format on readline's output stream.
1745 * 'matches' is list of strings, 'len' is number of strings in 'matches',
1746 * 'max' is maximum length of string in 'matches'.
1749 rl_display_match_list(char **matches
, int len
, int max
)
1752 fn_display_match_list(e
, matches
, (size_t)len
, (size_t)max
);
1757 _rl_completion_append_character_function(const char *dummy
1758 __attribute__((__unused__
)))
1761 buf
[0] = (char)rl_completion_append_character
;
1768 * complete word at current point
1772 rl_complete(int ignore
__attribute__((__unused__
)), int invoking_key
)
1775 static ct_buffer_t wbreak_conv
, sprefix_conv
;
1779 if (h
== NULL
|| e
== NULL
)
1782 if (rl_inhibit_completion
) {
1784 arr
[0] = (char)invoking_key
;
1786 el_insertstr(e
, arr
);
1790 if (rl_completion_word_break_hook
!= NULL
)
1791 breakchars
= (*rl_completion_word_break_hook
)();
1793 breakchars
= rl_basic_word_break_characters
;
1795 /* Just look at how many global variables modify this operation! */
1796 return fn_complete(e
,
1797 (CPFunction
*)rl_completion_entry_function
,
1798 rl_attempted_completion_function
,
1799 ct_decode_string(rl_basic_word_break_characters
, &wbreak_conv
),
1800 ct_decode_string(breakchars
, &sprefix_conv
),
1801 _rl_completion_append_character_function
,
1802 (size_t)rl_completion_query_items
,
1803 &rl_completion_type
, &rl_attempted_completion_over
,
1804 &rl_point
, &rl_end
);
1811 static unsigned char
1812 _el_rl_complete(EditLine
*el
__attribute__((__unused__
)), int ch
)
1814 return (unsigned char)rl_complete(0, ch
);
1818 * misc other functions
1822 * bind key c to readline-type function func
1825 rl_bind_key(int c
, rl_command_func_t
*func
)
1829 if (h
== NULL
|| e
== NULL
)
1832 if (func
== rl_insert
) {
1833 /* XXX notice there is no range checking of ``c'' */
1834 e
->el_map
.key
[c
] = ED_INSERT
;
1842 * read one key from input - handles chars pushed back
1843 * to input stream also
1848 char fooarr
[2 * sizeof(int)];
1850 if (e
== NULL
|| h
== NULL
)
1853 return el_getc(e
, fooarr
);
1858 * reset the terminal
1862 rl_reset_terminal(const char *p
__attribute__((__unused__
)))
1865 if (h
== NULL
|| e
== NULL
)
1872 * insert character ``c'' back into input stream, ``count'' times
1875 rl_insert(int count
, int c
)
1879 if (h
== NULL
|| e
== NULL
)
1882 /* XXX - int -> char conversion can lose on multichars */
1886 for (; count
> 0; count
--)
1893 rl_insert_text(const char *text
)
1895 if (!text
|| *text
== 0)
1898 if (h
== NULL
|| e
== NULL
)
1901 if (el_insertstr(e
, text
) < 0)
1903 return (int)strlen(text
);
1908 rl_newline(int count
__attribute__((__unused__
)),
1909 int c
__attribute__((__unused__
)))
1912 * Readline-4.0 appears to ignore the args.
1914 return rl_insert(1, '\n');
1918 static unsigned char
1919 rl_bind_wrapper(EditLine
*el
__attribute__((__unused__
)), unsigned char c
)
1928 /* If rl_done was set by the above call, deal with it here */
1936 rl_add_defun(const char *name
, Function
*fun
, int c
)
1939 if ((size_t)c
>= sizeof(map
) / sizeof(map
[0]) || c
< 0)
1941 map
[(unsigned char)c
] = fun
;
1942 el_set(e
, EL_ADDFN
, name
, name
, rl_bind_wrapper
);
1943 vis(dest
, c
, VIS_WHITE
|VIS_NOSLASH
, 0);
1944 el_set(e
, EL_BIND
, dest
, name
, NULL
);
1949 rl_callback_read_char(void)
1951 int count
= 0, done
= 0;
1952 const char *buf
= el_gets(e
, &count
);
1955 if (buf
== NULL
|| count
-- <= 0)
1957 if (count
== 0 && buf
[0] == e
->el_tty
.t_c
[TS_IO
][C_EOF
])
1959 if (buf
[count
] == '\n' || buf
[count
] == '\r')
1962 if (done
&& rl_linefunc
!= NULL
) {
1963 el_set(e
, EL_UNBUFFERED
, 0);
1965 if ((wbuf
= strdup(buf
)) != NULL
)
1969 (*(void (*)(const char *))rl_linefunc
)(wbuf
);
1970 //el_set(e, EL_UNBUFFERED, 1);
1975 rl_callback_handler_install(const char *prompt
, VCPFunction
*linefunc
)
1980 (void)rl_set_prompt(prompt
);
1981 rl_linefunc
= linefunc
;
1982 el_set(e
, EL_UNBUFFERED
, 1);
1986 rl_callback_handler_remove(void)
1988 el_set(e
, EL_UNBUFFERED
, 0);
1996 a
[0] = (char)e
->el_tty
.t_c
[TS_IO
][C_REPRINT
];
2002 rl_get_previous_history(int count
, int key
)
2014 rl_prep_terminal(int meta_flag
__attribute__((__unused__
)))
2016 el_set(e
, EL_PREP_TERM
, 1);
2020 rl_deprep_terminal(void)
2022 el_set(e
, EL_PREP_TERM
, 0);
2026 rl_read_init_file(const char *s
)
2028 return el_source(e
, s
);
2032 rl_parse_and_bind(const char *line
)
2038 tok
= tok_init(NULL
);
2039 tok_str(tok
, line
, &argc
, &argv
);
2040 argc
= el_parse(e
, argc
, argv
);
2042 return argc
? 1 : 0;
2046 rl_variable_bind(const char *var
, const char *value
)
2049 * The proper return value is undocument, but this is what the
2050 * readline source seems to do.
2052 return el_set(e
, EL_BIND
, "", var
, value
, NULL
) == -1 ? 1 : 0;
2056 rl_stuff_char(int c
)
2062 el_insertstr(e
, buf
);
2066 _rl_event_read_char(EditLine
*el
, char *cp
)
2069 ssize_t num_read
= 0;
2072 while (rl_event_hook
) {
2076 #if defined(FIONREAD)
2077 if (ioctl(el
->el_infd
, FIONREAD
, &n
) < 0)
2080 num_read
= read(el
->el_infd
, cp
, (size_t)1);
2083 #elif defined(F_SETFL) && defined(O_NDELAY)
2084 if ((n
= fcntl(el
->el_infd
, F_GETFL
, 0)) < 0)
2086 if (fcntl(el
->el_infd
, F_SETFL
, n
|O_NDELAY
) < 0)
2088 num_read
= read(el
->el_infd
, cp
, 1);
2089 if (fcntl(el
->el_infd
, F_SETFL
, n
))
2092 /* not non-blocking, but what you gonna do? */
2093 num_read
= read(el
->el_infd
, cp
, 1);
2097 if (num_read
< 0 && errno
== EAGAIN
)
2104 el_set(el
, EL_GETCFN
, EL_BUILTIN_GETCFN
);
2105 return (int)num_read
;
2109 _rl_update_pos(void)
2111 const LineInfo
*li
= el_line(e
);
2113 rl_point
= (int)(li
->cursor
- li
->buffer
);
2114 rl_end
= (int)(li
->lastchar
- li
->buffer
);
2118 rl_get_screen_size(int *rows
, int *cols
)
2121 el_get(e
, EL_GETTC
, "li", rows
, (void *)0);
2123 el_get(e
, EL_GETTC
, "co", cols
, (void *)0);
2127 rl_set_screen_size(int rows
, int cols
)
2130 (void)snprintf(buf
, sizeof(buf
), "%d", rows
);
2131 el_set(e
, EL_SETTC
, "li", buf
, NULL
);
2132 (void)snprintf(buf
, sizeof(buf
), "%d", cols
);
2133 el_set(e
, EL_SETTC
, "co", buf
, NULL
);
2137 rl_completion_matches(const char *str
, rl_compentry_func_t
*fun
)
2139 size_t len
, max
, i
, j
, min
;
2140 char **list
, *match
, *a
, *b
;
2144 if ((list
= el_malloc(max
* sizeof(*list
))) == NULL
)
2147 while ((match
= (*fun
)(str
, (int)(len
- 1))) != NULL
) {
2148 list
[len
++] = match
;
2152 if ((nl
= el_realloc(list
, max
* sizeof(*nl
))) == NULL
)
2161 if ((list
[0] = strdup(list
[1])) == NULL
)
2165 qsort(&list
[1], len
- 1, sizeof(*list
),
2166 (int (*)(const void *, const void *)) strcmp
);
2168 for (i
= 1, a
= list
[i
]; i
< len
- 1; i
++, a
= b
) {
2170 for (j
= 0; a
[j
] && a
[j
] == b
[j
]; j
++)
2175 if (min
== 0 && *str
) {
2176 if ((list
[0] = strdup(str
)) == NULL
)
2179 if ((list
[0] = el_malloc((min
+ 1) * sizeof(*list
[0]))) == NULL
)
2181 (void)memcpy(list
[0], list
[1], min
);
2182 list
[0][min
] = '\0';
2192 rl_filename_completion_function (const char *text
, int state
)
2194 return fn_filename_completion_function(text
, state
);
2198 rl_forced_update_display(void)
2200 el_set(e
, EL_REFRESH
);
2204 _rl_abort_internal(void)
2212 _rl_qsort_string_compare(char **s1
, char **s2
)
2214 return strcoll(*s1
, *s2
);
2218 history_get_history_state(void)
2222 if ((hs
= el_malloc(sizeof(*hs
))) == NULL
)
2224 hs
->length
= history_length
;
2230 rl_kill_text(int from
__attribute__((__unused__
)),
2231 int to
__attribute__((__unused__
)))
2237 rl_make_bare_keymap(void)
2250 rl_set_keymap(Keymap k
__attribute__((__unused__
)))
2256 rl_generic_bind(int type
__attribute__((__unused__
)),
2257 const char * keyseq
__attribute__((__unused__
)),
2258 const char * data
__attribute__((__unused__
)),
2259 Keymap k
__attribute__((__unused__
)))
2266 rl_bind_key_in_map(int key
__attribute__((__unused__
)),
2267 rl_command_func_t
*fun
__attribute__((__unused__
)),
2268 Keymap k
__attribute__((__unused__
)))
2273 /* unsupported, but needed by python */
2275 rl_cleanup_after_signal(void)
2280 rl_on_new_line(void)
2286 rl_free_line_state(void)