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