]> CyberLeo.Net >> Repos - FreeBSD/stable/8.git/blob - lib/libedit/filecomplete.c
Add missed mergeinfo.
[FreeBSD/stable/8.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.19 2010/06/01 18:20:26 christos Exp $
30  */
31
32 #include <sys/cdefs.h>
33 __FBSDID("$FreeBSD$");
34
35 #include <sys/types.h>
36 #include <sys/stat.h>
37 #include <stdio.h>
38 #include <dirent.h>
39 #include <string.h>
40 #include <pwd.h>
41 #include <ctype.h>
42 #include <stdlib.h>
43 #include <unistd.h>
44 #include <limits.h>
45 #include <errno.h>
46 #include <fcntl.h>
47 #include <vis.h>
48 #include "el.h"
49 #include "fcns.h"               /* for EL_NUM_FCNS */
50 #include "histedit.h"
51 #include "filecomplete.h"
52
53 static char break_chars[] = { ' ', '\t', '\n', '"', '\\', '\'', '`', '@',
54     '$', '>', '<', '=', ';', '|', '&', '{', '(', '\0' };
55 /* Tilde is deliberately omitted here, we treat it specially. */
56 static char extra_quote_chars[] = { ')', '}', '\0' };
57
58
59 /********************************/
60 /* completion functions */
61
62 /*
63  * does tilde expansion of strings of type ``~user/foo''
64  * if ``user'' isn't valid user name or ``txt'' doesn't start
65  * w/ '~', returns pointer to strdup()ed copy of ``txt''
66  *
67  * it's callers's responsibility to free() returned string
68  */
69 char *
70 fn_tilde_expand(const char *txt)
71 {
72         struct passwd pwres, *pass;
73         char *temp;
74         size_t len = 0;
75         char pwbuf[1024];
76
77         if (txt[0] != '~')
78                 return (strdup(txt));
79
80         temp = strchr(txt + 1, '/');
81         if (temp == NULL) {
82                 temp = strdup(txt + 1);
83                 if (temp == NULL)
84                         return NULL;
85         } else {
86                 len = temp - txt + 1;   /* text until string after slash */
87                 temp = malloc(len);
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                 if (getpwuid_r(getuid(), &pwres, pwbuf, sizeof(pwbuf), &pass) != 0)
95                         pass = NULL;
96         } else {
97                 if (getpwnam_r(temp, &pwres, pwbuf, sizeof(pwbuf), &pass) != 0)
98                         pass = NULL;
99         }
100         free(temp);             /* value no more needed */
101         if (pass == NULL)
102                 return (strdup(txt));
103
104         /* update pointer txt to point at string immediately following */
105         /* first slash */
106         txt += len;
107
108         temp = malloc(strlen(pass->pw_dir) + 1 + strlen(txt) + 1);
109         if (temp == NULL)
110                 return NULL;
111         (void)sprintf(temp, "%s/%s", pass->pw_dir, txt);
112
113         return (temp);
114 }
115
116
117 /*
118  * return first found file name starting by the ``text'' or NULL if no
119  * such file can be found
120  * value of ``state'' is ignored
121  *
122  * it's caller's responsibility to free returned string
123  */
124 char *
125 fn_filename_completion_function(const char *text, int state)
126 {
127         static DIR *dir = NULL;
128         static char *filename = NULL, *dirname = NULL, *dirpath = NULL;
129         static size_t filename_len = 0;
130         struct dirent *entry;
131         char *temp;
132         size_t len;
133
134         if (state == 0 || dir == NULL) {
135                 temp = strrchr(text, '/');
136                 if (temp) {
137                         char *nptr;
138                         temp++;
139                         nptr = realloc(filename, strlen(temp) + 1);
140                         if (nptr == NULL) {
141                                 free(filename);
142                                 filename = NULL;
143                                 return NULL;
144                         }
145                         filename = nptr;
146                         (void)strcpy(filename, temp);
147                         len = temp - text;      /* including last slash */
148
149                         nptr = realloc(dirname, len + 1);
150                         if (nptr == NULL) {
151                                 free(dirname);
152                                 dirname = NULL;
153                                 return NULL;
154                         }
155                         dirname = nptr;
156                         (void)strncpy(dirname, text, len);
157                         dirname[len] = '\0';
158                 } else {
159                         free(filename);
160                         if (*text == 0)
161                                 filename = NULL;
162                         else {
163                                 filename = strdup(text);
164                                 if (filename == NULL)
165                                         return NULL;
166                         }
167                         free(dirname);
168                         dirname = NULL;
169                 }
170
171                 if (dir != NULL) {
172                         (void)closedir(dir);
173                         dir = NULL;
174                 }
175
176                 /* support for ``~user'' syntax */
177
178                 free(dirpath);
179                 dirpath = NULL;
180                 if (dirname == NULL) {
181                         if ((dirname = strdup("")) == NULL)
182                                 return NULL;
183                         dirpath = strdup("./");
184                 } else if (*dirname == '~')
185                         dirpath = fn_tilde_expand(dirname);
186                 else
187                         dirpath = strdup(dirname);
188
189                 if (dirpath == NULL)
190                         return NULL;
191
192                 dir = opendir(dirpath);
193                 if (!dir)
194                         return (NULL);  /* cannot open the directory */
195
196                 /* will be used in cycle */
197                 filename_len = filename ? strlen(filename) : 0;
198         }
199
200         /* find the match */
201         while ((entry = readdir(dir)) != NULL) {
202                 /* skip . and .. */
203                 if (entry->d_name[0] == '.' && (!entry->d_name[1]
204                     || (entry->d_name[1] == '.' && !entry->d_name[2])))
205                         continue;
206                 if (filename_len == 0)
207                         break;
208                 /* otherwise, get first entry where first */
209                 /* filename_len characters are equal      */
210                 if (entry->d_name[0] == filename[0]
211                     && entry->d_namlen >= filename_len
212                     && strncmp(entry->d_name, filename,
213                         filename_len) == 0)
214                         break;
215         }
216
217         if (entry) {            /* match found */
218                 len = entry->d_namlen;
219
220                 temp = malloc(strlen(dirname) + len + 1);
221                 if (temp == NULL)
222                         return NULL;
223                 (void)sprintf(temp, "%s%s", dirname, entry->d_name);
224         } else {
225                 (void)closedir(dir);
226                 dir = NULL;
227                 temp = NULL;
228         }
229
230         return (temp);
231 }
232
233
234 static const char *
235 append_char_function(const char *name)
236 {
237         struct stat stbuf;
238         char *expname = *name == '~' ? fn_tilde_expand(name) : NULL;
239         const char *rs = " ";
240
241         if (stat(expname ? expname : name, &stbuf) == -1)
242                 goto out;
243         if (S_ISDIR(stbuf.st_mode))
244                 rs = "/";
245 out:
246         if (expname)
247                 free(expname);
248         return rs;
249 }
250
251
252 /*
253  * returns list of completions for text given
254  * non-static for readline.
255  */
256 char ** completion_matches(const char *, char *(*)(const char *, int));
257 char **
258 completion_matches(const char *text, char *(*genfunc)(const char *, int))
259 {
260         char **match_list = NULL, *retstr, *prevstr;
261         size_t match_list_len, max_equal, which, i;
262         size_t matches;
263
264         matches = 0;
265         match_list_len = 1;
266         while ((retstr = (*genfunc) (text, (int)matches)) != NULL) {
267                 /* allow for list terminator here */
268                 if (matches + 3 >= match_list_len) {
269                         char **nmatch_list;
270                         while (matches + 3 >= match_list_len)
271                                 match_list_len <<= 1;
272                         nmatch_list = realloc(match_list,
273                             match_list_len * sizeof(char *));
274                         if (nmatch_list == NULL) {
275                                 free(match_list);
276                                 return NULL;
277                         }
278                         match_list = nmatch_list;
279
280                 }
281                 match_list[++matches] = retstr;
282         }
283
284         if (!match_list)
285                 return NULL;    /* nothing found */
286
287         /* find least denominator and insert it to match_list[0] */
288         which = 2;
289         prevstr = match_list[1];
290         max_equal = strlen(prevstr);
291         for (; which <= matches; which++) {
292                 for (i = 0; i < max_equal &&
293                     prevstr[i] == match_list[which][i]; i++)
294                         continue;
295                 max_equal = i;
296         }
297
298         retstr = malloc(max_equal + 1);
299         if (retstr == NULL) {
300                 free(match_list);
301                 return NULL;
302         }
303         (void)strncpy(retstr, match_list[1], max_equal);
304         retstr[max_equal] = '\0';
305         match_list[0] = retstr;
306
307         /* add NULL as last pointer to the array */
308         match_list[matches + 1] = (char *) NULL;
309
310         return (match_list);
311 }
312
313
314 /*
315  * Sort function for qsort(). Just wrapper around strcasecmp().
316  */
317 static int
318 _fn_qsort_string_compare(const void *i1, const void *i2)
319 {
320         const char *s1 = ((const char * const *)i1)[0];
321         const char *s2 = ((const char * const *)i2)[0];
322
323         return strcasecmp(s1, s2);
324 }
325
326
327 /*
328  * Display list of strings in columnar format on readline's output stream.
329  * 'matches' is list of strings, 'len' is number of strings in 'matches',
330  * 'max' is maximum length of string in 'matches'.
331  */
332 void
333 fn_display_match_list(EditLine *el, char **matches, size_t len, size_t max)
334 {
335         size_t i, idx, limit, count;
336         int screenwidth = el->el_term.t_size.h;
337
338         /*
339          * Find out how many entries can be put on one line, count
340          * with two spaces between strings.
341          */
342         limit = screenwidth / (max + 2);
343         if (limit == 0)
344                 limit = 1;
345
346         /* how many lines of output */
347         count = len / limit;
348         if (count * limit < len)
349                 count++;
350
351         /* Sort the items if they are not already sorted. */
352         qsort(&matches[1], (size_t)(len - 1), sizeof(char *),
353             _fn_qsort_string_compare);
354
355         idx = 1;
356         for(; count > 0; count--) {
357                 int more = limit > 0 && matches[0];
358                 for(i = 0; more; i++, idx++) {
359                         more = ++i < limit && matches[idx + 1];
360                         (void)fprintf(el->el_outfile, "%-*s%s", (int)max,
361                             matches[idx], more ? " " : "");
362                 }
363                 (void)fprintf(el->el_outfile, "\n");
364         }
365 }
366
367
368 /*
369  * Complete the word at or before point,
370  * 'what_to_do' says what to do with the completion.
371  * \t   means do standard completion.
372  * `?' means list the possible completions.
373  * `*' means insert all of the possible completions.
374  * `!' means to do standard completion, and list all possible completions if
375  * there is more than one.
376  *
377  * Note: '*' support is not implemented
378  *       '!' could never be invoked
379  */
380 int
381 fn_complete(EditLine *el,
382         char *(*complet_func)(const char *, int),
383         char **(*attempted_completion_function)(const char *, int, int),
384         const char *word_break, const char *special_prefixes,
385         const char *(*app_func)(const char *), size_t query_items,
386         int *completion_type, int *over, int *point, int *end,
387         const char *(*find_word_start_func)(const char *, const char *),
388         char *(*dequoting_func)(const char *),
389         char *(*quoting_func)(const char *))
390 {
391         const LineInfo *li;
392         char *temp;
393         char *dequoted_temp;
394         char **matches;
395         const char *ctemp;
396         size_t len;
397         int what_to_do = '\t';
398         int retval = CC_NORM;
399
400         if (el->el_state.lastcmd == el->el_state.thiscmd)
401                 what_to_do = '?';
402
403         /* readline's rl_complete() has to be told what we did... */
404         if (completion_type != NULL)
405                 *completion_type = what_to_do;
406
407         if (!complet_func)
408                 complet_func = fn_filename_completion_function;
409         if (!app_func)
410                 app_func = append_char_function;
411
412         /* We now look backwards for the start of a filename/variable word */
413         li = el_line(el);
414         if (find_word_start_func)
415                 ctemp = find_word_start_func(li->buffer, li->cursor);
416         else {
417                 ctemp = li->cursor;
418                 while (ctemp > li->buffer
419                     && !strchr(word_break, ctemp[-1])
420                     && (!special_prefixes || !strchr(special_prefixes, ctemp[-1]) ) )
421                         ctemp--;
422         }
423
424         len = li->cursor - ctemp;
425 #if defined(__SSP__) || defined(__SSP_ALL__)
426         temp = malloc(sizeof(*temp) * (len + 1));
427         if (temp == NULL)
428                 return retval;
429 #else
430         temp = alloca(sizeof(*temp) * (len + 1));
431 #endif
432         (void)strncpy(temp, ctemp, len);
433         temp[len] = '\0';
434
435         if (dequoting_func) {
436                 dequoted_temp = dequoting_func(temp);
437                 if (dequoted_temp == NULL)
438                         return retval;
439         } else
440                 dequoted_temp = NULL;
441
442         /* these can be used by function called in completion_matches() */
443         /* or (*attempted_completion_function)() */
444         if (point != 0)
445                 *point = (int)(li->cursor - li->buffer);
446         if (end != NULL)
447                 *end = (int)(li->lastchar - li->buffer);
448
449         if (attempted_completion_function) {
450                 int cur_off = (int)(li->cursor - li->buffer);
451                 matches = (*attempted_completion_function) (dequoted_temp ? dequoted_temp : 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(dequoted_temp ? dequoted_temp : temp, complet_func);
458
459         if (over != NULL)
460                 *over = 0;
461
462         if (matches) {
463                 int i;
464                 size_t 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                         char *quoted_match;
473                         if (quoting_func) {
474                                 quoted_match = quoting_func(matches[0]);
475                                 if (quoted_match == NULL)
476                                         goto free_matches;
477                         } else
478                                 quoted_match = NULL;
479
480                         el_deletestr(el, (int) len);
481                         el_insertstr(el, quoted_match ? quoted_match : matches[0]);
482
483                         free(quoted_match);
484                 }
485
486                 if (what_to_do == '?')
487                         goto display_matches;
488
489                 if (matches[2] == NULL && strcmp(matches[0], matches[1]) == 0) {
490                         /*
491                          * We found exact match. Add a space after
492                          * it, unless we do filename completion and the
493                          * object is a directory.
494                          */
495                         el_insertstr(el, (*app_func)(matches[0]));
496                 } else if (what_to_do == '!') {
497     display_matches:
498                         /*
499                          * More than one match and requested to list possible
500                          * matches.
501                          */
502
503                         for(i = 1, maxlen = 0; matches[i]; i++) {
504                                 match_len = strlen(matches[i]);
505                                 if (match_len > maxlen)
506                                         maxlen = match_len;
507                         }
508                         matches_num = i - 1;
509                                 
510                         /* newline to get on next line from command line */
511                         (void)fprintf(el->el_outfile, "\n");
512
513                         /*
514                          * If there are too many items, ask user for display
515                          * confirmation.
516                          */
517                         if (matches_num > query_items) {
518                                 (void)fprintf(el->el_outfile,
519                                     "Display all %zu possibilities? (y or n) ",
520                                     matches_num);
521                                 (void)fflush(el->el_outfile);
522                                 if (getc(stdin) != 'y')
523                                         match_display = 0;
524                                 (void)fprintf(el->el_outfile, "\n");
525                         }
526
527                         if (match_display)
528                                 fn_display_match_list(el, matches, matches_num,
529                                     maxlen);
530                         retval = CC_REDISPLAY;
531                 } else if (matches[0][0]) {
532                         /*
533                          * There was some common match, but the name was
534                          * not complete enough. Next tab will print possible
535                          * completions.
536                          */
537                         el_beep(el);
538                 } else {
539                         /* lcd is not a valid object - further specification */
540                         /* is needed */
541                         el_beep(el);
542                         retval = CC_NORM;
543                 }
544
545 free_matches:
546                 /* free elements of array and the array itself */
547                 for (i = 0; matches[i]; i++)
548                         free(matches[i]);
549                 free(matches);
550                 matches = NULL;
551         }
552         free(dequoted_temp);
553 #if defined(__SSP__) || defined(__SSP_ALL__)
554         free(temp);
555 #endif
556         return retval;
557 }
558
559
560 /*
561  * el-compatible wrapper around rl_complete; needed for key binding
562  */
563 /* ARGSUSED */
564 unsigned char
565 _el_fn_complete(EditLine *el, int ch __attribute__((__unused__)))
566 {
567         return (unsigned char)fn_complete(el, NULL, NULL,
568             break_chars, NULL, NULL, 100,
569             NULL, NULL, NULL, NULL,
570             NULL, NULL, NULL);
571 }
572
573
574 static const char *
575 sh_find_word_start(const char *buffer, const char *cursor)
576 {
577         const char *word_start = buffer;
578
579         while (buffer < cursor) {
580                 if (*buffer == '\\')
581                         buffer++;
582                 else if (strchr(break_chars, *buffer))
583                         word_start = buffer + 1;
584
585                 buffer++;
586         }
587
588         return word_start;
589 }
590
591
592 static char *
593 sh_quote(const char *str)
594 {
595         const char *src;
596         int extra_len = 0;
597         char *quoted_str, *dst;
598
599         for (src = str; *src != '\0'; src++)
600                 if (strchr(break_chars, *src) ||
601                     strchr(extra_quote_chars, *src))
602                         extra_len++;
603
604         quoted_str = malloc(sizeof(*quoted_str) *
605             (strlen(str) + extra_len + 1));
606         if (quoted_str == NULL)
607                 return NULL;
608
609         dst = quoted_str;
610         for (src = str; *src != '\0'; src++) {
611                 if (strchr(break_chars, *src) ||
612                     strchr(extra_quote_chars, *src))
613                         *dst++ = '\\';
614                 *dst++ = *src;
615         }
616         *dst = '\0';
617
618         return quoted_str;
619 }
620
621
622 static char *
623 sh_dequote(const char *str)
624 {
625         char *dequoted_str, *dst;
626
627         /* save extra space to replace \~ with ./~ */
628         dequoted_str = malloc(sizeof(*dequoted_str) * (strlen(str) + 1 + 1));
629         if (dequoted_str == NULL)
630                 return NULL;
631
632         dst = dequoted_str;
633
634         /* dequote \~ at start as ./~ */
635         if (*str == '\\' && str[1] == '~') {
636                 str++;
637                 *dst++ = '.';
638                 *dst++ = '/';
639         }
640
641         while (*str) {
642                 if (*str == '\\')
643                         str++;
644                 if (*str)
645                         *dst++ = *str++;
646         }
647         *dst = '\0';
648
649         return dequoted_str;
650 }
651
652
653 /*
654  * completion function using sh quoting rules; for key binding
655  */
656 /* ARGSUSED */
657 unsigned char
658 _el_fn_sh_complete(EditLine *el, int ch __attribute__((__unused__)))
659 {
660         return (unsigned char)fn_complete(el, NULL, NULL,
661             break_chars, NULL, NULL, 100,
662             NULL, NULL, NULL, NULL,
663             sh_find_word_start, sh_dequote, sh_quote);
664 }