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