filecomplete.c revision 1.26 1 /* $NetBSD: filecomplete.c,v 1.26 2011/07/28 20:50:55 christos Exp $ */
2
3 /*-
4 * Copyright (c) 1997 The NetBSD Foundation, Inc.
5 * All rights reserved.
6 *
7 * This code is derived from software contributed to The NetBSD Foundation
8 * by Jaromir Dolecek.
9 *
10 * Redistribution and use in source and binary forms, with or without
11 * modification, are permitted provided that the following conditions
12 * are met:
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.
18 *
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.
30 */
31
32 #include "config.h"
33 #if !defined(lint) && !defined(SCCSID)
34 __RCSID("$NetBSD: filecomplete.c,v 1.26 2011/07/28 20:50:55 christos Exp $");
35 #endif /* not lint && not SCCSID */
36
37 #include <sys/types.h>
38 #include <sys/stat.h>
39 #include <stdio.h>
40 #include <dirent.h>
41 #include <string.h>
42 #include <pwd.h>
43 #include <ctype.h>
44 #include <stdlib.h>
45 #include <unistd.h>
46 #include <limits.h>
47 #include <errno.h>
48 #include <fcntl.h>
49 #ifdef HAVE_VIS_H
50 #include <vis.h>
51 #else
52 #include "vis.h"
53 #endif
54 #include "el.h"
55 #include "fcns.h" /* for EL_NUM_FCNS */
56 #include "histedit.h"
57 #include "filecomplete.h"
58
59 static const Char break_chars[] = { ' ', '\t', '\n', '"', '\\', '\'', '`', '@',
60 '$', '>', '<', '=', ';', '|', '&', '{', '(', '\0' };
61
62
63 /********************************/
64 /* completion functions */
65
66 /*
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''
70 *
71 * it's callers's responsibility to free() returned string
72 */
73 char *
74 fn_tilde_expand(const char *txt)
75 {
76 #if defined(HAVE_GETPW_R_POSIX) || defined(HAVE_GETPW_R_DRAFT)
77 struct passwd pwres;
78 char pwbuf[1024];
79 #endif
80 struct passwd *pass;
81 char *temp;
82 size_t len = 0;
83
84 if (txt[0] != '~')
85 return (strdup(txt));
86
87 temp = strchr(txt + 1, '/');
88 if (temp == NULL) {
89 temp = strdup(txt + 1);
90 if (temp == NULL)
91 return NULL;
92 } else {
93 len = temp - txt + 1; /* text until string after slash */
94 temp = el_malloc(len * sizeof(*temp));
95 if (temp == NULL)
96 return NULL;
97 (void)strncpy(temp, txt + 1, len - 2);
98 temp[len - 2] = '\0';
99 }
100 if (temp[0] == 0) {
101 #ifdef HAVE_GETPW_R_POSIX
102 if (getpwuid_r(getuid(), &pwres, pwbuf, sizeof(pwbuf),
103 &pass) != 0)
104 pass = NULL;
105 #elif HAVE_GETPW_R_DRAFT
106 pass = getpwuid_r(getuid(), &pwres, pwbuf, sizeof(pwbuf));
107 #else
108 pass = getpwuid(getuid());
109 #endif
110 } else {
111 #ifdef HAVE_GETPW_R_POSIX
112 if (getpwnam_r(temp, &pwres, pwbuf, sizeof(pwbuf), &pass) != 0)
113 pass = NULL;
114 #elif HAVE_GETPW_R_DRAFT
115 pass = getpwnam_r(temp, &pwres, pwbuf, sizeof(pwbuf));
116 #else
117 pass = getpwnam(temp);
118 #endif
119 }
120 el_free(temp); /* value no more needed */
121 if (pass == NULL)
122 return (strdup(txt));
123
124 /* update pointer txt to point at string immedially following */
125 /* first slash */
126 txt += len;
127
128 len = strlen(pass->pw_dir) + 1 + strlen(txt) + 1;
129 temp = el_malloc(len * sizeof(*temp));
130 if (temp == NULL)
131 return NULL;
132 (void)snprintf(temp, len, "%s/%s", pass->pw_dir, txt);
133
134 return (temp);
135 }
136
137
138 /*
139 * return first found file name starting by the ``text'' or NULL if no
140 * such file can be found
141 * value of ``state'' is ignored
142 *
143 * it's caller's responsibility to free returned string
144 */
145 char *
146 fn_filename_completion_function(const char *text, int state)
147 {
148 static DIR *dir = NULL;
149 static char *filename = NULL, *dirname = NULL, *dirpath = NULL;
150 static size_t filename_len = 0;
151 struct dirent *entry;
152 char *temp;
153 size_t len;
154
155 if (state == 0 || dir == NULL) {
156 temp = strrchr(text, '/');
157 if (temp) {
158 char *nptr;
159 temp++;
160 nptr = el_realloc(filename, (strlen(temp) + 1) *
161 sizeof(*nptr));
162 if (nptr == NULL) {
163 el_free(filename);
164 filename = NULL;
165 return NULL;
166 }
167 filename = nptr;
168 (void)strcpy(filename, temp);
169 len = temp - text; /* including last slash */
170
171 nptr = el_realloc(dirname, (len + 1) *
172 sizeof(*nptr));
173 if (nptr == NULL) {
174 el_free(dirname);
175 dirname = NULL;
176 return NULL;
177 }
178 dirname = nptr;
179 (void)strncpy(dirname, text, len);
180 dirname[len] = '\0';
181 } else {
182 el_free(filename);
183 if (*text == 0)
184 filename = NULL;
185 else {
186 filename = strdup(text);
187 if (filename == NULL)
188 return NULL;
189 }
190 el_free(dirname);
191 dirname = NULL;
192 }
193
194 if (dir != NULL) {
195 (void)closedir(dir);
196 dir = NULL;
197 }
198
199 /* support for ``~user'' syntax */
200
201 el_free(dirpath);
202 dirpath = NULL;
203 if (dirname == NULL) {
204 if ((dirname = strdup("")) == NULL)
205 return NULL;
206 dirpath = strdup("./");
207 } else if (*dirname == '~')
208 dirpath = fn_tilde_expand(dirname);
209 else
210 dirpath = strdup(dirname);
211
212 if (dirpath == NULL)
213 return NULL;
214
215 dir = opendir(dirpath);
216 if (!dir)
217 return (NULL); /* cannot open the directory */
218
219 /* will be used in cycle */
220 filename_len = filename ? strlen(filename) : 0;
221 }
222
223 /* find the match */
224 while ((entry = readdir(dir)) != NULL) {
225 /* skip . and .. */
226 if (entry->d_name[0] == '.' && (!entry->d_name[1]
227 || (entry->d_name[1] == '.' && !entry->d_name[2])))
228 continue;
229 if (filename_len == 0)
230 break;
231 /* otherwise, get first entry where first */
232 /* filename_len characters are equal */
233 if (entry->d_name[0] == filename[0]
234 #if HAVE_STRUCT_DIRENT_D_NAMLEN
235 && entry->d_namlen >= filename_len
236 #else
237 && strlen(entry->d_name) >= filename_len
238 #endif
239 && strncmp(entry->d_name, filename,
240 filename_len) == 0)
241 break;
242 }
243
244 if (entry) { /* match found */
245
246 #if HAVE_STRUCT_DIRENT_D_NAMLEN
247 len = entry->d_namlen;
248 #else
249 len = strlen(entry->d_name);
250 #endif
251
252 len = strlen(dirname) + len + 1;
253 temp = el_malloc(len * sizeof(*temp));
254 if (temp == NULL)
255 return NULL;
256 (void)snprintf(temp, len, "%s%s", dirname, entry->d_name);
257 } else {
258 (void)closedir(dir);
259 dir = NULL;
260 temp = NULL;
261 }
262
263 return (temp);
264 }
265
266
267 static const char *
268 append_char_function(const char *name)
269 {
270 struct stat stbuf;
271 char *expname = *name == '~' ? fn_tilde_expand(name) : NULL;
272 const char *rs = " ";
273
274 if (stat(expname ? expname : name, &stbuf) == -1)
275 goto out;
276 if (S_ISDIR(stbuf.st_mode))
277 rs = "/";
278 out:
279 if (expname)
280 el_free(expname);
281 return rs;
282 }
283 /*
284 * returns list of completions for text given
285 * non-static for readline.
286 */
287 char ** completion_matches(const char *, char *(*)(const char *, int));
288 char **
289 completion_matches(const char *text, char *(*genfunc)(const char *, int))
290 {
291 char **match_list = NULL, *retstr, *prevstr;
292 size_t match_list_len, max_equal, which, i;
293 size_t matches;
294
295 matches = 0;
296 match_list_len = 1;
297 while ((retstr = (*genfunc) (text, (int)matches)) != NULL) {
298 /* allow for list terminator here */
299 if (matches + 3 >= match_list_len) {
300 char **nmatch_list;
301 while (matches + 3 >= match_list_len)
302 match_list_len <<= 1;
303 nmatch_list = el_realloc(match_list,
304 match_list_len * sizeof(*nmatch_list));
305 if (nmatch_list == NULL) {
306 el_free(match_list);
307 return NULL;
308 }
309 match_list = nmatch_list;
310
311 }
312 match_list[++matches] = retstr;
313 }
314
315 if (!match_list)
316 return NULL; /* nothing found */
317
318 /* find least denominator and insert it to match_list[0] */
319 which = 2;
320 prevstr = match_list[1];
321 max_equal = strlen(prevstr);
322 for (; which <= matches; which++) {
323 for (i = 0; i < max_equal &&
324 prevstr[i] == match_list[which][i]; i++)
325 continue;
326 max_equal = i;
327 }
328
329 retstr = el_malloc((max_equal + 1) * sizeof(*retstr));
330 if (retstr == NULL) {
331 el_free(match_list);
332 return NULL;
333 }
334 (void)strncpy(retstr, match_list[1], max_equal);
335 retstr[max_equal] = '\0';
336 match_list[0] = retstr;
337
338 /* add NULL as last pointer to the array */
339 match_list[matches + 1] = (char *) NULL;
340
341 return (match_list);
342 }
343
344 /*
345 * Sort function for qsort(). Just wrapper around strcasecmp().
346 */
347 static int
348 _fn_qsort_string_compare(const void *i1, const void *i2)
349 {
350 const char *s1 = ((const char * const *)i1)[0];
351 const char *s2 = ((const char * const *)i2)[0];
352
353 return strcasecmp(s1, s2);
354 }
355
356 /*
357 * Display list of strings in columnar format on readline's output stream.
358 * 'matches' is list of strings, 'num' is number of strings in 'matches',
359 * 'width' is maximum length of string in 'matches'.
360 *
361 * matches[0] is not one of the match strings, but it is counted in
362 * num, so the strings are matches[1] *through* matches[num-1].
363 */
364 void
365 fn_display_match_list (EditLine *el, char **matches, size_t num, size_t width)
366 {
367 size_t line, lines, col, cols, thisguy;
368 int screenwidth = el->el_terminal.t_size.h;
369
370 /* Ignore matches[0]. Avoid 1-based array logic below. */
371 matches++;
372 num--;
373
374 /*
375 * Find out how many entries can be put on one line; count
376 * with one space between strings the same way it's printed.
377 */
378 cols = screenwidth / (width + 1);
379 if (cols == 0)
380 cols = 1;
381
382 /* how many lines of output, rounded up */
383 lines = (num + cols - 1) / cols;
384
385 /* Sort the items. */
386 qsort(matches, num, sizeof(char *), _fn_qsort_string_compare);
387
388 /*
389 * On the ith line print elements i, i+lines, i+lines*2, etc.
390 */
391 for (line = 0; line < lines; line++) {
392 for (col = 0; col < cols; col++) {
393 thisguy = line + col * lines;
394 if (thisguy >= num)
395 break;
396 (void)fprintf(el->el_outfile, "%s%-*s",
397 col == 0 ? "" : " ", (int)width, matches[thisguy]);
398 }
399 (void)fprintf(el->el_outfile, "\n");
400 }
401 }
402
403 /*
404 * Complete the word at or before point,
405 * 'what_to_do' says what to do with the completion.
406 * \t means do standard completion.
407 * `?' means list the possible completions.
408 * `*' means insert all of the possible completions.
409 * `!' means to do standard completion, and list all possible completions if
410 * there is more than one.
411 *
412 * Note: '*' support is not implemented
413 * '!' could never be invoked
414 */
415 int
416 fn_complete(EditLine *el,
417 char *(*complet_func)(const char *, int),
418 char **(*attempted_completion_function)(const char *, int, int),
419 const Char *word_break, const Char *special_prefixes,
420 const char *(*app_func)(const char *), size_t query_items,
421 int *completion_type, int *over, int *point, int *end)
422 {
423 const TYPE(LineInfo) *li;
424 Char *temp;
425 char **matches;
426 const Char *ctemp;
427 size_t len;
428 int what_to_do = '\t';
429 int retval = CC_NORM;
430
431 if (el->el_state.lastcmd == el->el_state.thiscmd)
432 what_to_do = '?';
433
434 /* readline's rl_complete() has to be told what we did... */
435 if (completion_type != NULL)
436 *completion_type = what_to_do;
437
438 if (!complet_func)
439 complet_func = fn_filename_completion_function;
440 if (!app_func)
441 app_func = append_char_function;
442
443 /* We now look backwards for the start of a filename/variable word */
444 li = FUN(el,line)(el);
445 ctemp = li->cursor;
446 while (ctemp > li->buffer
447 && !Strchr(word_break, ctemp[-1])
448 && (!special_prefixes || !Strchr(special_prefixes, ctemp[-1]) ) )
449 ctemp--;
450
451 len = li->cursor - ctemp;
452 temp = el_malloc((len + 1) * sizeof(*temp));
453 (void)Strncpy(temp, ctemp, len);
454 temp[len] = '\0';
455
456 /* these can be used by function called in completion_matches() */
457 /* or (*attempted_completion_function)() */
458 if (point != 0)
459 *point = (int)(li->cursor - li->buffer);
460 if (end != NULL)
461 *end = (int)(li->lastchar - li->buffer);
462
463 if (attempted_completion_function) {
464 int cur_off = (int)(li->cursor - li->buffer);
465 matches = (*attempted_completion_function) (ct_encode_string(temp, &el->el_scratch),
466 (int)(cur_off - len), cur_off);
467 } else
468 matches = 0;
469 if (!attempted_completion_function ||
470 (over != NULL && !*over && !matches))
471 matches = completion_matches(ct_encode_string(temp, &el->el_scratch), complet_func);
472
473 if (over != NULL)
474 *over = 0;
475
476 if (matches) {
477 int i;
478 size_t matches_num, maxlen, match_len, match_display=1;
479
480 retval = CC_REFRESH;
481 /*
482 * Only replace the completed string with common part of
483 * possible matches if there is possible completion.
484 */
485 if (matches[0][0] != '\0') {
486 el_deletestr(el, (int) len);
487 FUN(el,insertstr)(el,
488 ct_decode_string(matches[0], &el->el_scratch));
489 }
490
491 if (what_to_do == '?')
492 goto display_matches;
493
494 if (matches[2] == NULL && strcmp(matches[0], matches[1]) == 0) {
495 /*
496 * We found exact match. Add a space after
497 * it, unless we do filename completion and the
498 * object is a directory.
499 */
500 FUN(el,insertstr)(el,
501 ct_decode_string((*app_func)(matches[0]),
502 &el->el_scratch));
503 } else if (what_to_do == '!') {
504 display_matches:
505 /*
506 * More than one match and requested to list possible
507 * matches.
508 */
509
510 for(i = 1, maxlen = 0; matches[i]; i++) {
511 match_len = strlen(matches[i]);
512 if (match_len > maxlen)
513 maxlen = match_len;
514 }
515 /* matches[1] through matches[i-1] are available */
516 matches_num = i - 1;
517
518 /* newline to get on next line from command line */
519 (void)fprintf(el->el_outfile, "\n");
520
521 /*
522 * If there are too many items, ask user for display
523 * confirmation.
524 */
525 if (matches_num > query_items) {
526 (void)fprintf(el->el_outfile,
527 "Display all %zu possibilities? (y or n) ",
528 matches_num);
529 (void)fflush(el->el_outfile);
530 if (getc(stdin) != 'y')
531 match_display = 0;
532 (void)fprintf(el->el_outfile, "\n");
533 }
534
535 if (match_display) {
536 /*
537 * Interface of this function requires the
538 * strings be matches[1..num-1] for compat.
539 * We have matches_num strings not counting
540 * the prefix in matches[0], so we need to
541 * add 1 to matches_num for the call.
542 */
543 fn_display_match_list(el, matches,
544 matches_num+1, maxlen);
545 }
546 retval = CC_REDISPLAY;
547 } else if (matches[0][0]) {
548 /*
549 * There was some common match, but the name was
550 * not complete enough. Next tab will print possible
551 * completions.
552 */
553 el_beep(el);
554 } else {
555 /* lcd is not a valid object - further specification */
556 /* is needed */
557 el_beep(el);
558 retval = CC_NORM;
559 }
560
561 /* free elements of array and the array itself */
562 for (i = 0; matches[i]; i++)
563 el_free(matches[i]);
564 el_free(matches);
565 matches = NULL;
566 }
567 el_free(temp);
568 return retval;
569 }
570
571 /*
572 * el-compatible wrapper around rl_complete; needed for key binding
573 */
574 /* ARGSUSED */
575 unsigned char
576 _el_fn_complete(EditLine *el, int ch __attribute__((__unused__)))
577 {
578 return (unsigned char)fn_complete(el, NULL, NULL,
579 break_chars, NULL, NULL, 100,
580 NULL, NULL, NULL, NULL);
581 }
582