2 * Copyright (c) 1997 The NetBSD Foundation, Inc.
5 * This code is derived from software contributed to The NetBSD Foundation
8 * Redistribution and use in source and binary forms, with or without
9 * modification, are permitted provided that the following conditions
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.
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.
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 $
38 #include <sys/types.h>
59 #include "fcns.h" /* for EL_NUM_FCNS */
61 #include "filecomplete.h"
63 static char break_chars
[] = { ' ', '\t', '\n', '"', '\\', '\'', '`', '@', '$',
64 '>', '<', '=', ';', '|', '&', '{', '(', '\0' };
67 /********************************/
68 /* completion functions */
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''
75 * it's callers's responsibility to free() returned string
78 fn_tilde_expand(const char *txt
)
81 XXX: replace the next line with this line when getpwuid_r or
82 getpwnam_r become available:
83 struct passwd pwres, *pass;
93 temp
= strchr(txt
+ 1, '/');
95 temp
= strdup(txt
+ 1);
99 len
= temp
- txt
+ 1; /* text until string after slash */
103 (void)strncpy(temp
, txt
+ 1, len
- 2);
104 temp
[len
- 2] = '\0';
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)
113 pass
= getpwuid(getuid());
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)
122 pass
= getpwnam(temp
);
124 free(temp
); /* value no more needed */
126 return (strdup(txt
));
128 /* update pointer txt to point at string immedially following */
132 temp
= malloc(strlen(pass
->pw_dir
) + 1 + strlen(txt
) + 1);
135 (void)sprintf(temp
, "%s/%s", pass
->pw_dir
, txt
);
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
146 * it's caller's responsibility to free returned string
149 fn_filename_completion_function(const char *text
, int state
)
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
;
158 if (state
== 0 || dir
== NULL
) {
159 temp
= strrchr(text
, '/');
163 nptr
= realloc(filename
, strlen(temp
) + 1);
169 (void)strcpy(filename
, temp
);
170 len
= temp
- text
; /* including last slash */
171 nptr
= realloc(dirname
, len
+ 1);
177 (void)strncpy(dirname
, text
, len
);
183 filename
= strdup(text
);
184 if (filename
== NULL
)
195 /* support for ``~user'' syntax */
198 if (dirname
== NULL
&& (dirname
= strdup("./")) == NULL
)
202 dirpath
= fn_tilde_expand(dirname
);
204 dirpath
= strdup(dirname
);
209 dir
= opendir(dirpath
);
211 return (NULL
); /* cannot open the directory */
213 /* will be used in cycle */
214 filename_len
= filename
? strlen(filename
) : 0;
218 while ((entry
= readdir(dir
)) != NULL
) {
220 if (entry
->d_name
[0] == '.' && (!entry
->d_name
[1]
221 || (entry
->d_name
[1] == '.' && !entry
->d_name
[2])))
223 if (filename_len
== 0)
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
231 && entry
->d_namlen
>= filename_len
233 && strncmp(entry
->d_name
, filename
,
238 if (entry
) { /* match found */
240 #if defined(__SVR4) || defined(__linux__)
241 len
= strlen(entry
->d_name
);
243 len
= entry
->d_namlen
;
246 temp
= malloc(strlen(dirname
) + len
+ 1);
249 (void)sprintf(temp
, "%s%s", dirname
, entry
->d_name
);
261 append_char_function(const char *name
)
264 char *expname
= *name
== '~' ? fn_tilde_expand(name
) : NULL
;
267 if (stat(expname
? expname
: name
, &stbuf
) == -1)
269 if (S_ISDIR(stbuf
.st_mode
))
277 * returns list of completions for text given
278 * non-static for readline.
280 char ** completion_matches(const char *, char *(*)(const char *, int));
282 completion_matches(const char *text
, char *(*genfunc
)(const char *, int))
284 char **match_list
= NULL
, *retstr
, *prevstr
;
285 size_t match_list_len
, max_equal
, which
, i
;
290 while ((retstr
= (*genfunc
) (text
, (int)matches
)) != NULL
) {
291 /* allow for list terminator here */
292 if (matches
+ 3 >= match_list_len
) {
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
) {
302 match_list
= nmatch_list
;
305 match_list
[++matches
] = retstr
;
309 return NULL
; /* nothing found */
311 /* find least denominator and insert it to match_list[0] */
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
++)
322 retstr
= malloc(max_equal
+ 1);
323 if (retstr
== NULL
) {
327 (void)strncpy(retstr
, match_list
[1], max_equal
);
328 retstr
[max_equal
] = '\0';
329 match_list
[0] = retstr
;
331 /* add NULL as last pointer to the array */
332 match_list
[matches
+ 1] = (char *) NULL
;
338 * Sort function for qsort(). Just wrapper around strcasecmp().
341 _fn_qsort_string_compare(const void *i1
, const void *i2
)
343 const char *s1
= ((const char * const *)i1
)[0];
344 const char *s2
= ((const char * const *)i2
)[0];
346 return strcasecmp(s1
, s2
);
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'.
355 fn_display_match_list (EditLine
*el
, char **matches
, int len
, int max
)
357 int i
, idx
, limit
, count
;
358 int screenwidth
= el
->el_term
.t_size
.h
;
361 * Find out how many entries can be put on one line, count
362 * with two spaces between strings.
364 limit
= screenwidth
/ (max
+ 2);
368 /* how many lines of output */
370 if (count
* limit
< len
)
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
);
378 for(; count
> 0; count
--) {
379 for(i
= 0; i
< limit
&& matches
[idx
]; i
++, idx
++)
380 (void)fprintf(el
->el_outfile
, "%-*s ", max
,
382 (void)fprintf(el
->el_outfile
, "\n");
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.
395 * Note: '*' support is not implemented
396 * '!' could never be invoked
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
)
407 char *temp
, **matches
;
410 int what_to_do
= '\t';
411 int retval
= CC_NORM
;
413 if (el
->el_state
.lastcmd
== el
->el_state
.thiscmd
)
416 /* readline's rl_complete() has to be told what we did... */
417 if (completion_type
!= NULL
)
418 *completion_type
= what_to_do
;
421 complet_func
= fn_filename_completion_function
;
423 app_func
= append_char_function
;
425 /* We now look backwards for the start of a filename/variable word */
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]) ) )
433 len
= li
->cursor
- ctemp
;
434 #if defined(__SSP__) || defined(__SSP_ALL__)
435 temp
= malloc(len
+ 1);
437 temp
= alloca(len
+ 1);
439 (void)strncpy(temp
, ctemp
, len
);
442 /* these can be used by function called in completion_matches() */
443 /* or (*attempted_completion_function)() */
445 *point
= li
->cursor
- li
->buffer
;
447 *end
= li
->lastchar
- li
->buffer
;
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
);
455 if (!attempted_completion_function
||
456 (over
!= NULL
&& !*over
&& !matches
))
457 matches
= completion_matches(temp
, complet_func
);
464 int matches_num
, maxlen
, match_len
, match_display
=1;
468 * Only replace the completed string with common part of
469 * possible matches if there is possible completion.
471 if (matches
[0][0] != '\0') {
472 el_deletestr(el
, (int) len
);
473 el_insertstr(el
, matches
[0]);
476 if (what_to_do
== '?')
477 goto display_matches
;
479 if (matches
[2] == NULL
&& strcmp(matches
[0], matches
[1]) == 0) {
481 * We found exact match. Add a space after
482 * it, unless we do filename completion and the
483 * object is a directory.
485 el_insertstr(el
, (*append_char_function
)(matches
[0]));
486 } else if (what_to_do
== '!') {
489 * More than one match and requested to list possible
493 for(i
=1, maxlen
=0; matches
[i
]; i
++) {
494 match_len
= strlen(matches
[i
]);
495 if (match_len
> maxlen
)
500 /* newline to get on next line from command line */
501 (void)fprintf(el
->el_outfile
, "\n");
504 * If there are too many items, ask user for display
507 if (matches_num
> query_items
) {
508 (void)fprintf(el
->el_outfile
,
509 "Display all %d possibilities? (y or n) ",
511 (void)fflush(el
->el_outfile
);
512 if (getc(stdin
) != 'y')
514 (void)fprintf(el
->el_outfile
, "\n");
518 fn_display_match_list(el
, matches
, matches_num
,
520 retval
= CC_REDISPLAY
;
521 } else if (matches
[0][0]) {
523 * There was some common match, but the name was
524 * not complete enough. Next tab will print possible
529 /* lcd is not a valid object - further specification */
535 /* free elements of array and the array itself */
536 for (i
= 0; matches
[i
]; i
++)
541 #if defined(__SSP__) || defined(__SSP_ALL__)
548 * el-compatible wrapper around rl_complete; needed for key binding
552 _el_fn_complete(EditLine
*el
, int ch
__attribute__((__unused__
)))
554 return (unsigned char)fn_complete(el
, NULL
, NULL
,
555 break_chars
, NULL
, NULL
, 100,
556 NULL
, NULL
, NULL
, NULL
);