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