Home | History | Annotate | Line # | Download | only in ksh
edit.c revision 1.18
      1 /*	$NetBSD: edit.c,v 1.18 2006/04/24 19:53:08 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.18 2006/04/24 19:53:08 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 (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, 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 	if (nwords) {
    626 		*wordsp = words;
    627 	} else {
    628 		x_free_words(nwords, words);
    629 		*wordsp = NULL;
    630 	}
    631 	return nwords;
    632 }
    633 
    634 /* Data structure used in x_command_glob() */
    635 struct path_order_info {
    636 	char *word;
    637 	int base;
    638 	int path_order;
    639 };
    640 
    641 static int path_order_cmp(const void *aa, const void *bb);
    642 
    643 /* Compare routine used in x_command_glob() */
    644 static int
    645 path_order_cmp(aa, bb)
    646 	const void *aa;
    647 	const void *bb;
    648 {
    649 	const struct path_order_info *a = (const struct path_order_info *) aa;
    650 	const struct path_order_info *b = (const struct path_order_info *) bb;
    651 	int t;
    652 
    653 	t = FILECMP(a->word + a->base, b->word + b->base);
    654 	return t ? t : a->path_order - b->path_order;
    655 }
    656 
    657 static int
    658 x_command_glob(flags, str, slen, wordsp)
    659 	int flags;
    660 	const char *str;
    661 	int slen;
    662 	char ***wordsp;
    663 {
    664 	char *toglob;
    665 	char *pat;
    666 	char *fpath;
    667 	int nwords;
    668 	XPtrV w;
    669 	struct block *l;
    670 
    671 	if (slen < 0)
    672 		return 0;
    673 
    674 	toglob = add_glob(str, slen);
    675 
    676 	/* Convert "foo*" (toglob) to a pattern for future use */
    677 	pat = evalstr(toglob, DOPAT|DOTILDE);
    678 	afree(toglob, ATEMP);
    679 
    680 	XPinit(w, 32);
    681 
    682 	glob_table(pat, &w, &keywords);
    683 	glob_table(pat, &w, &aliases);
    684 	glob_table(pat, &w, &builtins);
    685 	for (l = e->loc; l; l = l->next)
    686 		glob_table(pat, &w, &l->funs);
    687 
    688 	glob_path(flags, pat, &w, path);
    689 	if ((fpath = str_val(global("FPATH"))) != null)
    690 		glob_path(flags, pat, &w, fpath);
    691 
    692 	nwords = XPsize(w);
    693 
    694 	if (!nwords) {
    695 		*wordsp = (char **) 0;
    696 		XPfree(w);
    697 		return 0;
    698 	}
    699 
    700 	/* Sort entries */
    701 	if (flags & XCF_FULLPATH) {
    702 		/* Sort by basename, then path order */
    703 		struct path_order_info *info;
    704 		struct path_order_info *last_info = 0;
    705 		char **words = (char **) XPptrv(w);
    706 		int path_order = 0;
    707 		int i;
    708 
    709 		info = (struct path_order_info *)
    710 			alloc(sizeof(struct path_order_info) * nwords, ATEMP);
    711 		for (i = 0; i < nwords; i++) {
    712 			info[i].word = words[i];
    713 			info[i].base = x_basename(words[i], (char *) 0);
    714 			if (!last_info || info[i].base != last_info->base
    715 			    || FILENCMP(words[i],
    716 					last_info->word, info[i].base) != 0)
    717 			{
    718 				last_info = &info[i];
    719 				path_order++;
    720 			}
    721 			info[i].path_order = path_order;
    722 		}
    723 		qsort(info, nwords, sizeof(struct path_order_info),
    724 			path_order_cmp);
    725 		for (i = 0; i < nwords; i++)
    726 			words[i] = info[i].word;
    727 		afree((void *) info, ATEMP);
    728 	} else {
    729 		/* Sort and remove duplicate entries */
    730 		char **words = (char **) XPptrv(w);
    731 		int i, j;
    732 
    733 		qsortp(XPptrv(w), (size_t) nwords, xstrcmp);
    734 
    735 		for (i = j = 0; i < nwords - 1; i++) {
    736 			if (strcmp(words[i], words[i + 1]))
    737 				words[j++] = words[i];
    738 			else
    739 				afree(words[i], ATEMP);
    740 		}
    741 		words[j++] = words[i];
    742 		nwords = j;
    743 		w.cur = (void **) &words[j];
    744 	}
    745 
    746 	XPput(w, NULL);
    747 	*wordsp = (char **) XPclose(w);
    748 
    749 	return nwords;
    750 }
    751 
    752 #define IS_WORDC(c)	!( ctype(c, C_LEX1) || (c) == '\'' || (c) == '"'  \
    753 			    || (c) == '`' || (c) == '=' || (c) == ':' )
    754 
    755 static int
    756 x_locate_word(buf, buflen, pos, startp, is_commandp)
    757 	const char *buf;
    758 	int buflen;
    759 	int pos;
    760 	int *startp;
    761 	int *is_commandp;
    762 {
    763 	int p;
    764 	int start, end;
    765 
    766 	/* Bad call?  Probably should report error */
    767 	if (pos < 0 || pos > buflen) {
    768 		*startp = pos;
    769 		*is_commandp = 0;
    770 		return 0;
    771 	}
    772 	/* The case where pos == buflen happens to take care of itself... */
    773 
    774 	start = pos;
    775 	/* Keep going backwards to start of word (has effect of allowing
    776 	 * one blank after the end of a word)
    777 	 */
    778 	for (; (start > 0 && IS_WORDC(buf[start - 1]))
    779 		|| (start > 1 && buf[start-2] == '\\'); start--)
    780 		;
    781 	/* Go forwards to end of word */
    782 	for (end = start; end < buflen && IS_WORDC(buf[end]); end++) {
    783 		if (buf[end] == '\\' && (end+1) < buflen)
    784 			end++;
    785 	}
    786 
    787 	if (is_commandp) {
    788 		int iscmd;
    789 
    790 		/* Figure out if this is a command */
    791 		for (p = start - 1; p >= 0 && isspace((unsigned char)buf[p]); p--)
    792 			;
    793 		iscmd = p < 0 || strchr(";|&()`", buf[p]);
    794 		if (iscmd) {
    795 			/* If command has a /, path, etc. is not searched;
    796 			 * only current directory is searched, which is just
    797 			 * like file globbing.
    798 			 */
    799 			for (p = start; p < end; p++)
    800 				if (ISDIRSEP(buf[p]))
    801 					break;
    802 			iscmd = p == end;
    803 		}
    804 		*is_commandp = iscmd;
    805 	}
    806 
    807 	*startp = start;
    808 
    809 	return end - start;
    810 }
    811 
    812 int
    813 x_cf_glob(flags, buf, buflen, pos, startp, endp, wordsp, is_commandp)
    814 	int flags;
    815 	const char *buf;
    816 	int buflen;
    817 	int pos;
    818 	int *startp;
    819 	int *endp;
    820 	char ***wordsp;
    821 	int *is_commandp;
    822 {
    823 	int len;
    824 	int nwords;
    825 	char **words;
    826 	int is_command;
    827 
    828 	len = x_locate_word(buf, buflen, pos, startp, &is_command);
    829 	if (!(flags & XCF_COMMAND))
    830 		is_command = 0;
    831 	/* Don't do command globing on zero length strings - it takes too
    832 	 * long and isn't very useful.  File globs are more likely to be
    833 	 * useful, so allow these.
    834 	 */
    835 	if (len == 0 && is_command)
    836 		return 0;
    837 
    838 	nwords = (is_command ? x_command_glob : x_file_glob)(flags,
    839 				    buf + *startp, len, &words);
    840 	if (nwords == 0) {
    841 		*wordsp = (char **) 0;
    842 		return 0;
    843 	}
    844 
    845 	if (is_commandp)
    846 		*is_commandp = is_command;
    847 	*wordsp = words;
    848 	*endp = *startp + len;
    849 
    850 	return nwords;
    851 }
    852 
    853 /* Given a string, copy it and possibly add a '*' to the end.  The
    854  * new string is returned.
    855  */
    856 static char *
    857 add_glob(str, slen)
    858 	const char *str;
    859 	int slen;
    860 {
    861 	char *toglob;
    862 	char *s;
    863 	bool_t saw_slash = FALSE;
    864 
    865 	if (slen < 0)
    866 		return (char *) 0;
    867 
    868 	toglob = str_nsave(str, slen + 1, ATEMP); /* + 1 for "*" */
    869 	toglob[slen] = '\0';
    870 
    871 	/*
    872 	 * If the pathname contains a wildcard (an unquoted '*',
    873 	 * '?', or '[') or parameter expansion ('$'), or a ~username
    874 	 * with no trailing slash, then it is globbed based on that
    875 	 * value (i.e., without the appended '*').
    876 	 */
    877 	for (s = toglob; *s; s++) {
    878 		if (*s == '\\' && s[1])
    879 			s++;
    880 		else if (*s == '*' || *s == '[' || *s == '?' || *s == '$'
    881 			 || (s[1] == '(' /*)*/ && strchr("*+?@!", *s)))
    882 			break;
    883 		else if (ISDIRSEP(*s))
    884 			saw_slash = TRUE;
    885 	}
    886 	if (!*s && (*toglob != '~' || saw_slash)) {
    887 		toglob[slen] = '*';
    888 		toglob[slen + 1] = '\0';
    889 	}
    890 
    891 	return toglob;
    892 }
    893 
    894 /*
    895  * Find longest common prefix
    896  */
    897 int
    898 x_longest_prefix(nwords, words)
    899 	int nwords;
    900 	char *const *words;
    901 {
    902 	int i, j;
    903 	int prefix_len;
    904 	char *p;
    905 
    906 	if (nwords <= 0)
    907 		return 0;
    908 
    909 	prefix_len = strlen(words[0]);
    910 	for (i = 1; i < nwords; i++)
    911 		for (j = 0, p = words[i]; j < prefix_len; j++)
    912 			if (FILECHCONV((unsigned char)p[j])
    913 			    != FILECHCONV((unsigned char)words[0][j])) {
    914 				prefix_len = j;
    915 				break;
    916 			}
    917 	return prefix_len;
    918 }
    919 
    920 void
    921 x_free_words(nwords, words)
    922 	int nwords;
    923 	char **words;
    924 {
    925 	int i;
    926 
    927 	for (i = 0; i < nwords; i++)
    928 		if (words[i])
    929 			afree(words[i], ATEMP);
    930 	afree(words, ATEMP);
    931 }
    932 
    933 /* Return the offset of the basename of string s (which ends at se - need not
    934  * be null terminated).  Trailing slashes are ignored.  If s is just a slash,
    935  * then the offset is 0 (actually, length - 1).
    936  *	s		Return
    937  *	/etc		1
    938  *	/etc/		1
    939  *	/etc//		1
    940  *	/etc/fo		5
    941  *	foo		0
    942  *	///		2
    943  *			0
    944  */
    945 int
    946 x_basename(s, se)
    947 	const char *s;
    948 	const char *se;
    949 {
    950 	const char *p;
    951 
    952 	if (se == (char *) 0)
    953 		se = s + strlen(s);
    954 	if (s == se)
    955 		return 0;
    956 
    957 	/* Skip trailing slashes */
    958 	for (p = se - 1; p > s && ISDIRSEP(*p); p--)
    959 		;
    960 	for (; p > s && !ISDIRSEP(*p); p--)
    961 		;
    962 	if (ISDIRSEP(*p) && p + 1 < se)
    963 		p++;
    964 
    965 	return p - s;
    966 }
    967 
    968 /*
    969  *  Apply pattern matching to a table: all table entries that match a pattern
    970  * are added to wp.
    971  */
    972 static void
    973 glob_table(pat, wp, tp)
    974 	const char *pat;
    975 	XPtrV *wp;
    976 	struct table *tp;
    977 {
    978 	struct tstate ts;
    979 	struct tbl *te;
    980 
    981 	for (twalk(&ts, tp); (te = tnext(&ts)); ) {
    982 		if (gmatch(te->name, pat, FALSE))
    983 			XPput(*wp, str_save(te->name, ATEMP));
    984 	}
    985 }
    986 
    987 static void
    988 glob_path(flags, pat, wp, xpath)
    989 	int flags;
    990 	const char *pat;
    991 	XPtrV *wp;
    992 	const char *xpath;
    993 {
    994 	const char *sp, *p;
    995 	char *xp;
    996 	int staterr;
    997 	int pathlen;
    998 	int patlen;
    999 	int oldsize, newsize, i, j;
   1000 	char **words;
   1001 	XString xs;
   1002 
   1003 	patlen = strlen(pat) + 1;
   1004 	sp = xpath;
   1005 	Xinit(xs, xp, patlen + 128, ATEMP);
   1006 	while (sp) {
   1007 		xp = Xstring(xs, xp);
   1008 		if (!(p = strchr(sp, PATHSEP)))
   1009 			p = sp + strlen(sp);
   1010 		pathlen = p - sp;
   1011 		if (pathlen) {
   1012 			/* Copy sp into xp, stuffing any MAGIC characters
   1013 			 * on the way
   1014 			 */
   1015 			const char *s = sp;
   1016 
   1017 			XcheckN(xs, xp, pathlen * 2);
   1018 			while (s < p) {
   1019 				if (ISMAGIC(*s))
   1020 					*xp++ = MAGIC;
   1021 				*xp++ = *s++;
   1022 			}
   1023 			*xp++ = DIRSEP;
   1024 			pathlen++;
   1025 		}
   1026 		sp = p;
   1027 		XcheckN(xs, xp, patlen);
   1028 		memcpy(xp, pat, patlen);
   1029 
   1030 		oldsize = XPsize(*wp);
   1031 		glob_str(Xstring(xs, xp), wp, 1); /* mark dirs */
   1032 		newsize = XPsize(*wp);
   1033 
   1034 		/* Check that each match is executable... */
   1035 		words = (char **) XPptrv(*wp);
   1036 		for (i = j = oldsize; i < newsize; i++) {
   1037 			staterr = 0;
   1038 			if ((search_access(words[i], X_OK, &staterr) >= 0)
   1039 			    || (staterr == EISDIR)) {
   1040 				words[j] = words[i];
   1041 				if (!(flags & XCF_FULLPATH))
   1042 					memmove(words[j], words[j] + pathlen,
   1043 						strlen(words[j] + pathlen) + 1);
   1044 				j++;
   1045 			} else
   1046 				afree(words[i], ATEMP);
   1047 		}
   1048 		wp->cur = (void **) &words[j];
   1049 
   1050 		if (!*sp++)
   1051 			break;
   1052 	}
   1053 	Xfree(xs, xp);
   1054 }
   1055 
   1056 /*
   1057  * if argument string contains any special characters, they will
   1058  * be escaped and the result will be put into edit buffer by
   1059  * keybinding-specific function
   1060  */
   1061 int
   1062 x_escape(s, len, putbuf_func)
   1063 	const char *s;
   1064 	size_t len;
   1065 	int putbuf_func ARGS((const char *s, size_t len));
   1066 {
   1067 	size_t add, wlen;
   1068 	const char *ifs = str_val(local("IFS", 0));
   1069 	int rval=0;
   1070 
   1071 	for (add = 0, wlen = len; wlen - add > 0; add++) {
   1072 		if (strchr("\\$(){}*&;#|<>\"'`", s[add]) || strchr(ifs, s[add])) {
   1073 			if (putbuf_func(s, add) != 0) {
   1074 				rval = -1;
   1075 				break;
   1076 			}
   1077 
   1078 			putbuf_func("\\", 1);
   1079 			putbuf_func(&s[add], 1);
   1080 
   1081 			add++;
   1082 			wlen -= add;
   1083 			s += add;
   1084 			add = -1; /* after the increment it will go to 0 */
   1085 		}
   1086 	}
   1087 	if (wlen > 0 && rval == 0)
   1088 		rval = putbuf_func(s, wlen);
   1089 
   1090 	return (rval);
   1091 }
   1092 #endif /* EDIT */
   1093