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