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