Home | History | Annotate | Line # | Download | only in ksh
edit.c revision 1.14
      1 /*	$NetBSD: edit.c,v 1.14 2004/07/07 19:20:09 mycroft 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.14 2004/07/07 19:20:09 mycroft 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 #if defined(TIOCGWINSZ)
    139 	if (got_sigwinch)
    140 		check_sigwinch();
    141 #endif /* TIOCGWINSZ */
    142 
    143 	x_mode(TRUE);
    144 #ifdef EMACS
    145 	if (Flag(FEMACS) || Flag(FGMACS))
    146 		i = x_emacs(buf, len);
    147 	else
    148 #endif
    149 #ifdef VI
    150 	if (Flag(FVI))
    151 		i = x_vi(buf, len);
    152 	else
    153 #endif
    154 		i = -1;		/* internal error */
    155 	x_mode(FALSE);
    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 (at) 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, options[(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 *str, int slen));
    464 static void	glob_table ARGS((const char *pat, XPtrV *wp, struct table *tp));
    465 static void	glob_path ARGS((int flags, const char *pat, XPtrV *wp,
    466 				const char *path));
    467 
    468 #if 0 /* not used... */
    469 int	x_complete_word ARGS((const char *str, int slen, int is_command,
    470 			      int *multiple, char **ret));
    471 int
    472 x_complete_word(str, slen, is_command, nwordsp, ret)
    473 	const char *str;
    474 	int slen;
    475 	int is_command;
    476 	int *nwordsp;
    477 	char **ret;
    478 {
    479 	int nwords;
    480 	int prefix_len;
    481 	char **words;
    482 
    483 	nwords = (is_command ? x_command_glob : x_file_glob)(XCF_FULLPATH,
    484 				str, slen, &words);
    485 	*nwordsp = nwords;
    486 	if (nwords == 0) {
    487 		*ret = (char *) 0;
    488 		return -1;
    489 	}
    490 
    491 	prefix_len = x_longest_prefix(nwords, words);
    492 	*ret = str_nsave(words[0], prefix_len, ATEMP);
    493 	x_free_words(nwords, words);
    494 	return prefix_len;
    495 }
    496 #endif /* 0 */
    497 
    498 void
    499 x_print_expansions(nwords, words, is_command)
    500 	int nwords;
    501 	char *const *words;
    502 	int is_command;
    503 {
    504 	int use_copy = 0;
    505 	int prefix_len;
    506 	XPtrV l;
    507 
    508 	/* Check if all matches are in the same directory (in this
    509 	 * case, we want to omit the directory name)
    510 	 */
    511 	if (!is_command
    512 	    && (prefix_len = x_longest_prefix(nwords, words)) > 0)
    513 	{
    514 		int i;
    515 
    516 		/* Special case for 1 match (prefix is whole word) */
    517 		if (nwords == 1)
    518 			prefix_len = x_basename(words[0], (char *) 0);
    519 		/* Any (non-trailing) slashes in non-common word suffixes? */
    520 		for (i = 0; i < nwords; i++)
    521 			if (x_basename(words[i] + prefix_len, (char *) 0)
    522 							> prefix_len)
    523 				break;
    524 		/* All in same directory? */
    525 		if (i == nwords) {
    526 			while (prefix_len > 0
    527 			       && !ISDIRSEP(words[0][prefix_len - 1]))
    528 				prefix_len--;
    529 			use_copy = 1;
    530 			XPinit(l, nwords + 1);
    531 			for (i = 0; i < nwords; i++)
    532 				XPput(l, words[i] + prefix_len);
    533 			XPput(l, (char *) 0);
    534 		}
    535 	}
    536 
    537 	/*
    538 	 * Enumerate expansions
    539 	 */
    540 	x_putc('\r');
    541 	x_putc('\n');
    542 	pr_list(use_copy ? (char **) XPptrv(l) : words);
    543 
    544 	if (use_copy)
    545 		XPfree(l); /* not x_free_words() */
    546 }
    547 
    548 /*
    549  *  Do file globbing:
    550  *	- appends * to (copy of) str if no globbing chars found
    551  *	- does expansion, checks for no match, etc.
    552  *	- sets *wordsp to array of matching strings
    553  *	- returns number of matching strings
    554  */
    555 static int
    556 x_file_glob(flags, str, slen, wordsp)
    557 	int flags;
    558 	const char *str;
    559 	int slen;
    560 	char ***wordsp;
    561 {
    562 	char *toglob;
    563 	char **words;
    564 	int nwords, i, idx, escaping;
    565 	XPtrV w;
    566 	struct source *s, *sold;
    567 
    568 	if (slen < 0)
    569 		return 0;
    570 
    571 	toglob = add_glob(str, slen);
    572 
    573 	/* remove all escaping backward slashes */
    574 	escaping = 0;
    575 	for(i = 0, idx = 0; toglob[i]; i++) {
    576 		if (toglob[i] == '\\' && !escaping) {
    577 			escaping = 1;
    578 			continue;
    579 		}
    580 
    581 		toglob[idx] = toglob[i];
    582 		idx++;
    583 		if (escaping) escaping = 0;
    584 	}
    585 	toglob[idx] = '\0';
    586 
    587 	/*
    588 	 * Convert "foo*" (toglob) to an array of strings (words)
    589 	 */
    590 	sold = source;
    591 	s = pushs(SWSTR, ATEMP);
    592 	s->start = s->str = toglob;
    593 	source = s;
    594 	if (yylex(ONEWORD) != LWORD) {
    595 		source = sold;
    596 		internal_errorf(0, "fileglob: substitute error");
    597 		return 0;
    598 	}
    599 	source = sold;
    600 	XPinit(w, 32);
    601 	expand(yylval.cp, &w, DOGLOB|DOTILDE|DOMARKDIRS);
    602 	XPput(w, NULL);
    603 	words = (char **) XPclose(w);
    604 
    605 	for (nwords = 0; words[nwords]; nwords++)
    606 		;
    607 	if (nwords == 1) {
    608 		struct stat statb;
    609 
    610 		/* Check if globbing failed (returned glob pattern),
    611 		 * but be careful (E.g. toglob == "ab*" when the file
    612 		 * "ab*" exists is not an error).
    613 		 * Also, check for empty result - happens if we tried
    614 		 * to glob something which evaluated to an empty
    615 		 * string (e.g., "$FOO" when there is no FOO, etc).
    616 		 */
    617 		if ((strcmp(words[0], toglob) == 0
    618 		     && stat(words[0], &statb) < 0)
    619 		    || words[0][0] == '\0')
    620 		{
    621 			x_free_words(nwords, words);
    622 			nwords = 0;
    623 		}
    624 	}
    625 	afree(toglob, ATEMP);
    626 
    627 	*wordsp = nwords ? words : (char **) 0;
    628 
    629 	return nwords;
    630 }
    631 
    632 /* Data structure used in x_command_glob() */
    633 struct path_order_info {
    634 	char *word;
    635 	int base;
    636 	int path_order;
    637 };
    638 
    639 static int path_order_cmp(const void *aa, const void *bb);
    640 
    641 /* Compare routine used in x_command_glob() */
    642 static int
    643 path_order_cmp(aa, bb)
    644 	const void *aa;
    645 	const void *bb;
    646 {
    647 	const struct path_order_info *a = (const struct path_order_info *) aa;
    648 	const struct path_order_info *b = (const struct path_order_info *) bb;
    649 	int t;
    650 
    651 	t = FILECMP(a->word + a->base, b->word + b->base);
    652 	return t ? t : a->path_order - b->path_order;
    653 }
    654 
    655 static int
    656 x_command_glob(flags, str, slen, wordsp)
    657 	int flags;
    658 	const char *str;
    659 	int slen;
    660 	char ***wordsp;
    661 {
    662 	char *toglob;
    663 	char *pat;
    664 	char *fpath;
    665 	int nwords;
    666 	XPtrV w;
    667 	struct block *l;
    668 
    669 	if (slen < 0)
    670 		return 0;
    671 
    672 	toglob = add_glob(str, slen);
    673 
    674 	/* Convert "foo*" (toglob) to a pattern for future use */
    675 	pat = evalstr(toglob, DOPAT|DOTILDE);
    676 	afree(toglob, ATEMP);
    677 
    678 	XPinit(w, 32);
    679 
    680 	glob_table(pat, &w, &keywords);
    681 	glob_table(pat, &w, &aliases);
    682 	glob_table(pat, &w, &builtins);
    683 	for (l = e->loc; l; l = l->next)
    684 		glob_table(pat, &w, &l->funs);
    685 
    686 	glob_path(flags, pat, &w, path);
    687 	if ((fpath = str_val(global("FPATH"))) != null)
    688 		glob_path(flags, pat, &w, fpath);
    689 
    690 	nwords = XPsize(w);
    691 
    692 	if (!nwords) {
    693 		*wordsp = (char **) 0;
    694 		XPfree(w);
    695 		return 0;
    696 	}
    697 
    698 	/* Sort entries */
    699 	if (flags & XCF_FULLPATH) {
    700 		/* Sort by basename, then path order */
    701 		struct path_order_info *info;
    702 		struct path_order_info *last_info = 0;
    703 		char **words = (char **) XPptrv(w);
    704 		int path_order = 0;
    705 		int i;
    706 
    707 		info = (struct path_order_info *)
    708 			alloc(sizeof(struct path_order_info) * nwords, ATEMP);
    709 		for (i = 0; i < nwords; i++) {
    710 			info[i].word = words[i];
    711 			info[i].base = x_basename(words[i], (char *) 0);
    712 			if (!last_info || info[i].base != last_info->base
    713 			    || FILENCMP(words[i],
    714 					last_info->word, info[i].base) != 0)
    715 			{
    716 				last_info = &info[i];
    717 				path_order++;
    718 			}
    719 			info[i].path_order = path_order;
    720 		}
    721 		qsort(info, nwords, sizeof(struct path_order_info),
    722 			path_order_cmp);
    723 		for (i = 0; i < nwords; i++)
    724 			words[i] = info[i].word;
    725 		afree((void *) info, ATEMP);
    726 	} else {
    727 		/* Sort and remove duplicate entries */
    728 		char **words = (char **) XPptrv(w);
    729 		int i, j;
    730 
    731 		qsortp(XPptrv(w), (size_t) nwords, xstrcmp);
    732 
    733 		for (i = j = 0; i < nwords - 1; i++) {
    734 			if (strcmp(words[i], words[i + 1]))
    735 				words[j++] = words[i];
    736 			else
    737 				afree(words[i], ATEMP);
    738 		}
    739 		words[j++] = words[i];
    740 		nwords = j;
    741 		w.cur = (void **) &words[j];
    742 	}
    743 
    744 	XPput(w, NULL);
    745 	*wordsp = (char **) XPclose(w);
    746 
    747 	return nwords;
    748 }
    749 
    750 #define IS_WORDC(c)	!( ctype(c, C_LEX1) || (c) == '\'' || (c) == '"'  \
    751 			    || (c) == '`' || (c) == '=' || (c) == ':' )
    752 
    753 static int
    754 x_locate_word(buf, buflen, pos, startp, is_commandp)
    755 	const char *buf;
    756 	int buflen;
    757 	int pos;
    758 	int *startp;
    759 	int *is_commandp;
    760 {
    761 	int p;
    762 	int start, end;
    763 
    764 	/* Bad call?  Probably should report error */
    765 	if (pos < 0 || pos > buflen) {
    766 		*startp = pos;
    767 		*is_commandp = 0;
    768 		return 0;
    769 	}
    770 	/* The case where pos == buflen happens to take care of itself... */
    771 
    772 	start = pos;
    773 	/* Keep going backwards to start of word (has effect of allowing
    774 	 * one blank after the end of a word)
    775 	 */
    776 	for (; (start > 0 && IS_WORDC(buf[start - 1]))
    777 		|| (start > 1 && buf[start-2] == '\\'); start--)
    778 		;
    779 	/* Go forwards to end of word */
    780 	for (end = start; end < buflen && IS_WORDC(buf[end]); end++) {
    781 		if (buf[end] == '\\' && (end+1) < buflen)
    782 			end++;
    783 	}
    784 
    785 	if (is_commandp) {
    786 		int iscmd;
    787 
    788 		/* Figure out if this is a command */
    789 		for (p = start - 1; p >= 0 && isspace((unsigned char)buf[p]); p--)
    790 			;
    791 		iscmd = p < 0 || strchr(";|&()`", buf[p]);
    792 		if (iscmd) {
    793 			/* If command has a /, path, etc. is not searched;
    794 			 * only current directory is searched, which is just
    795 			 * like file globbing.
    796 			 */
    797 			for (p = start; p < end; p++)
    798 				if (ISDIRSEP(buf[p]))
    799 					break;
    800 			iscmd = p == end;
    801 		}
    802 		*is_commandp = iscmd;
    803 	}
    804 
    805 	*startp = start;
    806 
    807 	return end - start;
    808 }
    809 
    810 int
    811 x_cf_glob(flags, buf, buflen, pos, startp, endp, wordsp, is_commandp)
    812 	int flags;
    813 	const char *buf;
    814 	int buflen;
    815 	int pos;
    816 	int *startp;
    817 	int *endp;
    818 	char ***wordsp;
    819 	int *is_commandp;
    820 {
    821 	int len;
    822 	int nwords;
    823 	char **words;
    824 	int is_command;
    825 
    826 	len = x_locate_word(buf, buflen, pos, startp, &is_command);
    827 	if (!(flags & XCF_COMMAND))
    828 		is_command = 0;
    829 	/* Don't do command globing on zero length strings - it takes too
    830 	 * long and isn't very useful.  File globs are more likely to be
    831 	 * useful, so allow these.
    832 	 */
    833 	if (len == 0 && is_command)
    834 		return 0;
    835 
    836 	nwords = (is_command ? x_command_glob : x_file_glob)(flags,
    837 				    buf + *startp, len, &words);
    838 	if (nwords == 0) {
    839 		*wordsp = (char **) 0;
    840 		return 0;
    841 	}
    842 
    843 	if (is_commandp)
    844 		*is_commandp = is_command;
    845 	*wordsp = words;
    846 	*endp = *startp + len;
    847 
    848 	return nwords;
    849 }
    850 
    851 /* Given a string, copy it and possibly add a '*' to the end.  The
    852  * new string is returned.
    853  */
    854 static char *
    855 add_glob(str, slen)
    856 	const char *str;
    857 	int slen;
    858 {
    859 	char *toglob;
    860 	char *s;
    861 	bool_t saw_slash = FALSE;
    862 
    863 	if (slen < 0)
    864 		return (char *) 0;
    865 
    866 	toglob = str_nsave(str, slen + 1, ATEMP); /* + 1 for "*" */
    867 	toglob[slen] = '\0';
    868 
    869 	/*
    870 	 * If the pathname contains a wildcard (an unquoted '*',
    871 	 * '?', or '[') or parameter expansion ('$'), or a ~username
    872 	 * with no trailing slash, then it is globbed based on that
    873 	 * value (i.e., without the appended '*').
    874 	 */
    875 	for (s = toglob; *s; s++) {
    876 		if (*s == '\\' && s[1])
    877 			s++;
    878 		else if (*s == '*' || *s == '[' || *s == '?' || *s == '$'
    879 			 || (s[1] == '(' /*)*/ && strchr("*+?@!", *s)))
    880 			break;
    881 		else if (ISDIRSEP(*s))
    882 			saw_slash = TRUE;
    883 	}
    884 	if (!*s && (*toglob != '~' || saw_slash)) {
    885 		toglob[slen] = '*';
    886 		toglob[slen + 1] = '\0';
    887 	}
    888 
    889 	return toglob;
    890 }
    891 
    892 /*
    893  * Find longest common prefix
    894  */
    895 int
    896 x_longest_prefix(nwords, words)
    897 	int nwords;
    898 	char *const *words;
    899 {
    900 	int i, j;
    901 	int prefix_len;
    902 	char *p;
    903 
    904 	if (nwords <= 0)
    905 		return 0;
    906 
    907 	prefix_len = strlen(words[0]);
    908 	for (i = 1; i < nwords; i++)
    909 		for (j = 0, p = words[i]; j < prefix_len; j++)
    910 			if (FILECHCONV(p[j]) != FILECHCONV(words[0][j])) {
    911 				prefix_len = j;
    912 				break;
    913 			}
    914 	return prefix_len;
    915 }
    916 
    917 void
    918 x_free_words(nwords, words)
    919 	int nwords;
    920 	char **words;
    921 {
    922 	int i;
    923 
    924 	for (i = 0; i < nwords; i++)
    925 		if (words[i])
    926 			afree(words[i], ATEMP);
    927 	afree(words, ATEMP);
    928 }
    929 
    930 /* Return the offset of the basename of string s (which ends at se - need not
    931  * be null terminated).  Trailing slashes are ignored.  If s is just a slash,
    932  * then the offset is 0 (actually, length - 1).
    933  *	s		Return
    934  *	/etc		1
    935  *	/etc/		1
    936  *	/etc//		1
    937  *	/etc/fo		5
    938  *	foo		0
    939  *	///		2
    940  *			0
    941  */
    942 int
    943 x_basename(s, se)
    944 	const char *s;
    945 	const char *se;
    946 {
    947 	const char *p;
    948 
    949 	if (se == (char *) 0)
    950 		se = s + strlen(s);
    951 	if (s == se)
    952 		return 0;
    953 
    954 	/* Skip trailing slashes */
    955 	for (p = se - 1; p > s && ISDIRSEP(*p); p--)
    956 		;
    957 	for (; p > s && !ISDIRSEP(*p); p--)
    958 		;
    959 	if (ISDIRSEP(*p) && p + 1 < se)
    960 		p++;
    961 
    962 	return p - s;
    963 }
    964 
    965 /*
    966  *  Apply pattern matching to a table: all table entries that match a pattern
    967  * are added to wp.
    968  */
    969 static void
    970 glob_table(pat, wp, tp)
    971 	const char *pat;
    972 	XPtrV *wp;
    973 	struct table *tp;
    974 {
    975 	struct tstate ts;
    976 	struct tbl *te;
    977 
    978 	for (twalk(&ts, tp); (te = tnext(&ts)); ) {
    979 		if (gmatch(te->name, pat, FALSE))
    980 			XPput(*wp, str_save(te->name, ATEMP));
    981 	}
    982 }
    983 
    984 static void
    985 glob_path(flags, pat, wp, path)
    986 	int flags;
    987 	const char *pat;
    988 	XPtrV *wp;
    989 	const char *path;
    990 {
    991 	const char *sp, *p;
    992 	char *xp;
    993 	int staterr;
    994 	int pathlen;
    995 	int patlen;
    996 	int oldsize, newsize, i, j;
    997 	char **words;
    998 	XString xs;
    999 
   1000 	patlen = strlen(pat) + 1;
   1001 	sp = path;
   1002 	Xinit(xs, xp, patlen + 128, ATEMP);
   1003 	while (sp) {
   1004 		xp = Xstring(xs, xp);
   1005 		if (!(p = strchr(sp, PATHSEP)))
   1006 			p = sp + strlen(sp);
   1007 		pathlen = p - sp;
   1008 		if (pathlen) {
   1009 			/* Copy sp into xp, stuffing any MAGIC characters
   1010 			 * on the way
   1011 			 */
   1012 			const char *s = sp;
   1013 
   1014 			XcheckN(xs, xp, pathlen * 2);
   1015 			while (s < p) {
   1016 				if (ISMAGIC(*s))
   1017 					*xp++ = MAGIC;
   1018 				*xp++ = *s++;
   1019 			}
   1020 			*xp++ = DIRSEP;
   1021 			pathlen++;
   1022 		}
   1023 		sp = p;
   1024 		XcheckN(xs, xp, patlen);
   1025 		memcpy(xp, pat, patlen);
   1026 
   1027 		oldsize = XPsize(*wp);
   1028 		glob_str(Xstring(xs, xp), wp, 1); /* mark dirs */
   1029 		newsize = XPsize(*wp);
   1030 
   1031 		/* Check that each match is executable... */
   1032 		words = (char **) XPptrv(*wp);
   1033 		for (i = j = oldsize; i < newsize; i++) {
   1034 			staterr = 0;
   1035 			if ((search_access(words[i], X_OK, &staterr) >= 0)
   1036 			    || (staterr == EISDIR)) {
   1037 				words[j] = words[i];
   1038 				if (!(flags & XCF_FULLPATH))
   1039 					memmove(words[j], words[j] + pathlen,
   1040 						strlen(words[j] + pathlen) + 1);
   1041 				j++;
   1042 			} else
   1043 				afree(words[i], ATEMP);
   1044 		}
   1045 		wp->cur = (void **) &words[j];
   1046 
   1047 		if (!*sp++)
   1048 			break;
   1049 	}
   1050 	Xfree(xs, xp);
   1051 }
   1052 
   1053 /*
   1054  * if argument string contains any special characters, they will
   1055  * be escaped and the result will be put into edit buffer by
   1056  * keybinding-specific function
   1057  */
   1058 int
   1059 x_escape(s, len, putbuf_func)
   1060 	const char *s;
   1061 	size_t len;
   1062 	int putbuf_func ARGS((const char *s, size_t len));
   1063 {
   1064 	size_t add, wlen;
   1065 	const char *ifs = str_val(local("IFS", 0));
   1066 	int rval=0;
   1067 
   1068 	for (add = 0, wlen = len; wlen - add > 0; add++) {
   1069 		if (strchr("\\$(){}*&;#|<>\"'`", s[add]) || strchr(ifs, s[add])) {
   1070 			if (putbuf_func(s, add) != 0) {
   1071 				rval = -1;
   1072 				break;
   1073 			}
   1074 
   1075 			putbuf_func("\\", 1);
   1076 			putbuf_func(&s[add], 1);
   1077 
   1078 			add++;
   1079 			wlen -= add;
   1080 			s += add;
   1081 			add = -1; /* after the increment it will go to 0 */
   1082 		}
   1083 	}
   1084 	if (wlen > 0 && rval == 0)
   1085 		rval = putbuf_func(s, wlen);
   1086 
   1087 	return (rval);
   1088 }
   1089 #endif /* EDIT */
   1090