filecomplete.c revision 1.9
1/*	$NetBSD: filecomplete.c,v 1.9 2006/08/21 12:45:30 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 * 3. Neither the name of The NetBSD Foundation nor the names of its
19 *    contributors may be used to endorse or promote products derived
20 *    from this software without specific prior written permission.
21 *
22 * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
23 * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
24 * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
25 * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
26 * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
27 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
28 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
29 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
30 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
31 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
32 * POSSIBILITY OF SUCH DAMAGE.
33 */
34
35#include "config.h"
36#if !defined(lint) && !defined(SCCSID)
37__RCSID("$NetBSD: filecomplete.c,v 1.9 2006/08/21 12:45:30 christos Exp $");
38#endif /* not lint && not SCCSID */
39
40#include <sys/types.h>
41#include <sys/stat.h>
42#include <stdio.h>
43#include <dirent.h>
44#include <string.h>
45#include <pwd.h>
46#include <ctype.h>
47#include <stdlib.h>
48#include <unistd.h>
49#include <limits.h>
50#include <errno.h>
51#include <fcntl.h>
52#ifdef HAVE_VIS_H
53#include <vis.h>
54#else
55#include "np/vis.h"
56#endif
57#ifdef HAVE_ALLOCA_H
58#include <alloca.h>
59#endif
60#include "el.h"
61#include "fcns.h"		/* for EL_NUM_FCNS */
62#include "histedit.h"
63#include "filecomplete.h"
64
65static char break_chars[] = { ' ', '\t', '\n', '"', '\\', '\'', '`', '@', '$',
66    '>', '<', '=', ';', '|', '&', '{', '(', '\0' };
67
68
69/********************************/
70/* completion functions */
71
72/*
73 * does tilde expansion of strings of type ``~user/foo''
74 * if ``user'' isn't valid user name or ``txt'' doesn't start
75 * w/ '~', returns pointer to strdup()ed copy of ``txt''
76 *
77 * it's callers's responsibility to free() returned string
78 */
79char *
80fn_tilde_expand(const char *txt)
81{
82	struct passwd pwres, *pass;
83	char *temp;
84	size_t len = 0;
85	char pwbuf[1024];
86
87	if (txt[0] != '~')
88		return (strdup(txt));
89
90	temp = strchr(txt + 1, '/');
91	if (temp == NULL) {
92		temp = strdup(txt + 1);
93		if (temp == NULL)
94			return NULL;
95	} else {
96		len = temp - txt + 1;	/* text until string after slash */
97		temp = malloc(len);
98		if (temp == NULL)
99			return NULL;
100		(void)strncpy(temp, txt + 1, len - 2);
101		temp[len - 2] = '\0';
102	}
103	if (temp[0] == 0) {
104		if (getpwuid_r(getuid(), &pwres, pwbuf, sizeof(pwbuf), &pass) != 0)
105			pass = NULL;
106	} else {
107		if (getpwnam_r(temp, &pwres, pwbuf, sizeof(pwbuf), &pass) != 0)
108			pass = NULL;
109	}
110	free(temp);		/* value no more needed */
111	if (pass == NULL)
112		return (strdup(txt));
113
114	/* update pointer txt to point at string immedially following */
115	/* first slash */
116	txt += len;
117
118	temp = malloc(strlen(pass->pw_dir) + 1 + strlen(txt) + 1);
119	if (temp == NULL)
120		return NULL;
121	(void)sprintf(temp, "%s/%s", pass->pw_dir, txt);
122
123	return (temp);
124}
125
126
127/*
128 * return first found file name starting by the ``text'' or NULL if no
129 * such file can be found
130 * value of ``state'' is ignored
131 *
132 * it's caller's responsibility to free returned string
133 */
134char *
135fn_filename_completion_function(const char *text, int state)
136{
137	static DIR *dir = NULL;
138	static char *filename = NULL, *dirname = NULL, *dirpath = NULL;
139	static size_t filename_len = 0;
140	struct dirent *entry;
141	char *temp;
142	size_t len;
143
144	if (state == 0 || dir == NULL) {
145		temp = strrchr(text, '/');
146		if (temp) {
147			char *nptr;
148			temp++;
149			nptr = realloc(filename, strlen(temp) + 1);
150			if (nptr == NULL) {
151				free(filename);
152				return NULL;
153			}
154			filename = nptr;
155			(void)strcpy(filename, temp);
156			len = temp - text;	/* including last slash */
157			nptr = realloc(dirname, len + 1);
158			if (nptr == NULL) {
159				free(filename);
160				return NULL;
161			}
162			dirname = nptr;
163			(void)strncpy(dirname, text, len);
164			dirname[len] = '\0';
165		} else {
166			if (*text == 0)
167				filename = NULL;
168			else {
169				filename = strdup(text);
170				if (filename == NULL)
171					return NULL;
172			}
173			dirname = NULL;
174		}
175
176		if (dir != NULL) {
177			(void)closedir(dir);
178			dir = NULL;
179		}
180
181		/* support for ``~user'' syntax */
182		free(dirpath);
183
184		if (dirname == NULL && (dirname = strdup("./")) == NULL)
185			return NULL;
186
187		if (*dirname == '~')
188			dirpath = fn_tilde_expand(dirname);
189		else
190			dirpath = strdup(dirname);
191
192		if (dirpath == NULL)
193			return NULL;
194
195		dir = opendir(dirpath);
196		if (!dir)
197			return (NULL);	/* cannot open the directory */
198
199		/* will be used in cycle */
200		filename_len = filename ? strlen(filename) : 0;
201	}
202
203	/* find the match */
204	while ((entry = readdir(dir)) != NULL) {
205		/* skip . and .. */
206		if (entry->d_name[0] == '.' && (!entry->d_name[1]
207		    || (entry->d_name[1] == '.' && !entry->d_name[2])))
208			continue;
209		if (filename_len == 0)
210			break;
211		/* otherwise, get first entry where first */
212		/* filename_len characters are equal	  */
213		if (entry->d_name[0] == filename[0]
214#if defined(__SVR4) || defined(__linux__)
215		    && strlen(entry->d_name) >= filename_len
216#else
217		    && entry->d_namlen >= filename_len
218#endif
219		    && strncmp(entry->d_name, filename,
220			filename_len) == 0)
221			break;
222	}
223
224	if (entry) {		/* match found */
225
226#if defined(__SVR4) || defined(__linux__)
227		len = strlen(entry->d_name);
228#else
229		len = entry->d_namlen;
230#endif
231
232		temp = malloc(strlen(dirname) + len + 1);
233		if (temp == NULL)
234			return NULL;
235		(void)sprintf(temp, "%s%s", dirname, entry->d_name);
236	} else {
237		(void)closedir(dir);
238		dir = NULL;
239		temp = NULL;
240	}
241
242	return (temp);
243}
244
245
246static const char *
247append_char_function(const char *name)
248{
249	struct stat stbuf;
250	char *expname = *name == '~' ? fn_tilde_expand(name) : NULL;
251	const char *rs = "";
252
253	if (stat(expname ? expname : name, &stbuf) == -1)
254		goto out;
255	if (S_ISDIR(stbuf.st_mode))
256		rs = "/";
257out:
258	if (expname)
259		free(expname);
260	return rs;
261}
262/*
263 * returns list of completions for text given
264 * non-static for readline.
265 */
266char ** completion_matches(const char *, char *(*)(const char *, int));
267char **
268completion_matches(const char *text, char *(*genfunc)(const char *, int))
269{
270	char **match_list = NULL, *retstr, *prevstr;
271	size_t match_list_len, max_equal, which, i;
272	size_t matches;
273
274	matches = 0;
275	match_list_len = 1;
276	while ((retstr = (*genfunc) (text, (int)matches)) != NULL) {
277		/* allow for list terminator here */
278		if (matches + 3 >= match_list_len) {
279			char **nmatch_list;
280			while (matches + 3 >= match_list_len)
281				match_list_len <<= 1;
282			nmatch_list = realloc(match_list,
283			    match_list_len * sizeof(char *));
284			if (nmatch_list == NULL) {
285				free(match_list);
286				return NULL;
287			}
288			match_list = nmatch_list;
289
290		}
291		match_list[++matches] = retstr;
292	}
293
294	if (!match_list)
295		return NULL;	/* nothing found */
296
297	/* find least denominator and insert it to match_list[0] */
298	which = 2;
299	prevstr = match_list[1];
300	max_equal = strlen(prevstr);
301	for (; which <= matches; which++) {
302		for (i = 0; i < max_equal &&
303		    prevstr[i] == match_list[which][i]; i++)
304			continue;
305		max_equal = i;
306	}
307
308	retstr = malloc(max_equal + 1);
309	if (retstr == NULL) {
310		free(match_list);
311		return NULL;
312	}
313	(void)strncpy(retstr, match_list[1], max_equal);
314	retstr[max_equal] = '\0';
315	match_list[0] = retstr;
316
317	/* add NULL as last pointer to the array */
318	match_list[matches + 1] = (char *) NULL;
319
320	return (match_list);
321}
322
323/*
324 * Sort function for qsort(). Just wrapper around strcasecmp().
325 */
326static int
327_fn_qsort_string_compare(const void *i1, const void *i2)
328{
329	const char *s1 = ((const char * const *)i1)[0];
330	const char *s2 = ((const char * const *)i2)[0];
331
332	return strcasecmp(s1, s2);
333}
334
335/*
336 * Display list of strings in columnar format on readline's output stream.
337 * 'matches' is list of strings, 'len' is number of strings in 'matches',
338 * 'max' is maximum length of string in 'matches'.
339 */
340void
341fn_display_match_list (EditLine *el, char **matches, int len, int max)
342{
343	int i, idx, limit, count;
344	int screenwidth = el->el_term.t_size.h;
345
346	/*
347	 * Find out how many entries can be put on one line, count
348	 * with two spaces between strings.
349	 */
350	limit = screenwidth / (max + 2);
351	if (limit == 0)
352		limit = 1;
353
354	/* how many lines of output */
355	count = len / limit;
356	if (count * limit < len)
357		count++;
358
359	/* Sort the items if they are not already sorted. */
360	qsort(&matches[1], (size_t)(len - 1), sizeof(char *),
361	    _fn_qsort_string_compare);
362
363	idx = 1;
364	for(; count > 0; count--) {
365		for(i = 0; i < limit && matches[idx]; i++, idx++)
366			(void)fprintf(el->el_outfile, "%-*s  ", max,
367			    matches[idx]);
368		(void)fprintf(el->el_outfile, "\n");
369	}
370}
371
372/*
373 * Complete the word at or before point,
374 * 'what_to_do' says what to do with the completion.
375 * \t   means do standard completion.
376 * `?' means list the possible completions.
377 * `*' means insert all of the possible completions.
378 * `!' means to do standard completion, and list all possible completions if
379 * there is more than one.
380 *
381 * Note: '*' support is not implemented
382 *       '!' could never be invoked
383 */
384int
385fn_complete(EditLine *el,
386	char *(*complet_func)(const char *, int),
387	char **(*attempted_completion_function)(const char *, int, int),
388	const char *word_break, const char *special_prefixes,
389	const char *(*app_func)(const char *), int query_items,
390	int *completion_type, int *over, int *point, int *end)
391{
392	const LineInfo *li;
393	char *temp, **matches;
394	const char *ctemp;
395	size_t len;
396	int what_to_do = '\t';
397
398	if (el->el_state.lastcmd == el->el_state.thiscmd)
399		what_to_do = '?';
400
401	/* readline's rl_complete() has to be told what we did... */
402	if (completion_type != NULL)
403		*completion_type = what_to_do;
404
405	if (!complet_func)
406		complet_func = fn_filename_completion_function;
407	if (!app_func)
408		app_func = append_char_function;
409
410	/* We now look backwards for the start of a filename/variable word */
411	li = el_line(el);
412	ctemp = (const char *) li->cursor;
413	while (ctemp > li->buffer
414	    && !strchr(word_break, ctemp[-1])
415	    && (!special_prefixes || !strchr(special_prefixes, ctemp[-1]) ) )
416		ctemp--;
417
418	len = li->cursor - ctemp;
419	temp = alloca(len + 1);
420	(void)strncpy(temp, ctemp, len);
421	temp[len] = '\0';
422
423	/* these can be used by function called in completion_matches() */
424	/* or (*attempted_completion_function)() */
425	if (point != 0)
426		*point = li->cursor - li->buffer;
427	if (end != NULL)
428		*end = li->lastchar - li->buffer;
429
430	if (attempted_completion_function) {
431		int cur_off = li->cursor - li->buffer;
432		matches = (*attempted_completion_function) (temp,
433		    (int)(cur_off - len), cur_off);
434	} else
435		matches = 0;
436	if (!attempted_completion_function ||
437	    (over != NULL && !*over && !matches))
438		matches = completion_matches(temp, complet_func);
439
440	if (over != NULL)
441		*over = 0;
442
443	if (matches) {
444		int i, retval = CC_REFRESH;
445		int matches_num, maxlen, match_len, match_display=1;
446
447		/*
448		 * Only replace the completed string with common part of
449		 * possible matches if there is possible completion.
450		 */
451		if (matches[0][0] != '\0') {
452			el_deletestr(el, (int) len);
453			el_insertstr(el, matches[0]);
454		}
455
456		if (what_to_do == '?')
457			goto display_matches;
458
459		if (matches[2] == NULL && strcmp(matches[0], matches[1]) == 0) {
460			/*
461			 * We found exact match. Add a space after
462			 * it, unless we do filename completion and the
463			 * object is a directory.
464			 */
465			el_insertstr(el, (*append_char_function)(matches[0]));
466		} else if (what_to_do == '!') {
467    display_matches:
468			/*
469			 * More than one match and requested to list possible
470			 * matches.
471			 */
472
473			for(i=1, maxlen=0; matches[i]; i++) {
474				match_len = strlen(matches[i]);
475				if (match_len > maxlen)
476					maxlen = match_len;
477			}
478			matches_num = i - 1;
479
480			/* newline to get on next line from command line */
481			(void)fprintf(el->el_outfile, "\n");
482
483			/*
484			 * If there are too many items, ask user for display
485			 * confirmation.
486			 */
487			if (matches_num > query_items) {
488				(void)fprintf(el->el_outfile,
489				    "Display all %d possibilities? (y or n) ",
490				    matches_num);
491				(void)fflush(el->el_outfile);
492				if (getc(stdin) != 'y')
493					match_display = 0;
494				(void)fprintf(el->el_outfile, "\n");
495			}
496
497			if (match_display)
498				fn_display_match_list(el, matches, matches_num,
499					maxlen);
500			retval = CC_REDISPLAY;
501		} else if (matches[0][0]) {
502			/*
503			 * There was some common match, but the name was
504			 * not complete enough. Next tab will print possible
505			 * completions.
506			 */
507			el_beep(el);
508		} else {
509			/* lcd is not a valid object - further specification */
510			/* is needed */
511			el_beep(el);
512			retval = CC_NORM;
513		}
514
515		/* free elements of array and the array itself */
516		for (i = 0; matches[i]; i++)
517			free(matches[i]);
518		free(matches), matches = NULL;
519
520		return (retval);
521	}
522	return (CC_NORM);
523}
524
525/*
526 * el-compatible wrapper around rl_complete; needed for key binding
527 */
528/* ARGSUSED */
529unsigned char
530_el_fn_complete(EditLine *el, int ch __attribute__((__unused__)))
531{
532	return (unsigned char)fn_complete(el, NULL, NULL,
533	    break_chars, NULL, NULL, 100,
534	    NULL, NULL, NULL, NULL);
535}
536