1 /* $NetBSD: filecomplete.c,v 1.44 2016/10/31 17:46:32 abhinav 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.44 2016/10/31 17:46:32 abhinav Exp $");
36 #endif /* not lint && not SCCSID */
38 #include <sys/types.h>
51 #include "filecomplete.h"
53 static const wchar_t break_chars[] = L" \t\n\"\\'`@$><=;|&{(";
55 /********************************/
56 /* completion functions */
59 * does tilde expansion of strings of type ``~user/foo''
60 * if ``user'' isn't valid user name or ``txt'' doesn't start
61 * w/ '~', returns pointer to strdup()ed copy of ``txt''
63 * it's the caller's responsibility to free() the returned string
66 fn_tilde_expand(const char *txt)
68 #if defined(HAVE_GETPW_R_POSIX) || defined(HAVE_GETPW_R_DRAFT)
79 temp = strchr(txt + 1, '/');
81 temp = strdup(txt + 1);
85 /* text until string after slash */
86 len = (size_t)(temp - txt + 1);
87 temp = el_malloc(len * sizeof(*temp));
90 (void)strncpy(temp, txt + 1, len - 2);
94 #ifdef HAVE_GETPW_R_POSIX
95 if (getpwuid_r(getuid(), &pwres, pwbuf, sizeof(pwbuf),
98 #elif HAVE_GETPW_R_DRAFT
99 pass = getpwuid_r(getuid(), &pwres, pwbuf, sizeof(pwbuf));
101 pass = getpwuid(getuid());
104 #ifdef HAVE_GETPW_R_POSIX
105 if (getpwnam_r(temp, &pwres, pwbuf, sizeof(pwbuf), &pass) != 0)
107 #elif HAVE_GETPW_R_DRAFT
108 pass = getpwnam_r(temp, &pwres, pwbuf, sizeof(pwbuf));
110 pass = getpwnam(temp);
113 el_free(temp); /* value no more needed */
117 /* update pointer txt to point at string immedially following */
121 len = strlen(pass->pw_dir) + 1 + strlen(txt) + 1;
122 temp = el_malloc(len * sizeof(*temp));
125 (void)snprintf(temp, len, "%s/%s", pass->pw_dir, txt);
132 * return first found file name starting by the ``text'' or NULL if no
133 * such file can be found
134 * value of ``state'' is ignored
136 * it's the caller's responsibility to free the returned string
139 fn_filename_completion_function(const char *text, int state)
141 static DIR *dir = NULL;
142 static char *filename = NULL, *dirname = NULL, *dirpath = NULL;
143 static size_t filename_len = 0;
144 struct dirent *entry;
148 if (state == 0 || dir == NULL) {
149 temp = strrchr(text, '/');
153 nptr = el_realloc(filename, (strlen(temp) + 1) *
161 (void)strcpy(filename, temp);
162 len = (size_t)(temp - text); /* including last slash */
164 nptr = el_realloc(dirname, (len + 1) *
172 (void)strncpy(dirname, text, len);
179 filename = strdup(text);
180 if (filename == NULL)
192 /* support for ``~user'' syntax */
196 if (dirname == NULL) {
197 if ((dirname = strdup("")) == NULL)
199 dirpath = strdup("./");
200 } else if (*dirname == '~')
201 dirpath = fn_tilde_expand(dirname);
203 dirpath = strdup(dirname);
208 dir = opendir(dirpath);
210 return NULL; /* cannot open the directory */
212 /* will be used in cycle */
213 filename_len = filename ? strlen(filename) : 0;
217 while ((entry = readdir(dir)) != NULL) {
219 if (entry->d_name[0] == '.' && (!entry->d_name[1]
220 || (entry->d_name[1] == '.' && !entry->d_name[2])))
222 if (filename_len == 0)
224 /* otherwise, get first entry where first */
225 /* filename_len characters are equal */
226 if (entry->d_name[0] == filename[0]
227 /* Some dirents have d_namlen, but it is not portable. */
228 && strlen(entry->d_name) >= filename_len
229 && strncmp(entry->d_name, filename,
234 if (entry) { /* match found */
236 /* Some dirents have d_namlen, but it is not portable. */
237 len = strlen(entry->d_name);
239 len = strlen(dirname) + len + 1;
240 temp = el_malloc(len * sizeof(*temp));
243 (void)snprintf(temp, len, "%s%s", dirname, entry->d_name);
255 append_char_function(const char *name)
258 char *expname = *name == '~' ? fn_tilde_expand(name) : NULL;
259 const char *rs = " ";
261 if (stat(expname ? expname : name, &stbuf) == -1)
263 if (S_ISDIR(stbuf.st_mode))
271 * returns list of completions for text given
272 * non-static for readline.
274 char ** completion_matches(const char *, char *(*)(const char *, int));
276 completion_matches(const char *text, char *(*genfunc)(const char *, int))
278 char **match_list = NULL, *retstr, *prevstr;
279 size_t match_list_len, max_equal, which, i;
284 while ((retstr = (*genfunc) (text, (int)matches)) != NULL) {
285 /* allow for list terminator here */
286 if (matches + 3 >= match_list_len) {
288 while (matches + 3 >= match_list_len)
289 match_list_len <<= 1;
290 nmatch_list = el_realloc(match_list,
291 match_list_len * sizeof(*nmatch_list));
292 if (nmatch_list == NULL) {
296 match_list = nmatch_list;
299 match_list[++matches] = retstr;
303 return NULL; /* nothing found */
305 /* find least denominator and insert it to match_list[0] */
307 prevstr = match_list[1];
308 max_equal = strlen(prevstr);
309 for (; which <= matches; which++) {
310 for (i = 0; i < max_equal &&
311 prevstr[i] == match_list[which][i]; i++)
316 retstr = el_malloc((max_equal + 1) * sizeof(*retstr));
317 if (retstr == NULL) {
321 (void)strncpy(retstr, match_list[1], max_equal);
322 retstr[max_equal] = '\0';
323 match_list[0] = retstr;
325 /* add NULL as last pointer to the array */
326 match_list[matches + 1] = NULL;
332 * Sort function for qsort(). Just wrapper around strcasecmp().
335 _fn_qsort_string_compare(const void *i1, const void *i2)
337 const char *s1 = ((const char * const *)i1)[0];
338 const char *s2 = ((const char * const *)i2)[0];
340 return strcasecmp(s1, s2);
344 * Display list of strings in columnar format on readline's output stream.
345 * 'matches' is list of strings, 'num' is number of strings in 'matches',
346 * 'width' is maximum length of string in 'matches'.
348 * matches[0] is not one of the match strings, but it is counted in
349 * num, so the strings are matches[1] *through* matches[num-1].
352 fn_display_match_list (EditLine *el, char **matches, size_t num, size_t width)
354 size_t line, lines, col, cols, thisguy;
355 int screenwidth = el->el_terminal.t_size.h;
357 /* Ignore matches[0]. Avoid 1-based array logic below. */
362 * Find out how many entries can be put on one line; count
363 * with one space between strings the same way it's printed.
365 cols = (size_t)screenwidth / (width + 1);
369 /* how many lines of output, rounded up */
370 lines = (num + cols - 1) / cols;
372 /* Sort the items. */
373 qsort(matches, num, sizeof(char *), _fn_qsort_string_compare);
376 * On the ith line print elements i, i+lines, i+lines*2, etc.
378 for (line = 0; line < lines; line++) {
379 for (col = 0; col < cols; col++) {
380 thisguy = line + col * lines;
383 (void)fprintf(el->el_outfile, "%s%-*s",
384 col == 0 ? "" : " ", (int)width, matches[thisguy]);
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 wchar_t *word_break, const wchar_t *special_prefixes,
407 const char *(*app_func)(const char *), size_t query_items,
408 int *completion_type, int *over, int *point, int *end)
413 const wchar_t *ctemp;
415 int what_to_do = '\t';
416 int retval = CC_NORM;
418 if (el->el_state.lastcmd == el->el_state.thiscmd)
421 /* readline's rl_complete() has to be told what we did... */
422 if (completion_type != NULL)
423 *completion_type = what_to_do;
426 complet_func = fn_filename_completion_function;
428 app_func = append_char_function;
430 /* We now look backwards for the start of a filename/variable word */
433 while (ctemp > li->buffer
434 && !wcschr(word_break, ctemp[-1])
435 && (!special_prefixes || !wcschr(special_prefixes, ctemp[-1]) ) )
438 len = (size_t)(li->cursor - ctemp);
439 temp = el_malloc((len + 1) * sizeof(*temp));
440 (void)wcsncpy(temp, ctemp, len);
443 /* these can be used by function called in completion_matches() */
444 /* or (*attempted_completion_function)() */
446 *point = (int)(li->cursor - li->buffer);
448 *end = (int)(li->lastchar - li->buffer);
450 if (attempted_completion_function) {
451 int cur_off = (int)(li->cursor - li->buffer);
452 matches = (*attempted_completion_function)(
453 ct_encode_string(temp, &el->el_scratch),
454 cur_off - (int)len, cur_off);
457 if (!attempted_completion_function ||
458 (over != NULL && !*over && !matches))
459 matches = completion_matches(
460 ct_encode_string(temp, &el->el_scratch), complet_func);
467 size_t matches_num, maxlen, match_len, match_display=1;
471 * Only replace the completed string with common part of
472 * possible matches if there is possible completion.
474 if (matches[0][0] != '\0') {
475 el_deletestr(el, (int) len);
477 ct_decode_string(matches[0], &el->el_scratch));
481 if (matches[2] == NULL &&
482 (matches[1] == NULL || strcmp(matches[0], matches[1]) == 0)) {
484 * We found exact match. Add a space after
485 * it, unless we do filename completion and the
486 * object is a directory.
489 ct_decode_string((*app_func)(matches[0]),
491 } else if (what_to_do == '!' || what_to_do == '?') {
493 * More than one match and requested to list possible
497 for(i = 1, maxlen = 0; matches[i]; i++) {
498 match_len = strlen(matches[i]);
499 if (match_len > maxlen)
502 /* matches[1] through matches[i-1] are available */
503 matches_num = (size_t)(i - 1);
505 /* newline to get on next line from command line */
506 (void)fprintf(el->el_outfile, "\n");
509 * If there are too many items, ask user for display
512 if (matches_num > query_items) {
513 (void)fprintf(el->el_outfile,
514 "Display all %zu possibilities? (y or n) ",
516 (void)fflush(el->el_outfile);
517 if (getc(stdin) != 'y')
519 (void)fprintf(el->el_outfile, "\n");
524 * Interface of this function requires the
525 * strings be matches[1..num-1] for compat.
526 * We have matches_num strings not counting
527 * the prefix in matches[0], so we need to
528 * add 1 to matches_num for the call.
530 fn_display_match_list(el, matches,
531 matches_num+1, maxlen);
533 retval = CC_REDISPLAY;
534 } else if (matches[0][0]) {
536 * There was some common match, but the name was
537 * not complete enough. Next tab will print possible
542 /* lcd is not a valid object - further specification */
548 /* free elements of array and the array itself */
549 for (i = 0; matches[i]; i++)
559 * el-compatible wrapper around rl_complete; needed for key binding
563 _el_fn_complete(EditLine *el, int ch __attribute__((__unused__)))
565 return (unsigned char)fn_complete(el, NULL, NULL,
566 break_chars, NULL, NULL, (size_t)100,
567 NULL, NULL, NULL, NULL);