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.
17 * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
18 * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
19 * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
20 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
21 * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
22 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
23 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
24 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
25 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
26 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
27 * POSSIBILITY OF SUCH DAMAGE.
29 * $NetBSD: filecomplete.c,v 1.19 2010/06/01 18:20:26 christos Exp $
32 #include <sys/cdefs.h>
33 __FBSDID("$FreeBSD$");
35 #include <sys/types.h>
49 #include "fcns.h" /* for EL_NUM_FCNS */
51 #include "filecomplete.h"
53 static char break_chars[] = { ' ', '\t', '\n', '"', '\\', '\'', '`',
54 '>', '<', '=', ';', '|', '&', '{', '(', '\0' };
55 /* Tilde is deliberately omitted here, we treat it specially. */
56 static char extra_quote_chars[] = { ')', '}', '*', '?', '[', '$', '\0' };
59 /********************************/
60 /* completion functions */
63 * does tilde expansion of strings of type ``~user/foo''
64 * if ``user'' isn't valid user name or ``txt'' doesn't start
65 * w/ '~', returns pointer to strdup()ed copy of ``txt''
67 * it's callers's responsibility to free() returned string
70 fn_tilde_expand(const char *txt)
72 struct passwd pwres, *pass;
80 temp = strchr(txt + 1, '/');
82 temp = strdup(txt + 1);
86 len = temp - txt + 1; /* text until string after slash */
90 (void)strncpy(temp, txt + 1, len - 2);
94 if (getpwuid_r(getuid(), &pwres, pwbuf, sizeof(pwbuf), &pass) != 0)
97 if (getpwnam_r(temp, &pwres, pwbuf, sizeof(pwbuf), &pass) != 0)
100 free(temp); /* value no more needed */
102 return (strdup(txt));
104 /* update pointer txt to point at string immediately following */
108 temp = malloc(strlen(pass->pw_dir) + 1 + strlen(txt) + 1);
111 (void)sprintf(temp, "%s/%s", pass->pw_dir, txt);
118 * return first found file name starting by the ``text'' or NULL if no
119 * such file can be found
120 * value of ``state'' is ignored
122 * it's caller's responsibility to free returned string
125 fn_filename_completion_function(const char *text, int state)
127 static DIR *dir = NULL;
128 static char *filename = NULL, *dirname = NULL, *dirpath = NULL;
129 static size_t filename_len = 0;
130 struct dirent *entry;
134 if (state == 0 || dir == NULL) {
135 temp = strrchr(text, '/');
139 nptr = realloc(filename, strlen(temp) + 1);
146 (void)strcpy(filename, temp);
147 len = temp - text; /* including last slash */
149 nptr = realloc(dirname, len + 1);
156 (void)strncpy(dirname, text, len);
163 filename = strdup(text);
164 if (filename == NULL)
176 /* support for ``~user'' syntax */
180 if (dirname == NULL) {
181 if ((dirname = strdup("")) == NULL)
183 dirpath = strdup("./");
184 } else if (*dirname == '~')
185 dirpath = fn_tilde_expand(dirname);
187 dirpath = strdup(dirname);
192 dir = opendir(dirpath);
194 return (NULL); /* cannot open the directory */
196 /* will be used in cycle */
197 filename_len = filename ? strlen(filename) : 0;
201 while ((entry = readdir(dir)) != NULL) {
203 if (entry->d_name[0] == '.' && (!entry->d_name[1]
204 || (entry->d_name[1] == '.' && !entry->d_name[2])))
206 if (filename_len == 0)
208 /* otherwise, get first entry where first */
209 /* filename_len characters are equal */
210 if (entry->d_name[0] == filename[0]
211 && entry->d_namlen >= filename_len
212 && strncmp(entry->d_name, filename,
217 if (entry) { /* match found */
218 len = entry->d_namlen;
220 temp = malloc(strlen(dirname) + len + 1);
223 (void)sprintf(temp, "%s%s", dirname, entry->d_name);
235 append_char_function(const char *name)
238 char *expname = *name == '~' ? fn_tilde_expand(name) : NULL;
239 const char *rs = " ";
241 if (stat(expname ? expname : name, &stbuf) == -1)
243 if (S_ISDIR(stbuf.st_mode))
253 * returns list of completions for text given
254 * non-static for readline.
256 char ** completion_matches(const char *, char *(*)(const char *, int));
258 completion_matches(const char *text, char *(*genfunc)(const char *, int))
260 char **match_list = NULL, *retstr, *prevstr;
261 size_t match_list_len, max_equal, which, i;
266 while ((retstr = (*genfunc) (text, (int)matches)) != NULL) {
267 /* allow for list terminator here */
268 if (matches + 3 >= match_list_len) {
270 while (matches + 3 >= match_list_len)
271 match_list_len <<= 1;
272 nmatch_list = realloc(match_list,
273 match_list_len * sizeof(char *));
274 if (nmatch_list == NULL) {
278 match_list = nmatch_list;
281 match_list[++matches] = retstr;
285 return NULL; /* nothing found */
287 /* find least denominator and insert it to match_list[0] */
289 prevstr = match_list[1];
290 max_equal = strlen(prevstr);
291 for (; which <= matches; which++) {
292 for (i = 0; i < max_equal &&
293 prevstr[i] == match_list[which][i]; i++)
298 retstr = malloc(max_equal + 1);
299 if (retstr == NULL) {
303 (void)strncpy(retstr, match_list[1], max_equal);
304 retstr[max_equal] = '\0';
305 match_list[0] = retstr;
307 /* add NULL as last pointer to the array */
308 match_list[matches + 1] = (char *) NULL;
315 * Sort function for qsort(). Just wrapper around strcasecmp().
318 _fn_qsort_string_compare(const void *i1, const void *i2)
320 const char *s1 = ((const char * const *)i1)[0];
321 const char *s2 = ((const char * const *)i2)[0];
323 return strcasecmp(s1, s2);
328 * Display list of strings in columnar format on readline's output stream.
329 * 'matches' is list of strings, 'len' is number of strings in 'matches',
330 * 'max' is maximum length of string in 'matches'.
333 fn_display_match_list(EditLine *el, char **matches, size_t len, size_t max)
335 size_t i, idx, limit, count;
336 int screenwidth = el->el_term.t_size.h;
339 * Find out how many entries can be put on one line, count
340 * with two spaces between strings.
342 limit = screenwidth / (max + 2);
346 /* how many lines of output */
348 if (count * limit < len)
351 /* Sort the items if they are not already sorted. */
352 qsort(&matches[1], len, sizeof(char *), _fn_qsort_string_compare);
355 for(; count > 0; count--) {
356 int more = limit > 0 && matches[0];
357 for(i = 0; more; idx++) {
358 more = ++i < limit && matches[idx + 1];
359 (void)fprintf(el->el_outfile, "%-*s%s", (int)max,
360 matches[idx], more ? " " : "");
362 (void)fprintf(el->el_outfile, "\n");
368 * Complete the word at or before point,
369 * 'what_to_do' says what to do with the completion.
370 * \t means do standard completion.
371 * `?' means list the possible completions.
372 * `*' means insert all of the possible completions.
373 * `!' means to do standard completion, and list all possible completions if
374 * there is more than one.
376 * Note: '*' support is not implemented
377 * '!' could never be invoked
380 fn_complete(EditLine *el,
381 char *(*complet_func)(const char *, int),
382 char **(*attempted_completion_function)(const char *, int, int),
383 const char *word_break, const char *special_prefixes,
384 const char *(*app_func)(const char *), size_t query_items,
385 int *completion_type, int *over, int *point, int *end,
386 const char *(*find_word_start_func)(const char *, const char *),
387 char *(*dequoting_func)(const char *),
388 char *(*quoting_func)(const char *))
396 int what_to_do = '\t';
397 int retval = CC_NORM;
399 if (el->el_state.lastcmd == el->el_state.thiscmd)
402 /* readline's rl_complete() has to be told what we did... */
403 if (completion_type != NULL)
404 *completion_type = what_to_do;
407 complet_func = fn_filename_completion_function;
409 app_func = append_char_function;
411 /* We now look backwards for the start of a filename/variable word */
413 if (find_word_start_func)
414 ctemp = find_word_start_func(li->buffer, li->cursor);
417 while (ctemp > li->buffer
418 && !strchr(word_break, ctemp[-1])
419 && (!special_prefixes || !strchr(special_prefixes, ctemp[-1]) ) )
423 len = li->cursor - ctemp;
424 #if defined(__SSP__) || defined(__SSP_ALL__)
425 temp = malloc(sizeof(*temp) * (len + 1));
429 temp = alloca(sizeof(*temp) * (len + 1));
431 (void)strncpy(temp, ctemp, len);
434 if (dequoting_func) {
435 dequoted_temp = dequoting_func(temp);
436 if (dequoted_temp == NULL)
439 dequoted_temp = NULL;
441 /* these can be used by function called in completion_matches() */
442 /* or (*attempted_completion_function)() */
444 *point = (int)(li->cursor - li->buffer);
446 *end = (int)(li->lastchar - li->buffer);
448 if (attempted_completion_function) {
449 int cur_off = (int)(li->cursor - li->buffer);
450 matches = (*attempted_completion_function) (dequoted_temp ? dequoted_temp : temp,
451 (int)(cur_off - len), cur_off);
454 if (!attempted_completion_function ||
455 (over != NULL && !*over && !matches))
456 matches = completion_matches(dequoted_temp ? dequoted_temp : temp, complet_func);
463 size_t matches_num, maxlen, match_len, match_display=1;
467 * Only replace the completed string with common part of
468 * possible matches if there is possible completion.
470 if (matches[0][0] != '\0') {
473 quoted_match = quoting_func(matches[0]);
474 if (quoted_match == NULL)
479 el_deletestr(el, (int) len);
480 el_insertstr(el, quoted_match ? quoted_match : matches[0]);
485 if (what_to_do == '?')
486 goto display_matches;
488 if (matches[2] == NULL && strcmp(matches[0], matches[1]) == 0) {
490 * We found exact match. Add a space after
491 * it, unless we do filename completion and the
492 * object is a directory.
494 el_insertstr(el, (*app_func)(matches[0]));
495 } else if (what_to_do == '!') {
498 * More than one match and requested to list possible
502 for(i = 1, maxlen = 0; matches[i]; i++) {
503 match_len = strlen(matches[i]);
504 if (match_len > maxlen)
509 /* newline to get on next line from command line */
510 (void)fprintf(el->el_outfile, "\n");
513 * If there are too many items, ask user for display
516 if (matches_num > query_items) {
517 (void)fprintf(el->el_outfile,
518 "Display all %zu possibilities? (y or n) ",
520 (void)fflush(el->el_outfile);
521 if (getc(stdin) != 'y')
523 (void)fprintf(el->el_outfile, "\n");
527 fn_display_match_list(el, matches, matches_num,
529 retval = CC_REDISPLAY;
530 } else if (matches[0][0]) {
532 * There was some common match, but the name was
533 * not complete enough. Next tab will print possible
538 /* lcd is not a valid object - further specification */
545 /* free elements of array and the array itself */
546 for (i = 0; matches[i]; i++)
552 #if defined(__SSP__) || defined(__SSP_ALL__)
560 * el-compatible wrapper around rl_complete; needed for key binding
564 _el_fn_complete(EditLine *el, int ch __attribute__((__unused__)))
566 return (unsigned char)fn_complete(el, NULL, NULL,
567 break_chars, NULL, NULL, 100,
568 NULL, NULL, NULL, NULL,
574 sh_find_word_start(const char *buffer, const char *cursor)
576 const char *word_start = buffer;
578 while (buffer < cursor) {
581 else if (strchr(break_chars, *buffer))
582 word_start = buffer + 1;
592 sh_quote(const char *str)
596 char *quoted_str, *dst;
598 if (*str == '-' || *str == '+')
600 for (src = str; *src != '\0'; src++)
601 if (strchr(break_chars, *src) ||
602 strchr(extra_quote_chars, *src))
605 quoted_str = malloc(sizeof(*quoted_str) *
606 (strlen(str) + extra_len + 1));
607 if (quoted_str == NULL)
611 if (*str == '-' || *str == '+')
612 *dst++ = '.', *dst++ = '/';
613 for (src = str; *src != '\0'; src++) {
614 if (strchr(break_chars, *src) ||
615 strchr(extra_quote_chars, *src))
626 sh_dequote(const char *str)
628 char *dequoted_str, *dst;
630 /* save extra space to replace \~ with ./~ */
631 dequoted_str = malloc(sizeof(*dequoted_str) * (strlen(str) + 1 + 1));
632 if (dequoted_str == NULL)
637 /* dequote \~ at start as ./~ */
638 if (*str == '\\' && str[1] == '~') {
657 * completion function using sh quoting rules; for key binding
661 _el_fn_sh_complete(EditLine *el, int ch __attribute__((__unused__)))
663 return (unsigned char)fn_complete(el, NULL, NULL,
664 break_chars, NULL, NULL, 100,
665 NULL, NULL, NULL, NULL,
666 sh_find_word_start, sh_dequote, sh_quote);