filecomplete.c revision 1.4 1 /* $NetBSD: filecomplete.c,v 1.4 2005/05/12 15:48:40 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. 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.4 2005/05/12 15:48:40 christos 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
188 if (dirname == NULL && (dirname = strdup("./")) == NULL)
189 return NULL;
190
191 if (*dirname == '~')
192 dirpath = tilde_expand(dirname);
193 else
194 dirpath = strdup(dirname);
195
196 if (dirpath == NULL)
197 return NULL;
198
199 dir = opendir(dirpath);
200 if (!dir)
201 return (NULL); /* cannot open the directory */
202
203 /* will be used in cycle */
204 filename_len = filename ? strlen(filename) : 0;
205 }
206
207 /* find the match */
208 while ((entry = readdir(dir)) != NULL) {
209 /* skip . and .. */
210 if (entry->d_name[0] == '.' && (!entry->d_name[1]
211 || (entry->d_name[1] == '.' && !entry->d_name[2])))
212 continue;
213 if (filename_len == 0)
214 break;
215 /* otherwise, get first entry where first */
216 /* filename_len characters are equal */
217 if (entry->d_name[0] == filename[0]
218 #if defined(__SVR4) || defined(__linux__)
219 && strlen(entry->d_name) >= filename_len
220 #else
221 && entry->d_namlen >= filename_len
222 #endif
223 && strncmp(entry->d_name, filename,
224 filename_len) == 0)
225 break;
226 }
227
228 if (entry) { /* match found */
229 struct stat stbuf;
230 const char *isdir = "";
231
232 #if defined(__SVR4) || defined(__linux__)
233 len = strlen(entry->d_name);
234 #else
235 len = entry->d_namlen;
236 #endif
237 temp = malloc(strlen(dirpath) + len + 1);
238 if (temp == NULL)
239 return NULL;
240 (void)sprintf(temp, "%s%s", dirpath, entry->d_name); /* safe */
241
242 /* test, if it's directory */
243 if (stat(temp, &stbuf) == 0 && S_ISDIR(stbuf.st_mode))
244 isdir = "/";
245 free(temp);
246 temp = malloc(strlen(dirname) + len + 1 + 1);
247 if (temp == NULL)
248 return NULL;
249 (void)sprintf(temp, "%s%s%s", dirname, entry->d_name, isdir);
250 } else {
251 (void)closedir(dir);
252 dir = NULL;
253 temp = NULL;
254 }
255
256 return (temp);
257 }
258
259
260
261 /*
262 * returns list of completions for text given
263 */
264 static char **
265 completion_matches(const char *text, char *(*genfunc)(const char *, int))
266 {
267 char **match_list = NULL, *retstr, *prevstr;
268 size_t match_list_len, max_equal, which, i;
269 size_t matches;
270
271 matches = 0;
272 match_list_len = 1;
273 while ((retstr = (*genfunc) (text, (int)matches)) != NULL) {
274 /* allow for list terminator here */
275 if (matches + 3 >= match_list_len) {
276 char **nmatch_list;
277 while (matches + 3 >= match_list_len)
278 match_list_len <<= 1;
279 nmatch_list = realloc(match_list,
280 match_list_len * sizeof(char *));
281 if (nmatch_list == NULL) {
282 free(match_list);
283 return NULL;
284 }
285 match_list = nmatch_list;
286
287 }
288 match_list[++matches] = retstr;
289 }
290
291 if (!match_list)
292 return NULL; /* nothing found */
293
294 /* find least denominator and insert it to match_list[0] */
295 which = 2;
296 prevstr = match_list[1];
297 max_equal = strlen(prevstr);
298 for (; which <= matches; which++) {
299 for (i = 0; i < max_equal &&
300 prevstr[i] == match_list[which][i]; i++)
301 continue;
302 max_equal = i;
303 }
304
305 retstr = malloc(max_equal + 1);
306 if (retstr == NULL) {
307 free(match_list);
308 return NULL;
309 }
310 (void)strncpy(retstr, match_list[1], max_equal);
311 retstr[max_equal] = '\0';
312 match_list[0] = retstr;
313
314 /* add NULL as last pointer to the array */
315 match_list[matches + 1] = (char *) NULL;
316
317 return (match_list);
318 }
319
320 /*
321 * Sort function for qsort(). Just wrapper around strcasecmp().
322 */
323 static int
324 _fn_qsort_string_compare(const void *i1, const void *i2)
325 {
326 const char *s1 = ((const char * const *)i1)[0];
327 const char *s2 = ((const char * const *)i2)[0];
328
329 return strcasecmp(s1, s2);
330 }
331
332 /*
333 * Display list of strings in columnar format on readline's output stream.
334 * 'matches' is list of strings, 'len' is number of strings in 'matches',
335 * 'max' is maximum length of string in 'matches'.
336 */
337 void
338 fn_display_match_list (EditLine *el, char **matches, int len, int max)
339 {
340 int i, idx, limit, count;
341 int screenwidth = el->el_term.t_size.h;
342
343 /*
344 * Find out how many entries can be put on one line, count
345 * with two spaces between strings.
346 */
347 limit = screenwidth / (max + 2);
348 if (limit == 0)
349 limit = 1;
350
351 /* how many lines of output */
352 count = len / limit;
353 if (count * limit < len)
354 count++;
355
356 /* Sort the items if they are not already sorted. */
357 qsort(&matches[1], (size_t)(len - 1), sizeof(char *),
358 _fn_qsort_string_compare);
359
360 idx = 1;
361 for(; count > 0; count--) {
362 for(i = 0; i < limit && matches[idx]; i++, idx++)
363 (void)fprintf(el->el_outfile, "%-*s ", max,
364 matches[idx]);
365 (void)fprintf(el->el_outfile, "\n");
366 }
367 }
368
369 /*
370 * Complete the word at or before point,
371 * 'what_to_do' says what to do with the completion.
372 * \t means do standard completion.
373 * `?' means list the possible completions.
374 * `*' means insert all of the possible completions.
375 * `!' means to do standard completion, and list all possible completions if
376 * there is more than one.
377 *
378 * Note: '*' support is not implemented
379 * '!' could never be invoked
380 */
381 int
382 fn_complete(EditLine *el,
383 char *(*complet_func)(const char *, int),
384 char **(*attempted_completion_function)(const char *, int, int),
385 const char *word_break, const char *special_prefixes,
386 char append_character, int query_items,
387 int *completion_type, int *over, int *point, int *end)
388 {
389 const LineInfo *li;
390 char *temp, **matches;
391 const char *ctemp;
392 size_t len;
393 int what_to_do = '\t';
394
395 if (el->el_state.lastcmd == el->el_state.thiscmd)
396 what_to_do = '?';
397
398 /* readline's rl_complete() has to be told what we did... */
399 if (completion_type != NULL)
400 *completion_type = what_to_do;
401
402 if (!complet_func)
403 complet_func = filename_completion_function;
404
405 /* We now look backwards for the start of a filename/variable word */
406 li = el_line(el);
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]) ) )
411 ctemp--;
412
413 len = li->cursor - ctemp;
414 temp = alloca(len + 1);
415 (void)strncpy(temp, ctemp, len);
416 temp[len] = '\0';
417
418 /* these can be used by function called in completion_matches() */
419 /* or (*attempted_completion_function)() */
420 if (point != 0)
421 *point = li->cursor - li->buffer;
422 if (end != NULL)
423 *end = li->lastchar - li->buffer;
424
425 if (attempted_completion_function) {
426 int cur_off = li->cursor - li->buffer;
427 matches = (*attempted_completion_function) (temp,
428 (int)(cur_off - len), cur_off);
429 } else
430 matches = 0;
431 if (!attempted_completion_function ||
432 (over != NULL && *over && !matches))
433 matches = completion_matches(temp, complet_func);
434
435 if (over != NULL)
436 *over = 0;
437
438 if (matches) {
439 int i, retval = CC_REFRESH;
440 int matches_num, maxlen, match_len, match_display=1;
441
442 /*
443 * Only replace the completed string with common part of
444 * possible matches if there is possible completion.
445 */
446 if (matches[0][0] != '\0') {
447 el_deletestr(el, (int) len);
448 el_insertstr(el, matches[0]);
449 }
450
451 if (what_to_do == '?')
452 goto display_matches;
453
454 if (matches[2] == NULL && strcmp(matches[0], matches[1]) == 0) {
455 /*
456 * We found exact match. Add a space after
457 * it, unless we do filename completion and the
458 * object is a directory.
459 */
460 size_t alen = strlen(matches[0]);
461 if ((complet_func != filename_completion_function
462 || (alen > 0 && (matches[0])[alen - 1] != '/'))
463 && append_character) {
464 char buf[2];
465 buf[0] = append_character;
466 buf[1] = '\0';
467 el_insertstr(el, buf);
468 }
469 } else if (what_to_do == '!') {
470 display_matches:
471 /*
472 * More than one match and requested to list possible
473 * matches.
474 */
475
476 for(i=1, maxlen=0; matches[i]; i++) {
477 match_len = strlen(matches[i]);
478 if (match_len > maxlen)
479 maxlen = match_len;
480 }
481 matches_num = i - 1;
482
483 /* newline to get on next line from command line */
484 (void)fprintf(el->el_outfile, "\n");
485
486 /*
487 * If there are too many items, ask user for display
488 * confirmation.
489 */
490 if (matches_num > query_items) {
491 (void)fprintf(el->el_outfile,
492 "Display all %d possibilities? (y or n) ",
493 matches_num);
494 (void)fflush(el->el_outfile);
495 if (getc(stdin) != 'y')
496 match_display = 0;
497 (void)fprintf(el->el_outfile, "\n");
498 }
499
500 if (match_display)
501 fn_display_match_list(el, matches, matches_num,
502 maxlen);
503 retval = CC_REDISPLAY;
504 } else if (matches[0][0]) {
505 /*
506 * There was some common match, but the name was
507 * not complete enough. Next tab will print possible
508 * completions.
509 */
510 el_beep(el);
511 } else {
512 /* lcd is not a valid object - further specification */
513 /* is needed */
514 el_beep(el);
515 retval = CC_NORM;
516 }
517
518 /* free elements of array and the array itself */
519 for (i = 0; matches[i]; i++)
520 free(matches[i]);
521 free(matches), matches = NULL;
522
523 return (retval);
524 }
525 return (CC_NORM);
526 }
527
528 /*
529 * el-compatible wrapper around rl_complete; needed for key binding
530 */
531 /* ARGSUSED */
532 unsigned char
533 _el_fn_complete(EditLine *el, int ch __attribute__((__unused__)))
534 {
535 return (unsigned char)fn_complete(el, NULL, NULL,
536 break_chars, NULL, ' ', 100,
537 NULL, NULL, NULL, NULL);
538 }
539