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