1 /* $NetBSD: filecomplete.c,v 1.32 2014/06/05 22:07:42 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.
34 #if !defined(lint) && !defined(SCCSID)
35 __RCSID("$NetBSD: filecomplete.c,v 1.32 2014/06/05 22:07:42 christos Exp $");
36 #endif /* not lint && not SCCSID */
38 #include <sys/types.h>
53 #include "fcns.h" /* for EL_NUM_FCNS */
55 #include "filecomplete.h"
57 static const Char break_chars[] = { ' ', '\t', '\n', '"', '\\', '\'', '`', '@',
58 '$', '>', '<', '=', ';', '|', '&', '{', '(', '\0' };
61 /********************************/
62 /* completion functions */
65 * does tilde expansion of strings of type ``~user/foo''
66 * if ``user'' isn't valid user name or ``txt'' doesn't start
67 * w/ '~', returns pointer to strdup()ed copy of ``txt''
69 * it's callers's responsibility to free() returned string
72 fn_tilde_expand(const char *txt)
74 #if defined(HAVE_GETPW_R_POSIX) || defined(HAVE_GETPW_R_DRAFT)
85 temp = strchr(txt + 1, '/');
87 temp = strdup(txt + 1);
91 /* text until string after slash */
92 len = (size_t)(temp - txt + 1);
93 temp = el_malloc(len * sizeof(*temp));
96 (void)strncpy(temp, txt + 1, len - 2);
100 #ifdef HAVE_GETPW_R_POSIX
101 if (getpwuid_r(getuid(), &pwres, pwbuf, sizeof(pwbuf),
104 #elif HAVE_GETPW_R_DRAFT
105 pass = getpwuid_r(getuid(), &pwres, pwbuf, sizeof(pwbuf));
107 pass = getpwuid(getuid());
110 #ifdef HAVE_GETPW_R_POSIX
111 if (getpwnam_r(temp, &pwres, pwbuf, sizeof(pwbuf), &pass) != 0)
113 #elif HAVE_GETPW_R_DRAFT
114 pass = getpwnam_r(temp, &pwres, pwbuf, sizeof(pwbuf));
116 pass = getpwnam(temp);
119 el_free(temp); /* value no more needed */
123 /* update pointer txt to point at string immedially following */
127 len = strlen(pass->pw_dir) + 1 + strlen(txt) + 1;
128 temp = el_malloc(len * sizeof(*temp));
131 (void)snprintf(temp, len, "%s/%s", pass->pw_dir, txt);
138 * return first found file name starting by the ``text'' or NULL if no
139 * such file can be found
140 * value of ``state'' is ignored
142 * it's caller's responsibility to free returned string
145 fn_filename_completion_function(const char *text, int state)
147 static DIR *dir = NULL;
148 static char *filename = NULL, *dirname = NULL, *dirpath = NULL;
149 static size_t filename_len = 0;
150 struct dirent *entry;
154 if (state == 0 || dir == NULL) {
155 temp = strrchr(text, '/');
159 nptr = el_realloc(filename, (strlen(temp) + 1) *
167 (void)strcpy(filename, temp);
168 len = (size_t)(temp - text); /* including last slash */
170 nptr = el_realloc(dirname, (len + 1) *
178 (void)strncpy(dirname, text, len);
185 filename = strdup(text);
186 if (filename == NULL)
198 /* support for ``~user'' syntax */
202 if (dirname == NULL) {
203 if ((dirname = strdup("")) == NULL)
205 dirpath = strdup("./");
206 } else if (*dirname == '~')
207 dirpath = fn_tilde_expand(dirname);
209 dirpath = strdup(dirname);
214 dir = opendir(dirpath);
216 return NULL; /* cannot open the directory */
218 /* will be used in cycle */
219 filename_len = filename ? strlen(filename) : 0;
223 while ((entry = readdir(dir)) != NULL) {
225 if (entry->d_name[0] == '.' && (!entry->d_name[1]
226 || (entry->d_name[1] == '.' && !entry->d_name[2])))
228 if (filename_len == 0)
230 /* otherwise, get first entry where first */
231 /* filename_len characters are equal */
232 if (entry->d_name[0] == filename[0]
233 /* Some dirents have d_namlen, but it is not portable. */
234 && strlen(entry->d_name) >= filename_len
235 && strncmp(entry->d_name, filename,
240 if (entry) { /* match found */
242 /* Some dirents have d_namlen, but it is not portable. */
243 len = strlen(entry->d_name);
245 len = strlen(dirname) + len + 1;
246 temp = el_malloc(len * sizeof(*temp));
249 (void)snprintf(temp, len, "%s%s", dirname, entry->d_name);
261 append_char_function(const char *name)
264 char *expname = *name == '~' ? fn_tilde_expand(name) : NULL;
265 const char *rs = " ";
267 if (stat(expname ? expname : name, &stbuf) == -1)
269 if (S_ISDIR(stbuf.st_mode))
277 * returns list of completions for text given
278 * non-static for readline.
280 char ** completion_matches(const char *, char *(*)(const char *, int));
282 completion_matches(const char *text, char *(*genfunc)(const char *, int))
284 char **match_list = NULL, *retstr, *prevstr;
285 size_t match_list_len, max_equal, which, i;
290 while ((retstr = (*genfunc) (text, (int)matches)) != NULL) {
291 /* allow for list terminator here */
292 if (matches + 3 >= match_list_len) {
294 while (matches + 3 >= match_list_len)
295 match_list_len <<= 1;
296 nmatch_list = el_realloc(match_list,
297 match_list_len * sizeof(*nmatch_list));
298 if (nmatch_list == NULL) {
302 match_list = nmatch_list;
305 match_list[++matches] = retstr;
309 return NULL; /* nothing found */
311 /* find least denominator and insert it to match_list[0] */
313 prevstr = match_list[1];
314 max_equal = strlen(prevstr);
315 for (; which <= matches; which++) {
316 for (i = 0; i < max_equal &&
317 prevstr[i] == match_list[which][i]; i++)
322 retstr = el_malloc((max_equal + 1) * sizeof(*retstr));
323 if (retstr == NULL) {
327 (void)strncpy(retstr, match_list[1], max_equal);
328 retstr[max_equal] = '\0';
329 match_list[0] = retstr;
331 /* add NULL as last pointer to the array */
332 match_list[matches + 1] = NULL;
338 * Sort function for qsort(). Just wrapper around strcasecmp().
341 _fn_qsort_string_compare(const void *i1, const void *i2)
343 const char *s1 = ((const char * const *)i1)[0];
344 const char *s2 = ((const char * const *)i2)[0];
346 return strcasecmp(s1, s2);
350 * Display list of strings in columnar format on readline's output stream.
351 * 'matches' is list of strings, 'num' is number of strings in 'matches',
352 * 'width' is maximum length of string in 'matches'.
354 * matches[0] is not one of the match strings, but it is counted in
355 * num, so the strings are matches[1] *through* matches[num-1].
358 fn_display_match_list (EditLine *el, char **matches, size_t num, size_t width)
360 size_t line, lines, col, cols, thisguy;
361 int screenwidth = el->el_terminal.t_size.h;
363 /* Ignore matches[0]. Avoid 1-based array logic below. */
368 * Find out how many entries can be put on one line; count
369 * with one space between strings the same way it's printed.
371 cols = (size_t)screenwidth / (width + 1);
375 /* how many lines of output, rounded up */
376 lines = (num + cols - 1) / cols;
378 /* Sort the items. */
379 qsort(matches, num, sizeof(char *), _fn_qsort_string_compare);
382 * On the ith line print elements i, i+lines, i+lines*2, etc.
384 for (line = 0; line < lines; line++) {
385 for (col = 0; col < cols; col++) {
386 thisguy = line + col * lines;
389 (void)fprintf(el->el_outfile, "%s%-*s",
390 col == 0 ? "" : " ", (int)width, matches[thisguy]);
392 (void)fprintf(el->el_outfile, "\n");
397 * Complete the word at or before point,
398 * 'what_to_do' says what to do with the completion.
399 * \t means do standard completion.
400 * `?' means list the possible completions.
401 * `*' means insert all of the possible completions.
402 * `!' means to do standard completion, and list all possible completions if
403 * there is more than one.
405 * Note: '*' support is not implemented
406 * '!' could never be invoked
409 fn_complete(EditLine *el,
410 char *(*complet_func)(const char *, int),
411 char **(*attempted_completion_function)(const char *, int, int),
412 const Char *word_break, const Char *special_prefixes,
413 const char *(*app_func)(const char *), size_t query_items,
414 int *completion_type, int *over, int *point, int *end)
416 const TYPE(LineInfo) *li;
421 int what_to_do = '\t';
422 int retval = CC_NORM;
424 if (el->el_state.lastcmd == el->el_state.thiscmd)
427 /* readline's rl_complete() has to be told what we did... */
428 if (completion_type != NULL)
429 *completion_type = what_to_do;
432 complet_func = fn_filename_completion_function;
434 app_func = append_char_function;
436 /* We now look backwards for the start of a filename/variable word */
437 li = FUN(el,line)(el);
439 while (ctemp > li->buffer
440 && !Strchr(word_break, ctemp[-1])
441 && (!special_prefixes || !Strchr(special_prefixes, ctemp[-1]) ) )
444 len = (size_t)(li->cursor - ctemp);
445 temp = el_malloc((len + 1) * sizeof(*temp));
446 (void)Strncpy(temp, ctemp, len);
449 /* these can be used by function called in completion_matches() */
450 /* or (*attempted_completion_function)() */
452 *point = (int)(li->cursor - li->buffer);
454 *end = (int)(li->lastchar - li->buffer);
456 if (attempted_completion_function) {
457 int cur_off = (int)(li->cursor - li->buffer);
458 matches = (*attempted_completion_function)(
459 ct_encode_string(temp, &el->el_scratch),
460 cur_off - (int)len, cur_off);
463 if (!attempted_completion_function ||
464 (over != NULL && !*over && !matches))
465 matches = completion_matches(
466 ct_encode_string(temp, &el->el_scratch), complet_func);
473 size_t matches_num, maxlen, match_len, match_display=1;
477 * Only replace the completed string with common part of
478 * possible matches if there is possible completion.
480 if (matches[0][0] != '\0') {
481 el_deletestr(el, (int) len);
482 FUN(el,insertstr)(el,
483 ct_decode_string(matches[0], &el->el_scratch));
486 if (what_to_do == '?')
487 goto display_matches;
489 if (matches[2] == NULL &&
490 (matches[1] == NULL || strcmp(matches[0], matches[1]) == 0)) {
492 * We found exact match. Add a space after
493 * it, unless we do filename completion and the
494 * object is a directory.
496 FUN(el,insertstr)(el,
497 ct_decode_string((*app_func)(matches[0]),
499 } else if (what_to_do == '!') {
502 * More than one match and requested to list possible
506 for(i = 1, maxlen = 0; matches[i]; i++) {
507 match_len = strlen(matches[i]);
508 if (match_len > maxlen)
511 /* matches[1] through matches[i-1] are available */
512 matches_num = (size_t)(i - 1);
514 /* newline to get on next line from command line */
515 (void)fprintf(el->el_outfile, "\n");
518 * If there are too many items, ask user for display
521 if (matches_num > query_items) {
522 (void)fprintf(el->el_outfile,
523 "Display all %zu possibilities? (y or n) ",
525 (void)fflush(el->el_outfile);
526 if (getc(stdin) != 'y')
528 (void)fprintf(el->el_outfile, "\n");
533 * Interface of this function requires the
534 * strings be matches[1..num-1] for compat.
535 * We have matches_num strings not counting
536 * the prefix in matches[0], so we need to
537 * add 1 to matches_num for the call.
539 fn_display_match_list(el, matches,
540 matches_num+1, maxlen);
542 retval = CC_REDISPLAY;
543 } else if (matches[0][0]) {
545 * There was some common match, but the name was
546 * not complete enough. Next tab will print possible
551 /* lcd is not a valid object - further specification */
557 /* free elements of array and the array itself */
558 for (i = 0; matches[i]; i++)
568 * el-compatible wrapper around rl_complete; needed for key binding
572 _el_fn_complete(EditLine *el, int ch __attribute__((__unused__)))
574 return (unsigned char)fn_complete(el, NULL, NULL,
575 break_chars, NULL, NULL, (size_t)100,
576 NULL, NULL, NULL, NULL);