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