1 /* $NetBSD: readline.c,v 1.87 2009/12/30 23:54: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.87 2009/12/30 23:54:52 christos Exp $");
35 #endif /* not lint && not SCCSID */
37 #include <sys/types.h>
55 #include "readline/readline.h"
57 #include "fcns.h" /* for EL_NUM_FCNS */
59 #include "filecomplete.h"
61 void rl_prep_terminal(int);
62 void rl_deprep_terminal(void);
64 /* for rl_complete() */
67 /* see comment at the #ifdef for sense of this */
68 /* #define GDB_411_HACK */
70 /* readline compatibility stuff - look at readline sources/documentation */
71 /* to see what these variables mean */
72 const char *rl_library_version
= "EditLine wrapper";
73 int rl_readline_version
= RL_READLINE_VERSION
;
74 static char empty
[] = { '\0' };
75 static char expand_chars
[] = { ' ', '\t', '\n', '=', '(', '\0' };
76 static char break_chars
[] = { ' ', '\t', '\n', '"', '\\', '\'', '`', '@', '$',
77 '>', '<', '=', ';', '|', '&', '{', '(', '\0' };
78 char *rl_readline_name
= empty
;
79 FILE *rl_instream
= NULL
;
80 FILE *rl_outstream
= NULL
;
83 char *rl_line_buffer
= NULL
;
84 VCPFunction
*rl_linefunc
= NULL
;
86 VFunction
*rl_event_hook
= NULL
;
87 KEYMAP_ENTRY_ARRAY emacs_standard_keymap
,
91 int history_base
= 1; /* probably never subject to change */
92 int history_length
= 0;
93 int max_input_history
= 0;
94 char history_expansion_char
= '!';
95 char history_subst_char
= '^';
96 char *history_no_expand_chars
= expand_chars
;
97 Function
*history_inhibit_expansion_function
= NULL
;
98 char *history_arg_extract(int start
, int end
, const char *str
);
100 int rl_inhibit_completion
= 0;
101 int rl_attempted_completion_over
= 0;
102 char *rl_basic_word_break_characters
= break_chars
;
103 char *rl_completer_word_break_characters
= NULL
;
104 char *rl_completer_quote_characters
= NULL
;
105 Function
*rl_completion_entry_function
= NULL
;
106 CPPFunction
*rl_attempted_completion_function
= NULL
;
107 Function
*rl_pre_input_hook
= NULL
;
108 Function
*rl_startup1_hook
= NULL
;
109 int (*rl_getc_function
)(FILE *) = NULL
;
110 char *rl_terminal_name
= NULL
;
111 int rl_already_prompted
= 0;
112 int rl_filename_completion_desired
= 0;
113 int rl_ignore_completion_duplicates
= 0;
114 int rl_catch_signals
= 1;
115 int readline_echoing_p
= 1;
116 int _rl_print_completions_horizontally
= 0;
117 VFunction
*rl_redisplay_function
= NULL
;
118 Function
*rl_startup_hook
= NULL
;
119 VFunction
*rl_completion_display_matches_hook
= NULL
;
120 VFunction
*rl_prep_term_function
= (VFunction
*)rl_prep_terminal
;
121 VFunction
*rl_deprep_term_function
= (VFunction
*)rl_deprep_terminal
;
122 KEYMAP_ENTRY_ARRAY emacs_meta_keymap
;
125 static ct_buffer_t conv
;
129 * The current prompt string.
131 char *rl_prompt
= NULL
;
133 * This is set to character indicating type of completion being done by
134 * rl_complete_internal(); this is available for application completion
137 int rl_completion_type
= 0;
140 * If more than this number of items results from query for possible
141 * completions, we ask user if they are sure to really display the list.
143 int rl_completion_query_items
= 100;
146 * List of characters which are word break characters, but should be left
147 * in the parsed text when it is passed to the completion function.
148 * Shell uses this to help determine what kind of completing to do.
150 char *rl_special_prefixes
= NULL
;
153 * This is the character appended to the completed words if at the end of
154 * the line. Default is ' ' (a space).
156 int rl_completion_append_character
= ' ';
158 /* stuff below is used internally by libedit for readline emulation */
160 static TYPE(History
) *h
= NULL
;
161 static EditLine
*e
= NULL
;
162 static Function
*map
[256];
163 static jmp_buf topbuf
;
165 /* internal functions */
166 static unsigned char _el_rl_complete(EditLine
*, int);
167 static unsigned char _el_rl_tstp(EditLine
*, int);
168 static char *_get_prompt(EditLine
*);
169 static int _getc_function(EditLine
*, char *);
170 static HIST_ENTRY
*_move_history(int);
171 static int _history_expand_command(const char *, size_t, size_t,
173 static char *_rl_compat_sub(const char *, const char *,
175 static int _rl_event_read_char(EditLine
*, char *);
176 static void _rl_update_pos(void);
181 _get_prompt(EditLine
*el
__attribute__((__unused__
)))
183 rl_already_prompted
= 1;
189 * generic function for moving around history
192 _move_history(int op
)
195 static HIST_ENTRY rl_he
;
197 if (FUNW(history
)(h
, &ev
, op
) != 0)
198 return (HIST_ENTRY
*) NULL
;
200 rl_he
.line
= ct_encode_string(ev
.str
, &conv
);
208 * read one key from user defined input function
212 _getc_function(EditLine
*el
, char *c
)
216 i
= (*rl_getc_function
)(NULL
);
223 static const char _dothistory
[] = "/.history";
226 _default_history_file(void)
229 static char path
[PATH_MAX
];
233 if ((p
= getpwuid(getuid())) == NULL
)
235 strlcpy(path
, p
->pw_dir
, PATH_MAX
);
236 strlcat(path
, _dothistory
, PATH_MAX
);
241 * READLINE compatibility stuff
248 rl_set_prompt(const char *prompt
)
254 if (rl_prompt
!= NULL
&& strcmp(rl_prompt
, prompt
) == 0)
258 rl_prompt
= strdup(prompt
);
259 if (rl_prompt
== NULL
)
262 while ((p
= strchr(rl_prompt
, RL_PROMPT_END_IGNORE
)) != NULL
)
263 *p
= RL_PROMPT_START_IGNORE
;
269 * initialize rl compat stuff
287 rl_outstream
= stdout
;
290 * See if we don't really want to run the editor
292 if (tcgetattr(fileno(rl_instream
), &t
) != -1 && (t
.c_lflag
& ECHO
) == 0)
295 e
= el_init(rl_readline_name
, rl_instream
, rl_outstream
, stderr
);
298 FUN(el
,set
)(e
, EL_EDITMODE
, 0);
300 h
= FUN(history
,init
)();
304 FUNW(history
)(h
, &ev
, H_SETSIZE
, INT_MAX
); /* unlimited */
306 max_input_history
= INT_MAX
;
307 el_set(e
, EL_HIST
, history
, h
);
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 overriden */
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
);
347 /* read settings from configuration file */
351 * Unfortunately, some applications really do use rl_point
352 * and rl_line_buffer directly.
355 /* a cheesy way to get rid of const cast. */
356 rl_line_buffer
= memchr(li
->buffer
, *li
->buffer
, 1);
360 (*rl_startup_hook
)(NULL
, 0);
367 * read one line from input stream and return it, chomping
368 * trailing newline (if there is any)
371 readline(const char *p
)
374 const char * volatile prompt
= p
;
378 static int used_event_hook
;
380 if (e
== NULL
|| h
== NULL
)
385 (void)setjmp(topbuf
);
387 /* update prompt accordingly to what has been passed */
388 if (rl_set_prompt(prompt
) == -1)
391 if (rl_pre_input_hook
)
392 (*rl_pre_input_hook
)(NULL
, 0);
394 if (rl_event_hook
&& !(e
->el_flags
&NO_TTY
)) {
395 el_set(e
, EL_GETCFN
, _rl_event_read_char
);
399 if (!rl_event_hook
&& used_event_hook
) {
400 el_set(e
, EL_GETCFN
, EL_BUILTIN_GETCFN
);
404 rl_already_prompted
= 0;
406 /* get one line from input stream */
407 ret
= el_gets(e
, &count
);
409 if (ret
&& count
> 0) {
416 if (buf
[lastidx
] == '\n')
421 FUNW(history
)(h
, &ev
, H_GETSIZE
);
422 history_length
= ev
.num
;
432 * is normally called before application starts to use
433 * history expansion functions
438 if (h
== NULL
|| e
== NULL
)
444 * substitute ``what'' with ``with'', returning resulting string; if
445 * globally == 1, substitutes all occurrences of what, otherwise only the
449 _rl_compat_sub(const char *str
, const char *what
, const char *with
,
454 size_t len
, with_len
, what_len
;
457 with_len
= strlen(with
);
458 what_len
= strlen(what
);
460 /* calculate length we need for result */
463 if (*s
== *what
&& !strncmp(s
, what
, what_len
)) {
464 len
+= with_len
- what_len
;
471 r
= result
= malloc(len
+ 1);
476 if (*s
== *what
&& !strncmp(s
, what
, what_len
)) {
477 (void)strncpy(r
, with
, with_len
);
491 static char *last_search_pat
; /* last !?pat[?] search pattern */
492 static char *last_search_match
; /* last !?pat[?] that matched */
495 get_history_event(const char *cmd
, int *cindex
, int qchar
)
497 int idx
, sign
, sub
, num
, begin
, ret
;
504 if (cmd
[idx
++] != history_expansion_char
)
507 /* find out which event to take */
508 if (cmd
[idx
] == history_expansion_char
|| cmd
[idx
] == '\0') {
509 if (FUNW(history
)(h
, &ev
, H_FIRST
) != 0)
511 *cindex
= cmd
[idx
]? (idx
+ 1):idx
;
512 return ct_encode_string(ev
.str
, &conv
);
515 if (cmd
[idx
] == '-') {
520 if ('0' <= cmd
[idx
] && cmd
[idx
] <= '9') {
524 while (cmd
[idx
] && '0' <= cmd
[idx
] && cmd
[idx
] <= '9') {
525 num
= num
* 10 + cmd
[idx
] - '0';
529 num
= history_length
- num
+ 1;
531 if (!(rl_he
= history_get(num
)))
538 if (cmd
[idx
] == '?') {
544 if (cmd
[idx
] == '\n')
546 if (sub
&& cmd
[idx
] == '?')
548 if (!sub
&& (cmd
[idx
] == ':' || cmd
[idx
] == ' '
549 || cmd
[idx
] == '\t' || cmd
[idx
] == qchar
))
554 if (sub
&& cmd
[idx
] == '?')
556 if (sub
&& len
== 0 && last_search_pat
&& *last_search_pat
)
557 pat
= last_search_pat
;
561 if ((pat
= malloc(len
+ 1)) == NULL
)
563 (void)strncpy(pat
, cmd
+ begin
, len
);
567 if (FUNW(history
)(h
, &ev
, H_CURR
) != 0) {
568 if (pat
!= last_search_pat
)
575 if (pat
!= last_search_pat
) {
577 free(last_search_pat
);
578 last_search_pat
= pat
;
580 ret
= history_search(pat
, -1);
582 ret
= history_search_prefix(pat
, -1);
585 /* restore to end of list on failed search */
586 FUNW(history
)(h
, &ev
, H_FIRST
);
587 (void)fprintf(rl_outstream
, "%s: Event not found\n", pat
);
588 if (pat
!= last_search_pat
)
594 if (last_search_match
&& last_search_match
!= pat
)
595 free(last_search_match
);
596 last_search_match
= pat
;
599 if (pat
!= last_search_pat
)
602 if (FUNW(history
)(h
, &ev
, H_CURR
) != 0)
605 rptr
= ct_encode_string(ev
.str
, &conv
);
607 /* roll back to original position */
608 (void)FUNW(history
)(h
, &ev
, H_SET
, num
);
614 * the real function doing history expansion - takes as argument command
615 * to do and data upon which the command should be executed
616 * does expansion the way I've understood readline documentation
618 * returns 0 if data was not modified, 1 if it was and 2 if the string
619 * should be only printed and not executed; in case of error,
620 * returns -1 and *result points to NULL
621 * it's callers responsibility to free() string returned in *result
624 _history_expand_command(const char *command
, size_t offs
, size_t cmdlen
,
627 char *tmp
, *search
= NULL
, *aptr
;
628 const char *ptr
, *cmd
;
629 static char *from
= NULL
, *to
= NULL
;
630 int start
, end
, idx
, has_mods
= 0;
631 int p_on
= 0, g_on
= 0;
637 /* First get event specifier */
640 if (strchr(":^*$", command
[offs
+ 1])) {
643 * "!:" is shorthand for "!!:".
644 * "!^", "!*" and "!$" are shorthand for
645 * "!!:^", "!!:*" and "!!:$" respectively.
647 str
[0] = str
[1] = '!';
649 ptr
= get_history_event(str
, &idx
, 0);
650 idx
= (command
[offs
+ 1] == ':')? 1:0;
653 if (command
[offs
+ 1] == '#') {
654 /* use command so far */
655 if ((aptr
= malloc(offs
+ 1)) == NULL
)
657 (void)strncpy(aptr
, command
, offs
);
663 qchar
= (offs
> 0 && command
[offs
- 1] == '"')? '"':0;
664 ptr
= get_history_event(command
+ offs
, &idx
, qchar
);
666 has_mods
= command
[offs
+ idx
] == ':';
669 if (ptr
== NULL
&& aptr
== NULL
)
673 *result
= strdup(aptr
? aptr
: ptr
);
681 cmd
= command
+ offs
+ idx
+ 1;
683 /* Now parse any word designators */
685 if (*cmd
== '%') /* last word matched by ?pat? */
686 tmp
= strdup(last_search_match
? last_search_match
:"");
687 else if (strchr("^*$-0123456789", *cmd
)) {
690 start
= end
= 1, cmd
++;
691 else if (*cmd
== '$')
693 else if (*cmd
== '*')
695 else if (*cmd
== '-' || isdigit((unsigned char) *cmd
)) {
697 while (*cmd
&& '0' <= *cmd
&& *cmd
<= '9')
698 start
= start
* 10 + *cmd
++ - '0';
701 if (isdigit((unsigned char) cmd
[1])) {
704 while (*cmd
&& '0' <= *cmd
&& *cmd
<= '9')
705 end
= end
* 10 + *cmd
++ - '0';
706 } else if (cmd
[1] == '$') {
713 } else if (*cmd
== '*')
718 tmp
= history_arg_extract(start
, end
, aptr
? aptr
:ptr
);
720 (void)fprintf(rl_outstream
, "%s: Bad word specifier",
721 command
+ offs
+ idx
);
727 tmp
= strdup(aptr
? aptr
:ptr
);
732 if (*cmd
== '\0' || ((size_t)(cmd
- (command
+ offs
)) >= cmdlen
)) {
737 for (; *cmd
; cmd
++) {
740 else if (*cmd
== 'h') { /* remove trailing path */
741 if ((aptr
= strrchr(tmp
, '/')) != NULL
)
743 } else if (*cmd
== 't') { /* remove leading path */
744 if ((aptr
= strrchr(tmp
, '/')) != NULL
) {
745 aptr
= strdup(aptr
+ 1);
749 } else if (*cmd
== 'r') { /* remove trailing suffix */
750 if ((aptr
= strrchr(tmp
, '.')) != NULL
)
752 } else if (*cmd
== 'e') { /* remove all but suffix */
753 if ((aptr
= strrchr(tmp
, '.')) != NULL
) {
758 } else if (*cmd
== 'p') /* print only */
760 else if (*cmd
== 'g')
762 else if (*cmd
== 's' || *cmd
== '&') {
763 char *what
, *with
, delim
;
764 size_t len
, from_len
;
767 if (*cmd
== '&' && (from
== NULL
|| to
== NULL
))
769 else if (*cmd
== 's') {
770 delim
= *(++cmd
), cmd
++;
772 what
= realloc(from
, size
);
779 for (; *cmd
&& *cmd
!= delim
; cmd
++) {
780 if (*cmd
== '\\' && cmd
[1] == delim
)
784 nwhat
= realloc(what
,
800 from
= strdup(search
);
811 cmd
++; /* shift after delim */
816 with
= realloc(to
, size
);
823 from_len
= strlen(from
);
824 for (; *cmd
&& *cmd
!= delim
; cmd
++) {
825 if (len
+ from_len
+ 1 >= size
) {
827 size
+= from_len
+ 1;
828 nwith
= realloc(with
, size
);
838 (void)strcpy(&with
[len
], from
);
843 && (*(cmd
+ 1) == delim
844 || *(cmd
+ 1) == '&'))
852 aptr
= _rl_compat_sub(tmp
, from
, to
, g_on
);
866 * csh-style history expansion
869 history_expand(char *str
, char **output
)
875 if (h
== NULL
|| e
== NULL
)
878 if (history_expansion_char
== 0) {
879 *output
= strdup(str
);
884 if (str
[0] == history_subst_char
) {
885 /* ^foo^foo2^ is equivalent to !!:s^foo^foo2^ */
886 *output
= malloc(strlen(str
) + 4 + 1);
889 (*output
)[0] = (*output
)[1] = history_expansion_char
;
892 (void)strcpy((*output
) + 4, str
);
895 *output
= strdup(str
);
900 #define ADD_STRING(what, len, fr) \
902 if (idx + len + 1 > size) { \
903 char *nresult = realloc(result, (size += len + 1));\
904 if (nresult == NULL) { \
906 if (/*CONSTCOND*/fr) \
912 (void)strncpy(&result[idx], what, len); \
914 result[idx] = '\0'; \
920 for (i
= 0; str
[i
];) {
921 int qchar
, loop_again
;
922 size_t len
, start
, j
;
928 for (; str
[j
]; j
++) {
929 if (str
[j
] == '\\' &&
930 str
[j
+ 1] == history_expansion_char
) {
931 (void)strcpy(&str
[j
], &str
[j
+ 1]);
935 if (isspace((unsigned char) str
[j
])
939 if (str
[j
] == history_expansion_char
940 && !strchr(history_no_expand_chars
, str
[j
+ 1])
941 && (!history_inhibit_expansion_function
||
942 (*history_inhibit_expansion_function
)(str
,
947 if (str
[j
] && loop_again
) {
949 qchar
= (j
> 0 && str
[j
- 1] == '"' )? '"':0;
951 if (str
[j
] == history_expansion_char
)
957 ADD_STRING(&str
[start
], len
, 0);
959 if (str
[i
] == '\0' || str
[i
] != history_expansion_char
) {
961 ADD_STRING(&str
[i
], len
, 0);
968 ret
= _history_expand_command (str
, i
, (j
- i
), &tmp
);
969 if (ret
> 0 && tmp
) {
971 ADD_STRING(tmp
, len
, 1);
980 /* ret is 2 for "print only" option */
984 /* gdb 4.11 has been shipped with readline, where */
985 /* history_expand() returned -1 when the line */
986 /* should not be executed; in readline 2.1+ */
987 /* it should return 2 in such a case */
998 * Return a string consisting of arguments of "str" from "start" to "end".
1001 history_arg_extract(int start
, int end
, const char *str
)
1004 char **arr
, *result
= NULL
;
1006 arr
= history_tokenize(str
);
1009 if (arr
&& *arr
== NULL
)
1012 for (max
= 0; arr
[max
]; max
++)
1021 end
= (int)max
+ end
+ 1;
1025 if (start
< 0 || end
< 0 || (size_t)start
> max
||
1026 (size_t)end
> max
|| start
> end
)
1029 for (i
= start
, len
= 0; i
<= (size_t)end
; i
++)
1030 len
+= strlen(arr
[i
]) + 1;
1032 result
= malloc(len
);
1036 for (i
= start
, len
= 0; i
<= (size_t)end
; i
++) {
1037 (void)strcpy(result
+ len
, arr
[i
]);
1038 len
+= strlen(arr
[i
]);
1039 if (i
< (size_t)end
)
1040 result
[len
++] = ' ';
1045 for (i
= 0; arr
[i
]; i
++)
1053 * Parse the string into individual tokens,
1054 * similar to how shell would do it.
1057 history_tokenize(const char *str
)
1059 int size
= 1, idx
= 0, i
, start
;
1061 char **result
= NULL
, *temp
, delim
= '\0';
1063 for (i
= 0; str
[i
];) {
1064 while (isspace((unsigned char) str
[i
]))
1068 if (str
[i
] == '\\') {
1069 if (str
[i
+1] != '\0')
1071 } else if (str
[i
] == delim
)
1074 (isspace((unsigned char) str
[i
]) ||
1075 strchr("()<>;&|$", str
[i
])))
1077 else if (!delim
&& strchr("'`\"", str
[i
]))
1083 if (idx
+ 2 >= size
) {
1086 nresult
= realloc(result
, size
* sizeof(char *));
1087 if (nresult
== NULL
) {
1094 temp
= malloc(len
+ 1);
1096 for (i
= 0; i
< idx
; i
++)
1101 (void)strncpy(temp
, &str
[start
], len
);
1103 result
[idx
++] = temp
;
1113 * limit size of history record to ``max'' events
1116 stifle_history(int max
)
1120 if (h
== NULL
|| e
== NULL
)
1123 if (FUNW(history
)(h
, &ev
, H_SETSIZE
, max
) == 0)
1124 max_input_history
= max
;
1129 * "unlimit" size of history - set the limit to maximum allowed int value
1132 unstifle_history(void)
1137 FUNW(history
)(h
, &ev
, H_SETSIZE
, INT_MAX
);
1138 omax
= max_input_history
;
1139 max_input_history
= INT_MAX
;
1140 return (omax
); /* some value _must_ be returned */
1145 history_is_stifled(void)
1148 /* cannot return true answer */
1149 return (max_input_history
!= INT_MAX
);
1152 static const char _history_tmp_template
[] = "/tmp/.historyXXXXXX";
1155 history_truncate_file (const char *filename
, int nlines
)
1159 char template[sizeof(_history_tmp_template
)];
1167 if (filename
== NULL
&& (filename
= _default_history_file()) == NULL
)
1169 if ((fp
= fopen(filename
, "r+")) == NULL
)
1171 strcpy(template, _history_tmp_template
);
1172 if ((fd
= mkstemp(template)) == -1) {
1177 if ((tp
= fdopen(fd
, "r+")) == NULL
) {
1184 if (fread(buf
, sizeof(buf
), 1, fp
) != 1) {
1189 if (fseeko(fp
, (off_t
)sizeof(buf
) * count
, SEEK_SET
) ==
1194 left
= fread(buf
, 1, sizeof(buf
), fp
);
1202 } else if (fwrite(buf
, (size_t)left
, 1, tp
) != 1) {
1209 if (fwrite(buf
, sizeof(buf
), 1, tp
) != 1) {
1217 cp
= buf
+ left
- 1;
1221 while (--cp
>= buf
) {
1223 if (--nlines
== 0) {
1224 if (++cp
>= buf
+ sizeof(buf
)) {
1232 if (nlines
<= 0 || count
== 0)
1235 if (fseeko(tp
, (off_t
)sizeof(buf
) * count
, SEEK_SET
) < 0) {
1239 if (fread(buf
, sizeof(buf
), 1, tp
) != 1) {
1247 cp
= buf
+ sizeof(buf
);
1250 if (ret
|| nlines
> 0)
1253 if (fseeko(fp
, 0, SEEK_SET
) == (off_t
)-1) {
1258 if (fseeko(tp
, (off_t
)sizeof(buf
) * count
+ (cp
- buf
), SEEK_SET
) ==
1265 if ((left
= fread(buf
, 1, sizeof(buf
), tp
)) == 0) {
1270 if (fwrite(buf
, (size_t)left
, 1, fp
) != 1) {
1276 if((off
= ftello(fp
)) > 0)
1277 (void)ftruncate(fileno(fp
), off
);
1290 * read history from a file given
1293 read_history(const char *filename
)
1297 if (h
== NULL
|| e
== NULL
)
1299 if (filename
== NULL
&& (filename
= _default_history_file()) == NULL
)
1301 return (FUNW(history
)(h
, &ev
, H_LOAD
, filename
) == -1 ?
1302 (errno
? errno
: EINVAL
) : 0);
1307 * write history to a file given
1310 write_history(const char *filename
)
1314 if (h
== NULL
|| e
== NULL
)
1316 if (filename
== NULL
&& (filename
= _default_history_file()) == NULL
)
1318 return (FUNW(history
)(h
, &ev
, H_SAVE
, filename
) == -1 ?
1319 (errno
? errno
: EINVAL
) : 0);
1324 * returns history ``num''th event
1326 * returned pointer points to static variable
1329 history_get(int num
)
1331 static HIST_ENTRY she
;
1335 if (h
== NULL
|| e
== NULL
)
1338 /* save current position */
1339 if (FUNW(history
)(h
, &ev
, H_CURR
) != 0)
1343 /* start from the oldest */
1344 if (FUNW(history
)(h
, &ev
, H_LAST
) != 0)
1345 return (NULL
); /* error */
1347 /* look forwards for event matching specified offset */
1348 if (FUNW(history
)(h
, &ev
, H_NEXT_EVDATA
, num
, &she
.data
))
1351 she
.line
= ct_encode_string(ev
.str
, &conv
);
1353 /* restore pointer to where it was */
1354 (void)FUNW(history
)(h
, &ev
, H_SET
, curr_num
);
1361 * add the line to history table
1364 add_history(const char *line
)
1368 if (h
== NULL
|| e
== NULL
)
1371 (void)FUNW(history
)(h
, &ev
, H_ENTER
, line
);
1372 if (FUNW(history
)(h
, &ev
, H_GETSIZE
) == 0)
1373 history_length
= ev
.num
;
1375 return (!(history_length
> 0)); /* return 0 if all is okay */
1380 * remove the specified entry from the history list and return it.
1383 remove_history(int num
)
1388 if (h
== NULL
|| e
== NULL
)
1391 if ((he
= malloc(sizeof(*he
))) == NULL
)
1394 if (FUNW(history
)(h
, &ev
, H_DELDATA
, num
, &he
->data
) != 0) {
1399 he
->line
= ct_encode_string(ev
.str
, &conv
);
1400 if (FUNW(history
)(h
, &ev
, H_GETSIZE
) == 0)
1401 history_length
= ev
.num
;
1408 * replace the line and data of the num-th entry
1411 replace_history_entry(int num
, const char *line
, histdata_t data
)
1417 if (h
== NULL
|| e
== NULL
)
1420 /* save current position */
1421 if (FUNW(history
)(h
, &ev
, H_CURR
) != 0)
1425 /* start from the oldest */
1426 if (FUNW(history
)(h
, &ev
, H_LAST
) != 0)
1427 return NULL
; /* error */
1429 if ((he
= malloc(sizeof(*he
))) == NULL
)
1432 /* look forwards for event matching specified offset */
1433 if (FUNW(history
)(h
, &ev
, H_NEXT_EVDATA
, num
, &he
->data
))
1436 he
->line
= strdup(ct_encode_string(ev
.str
, &e
->el_scratch
));
1437 if (he
->line
== NULL
)
1440 if (FUNW(history
)(h
, &ev
, H_REPLACE
, line
, data
))
1443 /* restore pointer to where it was */
1444 if (FUNW(history
)(h
, &ev
, H_SET
, curr_num
))
1454 * clear the history list - delete all entries
1461 (void)FUNW(history
)(h
, &ev
, H_CLEAR
);
1467 * returns offset of the current history event
1475 if (FUNW(history
)(h
, &ev
, H_CURR
) != 0)
1479 (void)FUNW(history
)(h
, &ev
, H_FIRST
);
1481 while (ev
.num
!= curr_num
&& FUNW(history
)(h
, &ev
, H_NEXT
) == 0)
1489 * returns current history event or NULL if there is no such event
1492 current_history(void)
1495 return (_move_history(H_CURR
));
1500 * returns total number of bytes history events' data are using
1503 history_total_bytes(void)
1509 if (FUNW(history
)(h
, &ev
, H_CURR
) != 0)
1513 (void)FUNW(history
)(h
, &ev
, H_FIRST
);
1516 size
+= Strlen(ev
.str
) * sizeof(*ev
.str
);
1517 while (FUNW(history
)(h
, &ev
, H_NEXT
) == 0);
1519 /* get to the same position as before */
1520 FUNW(history
)(h
, &ev
, H_PREV_EVENT
, curr_num
);
1527 * sets the position in the history list to ``pos''
1530 history_set_pos(int pos
)
1535 if (pos
>= history_length
|| pos
< 0)
1538 (void)FUNW(history
)(h
, &ev
, H_CURR
);
1542 * use H_DELDATA to set to nth history (without delete) by passing
1545 if (FUNW(history
)(h
, &ev
, H_DELDATA
, pos
, (void **)-1)) {
1546 (void)FUNW(history
)(h
, &ev
, H_SET
, curr_num
);
1554 * returns previous event in history and shifts pointer accordingly
1557 previous_history(void)
1560 return (_move_history(H_PREV
));
1565 * returns next event in history and shifts pointer accordingly
1571 return (_move_history(H_NEXT
));
1576 * searches for first history event containing the str
1579 history_search(const char *str
, int direction
)
1586 if (FUNW(history
)(h
, &ev
, H_CURR
) != 0)
1590 wstr
= ct_decode_string(str
, &conv
);
1592 if ((strp
= Strstr(ev
.str
, wstr
)) != NULL
)
1593 return (int) (strp
- ev
.str
);
1594 if (FUNW(history
)(h
, &ev
, direction
< 0 ? H_NEXT
:H_PREV
) != 0)
1597 (void)FUNW(history
)(h
, &ev
, H_SET
, curr_num
);
1603 * searches for first history event beginning with str
1606 history_search_prefix(const char *str
, int direction
)
1610 return (FUNW(history
)(h
, &ev
, direction
< 0 ?
1611 H_PREV_STR
: H_NEXT_STR
, str
));
1616 * search for event in history containing str, starting at offset
1617 * abs(pos); continue backward, if pos<0, forward otherwise
1621 history_search_pos(const char *str
,
1622 int direction
__attribute__((__unused__
)), int pos
)
1628 off
= (pos
> 0) ? pos
: -pos
;
1629 pos
= (pos
> 0) ? 1 : -1;
1631 if (FUNW(history
)(h
, &ev
, H_CURR
) != 0)
1635 if (history_set_pos(off
) != 0 || FUNW(history
)(h
, &ev
, H_CURR
) != 0)
1638 wstr
= ct_decode_string(str
, &conv
);
1640 if (Strstr(ev
.str
, wstr
))
1642 if (FUNW(history
)(h
, &ev
, (pos
< 0) ? H_PREV
: H_NEXT
) != 0)
1646 /* set "current" pointer back to previous state */
1647 (void)FUNW(history
)(h
, &ev
,
1648 pos
< 0 ? H_NEXT_EVENT
: H_PREV_EVENT
, curr_num
);
1654 /********************************/
1655 /* completion functions */
1658 tilde_expand(char *name
)
1660 return fn_tilde_expand(name
);
1664 filename_completion_function(const char *name
, int state
)
1666 return fn_filename_completion_function(name
, state
);
1670 * a completion generator for usernames; returns _first_ username
1671 * which starts with supplied text
1672 * text contains a partial username preceded by random character
1673 * (usually '~'); state is ignored
1674 * it's callers responsibility to free returned value
1677 username_completion_function(const char *text
, int state
)
1679 struct passwd
*pwd
, pwres
;
1682 if (text
[0] == '\0')
1691 while (getpwent_r(&pwres
, pwbuf
, sizeof(pwbuf
), &pwd
) == 0
1692 && pwd
!= NULL
&& text
[0] == pwd
->pw_name
[0]
1693 && strcmp(text
, pwd
->pw_name
) == 0);
1699 return strdup(pwd
->pw_name
);
1704 * el-compatible wrapper to send TSTP on ^Z
1707 static unsigned char
1708 _el_rl_tstp(EditLine
*el
__attribute__((__unused__
)), int ch
__attribute__((__unused__
)))
1710 (void)kill(0, SIGTSTP
);
1715 * Display list of strings in columnar format on readline's output stream.
1716 * 'matches' is list of strings, 'len' is number of strings in 'matches',
1717 * 'max' is maximum length of string in 'matches'.
1720 rl_display_match_list(char **matches
, int len
, int max
)
1723 fn_display_match_list(e
, matches
, (size_t)len
, (size_t)max
);
1728 _rl_completion_append_character_function(const char *dummy
1729 __attribute__((__unused__
)))
1732 buf
[0] = rl_completion_append_character
;
1739 * complete word at current point
1743 rl_complete(int ignore
__attribute__((__unused__
)), int invoking_key
)
1746 static ct_buffer_t wbreak_conv
, sprefix_conv
;
1749 if (h
== NULL
|| e
== NULL
)
1752 if (rl_inhibit_completion
) {
1754 arr
[0] = (char)invoking_key
;
1756 el_insertstr(e
, arr
);
1757 return (CC_REFRESH
);
1760 /* Just look at how many global variables modify this operation! */
1761 return fn_complete(e
,
1762 (CPFunction
*)rl_completion_entry_function
,
1763 rl_attempted_completion_function
,
1764 ct_decode_string(rl_basic_word_break_characters
, &wbreak_conv
),
1765 ct_decode_string(rl_special_prefixes
, &sprefix_conv
),
1766 _rl_completion_append_character_function
,
1767 (size_t)rl_completion_query_items
,
1768 &rl_completion_type
, &rl_attempted_completion_over
,
1769 &rl_point
, &rl_end
);
1774 static unsigned char
1775 _el_rl_complete(EditLine
*el
__attribute__((__unused__
)), int ch
)
1777 return (unsigned char)rl_complete(0, ch
);
1781 * misc other functions
1785 * bind key c to readline-type function func
1788 rl_bind_key(int c
, rl_command_func_t
*func
)
1792 if (h
== NULL
|| e
== NULL
)
1795 if (func
== rl_insert
) {
1796 /* XXX notice there is no range checking of ``c'' */
1797 e
->el_map
.key
[c
] = ED_INSERT
;
1805 * read one key from input - handles chars pushed back
1806 * to input stream also
1811 char fooarr
[2 * sizeof(int)];
1813 if (e
== NULL
|| h
== NULL
)
1816 return (el_getc(e
, fooarr
));
1821 * reset the terminal
1825 rl_reset_terminal(const char *p
__attribute__((__unused__
)))
1828 if (h
== NULL
|| e
== NULL
)
1835 * insert character ``c'' back into input stream, ``count'' times
1838 rl_insert(int count
, int c
)
1842 if (h
== NULL
|| e
== NULL
)
1845 /* XXX - int -> char conversion can lose on multichars */
1849 for (; count
> 0; count
--)
1856 rl_insert_text(const char *text
)
1858 if (!text
|| *text
== 0)
1861 if (h
== NULL
|| e
== NULL
)
1864 if (el_insertstr(e
, text
) < 0)
1866 return (int)strlen(text
);
1871 rl_newline(int count
, int c
)
1874 * Readline-4.0 appears to ignore the args.
1876 return rl_insert(1, '\n');
1880 static unsigned char
1881 rl_bind_wrapper(EditLine
*el
, unsigned char c
)
1890 /* If rl_done was set by the above call, deal with it here */
1898 rl_add_defun(const char *name
, Function
*fun
, int c
)
1901 if ((size_t)c
>= sizeof(map
) / sizeof(map
[0]) || c
< 0)
1903 map
[(unsigned char)c
] = fun
;
1904 el_set(e
, EL_ADDFN
, name
, name
, rl_bind_wrapper
);
1905 vis(dest
, c
, VIS_WHITE
|VIS_NOSLASH
, 0);
1906 el_set(e
, EL_BIND
, dest
, name
);
1911 rl_callback_read_char()
1913 int count
= 0, done
= 0;
1914 const char *buf
= el_gets(e
, &count
);
1917 if (buf
== NULL
|| count
-- <= 0)
1919 if (count
== 0 && buf
[0] == e
->el_tty
.t_c
[TS_IO
][C_EOF
])
1921 if (buf
[count
] == '\n' || buf
[count
] == '\r')
1924 if (done
&& rl_linefunc
!= NULL
) {
1925 el_set(e
, EL_UNBUFFERED
, 0);
1927 if ((wbuf
= strdup(buf
)) != NULL
)
1931 (*(void (*)(const char *))rl_linefunc
)(wbuf
);
1932 //el_set(e, EL_UNBUFFERED, 1);
1937 rl_callback_handler_install(const char *prompt
, VCPFunction
*linefunc
)
1942 (void)rl_set_prompt(prompt
);
1943 rl_linefunc
= linefunc
;
1944 el_set(e
, EL_UNBUFFERED
, 1);
1948 rl_callback_handler_remove(void)
1950 el_set(e
, EL_UNBUFFERED
, 0);
1958 a
[0] = e
->el_tty
.t_c
[TS_IO
][C_REPRINT
];
1964 rl_get_previous_history(int count
, int key
)
1976 rl_prep_terminal(int meta_flag
)
1978 el_set(e
, EL_PREP_TERM
, 1);
1982 rl_deprep_terminal(void)
1984 el_set(e
, EL_PREP_TERM
, 0);
1988 rl_read_init_file(const char *s
)
1990 return(el_source(e
, s
));
1994 rl_parse_and_bind(const char *line
)
2000 tok
= tok_init(NULL
);
2001 tok_str(tok
, line
, &argc
, &argv
);
2002 argc
= el_parse(e
, argc
, argv
);
2004 return (argc
? 1 : 0);
2008 rl_variable_bind(const char *var
, const char *value
)
2011 * The proper return value is undocument, but this is what the
2012 * readline source seems to do.
2014 return ((el_set(e
, EL_BIND
, "", var
, value
) == -1) ? 1 : 0);
2018 rl_stuff_char(int c
)
2024 el_insertstr(e
, buf
);
2028 _rl_event_read_char(EditLine
*el
, char *cp
)
2031 ssize_t num_read
= 0;
2034 while (rl_event_hook
) {
2038 #if defined(FIONREAD)
2039 if (ioctl(el
->el_infd
, FIONREAD
, &n
) < 0)
2042 num_read
= read(el
->el_infd
, cp
, 1);
2045 #elif defined(F_SETFL) && defined(O_NDELAY)
2046 if ((n
= fcntl(el
->el_infd
, F_GETFL
, 0)) < 0)
2048 if (fcntl(el
->el_infd
, F_SETFL
, n
|O_NDELAY
) < 0)
2050 num_read
= read(el
->el_infd
, cp
, 1);
2051 if (fcntl(el
->el_infd
, F_SETFL
, n
))
2054 /* not non-blocking, but what you gonna do? */
2055 num_read
= read(el
->el_infd
, cp
, 1);
2059 if (num_read
< 0 && errno
== EAGAIN
)
2066 el_set(el
, EL_GETCFN
, EL_BUILTIN_GETCFN
);
2067 return (int)num_read
;
2071 _rl_update_pos(void)
2073 const LineInfo
*li
= el_line(e
);
2075 rl_point
= (int)(li
->cursor
- li
->buffer
);
2076 rl_end
= (int)(li
->lastchar
- li
->buffer
);
2080 rl_get_screen_size(int *rows
, int *cols
)
2083 el_get(e
, EL_GETTC
, "li", rows
);
2085 el_get(e
, EL_GETTC
, "co", cols
);
2089 rl_set_screen_size(int rows
, int cols
)
2092 (void)snprintf(buf
, sizeof(buf
), "%d", rows
);
2093 el_set(e
, EL_SETTC
, "li", buf
);
2094 (void)snprintf(buf
, sizeof(buf
), "%d", cols
);
2095 el_set(e
, EL_SETTC
, "co", buf
);
2099 rl_completion_matches(const char *str
, rl_compentry_func_t
*fun
)
2101 size_t len
, max
, i
, j
, min
;
2102 char **list
, *match
, *a
, *b
;
2106 if ((list
= malloc(max
* sizeof(*list
))) == NULL
)
2109 while ((match
= (*fun
)(str
, (int)(len
- 1))) != NULL
) {
2110 list
[len
++] = match
;
2114 if ((nl
= realloc(list
, max
* sizeof(*nl
))) == NULL
)
2123 if ((list
[0] = strdup(list
[1])) == NULL
)
2127 qsort(&list
[1], len
- 1, sizeof(*list
),
2128 (int (*)(const void *, const void *)) strcmp
);
2130 for (i
= 1, a
= list
[i
]; i
< len
- 1; i
++, a
= b
) {
2132 for (j
= 0; a
[j
] && a
[j
] == b
[j
]; j
++)
2137 if (min
== 0 && *str
) {
2138 if ((list
[0] = strdup(str
)) == NULL
)
2141 if ((list
[0] = malloc(min
+ 1)) == NULL
)
2143 (void)memcpy(list
[0], list
[1], min
);
2144 list
[0][min
] = '\0';
2154 rl_filename_completion_function (const char *text
, int state
)
2156 return fn_filename_completion_function(text
, state
);
2160 rl_forced_update_display(void)
2162 el_set(e
, EL_REFRESH
);
2166 _rl_abort_internal(void)
2174 _rl_qsort_string_compare(char **s1
, char **s2
)
2176 return strcoll(*s1
, *s2
);
2180 history_get_history_state(void)
2184 if ((hs
= malloc(sizeof(HISTORY_STATE
))) == NULL
)
2186 hs
->length
= history_length
;
2192 rl_kill_text(int from
, int to
)
2198 rl_make_bare_keymap(void)
2211 rl_set_keymap(Keymap k
)
2217 rl_generic_bind(int type
, const char * keyseq
, const char * data
, Keymap k
)
2224 rl_bind_key_in_map(int key
, rl_command_func_t
*fun
, Keymap k
)
2229 /* unsupported, but needed by python */
2231 rl_cleanup_after_signal(void)