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.11 2008/04/29 06:53:01 martin Exp $
34 #include <sys/types.h>
55 #include "fcns.h" /* for EL_NUM_FCNS */
57 #include "filecomplete.h"
59 static char break_chars[] = { ' ', '\t', '\n', '"', '\\', '\'', '`', '@', '$',
60 '>', '<', '=', ';', '|', '&', '{', '(', '\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 callers's responsibility to free() returned string
74 fn_tilde_expand(const char *txt)
76 struct passwd pwres, *pass;
84 temp = strchr(txt + 1, '/');
86 temp = strdup(txt + 1);
90 len = temp - txt + 1; /* text until string after slash */
94 (void)strncpy(temp, txt + 1, len - 2);
98 if (getpwuid_r(getuid(), &pwres, pwbuf, sizeof(pwbuf), &pass) != 0)
101 if (getpwnam_r(temp, &pwres, pwbuf, sizeof(pwbuf), &pass) != 0)
104 free(temp); /* value no more needed */
106 return (strdup(txt));
108 /* update pointer txt to point at string immedially following */
112 temp = malloc(strlen(pass->pw_dir) + 1 + strlen(txt) + 1);
115 (void)sprintf(temp, "%s/%s", pass->pw_dir, txt);
122 * return first found file name starting by the ``text'' or NULL if no
123 * such file can be found
124 * value of ``state'' is ignored
126 * it's caller's responsibility to free returned string
129 fn_filename_completion_function(const char *text, int state)
131 static DIR *dir = NULL;
132 static char *filename = NULL, *dirname = NULL, *dirpath = NULL;
133 static size_t filename_len = 0;
134 struct dirent *entry;
138 if (state == 0 || dir == NULL) {
139 temp = strrchr(text, '/');
143 nptr = realloc(filename, strlen(temp) + 1);
149 (void)strcpy(filename, temp);
150 len = temp - text; /* including last slash */
151 nptr = realloc(dirname, len + 1);
157 (void)strncpy(dirname, text, len);
163 filename = strdup(text);
164 if (filename == NULL)
175 /* support for ``~user'' syntax */
178 if (dirname == NULL && (dirname = strdup("./")) == NULL)
182 dirpath = fn_tilde_expand(dirname);
184 dirpath = strdup(dirname);
189 dir = opendir(dirpath);
191 return (NULL); /* cannot open the directory */
193 /* will be used in cycle */
194 filename_len = filename ? strlen(filename) : 0;
198 while ((entry = readdir(dir)) != NULL) {
200 if (entry->d_name[0] == '.' && (!entry->d_name[1]
201 || (entry->d_name[1] == '.' && !entry->d_name[2])))
203 if (filename_len == 0)
205 /* otherwise, get first entry where first */
206 /* filename_len characters are equal */
207 if (entry->d_name[0] == filename[0]
208 #if defined(__SVR4) || defined(__linux__)
209 && strlen(entry->d_name) >= filename_len
211 && entry->d_namlen >= filename_len
213 && strncmp(entry->d_name, filename,
218 if (entry) { /* match found */
220 #if defined(__SVR4) || defined(__linux__)
221 len = strlen(entry->d_name);
223 len = entry->d_namlen;
226 temp = malloc(strlen(dirname) + len + 1);
229 (void)sprintf(temp, "%s%s", dirname, entry->d_name);
241 append_char_function(const char *name)
244 char *expname = *name == '~' ? fn_tilde_expand(name) : NULL;
247 if (stat(expname ? expname : name, &stbuf) == -1)
249 if (S_ISDIR(stbuf.st_mode))
257 * returns list of completions for text given
258 * non-static for readline.
260 char ** completion_matches(const char *, char *(*)(const char *, int));
262 completion_matches(const char *text, char *(*genfunc)(const char *, int))
264 char **match_list = NULL, *retstr, *prevstr;
265 size_t match_list_len, max_equal, which, i;
270 while ((retstr = (*genfunc) (text, (int)matches)) != NULL) {
271 /* allow for list terminator here */
272 if (matches + 3 >= match_list_len) {
274 while (matches + 3 >= match_list_len)
275 match_list_len <<= 1;
276 nmatch_list = realloc(match_list,
277 match_list_len * sizeof(char *));
278 if (nmatch_list == NULL) {
282 match_list = nmatch_list;
285 match_list[++matches] = retstr;
289 return NULL; /* nothing found */
291 /* find least denominator and insert it to match_list[0] */
293 prevstr = match_list[1];
294 max_equal = strlen(prevstr);
295 for (; which <= matches; which++) {
296 for (i = 0; i < max_equal &&
297 prevstr[i] == match_list[which][i]; i++)
302 retstr = malloc(max_equal + 1);
303 if (retstr == NULL) {
307 (void)strncpy(retstr, match_list[1], max_equal);
308 retstr[max_equal] = '\0';
309 match_list[0] = retstr;
311 /* add NULL as last pointer to the array */
312 match_list[matches + 1] = NULL;
318 * Sort function for qsort(). Just wrapper around strcasecmp().
321 _fn_qsort_string_compare(const void *i1, const void *i2)
323 const char *s1 = ((const char * const *)i1)[0];
324 const char *s2 = ((const char * const *)i2)[0];
326 return strcasecmp(s1, s2);
330 * Display list of strings in columnar format on readline's output stream.
331 * 'matches' is list of strings, 'len' is number of strings in 'matches',
332 * 'max' is maximum length of string in 'matches'.
335 fn_display_match_list (EditLine *el, char **matches, int len, int max)
337 int i, idx, limit, count;
338 int screenwidth = el->el_term.t_size.h;
341 * Find out how many entries can be put on one line, count
342 * with two spaces between strings.
344 limit = screenwidth / (max + 2);
348 /* how many lines of output */
350 if (count * limit < len)
353 /* Sort the items if they are not already sorted. */
354 qsort(&matches[1], (size_t)(len - 1), sizeof(char *),
355 _fn_qsort_string_compare);
358 for(; count > 0; count--) {
359 for(i = 0; i < limit && matches[idx]; i++, idx++)
360 (void)fprintf(el->el_outfile, "%-*s ", max,
362 (void)fprintf(el->el_outfile, "\n");
367 * Complete the word at or before point,
368 * 'what_to_do' says what to do with the completion.
369 * \t means do standard completion.
370 * `?' means list the possible completions.
371 * `*' means insert all of the possible completions.
372 * `!' means to do standard completion, and list all possible completions if
373 * there is more than one.
375 * Note: '*' support is not implemented
376 * '!' could never be invoked
379 fn_complete(EditLine *el,
380 char *(*complet_func)(const char *, int),
381 char **(*attempted_completion_function)(const char *, int, int),
382 const char *word_break, const char *special_prefixes,
383 const char *(*app_func)(const char *), int query_items,
384 int *completion_type, int *over, int *point, int *end)
387 char *temp, **matches;
390 int what_to_do = '\t';
391 int retval = CC_NORM;
393 if (el->el_state.lastcmd == el->el_state.thiscmd)
396 /* readline's rl_complete() has to be told what we did... */
397 if (completion_type != NULL)
398 *completion_type = what_to_do;
401 complet_func = fn_filename_completion_function;
403 app_func = append_char_function;
405 /* We now look backwards for the start of a filename/variable word */
407 ctemp = (const char *) li->cursor;
408 while (ctemp > li->buffer
409 && !strchr(word_break, ctemp[-1])
410 && (!special_prefixes || !strchr(special_prefixes, ctemp[-1]) ) )
413 len = li->cursor - ctemp;
414 #if defined(__SSP__) || defined(__SSP_ALL__)
415 temp = malloc(len + 1);
417 temp = alloca(len + 1);
419 (void)strncpy(temp, ctemp, len);
422 /* these can be used by function called in completion_matches() */
423 /* or (*attempted_completion_function)() */
425 *point = li->cursor - li->buffer;
427 *end = li->lastchar - li->buffer;
429 if (attempted_completion_function) {
430 int cur_off = li->cursor - li->buffer;
431 matches = (*attempted_completion_function) (temp,
432 (int)(cur_off - len), cur_off);
435 if (!attempted_completion_function ||
436 (over != NULL && !*over && !matches))
437 matches = completion_matches(temp, complet_func);
444 int matches_num, maxlen, match_len, match_display=1;
448 * Only replace the completed string with common part of
449 * possible matches if there is possible completion.
451 if (matches[0][0] != '\0') {
452 el_deletestr(el, (int) len);
453 el_insertstr(el, matches[0]);
456 if (what_to_do == '?')
457 goto display_matches;
459 if (matches[2] == NULL && strcmp(matches[0], matches[1]) == 0) {
461 * We found exact match. Add a space after
462 * it, unless we do filename completion and the
463 * object is a directory.
465 el_insertstr(el, (*append_char_function)(matches[0]));
466 } else if (what_to_do == '!') {
469 * More than one match and requested to list possible
473 for(i=1, maxlen=0; matches[i]; i++) {
474 match_len = strlen(matches[i]);
475 if (match_len > maxlen)
480 /* newline to get on next line from command line */
481 (void)fprintf(el->el_outfile, "\n");
484 * If there are too many items, ask user for display
487 if (matches_num > query_items) {
488 (void)fprintf(el->el_outfile,
489 "Display all %d possibilities? (y or n) ",
491 (void)fflush(el->el_outfile);
492 if (getc(stdin) != 'y')
494 (void)fprintf(el->el_outfile, "\n");
498 fn_display_match_list(el, matches, matches_num,
500 retval = CC_REDISPLAY;
501 } else if (matches[0][0]) {
503 * There was some common match, but the name was
504 * not complete enough. Next tab will print possible
509 /* lcd is not a valid object - further specification */
515 /* free elements of array and the array itself */
516 for (i = 0; matches[i]; i++)
521 #if defined(__SSP__) || defined(__SSP_ALL__)
528 * el-compatible wrapper around rl_complete; needed for key binding
532 _el_fn_complete(EditLine *el, int ch __attribute__((__unused__)))
534 return (unsigned char)fn_complete(el, NULL, NULL,
535 break_chars, NULL, NULL, 100,
536 NULL, NULL, NULL, NULL);