1 /* $NetBSD: readline.c,v 1.21 2002/03/18 16:20:36 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.
18 * 3. All advertising materials mentioning features or use of this software
19 * must display the following acknowledgement:
20 * This product includes software developed by the NetBSD
21 * Foundation, Inc. and its contributors.
22 * 4. Neither the name of The NetBSD Foundation nor the names of its
23 * contributors may be used to endorse or promote products derived
24 * from this software without specific prior written permission.
26 * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
27 * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
28 * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
29 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
30 * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
31 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
32 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
33 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
34 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
35 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
36 * POSSIBILITY OF SUCH DAMAGE.
41 #if !defined(lint) && !defined(SCCSID)
42 __RCSID("$NetBSD: readline.c,v 1.21 2002/03/18 16:20:36 christos Exp $");
43 #endif /* not lint && not SCCSID */
45 #include <sys/types.h>
63 #include "fcns.h" /* for EL_NUM_FCNS */
65 /* for rl_complete() */
68 /* see comment at the #ifdef for sense of this */
71 /* readline compatibility stuff - look at readline sources/documentation */
72 /* to see what these variables mean */
73 const char *rl_library_version = "EditLine wrapper";
74 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;
85 int history_base = 1; /* probably never subject to change */
86 int history_length = 0;
87 int max_input_history = 0;
88 char history_expansion_char = '!';
89 char history_subst_char = '^';
90 char *history_no_expand_chars = expand_chars;
91 Function *history_inhibit_expansion_function = NULL;
93 int rl_inhibit_completion = 0;
94 int rl_attempted_completion_over = 0;
95 char *rl_basic_word_break_characters = break_chars;
96 char *rl_completer_word_break_characters = NULL;
97 char *rl_completer_quote_characters = NULL;
98 CPFunction *rl_completion_entry_function = NULL;
99 CPPFunction *rl_attempted_completion_function = NULL;
102 * This is set to character indicating type of completion being done by
103 * rl_complete_internal(); this is available for application completion
106 int rl_completion_type = 0;
109 * If more than this number of items results from query for possible
110 * completions, we ask user if they are sure to really display the list.
112 int rl_completion_query_items = 100;
115 * List of characters which are word break characters, but should be left
116 * in the parsed text when it is passed to the completion function.
117 * Shell uses this to help determine what kind of completing to do.
119 char *rl_special_prefixes = (char *)NULL;
122 * This is the character appended to the completed words if at the end of
123 * the line. Default is ' ' (a space).
125 int rl_completion_append_character = ' ';
127 /* stuff below is used internally by libedit for readline emulation */
129 /* if not zero, non-unique completions always show list of possible matches */
130 static int _rl_complete_show_all = 0;
132 static History *h = NULL;
133 static EditLine *e = NULL;
134 static int el_rl_complete_cmdnum = 0;
136 /* internal functions */
137 static unsigned char _el_rl_complete(EditLine *, int);
138 static char *_get_prompt(EditLine *);
139 static HIST_ENTRY *_move_history(int);
140 static int _history_search_gen(const char *, int, int);
141 static int _history_expand_command(const char *, size_t, char **);
142 static char *_rl_compat_sub(const char *, const char *,
144 static int rl_complete_internal(int);
145 static int _rl_qsort_string_compare(const void *, const void *);
148 * needed for prompt switching in readline()
150 static char *el_rl_prompt = NULL;
155 _get_prompt(EditLine *el)
157 return (el_rl_prompt);
162 * generic function for moving around history
165 _move_history(int op)
168 static HIST_ENTRY rl_he;
170 if (history(h, &ev, op) != 0)
171 return (HIST_ENTRY *) NULL;
181 * READLINE compatibility stuff
185 * initialize rl compat stuff
204 rl_outstream = stdout;
207 * See if we don't really want to run the editor
209 if (tcgetattr(fileno(rl_instream), &t) != -1 && (t.c_lflag & ECHO) == 0)
212 e = el_init(rl_readline_name, rl_instream, rl_outstream, stderr);
215 el_set(e, EL_EDITMODE, 0);
221 history(h, &ev, H_SETSIZE, INT_MAX); /* unlimited */
223 max_input_history = INT_MAX;
224 el_set(e, EL_HIST, history, h);
226 /* for proper prompt printing in readline() */
227 el_rl_prompt = strdup("");
228 el_set(e, EL_PROMPT, _get_prompt);
229 el_set(e, EL_SIGNAL, 1);
231 /* set default mode to "emacs"-style and read setting afterwards */
232 /* so this can be overriden */
233 el_set(e, EL_EDITOR, "emacs");
236 * Word completition - this has to go AFTER rebinding keys
239 el_set(e, EL_ADDFN, "rl_complete",
240 "ReadLine compatible completition function",
242 el_set(e, EL_BIND, "^I", "rl_complete", NULL);
245 * Find out where the rl_complete function was added; this is
246 * used later to detect that lastcmd was also rl_complete.
248 for(i=EL_NUM_FCNS; i < e->el_map.nfunc; i++) {
249 if (e->el_map.func[i] == _el_rl_complete) {
250 el_rl_complete_cmdnum = i;
255 /* read settings from configuration file */
259 * Unfortunately, some applications really do use rl_point
260 * and rl_line_buffer directly.
263 /* a cheesy way to get rid of const cast. */
264 rl_line_buffer = memchr(li->buffer, *li->buffer, 1);
265 rl_point = rl_end = 0;
272 * read one line from input stream and return it, chomping
273 * trailing newline (if there is any)
276 readline(const char *prompt)
283 if (e == NULL || h == NULL)
286 /* update prompt accordingly to what has been passed */
289 if (strcmp(el_rl_prompt, prompt) != 0) {
291 el_rl_prompt = strdup(prompt);
293 /* get one line from input stream */
294 ret = el_gets(e, &count);
296 if (ret && count > 0) {
301 if (buf[lastidx] == '\n')
306 history(h, &ev, H_GETSIZE);
307 history_length = ev.num;
317 * is normally called before application starts to use
318 * history expansion functions
323 if (h == NULL || e == NULL)
329 * substitute ``what'' with ``with'', returning resulting string; if
330 * globally == 1, substitutes all occurences of what, otherwise only the
334 _rl_compat_sub(const char *str, const char *what, const char *with,
338 const char *temp, *new;
339 int len, with_len, what_len, add;
342 result = malloc((size = 16));
344 with_len = strlen(with);
345 what_len = strlen(what);
348 new = strstr(temp, what);
352 if (i + add + 1 >= size) {
354 result = realloc(result, size);
356 (void) strncpy(&result[len], temp, i);
358 (void) strcpy(&result[len], with); /* safe */
360 temp = new + what_len;
363 if (len + add + 1 >= size) {
365 result = realloc(result, size);
367 (void) strcpy(&result[len], temp); /* safe */
371 } while (temp && globally);
379 * the real function doing history expansion - takes as argument command
380 * to do and data upon which the command should be executed
381 * does expansion the way I've understood readline documentation
382 * word designator ``%'' isn't supported (yet ?)
384 * returns 0 if data was not modified, 1 if it was and 2 if the string
385 * should be only printed and not executed; in case of error,
386 * returns -1 and *result points to NULL
387 * it's callers responsibility to free() string returned in *result
390 _history_expand_command(const char *command, size_t cmdlen, char **result)
392 char **arr, *tempcmd, *line, *search = NULL, *cmd;
393 const char *event_data = NULL;
394 static char *from = NULL, *to = NULL;
395 int start = -1, end = -1, max, i, idx;
396 int h_on = 0, t_on = 0, r_on = 0, e_on = 0, p_on = 0, g_on = 0;
397 int event_num = 0, retval;
402 cmd = alloca(cmdlen + 1);
403 (void) strncpy(cmd, command, cmdlen);
407 /* find out which event to take */
408 if (cmd[idx] == history_expansion_char) {
409 event_num = history_length;
415 while (cmd[off] && !strchr(":^$*-%", cmd[off]))
417 num = atoi(&cmd[idx]);
421 event_num += history_length + 1;
423 int prefix = 1, curr_num;
427 if (cmd[idx] == '?') {
429 if (cmd[off - 1] == '?')
431 else if (cmd[off] != '\n' && cmd[off] != '\0')
435 search = alloca(len + 1);
436 (void) strncpy(search, &cmd[idx], len);
439 if (history(h, &ev, H_CURR) != 0)
444 retval = history_search_prefix(search, -1);
446 retval = history_search(search, -1);
449 fprintf(rl_outstream, "%s: Event not found\n",
453 if (history(h, &ev, H_CURR) != 0)
457 /* roll back to original position */
458 history(h, &ev, H_NEXT_EVENT, curr_num);
463 if (!event_data && event_num >= 0) {
465 rl_he = history_get(event_num);
468 event_data = rl_he->line;
478 start = end = 1, cmd++;
479 else if (*cmd == '$')
480 start = end = -1, cmd++;
481 else if (*cmd == '*')
482 start = 1, end = -1, cmd++;
483 else if (isdigit((unsigned char) *cmd)) {
489 for (; isdigit((unsigned char) *cmd); cmd++);
492 if (shifted && *cmd == '-') {
493 if (!isdigit((unsigned char) *(cmd + 1)))
497 for (; isdigit((unsigned char) *cmd); cmd++);
499 } else if (shifted && *cmd == '*')
507 line = strdup(event_data);
508 for (; *cmd; cmd++) {
511 else if (*cmd == 'h')
512 h_on = 1 | g_on, g_on = 0;
513 else if (*cmd == 't')
514 t_on = 1 | g_on, g_on = 0;
515 else if (*cmd == 'r')
516 r_on = 1 | g_on, g_on = 0;
517 else if (*cmd == 'e')
518 e_on = 1 | g_on, g_on = 0;
519 else if (*cmd == 'p')
520 p_on = 1 | g_on, g_on = 0;
521 else if (*cmd == 'g')
523 else if (*cmd == 's' || *cmd == '&') {
524 char *what, *with, delim;
528 if (*cmd == '&' && (from == NULL || to == NULL))
530 else if (*cmd == 's') {
531 delim = *(++cmd), cmd++;
533 what = realloc(from, size);
535 for (; *cmd && *cmd != delim; cmd++) {
537 && *(cmd + 1) == delim)
549 from = strdup(search);
556 cmd++; /* shift after delim */
561 with = realloc(to, size);
563 from_len = strlen(from);
564 for (; *cmd && *cmd != delim; cmd++) {
565 if (len + from_len + 1 >= size) {
566 size += from_len + 1;
567 with = realloc(with, size);
571 (void) strcpy(&with[len], from);
576 && (*(cmd + 1) == delim
577 || *(cmd + 1) == '&'))
584 tempcmd = _rl_compat_sub(line, from, to,
593 arr = history_tokenize(line);
594 free(line); /* no more needed */
595 if (arr && *arr == NULL)
596 free(arr), arr = NULL;
600 /* find out max valid idx to array of array */
602 for (i = 0; arr[i]; i++)
606 /* set boundaries to something relevant */
610 end = max - ((end < -1) ? 1 : 0);
612 /* check boundaries ... */
613 if (start > max || end > max || start > end) {
614 for (i = 0; i <= max; i++) {
617 free(arr), arr = (char **) NULL;
621 for (i = 0; i <= max; i++) {
623 if (h_on && (i == 1 || h_on > 1) &&
624 (temp = strrchr(arr[i], '/')))
626 if (t_on && (i == 1 || t_on > 1) &&
627 (temp = strrchr(arr[i], '/')))
628 (void) strcpy(arr[i], temp + 1);
629 if (r_on && (i == 1 || r_on > 1) &&
630 (temp = strrchr(arr[i], '.')))
632 if (e_on && (i == 1 || e_on > 1) &&
633 (temp = strrchr(arr[i], '.')))
634 (void) strcpy(arr[i], temp);
637 cmdsize = 1, cmdlen = 0;
638 tempcmd = malloc(cmdsize);
639 for (i = start; start <= i && i <= end; i++) {
642 arr_len = strlen(arr[i]);
643 if (cmdlen + arr_len + 1 >= cmdsize) {
644 cmdsize += arr_len + 1;
645 tempcmd = realloc(tempcmd, cmdsize);
647 (void) strcpy(&tempcmd[cmdlen], arr[i]); /* safe */
649 tempcmd[cmdlen++] = ' '; /* add a space */
651 while (cmdlen > 0 && isspace((unsigned char) tempcmd[cmdlen - 1]))
653 tempcmd[cmdlen] = '\0';
657 for (i = 0; i <= max; i++)
659 free(arr), arr = (char **) NULL;
660 return (p_on) ? 2 : 1;
665 * csh-style history expansion
668 history_expand(char *str, char **output)
670 int i, retval = 0, idx;
674 if (h == NULL || e == NULL)
677 *output = strdup(str); /* do it early */
679 if (str[0] == history_subst_char) {
680 /* ^foo^foo2^ is equivalent to !!:s^foo^foo2^ */
681 temp = alloca(4 + strlen(str) + 1);
682 temp[0] = temp[1] = history_expansion_char;
685 (void) strcpy(temp + 4, str);
688 #define ADD_STRING(what, len) \
690 if (idx + len + 1 > size) \
691 result = realloc(result, (size += len + 1)); \
692 (void)strncpy(&result[idx], what, len); \
694 result[idx] = '\0'; \
699 for (i = 0; str[i];) {
700 int start, j, loop_again;
706 for (; str[j]; j++) {
707 if (str[j] == '\\' &&
708 str[j + 1] == history_expansion_char) {
709 (void) strcpy(&str[j], &str[j + 1]);
714 while (str[j] && str[++j] != '?');
717 } else if (isspace((unsigned char) str[j]))
720 if (str[j] == history_expansion_char
721 && !strchr(history_no_expand_chars, str[j + 1])
722 && (!history_inhibit_expansion_function ||
723 (*history_inhibit_expansion_function)(str, j) == 0))
727 if (str[j] && str[j + 1] != '#' && loop_again) {
730 if (str[j] == history_expansion_char)
737 ADD_STRING(temp, len);
739 if (str[i] == '\0' || str[i] != history_expansion_char
740 || str[i + 1] == '#') {
743 ADD_STRING(temp, len);
750 retval = _history_expand_command(&str[i], (size_t) (j - i),
754 ADD_STRING(temp, len);
762 /* gdb 4.11 has been shipped with readline, where */
763 /* history_expand() returned -1 when the line */
764 /* should not be executed; in readline 2.1+ */
765 /* it should return 2 in such a case */
777 * Parse the string into individual tokens, similarily to how shell would do it.
780 history_tokenize(const char *str)
782 int size = 1, result_idx = 0, i, start;
784 char **result = NULL, *temp, delim = '\0';
786 for (i = 0; str[i]; i++) {
787 while (isspace((unsigned char) str[i]))
790 for (; str[i]; i++) {
791 if (str[i] == '\\') {
792 if (str[i+1] != '\0')
794 } else if (str[i] == delim)
797 (isspace((unsigned char) str[i]) ||
798 strchr("()<>;&|$", str[i])))
800 else if (!delim && strchr("'`\"", str[i]))
804 if (result_idx + 2 >= size) {
806 result = realloc(result, size * sizeof(char *));
809 temp = malloc(len + 1);
810 (void) strncpy(temp, &str[start], len);
812 result[result_idx++] = temp;
813 result[result_idx] = NULL;
821 * limit size of history record to ``max'' events
824 stifle_history(int max)
828 if (h == NULL || e == NULL)
831 if (history(h, &ev, H_SETSIZE, max) == 0)
832 max_input_history = max;
837 * "unlimit" size of history - set the limit to maximum allowed int value
840 unstifle_history(void)
845 history(h, &ev, H_SETSIZE, INT_MAX);
846 omax = max_input_history;
847 max_input_history = INT_MAX;
848 return (omax); /* some value _must_ be returned */
853 history_is_stifled(void)
856 /* cannot return true answer */
857 return (max_input_history != INT_MAX);
862 * read history from a file given
865 read_history(const char *filename)
869 if (h == NULL || e == NULL)
871 return (history(h, &ev, H_LOAD, filename));
876 * write history to a file given
879 write_history(const char *filename)
883 if (h == NULL || e == NULL)
885 return (history(h, &ev, H_SAVE, filename));
890 * returns history ``num''th event
892 * returned pointer points to static variable
897 static HIST_ENTRY she;
901 if (h == NULL || e == NULL)
904 /* rewind to beginning */
905 if (history(h, &ev, H_CURR) != 0)
908 if (history(h, &ev, H_LAST) != 0)
909 return (NULL); /* error */
910 while (i < num && history(h, &ev, H_PREV) == 0)
913 return (NULL); /* not so many entries */
918 /* rewind history to the same event it was before */
919 (void) history(h, &ev, H_FIRST);
920 (void) history(h, &ev, H_NEXT_EVENT, curr_num);
927 * add the line to history table
930 add_history(const char *line)
934 if (h == NULL || e == NULL)
937 (void) history(h, &ev, H_ENTER, line);
938 if (history(h, &ev, H_GETSIZE) == 0)
939 history_length = ev.num;
941 return (!(history_length > 0)); /* return 0 if all is okay */
946 * clear the history list - delete all entries
953 history(h, &ev, H_CLEAR);
958 * returns offset of the current history event
966 if (history(h, &ev, H_CURR) != 0)
970 history(h, &ev, H_FIRST);
972 while (ev.num != curr_num && history(h, &ev, H_NEXT) == 0)
980 * returns current history event or NULL if there is no such event
983 current_history(void)
986 return (_move_history(H_CURR));
991 * returns total number of bytes history events' data are using
994 history_total_bytes(void)
999 if (history(h, &ev, H_CURR) != 0)
1003 history(h, &ev, H_FIRST);
1006 size += strlen(ev.str);
1007 while (history(h, &ev, H_NEXT) == 0);
1009 /* get to the same position as before */
1010 history(h, &ev, H_PREV_EVENT, curr_num);
1017 * sets the position in the history list to ``pos''
1020 history_set_pos(int pos)
1025 if (pos > history_length || pos < 0)
1028 history(h, &ev, H_CURR);
1030 history(h, &ev, H_FIRST);
1032 while (off < pos && history(h, &ev, H_NEXT) == 0)
1035 if (off != pos) { /* do a rollback in case of error */
1036 history(h, &ev, H_FIRST);
1037 history(h, &ev, H_NEXT_EVENT, curr_num);
1045 * returns previous event in history and shifts pointer accordingly
1048 previous_history(void)
1051 return (_move_history(H_PREV));
1056 * returns next event in history and shifts pointer accordingly
1062 return (_move_history(H_NEXT));
1067 * generic history search function
1070 _history_search_gen(const char *str, int direction, int pos)
1076 if (history(h, &ev, H_CURR) != 0)
1081 strp = strstr(ev.str, str);
1082 if (strp && (pos < 0 || &ev.str[pos] == strp))
1083 return (int) (strp - ev.str);
1084 if (history(h, &ev, direction < 0 ? H_PREV : H_NEXT) != 0)
1088 history(h, &ev, direction < 0 ? H_NEXT_EVENT : H_PREV_EVENT, curr_num);
1095 * searches for first history event containing the str
1098 history_search(const char *str, int direction)
1101 return (_history_search_gen(str, direction, -1));
1106 * searches for first history event beginning with str
1109 history_search_prefix(const char *str, int direction)
1112 return (_history_search_gen(str, direction, 0));
1117 * search for event in history containing str, starting at offset
1118 * abs(pos); continue backward, if pos<0, forward otherwise
1122 history_search_pos(const char *str, int direction, int pos)
1127 off = (pos > 0) ? pos : -pos;
1128 pos = (pos > 0) ? 1 : -1;
1130 if (history(h, &ev, H_CURR) != 0)
1134 if (history_set_pos(off) != 0 || history(h, &ev, H_CURR) != 0)
1139 if (strstr(ev.str, str))
1141 if (history(h, &ev, (pos < 0) ? H_PREV : H_NEXT) != 0)
1145 /* set "current" pointer back to previous state */
1146 history(h, &ev, (pos < 0) ? H_NEXT_EVENT : H_PREV_EVENT, curr_num);
1152 /********************************/
1153 /* completition functions */
1156 * does tilde expansion of strings of type ``~user/foo''
1157 * if ``user'' isn't valid user name or ``txt'' doesn't start
1158 * w/ '~', returns pointer to strdup()ed copy of ``txt''
1160 * it's callers's responsibility to free() returned string
1163 tilde_expand(char *txt)
1165 struct passwd *pass;
1170 return (strdup(txt));
1172 temp = strchr(txt + 1, '/');
1174 temp = strdup(txt + 1);
1176 len = temp - txt + 1; /* text until string after slash */
1178 (void) strncpy(temp, txt + 1, len - 2);
1179 temp[len - 2] = '\0';
1181 pass = getpwnam(temp);
1182 free(temp); /* value no more needed */
1184 return (strdup(txt));
1186 /* update pointer txt to point at string immedially following */
1190 temp = malloc(strlen(pass->pw_dir) + 1 + strlen(txt) + 1);
1191 (void) sprintf(temp, "%s/%s", pass->pw_dir, txt);
1198 * return first found file name starting by the ``text'' or NULL if no
1199 * such file can be found.
1200 * The first ``state'' matches are ignored.
1202 * it's caller's responsibility to free returned string
1205 filename_completion_function(const char *text, int state)
1208 char *filename = NULL, *dirname = NULL;
1209 size_t filename_len = 0;
1210 struct dirent *entry;
1214 temp = strrchr(text, '/');
1217 filename = realloc(filename, strlen(temp) + 1);
1218 (void) strcpy(filename, temp);
1219 len = temp - text; /* including last slash */
1220 dirname = realloc(dirname, len + 1);
1221 (void) strncpy(dirname, text, len);
1222 dirname[len] = '\0';
1224 filename = strdup(text);
1228 /* support for ``~user'' syntax */
1229 if (dirname && *dirname == '~') {
1230 temp = tilde_expand(dirname);
1231 dirname = realloc(dirname, strlen(temp) + 1);
1232 (void) strcpy(dirname, temp); /* safe */
1233 free(temp); /* no longer needed */
1235 /* will be used in cycle */
1236 filename_len = strlen(filename);
1238 dir = opendir(dirname ? dirname : ".");
1240 return (NULL); /* cannot open the directory */
1242 /* find the match */
1243 while ((entry = readdir(dir)) != NULL) {
1244 /* otherwise, get first entry where first */
1245 /* filename_len characters are equal */
1247 #if defined(__SVR4) || defined(__linux__)
1248 strlen(entry->d_name) >= filename_len
1250 entry->d_namlen >= filename_len
1252 && strncmp(entry->d_name, filename,
1258 if (entry) { /* match found */
1261 #if defined(__SVR4) || defined(__linux__)
1262 len = strlen(entry->d_name) +
1264 len = entry->d_namlen +
1266 ((dirname) ? strlen(dirname) : 0) + 1 + 1;
1268 (void) sprintf(temp, "%s%s",
1269 dirname ? dirname : "", entry->d_name); /* safe */
1271 /* test, if it's directory */
1272 if (stat(temp, &stbuf) == 0 && S_ISDIR(stbuf.st_mode))
1273 strcat(temp, "/"); /* safe */
1283 * a completion generator for usernames; returns _first_ username
1284 * which starts with supplied text
1285 * text contains a partial username preceded by random character
1286 * (usually '~'); state is ignored
1287 * it's callers responsibility to free returned value
1290 username_completion_function(const char *text, int state)
1294 if (text[0] == '\0')
1303 while ((pwd = getpwent()) && text[0] == pwd->pw_name[0]
1304 && strcmp(text, pwd->pw_name) == 0);
1310 return (strdup(pwd->pw_name));
1315 * el-compatible wrapper around rl_complete; needed for key binding
1318 static unsigned char
1319 _el_rl_complete(EditLine *el, int ch)
1321 return (unsigned char) rl_complete(0, ch);
1326 * returns list of completitions for text given
1329 completion_matches(const char *text, CPFunction *genfunc)
1331 char **match_list = NULL, *retstr, *prevstr;
1332 size_t match_list_len, max_equal, which, i;
1335 if (h == NULL || e == NULL)
1340 while ((retstr = (*genfunc) (text, matches)) != NULL) {
1341 if (matches + 1 >= match_list_len) {
1342 match_list_len <<= 1;
1343 match_list = realloc(match_list,
1344 match_list_len * sizeof(char *));
1346 match_list[++matches] = retstr;
1350 return (char **) NULL; /* nothing found */
1352 /* find least denominator and insert it to match_list[0] */
1354 prevstr = match_list[1];
1355 max_equal = strlen(prevstr);
1356 for (; which <= matches; which++) {
1357 for (i = 0; i < max_equal &&
1358 prevstr[i] == match_list[which][i]; i++)
1363 retstr = malloc(max_equal + 1);
1364 (void) strncpy(retstr, match_list[1], max_equal);
1365 retstr[max_equal] = '\0';
1366 match_list[0] = retstr;
1368 /* add NULL as last pointer to the array */
1369 if (matches + 1 >= match_list_len)
1370 match_list = realloc(match_list,
1371 (match_list_len + 1) * sizeof(char *));
1372 match_list[matches + 1] = (char *) NULL;
1374 return (match_list);
1378 * Sort function for qsort(). Just wrapper around strcasecmp().
1381 _rl_qsort_string_compare(i1, i2)
1382 const void *i1, *i2;
1384 /* LINTED const castaway */
1385 const char *s1 = ((const char **)i1)[0];
1386 /* LINTED const castaway */
1387 const char *s2 = ((const char **)i2)[0];
1389 return strcasecmp(s1, s2);
1393 * Display list of strings in columnar format on readline's output stream.
1394 * 'matches' is list of strings, 'len' is number of strings in 'matches',
1395 * 'max' is maximum length of string in 'matches'.
1398 rl_display_match_list (matches, len, max)
1402 int i, idx, limit, count;
1403 int screenwidth = e->el_term.t_size.h;
1406 * Find out how many entries can be put on one line, count
1407 * with two spaces between strings.
1409 limit = screenwidth / (max + 2);
1413 /* how many lines of output */
1414 count = len / limit;
1415 if (count * limit < len)
1418 /* Sort the items if they are not already sorted. */
1419 qsort(&matches[1], (size_t)(len - 1), sizeof(char *),
1420 _rl_qsort_string_compare);
1423 for(; count > 0; count--) {
1424 for(i=0; i < limit && matches[idx]; i++, idx++)
1425 fprintf(e->el_outfile, "%-*s ", max, matches[idx]);
1426 fprintf(e->el_outfile, "\n");
1431 * Complete the word at or before point, called by rl_complete()
1432 * 'what_to_do' says what to do with the completion.
1433 * `?' means list the possible completions.
1434 * TAB means do standard completion.
1435 * `*' means insert all of the possible completions.
1436 * `!' means to do standard completion, and list all possible completions if
1437 * there is more than one.
1439 * Note: '*' support is not implemented
1442 rl_complete_internal(int what_to_do)
1444 CPFunction *complet_func;
1446 char *temp, **matches;
1450 rl_completion_type = what_to_do;
1452 if (h == NULL || e == NULL)
1455 complet_func = rl_completion_entry_function;
1457 complet_func = filename_completion_function;
1459 /* We now look backwards for the start of a filename/variable word */
1461 ctemp = (const char *) li->cursor;
1462 while (ctemp > li->buffer
1463 && !strchr(rl_basic_word_break_characters, ctemp[-1])
1464 && (!rl_special_prefixes
1465 || !strchr(rl_special_prefixes, ctemp[-1]) ) )
1468 len = li->cursor - ctemp;
1469 temp = alloca(len + 1);
1470 (void) strncpy(temp, ctemp, len);
1473 /* these can be used by function called in completion_matches() */
1474 /* or (*rl_attempted_completion_function)() */
1475 rl_point = li->cursor - li->buffer;
1476 rl_end = li->lastchar - li->buffer;
1478 if (!rl_attempted_completion_function)
1479 matches = completion_matches(temp, complet_func);
1481 int end = li->cursor - li->buffer;
1482 matches = (*rl_attempted_completion_function) (temp, (int)
1487 int i, retval = CC_REFRESH;
1488 int matches_num, maxlen, match_len, match_display=1;
1491 * Only replace the completed string with common part of
1492 * possible matches if there is possible completion.
1494 if (matches[0][0] != '\0') {
1495 el_deletestr(e, (int) len);
1496 el_insertstr(e, matches[0]);
1499 if (what_to_do == '?')
1500 goto display_matches;
1502 if (matches[2] == NULL && strcmp(matches[0], matches[1]) == 0) {
1504 * We found exact match. Add a space after
1505 * it, unless we do filename completition and the
1506 * object is a directory.
1508 size_t alen = strlen(matches[0]);
1509 if ((complet_func != filename_completion_function
1510 || (alen > 0 && (matches[0])[alen - 1] != '/'))
1511 && rl_completion_append_character) {
1513 buf[0] = rl_completion_append_character;
1515 el_insertstr(e, buf);
1517 } else if (what_to_do == '!') {
1520 * More than one match and requested to list possible
1524 for(i=1, maxlen=0; matches[i]; i++) {
1525 match_len = strlen(matches[i]);
1526 if (match_len > maxlen)
1529 matches_num = i - 1;
1531 /* newline to get on next line from command line */
1532 fprintf(e->el_outfile, "\n");
1535 * If there are too many items, ask user for display
1538 if (matches_num > rl_completion_query_items) {
1539 fprintf(e->el_outfile,
1540 "Display all %d possibilities? (y or n) ",
1542 fflush(e->el_outfile);
1543 if (getc(stdin) != 'y')
1545 fprintf(e->el_outfile, "\n");
1549 rl_display_match_list(matches, matches_num,
1551 retval = CC_REDISPLAY;
1552 } else if (matches[0][0]) {
1554 * There was some common match, but the name was
1555 * not complete enough. Next tab will print possible
1560 /* lcd is not a valid object - further specification */
1566 /* free elements of array and the array itself */
1567 for (i = 0; matches[i]; i++)
1569 free(matches), matches = NULL;
1578 * complete word at current point
1581 rl_complete(int ignore, int invoking_key)
1583 if (h == NULL || e == NULL)
1586 if (rl_inhibit_completion) {
1587 rl_insert(ignore, invoking_key);
1588 return (CC_REFRESH);
1589 } else if (e->el_state.lastcmd == el_rl_complete_cmdnum)
1590 return rl_complete_internal('?');
1591 else if (_rl_complete_show_all)
1592 return rl_complete_internal('!');
1594 return (rl_complete_internal(TAB));
1599 * misc other functions
1603 * bind key c to readline-type function func
1606 rl_bind_key(int c, int func(int, int))
1610 if (h == NULL || e == NULL)
1613 if (func == rl_insert) {
1614 /* XXX notice there is no range checking of ``c'' */
1615 e->el_map.key[c] = ED_INSERT;
1623 * read one key from input - handles chars pushed back
1624 * to input stream also
1629 char fooarr[2 * sizeof(int)];
1631 if (e == NULL || h == NULL)
1634 return (el_getc(e, fooarr));
1639 * reset the terminal
1643 rl_reset_terminal(const char *p)
1646 if (h == NULL || e == NULL)
1653 * insert character ``c'' back into input stream, ``count'' times
1656 rl_insert(int count, int c)
1660 if (h == NULL || e == NULL)
1663 /* XXX - int -> char conversion can lose on multichars */
1667 for (; count > 0; count--)