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