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