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