Home | History | Annotate | Line # | Download | only in libedit
filecomplete.c revision 1.5
      1 /*	$NetBSD: filecomplete.c,v 1.5 2005/05/18 22:34: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  * 3. All advertising materials mentioning features or use of this software
     19  *    must display the following acknowledgement:
     20  *	This product includes software developed by the NetBSD
     21  *	Foundation, Inc. and its contributors.
     22  * 4. Neither the name of The NetBSD Foundation nor the names of its
     23  *    contributors may be used to endorse or promote products derived
     24  *    from this software without specific prior written permission.
     25  *
     26  * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
     27  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
     28  * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
     29  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
     30  * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
     31  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
     32  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
     33  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
     34  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
     35  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
     36  * POSSIBILITY OF SUCH DAMAGE.
     37  */
     38 
     39 #include "config.h"
     40 #if !defined(lint) && !defined(SCCSID)
     41 __RCSID("$NetBSD: filecomplete.c,v 1.5 2005/05/18 22:34:41 christos Exp $");
     42 #endif /* not lint && not SCCSID */
     43 
     44 #include <sys/types.h>
     45 #include <sys/stat.h>
     46 #include <stdio.h>
     47 #include <dirent.h>
     48 #include <string.h>
     49 #include <pwd.h>
     50 #include <ctype.h>
     51 #include <stdlib.h>
     52 #include <unistd.h>
     53 #include <limits.h>
     54 #include <errno.h>
     55 #include <fcntl.h>
     56 #ifdef HAVE_VIS_H
     57 #include <vis.h>
     58 #else
     59 #include "np/vis.h"
     60 #endif
     61 #ifdef HAVE_ALLOCA_H
     62 #include <alloca.h>
     63 #endif
     64 #include "el.h"
     65 #include "fcns.h"		/* for EL_NUM_FCNS */
     66 #include "histedit.h"
     67 #include "filecomplete.h"
     68 
     69 static char break_chars[] = { ' ', '\t', '\n', '"', '\\', '\'', '`', '@', '$',
     70     '>', '<', '=', ';', '|', '&', '{', '(', '\0' };
     71 
     72 
     73 /********************************/
     74 /* completion functions */
     75 
     76 /*
     77  * does tilde expansion of strings of type ``~user/foo''
     78  * if ``user'' isn't valid user name or ``txt'' doesn't start
     79  * w/ '~', returns pointer to strdup()ed copy of ``txt''
     80  *
     81  * it's callers's responsibility to free() returned string
     82  */
     83 char *
     84 tilde_expand(char *txt)
     85 {
     86 	struct passwd pwres, *pass;
     87 	char *temp;
     88 	size_t len = 0;
     89 	char pwbuf[1024];
     90 
     91 	if (txt[0] != '~')
     92 		return (strdup(txt));
     93 
     94 	temp = strchr(txt + 1, '/');
     95 	if (temp == NULL) {
     96 		temp = strdup(txt + 1);
     97 		if (temp == NULL)
     98 			return NULL;
     99 	} else {
    100 		len = temp - txt + 1;	/* text until string after slash */
    101 		temp = malloc(len);
    102 		if (temp == NULL)
    103 			return NULL;
    104 		(void)strncpy(temp, txt + 1, len - 2);
    105 		temp[len - 2] = '\0';
    106 	}
    107 	if (temp[0] == 0) {
    108 		if (getpwuid_r(getuid(), &pwres, pwbuf, sizeof(pwbuf), &pass) != 0)
    109 			pass = NULL;
    110 	} else {
    111 		if (getpwnam_r(temp, &pwres, pwbuf, sizeof(pwbuf), &pass) != 0)
    112 			pass = NULL;
    113 	}
    114 	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 	temp = malloc(strlen(pass->pw_dir) + 1 + strlen(txt) + 1);
    123 	if (temp == NULL)
    124 		return NULL;
    125 	(void)sprintf(temp, "%s/%s", pass->pw_dir, txt);
    126 
    127 	return (temp);
    128 }
    129 
    130 
    131 /*
    132  * return first found file name starting by the ``text'' or NULL if no
    133  * such file can be found
    134  * value of ``state'' is ignored
    135  *
    136  * it's caller's responsibility to free returned string
    137  */
    138 char *
    139 filename_completion_function(const char *text, int state)
    140 {
    141 	static DIR *dir = NULL;
    142 	static char *filename = NULL, *dirname = NULL, *dirpath = NULL;
    143 	static size_t filename_len = 0;
    144 	struct dirent *entry;
    145 	char *temp;
    146 	size_t len;
    147 
    148 	if (state == 0 || dir == NULL) {
    149 		temp = strrchr(text, '/');
    150 		if (temp) {
    151 			char *nptr;
    152 			temp++;
    153 			nptr = realloc(filename, strlen(temp) + 1);
    154 			if (nptr == NULL) {
    155 				free(filename);
    156 				return NULL;
    157 			}
    158 			filename = nptr;
    159 			(void)strcpy(filename, temp);
    160 			len = temp - text;	/* including last slash */
    161 			nptr = realloc(dirname, len + 1);
    162 			if (nptr == NULL) {
    163 				free(filename);
    164 				return NULL;
    165 			}
    166 			dirname = nptr;
    167 			(void)strncpy(dirname, text, len);
    168 			dirname[len] = '\0';
    169 		} else {
    170 			if (*text == 0)
    171 				filename = NULL;
    172 			else {
    173 				filename = strdup(text);
    174 				if (filename == NULL)
    175 					return NULL;
    176 			}
    177 			dirname = NULL;
    178 		}
    179 
    180 		if (dir != NULL) {
    181 			(void)closedir(dir);
    182 			dir = NULL;
    183 		}
    184 
    185 		/* support for ``~user'' syntax */
    186 		free(dirpath);
    187 
    188 		if (dirname == NULL && (dirname = strdup("./")) == NULL)
    189 			return NULL;
    190 
    191 		if (*dirname == '~')
    192 			dirpath = 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 defined(__SVR4) || defined(__linux__)
    219 		    && strlen(entry->d_name) >= filename_len
    220 #else
    221 		    && entry->d_namlen >= filename_len
    222 #endif
    223 		    && strncmp(entry->d_name, filename,
    224 			filename_len) == 0)
    225 			break;
    226 	}
    227 
    228 	if (entry) {		/* match found */
    229 		struct stat stbuf;
    230 		const char *isdir = "";
    231 
    232 #if defined(__SVR4) || defined(__linux__)
    233 		len = strlen(entry->d_name);
    234 #else
    235 		len = entry->d_namlen;
    236 #endif
    237 		temp = malloc(strlen(dirpath) + len + 1);
    238 		if (temp == NULL)
    239 			return NULL;
    240 		(void)sprintf(temp, "%s%s", dirpath, entry->d_name); /* safe */
    241 
    242 		/* test, if it's directory */
    243 		if (stat(temp, &stbuf) == 0 && S_ISDIR(stbuf.st_mode))
    244 			isdir = "/";
    245 		free(temp);
    246 		temp = malloc(strlen(dirname) + len + 1 + 1);
    247 		if (temp == NULL)
    248 			return NULL;
    249 		(void)sprintf(temp, "%s%s%s", dirname, entry->d_name, isdir);
    250 	} else {
    251 		(void)closedir(dir);
    252 		dir = NULL;
    253 		temp = NULL;
    254 	}
    255 
    256 	return (temp);
    257 }
    258 
    259 
    260 
    261 /*
    262  * returns list of completions for text given
    263  * non-static for readline.
    264  */
    265 char ** completion_matches(const char *, char *(*)(const char *, int));
    266 char **
    267 completion_matches(const char *text, char *(*genfunc)(const char *, int))
    268 {
    269 	char **match_list = NULL, *retstr, *prevstr;
    270 	size_t match_list_len, max_equal, which, i;
    271 	size_t matches;
    272 
    273 	matches = 0;
    274 	match_list_len = 1;
    275 	while ((retstr = (*genfunc) (text, (int)matches)) != NULL) {
    276 		/* allow for list terminator here */
    277 		if (matches + 3 >= match_list_len) {
    278 			char **nmatch_list;
    279 			while (matches + 3 >= match_list_len)
    280 				match_list_len <<= 1;
    281 			nmatch_list = realloc(match_list,
    282 			    match_list_len * sizeof(char *));
    283 			if (nmatch_list == NULL) {
    284 				free(match_list);
    285 				return NULL;
    286 			}
    287 			match_list = nmatch_list;
    288 
    289 		}
    290 		match_list[++matches] = retstr;
    291 	}
    292 
    293 	if (!match_list)
    294 		return NULL;	/* nothing found */
    295 
    296 	/* find least denominator and insert it to match_list[0] */
    297 	which = 2;
    298 	prevstr = match_list[1];
    299 	max_equal = strlen(prevstr);
    300 	for (; which <= matches; which++) {
    301 		for (i = 0; i < max_equal &&
    302 		    prevstr[i] == match_list[which][i]; i++)
    303 			continue;
    304 		max_equal = i;
    305 	}
    306 
    307 	retstr = malloc(max_equal + 1);
    308 	if (retstr == NULL) {
    309 		free(match_list);
    310 		return NULL;
    311 	}
    312 	(void)strncpy(retstr, match_list[1], max_equal);
    313 	retstr[max_equal] = '\0';
    314 	match_list[0] = retstr;
    315 
    316 	/* add NULL as last pointer to the array */
    317 	match_list[matches + 1] = (char *) NULL;
    318 
    319 	return (match_list);
    320 }
    321 
    322 /*
    323  * Sort function for qsort(). Just wrapper around strcasecmp().
    324  */
    325 static int
    326 _fn_qsort_string_compare(const void *i1, const void *i2)
    327 {
    328 	const char *s1 = ((const char * const *)i1)[0];
    329 	const char *s2 = ((const char * const *)i2)[0];
    330 
    331 	return strcasecmp(s1, s2);
    332 }
    333 
    334 /*
    335  * Display list of strings in columnar format on readline's output stream.
    336  * 'matches' is list of strings, 'len' is number of strings in 'matches',
    337  * 'max' is maximum length of string in 'matches'.
    338  */
    339 void
    340 fn_display_match_list (EditLine *el, char **matches, int len, int max)
    341 {
    342 	int i, idx, limit, count;
    343 	int screenwidth = el->el_term.t_size.h;
    344 
    345 	/*
    346 	 * Find out how many entries can be put on one line, count
    347 	 * with two spaces between strings.
    348 	 */
    349 	limit = screenwidth / (max + 2);
    350 	if (limit == 0)
    351 		limit = 1;
    352 
    353 	/* how many lines of output */
    354 	count = len / limit;
    355 	if (count * limit < len)
    356 		count++;
    357 
    358 	/* Sort the items if they are not already sorted. */
    359 	qsort(&matches[1], (size_t)(len - 1), sizeof(char *),
    360 	    _fn_qsort_string_compare);
    361 
    362 	idx = 1;
    363 	for(; count > 0; count--) {
    364 		for(i = 0; i < limit && matches[idx]; i++, idx++)
    365 			(void)fprintf(el->el_outfile, "%-*s  ", max,
    366 			    matches[idx]);
    367 		(void)fprintf(el->el_outfile, "\n");
    368 	}
    369 }
    370 
    371 /*
    372  * Complete the word at or before point,
    373  * 'what_to_do' says what to do with the completion.
    374  * \t   means do standard completion.
    375  * `?' means list the possible completions.
    376  * `*' means insert all of the possible completions.
    377  * `!' means to do standard completion, and list all possible completions if
    378  * there is more than one.
    379  *
    380  * Note: '*' support is not implemented
    381  *       '!' could never be invoked
    382  */
    383 int
    384 fn_complete(EditLine *el,
    385 	char *(*complet_func)(const char *, int),
    386 	char **(*attempted_completion_function)(const char *, int, int),
    387 	const char *word_break, const char *special_prefixes,
    388 	char append_character, int query_items,
    389 	int *completion_type, int *over, int *point, int *end)
    390 {
    391 	const LineInfo *li;
    392 	char *temp, **matches;
    393 	const char *ctemp;
    394 	size_t len;
    395 	int what_to_do = '\t';
    396 
    397 	if (el->el_state.lastcmd == el->el_state.thiscmd)
    398 		what_to_do = '?';
    399 
    400 	/* readline's rl_complete() has to be told what we did... */
    401 	if (completion_type != NULL)
    402 		*completion_type = what_to_do;
    403 
    404 	if (!complet_func)
    405 		complet_func = filename_completion_function;
    406 
    407 	/* We now look backwards for the start of a filename/variable word */
    408 	li = el_line(el);
    409 	ctemp = (const char *) li->cursor;
    410 	while (ctemp > li->buffer
    411 	    && !strchr(word_break, ctemp[-1])
    412 	    && (!special_prefixes || !strchr(special_prefixes, ctemp[-1]) ) )
    413 		ctemp--;
    414 
    415 	len = li->cursor - ctemp;
    416 	temp = alloca(len + 1);
    417 	(void)strncpy(temp, ctemp, len);
    418 	temp[len] = '\0';
    419 
    420 	/* these can be used by function called in completion_matches() */
    421 	/* or (*attempted_completion_function)() */
    422 	if (point != 0)
    423 		*point = li->cursor - li->buffer;
    424 	if (end != NULL)
    425 		*end = li->lastchar - li->buffer;
    426 
    427 	if (attempted_completion_function) {
    428 		int cur_off = li->cursor - li->buffer;
    429 		matches = (*attempted_completion_function) (temp,
    430 		    (int)(cur_off - len), cur_off);
    431 	} else
    432 		matches = 0;
    433 	if (!attempted_completion_function ||
    434 	    (over != NULL && *over && !matches))
    435 		matches = completion_matches(temp, complet_func);
    436 
    437 	if (over != NULL)
    438 		*over = 0;
    439 
    440 	if (matches) {
    441 		int i, retval = CC_REFRESH;
    442 		int matches_num, maxlen, match_len, match_display=1;
    443 
    444 		/*
    445 		 * Only replace the completed string with common part of
    446 		 * possible matches if there is possible completion.
    447 		 */
    448 		if (matches[0][0] != '\0') {
    449 			el_deletestr(el, (int) len);
    450 			el_insertstr(el, matches[0]);
    451 		}
    452 
    453 		if (what_to_do == '?')
    454 			goto display_matches;
    455 
    456 		if (matches[2] == NULL && strcmp(matches[0], matches[1]) == 0) {
    457 			/*
    458 			 * We found exact match. Add a space after
    459 			 * it, unless we do filename completion and the
    460 			 * object is a directory.
    461 			 */
    462 			size_t alen = strlen(matches[0]);
    463 			if ((complet_func != filename_completion_function
    464 			      || (alen > 0 && (matches[0])[alen - 1] != '/'))
    465 			    && append_character) {
    466 				char buf[2];
    467 				buf[0] = append_character;
    468 				buf[1] = '\0';
    469 				el_insertstr(el, buf);
    470 			}
    471 		} else if (what_to_do == '!') {
    472     display_matches:
    473 			/*
    474 			 * More than one match and requested to list possible
    475 			 * matches.
    476 			 */
    477 
    478 			for(i=1, maxlen=0; matches[i]; i++) {
    479 				match_len = strlen(matches[i]);
    480 				if (match_len > maxlen)
    481 					maxlen = match_len;
    482 			}
    483 			matches_num = i - 1;
    484 
    485 			/* newline to get on next line from command line */
    486 			(void)fprintf(el->el_outfile, "\n");
    487 
    488 			/*
    489 			 * If there are too many items, ask user for display
    490 			 * confirmation.
    491 			 */
    492 			if (matches_num > query_items) {
    493 				(void)fprintf(el->el_outfile,
    494 				    "Display all %d possibilities? (y or n) ",
    495 				    matches_num);
    496 				(void)fflush(el->el_outfile);
    497 				if (getc(stdin) != 'y')
    498 					match_display = 0;
    499 				(void)fprintf(el->el_outfile, "\n");
    500 			}
    501 
    502 			if (match_display)
    503 				fn_display_match_list(el, matches, matches_num,
    504 					maxlen);
    505 			retval = CC_REDISPLAY;
    506 		} else if (matches[0][0]) {
    507 			/*
    508 			 * There was some common match, but the name was
    509 			 * not complete enough. Next tab will print possible
    510 			 * completions.
    511 			 */
    512 			el_beep(el);
    513 		} else {
    514 			/* lcd is not a valid object - further specification */
    515 			/* is needed */
    516 			el_beep(el);
    517 			retval = CC_NORM;
    518 		}
    519 
    520 		/* free elements of array and the array itself */
    521 		for (i = 0; matches[i]; i++)
    522 			free(matches[i]);
    523 		free(matches), matches = NULL;
    524 
    525 		return (retval);
    526 	}
    527 	return (CC_NORM);
    528 }
    529 
    530 /*
    531  * el-compatible wrapper around rl_complete; needed for key binding
    532  */
    533 /* ARGSUSED */
    534 unsigned char
    535 _el_fn_complete(EditLine *el, int ch __attribute__((__unused__)))
    536 {
    537 	return (unsigned char)fn_complete(el, NULL, NULL,
    538 	    break_chars, NULL, ' ', 100,
    539 	    NULL, NULL, NULL, NULL);
    540 }
    541