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