2 * Copyright (c) 1997 The NetBSD Foundation, Inc.
5 * This code is derived from software contributed to The NetBSD Foundation
8 * Redistribution and use in source and binary forms, with or without
9 * modification, are permitted provided that the following conditions
11 * 1. Redistributions of source code must retain the above copyright
12 * notice, this list of conditions and the following disclaimer.
13 * 2. Redistributions in binary form must reproduce the above copyright
14 * notice, this list of conditions and the following disclaimer in the
15 * documentation and/or other materials provided with the distribution.
16 * 3. All advertising materials mentioning features or use of this software
17 * must display the following acknowledgement:
18 * This product includes software developed by the NetBSD
19 * Foundation, Inc. and its contributors.
20 * 4. Neither the name of The NetBSD Foundation nor the names of its
21 * contributors may be used to endorse or promote products derived
22 * from this software without specific prior written permission.
24 * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
25 * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
26 * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
27 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
28 * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
29 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
30 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
31 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
32 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
33 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
34 * POSSIBILITY OF SUCH DAMAGE.
36 * $NetBSD: filecomplete.c,v 1.7 2005/06/11 18:18:59 christos Exp $
37 * $DragonFly: src/lib/libedit/filecomplete.c,v 1.1 2005/11/13 11:58:30 corecode Exp $
42 #include <sys/types.h>
63 #include "fcns.h" /* for EL_NUM_FCNS */
65 #include "filecomplete.h"
67 static char break_chars[] = { ' ', '\t', '\n', '"', '\\', '\'', '`', '@', '$',
68 '>', '<', '=', ';', '|', '&', '{', '(', '\0' };
71 /********************************/
72 /* completion functions */
75 * does tilde expansion of strings of type ``~user/foo''
76 * if ``user'' isn't valid user name or ``txt'' doesn't start
77 * w/ '~', returns pointer to strdup()ed copy of ``txt''
79 * it's callers's responsibility to free() returned string
82 fn_tilde_expand(const char *txt)
85 XXX: replace the next line with this line when getpwuid_r or
86 getpwnam_r become available:
87 struct passwd pwres, *pass;
97 temp = strchr(txt + 1, '/');
99 temp = strdup(txt + 1);
103 len = temp - txt + 1; /* text until string after slash */
107 (void)strncpy(temp, txt + 1, len - 2);
108 temp[len - 2] = '\0';
112 XXX: use the following instead of the next line when
113 getpwuid_r is available:
114 if (getpwuid_r(getuid(), &pwres, pwbuf, sizeof(pwbuf), &pass) != 0)
117 pass = getpwuid(getuid());
121 XXX: use the following instead of the next line when
122 getpwname_r is available:
123 if (getpwnam_r(temp, &pwres, pwbuf, sizeof(pwbuf), &pass) != 0)
126 pass = getpwnam(temp);
128 free(temp); /* value no more needed */
130 return (strdup(txt));
132 /* update pointer txt to point at string immedially following */
136 temp = malloc(strlen(pass->pw_dir) + 1 + strlen(txt) + 1);
139 (void)sprintf(temp, "%s/%s", pass->pw_dir, txt);
146 * return first found file name starting by the ``text'' or NULL if no
147 * such file can be found
148 * value of ``state'' is ignored
150 * it's caller's responsibility to free returned string
153 fn_filename_completion_function(const char *text, int state)
155 static DIR *dir = NULL;
156 static char *filename = NULL, *dirname = NULL, *dirpath = NULL;
157 static size_t filename_len = 0;
158 struct dirent *entry;
162 if (state == 0 || dir == NULL) {
163 temp = strrchr(text, '/');
167 nptr = realloc(filename, strlen(temp) + 1);
173 (void)strcpy(filename, temp);
174 len = temp - text; /* including last slash */
175 nptr = realloc(dirname, len + 1);
181 (void)strncpy(dirname, text, len);
187 filename = strdup(text);
188 if (filename == NULL)
199 /* support for ``~user'' syntax */
202 if (dirname == NULL && (dirname = strdup("./")) == NULL)
206 dirpath = fn_tilde_expand(dirname);
208 dirpath = strdup(dirname);
213 dir = opendir(dirpath);
215 return (NULL); /* cannot open the directory */
217 /* will be used in cycle */
218 filename_len = filename ? strlen(filename) : 0;
222 while ((entry = readdir(dir)) != NULL) {
224 if (entry->d_name[0] == '.' && (!entry->d_name[1]
225 || (entry->d_name[1] == '.' && !entry->d_name[2])))
227 if (filename_len == 0)
229 /* otherwise, get first entry where first */
230 /* filename_len characters are equal */
231 if (entry->d_name[0] == filename[0]
232 #if defined(__SVR4) || defined(__linux__)
233 && strlen(entry->d_name) >= filename_len
235 && entry->d_namlen >= filename_len
237 && strncmp(entry->d_name, filename,
242 if (entry) { /* match found */
244 #if defined(__SVR4) || defined(__linux__)
245 len = strlen(entry->d_name);
247 len = entry->d_namlen;
250 temp = malloc(strlen(dirname) + len + 1);
253 (void)sprintf(temp, "%s%s", dirname, entry->d_name);
265 append_char_function(const char *name)
268 char *expname = *name == '~' ? fn_tilde_expand(name) : NULL;
271 if (stat(expname ? expname : name, &stbuf) == -1)
273 if (S_ISDIR(stbuf.st_mode))
281 * returns list of completions for text given
282 * non-static for readline.
284 char ** completion_matches(const char *, char *(*)(const char *, int));
286 completion_matches(const char *text, char *(*genfunc)(const char *, int))
288 char **match_list = NULL, *retstr, *prevstr;
289 size_t match_list_len, max_equal, which, i;
294 while ((retstr = (*genfunc) (text, (int)matches)) != NULL) {
295 /* allow for list terminator here */
296 if (matches + 3 >= match_list_len) {
298 while (matches + 3 >= match_list_len)
299 match_list_len <<= 1;
300 nmatch_list = realloc(match_list,
301 match_list_len * sizeof(char *));
302 if (nmatch_list == NULL) {
306 match_list = nmatch_list;
309 match_list[++matches] = retstr;
313 return NULL; /* nothing found */
315 /* find least denominator and insert it to match_list[0] */
317 prevstr = match_list[1];
318 max_equal = strlen(prevstr);
319 for (; which <= matches; which++) {
320 for (i = 0; i < max_equal &&
321 prevstr[i] == match_list[which][i]; i++)
326 retstr = malloc(max_equal + 1);
327 if (retstr == NULL) {
331 (void)strncpy(retstr, match_list[1], max_equal);
332 retstr[max_equal] = '\0';
333 match_list[0] = retstr;
335 /* add NULL as last pointer to the array */
336 match_list[matches + 1] = (char *) NULL;
342 * Sort function for qsort(). Just wrapper around strcasecmp().
345 _fn_qsort_string_compare(const void *i1, const void *i2)
347 const char *s1 = ((const char * const *)i1)[0];
348 const char *s2 = ((const char * const *)i2)[0];
350 return strcasecmp(s1, s2);
354 * Display list of strings in columnar format on readline's output stream.
355 * 'matches' is list of strings, 'len' is number of strings in 'matches',
356 * 'max' is maximum length of string in 'matches'.
359 fn_display_match_list (EditLine *el, char **matches, int len, int max)
361 int i, idx, limit, count;
362 int screenwidth = el->el_term.t_size.h;
365 * Find out how many entries can be put on one line, count
366 * with two spaces between strings.
368 limit = screenwidth / (max + 2);
372 /* how many lines of output */
374 if (count * limit < len)
377 /* Sort the items if they are not already sorted. */
378 qsort(&matches[1], (size_t)(len - 1), sizeof(char *),
379 _fn_qsort_string_compare);
382 for(; count > 0; count--) {
383 for(i = 0; i < limit && matches[idx]; i++, idx++)
384 (void)fprintf(el->el_outfile, "%-*s ", max,
386 (void)fprintf(el->el_outfile, "\n");
391 * Complete the word at or before point,
392 * 'what_to_do' says what to do with the completion.
393 * \t means do standard completion.
394 * `?' means list the possible completions.
395 * `*' means insert all of the possible completions.
396 * `!' means to do standard completion, and list all possible completions if
397 * there is more than one.
399 * Note: '*' support is not implemented
400 * '!' could never be invoked
403 fn_complete(EditLine *el,
404 char *(*complet_func)(const char *, int),
405 char **(*attempted_completion_function)(const char *, int, int),
406 const char *word_break, const char *special_prefixes,
407 const char *(*app_func)(const char *), int query_items,
408 int *completion_type, int *over, int *point, int *end)
411 char *temp, **matches;
414 int what_to_do = '\t';
416 if (el->el_state.lastcmd == el->el_state.thiscmd)
419 /* readline's rl_complete() has to be told what we did... */
420 if (completion_type != NULL)
421 *completion_type = what_to_do;
424 complet_func = fn_filename_completion_function;
426 app_func = append_char_function;
428 /* We now look backwards for the start of a filename/variable word */
430 ctemp = (const char *) li->cursor;
431 while (ctemp > li->buffer
432 && !strchr(word_break, ctemp[-1])
433 && (!special_prefixes || !strchr(special_prefixes, ctemp[-1]) ) )
436 len = li->cursor - ctemp;
437 temp = alloca(len + 1);
438 (void)strncpy(temp, ctemp, len);
441 /* these can be used by function called in completion_matches() */
442 /* or (*attempted_completion_function)() */
444 *point = li->cursor - li->buffer;
446 *end = li->lastchar - li->buffer;
448 if (attempted_completion_function) {
449 int cur_off = li->cursor - li->buffer;
450 matches = (*attempted_completion_function) (temp,
451 (int)(cur_off - len), cur_off);
454 if (!attempted_completion_function ||
455 (over != NULL && *over && !matches))
456 matches = completion_matches(temp, complet_func);
462 int i, retval = CC_REFRESH;
463 int matches_num, maxlen, match_len, match_display=1;
466 * Only replace the completed string with common part of
467 * possible matches if there is possible completion.
469 if (matches[0][0] != '\0') {
470 el_deletestr(el, (int) len);
471 el_insertstr(el, matches[0]);
474 if (what_to_do == '?')
475 goto display_matches;
477 if (matches[2] == NULL && strcmp(matches[0], matches[1]) == 0) {
479 * We found exact match. Add a space after
480 * it, unless we do filename completion and the
481 * object is a directory.
483 el_insertstr(el, (*append_char_function)(matches[0]));
484 } else if (what_to_do == '!') {
487 * More than one match and requested to list possible
491 for(i=1, maxlen=0; matches[i]; i++) {
492 match_len = strlen(matches[i]);
493 if (match_len > maxlen)
498 /* newline to get on next line from command line */
499 (void)fprintf(el->el_outfile, "\n");
502 * If there are too many items, ask user for display
505 if (matches_num > query_items) {
506 (void)fprintf(el->el_outfile,
507 "Display all %d possibilities? (y or n) ",
509 (void)fflush(el->el_outfile);
510 if (getc(stdin) != 'y')
512 (void)fprintf(el->el_outfile, "\n");
516 fn_display_match_list(el, matches, matches_num,
518 retval = CC_REDISPLAY;
519 } else if (matches[0][0]) {
521 * There was some common match, but the name was
522 * not complete enough. Next tab will print possible
527 /* lcd is not a valid object - further specification */
533 /* free elements of array and the array itself */
534 for (i = 0; matches[i]; i++)
536 free(matches), matches = NULL;
544 * el-compatible wrapper around rl_complete; needed for key binding
548 _el_fn_complete(EditLine *el, int ch __attribute__((__unused__)))
550 return (unsigned char)fn_complete(el, NULL, NULL,
551 break_chars, NULL, NULL, 100,
552 NULL, NULL, NULL, NULL);