xref: /netbsd-src/bin/ksh/edit.c (revision aaf4ece63a859a04e37cf3a7229b5fab0157cc06)
1 /*	$NetBSD: edit.c,v 1.17 2005/09/11 22:23:42 christos Exp $	*/
2 
3 /*
4  * Command line editing - common code
5  *
6  */
7 #include <sys/cdefs.h>
8 
9 #ifndef lint
10 __RCSID("$NetBSD: edit.c,v 1.17 2005/09/11 22:23:42 christos Exp $");
11 #endif
12 
13 
14 #include "config.h"
15 #ifdef EDIT
16 
17 #include "sh.h"
18 #include "tty.h"
19 #define EXTERN
20 #include "edit.h"
21 #undef EXTERN
22 #ifdef OS_SCO	/* SCO Unix 3.2v4.1 */
23 # include <sys/stream.h>	/* needed for <sys/ptem.h> */
24 # include <sys/ptem.h>		/* needed for struct winsize */
25 #endif /* OS_SCO */
26 #include <sys/ioctl.h>
27 #include <ctype.h>
28 #include "ksh_stat.h"
29 
30 
31 #if defined(TIOCGWINSZ)
32 static RETSIGTYPE x_sigwinch ARGS((int sig));
33 static int got_sigwinch;
34 static void check_sigwinch ARGS((void));
35 #endif /* TIOCGWINSZ */
36 
37 static int	x_file_glob ARGS((int flags, const char *str, int slen,
38 				  char ***wordsp));
39 static int	x_command_glob ARGS((int flags, const char *str, int slen,
40 				     char ***wordsp));
41 static int	x_locate_word ARGS((const char *buf, int buflen, int pos,
42 				    int *startp, int *is_command));
43 
44 static char vdisable_c;
45 
46 
47 /* Called from main */
48 void
49 x_init()
50 {
51 	/* set to -2 to force initial binding */
52 	edchars.erase = edchars.kill = edchars.intr = edchars.quit
53 		= edchars.eof = -2;
54 	/* default value for deficient systems */
55 	edchars.werase = 027;	/* ^W */
56 
57 #ifdef TIOCGWINSZ
58 # ifdef SIGWINCH
59 	if (setsig(&sigtraps[SIGWINCH], x_sigwinch, SS_RESTORE_ORIG|SS_SHTRAP))
60 		sigtraps[SIGWINCH].flags |= TF_SHELL_USES;
61 # endif /* SIGWINCH */
62 	got_sigwinch = 1; /* force initial check */
63 	check_sigwinch();
64 #endif /* TIOCGWINSZ */
65 
66 #ifdef EMACS
67 	x_init_emacs();
68 #endif /* EMACS */
69 
70 	/* Bizarreness to figure out how to disable
71 	 * a struct termios.c_cc[] char
72 	 */
73 #ifdef _POSIX_VDISABLE
74 	if (_POSIX_VDISABLE >= 0)
75 		vdisable_c = (char) _POSIX_VDISABLE;
76 	else
77 		/* `feature not available' */
78 		vdisable_c = (char) 0377;
79 #else
80 # if defined(HAVE_PATHCONF) && defined(_PC_VDISABLE)
81 	vdisable_c = fpathconf(tty_fd, _PC_VDISABLE);
82 # else
83 	vdisable_c = (char) 0377;	/* default to old BSD value */
84 # endif
85 #endif /* _POSIX_VDISABLE */
86 }
87 
88 #if defined(TIOCGWINSZ)
89 static RETSIGTYPE
90 x_sigwinch(sig)
91     	int sig;
92 {
93 	got_sigwinch = 1;
94 	return RETSIGVAL;
95 }
96 
97 static void
98 check_sigwinch ARGS((void))
99 {
100 	if (got_sigwinch) {
101 		struct winsize ws;
102 
103 		got_sigwinch = 0;
104 		if (procpid == kshpid && ioctl(tty_fd, TIOCGWINSZ, &ws) >= 0) {
105 			struct tbl *vp;
106 
107 			/* Do NOT export COLUMNS/LINES.  Many applications
108 			 * check COLUMNS/LINES before checking ws.ws_col/row,
109 			 * so if the app is started with C/L in the environ
110 			 * and the window is then resized, the app won't
111 			 * see the change cause the environ doesn't change.
112 			 */
113 			if (ws.ws_col) {
114 				x_cols = ws.ws_col < MIN_COLS ? MIN_COLS
115 						: ws.ws_col;
116 
117 				if ((vp = typeset("COLUMNS", 0, 0, 0, 0)))
118 					setint(vp, (long) ws.ws_col);
119 			}
120 			if (ws.ws_row
121 			    && (vp = typeset("LINES", 0, 0, 0, 0)))
122 				setint(vp, (long) ws.ws_row);
123 		}
124 	}
125 }
126 #endif /* TIOCGWINSZ */
127 
128 /*
129  * read an edited command line
130  */
131 int
132 x_read(buf, len)
133 	char *buf;
134 	size_t len;
135 {
136 	int	i;
137 
138 	x_mode(TRUE);
139 #ifdef EMACS
140 	if (Flag(FEMACS) || Flag(FGMACS))
141 		i = x_emacs(buf, len);
142 	else
143 #endif
144 #ifdef VI
145 	if (Flag(FVI))
146 		i = x_vi(buf, len);
147 	else
148 #endif
149 		i = -1;		/* internal error */
150 	x_mode(FALSE);
151 #if defined(TIOCGWINSZ)
152 	if (got_sigwinch)
153 		check_sigwinch();
154 #endif /* TIOCGWINSZ */
155 
156 	return i;
157 }
158 
159 /* tty I/O */
160 
161 int
162 x_getc()
163 {
164 #ifdef OS2
165 	unsigned char c = _read_kbd(0, 1, 0);
166 	return c == 0 ? 0xE0 : c;
167 #else /* OS2 */
168 	char c;
169 	int n;
170 
171 	while ((n = blocking_read(0, &c, 1)) < 0 && errno == EINTR)
172 		if (trap) {
173 			x_mode(FALSE);
174 			runtraps(0);
175 			x_mode(TRUE);
176 		}
177 	if (n != 1)
178 		return -1;
179 	return (int) (unsigned char) c;
180 #endif /* OS2 */
181 }
182 
183 void
184 x_flush()
185 {
186 	shf_flush(shl_out);
187 }
188 
189 void
190 x_putc(c)
191 	int c;
192 {
193 	shf_putc(c, shl_out);
194 }
195 
196 void
197 x_puts(s)
198 	const char *s;
199 {
200 	while (*s != 0)
201 		shf_putc(*s++, shl_out);
202 }
203 
204 bool_t
205 x_mode(onoff)
206 	bool_t	onoff;
207 {
208 	static bool_t	x_cur_mode;
209 	bool_t		prev;
210 
211 	if (x_cur_mode == onoff)
212 		return x_cur_mode;
213 	prev = x_cur_mode;
214 	x_cur_mode = onoff;
215 
216 	if (onoff) {
217 		TTY_state	cb;
218 		X_chars		oldchars;
219 
220 		oldchars = edchars;
221 		cb = tty_state;
222 
223 #if defined(HAVE_TERMIOS_H) || defined(HAVE_TERMIO_H)
224 		edchars.erase = cb.c_cc[VERASE];
225 		edchars.kill = cb.c_cc[VKILL];
226 		edchars.intr = cb.c_cc[VINTR];
227 		edchars.quit = cb.c_cc[VQUIT];
228 		edchars.eof = cb.c_cc[VEOF];
229 # ifdef VWERASE
230 		edchars.werase = cb.c_cc[VWERASE];
231 # endif
232 # ifdef _CRAY2		/* brain-damaged terminal handler */
233 		cb.c_lflag &= ~(ICANON|ECHO);
234 		/* rely on print routine to map '\n' to CR,LF */
235 # else
236 		cb.c_iflag &= ~(INLCR|ICRNL);
237 #  ifdef _BSD_SYSV	/* need to force CBREAK instead of RAW (need CRMOD on output) */
238 		cb.c_lflag &= ~(ICANON|ECHO);
239 #  else
240 #   ifdef SWTCH	/* need CBREAK to handle swtch char */
241 		cb.c_lflag &= ~(ICANON|ECHO);
242 		cb.c_lflag |= ISIG;
243 		cb.c_cc[VINTR] = vdisable_c;
244 		cb.c_cc[VQUIT] = vdisable_c;
245 #   else
246 		cb.c_lflag &= ~(ISIG|ICANON|ECHO);
247 #   endif
248 #  endif
249 #  ifdef VLNEXT
250 		/* osf/1 processes lnext when ~icanon */
251 		cb.c_cc[VLNEXT] = vdisable_c;
252 #  endif /* VLNEXT */
253 #  ifdef VDISCARD
254 		/* sunos 4.1.x & osf/1 processes discard(flush) when ~icanon */
255 		cb.c_cc[VDISCARD] = vdisable_c;
256 #  endif /* VDISCARD */
257 		cb.c_cc[VTIME] = 0;
258 		cb.c_cc[VMIN] = 1;
259 # endif	/* _CRAY2 */
260 #else
261 	/* Assume BSD tty stuff. */
262 		edchars.erase = cb.sgttyb.sg_erase;
263 		edchars.kill = cb.sgttyb.sg_kill;
264 		cb.sgttyb.sg_flags &= ~ECHO;
265 		cb.sgttyb.sg_flags |= CBREAK;
266 #  ifdef TIOCGATC
267 		edchars.intr = cb.lchars.tc_intrc;
268 		edchars.quit = cb.lchars.tc_quitc;
269 		edchars.eof = cb.lchars.tc_eofc;
270 		edchars.werase = cb.lchars.tc_werasc;
271 		cb.lchars.tc_suspc = -1;
272 		cb.lchars.tc_dsuspc = -1;
273 		cb.lchars.tc_lnextc = -1;
274 		cb.lchars.tc_statc = -1;
275 		cb.lchars.tc_intrc = -1;
276 		cb.lchars.tc_quitc = -1;
277 		cb.lchars.tc_rprntc = -1;
278 #  else
279 		edchars.intr = cb.tchars.t_intrc;
280 		edchars.quit = cb.tchars.t_quitc;
281 		edchars.eof = cb.tchars.t_eofc;
282 		cb.tchars.t_intrc = -1;
283 		cb.tchars.t_quitc = -1;
284 #   ifdef TIOCGLTC
285 		edchars.werase = cb.ltchars.t_werasc;
286 		cb.ltchars.t_suspc = -1;
287 		cb.ltchars.t_dsuspc = -1;
288 		cb.ltchars.t_lnextc = -1;
289 		cb.ltchars.t_rprntc = -1;
290 #   endif
291 #  endif /* TIOCGATC */
292 #endif /* HAVE_TERMIOS_H || HAVE_TERMIO_H */
293 
294 		set_tty(tty_fd, &cb, TF_WAIT);
295 
296 #ifdef __CYGWIN__
297 		if (edchars.eof == '\0')
298 			edchars.eof = '\4';
299 #endif /* __CYGWIN__ */
300 
301 		/* Convert unset values to internal `unset' value */
302 		if (edchars.erase == vdisable_c)
303 			edchars.erase = -1;
304 		if (edchars.kill == vdisable_c)
305 			edchars.kill = -1;
306 		if (edchars.intr == vdisable_c)
307 			edchars.intr = -1;
308 		if (edchars.quit == vdisable_c)
309 			edchars.quit = -1;
310 		if (edchars.eof == vdisable_c)
311 			edchars.eof = -1;
312 		if (edchars.werase == vdisable_c)
313 			edchars.werase = -1;
314 		if (memcmp(&edchars, &oldchars, sizeof(edchars)) != 0) {
315 #ifdef EMACS
316 			x_emacs_keys(&edchars);
317 #endif
318 		}
319 	} else {
320 		/* TF_WAIT doesn't seem to be necessary when leaving xmode */
321 		set_tty(tty_fd, &tty_state, TF_NONE);
322 	}
323 
324 	return prev;
325 }
326 
327 /* NAME:
328  *      promptlen - calculate the length of PS1 etc.
329  *
330  * DESCRIPTION:
331  *      This function is based on a fix from guy@demon.co.uk
332  *      It fixes a bug in that if PS1 contains '!', the length
333  *      given by strlen() is probably wrong.
334  *
335  * RETURN VALUE:
336  *      length
337  */
338 int
339 promptlen(cp, spp)
340     const char  *cp;
341     const char **spp;
342 {
343     int count = 0;
344     const char *sp = cp;
345     char delimiter = 0;
346     int indelimit = 0;
347 
348     /* Undocumented AT&T ksh feature:
349      * If the second char in the prompt string is \r then the first char
350      * is taken to be a non-printing delimiter and any chars between two
351      * instances of the delimiter are not considered to be part of the
352      * prompt length
353      */
354     if (*cp && cp[1] == '\r') {
355 	delimiter = *cp;
356 	cp += 2;
357     }
358 
359     for (; *cp; cp++) {
360 	if (indelimit && *cp != delimiter)
361 	    ;
362 	else if (*cp == '\n' || *cp == '\r') {
363 	    count = 0;
364 	    sp = cp + 1;
365 	} else if (*cp == '\t') {
366 	    count = (count | 7) + 1;
367 	} else if (*cp == '\b') {
368 	    if (count > 0)
369 		count--;
370 	} else if (*cp == delimiter)
371 	    indelimit = !indelimit;
372 	else
373 	    count++;
374     }
375     if (spp)
376 	*spp = sp;
377     return count;
378 }
379 
380 void
381 set_editmode(ed)
382 	const char *ed;
383 {
384 	static const enum sh_flag edit_flags[] = {
385 #ifdef EMACS
386 			FEMACS, FGMACS,
387 #endif
388 #ifdef VI
389 			FVI,
390 #endif
391 		    };
392 	char *rcp;
393 	int i;
394 
395 	if ((rcp = ksh_strrchr_dirsep(ed)))
396 		ed = ++rcp;
397 	for (i = 0; i < NELEM(edit_flags); i++)
398 		if (strstr(ed, goptions[(int) edit_flags[i]].name)) {
399 			change_flag(edit_flags[i], OF_SPECIAL, 1);
400 			return;
401 		}
402 }
403 
404 /* ------------------------------------------------------------------------- */
405 /*           Misc common code for vi/emacs				     */
406 
407 /* Handle the commenting/uncommenting of a line.
408  * Returns:
409  *	1 if a carriage return is indicated (comment added)
410  *	0 if no return (comment removed)
411  *	-1 if there is an error (not enough room for comment chars)
412  * If successful, *lenp contains the new length.  Note: cursor should be
413  * moved to the start of the line after (un)commenting.
414  */
415 int
416 x_do_comment(buf, bsize, lenp)
417 	char *buf;
418 	int bsize;
419 	int *lenp;
420 {
421 	int i, j;
422 	int len = *lenp;
423 
424 	if (len == 0)
425 		return 1; /* somewhat arbitrary - it's what at&t ksh does */
426 
427 	/* Already commented? */
428 	if (buf[0] == '#') {
429 		int saw_nl = 0;
430 
431 		for (j = 0, i = 1; i < len; i++) {
432 			if (!saw_nl || buf[i] != '#')
433 				buf[j++] = buf[i];
434 			saw_nl = buf[i] == '\n';
435 		}
436 		*lenp = j;
437 		return 0;
438 	} else {
439 		int n = 1;
440 
441 		/* See if there's room for the #'s - 1 per \n */
442 		for (i = 0; i < len; i++)
443 			if (buf[i] == '\n')
444 				n++;
445 		if (len + n >= bsize)
446 			return -1;
447 		/* Now add them... */
448 		for (i = len, j = len + n; --i >= 0; ) {
449 			if (buf[i] == '\n')
450 				buf[--j] = '#';
451 			buf[--j] = buf[i];
452 		}
453 		buf[0] = '#';
454 		*lenp += n;
455 		return 1;
456 	}
457 }
458 
459 /* ------------------------------------------------------------------------- */
460 /*           Common file/command completion code for vi/emacs	             */
461 
462 
463 static char	*add_glob ARGS((const char *, int));
464 static void	glob_table ARGS((const char *, XPtrV *, struct table *));
465 static void	glob_path ARGS((int, const char *, XPtrV *, const char *));
466 
467 #if 0 /* not used... */
468 int	x_complete_word ARGS((const char *, int, int, int *, char **));
469 int
470 x_complete_word(str, slen, is_command, nwordsp, ret)
471 	const char *str;
472 	int slen;
473 	int is_command;
474 	int *nwordsp;
475 	char **ret;
476 {
477 	int nwords;
478 	int prefix_len;
479 	char **words;
480 
481 	nwords = (is_command ? x_command_glob : x_file_glob)(XCF_FULLPATH,
482 				str, slen, &words);
483 	*nwordsp = nwords;
484 	if (nwords == 0) {
485 		*ret = (char *) 0;
486 		return -1;
487 	}
488 
489 	prefix_len = x_longest_prefix(nwords, words);
490 	*ret = str_nsave(words[0], prefix_len, ATEMP);
491 	x_free_words(nwords, words);
492 	return prefix_len;
493 }
494 #endif /* 0 */
495 
496 void
497 x_print_expansions(nwords, words, is_command)
498 	int nwords;
499 	char *const *words;
500 	int is_command;
501 {
502 	int use_copy = 0;
503 	int prefix_len;
504 	XPtrV l;
505 
506 	/* Check if all matches are in the same directory (in this
507 	 * case, we want to omit the directory name)
508 	 */
509 	if (!is_command
510 	    && (prefix_len = x_longest_prefix(nwords, words)) > 0)
511 	{
512 		int i;
513 
514 		/* Special case for 1 match (prefix is whole word) */
515 		if (nwords == 1)
516 			prefix_len = x_basename(words[0], (char *) 0);
517 		/* Any (non-trailing) slashes in non-common word suffixes? */
518 		for (i = 0; i < nwords; i++)
519 			if (x_basename(words[i] + prefix_len, (char *) 0)
520 							> prefix_len)
521 				break;
522 		/* All in same directory? */
523 		if (i == nwords) {
524 			while (prefix_len > 0
525 			       && !ISDIRSEP(words[0][prefix_len - 1]))
526 				prefix_len--;
527 			use_copy = 1;
528 			XPinit(l, nwords + 1);
529 			for (i = 0; i < nwords; i++)
530 				XPput(l, words[i] + prefix_len);
531 			XPput(l, (char *) 0);
532 		}
533 	}
534 
535 	/*
536 	 * Enumerate expansions
537 	 */
538 	x_putc('\r');
539 	x_putc('\n');
540 	pr_list(use_copy ? (char **) XPptrv(l) : words);
541 
542 	if (use_copy)
543 		XPfree(l); /* not x_free_words() */
544 }
545 
546 /*
547  *  Do file globbing:
548  *	- appends * to (copy of) str if no globbing chars found
549  *	- does expansion, checks for no match, etc.
550  *	- sets *wordsp to array of matching strings
551  *	- returns number of matching strings
552  */
553 static int
554 x_file_glob(flags, str, slen, wordsp)
555 	int flags;
556 	const char *str;
557 	int slen;
558 	char ***wordsp;
559 {
560 	char *toglob;
561 	char **words;
562 	int nwords, i, idx, escaping;
563 	XPtrV w;
564 	struct source *s, *sold;
565 
566 	if (slen < 0)
567 		return 0;
568 
569 	toglob = add_glob(str, slen);
570 
571 	/* remove all escaping backward slashes */
572 	escaping = 0;
573 	for(i = 0, idx = 0; toglob[i]; i++) {
574 		if (toglob[i] == '\\' && !escaping) {
575 			escaping = 1;
576 			continue;
577 		}
578 
579 		toglob[idx] = toglob[i];
580 		idx++;
581 		if (escaping) escaping = 0;
582 	}
583 	toglob[idx] = '\0';
584 
585 	/*
586 	 * Convert "foo*" (toglob) to an array of strings (words)
587 	 */
588 	sold = source;
589 	s = pushs(SWSTR, ATEMP);
590 	s->start = s->str = toglob;
591 	source = s;
592 	if (yylex(ONEWORD) != LWORD) {
593 		source = sold;
594 		internal_errorf(0, "fileglob: substitute error");
595 		return 0;
596 	}
597 	source = sold;
598 	XPinit(w, 32);
599 	expand(yylval.cp, &w, DOGLOB|DOTILDE|DOMARKDIRS);
600 	XPput(w, NULL);
601 	words = (char **) XPclose(w);
602 
603 	for (nwords = 0; words[nwords]; nwords++)
604 		;
605 	if (nwords == 1) {
606 		struct stat statb;
607 
608 		/* Check if globbing failed (returned glob pattern),
609 		 * but be careful (E.g. toglob == "ab*" when the file
610 		 * "ab*" exists is not an error).
611 		 * Also, check for empty result - happens if we tried
612 		 * to glob something which evaluated to an empty
613 		 * string (e.g., "$FOO" when there is no FOO, etc).
614 		 */
615 		if ((strcmp(words[0], toglob) == 0
616 		     && stat(words[0], &statb) < 0)
617 		    || words[0][0] == '\0')
618 		{
619 			x_free_words(nwords, words);
620 			nwords = 0;
621 		}
622 	}
623 	afree(toglob, ATEMP);
624 
625 	*wordsp = nwords ? words : (char **) 0;
626 
627 	return nwords;
628 }
629 
630 /* Data structure used in x_command_glob() */
631 struct path_order_info {
632 	char *word;
633 	int base;
634 	int path_order;
635 };
636 
637 static int path_order_cmp(const void *aa, const void *bb);
638 
639 /* Compare routine used in x_command_glob() */
640 static int
641 path_order_cmp(aa, bb)
642 	const void *aa;
643 	const void *bb;
644 {
645 	const struct path_order_info *a = (const struct path_order_info *) aa;
646 	const struct path_order_info *b = (const struct path_order_info *) bb;
647 	int t;
648 
649 	t = FILECMP(a->word + a->base, b->word + b->base);
650 	return t ? t : a->path_order - b->path_order;
651 }
652 
653 static int
654 x_command_glob(flags, str, slen, wordsp)
655 	int flags;
656 	const char *str;
657 	int slen;
658 	char ***wordsp;
659 {
660 	char *toglob;
661 	char *pat;
662 	char *fpath;
663 	int nwords;
664 	XPtrV w;
665 	struct block *l;
666 
667 	if (slen < 0)
668 		return 0;
669 
670 	toglob = add_glob(str, slen);
671 
672 	/* Convert "foo*" (toglob) to a pattern for future use */
673 	pat = evalstr(toglob, DOPAT|DOTILDE);
674 	afree(toglob, ATEMP);
675 
676 	XPinit(w, 32);
677 
678 	glob_table(pat, &w, &keywords);
679 	glob_table(pat, &w, &aliases);
680 	glob_table(pat, &w, &builtins);
681 	for (l = e->loc; l; l = l->next)
682 		glob_table(pat, &w, &l->funs);
683 
684 	glob_path(flags, pat, &w, path);
685 	if ((fpath = str_val(global("FPATH"))) != null)
686 		glob_path(flags, pat, &w, fpath);
687 
688 	nwords = XPsize(w);
689 
690 	if (!nwords) {
691 		*wordsp = (char **) 0;
692 		XPfree(w);
693 		return 0;
694 	}
695 
696 	/* Sort entries */
697 	if (flags & XCF_FULLPATH) {
698 		/* Sort by basename, then path order */
699 		struct path_order_info *info;
700 		struct path_order_info *last_info = 0;
701 		char **words = (char **) XPptrv(w);
702 		int path_order = 0;
703 		int i;
704 
705 		info = (struct path_order_info *)
706 			alloc(sizeof(struct path_order_info) * nwords, ATEMP);
707 		for (i = 0; i < nwords; i++) {
708 			info[i].word = words[i];
709 			info[i].base = x_basename(words[i], (char *) 0);
710 			if (!last_info || info[i].base != last_info->base
711 			    || FILENCMP(words[i],
712 					last_info->word, info[i].base) != 0)
713 			{
714 				last_info = &info[i];
715 				path_order++;
716 			}
717 			info[i].path_order = path_order;
718 		}
719 		qsort(info, nwords, sizeof(struct path_order_info),
720 			path_order_cmp);
721 		for (i = 0; i < nwords; i++)
722 			words[i] = info[i].word;
723 		afree((void *) info, ATEMP);
724 	} else {
725 		/* Sort and remove duplicate entries */
726 		char **words = (char **) XPptrv(w);
727 		int i, j;
728 
729 		qsortp(XPptrv(w), (size_t) nwords, xstrcmp);
730 
731 		for (i = j = 0; i < nwords - 1; i++) {
732 			if (strcmp(words[i], words[i + 1]))
733 				words[j++] = words[i];
734 			else
735 				afree(words[i], ATEMP);
736 		}
737 		words[j++] = words[i];
738 		nwords = j;
739 		w.cur = (void **) &words[j];
740 	}
741 
742 	XPput(w, NULL);
743 	*wordsp = (char **) XPclose(w);
744 
745 	return nwords;
746 }
747 
748 #define IS_WORDC(c)	!( ctype(c, C_LEX1) || (c) == '\'' || (c) == '"'  \
749 			    || (c) == '`' || (c) == '=' || (c) == ':' )
750 
751 static int
752 x_locate_word(buf, buflen, pos, startp, is_commandp)
753 	const char *buf;
754 	int buflen;
755 	int pos;
756 	int *startp;
757 	int *is_commandp;
758 {
759 	int p;
760 	int start, end;
761 
762 	/* Bad call?  Probably should report error */
763 	if (pos < 0 || pos > buflen) {
764 		*startp = pos;
765 		*is_commandp = 0;
766 		return 0;
767 	}
768 	/* The case where pos == buflen happens to take care of itself... */
769 
770 	start = pos;
771 	/* Keep going backwards to start of word (has effect of allowing
772 	 * one blank after the end of a word)
773 	 */
774 	for (; (start > 0 && IS_WORDC(buf[start - 1]))
775 		|| (start > 1 && buf[start-2] == '\\'); start--)
776 		;
777 	/* Go forwards to end of word */
778 	for (end = start; end < buflen && IS_WORDC(buf[end]); end++) {
779 		if (buf[end] == '\\' && (end+1) < buflen)
780 			end++;
781 	}
782 
783 	if (is_commandp) {
784 		int iscmd;
785 
786 		/* Figure out if this is a command */
787 		for (p = start - 1; p >= 0 && isspace((unsigned char)buf[p]); p--)
788 			;
789 		iscmd = p < 0 || strchr(";|&()`", buf[p]);
790 		if (iscmd) {
791 			/* If command has a /, path, etc. is not searched;
792 			 * only current directory is searched, which is just
793 			 * like file globbing.
794 			 */
795 			for (p = start; p < end; p++)
796 				if (ISDIRSEP(buf[p]))
797 					break;
798 			iscmd = p == end;
799 		}
800 		*is_commandp = iscmd;
801 	}
802 
803 	*startp = start;
804 
805 	return end - start;
806 }
807 
808 int
809 x_cf_glob(flags, buf, buflen, pos, startp, endp, wordsp, is_commandp)
810 	int flags;
811 	const char *buf;
812 	int buflen;
813 	int pos;
814 	int *startp;
815 	int *endp;
816 	char ***wordsp;
817 	int *is_commandp;
818 {
819 	int len;
820 	int nwords;
821 	char **words;
822 	int is_command;
823 
824 	len = x_locate_word(buf, buflen, pos, startp, &is_command);
825 	if (!(flags & XCF_COMMAND))
826 		is_command = 0;
827 	/* Don't do command globing on zero length strings - it takes too
828 	 * long and isn't very useful.  File globs are more likely to be
829 	 * useful, so allow these.
830 	 */
831 	if (len == 0 && is_command)
832 		return 0;
833 
834 	nwords = (is_command ? x_command_glob : x_file_glob)(flags,
835 				    buf + *startp, len, &words);
836 	if (nwords == 0) {
837 		*wordsp = (char **) 0;
838 		return 0;
839 	}
840 
841 	if (is_commandp)
842 		*is_commandp = is_command;
843 	*wordsp = words;
844 	*endp = *startp + len;
845 
846 	return nwords;
847 }
848 
849 /* Given a string, copy it and possibly add a '*' to the end.  The
850  * new string is returned.
851  */
852 static char *
853 add_glob(str, slen)
854 	const char *str;
855 	int slen;
856 {
857 	char *toglob;
858 	char *s;
859 	bool_t saw_slash = FALSE;
860 
861 	if (slen < 0)
862 		return (char *) 0;
863 
864 	toglob = str_nsave(str, slen + 1, ATEMP); /* + 1 for "*" */
865 	toglob[slen] = '\0';
866 
867 	/*
868 	 * If the pathname contains a wildcard (an unquoted '*',
869 	 * '?', or '[') or parameter expansion ('$'), or a ~username
870 	 * with no trailing slash, then it is globbed based on that
871 	 * value (i.e., without the appended '*').
872 	 */
873 	for (s = toglob; *s; s++) {
874 		if (*s == '\\' && s[1])
875 			s++;
876 		else if (*s == '*' || *s == '[' || *s == '?' || *s == '$'
877 			 || (s[1] == '(' /*)*/ && strchr("*+?@!", *s)))
878 			break;
879 		else if (ISDIRSEP(*s))
880 			saw_slash = TRUE;
881 	}
882 	if (!*s && (*toglob != '~' || saw_slash)) {
883 		toglob[slen] = '*';
884 		toglob[slen + 1] = '\0';
885 	}
886 
887 	return toglob;
888 }
889 
890 /*
891  * Find longest common prefix
892  */
893 int
894 x_longest_prefix(nwords, words)
895 	int nwords;
896 	char *const *words;
897 {
898 	int i, j;
899 	int prefix_len;
900 	char *p;
901 
902 	if (nwords <= 0)
903 		return 0;
904 
905 	prefix_len = strlen(words[0]);
906 	for (i = 1; i < nwords; i++)
907 		for (j = 0, p = words[i]; j < prefix_len; j++)
908 			if (FILECHCONV((unsigned char)p[j])
909 			    != FILECHCONV((unsigned char)words[0][j])) {
910 				prefix_len = j;
911 				break;
912 			}
913 	return prefix_len;
914 }
915 
916 void
917 x_free_words(nwords, words)
918 	int nwords;
919 	char **words;
920 {
921 	int i;
922 
923 	for (i = 0; i < nwords; i++)
924 		if (words[i])
925 			afree(words[i], ATEMP);
926 	afree(words, ATEMP);
927 }
928 
929 /* Return the offset of the basename of string s (which ends at se - need not
930  * be null terminated).  Trailing slashes are ignored.  If s is just a slash,
931  * then the offset is 0 (actually, length - 1).
932  *	s		Return
933  *	/etc		1
934  *	/etc/		1
935  *	/etc//		1
936  *	/etc/fo		5
937  *	foo		0
938  *	///		2
939  *			0
940  */
941 int
942 x_basename(s, se)
943 	const char *s;
944 	const char *se;
945 {
946 	const char *p;
947 
948 	if (se == (char *) 0)
949 		se = s + strlen(s);
950 	if (s == se)
951 		return 0;
952 
953 	/* Skip trailing slashes */
954 	for (p = se - 1; p > s && ISDIRSEP(*p); p--)
955 		;
956 	for (; p > s && !ISDIRSEP(*p); p--)
957 		;
958 	if (ISDIRSEP(*p) && p + 1 < se)
959 		p++;
960 
961 	return p - s;
962 }
963 
964 /*
965  *  Apply pattern matching to a table: all table entries that match a pattern
966  * are added to wp.
967  */
968 static void
969 glob_table(pat, wp, tp)
970 	const char *pat;
971 	XPtrV *wp;
972 	struct table *tp;
973 {
974 	struct tstate ts;
975 	struct tbl *te;
976 
977 	for (twalk(&ts, tp); (te = tnext(&ts)); ) {
978 		if (gmatch(te->name, pat, FALSE))
979 			XPput(*wp, str_save(te->name, ATEMP));
980 	}
981 }
982 
983 static void
984 glob_path(flags, pat, wp, xpath)
985 	int flags;
986 	const char *pat;
987 	XPtrV *wp;
988 	const char *xpath;
989 {
990 	const char *sp, *p;
991 	char *xp;
992 	int staterr;
993 	int pathlen;
994 	int patlen;
995 	int oldsize, newsize, i, j;
996 	char **words;
997 	XString xs;
998 
999 	patlen = strlen(pat) + 1;
1000 	sp = xpath;
1001 	Xinit(xs, xp, patlen + 128, ATEMP);
1002 	while (sp) {
1003 		xp = Xstring(xs, xp);
1004 		if (!(p = strchr(sp, PATHSEP)))
1005 			p = sp + strlen(sp);
1006 		pathlen = p - sp;
1007 		if (pathlen) {
1008 			/* Copy sp into xp, stuffing any MAGIC characters
1009 			 * on the way
1010 			 */
1011 			const char *s = sp;
1012 
1013 			XcheckN(xs, xp, pathlen * 2);
1014 			while (s < p) {
1015 				if (ISMAGIC(*s))
1016 					*xp++ = MAGIC;
1017 				*xp++ = *s++;
1018 			}
1019 			*xp++ = DIRSEP;
1020 			pathlen++;
1021 		}
1022 		sp = p;
1023 		XcheckN(xs, xp, patlen);
1024 		memcpy(xp, pat, patlen);
1025 
1026 		oldsize = XPsize(*wp);
1027 		glob_str(Xstring(xs, xp), wp, 1); /* mark dirs */
1028 		newsize = XPsize(*wp);
1029 
1030 		/* Check that each match is executable... */
1031 		words = (char **) XPptrv(*wp);
1032 		for (i = j = oldsize; i < newsize; i++) {
1033 			staterr = 0;
1034 			if ((search_access(words[i], X_OK, &staterr) >= 0)
1035 			    || (staterr == EISDIR)) {
1036 				words[j] = words[i];
1037 				if (!(flags & XCF_FULLPATH))
1038 					memmove(words[j], words[j] + pathlen,
1039 						strlen(words[j] + pathlen) + 1);
1040 				j++;
1041 			} else
1042 				afree(words[i], ATEMP);
1043 		}
1044 		wp->cur = (void **) &words[j];
1045 
1046 		if (!*sp++)
1047 			break;
1048 	}
1049 	Xfree(xs, xp);
1050 }
1051 
1052 /*
1053  * if argument string contains any special characters, they will
1054  * be escaped and the result will be put into edit buffer by
1055  * keybinding-specific function
1056  */
1057 int
1058 x_escape(s, len, putbuf_func)
1059 	const char *s;
1060 	size_t len;
1061 	int putbuf_func ARGS((const char *s, size_t len));
1062 {
1063 	size_t add, wlen;
1064 	const char *ifs = str_val(local("IFS", 0));
1065 	int rval=0;
1066 
1067 	for (add = 0, wlen = len; wlen - add > 0; add++) {
1068 		if (strchr("\\$(){}*&;#|<>\"'`", s[add]) || strchr(ifs, s[add])) {
1069 			if (putbuf_func(s, add) != 0) {
1070 				rval = -1;
1071 				break;
1072 			}
1073 
1074 			putbuf_func("\\", 1);
1075 			putbuf_func(&s[add], 1);
1076 
1077 			add++;
1078 			wlen -= add;
1079 			s += add;
1080 			add = -1; /* after the increment it will go to 0 */
1081 		}
1082 	}
1083 	if (wlen > 0 && rval == 0)
1084 		rval = putbuf_func(s, wlen);
1085 
1086 	return (rval);
1087 }
1088 #endif /* EDIT */
1089