1 /* $NetBSD: filecomplete.c,v 1.40 2016/02/17 19:47:49 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.
33 #if !defined(lint) && !defined(SCCSID)
34 __RCSID("$NetBSD: filecomplete.c,v 1.40 2016/02/17 19:47:49 christos Exp $");
35 #endif /* not lint && not SCCSID */
36 #include <sys/cdefs.h>
37 __FBSDID("$FreeBSD$");
39 #include <sys/types.h>
52 #include "filecomplete.h"
54 static const Char break_chars[] = { ' ', '\t', '\n', '"', '\\', '\'', '`', '@',
55 '$', '>', '<', '=', ';', '|', '&', '{', '(', '\0' };
56 /* Tilde is deliberately omitted here, we treat it specially. */
57 static const Char extra_quote_chars[] = { ')', '}', '*', '?', '[', '$', '\0' };
60 /********************************/
61 /* completion functions */
64 * does tilde expansion of strings of type ``~user/foo''
65 * if ``user'' isn't valid user name or ``txt'' doesn't start
66 * w/ '~', returns pointer to strdup()ed copy of ``txt''
68 * it's the caller's responsibility to free() the returned string
71 fn_tilde_expand(const char *txt)
73 #if defined(HAVE_GETPW_R_POSIX) || defined(HAVE_GETPW_R_DRAFT)
84 temp = strchr(txt + 1, '/');
86 temp = strdup(txt + 1);
90 /* text until string after slash */
91 len = (size_t)(temp - txt + 1);
92 temp = el_malloc(len * sizeof(*temp));
95 (void)strncpy(temp, txt + 1, len - 2);
99 #ifdef HAVE_GETPW_R_POSIX
100 if (getpwuid_r(getuid(), &pwres, pwbuf, sizeof(pwbuf),
103 #elif HAVE_GETPW_R_DRAFT
104 pass = getpwuid_r(getuid(), &pwres, pwbuf, sizeof(pwbuf));
106 pass = getpwuid(getuid());
109 #ifdef HAVE_GETPW_R_POSIX
110 if (getpwnam_r(temp, &pwres, pwbuf, sizeof(pwbuf), &pass) != 0)
112 #elif HAVE_GETPW_R_DRAFT
113 pass = getpwnam_r(temp, &pwres, pwbuf, sizeof(pwbuf));
115 pass = getpwnam(temp);
118 el_free(temp); /* value no more needed */
122 /* update pointer txt to point at string immedially following */
126 len = strlen(pass->pw_dir) + 1 + strlen(txt) + 1;
127 temp = el_malloc(len * sizeof(*temp));
130 (void)snprintf(temp, len, "%s/%s", pass->pw_dir, txt);
137 * return first found file name starting by the ``text'' or NULL if no
138 * such file can be found
139 * value of ``state'' is ignored
141 * it's the caller's responsibility to free the returned string
144 fn_filename_completion_function(const char *text, int state)
146 static DIR *dir = NULL;
147 static char *filename = NULL, *dirname = NULL, *dirpath = NULL;
148 static size_t filename_len = 0;
149 struct dirent *entry;
153 if (state == 0 || dir == NULL) {
154 temp = strrchr(text, '/');
158 nptr = el_realloc(filename, (strlen(temp) + 1) *
166 (void)strcpy(filename, temp);
167 len = (size_t)(temp - text); /* including last slash */
169 nptr = el_realloc(dirname, (len + 1) *
177 (void)strncpy(dirname, text, len);
184 filename = strdup(text);
185 if (filename == NULL)
197 /* support for ``~user'' syntax */
201 if (dirname == NULL) {
202 if ((dirname = strdup("")) == NULL)
204 dirpath = strdup("./");
205 } else if (*dirname == '~')
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 HAVE_STRUCT_DIRENT_D_NAMLEN
233 && entry->d_namlen >= filename_len
235 && strlen(entry->d_name) >= filename_len
237 && strncmp(entry->d_name, filename,
242 if (entry) { /* match found */
244 #if HAVE_STRUCT_DIRENT_D_NAMLEN
245 len = entry->d_namlen;
247 len = strlen(entry->d_name);
250 len = strlen(dirname) + len + 1;
251 temp = el_malloc(len * sizeof(*temp));
254 (void)snprintf(temp, len, "%s%s", dirname, entry->d_name);
266 append_char_function(const char *name)
269 char *expname = *name == '~' ? fn_tilde_expand(name) : NULL;
270 const char *rs = " ";
272 if (stat(expname ? expname : name, &stbuf) == -1)
274 if (S_ISDIR(stbuf.st_mode))
282 * returns list of completions for text given
283 * non-static for readline.
285 char ** completion_matches(const char *, char *(*)(const char *, int));
287 completion_matches(const char *text, char *(*genfunc)(const char *, int))
289 char **match_list = NULL, *retstr, *prevstr;
290 size_t match_list_len, max_equal, which, i;
295 while ((retstr = (*genfunc) (text, (int)matches)) != NULL) {
296 /* allow for list terminator here */
297 if (matches + 3 >= match_list_len) {
299 while (matches + 3 >= match_list_len)
300 match_list_len <<= 1;
301 nmatch_list = el_realloc(match_list,
302 match_list_len * sizeof(*nmatch_list));
303 if (nmatch_list == NULL) {
307 match_list = nmatch_list;
310 match_list[++matches] = retstr;
314 return NULL; /* nothing found */
316 /* find least denominator and insert it to match_list[0] */
318 prevstr = match_list[1];
319 max_equal = strlen(prevstr);
320 for (; which <= matches; which++) {
321 for (i = 0; i < max_equal &&
322 prevstr[i] == match_list[which][i]; i++)
327 retstr = el_malloc((max_equal + 1) * sizeof(*retstr));
328 if (retstr == NULL) {
332 (void)strncpy(retstr, match_list[1], max_equal);
333 retstr[max_equal] = '\0';
334 match_list[0] = retstr;
336 /* add NULL as last pointer to the array */
337 match_list[matches + 1] = NULL;
343 * Sort function for qsort(). Just wrapper around strcasecmp().
346 _fn_qsort_string_compare(const void *i1, const void *i2)
348 const char *s1 = ((const char * const *)i1)[0];
349 const char *s2 = ((const char * const *)i2)[0];
351 return strcasecmp(s1, s2);
355 * Display list of strings in columnar format on readline's output stream.
356 * 'matches' is list of strings, 'num' is number of strings in 'matches',
357 * 'width' is maximum length of string in 'matches'.
359 * matches[0] is not one of the match strings, but it is counted in
360 * num, so the strings are matches[1] *through* matches[num-1].
363 fn_display_match_list (EditLine *el, char **matches, size_t num, size_t width)
365 size_t line, lines, col, cols, thisguy;
366 int screenwidth = el->el_terminal.t_size.h;
368 /* Ignore matches[0]. Avoid 1-based array logic below. */
373 * Find out how many entries can be put on one line; count
374 * with one space between strings the same way it's printed.
376 cols = (size_t)screenwidth / (width + 1);
380 /* how many lines of output, rounded up */
381 lines = (num + cols - 1) / cols;
383 /* Sort the items. */
384 qsort(matches, num, sizeof(char *), _fn_qsort_string_compare);
387 * On the ith line print elements i, i+lines, i+lines*2, etc.
389 for (line = 0; line < lines; line++) {
390 for (col = 0; col < cols; col++) {
391 thisguy = line + col * lines;
394 (void)fprintf(el->el_outfile, "%s%-*s",
395 col == 0 ? "" : " ", (int)width, matches[thisguy]);
397 (void)fprintf(el->el_outfile, "\n");
402 * Complete the word at or before point,
403 * 'what_to_do' says what to do with the completion.
404 * \t means do standard completion.
405 * `?' means list the possible completions.
406 * `*' means insert all of the possible completions.
407 * `!' means to do standard completion, and list all possible completions if
408 * there is more than one.
410 * Note: '*' support is not implemented
411 * '!' could never be invoked
414 fn_complete(EditLine *el,
415 char *(*complet_func)(const char *, int),
416 char **(*attempted_completion_function)(const char *, int, int),
417 const Char *word_break, const Char *special_prefixes,
418 const char *(*app_func)(const char *), size_t query_items,
419 int *completion_type, int *over, int *point, int *end,
420 const Char *(*find_word_start_func)(const Char *, const Char *),
421 Char *(*dequoting_func)(const Char *),
422 char *(*quoting_func)(const char *))
424 const TYPE(LineInfo) *li;
430 int what_to_do = '\t';
431 int retval = CC_NORM;
433 if (el->el_state.lastcmd == el->el_state.thiscmd)
436 /* readline's rl_complete() has to be told what we did... */
437 if (completion_type != NULL)
438 *completion_type = what_to_do;
441 complet_func = fn_filename_completion_function;
443 app_func = append_char_function;
445 /* We now look backwards for the start of a filename/variable word */
446 li = FUN(el,line)(el);
447 if (find_word_start_func)
448 ctemp = find_word_start_func(li->buffer, li->cursor);
451 while (ctemp > li->buffer
452 && !Strchr(word_break, ctemp[-1])
453 && (!special_prefixes || !Strchr(special_prefixes, ctemp[-1]) ) )
457 len = (size_t)(li->cursor - ctemp);
458 temp = el_malloc((len + 1) * sizeof(*temp));
459 (void)Strncpy(temp, ctemp, len);
462 if (dequoting_func) {
463 dequoted_temp = dequoting_func(temp);
464 if (dequoted_temp == NULL)
467 dequoted_temp = NULL;
469 /* these can be used by function called in completion_matches() */
470 /* or (*attempted_completion_function)() */
472 *point = (int)(li->cursor - li->buffer);
474 *end = (int)(li->lastchar - li->buffer);
476 if (attempted_completion_function) {
477 int cur_off = (int)(li->cursor - li->buffer);
478 matches = (*attempted_completion_function)(
479 ct_encode_string(dequoted_temp ? dequoted_temp : temp,
481 cur_off - (int)len, cur_off);
484 if (!attempted_completion_function ||
485 (over != NULL && !*over && !matches))
486 matches = completion_matches(
487 ct_encode_string(dequoted_temp ? dequoted_temp : temp,
488 &el->el_scratch), complet_func);
495 size_t matches_num, maxlen, match_len, match_display=1;
499 * Only replace the completed string with common part of
500 * possible matches if there is possible completion.
502 if (matches[0][0] != '\0') {
505 quoted_match = quoting_func(matches[0]);
506 if (quoted_match == NULL)
510 el_deletestr(el, (int) len);
511 FUN(el,insertstr)(el,
512 ct_decode_string(quoted_match ? quoted_match :
513 matches[0] , &el->el_scratch));
516 if (what_to_do == '?')
517 goto display_matches;
519 if (matches[2] == NULL &&
520 (matches[1] == NULL || strcmp(matches[0], matches[1]) == 0)) {
522 * We found exact match. Add a space after
523 * it, unless we do filename completion and the
524 * object is a directory.
526 FUN(el,insertstr)(el,
527 ct_decode_string((*app_func)(matches[0]),
529 } else if (what_to_do == '!') {
532 * More than one match and requested to list possible
536 for(i = 1, maxlen = 0; matches[i]; i++) {
537 match_len = strlen(matches[i]);
538 if (match_len > maxlen)
541 /* matches[1] through matches[i-1] are available */
542 matches_num = (size_t)(i - 1);
544 /* newline to get on next line from command line */
545 (void)fprintf(el->el_outfile, "\n");
548 * If there are too many items, ask user for display
551 if (matches_num > query_items) {
552 (void)fprintf(el->el_outfile,
553 "Display all %zu possibilities? (y or n) ",
555 (void)fflush(el->el_outfile);
556 if (getc(stdin) != 'y')
558 (void)fprintf(el->el_outfile, "\n");
563 * Interface of this function requires the
564 * strings be matches[1..num-1] for compat.
565 * We have matches_num strings not counting
566 * the prefix in matches[0], so we need to
567 * add 1 to matches_num for the call.
569 fn_display_match_list(el, matches,
570 matches_num+1, maxlen);
572 retval = CC_REDISPLAY;
573 } else if (matches[0][0]) {
575 * There was some common match, but the name was
576 * not complete enough. Next tab will print possible
581 /* lcd is not a valid object - further specification */
588 /* free elements of array and the array itself */
589 for (i = 0; matches[i]; i++)
600 * el-compatible wrapper around rl_complete; needed for key binding
604 _el_fn_complete(EditLine *el, int ch __attribute__((__unused__)))
606 return (unsigned char)fn_complete(el, NULL, NULL,
607 break_chars, NULL, NULL, (size_t)100,
608 NULL, NULL, NULL, NULL,
613 sh_find_word_start(const Char *buffer, const Char *cursor)
615 const Char *word_start = buffer;
617 while (buffer < cursor) {
620 else if (Strchr(break_chars, *buffer))
621 word_start = buffer + 1;
628 sh_quote(const char *str)
632 char *quoted_str, *dst;
634 for (src = str; *src != '\0'; src++)
635 if (Strchr(break_chars, *src) ||
636 Strchr(extra_quote_chars, *src))
639 quoted_str = malloc(sizeof(*quoted_str) *
640 (strlen(str) + extra_len + 1));
641 if (quoted_str == NULL)
645 for (src = str; *src != '\0'; src++) {
646 if (Strchr(break_chars, *src) ||
647 Strchr(extra_quote_chars, *src))
657 sh_dequote(const Char *str)
659 Char *dequoted_str, *dst;
661 /* save extra space to replace \~ with ./~ */
662 dequoted_str = malloc(sizeof(*dequoted_str) * (Strlen(str) + 1 + 1));
663 if (dequoted_str == NULL)
668 /* dequote \~ at start as ./~ */
669 if (*str == '\\' && str[1] == '~') {
687 * completion function using sh quoting rules; for key binding
691 _el_fn_sh_complete(EditLine *el, int ch __attribute__((__unused__)))
693 return (unsigned char)fn_complete(el, NULL, NULL,
694 break_chars, NULL, NULL, 100,
695 NULL, NULL, NULL, NULL,
696 sh_find_word_start, sh_dequote, sh_quote);