1 /* $NetBSD: filecomplete.c,v 1.34 2014/10/18 15:07:02 riz Exp $ */
4 * Copyright (c) 1997 The NetBSD Foundation, Inc.
7 * This code is derived from software contributed to The NetBSD Foundation
10 * Redistribution and use in source and binary forms, with or without
11 * modification, are permitted provided that the following conditions
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.
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.
33 #if !defined(lint) && !defined(SCCSID)
34 __RCSID("$NetBSD: filecomplete.c,v 1.34 2014/10/18 15:07:02 riz Exp $");
35 #endif /* not lint && not SCCSID */
37 #include <sys/types.h>
51 #include "fcns.h" /* for EL_NUM_FCNS */
53 #include "filecomplete.h"
55 static const Char break_chars
[] = { ' ', '\t', '\n', '"', '\\', '\'', '`', '@',
56 '$', '>', '<', '=', ';', '|', '&', '{', '(', '\0' };
59 /********************************/
60 /* completion functions */
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''
67 * it's the caller's responsibility to free() the returned string
70 fn_tilde_expand(const char *txt
)
72 #if defined(HAVE_GETPW_R_POSIX) || defined(HAVE_GETPW_R_DRAFT)
83 temp
= strchr(txt
+ 1, '/');
85 temp
= strdup(txt
+ 1);
89 /* text until string after slash */
90 len
= (size_t)(temp
- txt
+ 1);
91 temp
= el_malloc(len
* sizeof(*temp
));
94 (void)strncpy(temp
, txt
+ 1, len
- 2);
98 #ifdef HAVE_GETPW_R_POSIX
99 if (getpwuid_r(getuid(), &pwres
, pwbuf
, sizeof(pwbuf
),
102 #elif HAVE_GETPW_R_DRAFT
103 pass
= getpwuid_r(getuid(), &pwres
, pwbuf
, sizeof(pwbuf
));
105 pass
= getpwuid(getuid());
108 #ifdef HAVE_GETPW_R_POSIX
109 if (getpwnam_r(temp
, &pwres
, pwbuf
, sizeof(pwbuf
), &pass
) != 0)
111 #elif HAVE_GETPW_R_DRAFT
112 pass
= getpwnam_r(temp
, &pwres
, pwbuf
, sizeof(pwbuf
));
114 pass
= getpwnam(temp
);
117 el_free(temp
); /* value no more needed */
121 /* update pointer txt to point at string immedially following */
125 len
= strlen(pass
->pw_dir
) + 1 + strlen(txt
) + 1;
126 temp
= el_malloc(len
* sizeof(*temp
));
129 (void)snprintf(temp
, len
, "%s/%s", pass
->pw_dir
, txt
);
136 * return first found file name starting by the ``text'' or NULL if no
137 * such file can be found
138 * value of ``state'' is ignored
140 * it's the caller's responsibility to free the returned string
143 fn_filename_completion_function(const char *text
, int state
)
145 static DIR *dir
= NULL
;
146 static char *filename
= NULL
, *dirname
= NULL
, *dirpath
= NULL
;
147 static size_t filename_len
= 0;
148 struct dirent
*entry
;
152 if (state
== 0 || dir
== NULL
) {
153 temp
= strrchr(text
, '/');
157 nptr
= el_realloc(filename
, (strlen(temp
) + 1) *
165 (void)strcpy(filename
, temp
);
166 len
= (size_t)(temp
- text
); /* including last slash */
168 nptr
= el_realloc(dirname
, (len
+ 1) *
176 (void)strncpy(dirname
, text
, len
);
183 filename
= strdup(text
);
184 if (filename
== NULL
)
196 /* support for ``~user'' syntax */
200 if (dirname
== NULL
) {
201 if ((dirname
= strdup("")) == NULL
)
203 dirpath
= strdup("./");
204 } else if (*dirname
== '~')
205 dirpath
= fn_tilde_expand(dirname
);
207 dirpath
= strdup(dirname
);
212 dir
= opendir(dirpath
);
214 return NULL
; /* cannot open the directory */
216 /* will be used in cycle */
217 filename_len
= filename
? strlen(filename
) : 0;
221 while ((entry
= readdir(dir
)) != NULL
) {
223 if (entry
->d_name
[0] == '.' && (!entry
->d_name
[1]
224 || (entry
->d_name
[1] == '.' && !entry
->d_name
[2])))
226 if (filename_len
== 0)
228 /* otherwise, get first entry where first */
229 /* filename_len characters are equal */
230 if (entry
->d_name
[0] == filename
[0]
231 #if HAVE_STRUCT_DIRENT_D_NAMLEN
232 && entry
->d_namlen
>= filename_len
234 && strlen(entry
->d_name
) >= filename_len
236 && strncmp(entry
->d_name
, filename
,
241 if (entry
) { /* match found */
243 #if HAVE_STRUCT_DIRENT_D_NAMLEN
244 len
= entry
->d_namlen
;
246 len
= strlen(entry
->d_name
);
249 len
= strlen(dirname
) + len
+ 1;
250 temp
= el_malloc(len
* sizeof(*temp
));
253 (void)snprintf(temp
, len
, "%s%s", dirname
, entry
->d_name
);
265 append_char_function(const char *name
)
268 char *expname
= *name
== '~' ? fn_tilde_expand(name
) : NULL
;
269 const char *rs
= " ";
271 if (stat(expname
? expname
: name
, &stbuf
) == -1)
273 if (S_ISDIR(stbuf
.st_mode
))
281 * returns list of completions for text given
282 * non-static for readline.
284 char ** completion_matches(const char *, char *(*)(const char *, int));
286 completion_matches(const char *text
, char *(*genfunc
)(const char *, int))
288 char **match_list
= NULL
, *retstr
, *prevstr
;
289 size_t match_list_len
, max_equal
, which
, i
;
294 while ((retstr
= (*genfunc
) (text
, (int)matches
)) != NULL
) {
295 /* allow for list terminator here */
296 if (matches
+ 3 >= match_list_len
) {
298 while (matches
+ 3 >= match_list_len
)
299 match_list_len
<<= 1;
300 nmatch_list
= el_realloc(match_list
,
301 match_list_len
* sizeof(*nmatch_list
));
302 if (nmatch_list
== NULL
) {
306 match_list
= nmatch_list
;
309 match_list
[++matches
] = retstr
;
313 return NULL
; /* nothing found */
315 /* find least denominator and insert it to match_list[0] */
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
++)
326 retstr
= el_malloc((max_equal
+ 1) * sizeof(*retstr
));
327 if (retstr
== NULL
) {
331 (void)strncpy(retstr
, match_list
[1], max_equal
);
332 retstr
[max_equal
] = '\0';
333 match_list
[0] = retstr
;
335 /* add NULL as last pointer to the array */
336 match_list
[matches
+ 1] = NULL
;
342 * Sort function for qsort(). Just wrapper around strcasecmp().
345 _fn_qsort_string_compare(const void *i1
, const void *i2
)
347 const char *s1
= ((const char * const *)i1
)[0];
348 const char *s2
= ((const char * const *)i2
)[0];
350 return strcasecmp(s1
, s2
);
354 * Display list of strings in columnar format on readline's output stream.
355 * 'matches' is list of strings, 'num' is number of strings in 'matches',
356 * 'width' is maximum length of string in 'matches'.
358 * matches[0] is not one of the match strings, but it is counted in
359 * num, so the strings are matches[1] *through* matches[num-1].
362 fn_display_match_list (EditLine
*el
, char **matches
, size_t num
, size_t width
)
364 size_t line
, lines
, col
, cols
, thisguy
;
365 int screenwidth
= el
->el_terminal
.t_size
.h
;
367 /* Ignore matches[0]. Avoid 1-based array logic below. */
372 * Find out how many entries can be put on one line; count
373 * with one space between strings the same way it's printed.
375 cols
= (size_t)screenwidth
/ (width
+ 1);
379 /* how many lines of output, rounded up */
380 lines
= (num
+ cols
- 1) / cols
;
382 /* Sort the items. */
383 qsort(matches
, num
, sizeof(char *), _fn_qsort_string_compare
);
386 * On the ith line print elements i, i+lines, i+lines*2, etc.
388 for (line
= 0; line
< lines
; line
++) {
389 for (col
= 0; col
< cols
; col
++) {
390 thisguy
= line
+ col
* lines
;
393 (void)fprintf(el
->el_outfile
, "%s%-*s",
394 col
== 0 ? "" : " ", (int)width
, matches
[thisguy
]);
396 (void)fprintf(el
->el_outfile
, "\n");
401 * Complete the word at or before point,
402 * 'what_to_do' says what to do with the completion.
403 * \t means do standard completion.
404 * `?' means list the possible completions.
405 * `*' means insert all of the possible completions.
406 * `!' means to do standard completion, and list all possible completions if
407 * there is more than one.
409 * Note: '*' support is not implemented
410 * '!' could never be invoked
413 fn_complete(EditLine
*el
,
414 char *(*complet_func
)(const char *, int),
415 char **(*attempted_completion_function
)(const char *, int, int),
416 const Char
*word_break
, const Char
*special_prefixes
,
417 const char *(*app_func
)(const char *), size_t query_items
,
418 int *completion_type
, int *over
, int *point
, int *end
)
420 const TYPE(LineInfo
) *li
;
425 int what_to_do
= '\t';
426 int retval
= CC_NORM
;
428 if (el
->el_state
.lastcmd
== el
->el_state
.thiscmd
)
431 /* readline's rl_complete() has to be told what we did... */
432 if (completion_type
!= NULL
)
433 *completion_type
= what_to_do
;
436 complet_func
= fn_filename_completion_function
;
438 app_func
= append_char_function
;
440 /* We now look backwards for the start of a filename/variable word */
441 li
= FUN(el
,line
)(el
);
443 while (ctemp
> li
->buffer
444 && !Strchr(word_break
, ctemp
[-1])
445 && (!special_prefixes
|| !Strchr(special_prefixes
, ctemp
[-1]) ) )
448 len
= (size_t)(li
->cursor
- ctemp
);
449 temp
= el_malloc((len
+ 1) * sizeof(*temp
));
450 (void)Strncpy(temp
, ctemp
, len
);
453 /* these can be used by function called in completion_matches() */
454 /* or (*attempted_completion_function)() */
456 *point
= (int)(li
->cursor
- li
->buffer
);
458 *end
= (int)(li
->lastchar
- li
->buffer
);
460 if (attempted_completion_function
) {
461 int cur_off
= (int)(li
->cursor
- li
->buffer
);
462 matches
= (*attempted_completion_function
)(
463 ct_encode_string(temp
, &el
->el_scratch
),
464 cur_off
- (int)len
, cur_off
);
467 if (!attempted_completion_function
||
468 (over
!= NULL
&& !*over
&& !matches
))
469 matches
= completion_matches(
470 ct_encode_string(temp
, &el
->el_scratch
), complet_func
);
477 size_t matches_num
, maxlen
, match_len
, match_display
=1;
481 * Only replace the completed string with common part of
482 * possible matches if there is possible completion.
484 if (matches
[0][0] != '\0') {
485 el_deletestr(el
, (int) len
);
486 FUN(el
,insertstr
)(el
,
487 ct_decode_string(matches
[0], &el
->el_scratch
));
490 if (what_to_do
== '?')
491 goto display_matches
;
493 if (matches
[2] == NULL
&&
494 (matches
[1] == NULL
|| strcmp(matches
[0], matches
[1]) == 0)) {
496 * We found exact match. Add a space after
497 * it, unless we do filename completion and the
498 * object is a directory.
500 FUN(el
,insertstr
)(el
,
501 ct_decode_string((*app_func
)(matches
[0]),
503 } else if (what_to_do
== '!') {
506 * More than one match and requested to list possible
510 for(i
= 1, maxlen
= 0; matches
[i
]; i
++) {
511 match_len
= strlen(matches
[i
]);
512 if (match_len
> maxlen
)
515 /* matches[1] through matches[i-1] are available */
516 matches_num
= (size_t)(i
- 1);
518 /* newline to get on next line from command line */
519 (void)fprintf(el
->el_outfile
, "\n");
522 * If there are too many items, ask user for display
525 if (matches_num
> query_items
) {
526 (void)fprintf(el
->el_outfile
,
527 "Display all %zu possibilities? (y or n) ",
529 (void)fflush(el
->el_outfile
);
530 if (getc(stdin
) != 'y')
532 (void)fprintf(el
->el_outfile
, "\n");
537 * Interface of this function requires the
538 * strings be matches[1..num-1] for compat.
539 * We have matches_num strings not counting
540 * the prefix in matches[0], so we need to
541 * add 1 to matches_num for the call.
543 fn_display_match_list(el
, matches
,
544 matches_num
+1, maxlen
);
546 retval
= CC_REDISPLAY
;
547 } else if (matches
[0][0]) {
549 * There was some common match, but the name was
550 * not complete enough. Next tab will print possible
555 /* lcd is not a valid object - further specification */
561 /* free elements of array and the array itself */
562 for (i
= 0; matches
[i
]; i
++)
572 * el-compatible wrapper around rl_complete; needed for key binding
576 _el_fn_complete(EditLine
*el
, int ch
__attribute__((__unused__
)))
578 return (unsigned char)fn_complete(el
, NULL
, NULL
,
579 break_chars
, NULL
, NULL
, (size_t)100,
580 NULL
, NULL
, NULL
, NULL
);