1
/* $NetBSD: filecomplete.c,v 1.13 2009/01/26 17:32:41 apb 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.
32
/* AIX requires this to be the first thing in the file. */
33
#if defined (_AIX) && !defined (__GNUC__)
42
# define alloca(n) __builtin_alloca (n)
48
extern char *alloca ();
53
#if !defined(lint) && !defined(SCCSID)
54
#endif /* not lint && not SCCSID */
56
#include <sys/types.h>
77
#include "fcns.h" /* for EL_NUM_FCNS */
79
#include "filecomplete.h"
81
static char break_chars[] = { ' ', '\t', '\n', '"', '\\', '\'', '`', '@', '$',
82
'>', '<', '=', ';', '|', '&', '{', '(', '\0' };
85
/********************************/
86
/* completion functions */
89
* does tilde expansion of strings of type ``~user/foo''
90
* if ``user'' isn't valid user name or ``txt'' doesn't start
91
* w/ '~', returns pointer to strdup()ed copy of ``txt''
93
* it's callers's responsibility to free() returned string
96
fn_tilde_expand(const char *txt)
98
struct passwd pwres, *pass;
104
return (strdup(txt));
106
temp = strchr(txt + 1, '/');
108
temp = strdup(txt + 1);
112
len = temp - txt + 1; /* text until string after slash */
116
(void)strncpy(temp, txt + 1, len - 2);
117
temp[len - 2] = '\0';
119
/* XXXMYSQL: use non-_r functions for now */
121
pass = getpwuid(getuid());
123
pass = getpwnam(temp);
125
free(temp); /* value no more needed */
127
return (strdup(txt));
129
/* update pointer txt to point at string immedially following */
133
temp = malloc(strlen(pass->pw_dir) + 1 + strlen(txt) + 1);
136
(void)sprintf(temp, "%s/%s", pass->pw_dir, txt);
143
* return first found file name starting by the ``text'' or NULL if no
144
* such file can be found
145
* value of ``state'' is ignored
147
* it's caller's responsibility to free returned string
150
fn_filename_completion_function(const char *text, int state)
152
static DIR *dir = NULL;
153
static char *filename = NULL, *dirname = NULL, *dirpath = NULL;
154
static size_t filename_len = 0;
155
struct dirent *entry;
159
if (state == 0 || dir == NULL) {
160
temp = strrchr(text, '/');
164
nptr = realloc(filename, strlen(temp) + 1);
170
(void)strcpy(filename, temp);
171
len = temp - text; /* including last slash */
172
nptr = realloc(dirname, len + 1);
178
(void)strncpy(dirname, text, len);
184
filename = strdup(text);
185
if (filename == NULL)
196
/* support for ``~user'' syntax */
199
if (dirname == NULL && (dirname = strdup("./")) == NULL)
203
dirpath = fn_tilde_expand(dirname);
205
dirpath = strdup(dirname);
210
dir = opendir(dirpath);
212
return (NULL); /* cannot open the directory */
214
/* will be used in cycle */
215
filename_len = filename ? strlen(filename) : 0;
219
while ((entry = readdir(dir)) != NULL) {
221
if (entry->d_name[0] == '.' && (!entry->d_name[1]
222
|| (entry->d_name[1] == '.' && !entry->d_name[2])))
224
if (filename_len == 0)
226
/* otherwise, get first entry where first */
227
/* filename_len characters are equal */
228
if (entry->d_name[0] == filename[0]
229
#if HAVE_STRUCT_DIRENT_D_NAMLEN
230
&& entry->d_namlen >= filename_len
232
&& strlen(entry->d_name) >= filename_len
234
&& strncmp(entry->d_name, filename,
239
if (entry) { /* match found */
241
#if HAVE_STRUCT_DIRENT_D_NAMLEN
242
len = entry->d_namlen;
244
len = strlen(entry->d_name);
247
temp = malloc(strlen(dirname) + len + 1);
250
(void)sprintf(temp, "%s%s", dirname, entry->d_name);
262
append_char_function(const char *name)
265
char *expname = *name == '~' ? fn_tilde_expand(name) : NULL;
266
const char *rs = " ";
268
if (stat(expname ? expname : name, &stbuf) == -1)
270
if (S_ISDIR(stbuf.st_mode))
278
* returns list of completions for text given
279
* non-static for readline.
281
char ** completion_matches(const char *, char *(*)(const char *, int));
283
completion_matches(const char *text, char *(*genfunc)(const char *, int))
285
char **match_list = NULL, *retstr, *prevstr;
286
size_t match_list_len, max_equal, which, i;
291
while ((retstr = (*genfunc) (text, (int)matches)) != NULL) {
292
/* allow for list terminator here */
293
if (matches + 3 >= match_list_len) {
295
while (matches + 3 >= match_list_len)
296
match_list_len <<= 1;
297
nmatch_list = realloc(match_list,
298
match_list_len * sizeof(char *));
299
if (nmatch_list == NULL) {
303
match_list = nmatch_list;
306
match_list[++matches] = retstr;
310
return NULL; /* nothing found */
312
/* find least denominator and insert it to match_list[0] */
314
prevstr = match_list[1];
315
max_equal = strlen(prevstr);
316
for (; which <= matches; which++) {
317
for (i = 0; i < max_equal &&
318
prevstr[i] == match_list[which][i]; i++)
323
retstr = malloc(max_equal + 1);
324
if (retstr == NULL) {
328
(void)strncpy(retstr, match_list[1], max_equal);
329
retstr[max_equal] = '\0';
330
match_list[0] = retstr;
332
/* add NULL as last pointer to the array */
333
match_list[matches + 1] = (char *) NULL;
339
* Sort function for qsort(). Just wrapper around strcasecmp().
342
_fn_qsort_string_compare(const void *i1, const void *i2)
344
const char *s1 = ((const char * const *)i1)[0];
345
const char *s2 = ((const char * const *)i2)[0];
347
return strcasecmp(s1, s2);
351
* Display list of strings in columnar format on readline's output stream.
352
* 'matches' is list of strings, 'len' is number of strings in 'matches',
353
* 'max' is maximum length of string in 'matches'.
356
fn_display_match_list (EditLine *el, char **matches, int len, int max)
358
int i, idx, limit, count;
359
int screenwidth = el->el_term.t_size.h;
362
* Find out how many entries can be put on one line, count
363
* with two spaces between strings.
365
limit = screenwidth / (max + 2);
369
/* how many lines of output */
371
if (count * limit < len)
374
/* Sort the items if they are not already sorted. */
375
qsort(&matches[1], (size_t)(len - 1), sizeof(char *),
376
_fn_qsort_string_compare);
379
for(; count > 0; count--) {
380
for(i = 0; i < limit && matches[idx]; i++, idx++)
381
(void)fprintf(el->el_outfile, "%-*s ", max,
383
(void)fprintf(el->el_outfile, "\n");
388
* Complete the word at or before point,
389
* 'what_to_do' says what to do with the completion.
390
* \t means do standard completion.
391
* `?' means list the possible completions.
392
* `*' means insert all of the possible completions.
393
* `!' means to do standard completion, and list all possible completions if
394
* there is more than one.
396
* Note: '*' support is not implemented
397
* '!' could never be invoked
400
fn_complete(EditLine *el,
401
char *(*complet_func)(const char *, int),
402
char **(*attempted_completion_function)(const char *, int, int),
403
const char *word_break, const char *special_prefixes,
404
const char *(*app_func)(const char *), int query_items,
405
int *completion_type, int *over, int *point, int *end)
408
char *temp, **matches;
411
int what_to_do = '\t';
412
int retval = CC_NORM;
414
if (el->el_state.lastcmd == el->el_state.thiscmd)
417
/* readline's rl_complete() has to be told what we did... */
418
if (completion_type != NULL)
419
*completion_type = what_to_do;
422
complet_func = fn_filename_completion_function;
424
app_func = append_char_function;
426
/* We now look backwards for the start of a filename/variable word */
428
ctemp = (const char *) li->cursor;
429
while (ctemp > li->buffer
430
&& !strchr(word_break, ctemp[-1])
431
&& (!special_prefixes || !strchr(special_prefixes, ctemp[-1]) ) )
434
len = li->cursor - ctemp;
435
#if defined(__SSP__) || defined(__SSP_ALL__)
436
temp = malloc(len + 1);
438
temp = alloca(len + 1);
440
(void)strncpy(temp, ctemp, len);
443
/* these can be used by function called in completion_matches() */
444
/* or (*attempted_completion_function)() */
446
*point = li->cursor - li->buffer;
448
*end = li->lastchar - li->buffer;
450
if (attempted_completion_function) {
451
int cur_off = li->cursor - li->buffer;
452
matches = (*attempted_completion_function) (temp,
453
(int)(cur_off - len), cur_off);
456
if (!attempted_completion_function ||
457
(over != NULL && !*over && !matches))
458
matches = completion_matches(temp, complet_func);
465
int matches_num, maxlen, match_len, match_display=1;
469
* Only replace the completed string with common part of
470
* possible matches if there is possible completion.
472
if (matches[0][0] != '\0') {
473
el_deletestr(el, (int) len);
474
el_insertstr(el, matches[0]);
477
if (what_to_do == '?')
478
goto display_matches;
480
if (matches[2] == NULL && strcmp(matches[0], matches[1]) == 0) {
482
* We found exact match. Add a space after
483
* it, unless we do filename completion and the
484
* object is a directory.
486
el_insertstr(el, (*app_func)(matches[0]));
487
} else if (what_to_do == '!') {
490
* More than one match and requested to list possible
494
for(i=1, maxlen=0; matches[i]; i++) {
495
match_len = strlen(matches[i]);
496
if (match_len > maxlen)
501
/* newline to get on next line from command line */
502
(void)fprintf(el->el_outfile, "\n");
505
* If there are too many items, ask user for display
508
if (matches_num > query_items) {
509
(void)fprintf(el->el_outfile,
510
"Display all %d possibilities? (y or n) ",
512
(void)fflush(el->el_outfile);
513
if (getc(stdin) != 'y')
515
(void)fprintf(el->el_outfile, "\n");
519
fn_display_match_list(el, matches, matches_num,
521
retval = CC_REDISPLAY;
522
} else if (matches[0][0]) {
524
* There was some common match, but the name was
525
* not complete enough. Next tab will print possible
530
/* lcd is not a valid object - further specification */
536
/* free elements of array and the array itself */
537
for (i = 0; matches[i]; i++)
542
#if defined(__SSP__) || defined(__SSP_ALL__)
549
* el-compatible wrapper around rl_complete; needed for key binding
553
_el_fn_complete(EditLine *el, int ch __attribute__((__unused__)))
555
return (unsigned char)fn_complete(el, NULL, NULL,
556
break_chars, NULL, NULL, 100,
557
NULL, NULL, NULL, NULL);