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