1 /* $NetBSD: filecomplete.c,v 1.58 2019/09/08 05:50:58 abhinav 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.58 2019/09/08 05:50:58 abhinav 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)strncpy(temp, txt + 1, len - 2);
93 #ifdef HAVE_GETPW_R_POSIX
94 if (getpwuid_r(getuid(), &pwres, pwbuf, sizeof(pwbuf),
97 #elif HAVE_GETPW_R_DRAFT
98 pass = getpwuid_r(getuid(), &pwres, pwbuf, sizeof(pwbuf));
100 pass = getpwuid(getuid());
103 #ifdef HAVE_GETPW_R_POSIX
104 if (getpwnam_r(temp, &pwres, pwbuf, sizeof(pwbuf), &pass) != 0)
106 #elif HAVE_GETPW_R_DRAFT
107 pass = getpwnam_r(temp, &pwres, pwbuf, sizeof(pwbuf));
109 pass = getpwnam(temp);
112 el_free(temp); /* value no more needed */
116 /* update pointer txt to point at string immedially following */
120 len = strlen(pass->pw_dir) + 1 + strlen(txt) + 1;
121 temp = el_calloc(len, sizeof(*temp));
124 (void)snprintf(temp, len, "%s/%s", pass->pw_dir, txt);
130 needs_escaping(char c)
163 needs_dquote_escaping(char c)
178 unescape_string(const wchar_t *string, size_t length)
182 wchar_t *unescaped = el_calloc(length + 1, sizeof(*string));
183 if (unescaped == NULL)
185 for (i = 0; i < length ; i++) {
186 if (string[i] == '\\')
188 unescaped[j++] = string[i];
195 escape_filename(EditLine * el, const char *filename, int single_match,
196 const char *(*app_func)(const char *))
198 size_t original_len = 0;
199 size_t escaped_character_count = 0;
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 */
207 wchar_t *temp = el->el_line.buffer;
208 const char *append_char = NULL;
210 if (filename == NULL)
213 while (temp != el->el_line.cursor) {
215 * If we see a single quote but have not seen a double quote
216 * so far set/unset s_quote
218 if (temp[0] == '\'' && !d_quoted)
219 s_quoted = !s_quoted;
221 * vice versa to the above condition
223 else if (temp[0] == '"' && !s_quoted)
224 d_quoted = !d_quoted;
228 /* Count number of special characters so that we can calculate
229 * number of extra bytes needed in the new string
231 for (s = filename; *s; s++, original_len++) {
233 /* Inside a single quote only single quotes need escaping */
234 if (s_quoted && c == '\'') {
235 escaped_character_count += 3;
238 /* Inside double quotes only ", \, ` and $ need escaping */
239 if (d_quoted && needs_dquote_escaping(c)) {
240 escaped_character_count++;
243 if (!s_quoted && !d_quoted && needs_escaping(c))
244 escaped_character_count++;
247 newlen = original_len + escaped_character_count + 1;
248 if (s_quoted || d_quoted)
251 if (single_match && app_func)
254 if ((escaped_str = el_malloc(newlen)) == NULL)
257 for (s = filename; *s; s++) {
259 if (!needs_escaping(c)) {
260 /* no escaping is required continue as usual */
261 escaped_str[offset++] = c;
265 /* single quotes inside single quotes require special handling */
266 if (c == '\'' && s_quoted) {
267 escaped_str[offset++] = '\'';
268 escaped_str[offset++] = '\\';
269 escaped_str[offset++] = '\'';
270 escaped_str[offset++] = '\'';
274 /* Otherwise no escaping needed inside single quotes */
276 escaped_str[offset++] = c;
280 /* No escaping needed inside a double quoted string either
281 * unless we see a '$', '\', '`', or '"' (itself)
283 if (d_quoted && !needs_dquote_escaping(c)) {
284 escaped_str[offset++] = c;
288 /* If we reach here that means escaping is actually needed */
289 escaped_str[offset++] = '\\';
290 escaped_str[offset++] = c;
293 if (single_match && app_func) {
294 escaped_str[offset] = 0;
295 append_char = app_func(escaped_str);
296 /* we want to append space only if we are not inside quotes */
297 if (append_char[0] == ' ') {
298 if (!s_quoted && !d_quoted)
299 escaped_str[offset++] = append_char[0];
301 escaped_str[offset++] = append_char[0];
304 /* close the quotes if single match and the match is not a directory */
305 if (single_match && (append_char && append_char[0] == ' ')) {
307 escaped_str[offset++] = '\'';
309 escaped_str[offset++] = '"';
312 escaped_str[offset] = 0;
317 * return first found file name starting by the ``text'' or NULL if no
318 * such file can be found
319 * value of ``state'' is ignored
321 * it's the caller's responsibility to free the returned string
324 fn_filename_completion_function(const char *text, int state)
326 static DIR *dir = NULL;
327 static char *filename = NULL, *dirname = NULL, *dirpath = NULL;
328 static size_t filename_len = 0;
329 struct dirent *entry;
333 if (state == 0 || dir == NULL) {
334 temp = strrchr(text, '/');
338 nptr = el_realloc(filename, (strlen(temp) + 1) *
346 (void)strcpy(filename, temp);
347 len = (size_t)(temp - text); /* including last slash */
349 nptr = el_realloc(dirname, (len + 1) *
357 (void)strncpy(dirname, text, len);
364 filename = strdup(text);
365 if (filename == NULL)
377 /* support for ``~user'' syntax */
381 if (dirname == NULL) {
382 if ((dirname = strdup("")) == NULL)
384 dirpath = strdup("./");
385 } else if (*dirname == '~')
386 dirpath = fn_tilde_expand(dirname);
388 dirpath = strdup(dirname);
393 dir = opendir(dirpath);
395 return NULL; /* cannot open the directory */
397 /* will be used in cycle */
398 filename_len = filename ? strlen(filename) : 0;
402 while ((entry = readdir(dir)) != NULL) {
404 if (entry->d_name[0] == '.' && (!entry->d_name[1]
405 || (entry->d_name[1] == '.' && !entry->d_name[2])))
407 if (filename_len == 0)
409 /* otherwise, get first entry where first */
410 /* filename_len characters are equal */
411 if (entry->d_name[0] == filename[0]
412 #if HAVE_STRUCT_DIRENT_D_NAMLEN
413 && entry->d_namlen >= filename_len
415 && strlen(entry->d_name) >= filename_len
417 && strncmp(entry->d_name, filename,
422 if (entry) { /* match found */
424 #if HAVE_STRUCT_DIRENT_D_NAMLEN
425 len = entry->d_namlen;
427 len = strlen(entry->d_name);
430 len = strlen(dirname) + len + 1;
431 temp = el_calloc(len, sizeof(*temp));
434 (void)snprintf(temp, len, "%s%s", dirname, entry->d_name);
446 append_char_function(const char *name)
449 char *expname = *name == '~' ? fn_tilde_expand(name) : NULL;
450 const char *rs = " ";
452 if (stat(expname ? expname : name, &stbuf) == -1)
454 if (S_ISDIR(stbuf.st_mode))
462 * returns list of completions for text given
463 * non-static for readline.
465 char ** completion_matches(const char *, char *(*)(const char *, int));
467 completion_matches(const char *text, char *(*genfunc)(const char *, int))
469 char **match_list = NULL, *retstr, *prevstr;
470 size_t match_list_len, max_equal, which, i;
475 while ((retstr = (*genfunc) (text, (int)matches)) != NULL) {
476 /* allow for list terminator here */
477 if (matches + 3 >= match_list_len) {
479 while (matches + 3 >= match_list_len)
480 match_list_len <<= 1;
481 nmatch_list = el_realloc(match_list,
482 match_list_len * sizeof(*nmatch_list));
483 if (nmatch_list == NULL) {
487 match_list = nmatch_list;
490 match_list[++matches] = retstr;
494 return NULL; /* nothing found */
496 /* find least denominator and insert it to match_list[0] */
498 prevstr = match_list[1];
499 max_equal = strlen(prevstr);
500 for (; which <= matches; which++) {
501 for (i = 0; i < max_equal &&
502 prevstr[i] == match_list[which][i]; i++)
507 retstr = el_calloc(max_equal + 1, sizeof(*retstr));
508 if (retstr == NULL) {
512 (void)strncpy(retstr, match_list[1], max_equal);
513 retstr[max_equal] = '\0';
514 match_list[0] = retstr;
516 /* add NULL as last pointer to the array */
517 match_list[matches + 1] = NULL;
523 * Sort function for qsort(). Just wrapper around strcasecmp().
526 _fn_qsort_string_compare(const void *i1, const void *i2)
528 const char *s1 = ((const char * const *)i1)[0];
529 const char *s2 = ((const char * const *)i2)[0];
531 return strcasecmp(s1, s2);
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'.
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].
543 fn_display_match_list(EditLine * el, char **matches, size_t num, size_t width,
544 const char *(*app_func) (const char *))
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;
551 /* Ignore matches[0]. Avoid 1-based array logic below. */
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.
559 cols = (size_t)screenwidth / (width + 2);
563 /* how many lines of output, rounded up */
564 lines = (num + cols - 1) / cols;
566 /* Sort the items. */
567 qsort(matches, num, sizeof(char *), _fn_qsort_string_compare);
570 * On the ith line print elements i, i+lines, i+lines*2, etc.
572 for (line = 0; line < lines; line++) {
573 for (col = 0; col < cols; col++) {
574 thisguy = line + col * lines;
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])), "");
583 (void)fprintf(el->el_outfile, "\n");
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)
591 /* We now look backwards for the start of a filename/variable word */
592 const wchar_t *ctemp = cursor;
595 /* if the cursor is placed at a slash or a quote, we need to find the
598 if (ctemp > buffer) {
613 if (wcschr(word_break, ctemp[-1])) {
614 if (ctemp - buffer >= 2 && ctemp[-2] == '\\') {
617 } else if (ctemp - buffer >= 2 &&
618 (ctemp[-2] == '\'' || ctemp[-2] == '"')) {
624 if (special_prefixes && wcschr(special_prefixes, ctemp[-1]))
629 len = (size_t) (cursor - ctemp);
630 if (len == 1 && (ctemp[0] == '\'' || ctemp[0] == '"')) {
635 wchar_t *unescaped_word = unescape_string(ctemp, len);
636 if (unescaped_word == NULL)
638 return unescaped_word;
642 * Complete the word at or before point,
643 * 'what_to_do' says what to do with the completion.
644 * \t means do standard completion.
645 * `?' means list the possible completions.
646 * `*' means insert all of the possible completions.
647 * `!' means to do standard completion, and list all possible completions if
648 * there is more than one.
650 * Note: '*' support is not implemented
651 * '!' could never be invoked
654 fn_complete(EditLine *el,
655 char *(*complet_func)(const char *, int),
656 char **(*attempted_completion_function)(const char *, int, int),
657 const wchar_t *word_break, const wchar_t *special_prefixes,
658 const char *(*app_func)(const char *), size_t query_items,
659 int *completion_type, int *over, int *point, int *end)
666 int what_to_do = '\t';
667 int retval = CC_NORM;
669 if (el->el_state.lastcmd == el->el_state.thiscmd)
672 /* readline's rl_complete() has to be told what we did... */
673 if (completion_type != NULL)
674 *completion_type = what_to_do;
677 complet_func = fn_filename_completion_function;
679 app_func = append_char_function;
682 temp = find_word_to_complete(li->cursor,
683 li->buffer, word_break, special_prefixes, &len);
687 /* these can be used by function called in completion_matches() */
688 /* or (*attempted_completion_function)() */
690 *point = (int)(li->cursor - li->buffer);
692 *end = (int)(li->lastchar - li->buffer);
694 if (attempted_completion_function) {
695 int cur_off = (int)(li->cursor - li->buffer);
696 matches = (*attempted_completion_function)(
697 ct_encode_string(temp, &el->el_scratch),
698 cur_off - (int)len, cur_off);
701 if (!attempted_completion_function ||
702 (over != NULL && !*over && !matches))
703 matches = completion_matches(
704 ct_encode_string(temp, &el->el_scratch), complet_func);
711 size_t matches_num, maxlen, match_len, match_display=1;
712 int single_match = matches[2] == NULL &&
713 (matches[1] == NULL || strcmp(matches[0], matches[1]) == 0);
717 if (matches[0][0] != '\0') {
718 el_deletestr(el, (int)len);
719 if (!attempted_completion_function)
720 completion = escape_filename(el, matches[0],
721 single_match, app_func);
723 completion = strdup(matches[0]);
724 if (completion == NULL)
727 /* We found exact match. Add a space after it,
728 * unless we do filename completion and the
729 * object is a directory. Also do necessary
733 ct_decode_string(completion, &el->el_scratch));
735 /* Only replace the completed string with
736 * common part of possible matches if there is
737 * possible completion.
740 ct_decode_string(completion, &el->el_scratch));
746 if (!single_match && (what_to_do == '!' || what_to_do == '?')) {
748 * More than one match and requested to list possible
752 for(i = 1, maxlen = 0; matches[i]; i++) {
753 match_len = strlen(matches[i]);
754 if (match_len > maxlen)
757 /* matches[1] through matches[i-1] are available */
758 matches_num = (size_t)(i - 1);
760 /* newline to get on next line from command line */
761 (void)fprintf(el->el_outfile, "\n");
764 * If there are too many items, ask user for display
767 if (matches_num > query_items) {
768 (void)fprintf(el->el_outfile,
769 "Display all %zu possibilities? (y or n) ",
771 (void)fflush(el->el_outfile);
772 if (getc(stdin) != 'y')
774 (void)fprintf(el->el_outfile, "\n");
779 * Interface of this function requires the
780 * strings be matches[1..num-1] for compat.
781 * We have matches_num strings not counting
782 * the prefix in matches[0], so we need to
783 * add 1 to matches_num for the call.
785 fn_display_match_list(el, matches,
786 matches_num+1, maxlen, app_func);
788 retval = CC_REDISPLAY;
789 } else if (matches[0][0]) {
791 * There was some common match, but the name was
792 * not complete enough. Next tab will print possible
797 /* lcd is not a valid object - further specification */
803 /* free elements of array and the array itself */
804 for (i = 0; matches[i]; i++)
816 * el-compatible wrapper around rl_complete; needed for key binding
820 _el_fn_complete(EditLine *el, int ch __attribute__((__unused__)))
822 return (unsigned char)fn_complete(el, NULL, NULL,
823 break_chars, NULL, NULL, (size_t)100,
824 NULL, NULL, NULL, NULL);
828 * el-compatible wrapper around rl_complete; needed for key binding
832 _el_fn_sh_complete(EditLine *el, int ch)
834 return _el_fn_complete(el, ch);