1 /* $NetBSD: filecomplete.c,v 1.34 2014/10/18 15:07:02 riz 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.
33 #if !defined(lint) && !defined(SCCSID)
34 __RCSID("$NetBSD: filecomplete.c,v 1.34 2014/10/18 15:07:02 riz Exp $");
35 #endif /* not lint && not SCCSID */
36 #include <sys/cdefs.h>
37 __FBSDID("$FreeBSD$");
39 #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' };
59 /* Tilde is deliberately omitted here, we treat it specially. */
60 static const Char extra_quote_chars[] = { ')', '}', '*', '?', '[', '$', '\0' };
63 /********************************/
64 /* completion functions */
67 * does tilde expansion of strings of type ``~user/foo''
68 * if ``user'' isn't valid user name or ``txt'' doesn't start
69 * w/ '~', returns pointer to strdup()ed copy of ``txt''
71 * it's the caller's responsibility to free() the returned string
74 fn_tilde_expand(const char *txt)
76 #if defined(HAVE_GETPW_R_POSIX) || defined(HAVE_GETPW_R_DRAFT)
87 temp = strchr(txt + 1, '/');
89 temp = strdup(txt + 1);
93 /* text until string after slash */
94 len = (size_t)(temp - txt + 1);
95 temp = el_malloc(len * sizeof(*temp));
98 (void)strncpy(temp, txt + 1, len - 2);
102 #ifdef HAVE_GETPW_R_POSIX
103 if (getpwuid_r(getuid(), &pwres, pwbuf, sizeof(pwbuf),
106 #elif HAVE_GETPW_R_DRAFT
107 pass = getpwuid_r(getuid(), &pwres, pwbuf, sizeof(pwbuf));
109 pass = getpwuid(getuid());
112 #ifdef HAVE_GETPW_R_POSIX
113 if (getpwnam_r(temp, &pwres, pwbuf, sizeof(pwbuf), &pass) != 0)
115 #elif HAVE_GETPW_R_DRAFT
116 pass = getpwnam_r(temp, &pwres, pwbuf, sizeof(pwbuf));
118 pass = getpwnam(temp);
121 el_free(temp); /* value no more needed */
125 /* update pointer txt to point at string immedially following */
129 len = strlen(pass->pw_dir) + 1 + strlen(txt) + 1;
130 temp = el_malloc(len * sizeof(*temp));
133 (void)snprintf(temp, len, "%s/%s", pass->pw_dir, txt);
140 * return first found file name starting by the ``text'' or NULL if no
141 * such file can be found
142 * value of ``state'' is ignored
144 * it's the caller's responsibility to free the returned string
147 fn_filename_completion_function(const char *text, int state)
149 static DIR *dir = NULL;
150 static char *filename = NULL, *dirname = NULL, *dirpath = NULL;
151 static size_t filename_len = 0;
152 struct dirent *entry;
156 if (state == 0 || dir == NULL) {
157 temp = strrchr(text, '/');
161 nptr = el_realloc(filename, (strlen(temp) + 1) *
169 (void)strcpy(filename, temp);
170 len = (size_t)(temp - text); /* including last slash */
172 nptr = el_realloc(dirname, (len + 1) *
180 (void)strncpy(dirname, text, len);
187 filename = strdup(text);
188 if (filename == NULL)
200 /* support for ``~user'' syntax */
204 if (dirname == NULL) {
205 if ((dirname = strdup("")) == NULL)
207 dirpath = strdup("./");
208 } else if (*dirname == '~')
209 dirpath = fn_tilde_expand(dirname);
211 dirpath = strdup(dirname);
216 dir = opendir(dirpath);
218 return NULL; /* cannot open the directory */
220 /* will be used in cycle */
221 filename_len = filename ? strlen(filename) : 0;
225 while ((entry = readdir(dir)) != NULL) {
227 if (entry->d_name[0] == '.' && (!entry->d_name[1]
228 || (entry->d_name[1] == '.' && !entry->d_name[2])))
230 if (filename_len == 0)
232 /* otherwise, get first entry where first */
233 /* filename_len characters are equal */
234 if (entry->d_name[0] == filename[0]
235 #if HAVE_STRUCT_DIRENT_D_NAMLEN
236 && entry->d_namlen >= filename_len
238 && strlen(entry->d_name) >= filename_len
240 && strncmp(entry->d_name, filename,
245 if (entry) { /* match found */
247 #if HAVE_STRUCT_DIRENT_D_NAMLEN
248 len = entry->d_namlen;
250 len = strlen(entry->d_name);
253 len = strlen(dirname) + len + 1;
254 temp = el_malloc(len * sizeof(*temp));
257 (void)snprintf(temp, len, "%s%s", dirname, entry->d_name);
269 append_char_function(const char *name)
272 char *expname = *name == '~' ? fn_tilde_expand(name) : NULL;
273 const char *rs = " ";
275 if (stat(expname ? expname : name, &stbuf) == -1)
277 if (S_ISDIR(stbuf.st_mode))
285 * returns list of completions for text given
286 * non-static for readline.
288 char ** completion_matches(const char *, char *(*)(const char *, int));
290 completion_matches(const char *text, char *(*genfunc)(const char *, int))
292 char **match_list = NULL, *retstr, *prevstr;
293 size_t match_list_len, max_equal, which, i;
298 while ((retstr = (*genfunc) (text, (int)matches)) != NULL) {
299 /* allow for list terminator here */
300 if (matches + 3 >= match_list_len) {
302 while (matches + 3 >= match_list_len)
303 match_list_len <<= 1;
304 nmatch_list = el_realloc(match_list,
305 match_list_len * sizeof(*nmatch_list));
306 if (nmatch_list == NULL) {
310 match_list = nmatch_list;
313 match_list[++matches] = retstr;
317 return NULL; /* nothing found */
319 /* find least denominator and insert it to match_list[0] */
321 prevstr = match_list[1];
322 max_equal = strlen(prevstr);
323 for (; which <= matches; which++) {
324 for (i = 0; i < max_equal &&
325 prevstr[i] == match_list[which][i]; i++)
330 retstr = el_malloc((max_equal + 1) * sizeof(*retstr));
331 if (retstr == NULL) {
335 (void)strncpy(retstr, match_list[1], max_equal);
336 retstr[max_equal] = '\0';
337 match_list[0] = retstr;
339 /* add NULL as last pointer to the array */
340 match_list[matches + 1] = NULL;
346 * Sort function for qsort(). Just wrapper around strcasecmp().
349 _fn_qsort_string_compare(const void *i1, const void *i2)
351 const char *s1 = ((const char * const *)i1)[0];
352 const char *s2 = ((const char * const *)i2)[0];
354 return strcasecmp(s1, s2);
358 * Display list of strings in columnar format on readline's output stream.
359 * 'matches' is list of strings, 'num' is number of strings in 'matches',
360 * 'width' is maximum length of string in 'matches'.
362 * matches[0] is not one of the match strings, but it is counted in
363 * num, so the strings are matches[1] *through* matches[num-1].
366 fn_display_match_list (EditLine *el, char **matches, size_t num, size_t width)
368 size_t line, lines, col, cols, thisguy;
369 int screenwidth = el->el_terminal.t_size.h;
371 /* Ignore matches[0]. Avoid 1-based array logic below. */
376 * Find out how many entries can be put on one line; count
377 * with one space between strings the same way it's printed.
379 cols = (size_t)screenwidth / (width + 1);
383 /* how many lines of output, rounded up */
384 lines = (num + cols - 1) / cols;
386 /* Sort the items. */
387 qsort(matches, num, sizeof(char *), _fn_qsort_string_compare);
390 * On the ith line print elements i, i+lines, i+lines*2, etc.
392 for (line = 0; line < lines; line++) {
393 for (col = 0; col < cols; col++) {
394 thisguy = line + col * lines;
397 (void)fprintf(el->el_outfile, "%s%-*s",
398 col == 0 ? "" : " ", (int)width, matches[thisguy]);
400 (void)fprintf(el->el_outfile, "\n");
405 * Complete the word at or before point,
406 * 'what_to_do' says what to do with the completion.
407 * \t means do standard completion.
408 * `?' means list the possible completions.
409 * `*' means insert all of the possible completions.
410 * `!' means to do standard completion, and list all possible completions if
411 * there is more than one.
413 * Note: '*' support is not implemented
414 * '!' could never be invoked
417 fn_complete(EditLine *el,
418 char *(*complet_func)(const char *, int),
419 char **(*attempted_completion_function)(const char *, int, int),
420 const Char *word_break, const Char *special_prefixes,
421 const char *(*app_func)(const char *), size_t query_items,
422 int *completion_type, int *over, int *point, int *end,
423 const Char *(*find_word_start_func)(const Char *, const Char *),
424 Char *(*dequoting_func)(const Char *),
425 char *(*quoting_func)(const char *))
427 const TYPE(LineInfo) *li;
433 int what_to_do = '\t';
434 int retval = CC_NORM;
436 if (el->el_state.lastcmd == el->el_state.thiscmd)
439 /* readline's rl_complete() has to be told what we did... */
440 if (completion_type != NULL)
441 *completion_type = what_to_do;
444 complet_func = fn_filename_completion_function;
446 app_func = append_char_function;
448 /* We now look backwards for the start of a filename/variable word */
449 li = FUN(el,line)(el);
450 if (find_word_start_func)
451 ctemp = find_word_start_func(li->buffer, li->cursor);
454 while (ctemp > li->buffer
455 && !Strchr(word_break, ctemp[-1])
456 && (!special_prefixes || !Strchr(special_prefixes, ctemp[-1]) ) )
460 len = (size_t)(li->cursor - ctemp);
461 temp = el_malloc((len + 1) * sizeof(*temp));
462 (void)Strncpy(temp, ctemp, len);
465 if (dequoting_func) {
466 dequoted_temp = dequoting_func(temp);
467 if (dequoted_temp == NULL)
470 dequoted_temp = NULL;
472 /* these can be used by function called in completion_matches() */
473 /* or (*attempted_completion_function)() */
475 *point = (int)(li->cursor - li->buffer);
477 *end = (int)(li->lastchar - li->buffer);
479 if (attempted_completion_function) {
480 int cur_off = (int)(li->cursor - li->buffer);
481 matches = (*attempted_completion_function)(
482 ct_encode_string(dequoted_temp ? dequoted_temp : temp,
484 cur_off - (int)len, cur_off);
487 if (!attempted_completion_function ||
488 (over != NULL && !*over && !matches))
489 matches = completion_matches(
490 ct_encode_string(dequoted_temp ? dequoted_temp : temp,
491 &el->el_scratch), complet_func);
498 size_t matches_num, maxlen, match_len, match_display=1;
502 * Only replace the completed string with common part of
503 * possible matches if there is possible completion.
505 if (matches[0][0] != '\0') {
508 quoted_match = quoting_func(matches[0]);
509 if (quoted_match == NULL)
513 el_deletestr(el, (int) len);
514 FUN(el,insertstr)(el,
515 ct_decode_string(quoted_match ? quoted_match :
516 matches[0] , &el->el_scratch));
519 if (what_to_do == '?')
520 goto display_matches;
522 if (matches[2] == NULL &&
523 (matches[1] == NULL || strcmp(matches[0], matches[1]) == 0)) {
525 * We found exact match. Add a space after
526 * it, unless we do filename completion and the
527 * object is a directory.
529 FUN(el,insertstr)(el,
530 ct_decode_string((*app_func)(matches[0]),
532 } else if (what_to_do == '!') {
535 * More than one match and requested to list possible
539 for(i = 1, maxlen = 0; matches[i]; i++) {
540 match_len = strlen(matches[i]);
541 if (match_len > maxlen)
544 /* matches[1] through matches[i-1] are available */
545 matches_num = (size_t)(i - 1);
547 /* newline to get on next line from command line */
548 (void)fprintf(el->el_outfile, "\n");
551 * If there are too many items, ask user for display
554 if (matches_num > query_items) {
555 (void)fprintf(el->el_outfile,
556 "Display all %zu possibilities? (y or n) ",
558 (void)fflush(el->el_outfile);
559 if (getc(stdin) != 'y')
561 (void)fprintf(el->el_outfile, "\n");
566 * Interface of this function requires the
567 * strings be matches[1..num-1] for compat.
568 * We have matches_num strings not counting
569 * the prefix in matches[0], so we need to
570 * add 1 to matches_num for the call.
572 fn_display_match_list(el, matches,
573 matches_num+1, maxlen);
575 retval = CC_REDISPLAY;
576 } else if (matches[0][0]) {
578 * There was some common match, but the name was
579 * not complete enough. Next tab will print possible
584 /* lcd is not a valid object - further specification */
591 /* free elements of array and the array itself */
592 for (i = 0; matches[i]; i++)
603 * el-compatible wrapper around rl_complete; needed for key binding
607 _el_fn_complete(EditLine *el, int ch __attribute__((__unused__)))
609 return (unsigned char)fn_complete(el, NULL, NULL,
610 break_chars, NULL, NULL, (size_t)100,
611 NULL, NULL, NULL, NULL,
616 sh_find_word_start(const Char *buffer, const Char *cursor)
618 const Char *word_start = buffer;
620 while (buffer < cursor) {
623 else if (Strchr(break_chars, *buffer))
624 word_start = buffer + 1;
631 sh_quote(const char *str)
635 char *quoted_str, *dst;
637 for (src = str; *src != '\0'; src++)
638 if (Strchr(break_chars, *src) ||
639 Strchr(extra_quote_chars, *src))
642 quoted_str = malloc(sizeof(*quoted_str) *
643 (strlen(str) + extra_len + 1));
644 if (quoted_str == NULL)
648 for (src = str; *src != '\0'; src++) {
649 if (Strchr(break_chars, *src) ||
650 Strchr(extra_quote_chars, *src))
660 sh_dequote(const Char *str)
662 Char *dequoted_str, *dst;
664 /* save extra space to replace \~ with ./~ */
665 dequoted_str = malloc(sizeof(*dequoted_str) * (Strlen(str) + 1 + 1));
666 if (dequoted_str == NULL)
671 /* dequote \~ at start as ./~ */
672 if (*str == '\\' && str[1] == '~') {
690 * completion function using sh quoting rules; for key binding
694 _el_fn_sh_complete(EditLine *el, int ch __attribute__((__unused__)))
696 return (unsigned char)fn_complete(el, NULL, NULL,
697 break_chars, NULL, NULL, 100,
698 NULL, NULL, NULL, NULL,
699 sh_find_word_start, sh_dequote, sh_quote);