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