filecomplete.c revision 1.10 1 /* $NetBSD: filecomplete.c,v 1.10 2006/11/09 16:58:38 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 * 3. Neither the name of The NetBSD Foundation nor the names of its
19 * contributors may be used to endorse or promote products derived
20 * from this software without specific prior written permission.
21 *
22 * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
23 * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
24 * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
25 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
26 * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
27 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
28 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
29 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
30 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
31 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
32 * POSSIBILITY OF SUCH DAMAGE.
33 */
34
35 #include "config.h"
36 #if !defined(lint) && !defined(SCCSID)
37 __RCSID("$NetBSD: filecomplete.c,v 1.10 2006/11/09 16:58:38 christos Exp $");
38 #endif /* not lint && not SCCSID */
39
40 #include <sys/types.h>
41 #include <sys/stat.h>
42 #include <stdio.h>
43 #include <dirent.h>
44 #include <string.h>
45 #include <pwd.h>
46 #include <ctype.h>
47 #include <stdlib.h>
48 #include <unistd.h>
49 #include <limits.h>
50 #include <errno.h>
51 #include <fcntl.h>
52 #ifdef HAVE_VIS_H
53 #include <vis.h>
54 #else
55 #include "np/vis.h"
56 #endif
57 #ifdef HAVE_ALLOCA_H
58 #include <alloca.h>
59 #endif
60 #include "el.h"
61 #include "fcns.h" /* for EL_NUM_FCNS */
62 #include "histedit.h"
63 #include "filecomplete.h"
64
65 static char break_chars[] = { ' ', '\t', '\n', '"', '\\', '\'', '`', '@', '$',
66 '>', '<', '=', ';', '|', '&', '{', '(', '\0' };
67
68
69 /********************************/
70 /* completion functions */
71
72 /*
73 * does tilde expansion of strings of type ``~user/foo''
74 * if ``user'' isn't valid user name or ``txt'' doesn't start
75 * w/ '~', returns pointer to strdup()ed copy of ``txt''
76 *
77 * it's callers's responsibility to free() returned string
78 */
79 char *
80 fn_tilde_expand(const char *txt)
81 {
82 struct passwd pwres, *pass;
83 char *temp;
84 size_t len = 0;
85 char pwbuf[1024];
86
87 if (txt[0] != '~')
88 return (strdup(txt));
89
90 temp = strchr(txt + 1, '/');
91 if (temp == NULL) {
92 temp = strdup(txt + 1);
93 if (temp == NULL)
94 return NULL;
95 } else {
96 len = temp - txt + 1; /* text until string after slash */
97 temp = malloc(len);
98 if (temp == NULL)
99 return NULL;
100 (void)strncpy(temp, txt + 1, len - 2);
101 temp[len - 2] = '\0';
102 }
103 if (temp[0] == 0) {
104 if (getpwuid_r(getuid(), &pwres, pwbuf, sizeof(pwbuf), &pass) != 0)
105 pass = NULL;
106 } else {
107 if (getpwnam_r(temp, &pwres, pwbuf, sizeof(pwbuf), &pass) != 0)
108 pass = NULL;
109 }
110 free(temp); /* value no more needed */
111 if (pass == NULL)
112 return (strdup(txt));
113
114 /* update pointer txt to point at string immedially following */
115 /* first slash */
116 txt += len;
117
118 temp = malloc(strlen(pass->pw_dir) + 1 + strlen(txt) + 1);
119 if (temp == NULL)
120 return NULL;
121 (void)sprintf(temp, "%s/%s", pass->pw_dir, txt);
122
123 return (temp);
124 }
125
126
127 /*
128 * return first found file name starting by the ``text'' or NULL if no
129 * such file can be found
130 * value of ``state'' is ignored
131 *
132 * it's caller's responsibility to free returned string
133 */
134 char *
135 fn_filename_completion_function(const char *text, int state)
136 {
137 static DIR *dir = NULL;
138 static char *filename = NULL, *dirname = NULL, *dirpath = NULL;
139 static size_t filename_len = 0;
140 struct dirent *entry;
141 char *temp;
142 size_t len;
143
144 if (state == 0 || dir == NULL) {
145 temp = strrchr(text, '/');
146 if (temp) {
147 char *nptr;
148 temp++;
149 nptr = realloc(filename, strlen(temp) + 1);
150 if (nptr == NULL) {
151 free(filename);
152 return NULL;
153 }
154 filename = nptr;
155 (void)strcpy(filename, temp);
156 len = temp - text; /* including last slash */
157 nptr = realloc(dirname, len + 1);
158 if (nptr == NULL) {
159 free(filename);
160 return NULL;
161 }
162 dirname = nptr;
163 (void)strncpy(dirname, text, len);
164 dirname[len] = '\0';
165 } else {
166 if (*text == 0)
167 filename = NULL;
168 else {
169 filename = strdup(text);
170 if (filename == NULL)
171 return NULL;
172 }
173 dirname = NULL;
174 }
175
176 if (dir != NULL) {
177 (void)closedir(dir);
178 dir = NULL;
179 }
180
181 /* support for ``~user'' syntax */
182 free(dirpath);
183
184 if (dirname == NULL && (dirname = strdup("./")) == NULL)
185 return NULL;
186
187 if (*dirname == '~')
188 dirpath = fn_tilde_expand(dirname);
189 else
190 dirpath = strdup(dirname);
191
192 if (dirpath == NULL)
193 return NULL;
194
195 dir = opendir(dirpath);
196 if (!dir)
197 return (NULL); /* cannot open the directory */
198
199 /* will be used in cycle */
200 filename_len = filename ? strlen(filename) : 0;
201 }
202
203 /* find the match */
204 while ((entry = readdir(dir)) != NULL) {
205 /* skip . and .. */
206 if (entry->d_name[0] == '.' && (!entry->d_name[1]
207 || (entry->d_name[1] == '.' && !entry->d_name[2])))
208 continue;
209 if (filename_len == 0)
210 break;
211 /* otherwise, get first entry where first */
212 /* filename_len characters are equal */
213 if (entry->d_name[0] == filename[0]
214 #if defined(__SVR4) || defined(__linux__)
215 && strlen(entry->d_name) >= filename_len
216 #else
217 && entry->d_namlen >= filename_len
218 #endif
219 && strncmp(entry->d_name, filename,
220 filename_len) == 0)
221 break;
222 }
223
224 if (entry) { /* match found */
225
226 #if defined(__SVR4) || defined(__linux__)
227 len = strlen(entry->d_name);
228 #else
229 len = entry->d_namlen;
230 #endif
231
232 temp = malloc(strlen(dirname) + len + 1);
233 if (temp == NULL)
234 return NULL;
235 (void)sprintf(temp, "%s%s", dirname, entry->d_name);
236 } else {
237 (void)closedir(dir);
238 dir = NULL;
239 temp = NULL;
240 }
241
242 return (temp);
243 }
244
245
246 static const char *
247 append_char_function(const char *name)
248 {
249 struct stat stbuf;
250 char *expname = *name == '~' ? fn_tilde_expand(name) : NULL;
251 const char *rs = "";
252
253 if (stat(expname ? expname : name, &stbuf) == -1)
254 goto out;
255 if (S_ISDIR(stbuf.st_mode))
256 rs = "/";
257 out:
258 if (expname)
259 free(expname);
260 return rs;
261 }
262 /*
263 * returns list of completions for text given
264 * non-static for readline.
265 */
266 char ** completion_matches(const char *, char *(*)(const char *, int));
267 char **
268 completion_matches(const char *text, char *(*genfunc)(const char *, int))
269 {
270 char **match_list = NULL, *retstr, *prevstr;
271 size_t match_list_len, max_equal, which, i;
272 size_t matches;
273
274 matches = 0;
275 match_list_len = 1;
276 while ((retstr = (*genfunc) (text, (int)matches)) != NULL) {
277 /* allow for list terminator here */
278 if (matches + 3 >= match_list_len) {
279 char **nmatch_list;
280 while (matches + 3 >= match_list_len)
281 match_list_len <<= 1;
282 nmatch_list = realloc(match_list,
283 match_list_len * sizeof(char *));
284 if (nmatch_list == NULL) {
285 free(match_list);
286 return NULL;
287 }
288 match_list = nmatch_list;
289
290 }
291 match_list[++matches] = retstr;
292 }
293
294 if (!match_list)
295 return NULL; /* nothing found */
296
297 /* find least denominator and insert it to match_list[0] */
298 which = 2;
299 prevstr = match_list[1];
300 max_equal = strlen(prevstr);
301 for (; which <= matches; which++) {
302 for (i = 0; i < max_equal &&
303 prevstr[i] == match_list[which][i]; i++)
304 continue;
305 max_equal = i;
306 }
307
308 retstr = malloc(max_equal + 1);
309 if (retstr == NULL) {
310 free(match_list);
311 return NULL;
312 }
313 (void)strncpy(retstr, match_list[1], max_equal);
314 retstr[max_equal] = '\0';
315 match_list[0] = retstr;
316
317 /* add NULL as last pointer to the array */
318 match_list[matches + 1] = (char *) NULL;
319
320 return (match_list);
321 }
322
323 /*
324 * Sort function for qsort(). Just wrapper around strcasecmp().
325 */
326 static int
327 _fn_qsort_string_compare(const void *i1, const void *i2)
328 {
329 const char *s1 = ((const char * const *)i1)[0];
330 const char *s2 = ((const char * const *)i2)[0];
331
332 return strcasecmp(s1, s2);
333 }
334
335 /*
336 * Display list of strings in columnar format on readline's output stream.
337 * 'matches' is list of strings, 'len' is number of strings in 'matches',
338 * 'max' is maximum length of string in 'matches'.
339 */
340 void
341 fn_display_match_list (EditLine *el, char **matches, int len, int max)
342 {
343 int i, idx, limit, count;
344 int screenwidth = el->el_term.t_size.h;
345
346 /*
347 * Find out how many entries can be put on one line, count
348 * with two spaces between strings.
349 */
350 limit = screenwidth / (max + 2);
351 if (limit == 0)
352 limit = 1;
353
354 /* how many lines of output */
355 count = len / limit;
356 if (count * limit < len)
357 count++;
358
359 /* Sort the items if they are not already sorted. */
360 qsort(&matches[1], (size_t)(len - 1), sizeof(char *),
361 _fn_qsort_string_compare);
362
363 idx = 1;
364 for(; count > 0; count--) {
365 for(i = 0; i < limit && matches[idx]; i++, idx++)
366 (void)fprintf(el->el_outfile, "%-*s ", max,
367 matches[idx]);
368 (void)fprintf(el->el_outfile, "\n");
369 }
370 }
371
372 /*
373 * Complete the word at or before point,
374 * 'what_to_do' says what to do with the completion.
375 * \t means do standard completion.
376 * `?' means list the possible completions.
377 * `*' means insert all of the possible completions.
378 * `!' means to do standard completion, and list all possible completions if
379 * there is more than one.
380 *
381 * Note: '*' support is not implemented
382 * '!' could never be invoked
383 */
384 int
385 fn_complete(EditLine *el,
386 char *(*complet_func)(const char *, int),
387 char **(*attempted_completion_function)(const char *, int, int),
388 const char *word_break, const char *special_prefixes,
389 const char *(*app_func)(const char *), int query_items,
390 int *completion_type, int *over, int *point, int *end)
391 {
392 const LineInfo *li;
393 char *temp, **matches;
394 const char *ctemp;
395 size_t len;
396 int what_to_do = '\t';
397 int retval = CC_NORM;
398
399 if (el->el_state.lastcmd == el->el_state.thiscmd)
400 what_to_do = '?';
401
402 /* readline's rl_complete() has to be told what we did... */
403 if (completion_type != NULL)
404 *completion_type = what_to_do;
405
406 if (!complet_func)
407 complet_func = fn_filename_completion_function;
408 if (!app_func)
409 app_func = append_char_function;
410
411 /* We now look backwards for the start of a filename/variable word */
412 li = el_line(el);
413 ctemp = (const char *) li->cursor;
414 while (ctemp > li->buffer
415 && !strchr(word_break, ctemp[-1])
416 && (!special_prefixes || !strchr(special_prefixes, ctemp[-1]) ) )
417 ctemp--;
418
419 len = li->cursor - ctemp;
420 #if defined(__SSP__) || defined(__SSP_ALL__)
421 temp = malloc(len + 1);
422 #else
423 temp = alloca(len + 1);
424 #endif
425 (void)strncpy(temp, ctemp, len);
426 temp[len] = '\0';
427
428 /* these can be used by function called in completion_matches() */
429 /* or (*attempted_completion_function)() */
430 if (point != 0)
431 *point = li->cursor - li->buffer;
432 if (end != NULL)
433 *end = li->lastchar - li->buffer;
434
435 if (attempted_completion_function) {
436 int cur_off = li->cursor - li->buffer;
437 matches = (*attempted_completion_function) (temp,
438 (int)(cur_off - len), cur_off);
439 } else
440 matches = 0;
441 if (!attempted_completion_function ||
442 (over != NULL && !*over && !matches))
443 matches = completion_matches(temp, complet_func);
444
445 if (over != NULL)
446 *over = 0;
447
448 if (matches) {
449 int i;
450 int matches_num, maxlen, match_len, match_display=1;
451
452 retval = CC_REFRESH;
453 /*
454 * Only replace the completed string with common part of
455 * possible matches if there is possible completion.
456 */
457 if (matches[0][0] != '\0') {
458 el_deletestr(el, (int) len);
459 el_insertstr(el, matches[0]);
460 }
461
462 if (what_to_do == '?')
463 goto display_matches;
464
465 if (matches[2] == NULL && strcmp(matches[0], matches[1]) == 0) {
466 /*
467 * We found exact match. Add a space after
468 * it, unless we do filename completion and the
469 * object is a directory.
470 */
471 el_insertstr(el, (*append_char_function)(matches[0]));
472 } else if (what_to_do == '!') {
473 display_matches:
474 /*
475 * More than one match and requested to list possible
476 * matches.
477 */
478
479 for(i=1, maxlen=0; matches[i]; i++) {
480 match_len = strlen(matches[i]);
481 if (match_len > maxlen)
482 maxlen = match_len;
483 }
484 matches_num = i - 1;
485
486 /* newline to get on next line from command line */
487 (void)fprintf(el->el_outfile, "\n");
488
489 /*
490 * If there are too many items, ask user for display
491 * confirmation.
492 */
493 if (matches_num > query_items) {
494 (void)fprintf(el->el_outfile,
495 "Display all %d possibilities? (y or n) ",
496 matches_num);
497 (void)fflush(el->el_outfile);
498 if (getc(stdin) != 'y')
499 match_display = 0;
500 (void)fprintf(el->el_outfile, "\n");
501 }
502
503 if (match_display)
504 fn_display_match_list(el, matches, matches_num,
505 maxlen);
506 retval = CC_REDISPLAY;
507 } else if (matches[0][0]) {
508 /*
509 * There was some common match, but the name was
510 * not complete enough. Next tab will print possible
511 * completions.
512 */
513 el_beep(el);
514 } else {
515 /* lcd is not a valid object - further specification */
516 /* is needed */
517 el_beep(el);
518 retval = CC_NORM;
519 }
520
521 /* free elements of array and the array itself */
522 for (i = 0; matches[i]; i++)
523 free(matches[i]);
524 free(matches);
525 matches = NULL;
526 }
527 #if defined(__SSP__) || defined(__SSP_ALL__)
528 free(temp);
529 #endif
530 return retval;
531 }
532
533 /*
534 * el-compatible wrapper around rl_complete; needed for key binding
535 */
536 /* ARGSUSED */
537 unsigned char
538 _el_fn_complete(EditLine *el, int ch __attribute__((__unused__)))
539 {
540 return (unsigned char)fn_complete(el, NULL, NULL,
541 break_chars, NULL, NULL, 100,
542 NULL, NULL, NULL, NULL);
543 }
544