Home | History | Annotate | Line # | Download | only in libedit
filecomplete.c revision 1.69
      1 /*	$NetBSD: filecomplete.c,v 1.69 2021/09/26 13:45:37 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.69 2021/09/26 13:45:37 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 wchar_t break_chars[] = L" \t\n\"\\'`@$><=;|&{(";
     53 
     54 /********************************/
     55 /* completion functions */
     56 
     57 /*
     58  * does tilde expansion of strings of type ``~user/foo''
     59  * if ``user'' isn't valid user name or ``txt'' doesn't start
     60  * w/ '~', returns pointer to strdup()ed copy of ``txt''
     61  *
     62  * it's the caller's responsibility to free() the returned string
     63  */
     64 char *
     65 fn_tilde_expand(const char *txt)
     66 {
     67 #if defined(HAVE_GETPW_R_POSIX) || defined(HAVE_GETPW_R_DRAFT)
     68 	struct passwd pwres;
     69 	char pwbuf[1024];
     70 #endif
     71 	struct passwd *pass;
     72 	const char *pos;
     73 	char *temp;
     74 	size_t len = 0;
     75 
     76 	if (txt[0] != '~')
     77 		return strdup(txt);
     78 
     79 	pos = strchr(txt + 1, '/');
     80 	if (pos == NULL) {
     81 		temp = strdup(txt + 1);
     82 		if (temp == NULL)
     83 			return NULL;
     84 	} else {
     85 		/* text until string after slash */
     86 		len = (size_t)(pos - txt + 1);
     87 		temp = el_calloc(len, sizeof(*temp));
     88 		if (temp == NULL)
     89 			return NULL;
     90 		(void)strlcpy(temp, txt + 1, len - 1);
     91 	}
     92 	if (temp[0] == 0) {
     93 #ifdef HAVE_GETPW_R_POSIX
     94 		if (getpwuid_r(getuid(), &pwres, pwbuf, sizeof(pwbuf),
     95 		    &pass) != 0)
     96 			pass = NULL;
     97 #elif HAVE_GETPW_R_DRAFT
     98 		pass = getpwuid_r(getuid(), &pwres, pwbuf, sizeof(pwbuf));
     99 #else
    100 		pass = getpwuid(getuid());
    101 #endif
    102 	} else {
    103 #ifdef HAVE_GETPW_R_POSIX
    104 		if (getpwnam_r(temp, &pwres, pwbuf, sizeof(pwbuf), &pass) != 0)
    105 			pass = NULL;
    106 #elif HAVE_GETPW_R_DRAFT
    107 		pass = getpwnam_r(temp, &pwres, pwbuf, sizeof(pwbuf));
    108 #else
    109 		pass = getpwnam(temp);
    110 #endif
    111 	}
    112 	el_free(temp);		/* value no more needed */
    113 	if (pass == NULL)
    114 		return strdup(txt);
    115 
    116 	/* update pointer txt to point at string immedially following */
    117 	/* first slash */
    118 	txt += len;
    119 
    120 	len = strlen(pass->pw_dir) + 1 + strlen(txt) + 1;
    121 	temp = el_calloc(len, sizeof(*temp));
    122 	if (temp == NULL)
    123 		return NULL;
    124 	(void)snprintf(temp, len, "%s/%s", pass->pw_dir, txt);
    125 
    126 	return temp;
    127 }
    128 
    129 static int
    130 needs_escaping(char c)
    131 {
    132 	switch (c) {
    133 	case '\'':
    134 	case '"':
    135 	case '(':
    136 	case ')':
    137 	case '\\':
    138 	case '<':
    139 	case '>':
    140 	case '$':
    141 	case '#':
    142 	case ' ':
    143 	case '\n':
    144 	case '\t':
    145 	case '?':
    146 	case ';':
    147 	case '`':
    148 	case '@':
    149 	case '=':
    150 	case '|':
    151 	case '{':
    152 	case '}':
    153 	case '&':
    154 	case '*':
    155 	case '[':
    156 		return 1;
    157 	default:
    158 		return 0;
    159 	}
    160 }
    161 
    162 static int
    163 needs_dquote_escaping(char c)
    164 {
    165 	switch (c) {
    166 	case '"':
    167 	case '\\':
    168 	case '`':
    169 	case '$':
    170 		return 1;
    171 	default:
    172 		return 0;
    173 	}
    174 }
    175 
    176 
    177 static wchar_t *
    178 unescape_string(const wchar_t *string, size_t length)
    179 {
    180 	size_t i;
    181 	size_t j = 0;
    182 	wchar_t *unescaped = el_calloc(length + 1, sizeof(*string));
    183 	if (unescaped == NULL)
    184 		return NULL;
    185 	for (i = 0; i < length ; i++) {
    186 		if (string[i] == '\\')
    187 			continue;
    188 		unescaped[j++] = string[i];
    189 	}
    190 	unescaped[j] = 0;
    191 	return unescaped;
    192 }
    193 
    194 static char *
    195 escape_filename(EditLine * el, const char *filename, int single_match,
    196 		const char *(*app_func)(const char *))
    197 {
    198 	size_t original_len = 0;
    199 	size_t escaped_character_count = 0;
    200 	size_t offset = 0;
    201 	size_t newlen;
    202 	const char *s;
    203 	char c;
    204 	size_t s_quoted = 0;	/* does the input contain a single quote */
    205 	size_t d_quoted = 0;	/* does the input contain a double quote */
    206 	char *escaped_str;
    207 	wchar_t *temp = el->el_line.buffer;
    208 	const char *append_char = NULL;
    209 
    210 	if (filename == NULL)
    211 		return NULL;
    212 
    213 	while (temp != el->el_line.cursor) {
    214 		/*
    215 		 * If we see a single quote but have not seen a double quote
    216 		 * so far set/unset s_quote, unless it is already quoted
    217 		 */
    218 		if (temp[0] == '\'' && !d_quoted &&
    219 		    (temp == el->el_line.buffer || temp[-1] != '\\'))
    220 			s_quoted = !s_quoted;
    221 		/*
    222 		 * vice versa to the above condition
    223 		 */
    224 		else if (temp[0] == '"' && !s_quoted)
    225 			d_quoted = !d_quoted;
    226 		temp++;
    227 	}
    228 
    229 	/* Count number of special characters so that we can calculate
    230 	 * number of extra bytes needed in the new string
    231 	 */
    232 	for (s = filename; *s; s++, original_len++) {
    233 		c = *s;
    234 		/* Inside a single quote only single quotes need escaping */
    235 		if (s_quoted && c == '\'') {
    236 			escaped_character_count += 3;
    237 			continue;
    238 		}
    239 		/* Inside double quotes only ", \, ` and $ need escaping */
    240 		if (d_quoted && needs_dquote_escaping(c)) {
    241 			escaped_character_count++;
    242 			continue;
    243 		}
    244 		if (!s_quoted && !d_quoted && needs_escaping(c))
    245 			escaped_character_count++;
    246 	}
    247 
    248 	newlen = original_len + escaped_character_count + 1;
    249 	if (s_quoted || d_quoted)
    250 		newlen++;
    251 
    252 	if (single_match && app_func)
    253 		newlen++;
    254 
    255 	if ((escaped_str = el_malloc(newlen)) == NULL)
    256 		return NULL;
    257 
    258 	for (s = filename; *s; s++) {
    259 		c = *s;
    260 		if (!needs_escaping(c)) {
    261 			/* no escaping is required continue as usual */
    262 			escaped_str[offset++] = c;
    263 			continue;
    264 		}
    265 
    266 		/* single quotes inside single quotes require special handling */
    267 		if (c == '\'' && s_quoted) {
    268 			escaped_str[offset++] = '\'';
    269 			escaped_str[offset++] = '\\';
    270 			escaped_str[offset++] = '\'';
    271 			escaped_str[offset++] = '\'';
    272 			continue;
    273 		}
    274 
    275 		/* Otherwise no escaping needed inside single quotes */
    276 		if (s_quoted) {
    277 			escaped_str[offset++] = c;
    278 			continue;
    279 		}
    280 
    281 		/* No escaping needed inside a double quoted string either
    282 		 * unless we see a '$', '\', '`', or '"' (itself)
    283 		 */
    284 		if (d_quoted && !needs_dquote_escaping(c)) {
    285 			escaped_str[offset++] = c;
    286 			continue;
    287 		}
    288 
    289 		/* If we reach here that means escaping is actually needed */
    290 		escaped_str[offset++] = '\\';
    291 		escaped_str[offset++] = c;
    292 	}
    293 
    294 	if (single_match && app_func) {
    295 		escaped_str[offset] = 0;
    296 		append_char = app_func(filename);
    297 		/* we want to append space only if we are not inside quotes */
    298 		if (append_char[0] == ' ') {
    299 			if (!s_quoted && !d_quoted)
    300 				escaped_str[offset++] = append_char[0];
    301 		} else
    302 			escaped_str[offset++] = append_char[0];
    303 	}
    304 
    305 	/* close the quotes if single match and the match is not a directory */
    306 	if (single_match && (append_char && append_char[0] == ' ')) {
    307 		if (s_quoted)
    308 			escaped_str[offset++] = '\'';
    309 		else if (d_quoted)
    310 			escaped_str[offset++] = '"';
    311 	}
    312 
    313 	escaped_str[offset] = 0;
    314 	return escaped_str;
    315 }
    316 
    317 /*
    318  * return first found file name starting by the ``text'' or NULL if no
    319  * such file can be found
    320  * value of ``state'' is ignored
    321  *
    322  * it's the caller's responsibility to free the returned string
    323  */
    324 char *
    325 fn_filename_completion_function(const char *text, int state)
    326 {
    327 	static DIR *dir = NULL;
    328 	static char *filename = NULL, *dirname = NULL, *dirpath = NULL;
    329 	static size_t filename_len = 0;
    330 	struct dirent *entry;
    331 	char *temp;
    332 	const char *pos;
    333 	size_t len;
    334 
    335 	if (state == 0 || dir == NULL) {
    336 		pos = strrchr(text, '/');
    337 		if (pos) {
    338 			char *nptr;
    339 			pos++;
    340 			nptr = el_realloc(filename, (strlen(pos) + 1) *
    341 			    sizeof(*nptr));
    342 			if (nptr == NULL) {
    343 				el_free(filename);
    344 				filename = NULL;
    345 				return NULL;
    346 			}
    347 			filename = nptr;
    348 			(void)strcpy(filename, pos);
    349 			len = (size_t)(pos - text);	/* including last slash */
    350 
    351 			nptr = el_realloc(dirname, (len + 1) *
    352 			    sizeof(*nptr));
    353 			if (nptr == NULL) {
    354 				el_free(dirname);
    355 				dirname = NULL;
    356 				return NULL;
    357 			}
    358 			dirname = nptr;
    359 			(void)strlcpy(dirname, text, len + 1);
    360 		} else {
    361 			el_free(filename);
    362 			if (*text == 0)
    363 				filename = NULL;
    364 			else {
    365 				filename = strdup(text);
    366 				if (filename == NULL)
    367 					return NULL;
    368 			}
    369 			el_free(dirname);
    370 			dirname = NULL;
    371 		}
    372 
    373 		if (dir != NULL) {
    374 			(void)closedir(dir);
    375 			dir = NULL;
    376 		}
    377 
    378 		/* support for ``~user'' syntax */
    379 
    380 		el_free(dirpath);
    381 		dirpath = NULL;
    382 		if (dirname == NULL) {
    383 			if ((dirname = strdup("")) == NULL)
    384 				return NULL;
    385 			dirpath = strdup("./");
    386 		} else if (*dirname == '~')
    387 			dirpath = fn_tilde_expand(dirname);
    388 		else
    389 			dirpath = strdup(dirname);
    390 
    391 		if (dirpath == NULL)
    392 			return NULL;
    393 
    394 		dir = opendir(dirpath);
    395 		if (!dir)
    396 			return NULL;	/* cannot open the directory */
    397 
    398 		/* will be used in cycle */
    399 		filename_len = filename ? strlen(filename) : 0;
    400 	}
    401 
    402 	/* find the match */
    403 	while ((entry = readdir(dir)) != NULL) {
    404 		/* skip . and .. */
    405 		if (entry->d_name[0] == '.' && (!entry->d_name[1]
    406 		    || (entry->d_name[1] == '.' && !entry->d_name[2])))
    407 			continue;
    408 		if (filename_len == 0)
    409 			break;
    410 		/* otherwise, get first entry where first */
    411 		/* filename_len characters are equal	  */
    412 		if (entry->d_name[0] == filename[0]
    413 #if HAVE_STRUCT_DIRENT_D_NAMLEN
    414 		    && entry->d_namlen >= filename_len
    415 #else
    416 		    && strlen(entry->d_name) >= filename_len
    417 #endif
    418 		    && strncmp(entry->d_name, filename,
    419 			filename_len) == 0)
    420 			break;
    421 	}
    422 
    423 	if (entry) {		/* match found */
    424 
    425 #if HAVE_STRUCT_DIRENT_D_NAMLEN
    426 		len = entry->d_namlen;
    427 #else
    428 		len = strlen(entry->d_name);
    429 #endif
    430 
    431 		len = strlen(dirname) + len + 1;
    432 		temp = el_calloc(len, sizeof(*temp));
    433 		if (temp == NULL)
    434 			return NULL;
    435 		(void)snprintf(temp, len, "%s%s", dirname, entry->d_name);
    436 	} else {
    437 		(void)closedir(dir);
    438 		dir = NULL;
    439 		temp = NULL;
    440 	}
    441 
    442 	return temp;
    443 }
    444 
    445 
    446 static const char *
    447 append_char_function(const char *name)
    448 {
    449 	struct stat stbuf;
    450 	char *expname = *name == '~' ? fn_tilde_expand(name) : NULL;
    451 	const char *rs = " ";
    452 
    453 	if (stat(expname ? expname : name, &stbuf) == -1)
    454 		goto out;
    455 	if (S_ISDIR(stbuf.st_mode))
    456 		rs = "/";
    457 out:
    458 	if (expname)
    459 		el_free(expname);
    460 	return rs;
    461 }
    462 /*
    463  * returns list of completions for text given
    464  * non-static for readline.
    465  */
    466 char ** completion_matches(const char *, char *(*)(const char *, int));
    467 char **
    468 completion_matches(const char *text, char *(*genfunc)(const char *, int))
    469 {
    470 	char **match_list = NULL, *retstr, *prevstr;
    471 	size_t match_list_len, max_equal, which, i;
    472 	size_t matches;
    473 
    474 	matches = 0;
    475 	match_list_len = 1;
    476 	while ((retstr = (*genfunc) (text, (int)matches)) != NULL) {
    477 		/* allow for list terminator here */
    478 		if (matches + 3 >= match_list_len) {
    479 			char **nmatch_list;
    480 			while (matches + 3 >= match_list_len)
    481 				match_list_len <<= 1;
    482 			nmatch_list = el_realloc(match_list,
    483 			    match_list_len * sizeof(*nmatch_list));
    484 			if (nmatch_list == NULL) {
    485 				el_free(match_list);
    486 				return NULL;
    487 			}
    488 			match_list = nmatch_list;
    489 
    490 		}
    491 		match_list[++matches] = retstr;
    492 	}
    493 
    494 	if (!match_list)
    495 		return NULL;	/* nothing found */
    496 
    497 	/* find least denominator and insert it to match_list[0] */
    498 	which = 2;
    499 	prevstr = match_list[1];
    500 	max_equal = strlen(prevstr);
    501 	for (; which <= matches; which++) {
    502 		for (i = 0; i < max_equal &&
    503 		    prevstr[i] == match_list[which][i]; i++)
    504 			continue;
    505 		max_equal = i;
    506 	}
    507 
    508 	retstr = el_calloc(max_equal + 1, sizeof(*retstr));
    509 	if (retstr == NULL) {
    510 		el_free(match_list);
    511 		return NULL;
    512 	}
    513 	(void)strlcpy(retstr, match_list[1], max_equal + 1);
    514 	match_list[0] = retstr;
    515 
    516 	/* add NULL as last pointer to the array */
    517 	match_list[matches + 1] = NULL;
    518 
    519 	return match_list;
    520 }
    521 
    522 /*
    523  * Sort function for qsort(). Just wrapper around strcasecmp().
    524  */
    525 static int
    526 _fn_qsort_string_compare(const void *i1, const void *i2)
    527 {
    528 	const char *s1 = ((const char * const *)i1)[0];
    529 	const char *s2 = ((const char * const *)i2)[0];
    530 
    531 	return strcasecmp(s1, s2);
    532 }
    533 
    534 /*
    535  * Display list of strings in columnar format on readline's output stream.
    536  * 'matches' is list of strings, 'num' is number of strings in 'matches',
    537  * 'width' is maximum length of string in 'matches'.
    538  *
    539  * matches[0] is not one of the match strings, but it is counted in
    540  * num, so the strings are matches[1] *through* matches[num-1].
    541  */
    542 void
    543 fn_display_match_list(EditLine * el, char **matches, size_t num, size_t width,
    544     const char *(*app_func) (const char *))
    545 {
    546 	size_t line, lines, col, cols, thisguy;
    547 	int screenwidth = el->el_terminal.t_size.h;
    548 	if (app_func == NULL)
    549 		app_func = append_char_function;
    550 
    551 	/* Ignore matches[0]. Avoid 1-based array logic below. */
    552 	matches++;
    553 	num--;
    554 
    555 	/*
    556 	 * Find out how many entries can be put on one line; count
    557 	 * with one space between strings the same way it's printed.
    558 	 */
    559 	cols = (size_t)screenwidth / (width + 2);
    560 	if (cols == 0)
    561 		cols = 1;
    562 
    563 	/* how many lines of output, rounded up */
    564 	lines = (num + cols - 1) / cols;
    565 
    566 	/* Sort the items. */
    567 	qsort(matches, num, sizeof(char *), _fn_qsort_string_compare);
    568 
    569 	/*
    570 	 * On the ith line print elements i, i+lines, i+lines*2, etc.
    571 	 */
    572 	for (line = 0; line < lines; line++) {
    573 		for (col = 0; col < cols; col++) {
    574 			thisguy = line + col * lines;
    575 			if (thisguy >= num)
    576 				break;
    577 			(void)fprintf(el->el_outfile, "%s%s%s",
    578 			    col == 0 ? "" : " ", matches[thisguy],
    579 				(*app_func)(matches[thisguy]));
    580 			(void)fprintf(el->el_outfile, "%-*s",
    581 				(int) (width - strlen(matches[thisguy])), "");
    582 		}
    583 		(void)fprintf(el->el_outfile, "\n");
    584 	}
    585 }
    586 
    587 static wchar_t *
    588 find_word_to_complete(const wchar_t * cursor, const wchar_t * buffer,
    589     const wchar_t * word_break, const wchar_t * special_prefixes, size_t * length,
    590 	int do_unescape)
    591 {
    592 	/* We now look backwards for the start of a filename/variable word */
    593 	const wchar_t *ctemp = cursor;
    594 	wchar_t *temp;
    595 	size_t len;
    596 
    597 	/* if the cursor is placed at a slash or a quote, we need to find the
    598 	 * word before it
    599 	 */
    600 	if (ctemp > buffer) {
    601 		switch (ctemp[-1]) {
    602 		case '\\':
    603 		case '\'':
    604 		case '"':
    605 			ctemp--;
    606 			break;
    607 		default:
    608 			break;
    609 		}
    610 	}
    611 
    612 	for (;;) {
    613 		if (ctemp <= buffer)
    614 			break;
    615 		if (wcschr(word_break, ctemp[-1])) {
    616 			if (ctemp - buffer >= 2 && ctemp[-2] == '\\') {
    617 				ctemp -= 2;
    618 				continue;
    619 			}
    620 			break;
    621 		}
    622 		if (special_prefixes && wcschr(special_prefixes, ctemp[-1]))
    623 			break;
    624 		ctemp--;
    625 	}
    626 
    627 	len = (size_t) (cursor - ctemp);
    628 	if (len == 1 && (ctemp[0] == '\'' || ctemp[0] == '"')) {
    629 		len = 0;
    630 		ctemp++;
    631 	}
    632 	*length = len;
    633 	if (do_unescape) {
    634 		wchar_t *unescaped_word = unescape_string(ctemp, len);
    635 		if (unescaped_word == NULL)
    636 			return NULL;
    637 		return unescaped_word;
    638 	}
    639 	temp = el_malloc((len + 1) * sizeof(*temp));
    640 	(void) wcsncpy(temp, ctemp, len);
    641 	temp[len] = '\0';
    642 	return temp;
    643 }
    644 
    645 /*
    646  * Complete the word at or before point,
    647  * 'what_to_do' says what to do with the completion.
    648  * \t   means do standard completion.
    649  * `?' means list the possible completions.
    650  * `*' means insert all of the possible completions.
    651  * `!' means to do standard completion, and list all possible completions if
    652  * there is more than one.
    653  *
    654  * Note: '*' support is not implemented
    655  *       '!' could never be invoked
    656  */
    657 int
    658 fn_complete2(EditLine *el,
    659     char *(*complete_func)(const char *, int),
    660     char **(*attempted_completion_function)(const char *, int, int),
    661     const wchar_t *word_break, const wchar_t *special_prefixes,
    662     const char *(*app_func)(const char *), size_t query_items,
    663     int *completion_type, int *over, int *point, int *end,
    664     unsigned int flags)
    665 {
    666 	const LineInfoW *li;
    667 	wchar_t *temp;
    668 	char **matches;
    669 	char *completion;
    670 	size_t len;
    671 	int what_to_do = '\t';
    672 	int retval = CC_NORM;
    673 	int do_unescape = flags & FN_QUOTE_MATCH;
    674 
    675 	if (el->el_state.lastcmd == el->el_state.thiscmd)
    676 		what_to_do = '?';
    677 
    678 	/* readline's rl_complete() has to be told what we did... */
    679 	if (completion_type != NULL)
    680 		*completion_type = what_to_do;
    681 
    682 	if (!complete_func)
    683 		complete_func = fn_filename_completion_function;
    684 	if (!app_func)
    685 		app_func = append_char_function;
    686 
    687 	li = el_wline(el);
    688 	temp = find_word_to_complete(li->cursor,
    689 	    li->buffer, word_break, special_prefixes, &len, do_unescape);
    690 	if (temp == NULL)
    691 		goto out;
    692 
    693 	/* these can be used by function called in completion_matches() */
    694 	/* or (*attempted_completion_function)() */
    695 	if (point != NULL)
    696 		*point = (int)(li->cursor - li->buffer);
    697 	if (end != NULL)
    698 		*end = (int)(li->lastchar - li->buffer);
    699 
    700 	if (attempted_completion_function) {
    701 		int cur_off = (int)(li->cursor - li->buffer);
    702 		matches = (*attempted_completion_function)(
    703 		    ct_encode_string(temp, &el->el_scratch),
    704 		    cur_off - (int)len, cur_off);
    705 	} else
    706 		matches = NULL;
    707 	if (!attempted_completion_function ||
    708 	    (over != NULL && !*over && !matches))
    709 		matches = completion_matches(
    710 		    ct_encode_string(temp, &el->el_scratch), complete_func);
    711 
    712 	if (over != NULL)
    713 		*over = 0;
    714 
    715 	if (matches == NULL) {
    716 		goto out;
    717 	}
    718 	int i;
    719 	size_t matches_num, maxlen, match_len, match_display=1;
    720 	int single_match = matches[2] == NULL &&
    721 		(matches[1] == NULL || strcmp(matches[0], matches[1]) == 0);
    722 
    723 	retval = CC_REFRESH;
    724 
    725 	if (matches[0][0] != '\0') {
    726 		el_deletestr(el, (int)len);
    727 		if (flags & FN_QUOTE_MATCH)
    728 			completion = escape_filename(el, matches[0],
    729 			    single_match, app_func);
    730 		else
    731 			completion = strdup(matches[0]);
    732 		if (completion == NULL)
    733 			goto out2;
    734 
    735 		/*
    736 		 * Replace the completed string with the common part of
    737 		 * all possible matches if there is a possible completion.
    738 		 */
    739 		el_winsertstr(el,
    740 		    ct_decode_string(completion, &el->el_scratch));
    741 
    742 		if (single_match && attempted_completion_function &&
    743 		    !(flags & FN_QUOTE_MATCH))
    744 		{
    745 			/*
    746 			 * We found an exact match. Add a space after
    747 			 * it, unless we do filename completion and the
    748 			 * object is a directory. Also do necessary
    749 			 * escape quoting
    750 			 */
    751 			el_winsertstr(el, ct_decode_string(
    752 			    (*app_func)(completion), &el->el_scratch));
    753 		}
    754 		free(completion);
    755 	}
    756 
    757 
    758 	if (!single_match && (what_to_do == '!' || what_to_do == '?')) {
    759 		/*
    760 		 * More than one match and requested to list possible
    761 		 * matches.
    762 		 */
    763 
    764 		for(i = 1, maxlen = 0; matches[i]; i++) {
    765 			match_len = strlen(matches[i]);
    766 			if (match_len > maxlen)
    767 				maxlen = match_len;
    768 		}
    769 		/* matches[1] through matches[i-1] are available */
    770 		matches_num = (size_t)(i - 1);
    771 
    772 		/* newline to get on next line from command line */
    773 		(void)fprintf(el->el_outfile, "\n");
    774 
    775 		/*
    776 		 * If there are too many items, ask user for display
    777 		 * confirmation.
    778 		 */
    779 		if (matches_num > query_items) {
    780 			(void)fprintf(el->el_outfile,
    781 			    "Display all %zu possibilities? (y or n) ",
    782 			    matches_num);
    783 			(void)fflush(el->el_outfile);
    784 			if (getc(stdin) != 'y')
    785 				match_display = 0;
    786 			(void)fprintf(el->el_outfile, "\n");
    787 		}
    788 
    789 		if (match_display) {
    790 			/*
    791 			 * Interface of this function requires the
    792 			 * strings be matches[1..num-1] for compat.
    793 			 * We have matches_num strings not counting
    794 			 * the prefix in matches[0], so we need to
    795 			 * add 1 to matches_num for the call.
    796 			 */
    797 			fn_display_match_list(el, matches,
    798 			    matches_num+1, maxlen, app_func);
    799 		}
    800 		retval = CC_REDISPLAY;
    801 	} else if (matches[0][0]) {
    802 		/*
    803 		 * There was some common match, but the name was
    804 		 * not complete enough. Next tab will print possible
    805 		 * completions.
    806 		 */
    807 		el_beep(el);
    808 	} else {
    809 		/* lcd is not a valid object - further specification */
    810 		/* is needed */
    811 		el_beep(el);
    812 		retval = CC_NORM;
    813 	}
    814 
    815 	/* free elements of array and the array itself */
    816 out2:
    817 	for (i = 0; matches[i]; i++)
    818 		el_free(matches[i]);
    819 	el_free(matches);
    820 	matches = NULL;
    821 
    822 out:
    823 	el_free(temp);
    824 	return retval;
    825 }
    826 
    827 int
    828 fn_complete(EditLine *el,
    829     char *(*complete_func)(const char *, int),
    830     char **(*attempted_completion_function)(const char *, int, int),
    831     const wchar_t *word_break, const wchar_t *special_prefixes,
    832     const char *(*app_func)(const char *), size_t query_items,
    833     int *completion_type, int *over, int *point, int *end)
    834 {
    835 	return fn_complete2(el, complete_func, attempted_completion_function,
    836 	    word_break, special_prefixes, app_func, query_items,
    837 	    completion_type, over, point, end,
    838 	    attempted_completion_function ? 0 : FN_QUOTE_MATCH);
    839 }
    840 
    841 /*
    842  * el-compatible wrapper around rl_complete; needed for key binding
    843  */
    844 /* ARGSUSED */
    845 unsigned char
    846 _el_fn_complete(EditLine *el, int ch __attribute__((__unused__)))
    847 {
    848 	return (unsigned char)fn_complete(el, NULL, NULL,
    849 	    break_chars, NULL, NULL, (size_t)100,
    850 	    NULL, NULL, NULL, NULL);
    851 }
    852