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