1 /* $NetBSD: filecomplete.c,v 1.67 2021/03/28 13:39:39 christos Exp $ */
4 * Copyright (c) 1997 The NetBSD Foundation, Inc.
7 * This code is derived from software contributed to The NetBSD Foundation
10 * Redistribution and use in source and binary forms, with or without
11 * modification, are permitted provided that the following conditions
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.
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.
33 #if !defined(lint) && !defined(SCCSID)
34 __RCSID("$NetBSD: filecomplete.c,v 1.67 2021/03/28 13:39:39 christos Exp $");
35 #endif /* not lint && not SCCSID */
37 #include <sys/types.h>
50 #include "filecomplete.h"
52 static const wchar_t break_chars[] = L" \t\n\"\\'`@$><=;|&{(";
54 /********************************/
55 /* completion functions */
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''
62 * it's the caller's responsibility to free() the returned string
65 fn_tilde_expand(const char *txt)
67 #if defined(HAVE_GETPW_R_POSIX) || defined(HAVE_GETPW_R_DRAFT)
78 temp = strchr(txt + 1, '/');
80 temp = strdup(txt + 1);
84 /* text until string after slash */
85 len = (size_t)(temp - txt + 1);
86 temp = el_calloc(len, sizeof(*temp));
89 (void)strlcpy(temp, txt + 1, len - 1);
92 #ifdef HAVE_GETPW_R_POSIX
93 if (getpwuid_r(getuid(), &pwres, pwbuf, sizeof(pwbuf),
96 #elif HAVE_GETPW_R_DRAFT
97 pass = getpwuid_r(getuid(), &pwres, pwbuf, sizeof(pwbuf));
99 pass = getpwuid(getuid());
102 #ifdef HAVE_GETPW_R_POSIX
103 if (getpwnam_r(temp, &pwres, pwbuf, sizeof(pwbuf), &pass) != 0)
105 #elif HAVE_GETPW_R_DRAFT
106 pass = getpwnam_r(temp, &pwres, pwbuf, sizeof(pwbuf));
108 pass = getpwnam(temp);
111 el_free(temp); /* value no more needed */
115 /* update pointer txt to point at string immedially following */
119 len = strlen(pass->pw_dir) + 1 + strlen(txt) + 1;
120 temp = el_calloc(len, sizeof(*temp));
123 (void)snprintf(temp, len, "%s/%s", pass->pw_dir, txt);
129 needs_escaping(char c)
162 needs_dquote_escaping(char c)
177 unescape_string(const wchar_t *string, size_t length)
181 wchar_t *unescaped = el_calloc(length + 1, sizeof(*string));
182 if (unescaped == NULL)
184 for (i = 0; i < length ; i++) {
185 if (string[i] == '\\')
187 unescaped[j++] = string[i];
194 escape_filename(EditLine * el, const char *filename, int single_match,
195 const char *(*app_func)(const char *))
197 size_t original_len = 0;
198 size_t escaped_character_count = 0;
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 */
206 wchar_t *temp = el->el_line.buffer;
207 const char *append_char = NULL;
209 if (filename == NULL)
212 while (temp != el->el_line.cursor) {
214 * If we see a single quote but have not seen a double quote
215 * so far set/unset s_quote
217 if (temp[0] == '\'' && !d_quoted)
218 s_quoted = !s_quoted;
220 * vice versa to the above condition
222 else if (temp[0] == '"' && !s_quoted)
223 d_quoted = !d_quoted;
227 /* Count number of special characters so that we can calculate
228 * number of extra bytes needed in the new string
230 for (s = filename; *s; s++, original_len++) {
232 /* Inside a single quote only single quotes need escaping */
233 if (s_quoted && c == '\'') {
234 escaped_character_count += 3;
237 /* Inside double quotes only ", \, ` and $ need escaping */
238 if (d_quoted && needs_dquote_escaping(c)) {
239 escaped_character_count++;
242 if (!s_quoted && !d_quoted && needs_escaping(c))
243 escaped_character_count++;
246 newlen = original_len + escaped_character_count + 1;
247 if (s_quoted || d_quoted)
250 if (single_match && app_func)
253 if ((escaped_str = el_malloc(newlen)) == NULL)
256 for (s = filename; *s; s++) {
258 if (!needs_escaping(c)) {
259 /* no escaping is required continue as usual */
260 escaped_str[offset++] = c;
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++] = '\'';
273 /* Otherwise no escaping needed inside single quotes */
275 escaped_str[offset++] = c;
279 /* No escaping needed inside a double quoted string either
280 * unless we see a '$', '\', '`', or '"' (itself)
282 if (d_quoted && !needs_dquote_escaping(c)) {
283 escaped_str[offset++] = c;
287 /* If we reach here that means escaping is actually needed */
288 escaped_str[offset++] = '\\';
289 escaped_str[offset++] = c;
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];
300 escaped_str[offset++] = append_char[0];
303 /* close the quotes if single match and the match is not a directory */
304 if (single_match && (append_char && append_char[0] == ' ')) {
306 escaped_str[offset++] = '\'';
308 escaped_str[offset++] = '"';
311 escaped_str[offset] = 0;
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
320 * it's the caller's responsibility to free the returned string
323 fn_filename_completion_function(const char *text, int state)
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;
332 if (state == 0 || dir == NULL) {
333 temp = strrchr(text, '/');
337 nptr = el_realloc(filename, (strlen(temp) + 1) *
345 (void)strcpy(filename, temp);
346 len = (size_t)(temp - text); /* including last slash */
348 nptr = el_realloc(dirname, (len + 1) *
356 (void)strlcpy(dirname, text, len + 1);
362 filename = strdup(text);
363 if (filename == NULL)
375 /* support for ``~user'' syntax */
379 if (dirname == NULL) {
380 if ((dirname = strdup("")) == NULL)
382 dirpath = strdup("./");
383 } else if (*dirname == '~')
384 dirpath = fn_tilde_expand(dirname);
386 dirpath = strdup(dirname);
391 dir = opendir(dirpath);
393 return NULL; /* cannot open the directory */
395 /* will be used in cycle */
396 filename_len = filename ? strlen(filename) : 0;
400 while ((entry = readdir(dir)) != NULL) {
402 if (entry->d_name[0] == '.' && (!entry->d_name[1]
403 || (entry->d_name[1] == '.' && !entry->d_name[2])))
405 if (filename_len == 0)
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
413 && strlen(entry->d_name) >= filename_len
415 && strncmp(entry->d_name, filename,
420 if (entry) { /* match found */
422 #if HAVE_STRUCT_DIRENT_D_NAMLEN
423 len = entry->d_namlen;
425 len = strlen(entry->d_name);
428 len = strlen(dirname) + len + 1;
429 temp = el_calloc(len, sizeof(*temp));
432 (void)snprintf(temp, len, "%s%s", dirname, entry->d_name);
444 append_char_function(const char *name)
447 char *expname = *name == '~' ? fn_tilde_expand(name) : NULL;
448 const char *rs = " ";
450 if (stat(expname ? expname : name, &stbuf) == -1)
452 if (S_ISDIR(stbuf.st_mode))
460 * returns list of completions for text given
461 * non-static for readline.
463 char ** completion_matches(const char *, char *(*)(const char *, int));
465 completion_matches(const char *text, char *(*genfunc)(const char *, int))
467 char **match_list = NULL, *retstr, *prevstr;
468 size_t match_list_len, max_equal, which, i;
473 while ((retstr = (*genfunc) (text, (int)matches)) != NULL) {
474 /* allow for list terminator here */
475 if (matches + 3 >= match_list_len) {
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) {
485 match_list = nmatch_list;
488 match_list[++matches] = retstr;
492 return NULL; /* nothing found */
494 /* find least denominator and insert it to match_list[0] */
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++)
505 retstr = el_calloc(max_equal + 1, sizeof(*retstr));
506 if (retstr == NULL) {
510 (void)strlcpy(retstr, match_list[1], max_equal + 1);
511 match_list[0] = retstr;
513 /* add NULL as last pointer to the array */
514 match_list[matches + 1] = NULL;
520 * Sort function for qsort(). Just wrapper around strcasecmp().
523 _fn_qsort_string_compare(const void *i1, const void *i2)
525 const char *s1 = ((const char * const *)i1)[0];
526 const char *s2 = ((const char * const *)i2)[0];
528 return strcasecmp(s1, s2);
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'.
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].
540 fn_display_match_list(EditLine * el, char **matches, size_t num, size_t width,
541 const char *(*app_func) (const char *))
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;
548 /* Ignore matches[0]. Avoid 1-based array logic below. */
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.
556 cols = (size_t)screenwidth / (width + 2);
560 /* how many lines of output, rounded up */
561 lines = (num + cols - 1) / cols;
563 /* Sort the items. */
564 qsort(matches, num, sizeof(char *), _fn_qsort_string_compare);
567 * On the ith line print elements i, i+lines, i+lines*2, etc.
569 for (line = 0; line < lines; line++) {
570 for (col = 0; col < cols; col++) {
571 thisguy = line + col * lines;
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])), "");
580 (void)fprintf(el->el_outfile, "\n");
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,
589 /* We now look backwards for the start of a filename/variable word */
590 const wchar_t *ctemp = cursor;
594 /* if the cursor is placed at a slash or a quote, we need to find the
597 if (ctemp > buffer) {
612 if (wcschr(word_break, ctemp[-1])) {
613 if (ctemp - buffer >= 2 && ctemp[-2] == '\\') {
619 if (special_prefixes && wcschr(special_prefixes, ctemp[-1]))
624 len = (size_t) (cursor - ctemp);
625 if (len == 1 && (ctemp[0] == '\'' || ctemp[0] == '"')) {
631 wchar_t *unescaped_word = unescape_string(ctemp, len);
632 if (unescaped_word == NULL)
634 return unescaped_word;
636 temp = el_malloc((len + 1) * sizeof(*temp));
637 (void) wcsncpy(temp, ctemp, len);
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.
651 * Note: '*' support is not implemented
652 * '!' could never be invoked
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,
668 int what_to_do = '\t';
669 int retval = CC_NORM;
670 int do_unescape = flags & FN_QUOTE_MATCH;
672 if (el->el_state.lastcmd == el->el_state.thiscmd)
675 /* readline's rl_complete() has to be told what we did... */
676 if (completion_type != NULL)
677 *completion_type = what_to_do;
680 complete_func = fn_filename_completion_function;
682 app_func = append_char_function;
685 temp = find_word_to_complete(li->cursor,
686 li->buffer, word_break, special_prefixes, &len, do_unescape);
690 /* these can be used by function called in completion_matches() */
691 /* or (*attempted_completion_function)() */
693 *point = (int)(li->cursor - li->buffer);
695 *end = (int)(li->lastchar - li->buffer);
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);
704 if (!attempted_completion_function ||
705 (over != NULL && !*over && !matches))
706 matches = completion_matches(
707 ct_encode_string(temp, &el->el_scratch), complete_func);
712 if (matches == NULL) {
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);
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);
728 completion = strdup(matches[0]);
729 if (completion == NULL)
733 * Replace the completed string with the common part of
734 * all possible matches if there is a possible completion.
737 ct_decode_string(completion, &el->el_scratch));
739 if (single_match && attempted_completion_function &&
740 !(flags & FN_QUOTE_MATCH))
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
748 el_winsertstr(el, ct_decode_string(
749 (*app_func)(completion), &el->el_scratch));
755 if (!single_match && (what_to_do == '!' || what_to_do == '?')) {
757 * More than one match and requested to list possible
761 for(i = 1, maxlen = 0; matches[i]; i++) {
762 match_len = strlen(matches[i]);
763 if (match_len > maxlen)
766 /* matches[1] through matches[i-1] are available */
767 matches_num = (size_t)(i - 1);
769 /* newline to get on next line from command line */
770 (void)fprintf(el->el_outfile, "\n");
773 * If there are too many items, ask user for display
776 if (matches_num > query_items) {
777 (void)fprintf(el->el_outfile,
778 "Display all %zu possibilities? (y or n) ",
780 (void)fflush(el->el_outfile);
781 if (getc(stdin) != 'y')
783 (void)fprintf(el->el_outfile, "\n");
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.
794 fn_display_match_list(el, matches,
795 matches_num+1, maxlen, app_func);
797 retval = CC_REDISPLAY;
798 } else if (matches[0][0]) {
800 * There was some common match, but the name was
801 * not complete enough. Next tab will print possible
806 /* lcd is not a valid object - further specification */
812 /* free elements of array and the array itself */
813 for (i = 0; matches[i]; i++)
824 fn_complete(EditLine *el,
825 char *(*complete_func)(const char *, int),
826 char **(*attempted_completion_function)(const char *, int, int),
827 const wchar_t *word_break, const wchar_t *special_prefixes,
828 const char *(*app_func)(const char *), size_t query_items,
829 int *completion_type, int *over, int *point, int *end)
831 return fn_complete2(el, complete_func, attempted_completion_function,
832 word_break, special_prefixes, app_func, query_items,
833 completion_type, over, point, end,
834 attempted_completion_function ? 0 : FN_QUOTE_MATCH);
838 * el-compatible wrapper around rl_complete; needed for key binding
842 _el_fn_complete(EditLine *el, int ch __attribute__((__unused__)))
844 return (unsigned char)fn_complete(el, NULL, NULL,
845 break_chars, NULL, NULL, (size_t)100,
846 NULL, NULL, NULL, NULL);
850 * el-compatible wrapper around rl_complete; needed for key binding
854 _el_fn_sh_complete(EditLine *el, int ch)
856 return _el_fn_complete(el, ch);