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.
40 #if !defined(lint) && !defined(SCCSID)
41 __RCSID("$NetBSD: readline.c,v 1.21 2002/03/18 16:20:36 christos Exp $");
42 #endif /* not lint && not SCCSID */
44 #include <sys/types.h>
62 #include "fcns.h" /* for EL_NUM_FCNS */
64 /* for rl_complete() */
67 /* see comment at the #ifdef for sense of this */
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 static char empty[] = { '\0' };
74 static char expand_chars[] = { ' ', '\t', '\n', '=', '(', '\0' };
75 static char break_chars[] = { ' ', '\t', '\n', '"', '\\', '\'', '`', '@', '$',
76 '>', '<', '=', ';', '|', '&', '{', '(', '\0' };
77 char *rl_readline_name = empty;
78 FILE *rl_instream = NULL;
79 FILE *rl_outstream = NULL;
82 char *rl_line_buffer = NULL;
84 int history_base = 1; /* probably never subject to change */
85 int history_length = 0;
86 int max_input_history = 0;
87 char history_expansion_char = '!';
88 char history_subst_char = '^';
89 char *history_no_expand_chars = expand_chars;
90 Function *history_inhibit_expansion_function = NULL;
92 int rl_inhibit_completion = 0;
93 int rl_attempted_completion_over = 0;
94 char *rl_basic_word_break_characters = break_chars;
95 char *rl_completer_word_break_characters = NULL;
96 char *rl_completer_quote_characters = NULL;
97 CPFunction *rl_completion_entry_function = NULL;
98 CPPFunction *rl_attempted_completion_function = NULL;
101 * This is set to character indicating type of completion being done by
102 * rl_complete_internal(); this is available for application completion
105 int rl_completion_type = 0;
108 * If more than this number of items results from query for possible
109 * completions, we ask user if they are sure to really display the list.
111 int rl_completion_query_items = 100;
114 * List of characters which are word break characters, but should be left
115 * in the parsed text when it is passed to the completion function.
116 * Shell uses this to help determine what kind of completing to do.
118 char *rl_special_prefixes = (char *)NULL;
121 * This is the character appended to the completed words if at the end of
122 * the line. Default is ' ' (a space).
124 int rl_completion_append_character = ' ';
126 /* stuff below is used internally by libedit for readline emulation */
128 /* if not zero, non-unique completions always show list of possible matches */
129 static int _rl_complete_show_all = 0;
131 static History *h = NULL;
132 static EditLine *e = NULL;
133 static int el_rl_complete_cmdnum = 0;
135 /* internal functions */
136 static unsigned char _el_rl_complete(EditLine *, int);
137 static char *_get_prompt(EditLine *);
138 static HIST_ENTRY *_move_history(int);
139 static int _history_search_gen(const char *, int, int);
140 static int _history_expand_command(const char *, size_t, char **);
141 static char *_rl_compat_sub(const char *, const char *,
143 static int rl_complete_internal(int);
144 static int _rl_qsort_string_compare(const void *, const void *);
147 * needed for prompt switching in readline()
149 static char *el_rl_prompt = NULL;
154 _get_prompt(EditLine *el)
156 return (el_rl_prompt);
161 * generic function for moving around history
164 _move_history(int op)
167 static HIST_ENTRY rl_he;
169 if (history(h, &ev, op) != 0)
170 return (HIST_ENTRY *) NULL;
180 * READLINE compatibility stuff
184 * initialize rl compat stuff
203 rl_outstream = stdout;
206 * See if we don't really want to run the editor
208 if (tcgetattr(fileno(rl_instream), &t) != -1 && (t.c_lflag & ECHO) == 0)
211 e = el_init(rl_readline_name, rl_instream, rl_outstream, stderr);
214 el_set(e, EL_EDITMODE, 0);
220 history(h, &ev, H_SETSIZE, INT_MAX); /* unlimited */
222 max_input_history = INT_MAX;
223 el_set(e, EL_HIST, history, h);
225 /* for proper prompt printing in readline() */
226 el_rl_prompt = strdup("");
227 el_set(e, EL_PROMPT, _get_prompt);
228 el_set(e, EL_SIGNAL, 1);
230 /* set default mode to "emacs"-style and read setting afterwards */
231 /* so this can be overriden */
232 el_set(e, EL_EDITOR, "emacs");
235 * Word completition - this has to go AFTER rebinding keys
238 el_set(e, EL_ADDFN, "rl_complete",
239 "ReadLine compatible completition function",
241 el_set(e, EL_BIND, "^I", "rl_complete", NULL);
244 * Find out where the rl_complete function was added; this is
245 * used later to detect that lastcmd was also rl_complete.
247 for(i=EL_NUM_FCNS; i < e->el_map.nfunc; i++) {
248 if (e->el_map.func[i] == _el_rl_complete) {
249 el_rl_complete_cmdnum = i;
254 /* read settings from configuration file */
258 * Unfortunately, some applications really do use rl_point
259 * and rl_line_buffer directly.
262 /* a cheesy way to get rid of const cast. */
263 rl_line_buffer = memchr(li->buffer, *li->buffer, 1);
264 rl_point = rl_end = 0;
271 * read one line from input stream and return it, chomping
272 * trailing newline (if there is any)
275 readline(const char *prompt)
282 if (e == NULL || h == NULL)
285 /* update prompt accordingly to what has been passed */
288 if (strcmp(el_rl_prompt, prompt) != 0) {
290 el_rl_prompt = strdup(prompt);
292 /* get one line from input stream */
293 ret = el_gets(e, &count);
295 if (ret && count > 0) {
300 if (buf[lastidx] == '\n')
305 history(h, &ev, H_GETSIZE);
306 history_length = ev.num;
316 * is normally called before application starts to use
317 * history expansion functions
322 if (h == NULL || e == NULL)
328 * substitute ``what'' with ``with'', returning resulting string; if
329 * globally == 1, substitutes all occurences of what, otherwise only the
333 _rl_compat_sub(const char *str, const char *what, const char *with,
337 const char *temp, *new;
338 int len, with_len, what_len, add;
341 result = malloc((size = 16));
343 with_len = strlen(with);
344 what_len = strlen(what);
347 new = strstr(temp, what);
351 if (i + add + 1 >= size) {
353 result = realloc(result, size);
355 (void) strncpy(&result[len], temp, i);
357 (void) strcpy(&result[len], with); /* safe */
359 temp = new + what_len;
362 if (len + add + 1 >= size) {
364 result = realloc(result, size);
366 (void) strcpy(&result[len], temp); /* safe */
370 } while (temp && globally);
378 * the real function doing history expansion - takes as argument command
379 * to do and data upon which the command should be executed
380 * does expansion the way I've understood readline documentation
381 * word designator ``%'' isn't supported (yet ?)
383 * returns 0 if data was not modified, 1 if it was and 2 if the string
384 * should be only printed and not executed; in case of error,
385 * returns -1 and *result points to NULL
386 * it's callers responsibility to free() string returned in *result
389 _history_expand_command(const char *command, size_t cmdlen, char **result)
391 char **arr, *tempcmd, *line, *search = NULL, *cmd;
392 const char *event_data = NULL;
393 static char *from = NULL, *to = NULL;
394 int start = -1, end = -1, max, i, idx;
395 int h_on = 0, t_on = 0, r_on = 0, e_on = 0, p_on = 0, g_on = 0;
396 int event_num = 0, retval;
401 cmd = alloca(cmdlen + 1);
402 (void) strncpy(cmd, command, cmdlen);
406 /* find out which event to take */
407 if (cmd[idx] == history_expansion_char) {
408 event_num = history_length;
414 while (cmd[off] && !strchr(":^$*-%", cmd[off]))
416 num = atoi(&cmd[idx]);
420 event_num += history_length + 1;
422 int prefix = 1, curr_num;
426 if (cmd[idx] == '?') {
428 if (cmd[off - 1] == '?')
430 else if (cmd[off] != '\n' && cmd[off] != '\0')
434 search = alloca(len + 1);
435 (void) strncpy(search, &cmd[idx], len);
438 if (history(h, &ev, H_CURR) != 0)
443 retval = history_search_prefix(search, -1);
445 retval = history_search(search, -1);
448 fprintf(rl_outstream, "%s: Event not found\n",
452 if (history(h, &ev, H_CURR) != 0)
456 /* roll back to original position */
457 history(h, &ev, H_NEXT_EVENT, curr_num);
462 if (!event_data && event_num >= 0) {
464 rl_he = history_get(event_num);
467 event_data = rl_he->line;
477 start = end = 1, cmd++;
478 else if (*cmd == '$')
479 start = end = -1, cmd++;
480 else if (*cmd == '*')
481 start = 1, end = -1, cmd++;
482 else if (isdigit((unsigned char) *cmd)) {
488 for (; isdigit((unsigned char) *cmd); cmd++);
491 if (shifted && *cmd == '-') {
492 if (!isdigit((unsigned char) *(cmd + 1)))
496 for (; isdigit((unsigned char) *cmd); cmd++);
498 } else if (shifted && *cmd == '*')
506 line = strdup(event_data);
507 for (; *cmd; cmd++) {
510 else if (*cmd == 'h')
511 h_on = 1 | g_on, g_on = 0;
512 else if (*cmd == 't')
513 t_on = 1 | g_on, g_on = 0;
514 else if (*cmd == 'r')
515 r_on = 1 | g_on, g_on = 0;
516 else if (*cmd == 'e')
517 e_on = 1 | g_on, g_on = 0;
518 else if (*cmd == 'p')
519 p_on = 1 | g_on, g_on = 0;
520 else if (*cmd == 'g')
522 else if (*cmd == 's' || *cmd == '&') {
523 char *what, *with, delim;
527 if (*cmd == '&' && (from == NULL || to == NULL))
529 else if (*cmd == 's') {
530 delim = *(++cmd), cmd++;
532 what = realloc(from, size);
534 for (; *cmd && *cmd != delim; cmd++) {
536 && *(cmd + 1) == delim)
548 from = strdup(search);
555 cmd++; /* shift after delim */
560 with = realloc(to, size);
562 from_len = strlen(from);
563 for (; *cmd && *cmd != delim; cmd++) {
564 if (len + from_len + 1 >= size) {
565 size += from_len + 1;
566 with = realloc(with, size);
570 (void) strcpy(&with[len], from);
575 && (*(cmd + 1) == delim
576 || *(cmd + 1) == '&'))
583 tempcmd = _rl_compat_sub(line, from, to,
592 arr = history_tokenize(line);
593 free(line); /* no more needed */
594 if (arr && *arr == NULL)
595 free(arr), arr = NULL;
599 /* find out max valid idx to array of array */
601 for (i = 0; arr[i]; i++)
605 /* set boundaries to something relevant */
609 end = max - ((end < -1) ? 1 : 0);
611 /* check boundaries ... */
612 if (start > max || end > max || start > end) {
613 for (i = 0; i <= max; i++) {
616 free(arr), arr = (char **) NULL;
620 for (i = 0; i <= max; i++) {
622 if (h_on && (i == 1 || h_on > 1) &&
623 (temp = strrchr(arr[i], '/')))
625 if (t_on && (i == 1 || t_on > 1) &&
626 (temp = strrchr(arr[i], '/')))
627 (void) strcpy(arr[i], temp + 1);
628 if (r_on && (i == 1 || r_on > 1) &&
629 (temp = strrchr(arr[i], '.')))
631 if (e_on && (i == 1 || e_on > 1) &&
632 (temp = strrchr(arr[i], '.')))
633 (void) strcpy(arr[i], temp);
636 cmdsize = 1, cmdlen = 0;
637 tempcmd = malloc(cmdsize);
638 for (i = start; start <= i && i <= end; i++) {
641 arr_len = strlen(arr[i]);
642 if (cmdlen + arr_len + 1 >= cmdsize) {
643 cmdsize += arr_len + 1;
644 tempcmd = realloc(tempcmd, cmdsize);
646 (void) strcpy(&tempcmd[cmdlen], arr[i]); /* safe */
648 tempcmd[cmdlen++] = ' '; /* add a space */
650 while (cmdlen > 0 && isspace((unsigned char) tempcmd[cmdlen - 1]))
652 tempcmd[cmdlen] = '\0';
656 for (i = 0; i <= max; i++)
658 free(arr), arr = (char **) NULL;
659 return (p_on) ? 2 : 1;
664 * csh-style history expansion
667 history_expand(char *str, char **output)
669 int i, retval = 0, idx;
673 if (h == NULL || e == NULL)
676 *output = strdup(str); /* do it early */
678 if (str[0] == history_subst_char) {
679 /* ^foo^foo2^ is equivalent to !!:s^foo^foo2^ */
680 temp = alloca(4 + strlen(str) + 1);
681 temp[0] = temp[1] = history_expansion_char;
684 (void) strcpy(temp + 4, str);
687 #define ADD_STRING(what, len) \
689 if (idx + len + 1 > size) \
690 result = realloc(result, (size += len + 1)); \
691 (void)strncpy(&result[idx], what, len); \
693 result[idx] = '\0'; \
698 for (i = 0; str[i];) {
699 int start, j, loop_again;
705 for (; str[j]; j++) {
706 if (str[j] == '\\' &&
707 str[j + 1] == history_expansion_char) {
708 (void) strcpy(&str[j], &str[j + 1]);
713 while (str[j] && str[++j] != '?');
716 } else if (isspace((unsigned char) str[j]))
719 if (str[j] == history_expansion_char
720 && !strchr(history_no_expand_chars, str[j + 1])
721 && (!history_inhibit_expansion_function ||
722 (*history_inhibit_expansion_function)(str, j) == 0))
726 if (str[j] && str[j + 1] != '#' && loop_again) {
729 if (str[j] == history_expansion_char)
736 ADD_STRING(temp, len);
738 if (str[i] == '\0' || str[i] != history_expansion_char
739 || str[i + 1] == '#') {
742 ADD_STRING(temp, len);
749 retval = _history_expand_command(&str[i], (size_t) (j - i),
753 ADD_STRING(temp, len);
761 /* gdb 4.11 has been shipped with readline, where */
762 /* history_expand() returned -1 when the line */
763 /* should not be executed; in readline 2.1+ */
764 /* it should return 2 in such a case */
776 * Parse the string into individual tokens, similarily to how shell would do it.
779 history_tokenize(const char *str)
781 int size = 1, result_idx = 0, i, start;
783 char **result = NULL, *temp, delim = '\0';
785 for (i = 0; str[i]; i++) {
786 while (isspace((unsigned char) str[i]))
789 for (; str[i]; i++) {
790 if (str[i] == '\\') {
791 if (str[i+1] != '\0')
793 } else if (str[i] == delim)
796 (isspace((unsigned char) str[i]) ||
797 strchr("()<>;&|$", str[i])))
799 else if (!delim && strchr("'`\"", str[i]))
803 if (result_idx + 2 >= size) {
805 result = realloc(result, size * sizeof(char *));
808 temp = malloc(len + 1);
809 (void) strncpy(temp, &str[start], len);
811 result[result_idx++] = temp;
812 result[result_idx] = NULL;
820 * limit size of history record to ``max'' events
823 stifle_history(int max)
827 if (h == NULL || e == NULL)
830 if (history(h, &ev, H_SETSIZE, max) == 0)
831 max_input_history = max;
836 * "unlimit" size of history - set the limit to maximum allowed int value
839 unstifle_history(void)
844 history(h, &ev, H_SETSIZE, INT_MAX);
845 omax = max_input_history;
846 max_input_history = INT_MAX;
847 return (omax); /* some value _must_ be returned */
852 history_is_stifled(void)
855 /* cannot return true answer */
856 return (max_input_history != INT_MAX);
861 * read history from a file given
864 read_history(const char *filename)
868 if (h == NULL || e == NULL)
870 return (history(h, &ev, H_LOAD, filename));
875 * write history to a file given
878 write_history(const char *filename)
882 if (h == NULL || e == NULL)
884 return (history(h, &ev, H_SAVE, filename));
889 * returns history ``num''th event
891 * returned pointer points to static variable
896 static HIST_ENTRY she;
900 if (h == NULL || e == NULL)
903 /* rewind to beginning */
904 if (history(h, &ev, H_CURR) != 0)
907 if (history(h, &ev, H_LAST) != 0)
908 return (NULL); /* error */
909 while (i < num && history(h, &ev, H_PREV) == 0)
912 return (NULL); /* not so many entries */
917 /* rewind history to the same event it was before */
918 (void) history(h, &ev, H_FIRST);
919 (void) history(h, &ev, H_NEXT_EVENT, curr_num);
926 * add the line to history table
929 add_history(const char *line)
933 if (h == NULL || e == NULL)
936 (void) history(h, &ev, H_ENTER, line);
937 if (history(h, &ev, H_GETSIZE) == 0)
938 history_length = ev.num;
940 return (!(history_length > 0)); /* return 0 if all is okay */
945 * clear the history list - delete all entries
952 history(h, &ev, H_CLEAR);
957 * returns offset of the current history event
965 if (history(h, &ev, H_CURR) != 0)
969 history(h, &ev, H_FIRST);
971 while (ev.num != curr_num && history(h, &ev, H_NEXT) == 0)
979 * returns current history event or NULL if there is no such event
982 current_history(void)
985 return (_move_history(H_CURR));
990 * returns total number of bytes history events' data are using
993 history_total_bytes(void)
998 if (history(h, &ev, H_CURR) != 0)
1002 history(h, &ev, H_FIRST);
1005 size += strlen(ev.str);
1006 while (history(h, &ev, H_NEXT) == 0);
1008 /* get to the same position as before */
1009 history(h, &ev, H_PREV_EVENT, curr_num);
1016 * sets the position in the history list to ``pos''
1019 history_set_pos(int pos)
1024 if (pos > history_length || pos < 0)
1027 history(h, &ev, H_CURR);
1029 history(h, &ev, H_FIRST);
1031 while (off < pos && history(h, &ev, H_NEXT) == 0)
1034 if (off != pos) { /* do a rollback in case of error */
1035 history(h, &ev, H_FIRST);
1036 history(h, &ev, H_NEXT_EVENT, curr_num);
1044 * returns previous event in history and shifts pointer accordingly
1047 previous_history(void)
1050 return (_move_history(H_PREV));
1055 * returns next event in history and shifts pointer accordingly
1061 return (_move_history(H_NEXT));
1066 * generic history search function
1069 _history_search_gen(const char *str, int direction, int pos)
1075 if (history(h, &ev, H_CURR) != 0)
1080 strp = strstr(ev.str, str);
1081 if (strp && (pos < 0 || &ev.str[pos] == strp))
1082 return (int) (strp - ev.str);
1083 if (history(h, &ev, direction < 0 ? H_PREV : H_NEXT) != 0)
1087 history(h, &ev, direction < 0 ? H_NEXT_EVENT : H_PREV_EVENT, curr_num);
1094 * searches for first history event containing the str
1097 history_search(const char *str, int direction)
1100 return (_history_search_gen(str, direction, -1));
1105 * searches for first history event beginning with str
1108 history_search_prefix(const char *str, int direction)
1111 return (_history_search_gen(str, direction, 0));
1116 * search for event in history containing str, starting at offset
1117 * abs(pos); continue backward, if pos<0, forward otherwise
1121 history_search_pos(const char *str, int direction, int pos)
1126 off = (pos > 0) ? pos : -pos;
1127 pos = (pos > 0) ? 1 : -1;
1129 if (history(h, &ev, H_CURR) != 0)
1133 if (history_set_pos(off) != 0 || history(h, &ev, H_CURR) != 0)
1138 if (strstr(ev.str, str))
1140 if (history(h, &ev, (pos < 0) ? H_PREV : H_NEXT) != 0)
1144 /* set "current" pointer back to previous state */
1145 history(h, &ev, (pos < 0) ? H_NEXT_EVENT : H_PREV_EVENT, curr_num);
1151 /********************************/
1152 /* completition functions */
1155 * does tilde expansion of strings of type ``~user/foo''
1156 * if ``user'' isn't valid user name or ``txt'' doesn't start
1157 * w/ '~', returns pointer to strdup()ed copy of ``txt''
1159 * it's callers's responsibility to free() returned string
1162 tilde_expand(char *txt)
1164 struct passwd *pass;
1169 return (strdup(txt));
1171 temp = strchr(txt + 1, '/');
1173 temp = strdup(txt + 1);
1175 len = temp - txt + 1; /* text until string after slash */
1177 (void) strncpy(temp, txt + 1, len - 2);
1178 temp[len - 2] = '\0';
1180 pass = getpwnam(temp);
1181 free(temp); /* value no more needed */
1183 return (strdup(txt));
1185 /* update pointer txt to point at string immedially following */
1189 temp = malloc(strlen(pass->pw_dir) + 1 + strlen(txt) + 1);
1190 (void) sprintf(temp, "%s/%s", pass->pw_dir, txt);
1197 * return first found file name starting by the ``text'' or NULL if no
1198 * such file can be found.
1199 * The first ``state'' matches are ignored.
1201 * it's caller's responsibility to free returned string
1204 filename_completion_function(const char *text, int state)
1207 char *filename = NULL, *dirname = NULL;
1208 size_t filename_len = 0;
1209 struct dirent *entry;
1213 temp = strrchr(text, '/');
1216 filename = realloc(filename, strlen(temp) + 1);
1217 (void) strcpy(filename, temp);
1218 len = temp - text; /* including last slash */
1219 dirname = realloc(dirname, len + 1);
1220 (void) strncpy(dirname, text, len);
1221 dirname[len] = '\0';
1223 filename = strdup(text);
1227 /* support for ``~user'' syntax */
1228 if (dirname && *dirname == '~') {
1229 temp = tilde_expand(dirname);
1230 dirname = realloc(dirname, strlen(temp) + 1);
1231 (void) strcpy(dirname, temp); /* safe */
1232 free(temp); /* no longer needed */
1234 /* will be used in cycle */
1235 filename_len = strlen(filename);
1237 dir = opendir(dirname ? dirname : ".");
1241 return (NULL); /* cannot open the directory */
1244 /* find the match */
1245 while ((entry = readdir(dir)) != NULL) {
1246 /* otherwise, get first entry where first */
1247 /* filename_len characters are equal */
1249 #if defined(__SVR4) || defined(__linux__)
1250 strlen(entry->d_name) >= filename_len
1252 entry->d_namlen >= filename_len
1254 && strncmp(entry->d_name, filename,
1260 if (entry) { /* match found */
1263 #if defined(__SVR4) || defined(__linux__)
1264 len = strlen(entry->d_name) +
1266 len = entry->d_namlen +
1268 ((dirname) ? strlen(dirname) : 0) + 1 + 1;
1270 (void) sprintf(temp, "%s%s",
1271 dirname ? dirname : "", entry->d_name); /* safe */
1273 /* test, if it's directory */
1274 if (stat(temp, &stbuf) == 0 && S_ISDIR(stbuf.st_mode))
1275 strcat(temp, "/"); /* safe */
1287 * a completion generator for usernames; returns _first_ username
1288 * which starts with supplied text
1289 * text contains a partial username preceded by random character
1290 * (usually '~'); state is ignored
1291 * it's callers responsibility to free returned value
1294 username_completion_function(const char *text, int state)
1298 if (text[0] == '\0')
1307 while ((pwd = getpwent()) && text[0] == pwd->pw_name[0]
1308 && strcmp(text, pwd->pw_name) == 0);
1314 return (strdup(pwd->pw_name));
1319 * el-compatible wrapper around rl_complete; needed for key binding
1322 static unsigned char
1323 _el_rl_complete(EditLine *el, int ch)
1325 return (unsigned char) rl_complete(0, ch);
1330 * returns list of completitions for text given
1333 completion_matches(const char *text, CPFunction *genfunc)
1335 char **match_list = NULL, *retstr, *prevstr;
1336 size_t match_list_len, max_equal, which, i;
1339 if (h == NULL || e == NULL)
1344 while ((retstr = (*genfunc) (text, matches)) != NULL) {
1345 if (matches + 1 >= match_list_len) {
1346 match_list_len <<= 1;
1347 match_list = realloc(match_list,
1348 match_list_len * sizeof(char *));
1350 match_list[++matches] = retstr;
1354 return (char **) NULL; /* nothing found */
1356 /* find least denominator and insert it to match_list[0] */
1358 prevstr = match_list[1];
1359 max_equal = strlen(prevstr);
1360 for (; which <= matches; which++) {
1361 for (i = 0; i < max_equal &&
1362 prevstr[i] == match_list[which][i]; i++)
1367 retstr = malloc(max_equal + 1);
1368 (void) strncpy(retstr, match_list[1], max_equal);
1369 retstr[max_equal] = '\0';
1370 match_list[0] = retstr;
1372 /* add NULL as last pointer to the array */
1373 if (matches + 1 >= match_list_len)
1374 match_list = realloc(match_list,
1375 (match_list_len + 1) * sizeof(char *));
1376 match_list[matches + 1] = (char *) NULL;
1378 return (match_list);
1382 * Sort function for qsort(). Just wrapper around strcasecmp().
1385 _rl_qsort_string_compare(i1, i2)
1386 const void *i1, *i2;
1388 /* LINTED const castaway */
1389 const char *s1 = ((const char **)i1)[0];
1390 /* LINTED const castaway */
1391 const char *s2 = ((const char **)i2)[0];
1393 return strcasecmp(s1, s2);
1397 * Display list of strings in columnar format on readline's output stream.
1398 * 'matches' is list of strings, 'len' is number of strings in 'matches',
1399 * 'max' is maximum length of string in 'matches'.
1402 rl_display_match_list (matches, len, max)
1406 int i, idx, limit, count;
1407 int screenwidth = e->el_term.t_size.h;
1410 * Find out how many entries can be put on one line, count
1411 * with two spaces between strings.
1413 limit = screenwidth / (max + 2);
1417 /* how many lines of output */
1418 count = len / limit;
1419 if (count * limit < len)
1422 /* Sort the items if they are not already sorted. */
1423 qsort(&matches[1], (size_t)(len - 1), sizeof(char *),
1424 _rl_qsort_string_compare);
1427 for(; count > 0; count--) {
1428 for(i=0; i < limit && matches[idx]; i++, idx++)
1429 fprintf(e->el_outfile, "%-*s ", max, matches[idx]);
1430 fprintf(e->el_outfile, "\n");
1435 * Complete the word at or before point, called by rl_complete()
1436 * 'what_to_do' says what to do with the completion.
1437 * `?' means list the possible completions.
1438 * TAB means do standard completion.
1439 * `*' means insert all of the possible completions.
1440 * `!' means to do standard completion, and list all possible completions if
1441 * there is more than one.
1443 * Note: '*' support is not implemented
1446 rl_complete_internal(int what_to_do)
1448 CPFunction *complet_func;
1450 char *temp, **matches;
1454 rl_completion_type = what_to_do;
1456 if (h == NULL || e == NULL)
1459 complet_func = rl_completion_entry_function;
1461 complet_func = filename_completion_function;
1463 /* We now look backwards for the start of a filename/variable word */
1465 ctemp = (const char *) li->cursor;
1466 while (ctemp > li->buffer
1467 && !strchr(rl_basic_word_break_characters, ctemp[-1])
1468 && (!rl_special_prefixes
1469 || !strchr(rl_special_prefixes, ctemp[-1]) ) )
1472 len = li->cursor - ctemp;
1473 temp = alloca(len + 1);
1474 (void) strncpy(temp, ctemp, len);
1477 /* these can be used by function called in completion_matches() */
1478 /* or (*rl_attempted_completion_function)() */
1479 rl_point = li->cursor - li->buffer;
1480 rl_end = li->lastchar - li->buffer;
1482 if (!rl_attempted_completion_function)
1483 matches = completion_matches(temp, complet_func);
1485 int end = li->cursor - li->buffer;
1486 matches = (*rl_attempted_completion_function) (temp, (int)
1491 int i, retval = CC_REFRESH;
1492 int matches_num, maxlen, match_len, match_display=1;
1495 * Only replace the completed string with common part of
1496 * possible matches if there is possible completion.
1498 if (matches[0][0] != '\0') {
1499 el_deletestr(e, (int) len);
1500 el_insertstr(e, matches[0]);
1503 if (what_to_do == '?')
1504 goto display_matches;
1506 if (matches[2] == NULL && strcmp(matches[0], matches[1]) == 0) {
1508 * We found exact match. Add a space after
1509 * it, unless we do filename completition and the
1510 * object is a directory.
1512 size_t alen = strlen(matches[0]);
1513 if ((complet_func != filename_completion_function
1514 || (alen > 0 && (matches[0])[alen - 1] != '/'))
1515 && rl_completion_append_character) {
1517 buf[0] = rl_completion_append_character;
1519 el_insertstr(e, buf);
1521 } else if (what_to_do == '!') {
1524 * More than one match and requested to list possible
1528 for(i=1, maxlen=0; matches[i]; i++) {
1529 match_len = strlen(matches[i]);
1530 if (match_len > maxlen)
1533 matches_num = i - 1;
1535 /* newline to get on next line from command line */
1536 fprintf(e->el_outfile, "\n");
1539 * If there are too many items, ask user for display
1542 if (matches_num > rl_completion_query_items) {
1543 fprintf(e->el_outfile,
1544 "Display all %d possibilities? (y or n) ",
1546 fflush(e->el_outfile);
1547 if (getc(stdin) != 'y')
1549 fprintf(e->el_outfile, "\n");
1553 rl_display_match_list(matches, matches_num,
1555 retval = CC_REDISPLAY;
1556 } else if (matches[0][0]) {
1558 * There was some common match, but the name was
1559 * not complete enough. Next tab will print possible
1564 /* lcd is not a valid object - further specification */
1570 /* free elements of array and the array itself */
1571 for (i = 0; matches[i]; i++)
1573 free(matches), matches = NULL;
1582 * complete word at current point
1585 rl_complete(int ignore, int invoking_key)
1587 if (h == NULL || e == NULL)
1590 if (rl_inhibit_completion) {
1591 rl_insert(ignore, invoking_key);
1592 return (CC_REFRESH);
1593 } else if (e->el_state.lastcmd == el_rl_complete_cmdnum)
1594 return rl_complete_internal('?');
1595 else if (_rl_complete_show_all)
1596 return rl_complete_internal('!');
1598 return (rl_complete_internal(TAB));
1603 * misc other functions
1607 * bind key c to readline-type function func
1610 rl_bind_key(int c, int func(int, int))
1614 if (h == NULL || e == NULL)
1617 if (func == rl_insert) {
1618 /* XXX notice there is no range checking of ``c'' */
1619 e->el_map.key[c] = ED_INSERT;
1627 * read one key from input - handles chars pushed back
1628 * to input stream also
1633 char fooarr[2 * sizeof(int)];
1635 if (e == NULL || h == NULL)
1638 return (el_getc(e, fooarr));
1643 * reset the terminal
1647 rl_reset_terminal(const char *p)
1650 if (h == NULL || e == NULL)
1657 * insert character ``c'' back into input stream, ``count'' times
1660 rl_insert(int count, int c)
1664 if (h == NULL || e == NULL)
1667 /* XXX - int -> char conversion can lose on multichars */
1671 for (; count > 0; count--)