xref: /freebsd/contrib/libedit/filecomplete.c (revision 43a5ec4eb41567cc92586503212743d89686d78f)
1 /*	$NetBSD: filecomplete.c,v 1.68 2021/05/05 14:49:59 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.68 2021/05/05 14:49:59 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 - 1);
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(filename);
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 + 1);
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 completion_matches(const char *text, char *(*genfunc)(const char *, int))
466 {
467 	char **match_list = NULL, *retstr, *prevstr;
468 	size_t match_list_len, max_equal, which, i;
469 	size_t matches;
470 
471 	matches = 0;
472 	match_list_len = 1;
473 	while ((retstr = (*genfunc) (text, (int)matches)) != NULL) {
474 		/* allow for list terminator here */
475 		if (matches + 3 >= match_list_len) {
476 			char **nmatch_list;
477 			while (matches + 3 >= match_list_len)
478 				match_list_len <<= 1;
479 			nmatch_list = el_realloc(match_list,
480 			    match_list_len * sizeof(*nmatch_list));
481 			if (nmatch_list == NULL) {
482 				el_free(match_list);
483 				return NULL;
484 			}
485 			match_list = nmatch_list;
486 
487 		}
488 		match_list[++matches] = retstr;
489 	}
490 
491 	if (!match_list)
492 		return NULL;	/* nothing found */
493 
494 	/* find least denominator and insert it to match_list[0] */
495 	which = 2;
496 	prevstr = match_list[1];
497 	max_equal = strlen(prevstr);
498 	for (; which <= matches; which++) {
499 		for (i = 0; i < max_equal &&
500 		    prevstr[i] == match_list[which][i]; i++)
501 			continue;
502 		max_equal = i;
503 	}
504 
505 	retstr = el_calloc(max_equal + 1, sizeof(*retstr));
506 	if (retstr == NULL) {
507 		el_free(match_list);
508 		return NULL;
509 	}
510 	(void)strlcpy(retstr, match_list[1], max_equal + 1);
511 	match_list[0] = retstr;
512 
513 	/* add NULL as last pointer to the array */
514 	match_list[matches + 1] = NULL;
515 
516 	return match_list;
517 }
518 
519 /*
520  * Sort function for qsort(). Just wrapper around strcasecmp().
521  */
522 static int
523 _fn_qsort_string_compare(const void *i1, const void *i2)
524 {
525 	const char *s1 = ((const char * const *)i1)[0];
526 	const char *s2 = ((const char * const *)i2)[0];
527 
528 	return strcasecmp(s1, s2);
529 }
530 
531 /*
532  * Display list of strings in columnar format on readline's output stream.
533  * 'matches' is list of strings, 'num' is number of strings in 'matches',
534  * 'width' is maximum length of string in 'matches'.
535  *
536  * matches[0] is not one of the match strings, but it is counted in
537  * num, so the strings are matches[1] *through* matches[num-1].
538  */
539 void
540 fn_display_match_list(EditLine * el, char **matches, size_t num, size_t width,
541     const char *(*app_func) (const char *))
542 {
543 	size_t line, lines, col, cols, thisguy;
544 	int screenwidth = el->el_terminal.t_size.h;
545 	if (app_func == NULL)
546 		app_func = append_char_function;
547 
548 	/* Ignore matches[0]. Avoid 1-based array logic below. */
549 	matches++;
550 	num--;
551 
552 	/*
553 	 * Find out how many entries can be put on one line; count
554 	 * with one space between strings the same way it's printed.
555 	 */
556 	cols = (size_t)screenwidth / (width + 2);
557 	if (cols == 0)
558 		cols = 1;
559 
560 	/* how many lines of output, rounded up */
561 	lines = (num + cols - 1) / cols;
562 
563 	/* Sort the items. */
564 	qsort(matches, num, sizeof(char *), _fn_qsort_string_compare);
565 
566 	/*
567 	 * On the ith line print elements i, i+lines, i+lines*2, etc.
568 	 */
569 	for (line = 0; line < lines; line++) {
570 		for (col = 0; col < cols; col++) {
571 			thisguy = line + col * lines;
572 			if (thisguy >= num)
573 				break;
574 			(void)fprintf(el->el_outfile, "%s%s%s",
575 			    col == 0 ? "" : " ", matches[thisguy],
576 				(*app_func)(matches[thisguy]));
577 			(void)fprintf(el->el_outfile, "%-*s",
578 				(int) (width - strlen(matches[thisguy])), "");
579 		}
580 		(void)fprintf(el->el_outfile, "\n");
581 	}
582 }
583 
584 static wchar_t *
585 find_word_to_complete(const wchar_t * cursor, const wchar_t * buffer,
586     const wchar_t * word_break, const wchar_t * special_prefixes, size_t * length,
587 	int do_unescape)
588 {
589 	/* We now look backwards for the start of a filename/variable word */
590 	const wchar_t *ctemp = cursor;
591 	wchar_t *temp;
592 	size_t len;
593 
594 	/* if the cursor is placed at a slash or a quote, we need to find the
595 	 * word before it
596 	 */
597 	if (ctemp > buffer) {
598 		switch (ctemp[-1]) {
599 		case '\\':
600 		case '\'':
601 		case '"':
602 			ctemp--;
603 			break;
604 		default:
605 			break;
606 		}
607 	}
608 
609 	for (;;) {
610 		if (ctemp <= buffer)
611 			break;
612 		if (wcschr(word_break, ctemp[-1])) {
613 			if (ctemp - buffer >= 2 && ctemp[-2] == '\\') {
614 				ctemp -= 2;
615 				continue;
616 			}
617 			break;
618 		}
619 		if (special_prefixes && wcschr(special_prefixes, ctemp[-1]))
620 			break;
621 		ctemp--;
622 	}
623 
624 	len = (size_t) (cursor - ctemp);
625 	if (len == 1 && (ctemp[0] == '\'' || ctemp[0] == '"')) {
626 		len = 0;
627 		ctemp++;
628 	}
629 	*length = len;
630 	if (do_unescape) {
631 		wchar_t *unescaped_word = unescape_string(ctemp, len);
632 		if (unescaped_word == NULL)
633 			return NULL;
634 		return unescaped_word;
635 	}
636 	temp = el_malloc((len + 1) * sizeof(*temp));
637 	(void) wcsncpy(temp, ctemp, len);
638 	temp[len] = '\0';
639 	return temp;
640 }
641 
642 /*
643  * Complete the word at or before point,
644  * 'what_to_do' says what to do with the completion.
645  * \t   means do standard completion.
646  * `?' means list the possible completions.
647  * `*' means insert all of the possible completions.
648  * `!' means to do standard completion, and list all possible completions if
649  * there is more than one.
650  *
651  * Note: '*' support is not implemented
652  *       '!' could never be invoked
653  */
654 int
655 fn_complete2(EditLine *el,
656     char *(*complete_func)(const char *, int),
657     char **(*attempted_completion_function)(const char *, int, int),
658     const wchar_t *word_break, const wchar_t *special_prefixes,
659     const char *(*app_func)(const char *), size_t query_items,
660     int *completion_type, int *over, int *point, int *end,
661     unsigned int flags)
662 {
663 	const LineInfoW *li;
664 	wchar_t *temp;
665 	char **matches;
666 	char *completion;
667 	size_t len;
668 	int what_to_do = '\t';
669 	int retval = CC_NORM;
670 	int do_unescape = flags & FN_QUOTE_MATCH;
671 
672 	if (el->el_state.lastcmd == el->el_state.thiscmd)
673 		what_to_do = '?';
674 
675 	/* readline's rl_complete() has to be told what we did... */
676 	if (completion_type != NULL)
677 		*completion_type = what_to_do;
678 
679 	if (!complete_func)
680 		complete_func = fn_filename_completion_function;
681 	if (!app_func)
682 		app_func = append_char_function;
683 
684 	li = el_wline(el);
685 	temp = find_word_to_complete(li->cursor,
686 	    li->buffer, word_break, special_prefixes, &len, do_unescape);
687 	if (temp == NULL)
688 		goto out;
689 
690 	/* these can be used by function called in completion_matches() */
691 	/* or (*attempted_completion_function)() */
692 	if (point != NULL)
693 		*point = (int)(li->cursor - li->buffer);
694 	if (end != NULL)
695 		*end = (int)(li->lastchar - li->buffer);
696 
697 	if (attempted_completion_function) {
698 		int cur_off = (int)(li->cursor - li->buffer);
699 		matches = (*attempted_completion_function)(
700 		    ct_encode_string(temp, &el->el_scratch),
701 		    cur_off - (int)len, cur_off);
702 	} else
703 		matches = NULL;
704 	if (!attempted_completion_function ||
705 	    (over != NULL && !*over && !matches))
706 		matches = completion_matches(
707 		    ct_encode_string(temp, &el->el_scratch), complete_func);
708 
709 	if (over != NULL)
710 		*over = 0;
711 
712 	if (matches == NULL) {
713 		goto out;
714 	}
715 	int i;
716 	size_t matches_num, maxlen, match_len, match_display=1;
717 	int single_match = matches[2] == NULL &&
718 		(matches[1] == NULL || strcmp(matches[0], matches[1]) == 0);
719 
720 	retval = CC_REFRESH;
721 
722 	if (matches[0][0] != '\0') {
723 		el_deletestr(el, (int)len);
724 		if (flags & FN_QUOTE_MATCH)
725 			completion = escape_filename(el, matches[0],
726 			    single_match, app_func);
727 		else
728 			completion = strdup(matches[0]);
729 		if (completion == NULL)
730 			goto out2;
731 
732 		/*
733 		 * Replace the completed string with the common part of
734 		 * all possible matches if there is a possible completion.
735 		 */
736 		el_winsertstr(el,
737 		    ct_decode_string(completion, &el->el_scratch));
738 
739 		if (single_match && attempted_completion_function &&
740 		    !(flags & FN_QUOTE_MATCH))
741 		{
742 			/*
743 			 * We found an exact match. Add a space after
744 			 * it, unless we do filename completion and the
745 			 * object is a directory. Also do necessary
746 			 * escape quoting
747 			 */
748 			el_winsertstr(el, ct_decode_string(
749 			    (*app_func)(completion), &el->el_scratch));
750 		}
751 		free(completion);
752 	}
753 
754 
755 	if (!single_match && (what_to_do == '!' || what_to_do == '?')) {
756 		/*
757 		 * More than one match and requested to list possible
758 		 * matches.
759 		 */
760 
761 		for(i = 1, maxlen = 0; matches[i]; i++) {
762 			match_len = strlen(matches[i]);
763 			if (match_len > maxlen)
764 				maxlen = match_len;
765 		}
766 		/* matches[1] through matches[i-1] are available */
767 		matches_num = (size_t)(i - 1);
768 
769 		/* newline to get on next line from command line */
770 		(void)fprintf(el->el_outfile, "\n");
771 
772 		/*
773 		 * If there are too many items, ask user for display
774 		 * confirmation.
775 		 */
776 		if (matches_num > query_items) {
777 			(void)fprintf(el->el_outfile,
778 			    "Display all %zu possibilities? (y or n) ",
779 			    matches_num);
780 			(void)fflush(el->el_outfile);
781 			if (getc(stdin) != 'y')
782 				match_display = 0;
783 			(void)fprintf(el->el_outfile, "\n");
784 		}
785 
786 		if (match_display) {
787 			/*
788 			 * Interface of this function requires the
789 			 * strings be matches[1..num-1] for compat.
790 			 * We have matches_num strings not counting
791 			 * the prefix in matches[0], so we need to
792 			 * add 1 to matches_num for the call.
793 			 */
794 			fn_display_match_list(el, matches,
795 			    matches_num+1, maxlen, app_func);
796 		}
797 		retval = CC_REDISPLAY;
798 	} else if (matches[0][0]) {
799 		/*
800 		 * There was some common match, but the name was
801 		 * not complete enough. Next tab will print possible
802 		 * completions.
803 		 */
804 		el_beep(el);
805 	} else {
806 		/* lcd is not a valid object - further specification */
807 		/* is needed */
808 		el_beep(el);
809 		retval = CC_NORM;
810 	}
811 
812 	/* free elements of array and the array itself */
813 out2:
814 	for (i = 0; matches[i]; i++)
815 		el_free(matches[i]);
816 	el_free(matches);
817 	matches = NULL;
818 
819 out:
820 	el_free(temp);
821 	return retval;
822 }
823 
824 int
825 fn_complete(EditLine *el,
826     char *(*complete_func)(const char *, int),
827     char **(*attempted_completion_function)(const char *, int, int),
828     const wchar_t *word_break, const wchar_t *special_prefixes,
829     const char *(*app_func)(const char *), size_t query_items,
830     int *completion_type, int *over, int *point, int *end)
831 {
832 	return fn_complete2(el, complete_func, attempted_completion_function,
833 	    word_break, special_prefixes, app_func, query_items,
834 	    completion_type, over, point, end,
835 	    attempted_completion_function ? 0 : FN_QUOTE_MATCH);
836 }
837 
838 /*
839  * el-compatible wrapper around rl_complete; needed for key binding
840  */
841 /* ARGSUSED */
842 unsigned char
843 _el_fn_complete(EditLine *el, int ch __attribute__((__unused__)))
844 {
845 	return (unsigned char)fn_complete(el, NULL, NULL,
846 	    break_chars, NULL, NULL, (size_t)100,
847 	    NULL, NULL, NULL, NULL);
848 }
849 
850 /*
851  * el-compatible wrapper around rl_complete; needed for key binding
852  */
853 /* ARGSUSED */
854 unsigned char
855 _el_fn_sh_complete(EditLine *el, int ch)
856 {
857 	return _el_fn_complete(el, ch);
858 }
859