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