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