Home | History | Annotate | Download | only in src
      1 /*	$OpenBSD: edit.c,v 1.37 2013/01/21 10:13:24 halex Exp $	*/
      2 /*	$OpenBSD: edit.h,v 1.9 2011/05/30 17:14:35 martynas Exp $	*/
      3 /*	$OpenBSD: emacs.c,v 1.44 2011/09/05 04:50:33 marco Exp $	*/
      4 /*	$OpenBSD: vi.c,v 1.26 2009/06/29 22:50:19 martynas Exp $	*/
      5 
      6 /*-
      7  * Copyright (c) 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010,
      8  *		 2011, 2012, 2013
      9  *	Thorsten Glaser <tg (at) mirbsd.org>
     10  *
     11  * Provided that these terms and disclaimer and all copyright notices
     12  * are retained or reproduced in an accompanying document, permission
     13  * is granted to deal in this work without restriction, including un-
     14  * limited rights to use, publicly perform, distribute, sell, modify,
     15  * merge, give away, or sublicence.
     16  *
     17  * This work is provided "AS IS" and WITHOUT WARRANTY of any kind, to
     18  * the utmost extent permitted by applicable law, neither express nor
     19  * implied; without malicious intent or gross negligence. In no event
     20  * may a licensor, author or contributor be held liable for indirect,
     21  * direct, other damage, loss, or other issues arising in any way out
     22  * of dealing in the work, even if advised of the possibility of such
     23  * damage or existence of a defect, except proven that it results out
     24  * of said person's immediate fault when using the work as intended.
     25  */
     26 
     27 #include "sh.h"
     28 
     29 #ifndef MKSH_NO_CMDLINE_EDITING
     30 
     31 __RCSID("$MirOS: src/bin/mksh/edit.c,v 1.265 2013/02/10 19:05:36 tg Exp $");
     32 
     33 /*
     34  * in later versions we might use libtermcap for this, but since external
     35  * dependencies are problematic, this has not yet been decided on; another
     36  * good string is "\033c" except on hardware terminals like the DEC VT420
     37  * which do a full power cycle then...
     38  */
     39 #ifndef MKSH_CLS_STRING
     40 #define MKSH_CLS_STRING		"\033[;H\033[J"
     41 #endif
     42 #ifndef MKSH_CLRTOEOL_STRING
     43 #define MKSH_CLRTOEOL_STRING	"\033[K"
     44 #endif
     45 
     46 /* tty driver characters we are interested in */
     47 typedef struct {
     48 	int erase;
     49 	int kill;
     50 	int werase;
     51 	int intr;
     52 	int quit;
     53 	int eof;
     54 } X_chars;
     55 
     56 static X_chars edchars;
     57 
     58 /* x_cf_glob() flags */
     59 #define XCF_COMMAND	BIT(0)	/* Do command completion */
     60 #define XCF_FILE	BIT(1)	/* Do file completion */
     61 #define XCF_FULLPATH	BIT(2)	/* command completion: store full path */
     62 #define XCF_COMMAND_FILE (XCF_COMMAND | XCF_FILE)
     63 #define XCF_IS_COMMAND	BIT(3)	/* return flag: is command */
     64 #define XCF_IS_NOSPACE	BIT(4)	/* return flag: do not append a space */
     65 
     66 static char editmode;
     67 static int xx_cols;			/* for Emacs mode */
     68 static int modified;			/* buffer has been "modified" */
     69 static char holdbuf[LINE];		/* place to hold last edit buffer */
     70 
     71 static int x_getc(void);
     72 static void x_putcf(int);
     73 static void x_modified(void);
     74 static void x_mode(bool);
     75 static int x_do_comment(char *, ssize_t, ssize_t *);
     76 static void x_print_expansions(int, char * const *, bool);
     77 static int x_cf_glob(int *, const char *, int, int, int *, int *, char ***);
     78 static size_t x_longest_prefix(int, char * const *);
     79 static void x_glob_hlp_add_qchar(char *);
     80 static char *x_glob_hlp_tilde_and_rem_qchar(char *, bool);
     81 static int x_basename(const char *, const char *);
     82 static void x_free_words(int, char **);
     83 static int x_escape(const char *, size_t, int (*)(const char *, size_t));
     84 static int x_emacs(char *, size_t);
     85 static void x_init_prompt(void);
     86 #if !MKSH_S_NOVI
     87 static int x_vi(char *, size_t);
     88 #endif
     89 
     90 #define x_flush()	shf_flush(shl_out)
     91 #if defined(MKSH_SMALL) && !defined(MKSH_SMALL_BUT_FAST)
     92 #define x_putc(c)	x_putcf(c)
     93 #else
     94 #define x_putc(c)	shf_putc((c), shl_out)
     95 #endif
     96 
     97 static int path_order_cmp(const void *, const void *);
     98 static void glob_table(const char *, XPtrV *, struct table *);
     99 static void glob_path(int, const char *, XPtrV *, const char *);
    100 static int x_file_glob(int *, char *, char ***);
    101 static int x_command_glob(int, char *, char ***);
    102 static int x_locate_word(const char *, int, int, int *, bool *);
    103 
    104 static int x_e_getmbc(char *);
    105 static int x_e_rebuildline(const char *);
    106 
    107 /* +++ generic editing functions +++ */
    108 
    109 /*
    110  * read an edited command line
    111  */
    112 int
    113 x_read(char *buf, size_t len)
    114 {
    115 	int i;
    116 
    117 	x_mode(true);
    118 	modified = 1;
    119 	if (Flag(FEMACS) || Flag(FGMACS))
    120 		i = x_emacs(buf, len);
    121 #if !MKSH_S_NOVI
    122 	else if (Flag(FVI))
    123 		i = x_vi(buf, len);
    124 #endif
    125 	else
    126 		/* internal error */
    127 		i = -1;
    128 	editmode = 0;
    129 	x_mode(false);
    130 	return (i);
    131 }
    132 
    133 /* tty I/O */
    134 
    135 static int
    136 x_getc(void)
    137 {
    138 	char c;
    139 	ssize_t n;
    140 
    141 	while ((n = blocking_read(STDIN_FILENO, &c, 1)) < 0 && errno == EINTR)
    142 		if (trap) {
    143 			x_mode(false);
    144 			runtraps(0);
    145 #ifdef SIGWINCH
    146 			if (got_winch) {
    147 				change_winsz();
    148 				if (x_cols != xx_cols && editmode == 1) {
    149 					/* redraw line in Emacs mode */
    150 					xx_cols = x_cols;
    151 					x_e_rebuildline(MKSH_CLRTOEOL_STRING);
    152 				}
    153 			}
    154 #endif
    155 			x_mode(true);
    156 		}
    157 	return ((n == 1) ? (int)(unsigned char)c : -1);
    158 }
    159 
    160 static void
    161 x_putcf(int c)
    162 {
    163 	shf_putc(c, shl_out);
    164 }
    165 
    166 /*********************************
    167  * Misc common code for vi/emacs *
    168  *********************************/
    169 
    170 /*-
    171  * Handle the commenting/uncommenting of a line.
    172  * Returns:
    173  *	1 if a carriage return is indicated (comment added)
    174  *	0 if no return (comment removed)
    175  *	-1 if there is an error (not enough room for comment chars)
    176  * If successful, *lenp contains the new length. Note: cursor should be
    177  * moved to the start of the line after (un)commenting.
    178  */
    179 static int
    180 x_do_comment(char *buf, ssize_t bsize, ssize_t *lenp)
    181 {
    182 	ssize_t i, j, len = *lenp;
    183 
    184 	if (len == 0)
    185 		/* somewhat arbitrary - it's what AT&T ksh does */
    186 		return (1);
    187 
    188 	/* Already commented? */
    189 	if (buf[0] == '#') {
    190 		bool saw_nl = false;
    191 
    192 		for (j = 0, i = 1; i < len; i++) {
    193 			if (!saw_nl || buf[i] != '#')
    194 				buf[j++] = buf[i];
    195 			saw_nl = buf[i] == '\n';
    196 		}
    197 		*lenp = j;
    198 		return (0);
    199 	} else {
    200 		int n = 1;
    201 
    202 		/* See if there's room for the #s - 1 per \n */
    203 		for (i = 0; i < len; i++)
    204 			if (buf[i] == '\n')
    205 				n++;
    206 		if (len + n >= bsize)
    207 			return (-1);
    208 		/* Now add them... */
    209 		for (i = len, j = len + n; --i >= 0; ) {
    210 			if (buf[i] == '\n')
    211 				buf[--j] = '#';
    212 			buf[--j] = buf[i];
    213 		}
    214 		buf[0] = '#';
    215 		*lenp += n;
    216 		return (1);
    217 	}
    218 }
    219 
    220 /****************************************************
    221  * Common file/command completion code for vi/emacs *
    222  ****************************************************/
    223 
    224 static void
    225 x_print_expansions(int nwords, char * const *words, bool is_command)
    226 {
    227 	bool use_copy = false;
    228 	int prefix_len;
    229 	XPtrV l = { NULL, 0, 0 };
    230 
    231 	/*
    232 	 * Check if all matches are in the same directory (in this
    233 	 * case, we want to omit the directory name)
    234 	 */
    235 	if (!is_command &&
    236 	    (prefix_len = x_longest_prefix(nwords, words)) > 0) {
    237 		int i;
    238 
    239 		/* Special case for 1 match (prefix is whole word) */
    240 		if (nwords == 1)
    241 			prefix_len = x_basename(words[0], NULL);
    242 		/* Any (non-trailing) slashes in non-common word suffixes? */
    243 		for (i = 0; i < nwords; i++)
    244 			if (x_basename(words[i] + prefix_len, NULL) >
    245 			    prefix_len)
    246 				break;
    247 		/* All in same directory? */
    248 		if (i == nwords) {
    249 			while (prefix_len > 0 && words[0][prefix_len - 1] != '/')
    250 				prefix_len--;
    251 			use_copy = true;
    252 			XPinit(l, nwords + 1);
    253 			for (i = 0; i < nwords; i++)
    254 				XPput(l, words[i] + prefix_len);
    255 			XPput(l, NULL);
    256 		}
    257 	}
    258 	/*
    259 	 * Enumerate expansions
    260 	 */
    261 	x_putc('\r');
    262 	x_putc('\n');
    263 	pr_list(use_copy ? (char **)XPptrv(l) : words);
    264 
    265 	if (use_copy)
    266 		/* not x_free_words() */
    267 		XPfree(l);
    268 }
    269 
    270 /*
    271  * Convert backslash-escaped string to QCHAR-escaped
    272  * string useful for globbing; loses QCHAR unless it
    273  * can squeeze in, eg. by previous loss of backslash
    274  */
    275 static void
    276 x_glob_hlp_add_qchar(char *cp)
    277 {
    278 	char ch, *dp = cp;
    279 	bool escaping = false;
    280 
    281 	while ((ch = *cp++)) {
    282 		if (ch == '\\' && !escaping) {
    283 			escaping = true;
    284 			continue;
    285 		}
    286 		if (escaping || (ch == QCHAR && (cp - dp) > 1)) {
    287 			/*
    288 			 * empirically made list of chars to escape
    289 			 * for globbing as well as QCHAR itself
    290 			 */
    291 			switch (ch) {
    292 			case QCHAR:
    293 			case '$':
    294 			case '*':
    295 			case '?':
    296 			case '[':
    297 			case '\\':
    298 			case '`':
    299 				*dp++ = QCHAR;
    300 				break;
    301 			}
    302 			escaping = false;
    303 		}
    304 		*dp++ = ch;
    305 	}
    306 	*dp = '\0';
    307 }
    308 
    309 /*
    310  * Run tilde expansion on argument string, return the result
    311  * after unescaping; if the flag is set, the original string
    312  * is freed if changed and assumed backslash-escaped, if not
    313  * it is assumed QCHAR-escaped
    314  */
    315 static char *
    316 x_glob_hlp_tilde_and_rem_qchar(char *s, bool magic_flag)
    317 {
    318 	char ch, *cp, *dp;
    319 
    320 	/*
    321 	 * On the string, check whether we have a tilde expansion,
    322 	 * and if so, discern "~foo/bar" and "~/baz" from "~blah";
    323 	 * if we have a directory part (the former), try to expand
    324 	 */
    325 	if (*s == '~' && (cp = strchr(s, '/')) != NULL) {
    326 		/* ok, so split into "~foo"/"bar" or "~"/"baz" */
    327 		*cp++ = 0;
    328 		/* try to expand the tilde */
    329 		if (!(dp = tilde(s + 1))) {
    330 			/* nope, revert damage */
    331 			*--cp = '/';
    332 		} else {
    333 			/* ok, expand and replace */
    334 			cp = shf_smprintf("%s/%s", dp, cp);
    335 			if (magic_flag)
    336 				afree(s, ATEMP);
    337 			s = cp;
    338 		}
    339 	}
    340 
    341 	/* ... convert it from backslash-escaped via QCHAR-escaped... */
    342 	if (magic_flag)
    343 		x_glob_hlp_add_qchar(s);
    344 	/* ... to unescaped, for comparison with the matches */
    345 	cp = dp = s;
    346 
    347 	while ((ch = *cp++)) {
    348 		if (ch == QCHAR && !(ch = *cp++))
    349 			break;
    350 		*dp++ = ch;
    351 	}
    352 	*dp = '\0';
    353 
    354 	return (s);
    355 }
    356 
    357 /**
    358  * Do file globbing:
    359  *	- does expansion, checks for no match, etc.
    360  *	- sets *wordsp to array of matching strings
    361  *	- returns number of matching strings
    362  */
    363 static int
    364 x_file_glob(int *flagsp, char *toglob, char ***wordsp)
    365 {
    366 	char **words, *cp;
    367 	int nwords;
    368 	XPtrV w;
    369 	struct source *s, *sold;
    370 
    371 	/* remove all escaping backward slashes */
    372 	x_glob_hlp_add_qchar(toglob);
    373 
    374 	/*
    375 	 * Convert "foo*" (toglob) to an array of strings (words)
    376 	 */
    377 	sold = source;
    378 	s = pushs(SWSTR, ATEMP);
    379 	s->start = s->str = toglob;
    380 	source = s;
    381 	if (yylex(ONEWORD | LQCHAR) != LWORD) {
    382 		source = sold;
    383 		internal_warningf("%s: %s", "fileglob", "bad substitution");
    384 		return (0);
    385 	}
    386 	source = sold;
    387 	afree(s, ATEMP);
    388 	XPinit(w, 32);
    389 	cp = yylval.cp;
    390 	while (*cp == CHAR || *cp == QCHAR)
    391 		cp += 2;
    392 	nwords = DOGLOB | DOTILDE | DOMARKDIRS;
    393 	if (*cp != EOS) {
    394 		/* probably a $FOO expansion */
    395 		*flagsp |= XCF_IS_NOSPACE;
    396 		/* this always results in at most one match */
    397 		nwords = 0;
    398 	}
    399 	expand(yylval.cp, &w, nwords);
    400 	XPput(w, NULL);
    401 	words = (char **)XPclose(w);
    402 
    403 	for (nwords = 0; words[nwords]; nwords++)
    404 		;
    405 	if (nwords == 1) {
    406 		struct stat statb;
    407 
    408 		/* Expand any tilde and drop all QCHAR for comparison */
    409 		toglob = x_glob_hlp_tilde_and_rem_qchar(toglob, false);
    410 
    411 		/*
    412 		 * Check if globbing failed (returned glob pattern),
    413 		 * but be careful (e.g. toglob == "ab*" when the file
    414 		 * "ab*" exists is not an error).
    415 		 * Also, check for empty result - happens if we tried
    416 		 * to glob something which evaluated to an empty
    417 		 * string (e.g., "$FOO" when there is no FOO, etc).
    418 		 */
    419 		if ((strcmp(words[0], toglob) == 0 &&
    420 		    stat(words[0], &statb) < 0) ||
    421 		    words[0][0] == '\0') {
    422 			x_free_words(nwords, words);
    423 			words = NULL;
    424 			nwords = 0;
    425 		}
    426 	}
    427 
    428 	if ((*wordsp = nwords ? words : NULL) == NULL && words != NULL)
    429 		x_free_words(nwords, words);
    430 
    431 	return (nwords);
    432 }
    433 
    434 /* Data structure used in x_command_glob() */
    435 struct path_order_info {
    436 	char *word;
    437 	int base;
    438 	int path_order;
    439 };
    440 
    441 /* Compare routine used in x_command_glob() */
    442 static int
    443 path_order_cmp(const void *aa, const void *bb)
    444 {
    445 	const struct path_order_info *a = (const struct path_order_info *)aa;
    446 	const struct path_order_info *b = (const struct path_order_info *)bb;
    447 	int t;
    448 
    449 	t = strcmp(a->word + a->base, b->word + b->base);
    450 	return (t ? t : a->path_order - b->path_order);
    451 }
    452 
    453 static int
    454 x_command_glob(int flags, char *toglob, char ***wordsp)
    455 {
    456 	char *pat, *fpath;
    457 	size_t nwords;
    458 	XPtrV w;
    459 	struct block *l;
    460 
    461 	/* Convert "foo*" (toglob) to a pattern for future use */
    462 	pat = evalstr(toglob, DOPAT | DOTILDE);
    463 
    464 	XPinit(w, 32);
    465 
    466 	glob_table(pat, &w, &keywords);
    467 	glob_table(pat, &w, &aliases);
    468 	glob_table(pat, &w, &builtins);
    469 	for (l = e->loc; l; l = l->next)
    470 		glob_table(pat, &w, &l->funs);
    471 
    472 	glob_path(flags, pat, &w, path);
    473 	if ((fpath = str_val(global("FPATH"))) != null)
    474 		glob_path(flags, pat, &w, fpath);
    475 
    476 	nwords = XPsize(w);
    477 
    478 	if (!nwords) {
    479 		*wordsp = NULL;
    480 		XPfree(w);
    481 		return (0);
    482 	}
    483 	/* Sort entries */
    484 	if (flags & XCF_FULLPATH) {
    485 		/* Sort by basename, then path order */
    486 		struct path_order_info *info, *last_info = NULL;
    487 		char **words = (char **)XPptrv(w);
    488 		size_t i, path_order = 0;
    489 
    490 		info = (struct path_order_info *)
    491 		    alloc2(nwords, sizeof(struct path_order_info), ATEMP);
    492 		for (i = 0; i < nwords; i++) {
    493 			info[i].word = words[i];
    494 			info[i].base = x_basename(words[i], NULL);
    495 			if (!last_info || info[i].base != last_info->base ||
    496 			    strncmp(words[i], last_info->word, info[i].base) != 0) {
    497 				last_info = &info[i];
    498 				path_order++;
    499 			}
    500 			info[i].path_order = path_order;
    501 		}
    502 		qsort(info, nwords, sizeof(struct path_order_info),
    503 		    path_order_cmp);
    504 		for (i = 0; i < nwords; i++)
    505 			words[i] = info[i].word;
    506 		afree(info, ATEMP);
    507 	} else {
    508 		/* Sort and remove duplicate entries */
    509 		char **words = (char **)XPptrv(w);
    510 		size_t i, j;
    511 
    512 		qsort(words, nwords, sizeof(void *), xstrcmp);
    513 		for (i = j = 0; i < nwords - 1; i++) {
    514 			if (strcmp(words[i], words[i + 1]))
    515 				words[j++] = words[i];
    516 			else
    517 				afree(words[i], ATEMP);
    518 		}
    519 		words[j++] = words[i];
    520 		w.len = nwords = j;
    521 	}
    522 
    523 	XPput(w, NULL);
    524 	*wordsp = (char **)XPclose(w);
    525 
    526 	return (nwords);
    527 }
    528 
    529 #define IS_WORDC(c)	(!ctype(c, C_LEX1) && (c) != '\'' && (c) != '"' && \
    530 			    (c) != '`' && (c) != '=' && (c) != ':')
    531 
    532 static int
    533 x_locate_word(const char *buf, int buflen, int pos, int *startp,
    534     bool *is_commandp)
    535 {
    536 	int start, end;
    537 
    538 	/* Bad call? Probably should report error */
    539 	if (pos < 0 || pos > buflen) {
    540 		*startp = pos;
    541 		*is_commandp = false;
    542 		return (0);
    543 	}
    544 	/* The case where pos == buflen happens to take care of itself... */
    545 
    546 	start = pos;
    547 	/*
    548 	 * Keep going backwards to start of word (has effect of allowing
    549 	 * one blank after the end of a word)
    550 	 */
    551 	for (; (start > 0 && IS_WORDC(buf[start - 1])) ||
    552 	    (start > 1 && buf[start - 2] == '\\'); start--)
    553 		;
    554 	/* Go forwards to end of word */
    555 	for (end = start; end < buflen && IS_WORDC(buf[end]); end++) {
    556 		if (buf[end] == '\\' && (end + 1) < buflen)
    557 			end++;
    558 	}
    559 
    560 	if (is_commandp) {
    561 		bool iscmd;
    562 		int p = start - 1;
    563 
    564 		/* Figure out if this is a command */
    565 		while (p >= 0 && ksh_isspace(buf[p]))
    566 			p--;
    567 		iscmd = p < 0 || vstrchr(";|&()`", buf[p]);
    568 		if (iscmd) {
    569 			/*
    570 			 * If command has a /, path, etc. is not searched;
    571 			 * only current directory is searched which is just
    572 			 * like file globbing.
    573 			 */
    574 			for (p = start; p < end; p++)
    575 				if (buf[p] == '/')
    576 					break;
    577 			iscmd = p == end;
    578 		}
    579 		*is_commandp = iscmd;
    580 	}
    581 	*startp = start;
    582 
    583 	return (end - start);
    584 }
    585 
    586 static int
    587 x_cf_glob(int *flagsp, const char *buf, int buflen, int pos, int *startp,
    588     int *endp, char ***wordsp)
    589 {
    590 	int len, nwords = 0;
    591 	char **words = NULL;
    592 	bool is_command;
    593 
    594 	mkssert(buf != NULL);
    595 
    596 	len = x_locate_word(buf, buflen, pos, startp, &is_command);
    597 	if (!((*flagsp) & XCF_COMMAND))
    598 		is_command = false;
    599 	/*
    600 	 * Don't do command globing on zero length strings - it takes too
    601 	 * long and isn't very useful. File globs are more likely to be
    602 	 * useful, so allow these.
    603 	 */
    604 	if (len == 0 && is_command)
    605 		return (0);
    606 
    607 	if (len >= 0) {
    608 		char *toglob, *s;
    609 
    610 		/*
    611 		 * Given a string, copy it and possibly add a '*' to the end.
    612 		 */
    613 
    614 		strndupx(toglob, buf + *startp, len + /* the '*' */ 1, ATEMP);
    615 		toglob[len] = '\0';
    616 
    617 		/*
    618 		 * If the pathname contains a wildcard (an unquoted '*',
    619 		 * '?', or '[') or an extglob, then it is globbed based
    620 		 * on that value (i.e., without the appended '*'). Same
    621 		 * for parameter substitutions (as in cat $HOME/.ss)
    622 		 * without appending a trailing space (LP: #710539), as
    623 		 * well as for ~foo (but not ~foo/).
    624 		 */
    625 		for (s = toglob; *s; s++) {
    626 			if (*s == '\\' && s[1])
    627 				s++;
    628 			else if (*s == '?' || *s == '*' || *s == '[' ||
    629 			    *s == '$' ||
    630 			    /* ?() *() +() @() !() but two already checked */
    631 			    (s[1] == '(' /*)*/ &&
    632 			    (*s == '+' || *s == '@' || *s == '!'))) {
    633 				/*
    634 				 * just expand based on the extglob
    635 				 * or parameter
    636 				 */
    637 				goto dont_add_glob;
    638 			}
    639 		}
    640 
    641 		if (*toglob == '~' && !vstrchr(toglob, '/')) {
    642 			/* neither for '~foo' (but '~foo/bar') */
    643 			*flagsp |= XCF_IS_NOSPACE;
    644 			goto dont_add_glob;
    645 		}
    646 
    647 		/* append a glob */
    648 		toglob[len] = '*';
    649 		toglob[len + 1] = '\0';
    650  dont_add_glob:
    651 		/*
    652 		 * Expand (glob) it now.
    653 		 */
    654 
    655 		nwords = is_command ?
    656 		    x_command_glob(*flagsp, toglob, &words) :
    657 		    x_file_glob(flagsp, toglob, &words);
    658 		afree(toglob, ATEMP);
    659 	}
    660 	if (nwords == 0) {
    661 		*wordsp = NULL;
    662 		return (0);
    663 	}
    664 	if (is_command)
    665 		*flagsp |= XCF_IS_COMMAND;
    666 	*wordsp = words;
    667 	*endp = *startp + len;
    668 
    669 	return (nwords);
    670 }
    671 
    672 /*
    673  * Find longest common prefix
    674  */
    675 static size_t
    676 x_longest_prefix(int nwords, char * const * words)
    677 {
    678 	int i;
    679 	size_t j, prefix_len;
    680 	char *p;
    681 
    682 	if (nwords <= 0)
    683 		return (0);
    684 
    685 	prefix_len = strlen(words[0]);
    686 	for (i = 1; i < nwords; i++)
    687 		for (j = 0, p = words[i]; j < prefix_len; j++)
    688 			if (p[j] != words[0][j]) {
    689 				prefix_len = j;
    690 				break;
    691 			}
    692 	/* false for nwords==1 as 0 = words[0][prefix_len] then */
    693 	if (UTFMODE && prefix_len && (words[0][prefix_len] & 0xC0) == 0x80)
    694 		while (prefix_len && (words[0][prefix_len] & 0xC0) != 0xC0)
    695 			--prefix_len;
    696 	return (prefix_len);
    697 }
    698 
    699 static void
    700 x_free_words(int nwords, char **words)
    701 {
    702 	while (nwords)
    703 		afree(words[--nwords], ATEMP);
    704 	afree(words, ATEMP);
    705 }
    706 
    707 /*-
    708  * Return the offset of the basename of string s (which ends at se - need not
    709  * be null terminated). Trailing slashes are ignored. If s is just a slash,
    710  * then the offset is 0 (actually, length - 1).
    711  *	s		Return
    712  *	/etc		1
    713  *	/etc/		1
    714  *	/etc//		1
    715  *	/etc/fo		5
    716  *	foo		0
    717  *	///		2
    718  *			0
    719  */
    720 static int
    721 x_basename(const char *s, const char *se)
    722 {
    723 	const char *p;
    724 
    725 	if (se == NULL)
    726 		se = s + strlen(s);
    727 	if (s == se)
    728 		return (0);
    729 
    730 	/* Skip trailing slashes */
    731 	for (p = se - 1; p > s && *p == '/'; p--)
    732 		;
    733 	for (; p > s && *p != '/'; p--)
    734 		;
    735 	if (*p == '/' && p + 1 < se)
    736 		p++;
    737 
    738 	return (p - s);
    739 }
    740 
    741 /*
    742  * Apply pattern matching to a table: all table entries that match a pattern
    743  * are added to wp.
    744  */
    745 static void
    746 glob_table(const char *pat, XPtrV *wp, struct table *tp)
    747 {
    748 	struct tstate ts;
    749 	struct tbl *te;
    750 
    751 	ktwalk(&ts, tp);
    752 	while ((te = ktnext(&ts)))
    753 		if (gmatchx(te->name, pat, false)) {
    754 			char *cp;
    755 
    756 			strdupx(cp, te->name, ATEMP);
    757 			XPput(*wp, cp);
    758 		}
    759 }
    760 
    761 static void
    762 glob_path(int flags, const char *pat, XPtrV *wp, const char *lpath)
    763 {
    764 	const char *sp = lpath, *p;
    765 	char *xp, **words;
    766 	size_t pathlen, patlen, oldsize, newsize, i, j;
    767 	XString xs;
    768 
    769 	patlen = strlen(pat);
    770 	checkoktoadd(patlen, 129 + X_EXTRA);
    771 	++patlen;
    772 	Xinit(xs, xp, patlen + 128, ATEMP);
    773 	while (sp) {
    774 		xp = Xstring(xs, xp);
    775 		if (!(p = cstrchr(sp, ':')))
    776 			p = sp + strlen(sp);
    777 		pathlen = p - sp;
    778 		if (pathlen) {
    779 			/*
    780 			 * Copy sp into xp, stuffing any MAGIC characters
    781 			 * on the way
    782 			 */
    783 			const char *s = sp;
    784 
    785 			XcheckN(xs, xp, pathlen * 2);
    786 			while (s < p) {
    787 				if (ISMAGIC(*s))
    788 					*xp++ = MAGIC;
    789 				*xp++ = *s++;
    790 			}
    791 			*xp++ = '/';
    792 			pathlen++;
    793 		}
    794 		sp = p;
    795 		XcheckN(xs, xp, patlen);
    796 		memcpy(xp, pat, patlen);
    797 
    798 		oldsize = XPsize(*wp);
    799 		/* mark dirs */
    800 		glob_str(Xstring(xs, xp), wp, true);
    801 		newsize = XPsize(*wp);
    802 
    803 		/* Check that each match is executable... */
    804 		words = (char **)XPptrv(*wp);
    805 		for (i = j = oldsize; i < newsize; i++) {
    806 			if (ksh_access(words[i], X_OK) == 0) {
    807 				words[j] = words[i];
    808 				if (!(flags & XCF_FULLPATH))
    809 					memmove(words[j], words[j] + pathlen,
    810 					    strlen(words[j] + pathlen) + 1);
    811 				j++;
    812 			} else
    813 				afree(words[i], ATEMP);
    814 		}
    815 		wp->len = j;
    816 
    817 		if (!*sp++)
    818 			break;
    819 	}
    820 	Xfree(xs, xp);
    821 }
    822 
    823 /*
    824  * if argument string contains any special characters, they will
    825  * be escaped and the result will be put into edit buffer by
    826  * keybinding-specific function
    827  */
    828 static int
    829 x_escape(const char *s, size_t len, int (*putbuf_func)(const char *, size_t))
    830 {
    831 	size_t add = 0, wlen = len;
    832 	const char *ifs = str_val(local("IFS", 0));
    833 	int rval = 0;
    834 
    835 	while (wlen - add > 0)
    836 		if (vstrchr("\"#$&'()*:;<=>?[\\`{|}", s[add]) ||
    837 		    vstrchr(ifs, s[add])) {
    838 			if (putbuf_func(s, add) != 0) {
    839 				rval = -1;
    840 				break;
    841 			}
    842 			putbuf_func(s[add] == '\n' ? "'" : "\\", 1);
    843 			putbuf_func(&s[add], 1);
    844 			if (s[add] == '\n')
    845 				putbuf_func("'", 1);
    846 
    847 			add++;
    848 			wlen -= add;
    849 			s += add;
    850 			add = 0;
    851 		} else
    852 			++add;
    853 	if (wlen > 0 && rval == 0)
    854 		rval = putbuf_func(s, wlen);
    855 
    856 	return (rval);
    857 }
    858 
    859 
    860 /* +++ emacs editing mode +++ */
    861 
    862 static	Area	aedit;
    863 #define	AEDIT	&aedit		/* area for kill ring and macro defns */
    864 
    865 /* values returned by keyboard functions */
    866 #define	KSTD	0
    867 #define	KEOL	1		/* ^M, ^J */
    868 #define	KINTR	2		/* ^G, ^C */
    869 
    870 struct x_ftab {
    871 	int (*xf_func)(int c);
    872 	const char *xf_name;
    873 	short xf_flags;
    874 };
    875 
    876 struct x_defbindings {
    877 	unsigned char xdb_func;	/* XFUNC_* */
    878 	unsigned char xdb_tab;
    879 	unsigned char xdb_char;
    880 };
    881 
    882 #define XF_ARG		1	/* command takes number prefix */
    883 #define	XF_NOBIND	2	/* not allowed to bind to function */
    884 #define	XF_PREFIX	4	/* function sets prefix */
    885 
    886 /* Separator for completion */
    887 #define	is_cfs(c)	((c) == ' ' || (c) == '\t' || (c) == '"' || (c) == '\'')
    888 /* Separator for motion */
    889 #define	is_mfs(c)	(!(ksh_isalnux(c) || (c) == '$' || ((c) & 0x80)))
    890 
    891 #define X_NTABS		3			/* normal, meta1, meta2 */
    892 #define X_TABSZ		256			/* size of keydef tables etc */
    893 
    894 /*-
    895  * Arguments for do_complete()
    896  * 0 = enumerate	M-=	complete as much as possible and then list
    897  * 1 = complete		M-Esc
    898  * 2 = list		M-?
    899  */
    900 typedef enum {
    901 	CT_LIST,	/* list the possible completions */
    902 	CT_COMPLETE,	/* complete to longest prefix */
    903 	CT_COMPLIST	/* complete and then list (if non-exact) */
    904 } Comp_type;
    905 
    906 /*
    907  * The following are used for my horizontal scrolling stuff
    908  */
    909 static char *xbuf;		/* beg input buffer */
    910 static char *xend;		/* end input buffer */
    911 static char *xcp;		/* current position */
    912 static char *xep;		/* current end */
    913 static char *xbp;		/* start of visible portion of input buffer */
    914 static char *xlp;		/* last char visible on screen */
    915 static bool x_adj_ok;
    916 /*
    917  * we use x_adj_done so that functions can tell
    918  * whether x_adjust() has been called while they are active.
    919  */
    920 static int x_adj_done;		/* is incremented by x_adjust() */
    921 
    922 static int x_col;
    923 static int x_displen;
    924 static int x_arg;		/* general purpose arg */
    925 static bool x_arg_defaulted;	/* x_arg not explicitly set; defaulted to 1 */
    926 
    927 static bool xlp_valid;		/* lastvis pointer was recalculated */
    928 
    929 static char **x_histp;		/* history position */
    930 static int x_nextcmd;		/* for newline-and-next */
    931 static char **x_histncp;	/* saved x_histp for " */
    932 static char *xmp;		/* mark pointer */
    933 static unsigned char x_last_command;
    934 static unsigned char (*x_tab)[X_TABSZ];	/* key definition */
    935 #ifndef MKSH_SMALL
    936 static char *(*x_atab)[X_TABSZ];	/* macro definitions */
    937 #endif
    938 static unsigned char x_bound[(X_TABSZ * X_NTABS + 7) / 8];
    939 #define KILLSIZE	20
    940 static char *killstack[KILLSIZE];
    941 static int killsp, killtp;
    942 static int x_curprefix;
    943 #ifndef MKSH_SMALL
    944 static char *macroptr;		/* bind key macro active? */
    945 #endif
    946 #if !MKSH_S_NOVI
    947 static int cur_col;		/* current column on line */
    948 static int pwidth;		/* width of prompt */
    949 static int prompt_trunc;	/* how much of prompt to truncate */
    950 static int winwidth;		/* width of window */
    951 static char *wbuf[2];		/* window buffers */
    952 static int wbuf_len;		/* length of window buffers (x_cols - 3) */
    953 static int win;			/* window buffer in use */
    954 static char morec;		/* more character at right of window */
    955 static int lastref;		/* argument to last refresh() */
    956 static int holdlen;		/* length of holdbuf */
    957 #endif
    958 static bool prompt_redraw;	/* false if newline forced after prompt */
    959 
    960 static int x_ins(const char *);
    961 static void x_delete(size_t, bool);
    962 static size_t x_bword(void);
    963 static size_t x_fword(bool);
    964 static void x_goto(char *);
    965 static void x_bs3(char **);
    966 static int x_size_str(char *);
    967 static int x_size2(char *, char **);
    968 static void x_zots(char *);
    969 static void x_zotc2(int);
    970 static void x_zotc3(char **);
    971 static void x_load_hist(char **);
    972 static int x_search(char *, int, int);
    973 #ifndef MKSH_SMALL
    974 static int x_search_dir(int);
    975 #endif
    976 static int x_match(char *, char *);
    977 static void x_redraw(int);
    978 static void x_push(int);
    979 static char *x_mapin(const char *, Area *);
    980 static char *x_mapout(int);
    981 static void x_mapout2(int, char **);
    982 static void x_print(int, int);
    983 static void x_adjust(void);
    984 static void x_e_ungetc(int);
    985 static int x_e_getc(void);
    986 static void x_e_putc2(int);
    987 static void x_e_putc3(const char **);
    988 static void x_e_puts(const char *);
    989 #ifndef MKSH_SMALL
    990 static int x_fold_case(int);
    991 #endif
    992 static char *x_lastcp(void);
    993 static void do_complete(int, Comp_type);
    994 static size_t x_nb2nc(size_t);
    995 
    996 static int unget_char = -1;
    997 
    998 static int x_do_ins(const char *, size_t);
    999 static void bind_if_not_bound(int, int, int);
   1000 
   1001 enum emacs_funcs {
   1002 #define EMACSFN_ENUMS
   1003 #include "emacsfn.h"
   1004 	XFUNC_MAX
   1005 };
   1006 
   1007 #define EMACSFN_DEFNS
   1008 #include "emacsfn.h"
   1009 
   1010 static const struct x_ftab x_ftab[] = {
   1011 #define EMACSFN_ITEMS
   1012 #include "emacsfn.h"
   1013 	{ 0, NULL, 0 }
   1014 };
   1015 
   1016 static struct x_defbindings const x_defbindings[] = {
   1017 	{ XFUNC_del_back,		0, CTRL('?')	},
   1018 	{ XFUNC_del_bword,		1, CTRL('?')	},
   1019 	{ XFUNC_eot_del,		0, CTRL('D')	},
   1020 	{ XFUNC_del_back,		0, CTRL('H')	},
   1021 	{ XFUNC_del_bword,		1, CTRL('H')	},
   1022 	{ XFUNC_del_bword,		1,	'h'	},
   1023 	{ XFUNC_mv_bword,		1,	'b'	},
   1024 	{ XFUNC_mv_fword,		1,	'f'	},
   1025 	{ XFUNC_del_fword,		1,	'd'	},
   1026 	{ XFUNC_mv_back,		0, CTRL('B')	},
   1027 	{ XFUNC_mv_forw,		0, CTRL('F')	},
   1028 	{ XFUNC_search_char_forw,	0, CTRL(']')	},
   1029 	{ XFUNC_search_char_back,	1, CTRL(']')	},
   1030 	{ XFUNC_newline,		0, CTRL('M')	},
   1031 	{ XFUNC_newline,		0, CTRL('J')	},
   1032 	{ XFUNC_end_of_text,		0, CTRL('_')	},
   1033 	{ XFUNC_abort,			0, CTRL('G')	},
   1034 	{ XFUNC_prev_com,		0, CTRL('P')	},
   1035 	{ XFUNC_next_com,		0, CTRL('N')	},
   1036 	{ XFUNC_nl_next_com,		0, CTRL('O')	},
   1037 	{ XFUNC_search_hist,		0, CTRL('R')	},
   1038 	{ XFUNC_beg_hist,		1,	'<'	},
   1039 	{ XFUNC_end_hist,		1,	'>'	},
   1040 	{ XFUNC_goto_hist,		1,	'g'	},
   1041 	{ XFUNC_mv_end,			0, CTRL('E')	},
   1042 	{ XFUNC_mv_begin,		0, CTRL('A')	},
   1043 	{ XFUNC_draw_line,		0, CTRL('L')	},
   1044 	{ XFUNC_cls,			1, CTRL('L')	},
   1045 	{ XFUNC_meta1,			0, CTRL('[')	},
   1046 	{ XFUNC_meta2,			0, CTRL('X')	},
   1047 	{ XFUNC_kill,			0, CTRL('K')	},
   1048 	{ XFUNC_yank,			0, CTRL('Y')	},
   1049 	{ XFUNC_meta_yank,		1,	'y'	},
   1050 	{ XFUNC_literal,		0, CTRL('^')	},
   1051 	{ XFUNC_comment,		1,	'#'	},
   1052 	{ XFUNC_transpose,		0, CTRL('T')	},
   1053 	{ XFUNC_complete,		1, CTRL('[')	},
   1054 	{ XFUNC_comp_list,		0, CTRL('I')	},
   1055 	{ XFUNC_comp_list,		1,	'='	},
   1056 	{ XFUNC_enumerate,		1,	'?'	},
   1057 	{ XFUNC_expand,			1,	'*'	},
   1058 	{ XFUNC_comp_file,		1, CTRL('X')	},
   1059 	{ XFUNC_comp_comm,		2, CTRL('[')	},
   1060 	{ XFUNC_list_comm,		2,	'?'	},
   1061 	{ XFUNC_list_file,		2, CTRL('Y')	},
   1062 	{ XFUNC_set_mark,		1,	' '	},
   1063 	{ XFUNC_kill_region,		0, CTRL('W')	},
   1064 	{ XFUNC_xchg_point_mark,	2, CTRL('X')	},
   1065 	{ XFUNC_literal,		0, CTRL('V')	},
   1066 	{ XFUNC_version,		1, CTRL('V')	},
   1067 	{ XFUNC_prev_histword,		1,	'.'	},
   1068 	{ XFUNC_prev_histword,		1,	'_'	},
   1069 	{ XFUNC_set_arg,		1,	'0'	},
   1070 	{ XFUNC_set_arg,		1,	'1'	},
   1071 	{ XFUNC_set_arg,		1,	'2'	},
   1072 	{ XFUNC_set_arg,		1,	'3'	},
   1073 	{ XFUNC_set_arg,		1,	'4'	},
   1074 	{ XFUNC_set_arg,		1,	'5'	},
   1075 	{ XFUNC_set_arg,		1,	'6'	},
   1076 	{ XFUNC_set_arg,		1,	'7'	},
   1077 	{ XFUNC_set_arg,		1,	'8'	},
   1078 	{ XFUNC_set_arg,		1,	'9'	},
   1079 #ifndef MKSH_SMALL
   1080 	{ XFUNC_fold_upper,		1,	'U'	},
   1081 	{ XFUNC_fold_upper,		1,	'u'	},
   1082 	{ XFUNC_fold_lower,		1,	'L'	},
   1083 	{ XFUNC_fold_lower,		1,	'l'	},
   1084 	{ XFUNC_fold_capitalise,	1,	'C'	},
   1085 	{ XFUNC_fold_capitalise,	1,	'c'	},
   1086 #endif
   1087 	/*
   1088 	 * These for ANSI arrow keys: arguablely shouldn't be here by
   1089 	 * default, but its simpler/faster/smaller than using termcap
   1090 	 * entries.
   1091 	 */
   1092 	{ XFUNC_meta2,			1,	'['	},
   1093 	{ XFUNC_meta2,			1,	'O'	},
   1094 	{ XFUNC_prev_com,		2,	'A'	},
   1095 	{ XFUNC_next_com,		2,	'B'	},
   1096 	{ XFUNC_mv_forw,		2,	'C'	},
   1097 	{ XFUNC_mv_back,		2,	'D'	},
   1098 #ifndef MKSH_SMALL
   1099 	{ XFUNC_vt_hack,		2,	'1'	},
   1100 	{ XFUNC_mv_begin | 0x80,	2,	'7'	},
   1101 	{ XFUNC_mv_begin,		2,	'H'	},
   1102 	{ XFUNC_mv_end | 0x80,		2,	'4'	},
   1103 	{ XFUNC_mv_end | 0x80,		2,	'8'	},
   1104 	{ XFUNC_mv_end,			2,	'F'	},
   1105 	{ XFUNC_del_char | 0x80,	2,	'3'	},
   1106 	{ XFUNC_search_hist_up | 0x80,	2,	'5'	},
   1107 	{ XFUNC_search_hist_dn | 0x80,	2,	'6'	},
   1108 	/* more non-standard ones */
   1109 	{ XFUNC_edit_line,		2,	'e'	}
   1110 #endif
   1111 };
   1112 
   1113 static size_t
   1114 x_nb2nc(size_t nb)
   1115 {
   1116 	char *cp;
   1117 	size_t nc = 0;
   1118 
   1119 	for (cp = xcp; cp < (xcp + nb); ++nc)
   1120 		cp += utf_ptradj(cp);
   1121 	return (nc);
   1122 }
   1123 
   1124 static void
   1125 x_modified(void)
   1126 {
   1127 	if (!modified) {
   1128 		x_histp = histptr + 1;
   1129 		modified = 1;
   1130 	}
   1131 }
   1132 
   1133 #ifdef MKSH_SMALL
   1134 #define XFUNC_VALUE(f) (f)
   1135 #else
   1136 #define XFUNC_VALUE(f) (f & 0x7F)
   1137 #endif
   1138 
   1139 static int
   1140 x_e_getmbc(char *sbuf)
   1141 {
   1142 	int c, pos = 0;
   1143 	unsigned char *buf = (unsigned char *)sbuf;
   1144 
   1145 	memset(buf, 0, 4);
   1146 	buf[pos++] = c = x_e_getc();
   1147 	if (c == -1)
   1148 		return (-1);
   1149 	if (UTFMODE) {
   1150 		if ((buf[0] >= 0xC2) && (buf[0] < 0xF0)) {
   1151 			c = x_e_getc();
   1152 			if (c == -1)
   1153 				return (-1);
   1154 			if ((c & 0xC0) != 0x80) {
   1155 				x_e_ungetc(c);
   1156 				return (1);
   1157 			}
   1158 			buf[pos++] = c;
   1159 		}
   1160 		if ((buf[0] >= 0xE0) && (buf[0] < 0xF0)) {
   1161 			/* XXX x_e_ungetc is one-octet only */
   1162 			buf[pos++] = c = x_e_getc();
   1163 			if (c == -1)
   1164 				return (-1);
   1165 		}
   1166 	}
   1167 	return (pos);
   1168 }
   1169 
   1170 static void
   1171 x_init_prompt(void)
   1172 {
   1173 	x_col = promptlen(prompt);
   1174 	x_adj_ok = true;
   1175 	prompt_redraw = true;
   1176 	if (x_col >= xx_cols)
   1177 		x_col %= xx_cols;
   1178 	x_displen = xx_cols - 2 - x_col;
   1179 	x_adj_done = 0;
   1180 
   1181 	pprompt(prompt, 0);
   1182 	if (x_displen < 1) {
   1183 		x_col = 0;
   1184 		x_displen = xx_cols - 2;
   1185 		x_e_putc2('\n');
   1186 		prompt_redraw = false;
   1187 	}
   1188 }
   1189 
   1190 static int
   1191 x_emacs(char *buf, size_t len)
   1192 {
   1193 	int c, i;
   1194 	unsigned char f;
   1195 
   1196 	xbp = xbuf = buf; xend = buf + len;
   1197 	xlp = xcp = xep = buf;
   1198 	*xcp = 0;
   1199 	xlp_valid = true;
   1200 	xmp = NULL;
   1201 	x_curprefix = 0;
   1202 	x_histp = histptr + 1;
   1203 	x_last_command = XFUNC_error;
   1204 
   1205 	xx_cols = x_cols;
   1206 	x_init_prompt();
   1207 
   1208 	x_histncp = NULL;
   1209 	if (x_nextcmd >= 0) {
   1210 		int off = source->line - x_nextcmd;
   1211 		if (histptr - history >= off) {
   1212 			x_load_hist(histptr - off);
   1213 			x_histncp = x_histp;
   1214 		}
   1215 		x_nextcmd = -1;
   1216 	}
   1217 	editmode = 1;
   1218 	while (/* CONSTCOND */ 1) {
   1219 		x_flush();
   1220 		if ((c = x_e_getc()) < 0)
   1221 			return (0);
   1222 
   1223 		f = x_curprefix == -1 ? XFUNC_insert :
   1224 		    x_tab[x_curprefix][c];
   1225 #ifndef MKSH_SMALL
   1226 		if (f & 0x80) {
   1227 			f &= 0x7F;
   1228 			if ((i = x_e_getc()) != '~')
   1229 				x_e_ungetc(i);
   1230 		}
   1231 
   1232 		/* avoid bind key macro recursion */
   1233 		if (macroptr && f == XFUNC_ins_string)
   1234 			f = XFUNC_insert;
   1235 #endif
   1236 
   1237 		if (!(x_ftab[f].xf_flags & XF_PREFIX) &&
   1238 		    x_last_command != XFUNC_set_arg) {
   1239 			x_arg = 1;
   1240 			x_arg_defaulted = true;
   1241 		}
   1242 		i = c | (x_curprefix << 8);
   1243 		x_curprefix = 0;
   1244 		switch ((*x_ftab[f].xf_func)(i)) {
   1245 		case KSTD:
   1246 			if (!(x_ftab[f].xf_flags & XF_PREFIX))
   1247 				x_last_command = f;
   1248 			break;
   1249 		case KEOL:
   1250 			i = xep - xbuf;
   1251 			return (i);
   1252 		case KINTR:
   1253 			/* special case for interrupt */
   1254 			trapsig(SIGINT);
   1255 			x_mode(false);
   1256 			unwind(LSHELL);
   1257 		}
   1258 		/* ad-hoc hack for fixing the cursor position */
   1259 		x_goto(xcp);
   1260 	}
   1261 }
   1262 
   1263 static int
   1264 x_insert(int c)
   1265 {
   1266 	static int left, pos, save_arg;
   1267 	static char str[4];
   1268 
   1269 	/*
   1270 	 * Should allow tab and control chars.
   1271 	 */
   1272 	if (c == 0) {
   1273  invmbs:
   1274 		left = 0;
   1275 		x_e_putc2(7);
   1276 		return (KSTD);
   1277 	}
   1278 	if (UTFMODE) {
   1279 		if (((c & 0xC0) == 0x80) && left) {
   1280 			str[pos++] = c;
   1281 			if (!--left) {
   1282 				str[pos] = '\0';
   1283 				x_arg = save_arg;
   1284 				while (x_arg--)
   1285 					x_ins(str);
   1286 			}
   1287 			return (KSTD);
   1288 		}
   1289 		if (left) {
   1290 			if (x_curprefix == -1) {
   1291 				/* flush invalid multibyte */
   1292 				str[pos] = '\0';
   1293 				while (save_arg--)
   1294 					x_ins(str);
   1295 			}
   1296 		}
   1297 		if ((c >= 0xC2) && (c < 0xE0))
   1298 			left = 1;
   1299 		else if ((c >= 0xE0) && (c < 0xF0))
   1300 			left = 2;
   1301 		else if (c > 0x7F)
   1302 			goto invmbs;
   1303 		else
   1304 			left = 0;
   1305 		if (left) {
   1306 			save_arg = x_arg;
   1307 			pos = 1;
   1308 			str[0] = c;
   1309 			return (KSTD);
   1310 		}
   1311 	}
   1312 	left = 0;
   1313 	str[0] = c;
   1314 	str[1] = '\0';
   1315 	while (x_arg--)
   1316 		x_ins(str);
   1317 	return (KSTD);
   1318 }
   1319 
   1320 #ifndef MKSH_SMALL
   1321 static int
   1322 x_ins_string(int c)
   1323 {
   1324 	macroptr = x_atab[c >> 8][c & 255];
   1325 	/*
   1326 	 * we no longer need to bother checking if macroptr is
   1327 	 * not NULL but first char is NUL; x_e_getc() does it
   1328 	 */
   1329 	return (KSTD);
   1330 }
   1331 #endif
   1332 
   1333 static int
   1334 x_do_ins(const char *cp, size_t len)
   1335 {
   1336 	if (xep + len >= xend) {
   1337 		x_e_putc2(7);
   1338 		return (-1);
   1339 	}
   1340 	memmove(xcp + len, xcp, xep - xcp + 1);
   1341 	memmove(xcp, cp, len);
   1342 	xcp += len;
   1343 	xep += len;
   1344 	x_modified();
   1345 	return (0);
   1346 }
   1347 
   1348 static int
   1349 x_ins(const char *s)
   1350 {
   1351 	char *cp = xcp;
   1352 	int adj = x_adj_done;
   1353 
   1354 	if (x_do_ins(s, strlen(s)) < 0)
   1355 		return (-1);
   1356 	/*
   1357 	 * x_zots() may result in a call to x_adjust()
   1358 	 * we want xcp to reflect the new position.
   1359 	 */
   1360 	xlp_valid = false;
   1361 	x_lastcp();
   1362 	x_adj_ok = tobool(xcp >= xlp);
   1363 	x_zots(cp);
   1364 	/* has x_adjust() been called? */
   1365 	if (adj == x_adj_done) {
   1366 		/* no */
   1367 		cp = xlp;
   1368 		while (cp > xcp)
   1369 			x_bs3(&cp);
   1370 	}
   1371 	if (xlp == xep - 1)
   1372 		x_redraw(xx_cols);
   1373 	x_adj_ok = true;
   1374 	return (0);
   1375 }
   1376 
   1377 static int
   1378 x_del_back(int c MKSH_A_UNUSED)
   1379 {
   1380 	ssize_t i = 0;
   1381 
   1382 	if (xcp == xbuf) {
   1383 		x_e_putc2(7);
   1384 		return (KSTD);
   1385 	}
   1386 	do {
   1387 		x_goto(xcp - 1);
   1388 	} while ((++i < x_arg) && (xcp != xbuf));
   1389 	x_delete(i, false);
   1390 	return (KSTD);
   1391 }
   1392 
   1393 static int
   1394 x_del_char(int c MKSH_A_UNUSED)
   1395 {
   1396 	char *cp, *cp2;
   1397 	size_t i = 0;
   1398 
   1399 	cp = xcp;
   1400 	while (i < (size_t)x_arg) {
   1401 		utf_ptradjx(cp, cp2);
   1402 		if (cp2 > xep)
   1403 			break;
   1404 		cp = cp2;
   1405 		i++;
   1406 	}
   1407 
   1408 	if (!i) {
   1409 		x_e_putc2(7);
   1410 		return (KSTD);
   1411 	}
   1412 	x_delete(i, false);
   1413 	return (KSTD);
   1414 }
   1415 
   1416 /* Delete nc chars to the right of the cursor (including cursor position) */
   1417 static void
   1418 x_delete(size_t nc, bool push)
   1419 {
   1420 	size_t i, nb, nw;
   1421 	char *cp;
   1422 
   1423 	if (nc == 0)
   1424 		return;
   1425 
   1426 	nw = 0;
   1427 	cp = xcp;
   1428 	for (i = 0; i < nc; ++i) {
   1429 		char *cp2;
   1430 		int j;
   1431 
   1432 		j = x_size2(cp, &cp2);
   1433 		if (cp2 > xep)
   1434 			break;
   1435 		cp = cp2;
   1436 		nw += j;
   1437 	}
   1438 	nb = cp - xcp;
   1439 	/* nc = i; */
   1440 
   1441 	if (xmp != NULL && xmp > xcp) {
   1442 		if (xcp + nb > xmp)
   1443 			xmp = xcp;
   1444 		else
   1445 			xmp -= nb;
   1446 	}
   1447 	/*
   1448 	 * This lets us yank a word we have deleted.
   1449 	 */
   1450 	if (push)
   1451 		x_push(nb);
   1452 
   1453 	xep -= nb;
   1454 	/* Copies the NUL */
   1455 	memmove(xcp, xcp + nb, xep - xcp + 1);
   1456 	/* don't redraw */
   1457 	x_adj_ok = false;
   1458 	xlp_valid = false;
   1459 	x_zots(xcp);
   1460 	/*
   1461 	 * if we are already filling the line,
   1462 	 * there is no need to ' ', '\b'.
   1463 	 * But if we must, make sure we do the minimum.
   1464 	 */
   1465 	if ((i = xx_cols - 2 - x_col) > 0 || xep - xlp == 0) {
   1466 		nw = i = (nw < i) ? nw : i;
   1467 		while (i--)
   1468 			x_e_putc2(' ');
   1469 		if (x_col == xx_cols - 2) {
   1470 			x_e_putc2((xep > xlp) ? '>' : (xbp > xbuf) ? '<' : ' ');
   1471 			++nw;
   1472 		}
   1473 		while (nw--)
   1474 			x_e_putc2('\b');
   1475 	}
   1476 	/*x_goto(xcp);*/
   1477 	x_adj_ok = true;
   1478 	xlp_valid = false;
   1479 	cp = x_lastcp();
   1480 	while (cp > xcp)
   1481 		x_bs3(&cp);
   1482 
   1483 	x_modified();
   1484 	return;
   1485 }
   1486 
   1487 static int
   1488 x_del_bword(int c MKSH_A_UNUSED)
   1489 {
   1490 	x_delete(x_bword(), true);
   1491 	return (KSTD);
   1492 }
   1493 
   1494 static int
   1495 x_mv_bword(int c MKSH_A_UNUSED)
   1496 {
   1497 	x_bword();
   1498 	return (KSTD);
   1499 }
   1500 
   1501 static int
   1502 x_mv_fword(int c MKSH_A_UNUSED)
   1503 {
   1504 	x_fword(true);
   1505 	return (KSTD);
   1506 }
   1507 
   1508 static int
   1509 x_del_fword(int c MKSH_A_UNUSED)
   1510 {
   1511 	x_delete(x_fword(false), true);
   1512 	return (KSTD);
   1513 }
   1514 
   1515 static size_t
   1516 x_bword(void)
   1517 {
   1518 	size_t nb = 0;
   1519 	char *cp = xcp;
   1520 
   1521 	if (cp == xbuf) {
   1522 		x_e_putc2(7);
   1523 		return (0);
   1524 	}
   1525 	while (x_arg--) {
   1526 		while (cp != xbuf && is_mfs(cp[-1])) {
   1527 			cp--;
   1528 			nb++;
   1529 		}
   1530 		while (cp != xbuf && !is_mfs(cp[-1])) {
   1531 			cp--;
   1532 			nb++;
   1533 		}
   1534 	}
   1535 	x_goto(cp);
   1536 	return (x_nb2nc(nb));
   1537 }
   1538 
   1539 static size_t
   1540 x_fword(bool move)
   1541 {
   1542 	size_t nc;
   1543 	char *cp = xcp;
   1544 
   1545 	if (cp == xep) {
   1546 		x_e_putc2(7);
   1547 		return (0);
   1548 	}
   1549 	while (x_arg--) {
   1550 		while (cp != xep && is_mfs(*cp))
   1551 			cp++;
   1552 		while (cp != xep && !is_mfs(*cp))
   1553 			cp++;
   1554 	}
   1555 	nc = x_nb2nc(cp - xcp);
   1556 	if (move)
   1557 		x_goto(cp);
   1558 	return (nc);
   1559 }
   1560 
   1561 static void
   1562 x_goto(char *cp)
   1563 {
   1564 	if (cp >= xep)
   1565 		cp = xep;
   1566 	else if (UTFMODE)
   1567 		while ((cp > xbuf) && ((*cp & 0xC0) == 0x80))
   1568 			--cp;
   1569 	if (cp < xbp || cp >= utf_skipcols(xbp, x_displen)) {
   1570 		/* we are heading off screen */
   1571 		xcp = cp;
   1572 		x_adjust();
   1573 	} else if (cp < xcp) {
   1574 		/* move back */
   1575 		while (cp < xcp)
   1576 			x_bs3(&xcp);
   1577 	} else if (cp > xcp) {
   1578 		/* move forward */
   1579 		while (cp > xcp)
   1580 			x_zotc3(&xcp);
   1581 	}
   1582 }
   1583 
   1584 static void
   1585 x_bs3(char **p)
   1586 {
   1587 	int i;
   1588 
   1589 	(*p)--;
   1590 	if (UTFMODE)
   1591 		while (((unsigned char)**p & 0xC0) == 0x80)
   1592 			(*p)--;
   1593 
   1594 	i = x_size2(*p, NULL);
   1595 	while (i--)
   1596 		x_e_putc2('\b');
   1597 }
   1598 
   1599 static int
   1600 x_size_str(char *cp)
   1601 {
   1602 	int size = 0;
   1603 	while (*cp)
   1604 		size += x_size2(cp, &cp);
   1605 	return (size);
   1606 }
   1607 
   1608 static int
   1609 x_size2(char *cp, char **dcp)
   1610 {
   1611 	int c = *(unsigned char *)cp;
   1612 
   1613 	if (UTFMODE && (c > 0x7F))
   1614 		return (utf_widthadj(cp, (const char **)dcp));
   1615 	if (dcp)
   1616 		*dcp = cp + 1;
   1617 	if (c == '\t')
   1618 		/* Kludge, tabs are always four spaces. */
   1619 		return (4);
   1620 	if (c < ' ' || c == 0x7f)
   1621 		/* control unsigned char */
   1622 		return (2);
   1623 	return (1);
   1624 }
   1625 
   1626 static void
   1627 x_zots(char *str)
   1628 {
   1629 	int adj = x_adj_done;
   1630 
   1631 	x_lastcp();
   1632 	while (*str && str < xlp && adj == x_adj_done)
   1633 		x_zotc3(&str);
   1634 }
   1635 
   1636 static void
   1637 x_zotc2(int c)
   1638 {
   1639 	if (c == '\t') {
   1640 		/* Kludge, tabs are always four spaces. */
   1641 		x_e_puts("    ");
   1642 	} else if (c < ' ' || c == 0x7f) {
   1643 		x_e_putc2('^');
   1644 		x_e_putc2(UNCTRL(c));
   1645 	} else
   1646 		x_e_putc2(c);
   1647 }
   1648 
   1649 static void
   1650 x_zotc3(char **cp)
   1651 {
   1652 	unsigned char c = **(unsigned char **)cp;
   1653 
   1654 	if (c == '\t') {
   1655 		/* Kludge, tabs are always four spaces. */
   1656 		x_e_puts("    ");
   1657 		(*cp)++;
   1658 	} else if (c < ' ' || c == 0x7f) {
   1659 		x_e_putc2('^');
   1660 		x_e_putc2(UNCTRL(c));
   1661 		(*cp)++;
   1662 	} else
   1663 		x_e_putc3((const char **)cp);
   1664 }
   1665 
   1666 static int
   1667 x_mv_back(int c MKSH_A_UNUSED)
   1668 {
   1669 	if (xcp == xbuf) {
   1670 		x_e_putc2(7);
   1671 		return (KSTD);
   1672 	}
   1673 	while (x_arg--) {
   1674 		x_goto(xcp - 1);
   1675 		if (xcp == xbuf)
   1676 			break;
   1677 	}
   1678 	return (KSTD);
   1679 }
   1680 
   1681 static int
   1682 x_mv_forw(int c MKSH_A_UNUSED)
   1683 {
   1684 	char *cp = xcp, *cp2;
   1685 
   1686 	if (xcp == xep) {
   1687 		x_e_putc2(7);
   1688 		return (KSTD);
   1689 	}
   1690 	while (x_arg--) {
   1691 		utf_ptradjx(cp, cp2);
   1692 		if (cp2 > xep)
   1693 			break;
   1694 		cp = cp2;
   1695 	}
   1696 	x_goto(cp);
   1697 	return (KSTD);
   1698 }
   1699 
   1700 static int
   1701 x_search_char_forw(int c MKSH_A_UNUSED)
   1702 {
   1703 	char *cp = xcp;
   1704 	char tmp[4];
   1705 
   1706 	*xep = '\0';
   1707 	if (x_e_getmbc(tmp) < 0) {
   1708 		x_e_putc2(7);
   1709 		return (KSTD);
   1710 	}
   1711 	while (x_arg--) {
   1712 		if ((cp = (cp == xep) ? NULL : strstr(cp + 1, tmp)) == NULL &&
   1713 		    (cp = strstr(xbuf, tmp)) == NULL) {
   1714 			x_e_putc2(7);
   1715 			return (KSTD);
   1716 		}
   1717 	}
   1718 	x_goto(cp);
   1719 	return (KSTD);
   1720 }
   1721 
   1722 static int
   1723 x_search_char_back(int c MKSH_A_UNUSED)
   1724 {
   1725 	char *cp = xcp, *p, tmp[4];
   1726 	bool b;
   1727 
   1728 	if (x_e_getmbc(tmp) < 0) {
   1729 		x_e_putc2(7);
   1730 		return (KSTD);
   1731 	}
   1732 	for (; x_arg--; cp = p)
   1733 		for (p = cp; ; ) {
   1734 			if (p-- == xbuf)
   1735 				p = xep;
   1736 			if (p == cp) {
   1737 				x_e_putc2(7);
   1738 				return (KSTD);
   1739 			}
   1740 			if ((tmp[1] && ((p+1) > xep)) ||
   1741 			    (tmp[2] && ((p+2) > xep)))
   1742 				continue;
   1743 			b = true;
   1744 			if (*p != tmp[0])
   1745 				b = false;
   1746 			if (b && tmp[1] && p[1] != tmp[1])
   1747 				b = false;
   1748 			if (b && tmp[2] && p[2] != tmp[2])
   1749 				b = false;
   1750 			if (b)
   1751 				break;
   1752 		}
   1753 	x_goto(cp);
   1754 	return (KSTD);
   1755 }
   1756 
   1757 static int
   1758 x_newline(int c MKSH_A_UNUSED)
   1759 {
   1760 	x_e_putc2('\r');
   1761 	x_e_putc2('\n');
   1762 	x_flush();
   1763 	*xep++ = '\n';
   1764 	return (KEOL);
   1765 }
   1766 
   1767 static int
   1768 x_end_of_text(int c MKSH_A_UNUSED)
   1769 {
   1770 	x_zotc2(edchars.eof);
   1771 	x_putc('\r');
   1772 	x_putc('\n');
   1773 	x_flush();
   1774 	return (KEOL);
   1775 }
   1776 
   1777 static int
   1778 x_beg_hist(int c MKSH_A_UNUSED)
   1779 {
   1780 	x_load_hist(history);
   1781 	return (KSTD);
   1782 }
   1783 
   1784 static int
   1785 x_end_hist(int c MKSH_A_UNUSED)
   1786 {
   1787 	x_load_hist(histptr);
   1788 	return (KSTD);
   1789 }
   1790 
   1791 static int
   1792 x_prev_com(int c MKSH_A_UNUSED)
   1793 {
   1794 	x_load_hist(x_histp - x_arg);
   1795 	return (KSTD);
   1796 }
   1797 
   1798 static int
   1799 x_next_com(int c MKSH_A_UNUSED)
   1800 {
   1801 	x_load_hist(x_histp + x_arg);
   1802 	return (KSTD);
   1803 }
   1804 
   1805 /*
   1806  * Goto a particular history number obtained from argument.
   1807  * If no argument is given history 1 is probably not what you
   1808  * want so we'll simply go to the oldest one.
   1809  */
   1810 static int
   1811 x_goto_hist(int c MKSH_A_UNUSED)
   1812 {
   1813 	if (x_arg_defaulted)
   1814 		x_load_hist(history);
   1815 	else
   1816 		x_load_hist(histptr + x_arg - source->line);
   1817 	return (KSTD);
   1818 }
   1819 
   1820 static void
   1821 x_load_hist(char **hp)
   1822 {
   1823 	int oldsize;
   1824 	char *sp = NULL;
   1825 
   1826 	if (hp == histptr + 1) {
   1827 		sp = holdbuf;
   1828 		modified = 0;
   1829 	} else if (hp < history || hp > histptr) {
   1830 		x_e_putc2(7);
   1831 		return;
   1832 	}
   1833 	if (sp == NULL)
   1834 		sp = *hp;
   1835 	x_histp = hp;
   1836 	oldsize = x_size_str(xbuf);
   1837 	if (modified)
   1838 		strlcpy(holdbuf, xbuf, sizeof(holdbuf));
   1839 	strlcpy(xbuf, sp, xend - xbuf);
   1840 	xbp = xbuf;
   1841 	xep = xcp = xbuf + strlen(xbuf);
   1842 	xlp_valid = false;
   1843 	if (xep <= x_lastcp()) {
   1844 		x_redraw(oldsize);
   1845 	}
   1846 	x_goto(xep);
   1847 	modified = 0;
   1848 }
   1849 
   1850 static int
   1851 x_nl_next_com(int c MKSH_A_UNUSED)
   1852 {
   1853 	if (!x_histncp || (x_histp != x_histncp && x_histp != histptr + 1))
   1854 		/* fresh start of ^O */
   1855 		x_histncp = x_histp;
   1856 	x_nextcmd = source->line - (histptr - x_histncp) + 1;
   1857 	return (x_newline('\n'));
   1858 }
   1859 
   1860 static int
   1861 x_eot_del(int c)
   1862 {
   1863 	if (xep == xbuf && x_arg_defaulted)
   1864 		return (x_end_of_text(c));
   1865 	else
   1866 		return (x_del_char(c));
   1867 }
   1868 
   1869 /* reverse incremental history search */
   1870 static int
   1871 x_search_hist(int c)
   1872 {
   1873 	int offset = -1;	/* offset of match in xbuf, else -1 */
   1874 	char pat[80 + 1];	/* pattern buffer */
   1875 	char *p = pat;
   1876 	unsigned char f;
   1877 
   1878 	*p = '\0';
   1879 	while (/* CONSTCOND */ 1) {
   1880 		if (offset < 0) {
   1881 			x_e_puts("\nI-search: ");
   1882 			x_e_puts(pat);
   1883 		}
   1884 		x_flush();
   1885 		if ((c = x_e_getc()) < 0)
   1886 			return (KSTD);
   1887 		f = x_tab[0][c];
   1888 		if (c == CTRL('[')) {
   1889 			if ((f & 0x7F) == XFUNC_meta1) {
   1890 				if ((c = x_e_getc()) < 0)
   1891 					return (KSTD);
   1892 				f = x_tab[1][c] & 0x7F;
   1893 				if (f == XFUNC_meta1 || f == XFUNC_meta2)
   1894 					x_meta1(CTRL('['));
   1895 				x_e_ungetc(c);
   1896 			}
   1897 			break;
   1898 		}
   1899 #ifndef MKSH_SMALL
   1900 		if (f & 0x80) {
   1901 			f &= 0x7F;
   1902 			if ((c = x_e_getc()) != '~')
   1903 				x_e_ungetc(c);
   1904 		}
   1905 #endif
   1906 		if (f == XFUNC_search_hist)
   1907 			offset = x_search(pat, 0, offset);
   1908 		else if (f == XFUNC_del_back) {
   1909 			if (p == pat) {
   1910 				offset = -1;
   1911 				break;
   1912 			}
   1913 			if (p > pat)
   1914 				*--p = '\0';
   1915 			if (p == pat)
   1916 				offset = -1;
   1917 			else
   1918 				offset = x_search(pat, 1, offset);
   1919 			continue;
   1920 		} else if (f == XFUNC_insert) {
   1921 			/* add char to pattern */
   1922 			/* overflow check... */
   1923 			if ((size_t)(p - pat) >= sizeof(pat) - 1) {
   1924 				x_e_putc2(7);
   1925 				continue;
   1926 			}
   1927 			*p++ = c, *p = '\0';
   1928 			if (offset >= 0) {
   1929 				/* already have partial match */
   1930 				offset = x_match(xbuf, pat);
   1931 				if (offset >= 0) {
   1932 					x_goto(xbuf + offset + (p - pat) -
   1933 					    (*pat == '^'));
   1934 					continue;
   1935 				}
   1936 			}
   1937 			offset = x_search(pat, 0, offset);
   1938 		} else if (f == XFUNC_abort) {
   1939 			if (offset >= 0)
   1940 				x_load_hist(histptr + 1);
   1941 			break;
   1942 		} else {
   1943 			/* other command */
   1944 			x_e_ungetc(c);
   1945 			break;
   1946 		}
   1947 	}
   1948 	if (offset < 0)
   1949 		x_redraw(-1);
   1950 	return (KSTD);
   1951 }
   1952 
   1953 /* search backward from current line */
   1954 static int
   1955 x_search(char *pat, int sameline, int offset)
   1956 {
   1957 	char **hp;
   1958 	int i;
   1959 
   1960 	for (hp = x_histp - (sameline ? 0 : 1); hp >= history; --hp) {
   1961 		i = x_match(*hp, pat);
   1962 		if (i >= 0) {
   1963 			if (offset < 0)
   1964 				x_e_putc2('\n');
   1965 			x_load_hist(hp);
   1966 			x_goto(xbuf + i + strlen(pat) - (*pat == '^'));
   1967 			return (i);
   1968 		}
   1969 	}
   1970 	x_e_putc2(7);
   1971 	x_histp = histptr;
   1972 	return (-1);
   1973 }
   1974 
   1975 #ifndef MKSH_SMALL
   1976 /* anchored search up from current line */
   1977 static int
   1978 x_search_hist_up(int c MKSH_A_UNUSED)
   1979 {
   1980 	return (x_search_dir(-1));
   1981 }
   1982 
   1983 /* anchored search down from current line */
   1984 static int
   1985 x_search_hist_dn(int c MKSH_A_UNUSED)
   1986 {
   1987 	return (x_search_dir(1));
   1988 }
   1989 
   1990 /* anchored search in the indicated direction */
   1991 static int
   1992 x_search_dir(int search_dir /* should've been bool */)
   1993 {
   1994 	char **hp = x_histp + search_dir;
   1995 	size_t curs = xcp - xbuf;
   1996 
   1997 	while (histptr >= hp && hp >= history) {
   1998 		if (strncmp(xbuf, *hp, curs) == 0) {
   1999 			x_load_hist(hp);
   2000 			x_goto(xbuf + curs);
   2001 			break;
   2002 		}
   2003 		hp += search_dir;
   2004 	}
   2005 	return (KSTD);
   2006 }
   2007 #endif
   2008 
   2009 /* return position of first match of pattern in string, else -1 */
   2010 static int
   2011 x_match(char *str, char *pat)
   2012 {
   2013 	if (*pat == '^') {
   2014 		return ((strncmp(str, pat + 1, strlen(pat + 1)) == 0) ? 0 : -1);
   2015 	} else {
   2016 		char *q = strstr(str, pat);
   2017 		return ((q == NULL) ? -1 : q - str);
   2018 	}
   2019 }
   2020 
   2021 static int
   2022 x_del_line(int c MKSH_A_UNUSED)
   2023 {
   2024 	int i, j;
   2025 
   2026 	*xep = 0;
   2027 	i = xep - xbuf;
   2028 	j = x_size_str(xbuf);
   2029 	xcp = xbuf;
   2030 	x_push(i);
   2031 	xlp = xbp = xep = xbuf;
   2032 	xlp_valid = true;
   2033 	*xcp = 0;
   2034 	xmp = NULL;
   2035 	x_redraw(j);
   2036 	x_modified();
   2037 	return (KSTD);
   2038 }
   2039 
   2040 static int
   2041 x_mv_end(int c MKSH_A_UNUSED)
   2042 {
   2043 	x_goto(xep);
   2044 	return (KSTD);
   2045 }
   2046 
   2047 static int
   2048 x_mv_begin(int c MKSH_A_UNUSED)
   2049 {
   2050 	x_goto(xbuf);
   2051 	return (KSTD);
   2052 }
   2053 
   2054 static int
   2055 x_draw_line(int c MKSH_A_UNUSED)
   2056 {
   2057 	x_redraw(-1);
   2058 	return (KSTD);
   2059 }
   2060 
   2061 static int
   2062 x_e_rebuildline(const char *clrstr)
   2063 {
   2064 	shf_puts(clrstr, shl_out);
   2065 	x_adjust();
   2066 	return (KSTD);
   2067 }
   2068 
   2069 static int
   2070 x_cls(int c MKSH_A_UNUSED)
   2071 {
   2072 	return (x_e_rebuildline(MKSH_CLS_STRING));
   2073 }
   2074 
   2075 /*
   2076  * Redraw (part of) the line. If limit is < 0, the everything is redrawn
   2077  * on a NEW line, otherwise limit is the screen column up to which needs
   2078  * redrawing.
   2079  */
   2080 static void
   2081 x_redraw(int limit)
   2082 {
   2083 	int i, j, x_trunc = 0;
   2084 	char *cp;
   2085 
   2086 	x_adj_ok = false;
   2087 	if (limit == -1)
   2088 		x_e_putc2('\n');
   2089 	else
   2090 		x_e_putc2('\r');
   2091 	x_flush();
   2092 	if (xbp == xbuf) {
   2093 		x_col = promptlen(prompt);
   2094 		if (x_col >= xx_cols)
   2095 			x_trunc = (x_col / xx_cols) * xx_cols;
   2096 		if (prompt_redraw)
   2097 			pprompt(prompt, x_trunc);
   2098 	}
   2099 	if (x_col >= xx_cols)
   2100 		x_col %= xx_cols;
   2101 	x_displen = xx_cols - 2 - x_col;
   2102 	if (x_displen < 1) {
   2103 		x_col = 0;
   2104 		x_displen = xx_cols - 2;
   2105 	}
   2106 	xlp_valid = false;
   2107 	x_zots(xbp);
   2108 	if (xbp != xbuf || xep > xlp)
   2109 		limit = xx_cols;
   2110 	if (limit >= 0) {
   2111 		if (xep > xlp)
   2112 			/* we fill the line */
   2113 			i = 0;
   2114 		else {
   2115 			char *cpl = xbp;
   2116 
   2117 			i = limit;
   2118 			while (cpl < xlp)
   2119 				i -= x_size2(cpl, &cpl);
   2120 		}
   2121 
   2122 		j = 0;
   2123 		while ((j < i) || (x_col < (xx_cols - 2))) {
   2124 			if (!(x_col < (xx_cols - 2)))
   2125 				break;
   2126 			x_e_putc2(' ');
   2127 			j++;
   2128 		}
   2129 		i = ' ';
   2130 		if (xep > xlp) {
   2131 			/* more off screen */
   2132 			if (xbp > xbuf)
   2133 				i = '*';
   2134 			else
   2135 				i = '>';
   2136 		} else if (xbp > xbuf)
   2137 			i = '<';
   2138 		x_e_putc2(i);
   2139 		j++;
   2140 		while (j--)
   2141 			x_e_putc2('\b');
   2142 	}
   2143 	cp = xlp;
   2144 	while (cp > xcp)
   2145 		x_bs3(&cp);
   2146 	x_adj_ok = true;
   2147 	return;
   2148 }
   2149 
   2150 static int
   2151 x_transpose(int c MKSH_A_UNUSED)
   2152 {
   2153 	unsigned int tmpa, tmpb;
   2154 
   2155 	/*-
   2156 	 * What transpose is meant to do seems to be up for debate. This
   2157 	 * is a general summary of the options; the text is abcd with the
   2158 	 * upper case character or underscore indicating the cursor position:
   2159 	 *	Who			Before	After	Before	After
   2160 	 *	AT&T ksh in emacs mode:	abCd	abdC	abcd_	(bell)
   2161 	 *	AT&T ksh in gmacs mode:	abCd	baCd	abcd_	abdc_
   2162 	 *	gnu emacs:		abCd	acbD	abcd_	abdc_
   2163 	 * Pdksh currently goes with GNU behavior since I believe this is the
   2164 	 * most common version of emacs, unless in gmacs mode, in which case
   2165 	 * it does the AT&T ksh gmacs mode.
   2166 	 * This should really be broken up into 3 functions so users can bind
   2167 	 * to the one they want.
   2168 	 */
   2169 	if (xcp == xbuf) {
   2170 		x_e_putc2(7);
   2171 		return (KSTD);
   2172 	} else if (xcp == xep || Flag(FGMACS)) {
   2173 		if (xcp - xbuf == 1) {
   2174 			x_e_putc2(7);
   2175 			return (KSTD);
   2176 		}
   2177 		/*
   2178 		 * Gosling/Unipress emacs style: Swap two characters before
   2179 		 * the cursor, do not change cursor position
   2180 		 */
   2181 		x_bs3(&xcp);
   2182 		if (utf_mbtowc(&tmpa, xcp) == (size_t)-1) {
   2183 			x_e_putc2(7);
   2184 			return (KSTD);
   2185 		}
   2186 		x_bs3(&xcp);
   2187 		if (utf_mbtowc(&tmpb, xcp) == (size_t)-1) {
   2188 			x_e_putc2(7);
   2189 			return (KSTD);
   2190 		}
   2191 		utf_wctomb(xcp, tmpa);
   2192 		x_zotc3(&xcp);
   2193 		utf_wctomb(xcp, tmpb);
   2194 		x_zotc3(&xcp);
   2195 	} else {
   2196 		/*
   2197 		 * GNU emacs style: Swap the characters before and under the
   2198 		 * cursor, move cursor position along one.
   2199 		 */
   2200 		if (utf_mbtowc(&tmpa, xcp) == (size_t)-1) {
   2201 			x_e_putc2(7);
   2202 			return (KSTD);
   2203 		}
   2204 		x_bs3(&xcp);
   2205 		if (utf_mbtowc(&tmpb, xcp) == (size_t)-1) {
   2206 			x_e_putc2(7);
   2207 			return (KSTD);
   2208 		}
   2209 		utf_wctomb(xcp, tmpa);
   2210 		x_zotc3(&xcp);
   2211 		utf_wctomb(xcp, tmpb);
   2212 		x_zotc3(&xcp);
   2213 	}
   2214 	x_modified();
   2215 	return (KSTD);
   2216 }
   2217 
   2218 static int
   2219 x_literal(int c MKSH_A_UNUSED)
   2220 {
   2221 	x_curprefix = -1;
   2222 	return (KSTD);
   2223 }
   2224 
   2225 static int
   2226 x_meta1(int c MKSH_A_UNUSED)
   2227 {
   2228 	x_curprefix = 1;
   2229 	return (KSTD);
   2230 }
   2231 
   2232 static int
   2233 x_meta2(int c MKSH_A_UNUSED)
   2234 {
   2235 	x_curprefix = 2;
   2236 	return (KSTD);
   2237 }
   2238 
   2239 static int
   2240 x_kill(int c MKSH_A_UNUSED)
   2241 {
   2242 	size_t col = xcp - xbuf;
   2243 	size_t lastcol = xep - xbuf;
   2244 	size_t ndel, narg;
   2245 
   2246 	if (x_arg_defaulted || (narg = x_arg) > lastcol)
   2247 		narg = lastcol;
   2248 	if (narg < col) {
   2249 		x_goto(xbuf + narg);
   2250 		ndel = col - narg;
   2251 	} else
   2252 		ndel = narg - col;
   2253 	x_delete(x_nb2nc(ndel), true);
   2254 	return (KSTD);
   2255 }
   2256 
   2257 static void
   2258 x_push(int nchars)
   2259 {
   2260 	char *cp;
   2261 
   2262 	mkssert(xcp != NULL);
   2263 	strndupx(cp, xcp, nchars, AEDIT);
   2264 	if (killstack[killsp])
   2265 		afree(killstack[killsp], AEDIT);
   2266 	killstack[killsp] = cp;
   2267 	killsp = (killsp + 1) % KILLSIZE;
   2268 }
   2269 
   2270 static int
   2271 x_yank(int c MKSH_A_UNUSED)
   2272 {
   2273 	if (killsp == 0)
   2274 		killtp = KILLSIZE;
   2275 	else
   2276 		killtp = killsp;
   2277 	killtp--;
   2278 	if (killstack[killtp] == 0) {
   2279 		x_e_puts("\nnothing to yank");
   2280 		x_redraw(-1);
   2281 		return (KSTD);
   2282 	}
   2283 	xmp = xcp;
   2284 	x_ins(killstack[killtp]);
   2285 	return (KSTD);
   2286 }
   2287 
   2288 static int
   2289 x_meta_yank(int c MKSH_A_UNUSED)
   2290 {
   2291 	size_t len;
   2292 
   2293 	if ((x_last_command != XFUNC_yank && x_last_command != XFUNC_meta_yank) ||
   2294 	    killstack[killtp] == 0) {
   2295 		killtp = killsp;
   2296 		x_e_puts("\nyank something first");
   2297 		x_redraw(-1);
   2298 		return (KSTD);
   2299 	}
   2300 	len = strlen(killstack[killtp]);
   2301 	x_goto(xcp - len);
   2302 	x_delete(x_nb2nc(len), false);
   2303 	do {
   2304 		if (killtp == 0)
   2305 			killtp = KILLSIZE - 1;
   2306 		else
   2307 			killtp--;
   2308 	} while (killstack[killtp] == 0);
   2309 	x_ins(killstack[killtp]);
   2310 	return (KSTD);
   2311 }
   2312 
   2313 static int
   2314 x_abort(int c MKSH_A_UNUSED)
   2315 {
   2316 	/* x_zotc(c); */
   2317 	xlp = xep = xcp = xbp = xbuf;
   2318 	xlp_valid = true;
   2319 	*xcp = 0;
   2320 	x_modified();
   2321 	return (KINTR);
   2322 }
   2323 
   2324 static int
   2325 x_error(int c MKSH_A_UNUSED)
   2326 {
   2327 	x_e_putc2(7);
   2328 	return (KSTD);
   2329 }
   2330 
   2331 #ifndef MKSH_SMALL
   2332 /* special VT100 style key sequence hack */
   2333 static int
   2334 x_vt_hack(int c)
   2335 {
   2336 	/* we only support PF2-'1' for now */
   2337 	if (c != (2 << 8 | '1'))
   2338 		return (x_error(c));
   2339 
   2340 	/* what's the next character? */
   2341 	switch ((c = x_e_getc())) {
   2342 	case '~':
   2343 		x_arg = 1;
   2344 		x_arg_defaulted = true;
   2345 		return (x_mv_begin(0));
   2346 	case ';':
   2347 		/* "interesting" sequence detected */
   2348 		break;
   2349 	default:
   2350 		goto unwind_err;
   2351 	}
   2352 
   2353 	/* XXX x_e_ungetc is one-octet only */
   2354 	if ((c = x_e_getc()) != '5' && c != '3')
   2355 		goto unwind_err;
   2356 
   2357 	/*-
   2358 	 * At this point, we have read the following octets so far:
   2359 	 * - ESC+[ or ESC+O or Ctrl-X (Prefix 2)
   2360 	 * - 1 (vt_hack)
   2361 	 * - ;
   2362 	 * - 5 (Ctrl key combiner) or 3 (Alt key combiner)
   2363 	 * We can now accept one more octet designating the key.
   2364 	 */
   2365 
   2366 	switch ((c = x_e_getc())) {
   2367 	case 'C':
   2368 		return (x_mv_fword(c));
   2369 	case 'D':
   2370 		return (x_mv_bword(c));
   2371 	}
   2372 
   2373  unwind_err:
   2374 	x_e_ungetc(c);
   2375 	return (x_error(c));
   2376 }
   2377 #endif
   2378 
   2379 static char *
   2380 x_mapin(const char *cp, Area *ap)
   2381 {
   2382 	char *news, *op;
   2383 
   2384 	strdupx(news, cp, ap);
   2385 	op = news;
   2386 	while (*cp) {
   2387 		/* XXX -- should handle \^ escape? */
   2388 		if (*cp == '^') {
   2389 			cp++;
   2390 			if (*cp >= '?')
   2391 				/* includes '?'; ASCII */
   2392 				*op++ = CTRL(*cp);
   2393 			else {
   2394 				*op++ = '^';
   2395 				cp--;
   2396 			}
   2397 		} else
   2398 			*op++ = *cp;
   2399 		cp++;
   2400 	}
   2401 	*op = '\0';
   2402 
   2403 	return (news);
   2404 }
   2405 
   2406 static void
   2407 x_mapout2(int c, char **buf)
   2408 {
   2409 	char *p = *buf;
   2410 
   2411 	if (c < ' ' || c == 0x7f) {
   2412 		*p++ = '^';
   2413 		*p++ = UNCTRL(c);
   2414 	} else
   2415 		*p++ = c;
   2416 	*p = 0;
   2417 	*buf = p;
   2418 }
   2419 
   2420 static char *
   2421 x_mapout(int c)
   2422 {
   2423 	static char buf[8];
   2424 	char *bp = buf;
   2425 
   2426 	x_mapout2(c, &bp);
   2427 	return (buf);
   2428 }
   2429 
   2430 static void
   2431 x_print(int prefix, int key)
   2432 {
   2433 	int f = x_tab[prefix][key];
   2434 
   2435 	if (prefix)
   2436 		/* prefix == 1 || prefix == 2 */
   2437 		shf_puts(x_mapout(prefix == 1 ?
   2438 		    CTRL('[') : CTRL('X')), shl_stdout);
   2439 #ifdef MKSH_SMALL
   2440 	shprintf("%s = ", x_mapout(key));
   2441 #else
   2442 	shprintf("%s%s = ", x_mapout(key), (f & 0x80) ? "~" : "");
   2443 	if (XFUNC_VALUE(f) != XFUNC_ins_string)
   2444 #endif
   2445 		shprintf("%s\n", x_ftab[XFUNC_VALUE(f)].xf_name);
   2446 #ifndef MKSH_SMALL
   2447 	else
   2448 		shprintf("'%s'\n", x_atab[prefix][key]);
   2449 #endif
   2450 }
   2451 
   2452 int
   2453 x_bind(const char *a1, const char *a2,
   2454 #ifndef MKSH_SMALL
   2455     /* bind -m */
   2456     bool macro,
   2457 #endif
   2458     /* bind -l */
   2459     bool list)
   2460 {
   2461 	unsigned char f;
   2462 	int prefix, key;
   2463 	char *m1, *m2;
   2464 #ifndef MKSH_SMALL
   2465 	char *sp = NULL;
   2466 	bool hastilde;
   2467 #endif
   2468 
   2469 	if (x_tab == NULL) {
   2470 		bi_errorf("can't bind, not a tty");
   2471 		return (1);
   2472 	}
   2473 	/* List function names */
   2474 	if (list) {
   2475 		for (f = 0; f < NELEM(x_ftab); f++)
   2476 			if (x_ftab[f].xf_name &&
   2477 			    !(x_ftab[f].xf_flags & XF_NOBIND))
   2478 				shprintf("%s\n", x_ftab[f].xf_name);
   2479 		return (0);
   2480 	}
   2481 	if (a1 == NULL) {
   2482 		for (prefix = 0; prefix < X_NTABS; prefix++)
   2483 			for (key = 0; key < X_TABSZ; key++) {
   2484 				f = XFUNC_VALUE(x_tab[prefix][key]);
   2485 				if (f == XFUNC_insert || f == XFUNC_error
   2486 #ifndef MKSH_SMALL
   2487 				    || (macro && f != XFUNC_ins_string)
   2488 #endif
   2489 				    )
   2490 					continue;
   2491 				x_print(prefix, key);
   2492 			}
   2493 		return (0);
   2494 	}
   2495 	m2 = m1 = x_mapin(a1, ATEMP);
   2496 	prefix = 0;
   2497 	for (;; m1++) {
   2498 		key = (unsigned char)*m1;
   2499 		f = XFUNC_VALUE(x_tab[prefix][key]);
   2500 		if (f == XFUNC_meta1)
   2501 			prefix = 1;
   2502 		else if (f == XFUNC_meta2)
   2503 			prefix = 2;
   2504 		else
   2505 			break;
   2506 	}
   2507 	if (*++m1
   2508 #ifndef MKSH_SMALL
   2509 	    && ((*m1 != '~') || *(m1 + 1))
   2510 #endif
   2511 	    ) {
   2512 		char msg[256];
   2513 		const char *c = a1;
   2514 		m1 = msg;
   2515 		while (*c && (size_t)(m1 - msg) < sizeof(msg) - 3)
   2516 			x_mapout2(*c++, &m1);
   2517 		bi_errorf("%s: %s", "too long key sequence", msg);
   2518 		return (1);
   2519 	}
   2520 #ifndef MKSH_SMALL
   2521 	hastilde = tobool(*m1);
   2522 #endif
   2523 	afree(m2, ATEMP);
   2524 
   2525 	if (a2 == NULL) {
   2526 		x_print(prefix, key);
   2527 		return (0);
   2528 	}
   2529 	if (*a2 == 0) {
   2530 		f = XFUNC_insert;
   2531 #ifndef MKSH_SMALL
   2532 	} else if (macro) {
   2533 		f = XFUNC_ins_string;
   2534 		sp = x_mapin(a2, AEDIT);
   2535 #endif
   2536 	} else {
   2537 		for (f = 0; f < NELEM(x_ftab); f++)
   2538 			if (x_ftab[f].xf_name &&
   2539 			    strcmp(x_ftab[f].xf_name, a2) == 0)
   2540 				break;
   2541 		if (f == NELEM(x_ftab) || x_ftab[f].xf_flags & XF_NOBIND) {
   2542 			bi_errorf("%s: %s %s", a2, "no such", Tfunction);
   2543 			return (1);
   2544 		}
   2545 	}
   2546 
   2547 #ifndef MKSH_SMALL
   2548 	if (XFUNC_VALUE(x_tab[prefix][key]) == XFUNC_ins_string &&
   2549 	    x_atab[prefix][key])
   2550 		afree(x_atab[prefix][key], AEDIT);
   2551 #endif
   2552 	x_tab[prefix][key] = f
   2553 #ifndef MKSH_SMALL
   2554 	    | (hastilde ? 0x80 : 0)
   2555 #endif
   2556 	    ;
   2557 #ifndef MKSH_SMALL
   2558 	x_atab[prefix][key] = sp;
   2559 #endif
   2560 
   2561 	/* Track what the user has bound so x_mode(true) won't toast things */
   2562 	if (f == XFUNC_insert)
   2563 		x_bound[(prefix * X_TABSZ + key) / 8] &=
   2564 		    ~(1 << ((prefix * X_TABSZ + key) % 8));
   2565 	else
   2566 		x_bound[(prefix * X_TABSZ + key) / 8] |=
   2567 		    (1 << ((prefix * X_TABSZ + key) % 8));
   2568 
   2569 	return (0);
   2570 }
   2571 
   2572 static void
   2573 bind_if_not_bound(int p, int k, int func)
   2574 {
   2575 	int t;
   2576 
   2577 	/*
   2578 	 * Has user already bound this key?
   2579 	 * If so, do not override it.
   2580 	 */
   2581 	t = p * X_TABSZ + k;
   2582 	if (x_bound[t >> 3] & (1 << (t & 7)))
   2583 		return;
   2584 
   2585 	x_tab[p][k] = func;
   2586 }
   2587 
   2588 static int
   2589 x_set_mark(int c MKSH_A_UNUSED)
   2590 {
   2591 	xmp = xcp;
   2592 	return (KSTD);
   2593 }
   2594 
   2595 static int
   2596 x_kill_region(int c MKSH_A_UNUSED)
   2597 {
   2598 	size_t rsize;
   2599 	char *xr;
   2600 
   2601 	if (xmp == NULL) {
   2602 		x_e_putc2(7);
   2603 		return (KSTD);
   2604 	}
   2605 	if (xmp > xcp) {
   2606 		rsize = xmp - xcp;
   2607 		xr = xcp;
   2608 	} else {
   2609 		rsize = xcp - xmp;
   2610 		xr = xmp;
   2611 	}
   2612 	x_goto(xr);
   2613 	x_delete(x_nb2nc(rsize), true);
   2614 	xmp = xr;
   2615 	return (KSTD);
   2616 }
   2617 
   2618 static int
   2619 x_xchg_point_mark(int c MKSH_A_UNUSED)
   2620 {
   2621 	char *tmp;
   2622 
   2623 	if (xmp == NULL) {
   2624 		x_e_putc2(7);
   2625 		return (KSTD);
   2626 	}
   2627 	tmp = xmp;
   2628 	xmp = xcp;
   2629 	x_goto(tmp);
   2630 	return (KSTD);
   2631 }
   2632 
   2633 static int
   2634 x_noop(int c MKSH_A_UNUSED)
   2635 {
   2636 	return (KSTD);
   2637 }
   2638 
   2639 /*
   2640  *	File/command name completion routines
   2641  */
   2642 static int
   2643 x_comp_comm(int c MKSH_A_UNUSED)
   2644 {
   2645 	do_complete(XCF_COMMAND, CT_COMPLETE);
   2646 	return (KSTD);
   2647 }
   2648 
   2649 static int
   2650 x_list_comm(int c MKSH_A_UNUSED)
   2651 {
   2652 	do_complete(XCF_COMMAND, CT_LIST);
   2653 	return (KSTD);
   2654 }
   2655 
   2656 static int
   2657 x_complete(int c MKSH_A_UNUSED)
   2658 {
   2659 	do_complete(XCF_COMMAND_FILE, CT_COMPLETE);
   2660 	return (KSTD);
   2661 }
   2662 
   2663 static int
   2664 x_enumerate(int c MKSH_A_UNUSED)
   2665 {
   2666 	do_complete(XCF_COMMAND_FILE, CT_LIST);
   2667 	return (KSTD);
   2668 }
   2669 
   2670 static int
   2671 x_comp_file(int c MKSH_A_UNUSED)
   2672 {
   2673 	do_complete(XCF_FILE, CT_COMPLETE);
   2674 	return (KSTD);
   2675 }
   2676 
   2677 static int
   2678 x_list_file(int c MKSH_A_UNUSED)
   2679 {
   2680 	do_complete(XCF_FILE, CT_LIST);
   2681 	return (KSTD);
   2682 }
   2683 
   2684 static int
   2685 x_comp_list(int c MKSH_A_UNUSED)
   2686 {
   2687 	do_complete(XCF_COMMAND_FILE, CT_COMPLIST);
   2688 	return (KSTD);
   2689 }
   2690 
   2691 static int
   2692 x_expand(int c MKSH_A_UNUSED)
   2693 {
   2694 	char **words;
   2695 	int start, end, nwords, i;
   2696 
   2697 	i = XCF_FILE;
   2698 	nwords = x_cf_glob(&i, xbuf, xep - xbuf, xcp - xbuf,
   2699 	    &start, &end, &words);
   2700 
   2701 	if (nwords == 0) {
   2702 		x_e_putc2(7);
   2703 		return (KSTD);
   2704 	}
   2705 	x_goto(xbuf + start);
   2706 	x_delete(x_nb2nc(end - start), false);
   2707 
   2708 	i = 0;
   2709 	while (i < nwords) {
   2710 		if (x_escape(words[i], strlen(words[i]), x_do_ins) < 0 ||
   2711 		    (++i < nwords && x_ins(" ") < 0)) {
   2712 			x_e_putc2(7);
   2713 			return (KSTD);
   2714 		}
   2715 	}
   2716 	x_adjust();
   2717 
   2718 	return (KSTD);
   2719 }
   2720 
   2721 static void
   2722 do_complete(
   2723     /* XCF_{COMMAND,FILE,COMMAND_FILE} */
   2724     int flags,
   2725     /* 0 for list, 1 for complete and 2 for complete-list */
   2726     Comp_type type)
   2727 {
   2728 	char **words;
   2729 	int start, end, nlen, olen, nwords;
   2730 	bool completed;
   2731 
   2732 	nwords = x_cf_glob(&flags, xbuf, xep - xbuf, xcp - xbuf,
   2733 	    &start, &end, &words);
   2734 	/* no match */
   2735 	if (nwords == 0) {
   2736 		x_e_putc2(7);
   2737 		return;
   2738 	}
   2739 	if (type == CT_LIST) {
   2740 		x_print_expansions(nwords, words,
   2741 		    tobool(flags & XCF_IS_COMMAND));
   2742 		x_redraw(0);
   2743 		x_free_words(nwords, words);
   2744 		return;
   2745 	}
   2746 	olen = end - start;
   2747 	nlen = x_longest_prefix(nwords, words);
   2748 	if (nwords == 1) {
   2749 		/*
   2750 		 * always complete single matches;
   2751 		 * any expansion of parameter substitution
   2752 		 * is always at most one result, too
   2753 		 */
   2754 		completed = true;
   2755 	} else {
   2756 		char *unescaped;
   2757 
   2758 		/* make a copy of the original string part */
   2759 		strndupx(unescaped, xbuf + start, olen, ATEMP);
   2760 
   2761 		/* expand any tilde and unescape the string for comparison */
   2762 		unescaped = x_glob_hlp_tilde_and_rem_qchar(unescaped, true);
   2763 
   2764 		/*
   2765 		 * match iff entire original string is part of the
   2766 		 * longest prefix, implying the latter is at least
   2767 		 * the same size (after unescaping)
   2768 		 */
   2769 		completed = !strncmp(words[0], unescaped, strlen(unescaped));
   2770 
   2771 		afree(unescaped, ATEMP);
   2772 	}
   2773 	if (type == CT_COMPLIST && nwords > 1) {
   2774 		/*
   2775 		 * print expansions, since we didn't get back
   2776 		 * just a single match
   2777 		 */
   2778 		x_print_expansions(nwords, words,
   2779 		    tobool(flags & XCF_IS_COMMAND));
   2780 	}
   2781 	if (completed) {
   2782 		/* expand on the command line */
   2783 		xmp = NULL;
   2784 		xcp = xbuf + start;
   2785 		xep -= olen;
   2786 		memmove(xcp, xcp + olen, xep - xcp + 1);
   2787 		x_escape(words[0], nlen, x_do_ins);
   2788 	}
   2789 	x_adjust();
   2790 	/*
   2791 	 * append a space if this is a single non-directory match
   2792 	 * and not a parameter or homedir substitution
   2793 	 */
   2794 	if (nwords == 1 && words[0][nlen - 1] != '/' &&
   2795 	    !(flags & XCF_IS_NOSPACE)) {
   2796 		x_ins(" ");
   2797 	}
   2798 
   2799 	x_free_words(nwords, words);
   2800 }
   2801 
   2802 /*-
   2803  * NAME:
   2804  *	x_adjust - redraw the line adjusting starting point etc.
   2805  *
   2806  * DESCRIPTION:
   2807  *	This function is called when we have exceeded the bounds
   2808  *	of the edit window. It increments x_adj_done so that
   2809  *	functions like x_ins and x_delete know that we have been
   2810  *	called and can skip the x_bs() stuff which has already
   2811  *	been done by x_redraw.
   2812  *
   2813  * RETURN VALUE:
   2814  *	None
   2815  */
   2816 static void
   2817 x_adjust(void)
   2818 {
   2819 	/* flag the fact that we were called. */
   2820 	x_adj_done++;
   2821 	/*
   2822 	 * we had a problem if the prompt length > xx_cols / 2
   2823 	 */
   2824 	if ((xbp = xcp - (x_displen / 2)) < xbuf)
   2825 		xbp = xbuf;
   2826 	if (UTFMODE)
   2827 		while ((xbp > xbuf) && ((*xbp & 0xC0) == 0x80))
   2828 			--xbp;
   2829 	xlp_valid = false;
   2830 	x_redraw(xx_cols);
   2831 	x_flush();
   2832 }
   2833 
   2834 static void
   2835 x_e_ungetc(int c)
   2836 {
   2837 	unget_char = c < 0 ? -1 : (c & 255);
   2838 }
   2839 
   2840 static int
   2841 x_e_getc(void)
   2842 {
   2843 	int c;
   2844 
   2845 	if (unget_char >= 0) {
   2846 		c = unget_char;
   2847 		unget_char = -1;
   2848 		return (c);
   2849 	}
   2850 
   2851 #ifndef MKSH_SMALL
   2852 	if (macroptr) {
   2853 		if ((c = (unsigned char)*macroptr++))
   2854 			return (c);
   2855 		macroptr = NULL;
   2856 	}
   2857 #endif
   2858 
   2859 	return (x_getc());
   2860 }
   2861 
   2862 static void
   2863 x_e_putc2(int c)
   2864 {
   2865 	int width = 1;
   2866 
   2867 	if (c == '\r' || c == '\n')
   2868 		x_col = 0;
   2869 	if (x_col < xx_cols) {
   2870 		if (UTFMODE && (c > 0x7F)) {
   2871 			char utf_tmp[3];
   2872 			size_t x;
   2873 
   2874 			if (c < 0xA0)
   2875 				c = 0xFFFD;
   2876 			x = utf_wctomb(utf_tmp, c);
   2877 			x_putc(utf_tmp[0]);
   2878 			if (x > 1)
   2879 				x_putc(utf_tmp[1]);
   2880 			if (x > 2)
   2881 				x_putc(utf_tmp[2]);
   2882 			width = utf_wcwidth(c);
   2883 		} else
   2884 			x_putc(c);
   2885 		switch (c) {
   2886 		case 7:
   2887 			break;
   2888 		case '\r':
   2889 		case '\n':
   2890 			break;
   2891 		case '\b':
   2892 			x_col--;
   2893 			break;
   2894 		default:
   2895 			x_col += width;
   2896 			break;
   2897 		}
   2898 	}
   2899 	if (x_adj_ok && (x_col < 0 || x_col >= (xx_cols - 2)))
   2900 		x_adjust();
   2901 }
   2902 
   2903 static void
   2904 x_e_putc3(const char **cp)
   2905 {
   2906 	int width = 1, c = **(const unsigned char **)cp;
   2907 
   2908 	if (c == '\r' || c == '\n')
   2909 		x_col = 0;
   2910 	if (x_col < xx_cols) {
   2911 		if (UTFMODE && (c > 0x7F)) {
   2912 			char *cp2;
   2913 
   2914 			width = utf_widthadj(*cp, (const char **)&cp2);
   2915 			while (*cp < cp2)
   2916 				x_putcf(*(*cp)++);
   2917 		} else {
   2918 			(*cp)++;
   2919 			x_putc(c);
   2920 		}
   2921 		switch (c) {
   2922 		case 7:
   2923 			break;
   2924 		case '\r':
   2925 		case '\n':
   2926 			break;
   2927 		case '\b':
   2928 			x_col--;
   2929 			break;
   2930 		default:
   2931 			x_col += width;
   2932 			break;
   2933 		}
   2934 	}
   2935 	if (x_adj_ok && (x_col < 0 || x_col >= (xx_cols - 2)))
   2936 		x_adjust();
   2937 }
   2938 
   2939 static void
   2940 x_e_puts(const char *s)
   2941 {
   2942 	int adj = x_adj_done;
   2943 
   2944 	while (*s && adj == x_adj_done)
   2945 		x_e_putc3(&s);
   2946 }
   2947 
   2948 /*-
   2949  * NAME:
   2950  *	x_set_arg - set an arg value for next function
   2951  *
   2952  * DESCRIPTION:
   2953  *	This is a simple implementation of M-[0-9].
   2954  *
   2955  * RETURN VALUE:
   2956  *	KSTD
   2957  */
   2958 static int
   2959 x_set_arg(int c)
   2960 {
   2961 	unsigned int n = 0;
   2962 	bool first = true;
   2963 
   2964 	/* strip command prefix */
   2965 	c &= 255;
   2966 	while (c >= 0 && ksh_isdigit(c)) {
   2967 		n = n * 10 + (c - '0');
   2968 		if (n > LINE)
   2969 			/* upper bound for repeat */
   2970 			goto x_set_arg_too_big;
   2971 		c = x_e_getc();
   2972 		first = false;
   2973 	}
   2974 	if (c < 0 || first) {
   2975  x_set_arg_too_big:
   2976 		x_e_putc2(7);
   2977 		x_arg = 1;
   2978 		x_arg_defaulted = true;
   2979 	} else {
   2980 		x_e_ungetc(c);
   2981 		x_arg = n;
   2982 		x_arg_defaulted = false;
   2983 	}
   2984 	return (KSTD);
   2985 }
   2986 
   2987 /* Comment or uncomment the current line. */
   2988 static int
   2989 x_comment(int c MKSH_A_UNUSED)
   2990 {
   2991 	int oldsize = x_size_str(xbuf);
   2992 	ssize_t len = xep - xbuf;
   2993 	int ret = x_do_comment(xbuf, xend - xbuf, &len);
   2994 
   2995 	if (ret < 0)
   2996 		x_e_putc2(7);
   2997 	else {
   2998 		x_modified();
   2999 		xep = xbuf + len;
   3000 		*xep = '\0';
   3001 		xcp = xbp = xbuf;
   3002 		x_redraw(oldsize);
   3003 		if (ret > 0)
   3004 			return (x_newline('\n'));
   3005 	}
   3006 	return (KSTD);
   3007 }
   3008 
   3009 static int
   3010 x_version(int c MKSH_A_UNUSED)
   3011 {
   3012 	char *o_xbuf = xbuf, *o_xend = xend;
   3013 	char *o_xbp = xbp, *o_xep = xep, *o_xcp = xcp;
   3014 	int lim = x_lastcp() - xbp;
   3015 	size_t vlen;
   3016 	char *v;
   3017 
   3018 	strdupx(v, KSH_VERSION, ATEMP);
   3019 
   3020 	xbuf = xbp = xcp = v;
   3021 	xend = xep = v + (vlen = strlen(v));
   3022 	x_redraw(lim);
   3023 	x_flush();
   3024 
   3025 	c = x_e_getc();
   3026 	xbuf = o_xbuf;
   3027 	xend = o_xend;
   3028 	xbp = o_xbp;
   3029 	xep = o_xep;
   3030 	xcp = o_xcp;
   3031 	x_redraw((int)vlen);
   3032 
   3033 	if (c < 0)
   3034 		return (KSTD);
   3035 	/* This is what AT&T ksh seems to do... Very bizarre */
   3036 	if (c != ' ')
   3037 		x_e_ungetc(c);
   3038 
   3039 	afree(v, ATEMP);
   3040 	return (KSTD);
   3041 }
   3042 
   3043 #ifndef MKSH_SMALL
   3044 static int
   3045 x_edit_line(int c MKSH_A_UNUSED)
   3046 {
   3047 	if (x_arg_defaulted) {
   3048 		if (xep == xbuf) {
   3049 			x_e_putc2(7);
   3050 			return (KSTD);
   3051 		}
   3052 		if (modified) {
   3053 			*xep = '\0';
   3054 			histsave(&source->line, xbuf, true, true);
   3055 			x_arg = 0;
   3056 		} else
   3057 			x_arg = source->line - (histptr - x_histp);
   3058 	}
   3059 	if (x_arg)
   3060 		shf_snprintf(xbuf, xend - xbuf, "%s %d",
   3061 		    "fc -e ${VISUAL:-${EDITOR:-vi}} --", x_arg);
   3062 	else
   3063 		strlcpy(xbuf, "fc -e ${VISUAL:-${EDITOR:-vi}} --", xend - xbuf);
   3064 	xep = xbuf + strlen(xbuf);
   3065 	return (x_newline('\n'));
   3066 }
   3067 #endif
   3068 
   3069 /*-
   3070  * NAME:
   3071  *	x_prev_histword - recover word from prev command
   3072  *
   3073  * DESCRIPTION:
   3074  *	This function recovers the last word from the previous
   3075  *	command and inserts it into the current edit line. If a
   3076  *	numeric arg is supplied then the n'th word from the
   3077  *	start of the previous command is used.
   3078  *	As a side effect, trashes the mark in order to achieve
   3079  *	being called in a repeatable fashion.
   3080  *
   3081  *	Bound to M-.
   3082  *
   3083  * RETURN VALUE:
   3084  *	KSTD
   3085  */
   3086 static int
   3087 x_prev_histword(int c MKSH_A_UNUSED)
   3088 {
   3089 	char *rcp, *cp;
   3090 	char **xhp;
   3091 	int m = 1;
   3092 	/* -1 = defaulted; 0+ = argument */
   3093 	static int last_arg = -1;
   3094 
   3095 	if (x_last_command == XFUNC_prev_histword) {
   3096 		if (xmp && modified > 1)
   3097 			x_kill_region(0);
   3098 		if (modified)
   3099 			m = modified;
   3100 	} else
   3101 		last_arg = x_arg_defaulted ? -1 : x_arg;
   3102 	xhp = histptr - (m - 1);
   3103 	if ((xhp < history) || !(cp = *xhp)) {
   3104 		x_e_putc2(7);
   3105 		x_modified();
   3106 		return (KSTD);
   3107 	}
   3108 	x_set_mark(0);
   3109 	if ((x_arg = last_arg) == -1) {
   3110 		/* x_arg_defaulted */
   3111 
   3112 		rcp = &cp[strlen(cp) - 1];
   3113 		/*
   3114 		 * ignore white-space after the last word
   3115 		 */
   3116 		while (rcp > cp && is_cfs(*rcp))
   3117 			rcp--;
   3118 		while (rcp > cp && !is_cfs(*rcp))
   3119 			rcp--;
   3120 		if (is_cfs(*rcp))
   3121 			rcp++;
   3122 		x_ins(rcp);
   3123 	} else {
   3124 		/* not x_arg_defaulted */
   3125 		char ch;
   3126 
   3127 		rcp = cp;
   3128 		/*
   3129 		 * ignore white-space at start of line
   3130 		 */
   3131 		while (*rcp && is_cfs(*rcp))
   3132 			rcp++;
   3133 		while (x_arg-- > 0) {
   3134 			while (*rcp && !is_cfs(*rcp))
   3135 				rcp++;
   3136 			while (*rcp && is_cfs(*rcp))
   3137 				rcp++;
   3138 		}
   3139 		cp = rcp;
   3140 		while (*rcp && !is_cfs(*rcp))
   3141 			rcp++;
   3142 		ch = *rcp;
   3143 		*rcp = '\0';
   3144 		x_ins(cp);
   3145 		*rcp = ch;
   3146 	}
   3147 	modified = m + 1;
   3148 	return (KSTD);
   3149 }
   3150 
   3151 #ifndef MKSH_SMALL
   3152 /* Uppercase N(1) words */
   3153 static int
   3154 x_fold_upper(int c MKSH_A_UNUSED)
   3155 {
   3156 	return (x_fold_case('U'));
   3157 }
   3158 
   3159 /* Lowercase N(1) words */
   3160 static int
   3161 x_fold_lower(int c MKSH_A_UNUSED)
   3162 {
   3163 	return (x_fold_case('L'));
   3164 }
   3165 
   3166 /* Titlecase N(1) words */
   3167 static int
   3168 x_fold_capitalise(int c MKSH_A_UNUSED)
   3169 {
   3170 	return (x_fold_case('C'));
   3171 }
   3172 
   3173 /*-
   3174  * NAME:
   3175  *	x_fold_case - convert word to UPPER/lower/Capital case
   3176  *
   3177  * DESCRIPTION:
   3178  *	This function is used to implement M-U/M-u, M-L/M-l, M-C/M-c
   3179  *	to UPPER CASE, lower case or Capitalise Words.
   3180  *
   3181  * RETURN VALUE:
   3182  *	None
   3183  */
   3184 static int
   3185 x_fold_case(int c)
   3186 {
   3187 	char *cp = xcp;
   3188 
   3189 	if (cp == xep) {
   3190 		x_e_putc2(7);
   3191 		return (KSTD);
   3192 	}
   3193 	while (x_arg--) {
   3194 		/*
   3195 		 * first skip over any white-space
   3196 		 */
   3197 		while (cp != xep && is_mfs(*cp))
   3198 			cp++;
   3199 		/*
   3200 		 * do the first char on its own since it may be
   3201 		 * a different action than for the rest.
   3202 		 */
   3203 		if (cp != xep) {
   3204 			if (c == 'L')
   3205 				/* lowercase */
   3206 				*cp = ksh_tolower(*cp);
   3207 			else
   3208 				/* uppercase, capitalise */
   3209 				*cp = ksh_toupper(*cp);
   3210 			cp++;
   3211 		}
   3212 		/*
   3213 		 * now for the rest of the word
   3214 		 */
   3215 		while (cp != xep && !is_mfs(*cp)) {
   3216 			if (c == 'U')
   3217 				/* uppercase */
   3218 				*cp = ksh_toupper(*cp);
   3219 			else
   3220 				/* lowercase, capitalise */
   3221 				*cp = ksh_tolower(*cp);
   3222 			cp++;
   3223 		}
   3224 	}
   3225 	x_goto(cp);
   3226 	x_modified();
   3227 	return (KSTD);
   3228 }
   3229 #endif
   3230 
   3231 /*-
   3232  * NAME:
   3233  *	x_lastcp - last visible char
   3234  *
   3235  * SYNOPSIS:
   3236  *	x_lastcp()
   3237  *
   3238  * DESCRIPTION:
   3239  *	This function returns a pointer to that char in the
   3240  *	edit buffer that will be the last displayed on the
   3241  *	screen. The sequence:
   3242  *
   3243  *	cp = x_lastcp();
   3244  *	while (cp > xcp)
   3245  *		x_bs3(&cp);
   3246  *
   3247  *	Will position the cursor correctly on the screen.
   3248  *
   3249  * RETURN VALUE:
   3250  *	cp or NULL
   3251  */
   3252 static char *
   3253 x_lastcp(void)
   3254 {
   3255 	if (!xlp_valid) {
   3256 		int i = 0, j;
   3257 		char *xlp2;
   3258 
   3259 		xlp = xbp;
   3260 		while (xlp < xep) {
   3261 			j = x_size2(xlp, &xlp2);
   3262 			if ((i + j) > x_displen)
   3263 				break;
   3264 			i += j;
   3265 			xlp = xlp2;
   3266 		}
   3267 	}
   3268 	xlp_valid = true;
   3269 	return (xlp);
   3270 }
   3271 
   3272 static void
   3273 x_mode(bool onoff)
   3274 {
   3275 	static bool x_cur_mode;
   3276 
   3277 	if (x_cur_mode == onoff)
   3278 		return;
   3279 	x_cur_mode = onoff;
   3280 
   3281 	if (onoff) {
   3282 		x_mkraw(tty_fd, NULL, false);
   3283 
   3284 		edchars.erase = tty_state.c_cc[VERASE];
   3285 		edchars.kill = tty_state.c_cc[VKILL];
   3286 		edchars.intr = tty_state.c_cc[VINTR];
   3287 		edchars.quit = tty_state.c_cc[VQUIT];
   3288 		edchars.eof = tty_state.c_cc[VEOF];
   3289 #ifdef VWERASE
   3290 		edchars.werase = tty_state.c_cc[VWERASE];
   3291 #endif
   3292 
   3293 #ifdef _POSIX_VDISABLE
   3294 		/* Convert unset values to internal 'unset' value */
   3295 		if (edchars.erase == _POSIX_VDISABLE)
   3296 			edchars.erase = -1;
   3297 		if (edchars.kill == _POSIX_VDISABLE)
   3298 			edchars.kill = -1;
   3299 		if (edchars.intr == _POSIX_VDISABLE)
   3300 			edchars.intr = -1;
   3301 		if (edchars.quit == _POSIX_VDISABLE)
   3302 			edchars.quit = -1;
   3303 		if (edchars.eof == _POSIX_VDISABLE)
   3304 			edchars.eof = -1;
   3305 		if (edchars.werase == _POSIX_VDISABLE)
   3306 			edchars.werase = -1;
   3307 #endif
   3308 
   3309 		if (edchars.erase >= 0) {
   3310 			bind_if_not_bound(0, edchars.erase, XFUNC_del_back);
   3311 			bind_if_not_bound(1, edchars.erase, XFUNC_del_bword);
   3312 		}
   3313 		if (edchars.kill >= 0)
   3314 			bind_if_not_bound(0, edchars.kill, XFUNC_del_line);
   3315 		if (edchars.werase >= 0)
   3316 			bind_if_not_bound(0, edchars.werase, XFUNC_del_bword);
   3317 		if (edchars.intr >= 0)
   3318 			bind_if_not_bound(0, edchars.intr, XFUNC_abort);
   3319 		if (edchars.quit >= 0)
   3320 			bind_if_not_bound(0, edchars.quit, XFUNC_noop);
   3321 	} else
   3322 		mksh_tcset(tty_fd, &tty_state);
   3323 }
   3324 
   3325 #if !MKSH_S_NOVI
   3326 /* +++ vi editing mode +++ */
   3327 
   3328 #define Ctrl(c)		(c&0x1f)
   3329 
   3330 struct edstate {
   3331 	char *cbuf;
   3332 	ssize_t winleft;
   3333 	ssize_t cbufsize;
   3334 	ssize_t linelen;
   3335 	ssize_t cursor;
   3336 };
   3337 
   3338 static int vi_hook(int);
   3339 static int nextstate(int);
   3340 static int vi_insert(int);
   3341 static int vi_cmd(int, const char *);
   3342 static int domove(int, const char *, int);
   3343 static int redo_insert(int);
   3344 static void yank_range(int, int);
   3345 static int bracktype(int);
   3346 static void save_cbuf(void);
   3347 static void restore_cbuf(void);
   3348 static int putbuf(const char *, ssize_t, int);
   3349 static void del_range(int, int);
   3350 static int findch(int, int, int, int);
   3351 static int forwword(int);
   3352 static int backword(int);
   3353 static int endword(int);
   3354 static int Forwword(int);
   3355 static int Backword(int);
   3356 static int Endword(int);
   3357 static int grabhist(int, int);
   3358 static int grabsearch(int, int, int, const char *);
   3359 static void redraw_line(bool);
   3360 static void refresh(int);
   3361 static int outofwin(void);
   3362 static void rewindow(void);
   3363 static int newcol(int, int);
   3364 static void display(char *, char *, int);
   3365 static void ed_mov_opt(int, char *);
   3366 static int expand_word(int);
   3367 static int complete_word(int, int);
   3368 static int print_expansions(struct edstate *, int);
   3369 #define char_len(c)	((c) < ' ' || (c) == 0x7F ? 2 : 1)
   3370 static void x_vi_zotc(int);
   3371 static void vi_error(void);
   3372 static void vi_macro_reset(void);
   3373 static int x_vi_putbuf(const char *, size_t);
   3374 
   3375 #define vC	0x01		/* a valid command that isn't a vM, vE, vU */
   3376 #define vM	0x02		/* movement command (h, l, etc.) */
   3377 #define vE	0x04		/* extended command (c, d, y) */
   3378 #define vX	0x08		/* long command (@, f, F, t, T, etc.) */
   3379 #define vU	0x10		/* an UN-undoable command (that isn't a vM) */
   3380 #define vB	0x20		/* bad command (^@) */
   3381 #define vZ	0x40		/* repeat count defaults to 0 (not 1) */
   3382 #define vS	0x80		/* search (/, ?) */
   3383 
   3384 #define is_bad(c)	(classify[(c)&0x7f]&vB)
   3385 #define is_cmd(c)	(classify[(c)&0x7f]&(vM|vE|vC|vU))
   3386 #define is_move(c)	(classify[(c)&0x7f]&vM)
   3387 #define is_extend(c)	(classify[(c)&0x7f]&vE)
   3388 #define is_long(c)	(classify[(c)&0x7f]&vX)
   3389 #define is_undoable(c)	(!(classify[(c)&0x7f]&vU))
   3390 #define is_srch(c)	(classify[(c)&0x7f]&vS)
   3391 #define is_zerocount(c)	(classify[(c)&0x7f]&vZ)
   3392 
   3393 static const unsigned char classify[128] = {
   3394 /*	 0	1	2	3	4	5	6	7	*/
   3395 /* 0	^@	^A	^B	^C	^D	^E	^F	^G	*/
   3396 	vB,	0,	0,	0,	0,	vC|vU,	vC|vZ,	0,
   3397 /* 1	^H	^I	^J	^K	^L	^M	^N	^O	*/
   3398 	vM,	vC|vZ,	0,	0,	vC|vU,	0,	vC,	0,
   3399 /* 2	^P	^Q	^R	^S	^T	^U	^V	^W	*/
   3400 	vC,	0,	vC|vU,	0,	0,	0,	vC,	0,
   3401 /* 3	^X	^Y	^Z	^[	^\	^]	^^	^_	*/
   3402 	vC,	0,	0,	vC|vZ,	0,	0,	0,	0,
   3403 /* 4	<space>	!	"	#	$	%	&	'	*/
   3404 	vM,	0,	0,	vC,	vM,	vM,	0,	0,
   3405 /* 5	(	)	*	+	,	-	.	/	*/
   3406 	0,	0,	vC,	vC,	vM,	vC,	0,	vC|vS,
   3407 /* 6	0	1	2	3	4	5	6	7	*/
   3408 	vM,	0,	0,	0,	0,	0,	0,	0,
   3409 /* 7	8	9	:	;	<	=	>	?	*/
   3410 	0,	0,	0,	vM,	0,	vC,	0,	vC|vS,
   3411 /* 8	@	A	B	C	D	E	F	G	*/
   3412 	vC|vX,	vC,	vM,	vC,	vC,	vM,	vM|vX,	vC|vU|vZ,
   3413 /* 9	H	I	J	K	L	M	N	O	*/
   3414 	0,	vC,	0,	0,	0,	0,	vC|vU,	0,
   3415 /* A	P	Q	R	S	T	U	V	W	*/
   3416 	vC,	0,	vC,	vC,	vM|vX,	vC,	0,	vM,
   3417 /* B	X	Y	Z	[	\	]	^	_	*/
   3418 	vC,	vC|vU,	0,	0,	vC|vZ,	0,	vM,	vC|vZ,
   3419 /* C	`	a	b	c	d	e	f	g	*/
   3420 	0,	vC,	vM,	vE,	vE,	vM,	vM|vX,	vC|vZ,
   3421 /* D	h	i	j	k	l	m	n	o	*/
   3422 	vM,	vC,	vC|vU,	vC|vU,	vM,	0,	vC|vU,	0,
   3423 /* E	p	q	r	s	t	u	v	w	*/
   3424 	vC,	0,	vX,	vC,	vM|vX,	vC|vU,	vC|vU|vZ, vM,
   3425 /* F	x	y	z	{	|	}	~	^?	*/
   3426 	vC,	vE|vU,	0,	0,	vM|vZ,	0,	vC,	0
   3427 };
   3428 
   3429 #define MAXVICMD	3
   3430 #define SRCHLEN		40
   3431 
   3432 #define INSERT		1
   3433 #define REPLACE		2
   3434 
   3435 #define VNORMAL		0		/* command, insert or replace mode */
   3436 #define VARG1		1		/* digit prefix (first, eg, 5l) */
   3437 #define VEXTCMD		2		/* cmd + movement (eg, cl) */
   3438 #define VARG2		3		/* digit prefix (second, eg, 2c3l) */
   3439 #define VXCH		4		/* f, F, t, T, @ */
   3440 #define VFAIL		5		/* bad command */
   3441 #define VCMD		6		/* single char command (eg, X) */
   3442 #define VREDO		7		/* . */
   3443 #define VLIT		8		/* ^V */
   3444 #define VSEARCH		9		/* /, ? */
   3445 #define VVERSION	10		/* <ESC> ^V */
   3446 
   3447 static char		undocbuf[LINE];
   3448 
   3449 static struct edstate	*save_edstate(struct edstate *old);
   3450 static void		restore_edstate(struct edstate *old, struct edstate *news);
   3451 static void		free_edstate(struct edstate *old);
   3452 
   3453 static struct edstate	ebuf;
   3454 static struct edstate	undobuf = { undocbuf, 0, LINE, 0, 0 };
   3455 
   3456 static struct edstate	*es;			/* current editor state */
   3457 static struct edstate	*undo;
   3458 
   3459 static char ibuf[LINE];			/* input buffer */
   3460 static int first_insert;		/* set when starting in insert mode */
   3461 static int saved_inslen;		/* saved inslen for first insert */
   3462 static int inslen;			/* length of input buffer */
   3463 static int srchlen;			/* length of current search pattern */
   3464 static char ybuf[LINE];			/* yank buffer */
   3465 static int yanklen;			/* length of yank buffer */
   3466 static int fsavecmd = ' ';		/* last find command */
   3467 static int fsavech;			/* character to find */
   3468 static char lastcmd[MAXVICMD];		/* last non-move command */
   3469 static int lastac;			/* argcnt for lastcmd */
   3470 static int lastsearch = ' ';		/* last search command */
   3471 static char srchpat[SRCHLEN];		/* last search pattern */
   3472 static int insert;			/* non-zero in insert mode */
   3473 static int hnum;			/* position in history */
   3474 static int ohnum;			/* history line copied (after mod) */
   3475 static int hlast;			/* 1 past last position in history */
   3476 static int state;
   3477 
   3478 /*
   3479  * Information for keeping track of macros that are being expanded.
   3480  * The format of buf is the alias contents followed by a NUL byte followed
   3481  * by the name (letter) of the alias. The end of the buffer is marked by
   3482  * a double NUL. The name of the alias is stored so recursive macros can
   3483  * be detected.
   3484  */
   3485 struct macro_state {
   3486 	unsigned char *p;	/* current position in buf */
   3487 	unsigned char *buf;	/* pointer to macro(s) being expanded */
   3488 	size_t len;		/* how much data in buffer */
   3489 };
   3490 static struct macro_state macro;
   3491 
   3492 /* last input was expanded */
   3493 static enum expand_mode {
   3494 	NONE = 0, EXPAND, COMPLETE, PRINT
   3495 } expanded;
   3496 
   3497 static int
   3498 x_vi(char *buf, size_t len)
   3499 {
   3500 	int c;
   3501 
   3502 	state = VNORMAL;
   3503 	ohnum = hnum = hlast = histnum(-1) + 1;
   3504 	insert = INSERT;
   3505 	saved_inslen = inslen;
   3506 	first_insert = 1;
   3507 	inslen = 0;
   3508 	vi_macro_reset();
   3509 
   3510 	es = &ebuf;
   3511 	es->cbuf = buf;
   3512 	undo = &undobuf;
   3513 	undo->cbufsize = es->cbufsize = len > LINE ? LINE : len;
   3514 
   3515 	es->linelen = undo->linelen = 0;
   3516 	es->cursor = undo->cursor = 0;
   3517 	es->winleft = undo->winleft = 0;
   3518 
   3519 	cur_col = promptlen(prompt);
   3520 	prompt_trunc = (cur_col / x_cols) * x_cols;
   3521 	cur_col -= prompt_trunc;
   3522 
   3523 	pprompt(prompt, 0);
   3524 	if ((mksh_uari_t)cur_col > (mksh_uari_t)x_cols - 3 - MIN_EDIT_SPACE) {
   3525 		prompt_redraw = false;
   3526 		cur_col = 0;
   3527 		x_putc('\n');
   3528 	} else
   3529 		prompt_redraw = true;
   3530 	pwidth = cur_col;
   3531 
   3532 	if (!wbuf_len || wbuf_len != x_cols - 3) {
   3533 		wbuf_len = x_cols - 3;
   3534 		wbuf[0] = aresize(wbuf[0], wbuf_len, APERM);
   3535 		wbuf[1] = aresize(wbuf[1], wbuf_len, APERM);
   3536 	}
   3537 	if (wbuf_len) {
   3538 		memset(wbuf[0], ' ', wbuf_len);
   3539 		memset(wbuf[1], ' ', wbuf_len);
   3540 	}
   3541 	winwidth = x_cols - pwidth - 3;
   3542 	win = 0;
   3543 	morec = ' ';
   3544 	lastref = 1;
   3545 	holdlen = 0;
   3546 
   3547 	editmode = 2;
   3548 	x_flush();
   3549 	while (/* CONSTCOND */ 1) {
   3550 		if (macro.p) {
   3551 			c = *macro.p++;
   3552 			/* end of current macro? */
   3553 			if (!c) {
   3554 				/* more macros left to finish? */
   3555 				if (*macro.p++)
   3556 					continue;
   3557 				/* must be the end of all the macros */
   3558 				vi_macro_reset();
   3559 				c = x_getc();
   3560 			}
   3561 		} else
   3562 			c = x_getc();
   3563 
   3564 		if (c == -1)
   3565 			break;
   3566 		if (state != VLIT) {
   3567 			if (c == edchars.intr || c == edchars.quit) {
   3568 				/* pretend we got an interrupt */
   3569 				x_vi_zotc(c);
   3570 				x_flush();
   3571 				trapsig(c == edchars.intr ? SIGINT : SIGQUIT);
   3572 				x_mode(false);
   3573 				unwind(LSHELL);
   3574 			} else if (c == edchars.eof && state != VVERSION) {
   3575 				if (es->linelen == 0) {
   3576 					x_vi_zotc(edchars.eof);
   3577 					c = -1;
   3578 					break;
   3579 				}
   3580 				continue;
   3581 			}
   3582 		}
   3583 		if (vi_hook(c))
   3584 			break;
   3585 		x_flush();
   3586 	}
   3587 
   3588 	x_putc('\r');
   3589 	x_putc('\n');
   3590 	x_flush();
   3591 
   3592 	if (c == -1 || (ssize_t)len <= es->linelen)
   3593 		return (-1);
   3594 
   3595 	if (es->cbuf != buf)
   3596 		memmove(buf, es->cbuf, es->linelen);
   3597 
   3598 	buf[es->linelen++] = '\n';
   3599 
   3600 	return (es->linelen);
   3601 }
   3602 
   3603 static int
   3604 vi_hook(int ch)
   3605 {
   3606 	static char curcmd[MAXVICMD], locpat[SRCHLEN];
   3607 	static int cmdlen, argc1, argc2;
   3608 
   3609 	switch (state) {
   3610 
   3611 	case VNORMAL:
   3612 		if (insert != 0) {
   3613 			if (ch == Ctrl('v')) {
   3614 				state = VLIT;
   3615 				ch = '^';
   3616 			}
   3617 			switch (vi_insert(ch)) {
   3618 			case -1:
   3619 				vi_error();
   3620 				state = VNORMAL;
   3621 				break;
   3622 			case 0:
   3623 				if (state == VLIT) {
   3624 					es->cursor--;
   3625 					refresh(0);
   3626 				} else
   3627 					refresh(insert != 0);
   3628 				break;
   3629 			case 1:
   3630 				return (1);
   3631 			}
   3632 		} else {
   3633 			if (ch == '\r' || ch == '\n')
   3634 				return (1);
   3635 			cmdlen = 0;
   3636 			argc1 = 0;
   3637 			if (ch >= '1' && ch <= '9') {
   3638 				argc1 = ch - '0';
   3639 				state = VARG1;
   3640 			} else {
   3641 				curcmd[cmdlen++] = ch;
   3642 				state = nextstate(ch);
   3643 				if (state == VSEARCH) {
   3644 					save_cbuf();
   3645 					es->cursor = 0;
   3646 					es->linelen = 0;
   3647 					if (ch == '/') {
   3648 						if (putbuf("/", 1, 0) != 0)
   3649 							return (-1);
   3650 					} else if (putbuf("?", 1, 0) != 0)
   3651 						return (-1);
   3652 					refresh(0);
   3653 				}
   3654 				if (state == VVERSION) {
   3655 					save_cbuf();
   3656 					es->cursor = 0;
   3657 					es->linelen = 0;
   3658 					putbuf(KSH_VERSION,
   3659 					    strlen(KSH_VERSION), 0);
   3660 					refresh(0);
   3661 				}
   3662 			}
   3663 		}
   3664 		break;
   3665 
   3666 	case VLIT:
   3667 		if (is_bad(ch)) {
   3668 			del_range(es->cursor, es->cursor + 1);
   3669 			vi_error();
   3670 		} else
   3671 			es->cbuf[es->cursor++] = ch;
   3672 		refresh(1);
   3673 		state = VNORMAL;
   3674 		break;
   3675 
   3676 	case VVERSION:
   3677 		restore_cbuf();
   3678 		state = VNORMAL;
   3679 		refresh(0);
   3680 		break;
   3681 
   3682 	case VARG1:
   3683 		if (ksh_isdigit(ch))
   3684 			argc1 = argc1 * 10 + ch - '0';
   3685 		else {
   3686 			curcmd[cmdlen++] = ch;
   3687 			state = nextstate(ch);
   3688 		}
   3689 		break;
   3690 
   3691 	case VEXTCMD:
   3692 		argc2 = 0;
   3693 		if (ch >= '1' && ch <= '9') {
   3694 			argc2 = ch - '0';
   3695 			state = VARG2;
   3696 			return (0);
   3697 		} else {
   3698 			curcmd[cmdlen++] = ch;
   3699 			if (ch == curcmd[0])
   3700 				state = VCMD;
   3701 			else if (is_move(ch))
   3702 				state = nextstate(ch);
   3703 			else
   3704 				state = VFAIL;
   3705 		}
   3706 		break;
   3707 
   3708 	case VARG2:
   3709 		if (ksh_isdigit(ch))
   3710 			argc2 = argc2 * 10 + ch - '0';
   3711 		else {
   3712 			if (argc1 == 0)
   3713 				argc1 = argc2;
   3714 			else
   3715 				argc1 *= argc2;
   3716 			curcmd[cmdlen++] = ch;
   3717 			if (ch == curcmd[0])
   3718 				state = VCMD;
   3719 			else if (is_move(ch))
   3720 				state = nextstate(ch);
   3721 			else
   3722 				state = VFAIL;
   3723 		}
   3724 		break;
   3725 
   3726 	case VXCH:
   3727 		if (ch == Ctrl('['))
   3728 			state = VNORMAL;
   3729 		else {
   3730 			curcmd[cmdlen++] = ch;
   3731 			state = VCMD;
   3732 		}
   3733 		break;
   3734 
   3735 	case VSEARCH:
   3736 		if (ch == '\r' || ch == '\n' /*|| ch == Ctrl('[')*/ ) {
   3737 			restore_cbuf();
   3738 			/* Repeat last search? */
   3739 			if (srchlen == 0) {
   3740 				if (!srchpat[0]) {
   3741 					vi_error();
   3742 					state = VNORMAL;
   3743 					refresh(0);
   3744 					return (0);
   3745 				}
   3746 			} else {
   3747 				locpat[srchlen] = '\0';
   3748 				memcpy(srchpat, locpat, srchlen + 1);
   3749 			}
   3750 			state = VCMD;
   3751 		} else if (ch == edchars.erase || ch == Ctrl('h')) {
   3752 			if (srchlen != 0) {
   3753 				srchlen--;
   3754 				es->linelen -= char_len((unsigned char)locpat[srchlen]);
   3755 				es->cursor = es->linelen;
   3756 				refresh(0);
   3757 				return (0);
   3758 			}
   3759 			restore_cbuf();
   3760 			state = VNORMAL;
   3761 			refresh(0);
   3762 		} else if (ch == edchars.kill) {
   3763 			srchlen = 0;
   3764 			es->linelen = 1;
   3765 			es->cursor = 1;
   3766 			refresh(0);
   3767 			return (0);
   3768 		} else if (ch == edchars.werase) {
   3769 			int i, n = srchlen;
   3770 			struct edstate new_es, *save_es;
   3771 
   3772 			new_es.cursor = n;
   3773 			new_es.cbuf = locpat;
   3774 
   3775 			save_es = es;
   3776 			es = &new_es;
   3777 			n = backword(1);
   3778 			es = save_es;
   3779 
   3780 			for (i = srchlen; --i >= n; )
   3781 				es->linelen -= char_len((unsigned char)locpat[i]);
   3782 			srchlen = n;
   3783 			es->cursor = es->linelen;
   3784 			refresh(0);
   3785 			return (0);
   3786 		} else {
   3787 			if (srchlen == SRCHLEN - 1)
   3788 				vi_error();
   3789 			else {
   3790 				locpat[srchlen++] = ch;
   3791 				if (ch < ' ' || ch == 0x7f) {
   3792 					if ((size_t)es->linelen + 2 >
   3793 					    (size_t)es->cbufsize)
   3794 						vi_error();
   3795 					es->cbuf[es->linelen++] = '^';
   3796 					es->cbuf[es->linelen++] = ch ^ '@';
   3797 				} else {
   3798 					if (es->linelen >= es->cbufsize)
   3799 						vi_error();
   3800 					es->cbuf[es->linelen++] = ch;
   3801 				}
   3802 				es->cursor = es->linelen;
   3803 				refresh(0);
   3804 			}
   3805 			return (0);
   3806 		}
   3807 		break;
   3808 	}
   3809 
   3810 	switch (state) {
   3811 	case VCMD:
   3812 		state = VNORMAL;
   3813 		switch (vi_cmd(argc1, curcmd)) {
   3814 		case -1:
   3815 			vi_error();
   3816 			refresh(0);
   3817 			break;
   3818 		case 0:
   3819 			if (insert != 0)
   3820 				inslen = 0;
   3821 			refresh(insert != 0);
   3822 			break;
   3823 		case 1:
   3824 			refresh(0);
   3825 			return (1);
   3826 		case 2:
   3827 			/* back from a 'v' command - don't redraw the screen */
   3828 			return (1);
   3829 		}
   3830 		break;
   3831 
   3832 	case VREDO:
   3833 		state = VNORMAL;
   3834 		if (argc1 != 0)
   3835 			lastac = argc1;
   3836 		switch (vi_cmd(lastac, lastcmd)) {
   3837 		case -1:
   3838 			vi_error();
   3839 			refresh(0);
   3840 			break;
   3841 		case 0:
   3842 			if (insert != 0) {
   3843 				if (lastcmd[0] == 's' || lastcmd[0] == 'c' ||
   3844 				    lastcmd[0] == 'C') {
   3845 					if (redo_insert(1) != 0)
   3846 						vi_error();
   3847 				} else {
   3848 					if (redo_insert(lastac) != 0)
   3849 						vi_error();
   3850 				}
   3851 			}
   3852 			refresh(0);
   3853 			break;
   3854 		case 1:
   3855 			refresh(0);
   3856 			return (1);
   3857 		case 2:
   3858 			/* back from a 'v' command - can't happen */
   3859 			break;
   3860 		}
   3861 		break;
   3862 
   3863 	case VFAIL:
   3864 		state = VNORMAL;
   3865 		vi_error();
   3866 		break;
   3867 	}
   3868 	return (0);
   3869 }
   3870 
   3871 static int
   3872 nextstate(int ch)
   3873 {
   3874 	if (is_extend(ch))
   3875 		return (VEXTCMD);
   3876 	else if (is_srch(ch))
   3877 		return (VSEARCH);
   3878 	else if (is_long(ch))
   3879 		return (VXCH);
   3880 	else if (ch == '.')
   3881 		return (VREDO);
   3882 	else if (ch == Ctrl('v'))
   3883 		return (VVERSION);
   3884 	else if (is_cmd(ch))
   3885 		return (VCMD);
   3886 	else
   3887 		return (VFAIL);
   3888 }
   3889 
   3890 static int
   3891 vi_insert(int ch)
   3892 {
   3893 	int tcursor;
   3894 
   3895 	if (ch == edchars.erase || ch == Ctrl('h')) {
   3896 		if (insert == REPLACE) {
   3897 			if (es->cursor == undo->cursor) {
   3898 				vi_error();
   3899 				return (0);
   3900 			}
   3901 			if (inslen > 0)
   3902 				inslen--;
   3903 			es->cursor--;
   3904 			if (es->cursor >= undo->linelen)
   3905 				es->linelen--;
   3906 			else
   3907 				es->cbuf[es->cursor] = undo->cbuf[es->cursor];
   3908 		} else {
   3909 			if (es->cursor == 0)
   3910 				return (0);
   3911 			if (inslen > 0)
   3912 				inslen--;
   3913 			es->cursor--;
   3914 			es->linelen--;
   3915 			memmove(&es->cbuf[es->cursor], &es->cbuf[es->cursor + 1],
   3916 			    es->linelen - es->cursor + 1);
   3917 		}
   3918 		expanded = NONE;
   3919 		return (0);
   3920 	}
   3921 	if (ch == edchars.kill) {
   3922 		if (es->cursor != 0) {
   3923 			inslen = 0;
   3924 			memmove(es->cbuf, &es->cbuf[es->cursor],
   3925 			    es->linelen - es->cursor);
   3926 			es->linelen -= es->cursor;
   3927 			es->cursor = 0;
   3928 		}
   3929 		expanded = NONE;
   3930 		return (0);
   3931 	}
   3932 	if (ch == edchars.werase) {
   3933 		if (es->cursor != 0) {
   3934 			tcursor = backword(1);
   3935 			memmove(&es->cbuf[tcursor], &es->cbuf[es->cursor],
   3936 			    es->linelen - es->cursor);
   3937 			es->linelen -= es->cursor - tcursor;
   3938 			if (inslen < es->cursor - tcursor)
   3939 				inslen = 0;
   3940 			else
   3941 				inslen -= es->cursor - tcursor;
   3942 			es->cursor = tcursor;
   3943 		}
   3944 		expanded = NONE;
   3945 		return (0);
   3946 	}
   3947 	/*
   3948 	 * If any chars are entered before escape, trash the saved insert
   3949 	 * buffer (if user inserts & deletes char, ibuf gets trashed and
   3950 	 * we don't want to use it)
   3951 	 */
   3952 	if (first_insert && ch != Ctrl('['))
   3953 		saved_inslen = 0;
   3954 	switch (ch) {
   3955 	case '\0':
   3956 		return (-1);
   3957 
   3958 	case '\r':
   3959 	case '\n':
   3960 		return (1);
   3961 
   3962 	case Ctrl('['):
   3963 		expanded = NONE;
   3964 		if (first_insert) {
   3965 			first_insert = 0;
   3966 			if (inslen == 0) {
   3967 				inslen = saved_inslen;
   3968 				return (redo_insert(0));
   3969 			}
   3970 			lastcmd[0] = 'a';
   3971 			lastac = 1;
   3972 		}
   3973 		if (lastcmd[0] == 's' || lastcmd[0] == 'c' ||
   3974 		    lastcmd[0] == 'C')
   3975 			return (redo_insert(0));
   3976 		else
   3977 			return (redo_insert(lastac - 1));
   3978 
   3979 	/* { Begin nonstandard vi commands */
   3980 	case Ctrl('x'):
   3981 		expand_word(0);
   3982 		break;
   3983 
   3984 	case Ctrl('f'):
   3985 		complete_word(0, 0);
   3986 		break;
   3987 
   3988 	case Ctrl('e'):
   3989 		print_expansions(es, 0);
   3990 		break;
   3991 
   3992 	case Ctrl('i'):
   3993 		if (Flag(FVITABCOMPLETE)) {
   3994 			complete_word(0, 0);
   3995 			break;
   3996 		}
   3997 		/* FALLTHROUGH */
   3998 	/* End nonstandard vi commands } */
   3999 
   4000 	default:
   4001 		if (es->linelen >= es->cbufsize - 1)
   4002 			return (-1);
   4003 		ibuf[inslen++] = ch;
   4004 		if (insert == INSERT) {
   4005 			memmove(&es->cbuf[es->cursor + 1], &es->cbuf[es->cursor],
   4006 			    es->linelen - es->cursor);
   4007 			es->linelen++;
   4008 		}
   4009 		es->cbuf[es->cursor++] = ch;
   4010 		if (insert == REPLACE && es->cursor > es->linelen)
   4011 			es->linelen++;
   4012 		expanded = NONE;
   4013 	}
   4014 	return (0);
   4015 }
   4016 
   4017 static int
   4018 vi_cmd(int argcnt, const char *cmd)
   4019 {
   4020 	int ncursor;
   4021 	int cur, c1, c2, c3 = 0;
   4022 	int any;
   4023 	struct edstate *t;
   4024 
   4025 	if (argcnt == 0 && !is_zerocount(*cmd))
   4026 		argcnt = 1;
   4027 
   4028 	if (is_move(*cmd)) {
   4029 		if ((cur = domove(argcnt, cmd, 0)) >= 0) {
   4030 			if (cur == es->linelen && cur != 0)
   4031 				cur--;
   4032 			es->cursor = cur;
   4033 		} else
   4034 			return (-1);
   4035 	} else {
   4036 		/* Don't save state in middle of macro.. */
   4037 		if (is_undoable(*cmd) && !macro.p) {
   4038 			undo->winleft = es->winleft;
   4039 			memmove(undo->cbuf, es->cbuf, es->linelen);
   4040 			undo->linelen = es->linelen;
   4041 			undo->cursor = es->cursor;
   4042 			lastac = argcnt;
   4043 			memmove(lastcmd, cmd, MAXVICMD);
   4044 		}
   4045 		switch (*cmd) {
   4046 
   4047 		case Ctrl('l'):
   4048 		case Ctrl('r'):
   4049 			redraw_line(true);
   4050 			break;
   4051 
   4052 		case '@':
   4053 			{
   4054 				static char alias[] = "_\0";
   4055 				struct tbl *ap;
   4056 				size_t olen, nlen;
   4057 				char *p, *nbuf;
   4058 
   4059 				/* lookup letter in alias list... */
   4060 				alias[1] = cmd[1];
   4061 				ap = ktsearch(&aliases, alias, hash(alias));
   4062 				if (!cmd[1] || !ap || !(ap->flag & ISSET))
   4063 					return (-1);
   4064 				/* check if this is a recursive call... */
   4065 				if ((p = (char *)macro.p))
   4066 					while ((p = strnul(p)) && p[1])
   4067 						if (*++p == cmd[1])
   4068 							return (-1);
   4069 				/* insert alias into macro buffer */
   4070 				nlen = strlen(ap->val.s) + 1;
   4071 				olen = !macro.p ? 2 :
   4072 				    macro.len - (macro.p - macro.buf);
   4073 				/*
   4074 				 * at this point, it's fairly reasonable that
   4075 				 * nlen + olen + 2 doesn't overflow
   4076 				 */
   4077 				nbuf = alloc(nlen + 1 + olen, APERM);
   4078 				memcpy(nbuf, ap->val.s, nlen);
   4079 				nbuf[nlen++] = cmd[1];
   4080 				if (macro.p) {
   4081 					memcpy(nbuf + nlen, macro.p, olen);
   4082 					afree(macro.buf, APERM);
   4083 					nlen += olen;
   4084 				} else {
   4085 					nbuf[nlen++] = '\0';
   4086 					nbuf[nlen++] = '\0';
   4087 				}
   4088 				macro.p = macro.buf = (unsigned char *)nbuf;
   4089 				macro.len = nlen;
   4090 			}
   4091 			break;
   4092 
   4093 		case 'a':
   4094 			modified = 1;
   4095 			hnum = hlast;
   4096 			if (es->linelen != 0)
   4097 				es->cursor++;
   4098 			insert = INSERT;
   4099 			break;
   4100 
   4101 		case 'A':
   4102 			modified = 1;
   4103 			hnum = hlast;
   4104 			del_range(0, 0);
   4105 			es->cursor = es->linelen;
   4106 			insert = INSERT;
   4107 			break;
   4108 
   4109 		case 'S':
   4110 			es->cursor = domove(1, "^", 1);
   4111 			del_range(es->cursor, es->linelen);
   4112 			modified = 1;
   4113 			hnum = hlast;
   4114 			insert = INSERT;
   4115 			break;
   4116 
   4117 		case 'Y':
   4118 			cmd = "y$";
   4119 			/* ahhhhhh... */
   4120 		case 'c':
   4121 		case 'd':
   4122 		case 'y':
   4123 			if (*cmd == cmd[1]) {
   4124 				c1 = *cmd == 'c' ? domove(1, "^", 1) : 0;
   4125 				c2 = es->linelen;
   4126 			} else if (!is_move(cmd[1]))
   4127 				return (-1);
   4128 			else {
   4129 				if ((ncursor = domove(argcnt, &cmd[1], 1)) < 0)
   4130 					return (-1);
   4131 				if (*cmd == 'c' &&
   4132 				    (cmd[1] == 'w' || cmd[1] == 'W') &&
   4133 				    !ksh_isspace(es->cbuf[es->cursor])) {
   4134 					do {
   4135 						--ncursor;
   4136 					} while (ksh_isspace(es->cbuf[ncursor]));
   4137 					ncursor++;
   4138 				}
   4139 				if (ncursor > es->cursor) {
   4140 					c1 = es->cursor;
   4141 					c2 = ncursor;
   4142 				} else {
   4143 					c1 = ncursor;
   4144 					c2 = es->cursor;
   4145 					if (cmd[1] == '%')
   4146 						c2++;
   4147 				}
   4148 			}
   4149 			if (*cmd != 'c' && c1 != c2)
   4150 				yank_range(c1, c2);
   4151 			if (*cmd != 'y') {
   4152 				del_range(c1, c2);
   4153 				es->cursor = c1;
   4154 			}
   4155 			if (*cmd == 'c') {
   4156 				modified = 1;
   4157 				hnum = hlast;
   4158 				insert = INSERT;
   4159 			}
   4160 			break;
   4161 
   4162 		case 'p':
   4163 			modified = 1;
   4164 			hnum = hlast;
   4165 			if (es->linelen != 0)
   4166 				es->cursor++;
   4167 			while (putbuf(ybuf, yanklen, 0) == 0 && --argcnt > 0)
   4168 				;
   4169 			if (es->cursor != 0)
   4170 				es->cursor--;
   4171 			if (argcnt != 0)
   4172 				return (-1);
   4173 			break;
   4174 
   4175 		case 'P':
   4176 			modified = 1;
   4177 			hnum = hlast;
   4178 			any = 0;
   4179 			while (putbuf(ybuf, yanklen, 0) == 0 && --argcnt > 0)
   4180 				any = 1;
   4181 			if (any && es->cursor != 0)
   4182 				es->cursor--;
   4183 			if (argcnt != 0)
   4184 				return (-1);
   4185 			break;
   4186 
   4187 		case 'C':
   4188 			modified = 1;
   4189 			hnum = hlast;
   4190 			del_range(es->cursor, es->linelen);
   4191 			insert = INSERT;
   4192 			break;
   4193 
   4194 		case 'D':
   4195 			yank_range(es->cursor, es->linelen);
   4196 			del_range(es->cursor, es->linelen);
   4197 			if (es->cursor != 0)
   4198 				es->cursor--;
   4199 			break;
   4200 
   4201 		case 'g':
   4202 			if (!argcnt)
   4203 				argcnt = hlast;
   4204 			/* FALLTHROUGH */
   4205 		case 'G':
   4206 			if (!argcnt)
   4207 				argcnt = 1;
   4208 			else
   4209 				argcnt = hlast - (source->line - argcnt);
   4210 			if (grabhist(modified, argcnt - 1) < 0)
   4211 				return (-1);
   4212 			else {
   4213 				modified = 0;
   4214 				hnum = argcnt - 1;
   4215 			}
   4216 			break;
   4217 
   4218 		case 'i':
   4219 			modified = 1;
   4220 			hnum = hlast;
   4221 			insert = INSERT;
   4222 			break;
   4223 
   4224 		case 'I':
   4225 			modified = 1;
   4226 			hnum = hlast;
   4227 			es->cursor = domove(1, "^", 1);
   4228 			insert = INSERT;
   4229 			break;
   4230 
   4231 		case 'j':
   4232 		case '+':
   4233 		case Ctrl('n'):
   4234 			if (grabhist(modified, hnum + argcnt) < 0)
   4235 				return (-1);
   4236 			else {
   4237 				modified = 0;
   4238 				hnum += argcnt;
   4239 			}
   4240 			break;
   4241 
   4242 		case 'k':
   4243 		case '-':
   4244 		case Ctrl('p'):
   4245 			if (grabhist(modified, hnum - argcnt) < 0)
   4246 				return (-1);
   4247 			else {
   4248 				modified = 0;
   4249 				hnum -= argcnt;
   4250 			}
   4251 			break;
   4252 
   4253 		case 'r':
   4254 			if (es->linelen == 0)
   4255 				return (-1);
   4256 			modified = 1;
   4257 			hnum = hlast;
   4258 			if (cmd[1] == 0)
   4259 				vi_error();
   4260 			else {
   4261 				int n;
   4262 
   4263 				if (es->cursor + argcnt > es->linelen)
   4264 					return (-1);
   4265 				for (n = 0; n < argcnt; ++n)
   4266 					es->cbuf[es->cursor + n] = cmd[1];
   4267 				es->cursor += n - 1;
   4268 			}
   4269 			break;
   4270 
   4271 		case 'R':
   4272 			modified = 1;
   4273 			hnum = hlast;
   4274 			insert = REPLACE;
   4275 			break;
   4276 
   4277 		case 's':
   4278 			if (es->linelen == 0)
   4279 				return (-1);
   4280 			modified = 1;
   4281 			hnum = hlast;
   4282 			if (es->cursor + argcnt > es->linelen)
   4283 				argcnt = es->linelen - es->cursor;
   4284 			del_range(es->cursor, es->cursor + argcnt);
   4285 			insert = INSERT;
   4286 			break;
   4287 
   4288 		case 'v':
   4289 			if (!argcnt) {
   4290 				if (es->linelen == 0)
   4291 					return (-1);
   4292 				if (modified) {
   4293 					es->cbuf[es->linelen] = '\0';
   4294 					histsave(&source->line, es->cbuf, true,
   4295 					    true);
   4296 				} else
   4297 					argcnt = source->line + 1 -
   4298 					    (hlast - hnum);
   4299 			}
   4300 			if (argcnt)
   4301 				shf_snprintf(es->cbuf, es->cbufsize, "%s %d",
   4302 				    "fc -e ${VISUAL:-${EDITOR:-vi}} --",
   4303 				    argcnt);
   4304 			else
   4305 				strlcpy(es->cbuf,
   4306 				    "fc -e ${VISUAL:-${EDITOR:-vi}} --",
   4307 				    es->cbufsize);
   4308 			es->linelen = strlen(es->cbuf);
   4309 			return (2);
   4310 
   4311 		case 'x':
   4312 			if (es->linelen == 0)
   4313 				return (-1);
   4314 			modified = 1;
   4315 			hnum = hlast;
   4316 			if (es->cursor + argcnt > es->linelen)
   4317 				argcnt = es->linelen - es->cursor;
   4318 			yank_range(es->cursor, es->cursor + argcnt);
   4319 			del_range(es->cursor, es->cursor + argcnt);
   4320 			break;
   4321 
   4322 		case 'X':
   4323 			if (es->cursor > 0) {
   4324 				modified = 1;
   4325 				hnum = hlast;
   4326 				if (es->cursor < argcnt)
   4327 					argcnt = es->cursor;
   4328 				yank_range(es->cursor - argcnt, es->cursor);
   4329 				del_range(es->cursor - argcnt, es->cursor);
   4330 				es->cursor -= argcnt;
   4331 			} else
   4332 				return (-1);
   4333 			break;
   4334 
   4335 		case 'u':
   4336 			t = es;
   4337 			es = undo;
   4338 			undo = t;
   4339 			break;
   4340 
   4341 		case 'U':
   4342 			if (!modified)
   4343 				return (-1);
   4344 			if (grabhist(modified, ohnum) < 0)
   4345 				return (-1);
   4346 			modified = 0;
   4347 			hnum = ohnum;
   4348 			break;
   4349 
   4350 		case '?':
   4351 			if (hnum == hlast)
   4352 				hnum = -1;
   4353 			/* ahhh */
   4354 		case '/':
   4355 			c3 = 1;
   4356 			srchlen = 0;
   4357 			lastsearch = *cmd;
   4358 			/* FALLTHROUGH */
   4359 		case 'n':
   4360 		case 'N':
   4361 			if (lastsearch == ' ')
   4362 				return (-1);
   4363 			if (lastsearch == '?')
   4364 				c1 = 1;
   4365 			else
   4366 				c1 = 0;
   4367 			if (*cmd == 'N')
   4368 				c1 = !c1;
   4369 			if ((c2 = grabsearch(modified, hnum,
   4370 			    c1, srchpat)) < 0) {
   4371 				if (c3) {
   4372 					restore_cbuf();
   4373 					refresh(0);
   4374 				}
   4375 				return (-1);
   4376 			} else {
   4377 				modified = 0;
   4378 				hnum = c2;
   4379 				ohnum = hnum;
   4380 			}
   4381 			break;
   4382 		case '_':
   4383 			{
   4384 				bool inspace;
   4385 				char *p, *sp;
   4386 
   4387 				if (histnum(-1) < 0)
   4388 					return (-1);
   4389 				p = *histpos();
   4390 #define issp(c)		(ksh_isspace(c) || (c) == '\n')
   4391 				if (argcnt) {
   4392 					while (*p && issp(*p))
   4393 						p++;
   4394 					while (*p && --argcnt) {
   4395 						while (*p && !issp(*p))
   4396 							p++;
   4397 						while (*p && issp(*p))
   4398 							p++;
   4399 					}
   4400 					if (!*p)
   4401 						return (-1);
   4402 					sp = p;
   4403 				} else {
   4404 					sp = p;
   4405 					inspace = false;
   4406 					while (*p) {
   4407 						if (issp(*p))
   4408 							inspace = true;
   4409 						else if (inspace) {
   4410 							inspace = false;
   4411 							sp = p;
   4412 						}
   4413 						p++;
   4414 					}
   4415 					p = sp;
   4416 				}
   4417 				modified = 1;
   4418 				hnum = hlast;
   4419 				if (es->cursor != es->linelen)
   4420 					es->cursor++;
   4421 				while (*p && !issp(*p)) {
   4422 					argcnt++;
   4423 					p++;
   4424 				}
   4425 				if (putbuf(" ", 1, 0) != 0 ||
   4426 				    putbuf(sp, argcnt, 0) != 0) {
   4427 					if (es->cursor != 0)
   4428 						es->cursor--;
   4429 					return (-1);
   4430 				}
   4431 				insert = INSERT;
   4432 			}
   4433 			break;
   4434 
   4435 		case '~':
   4436 			{
   4437 				char *p;
   4438 				int i;
   4439 
   4440 				if (es->linelen == 0)
   4441 					return (-1);
   4442 				for (i = 0; i < argcnt; i++) {
   4443 					p = &es->cbuf[es->cursor];
   4444 					if (ksh_islower(*p)) {
   4445 						modified = 1;
   4446 						hnum = hlast;
   4447 						*p = ksh_toupper(*p);
   4448 					} else if (ksh_isupper(*p)) {
   4449 						modified = 1;
   4450 						hnum = hlast;
   4451 						*p = ksh_tolower(*p);
   4452 					}
   4453 					if (es->cursor < es->linelen - 1)
   4454 						es->cursor++;
   4455 				}
   4456 				break;
   4457 			}
   4458 
   4459 		case '#':
   4460 			{
   4461 				int ret = x_do_comment(es->cbuf, es->cbufsize,
   4462 				    &es->linelen);
   4463 				if (ret >= 0)
   4464 					es->cursor = 0;
   4465 				return (ret);
   4466 			}
   4467 
   4468 		/* AT&T ksh */
   4469 		case '=':
   4470 		/* Nonstandard vi/ksh */
   4471 		case Ctrl('e'):
   4472 			print_expansions(es, 1);
   4473 			break;
   4474 
   4475 
   4476 		/* Nonstandard vi/ksh */
   4477 		case Ctrl('i'):
   4478 			if (!Flag(FVITABCOMPLETE))
   4479 				return (-1);
   4480 			complete_word(1, argcnt);
   4481 			break;
   4482 
   4483 		/* some annoying AT&T kshs */
   4484 		case Ctrl('['):
   4485 			if (!Flag(FVIESCCOMPLETE))
   4486 				return (-1);
   4487 		/* AT&T ksh */
   4488 		case '\\':
   4489 		/* Nonstandard vi/ksh */
   4490 		case Ctrl('f'):
   4491 			complete_word(1, argcnt);
   4492 			break;
   4493 
   4494 
   4495 		/* AT&T ksh */
   4496 		case '*':
   4497 		/* Nonstandard vi/ksh */
   4498 		case Ctrl('x'):
   4499 			expand_word(1);
   4500 			break;
   4501 		}
   4502 		if (insert == 0 && es->cursor != 0 && es->cursor >= es->linelen)
   4503 			es->cursor--;
   4504 	}
   4505 	return (0);
   4506 }
   4507 
   4508 static int
   4509 domove(int argcnt, const char *cmd, int sub)
   4510 {
   4511 	int bcount, i = 0, t;
   4512 	int ncursor = 0;
   4513 
   4514 	switch (*cmd) {
   4515 	case 'b':
   4516 		if (!sub && es->cursor == 0)
   4517 			return (-1);
   4518 		ncursor = backword(argcnt);
   4519 		break;
   4520 
   4521 	case 'B':
   4522 		if (!sub && es->cursor == 0)
   4523 			return (-1);
   4524 		ncursor = Backword(argcnt);
   4525 		break;
   4526 
   4527 	case 'e':
   4528 		if (!sub && es->cursor + 1 >= es->linelen)
   4529 			return (-1);
   4530 		ncursor = endword(argcnt);
   4531 		if (sub && ncursor < es->linelen)
   4532 			ncursor++;
   4533 		break;
   4534 
   4535 	case 'E':
   4536 		if (!sub && es->cursor + 1 >= es->linelen)
   4537 			return (-1);
   4538 		ncursor = Endword(argcnt);
   4539 		if (sub && ncursor < es->linelen)
   4540 			ncursor++;
   4541 		break;
   4542 
   4543 	case 'f':
   4544 	case 'F':
   4545 	case 't':
   4546 	case 'T':
   4547 		fsavecmd = *cmd;
   4548 		fsavech = cmd[1];
   4549 		/* drop through */
   4550 
   4551 	case ',':
   4552 	case ';':
   4553 		if (fsavecmd == ' ')
   4554 			return (-1);
   4555 		i = fsavecmd == 'f' || fsavecmd == 'F';
   4556 		t = fsavecmd > 'a';
   4557 		if (*cmd == ',')
   4558 			t = !t;
   4559 		if ((ncursor = findch(fsavech, argcnt, t, i)) < 0)
   4560 			return (-1);
   4561 		if (sub && t)
   4562 			ncursor++;
   4563 		break;
   4564 
   4565 	case 'h':
   4566 	case Ctrl('h'):
   4567 		if (!sub && es->cursor == 0)
   4568 			return (-1);
   4569 		ncursor = es->cursor - argcnt;
   4570 		if (ncursor < 0)
   4571 			ncursor = 0;
   4572 		break;
   4573 
   4574 	case ' ':
   4575 	case 'l':
   4576 		if (!sub && es->cursor + 1 >= es->linelen)
   4577 			return (-1);
   4578 		if (es->linelen != 0) {
   4579 			ncursor = es->cursor + argcnt;
   4580 			if (ncursor > es->linelen)
   4581 				ncursor = es->linelen;
   4582 		}
   4583 		break;
   4584 
   4585 	case 'w':
   4586 		if (!sub && es->cursor + 1 >= es->linelen)
   4587 			return (-1);
   4588 		ncursor = forwword(argcnt);
   4589 		break;
   4590 
   4591 	case 'W':
   4592 		if (!sub && es->cursor + 1 >= es->linelen)
   4593 			return (-1);
   4594 		ncursor = Forwword(argcnt);
   4595 		break;
   4596 
   4597 	case '0':
   4598 		ncursor = 0;
   4599 		break;
   4600 
   4601 	case '^':
   4602 		ncursor = 0;
   4603 		while (ncursor < es->linelen - 1 &&
   4604 		    ksh_isspace(es->cbuf[ncursor]))
   4605 			ncursor++;
   4606 		break;
   4607 
   4608 	case '|':
   4609 		ncursor = argcnt;
   4610 		if (ncursor > es->linelen)
   4611 			ncursor = es->linelen;
   4612 		if (ncursor)
   4613 			ncursor--;
   4614 		break;
   4615 
   4616 	case '$':
   4617 		if (es->linelen != 0)
   4618 			ncursor = es->linelen;
   4619 		else
   4620 			ncursor = 0;
   4621 		break;
   4622 
   4623 	case '%':
   4624 		ncursor = es->cursor;
   4625 		while (ncursor < es->linelen &&
   4626 		    (i = bracktype(es->cbuf[ncursor])) == 0)
   4627 			ncursor++;
   4628 		if (ncursor == es->linelen)
   4629 			return (-1);
   4630 		bcount = 1;
   4631 		do {
   4632 			if (i > 0) {
   4633 				if (++ncursor >= es->linelen)
   4634 					return (-1);
   4635 			} else {
   4636 				if (--ncursor < 0)
   4637 					return (-1);
   4638 			}
   4639 			t = bracktype(es->cbuf[ncursor]);
   4640 			if (t == i)
   4641 				bcount++;
   4642 			else if (t == -i)
   4643 				bcount--;
   4644 		} while (bcount != 0);
   4645 		if (sub && i > 0)
   4646 			ncursor++;
   4647 		break;
   4648 
   4649 	default:
   4650 		return (-1);
   4651 	}
   4652 	return (ncursor);
   4653 }
   4654 
   4655 static int
   4656 redo_insert(int count)
   4657 {
   4658 	while (count-- > 0)
   4659 		if (putbuf(ibuf, inslen, insert == REPLACE) != 0)
   4660 			return (-1);
   4661 	if (es->cursor > 0)
   4662 		es->cursor--;
   4663 	insert = 0;
   4664 	return (0);
   4665 }
   4666 
   4667 static void
   4668 yank_range(int a, int b)
   4669 {
   4670 	yanklen = b - a;
   4671 	if (yanklen != 0)
   4672 		memmove(ybuf, &es->cbuf[a], yanklen);
   4673 }
   4674 
   4675 static int
   4676 bracktype(int ch)
   4677 {
   4678 	switch (ch) {
   4679 
   4680 	case '(':
   4681 		return (1);
   4682 
   4683 	case '[':
   4684 		return (2);
   4685 
   4686 	case '{':
   4687 		return (3);
   4688 
   4689 	case ')':
   4690 		return (-1);
   4691 
   4692 	case ']':
   4693 		return (-2);
   4694 
   4695 	case '}':
   4696 		return (-3);
   4697 
   4698 	default:
   4699 		return (0);
   4700 	}
   4701 }
   4702 
   4703 /*
   4704  *	Non user interface editor routines below here
   4705  */
   4706 
   4707 static void
   4708 save_cbuf(void)
   4709 {
   4710 	memmove(holdbuf, es->cbuf, es->linelen);
   4711 	holdlen = es->linelen;
   4712 	holdbuf[holdlen] = '\0';
   4713 }
   4714 
   4715 static void
   4716 restore_cbuf(void)
   4717 {
   4718 	es->cursor = 0;
   4719 	es->linelen = holdlen;
   4720 	memmove(es->cbuf, holdbuf, holdlen);
   4721 }
   4722 
   4723 /* return a new edstate */
   4724 static struct edstate *
   4725 save_edstate(struct edstate *old)
   4726 {
   4727 	struct edstate *news;
   4728 
   4729 	news = alloc(sizeof(struct edstate), APERM);
   4730 	news->cbuf = alloc(old->cbufsize, APERM);
   4731 	memcpy(news->cbuf, old->cbuf, old->linelen);
   4732 	news->cbufsize = old->cbufsize;
   4733 	news->linelen = old->linelen;
   4734 	news->cursor = old->cursor;
   4735 	news->winleft = old->winleft;
   4736 	return (news);
   4737 }
   4738 
   4739 static void
   4740 restore_edstate(struct edstate *news, struct edstate *old)
   4741 {
   4742 	memcpy(news->cbuf, old->cbuf, old->linelen);
   4743 	news->linelen = old->linelen;
   4744 	news->cursor = old->cursor;
   4745 	news->winleft = old->winleft;
   4746 	free_edstate(old);
   4747 }
   4748 
   4749 static void
   4750 free_edstate(struct edstate *old)
   4751 {
   4752 	afree(old->cbuf, APERM);
   4753 	afree(old, APERM);
   4754 }
   4755 
   4756 /*
   4757  * this is used for calling x_escape() in complete_word()
   4758  */
   4759 static int
   4760 x_vi_putbuf(const char *s, size_t len)
   4761 {
   4762 	return (putbuf(s, len, 0));
   4763 }
   4764 
   4765 static int
   4766 putbuf(const char *buf, ssize_t len, int repl)
   4767 {
   4768 	if (len == 0)
   4769 		return (0);
   4770 	if (repl) {
   4771 		if (es->cursor + len >= es->cbufsize)
   4772 			return (-1);
   4773 		if (es->cursor + len > es->linelen)
   4774 			es->linelen = es->cursor + len;
   4775 	} else {
   4776 		if (es->linelen + len >= es->cbufsize)
   4777 			return (-1);
   4778 		memmove(&es->cbuf[es->cursor + len], &es->cbuf[es->cursor],
   4779 		    es->linelen - es->cursor);
   4780 		es->linelen += len;
   4781 	}
   4782 	memmove(&es->cbuf[es->cursor], buf, len);
   4783 	es->cursor += len;
   4784 	return (0);
   4785 }
   4786 
   4787 static void
   4788 del_range(int a, int b)
   4789 {
   4790 	if (es->linelen != b)
   4791 		memmove(&es->cbuf[a], &es->cbuf[b], es->linelen - b);
   4792 	es->linelen -= b - a;
   4793 }
   4794 
   4795 static int
   4796 findch(int ch, int cnt, int forw, int incl)
   4797 {
   4798 	int ncursor;
   4799 
   4800 	if (es->linelen == 0)
   4801 		return (-1);
   4802 	ncursor = es->cursor;
   4803 	while (cnt--) {
   4804 		do {
   4805 			if (forw) {
   4806 				if (++ncursor == es->linelen)
   4807 					return (-1);
   4808 			} else {
   4809 				if (--ncursor < 0)
   4810 					return (-1);
   4811 			}
   4812 		} while (es->cbuf[ncursor] != ch);
   4813 	}
   4814 	if (!incl) {
   4815 		if (forw)
   4816 			ncursor--;
   4817 		else
   4818 			ncursor++;
   4819 	}
   4820 	return (ncursor);
   4821 }
   4822 
   4823 static int
   4824 forwword(int argcnt)
   4825 {
   4826 	int ncursor;
   4827 
   4828 	ncursor = es->cursor;
   4829 	while (ncursor < es->linelen && argcnt--) {
   4830 		if (ksh_isalnux(es->cbuf[ncursor]))
   4831 			while (ksh_isalnux(es->cbuf[ncursor]) &&
   4832 			    ncursor < es->linelen)
   4833 				ncursor++;
   4834 		else if (!ksh_isspace(es->cbuf[ncursor]))
   4835 			while (!ksh_isalnux(es->cbuf[ncursor]) &&
   4836 			    !ksh_isspace(es->cbuf[ncursor]) &&
   4837 			    ncursor < es->linelen)
   4838 				ncursor++;
   4839 		while (ksh_isspace(es->cbuf[ncursor]) &&
   4840 		    ncursor < es->linelen)
   4841 			ncursor++;
   4842 	}
   4843 	return (ncursor);
   4844 }
   4845 
   4846 static int
   4847 backword(int argcnt)
   4848 {
   4849 	int ncursor;
   4850 
   4851 	ncursor = es->cursor;
   4852 	while (ncursor > 0 && argcnt--) {
   4853 		while (--ncursor > 0 && ksh_isspace(es->cbuf[ncursor]))
   4854 			;
   4855 		if (ncursor > 0) {
   4856 			if (ksh_isalnux(es->cbuf[ncursor]))
   4857 				while (--ncursor >= 0 &&
   4858 				    ksh_isalnux(es->cbuf[ncursor]))
   4859 					;
   4860 			else
   4861 				while (--ncursor >= 0 &&
   4862 				    !ksh_isalnux(es->cbuf[ncursor]) &&
   4863 				    !ksh_isspace(es->cbuf[ncursor]))
   4864 					;
   4865 			ncursor++;
   4866 		}
   4867 	}
   4868 	return (ncursor);
   4869 }
   4870 
   4871 static int
   4872 endword(int argcnt)
   4873 {
   4874 	int ncursor;
   4875 
   4876 	ncursor = es->cursor;
   4877 	while (ncursor < es->linelen && argcnt--) {
   4878 		while (++ncursor < es->linelen - 1 &&
   4879 		    ksh_isspace(es->cbuf[ncursor]))
   4880 			;
   4881 		if (ncursor < es->linelen - 1) {
   4882 			if (ksh_isalnux(es->cbuf[ncursor]))
   4883 				while (++ncursor < es->linelen &&
   4884 				    ksh_isalnux(es->cbuf[ncursor]))
   4885 					;
   4886 			else
   4887 				while (++ncursor < es->linelen &&
   4888 				    !ksh_isalnux(es->cbuf[ncursor]) &&
   4889 				    !ksh_isspace(es->cbuf[ncursor]))
   4890 					;
   4891 			ncursor--;
   4892 		}
   4893 	}
   4894 	return (ncursor);
   4895 }
   4896 
   4897 static int
   4898 Forwword(int argcnt)
   4899 {
   4900 	int ncursor;
   4901 
   4902 	ncursor = es->cursor;
   4903 	while (ncursor < es->linelen && argcnt--) {
   4904 		while (!ksh_isspace(es->cbuf[ncursor]) &&
   4905 		    ncursor < es->linelen)
   4906 			ncursor++;
   4907 		while (ksh_isspace(es->cbuf[ncursor]) &&
   4908 		    ncursor < es->linelen)
   4909 			ncursor++;
   4910 	}
   4911 	return (ncursor);
   4912 }
   4913 
   4914 static int
   4915 Backword(int argcnt)
   4916 {
   4917 	int ncursor;
   4918 
   4919 	ncursor = es->cursor;
   4920 	while (ncursor > 0 && argcnt--) {
   4921 		while (--ncursor >= 0 && ksh_isspace(es->cbuf[ncursor]))
   4922 			;
   4923 		while (ncursor >= 0 && !ksh_isspace(es->cbuf[ncursor]))
   4924 			ncursor--;
   4925 		ncursor++;
   4926 	}
   4927 	return (ncursor);
   4928 }
   4929 
   4930 static int
   4931 Endword(int argcnt)
   4932 {
   4933 	int ncursor;
   4934 
   4935 	ncursor = es->cursor;
   4936 	while (ncursor < es->linelen - 1 && argcnt--) {
   4937 		while (++ncursor < es->linelen - 1 &&
   4938 		    ksh_isspace(es->cbuf[ncursor]))
   4939 			;
   4940 		if (ncursor < es->linelen - 1) {
   4941 			while (++ncursor < es->linelen &&
   4942 			    !ksh_isspace(es->cbuf[ncursor]))
   4943 				;
   4944 			ncursor--;
   4945 		}
   4946 	}
   4947 	return (ncursor);
   4948 }
   4949 
   4950 static int
   4951 grabhist(int save, int n)
   4952 {
   4953 	char *hptr;
   4954 
   4955 	if (n < 0 || n > hlast)
   4956 		return (-1);
   4957 	if (n == hlast) {
   4958 		restore_cbuf();
   4959 		ohnum = n;
   4960 		return (0);
   4961 	}
   4962 	(void)histnum(n);
   4963 	if ((hptr = *histpos()) == NULL) {
   4964 		internal_warningf("%s: %s", "grabhist", "bad history array");
   4965 		return (-1);
   4966 	}
   4967 	if (save)
   4968 		save_cbuf();
   4969 	if ((es->linelen = strlen(hptr)) >= es->cbufsize)
   4970 		es->linelen = es->cbufsize - 1;
   4971 	memmove(es->cbuf, hptr, es->linelen);
   4972 	es->cursor = 0;
   4973 	ohnum = n;
   4974 	return (0);
   4975 }
   4976 
   4977 static int
   4978 grabsearch(int save, int start, int fwd, const char *pat)
   4979 {
   4980 	char *hptr;
   4981 	int hist;
   4982 	int anchored;
   4983 
   4984 	if ((start == 0 && fwd == 0) || (start >= hlast - 1 && fwd == 1))
   4985 		return (-1);
   4986 	if (fwd)
   4987 		start++;
   4988 	else
   4989 		start--;
   4990 	anchored = *pat == '^' ? (++pat, 1) : 0;
   4991 	if ((hist = findhist(start, fwd, pat, anchored)) < 0) {
   4992 		/* (start != 0 && fwd && match(holdbuf, pat) >= 0) */
   4993 		if (start != 0 && fwd && strcmp(holdbuf, pat) >= 0) {
   4994 			restore_cbuf();
   4995 			return (0);
   4996 		} else
   4997 			return (-1);
   4998 	}
   4999 	if (save)
   5000 		save_cbuf();
   5001 	histnum(hist);
   5002 	hptr = *histpos();
   5003 	if ((es->linelen = strlen(hptr)) >= es->cbufsize)
   5004 		es->linelen = es->cbufsize - 1;
   5005 	memmove(es->cbuf, hptr, es->linelen);
   5006 	es->cursor = 0;
   5007 	return (hist);
   5008 }
   5009 
   5010 static void
   5011 redraw_line(bool newl)
   5012 {
   5013 	if (wbuf_len)
   5014 		memset(wbuf[win], ' ', wbuf_len);
   5015 	if (newl) {
   5016 		x_putc('\r');
   5017 		x_putc('\n');
   5018 	}
   5019 	if (prompt_redraw)
   5020 		pprompt(prompt, prompt_trunc);
   5021 	cur_col = pwidth;
   5022 	morec = ' ';
   5023 }
   5024 
   5025 static void
   5026 refresh(int leftside)
   5027 {
   5028 	if (leftside < 0)
   5029 		leftside = lastref;
   5030 	else
   5031 		lastref = leftside;
   5032 	if (outofwin())
   5033 		rewindow();
   5034 	display(wbuf[1 - win], wbuf[win], leftside);
   5035 	win = 1 - win;
   5036 }
   5037 
   5038 static int
   5039 outofwin(void)
   5040 {
   5041 	int cur, col;
   5042 
   5043 	if (es->cursor < es->winleft)
   5044 		return (1);
   5045 	col = 0;
   5046 	cur = es->winleft;
   5047 	while (cur < es->cursor)
   5048 		col = newcol((unsigned char)es->cbuf[cur++], col);
   5049 	if (col >= winwidth)
   5050 		return (1);
   5051 	return (0);
   5052 }
   5053 
   5054 static void
   5055 rewindow(void)
   5056 {
   5057 	int tcur, tcol;
   5058 	int holdcur1, holdcol1;
   5059 	int holdcur2, holdcol2;
   5060 
   5061 	holdcur1 = holdcur2 = tcur = 0;
   5062 	holdcol1 = holdcol2 = tcol = 0;
   5063 	while (tcur < es->cursor) {
   5064 		if (tcol - holdcol2 > winwidth / 2) {
   5065 			holdcur1 = holdcur2;
   5066 			holdcol1 = holdcol2;
   5067 			holdcur2 = tcur;
   5068 			holdcol2 = tcol;
   5069 		}
   5070 		tcol = newcol((unsigned char)es->cbuf[tcur++], tcol);
   5071 	}
   5072 	while (tcol - holdcol1 > winwidth / 2)
   5073 		holdcol1 = newcol((unsigned char)es->cbuf[holdcur1++],
   5074 		    holdcol1);
   5075 	es->winleft = holdcur1;
   5076 }
   5077 
   5078 static int
   5079 newcol(int ch, int col)
   5080 {
   5081 	if (ch == '\t')
   5082 		return ((col | 7) + 1);
   5083 	return (col + char_len(ch));
   5084 }
   5085 
   5086 static void
   5087 display(char *wb1, char *wb2, int leftside)
   5088 {
   5089 	unsigned char ch;
   5090 	char *twb1, *twb2, mc;
   5091 	int cur, col, cnt;
   5092 	int ncol = 0;
   5093 	int moreright;
   5094 
   5095 	col = 0;
   5096 	cur = es->winleft;
   5097 	moreright = 0;
   5098 	twb1 = wb1;
   5099 	while (col < winwidth && cur < es->linelen) {
   5100 		if (cur == es->cursor && leftside)
   5101 			ncol = col + pwidth;
   5102 		if ((ch = es->cbuf[cur]) == '\t')
   5103 			do {
   5104 				*twb1++ = ' ';
   5105 			} while (++col < winwidth && (col & 7) != 0);
   5106 		else if (col < winwidth) {
   5107 			if (ch < ' ' || ch == 0x7f) {
   5108 				*twb1++ = '^';
   5109 				if (++col < winwidth) {
   5110 					*twb1++ = ch ^ '@';
   5111 					col++;
   5112 				}
   5113 			} else {
   5114 				*twb1++ = ch;
   5115 				col++;
   5116 			}
   5117 		}
   5118 		if (cur == es->cursor && !leftside)
   5119 			ncol = col + pwidth - 1;
   5120 		cur++;
   5121 	}
   5122 	if (cur == es->cursor)
   5123 		ncol = col + pwidth;
   5124 	if (col < winwidth) {
   5125 		while (col < winwidth) {
   5126 			*twb1++ = ' ';
   5127 			col++;
   5128 		}
   5129 	} else
   5130 		moreright++;
   5131 	*twb1 = ' ';
   5132 
   5133 	col = pwidth;
   5134 	cnt = winwidth;
   5135 	twb1 = wb1;
   5136 	twb2 = wb2;
   5137 	while (cnt--) {
   5138 		if (*twb1 != *twb2) {
   5139 			if (cur_col != col)
   5140 				ed_mov_opt(col, wb1);
   5141 			x_putc(*twb1);
   5142 			cur_col++;
   5143 		}
   5144 		twb1++;
   5145 		twb2++;
   5146 		col++;
   5147 	}
   5148 	if (es->winleft > 0 && moreright)
   5149 		/*
   5150 		 * POSIX says to use * for this but that is a globbing
   5151 		 * character and may confuse people; + is more innocuous
   5152 		 */
   5153 		mc = '+';
   5154 	else if (es->winleft > 0)
   5155 		mc = '<';
   5156 	else if (moreright)
   5157 		mc = '>';
   5158 	else
   5159 		mc = ' ';
   5160 	if (mc != morec) {
   5161 		ed_mov_opt(pwidth + winwidth + 1, wb1);
   5162 		x_putc(mc);
   5163 		cur_col++;
   5164 		morec = mc;
   5165 	}
   5166 	if (cur_col != ncol)
   5167 		ed_mov_opt(ncol, wb1);
   5168 }
   5169 
   5170 static void
   5171 ed_mov_opt(int col, char *wb)
   5172 {
   5173 	if (col < cur_col) {
   5174 		if (col + 1 < cur_col - col) {
   5175 			x_putc('\r');
   5176 			if (prompt_redraw)
   5177 				pprompt(prompt, prompt_trunc);
   5178 			cur_col = pwidth;
   5179 			while (cur_col++ < col)
   5180 				x_putcf(*wb++);
   5181 		} else {
   5182 			while (cur_col-- > col)
   5183 				x_putc('\b');
   5184 		}
   5185 	} else {
   5186 		wb = &wb[cur_col - pwidth];
   5187 		while (cur_col++ < col)
   5188 			x_putcf(*wb++);
   5189 	}
   5190 	cur_col = col;
   5191 }
   5192 
   5193 
   5194 /* replace word with all expansions (ie, expand word*) */
   5195 static int
   5196 expand_word(int cmd)
   5197 {
   5198 	static struct edstate *buf;
   5199 	int rval = 0, nwords, start, end, i;
   5200 	char **words;
   5201 
   5202 	/* Undo previous expansion */
   5203 	if (cmd == 0 && expanded == EXPAND && buf) {
   5204 		restore_edstate(es, buf);
   5205 		buf = 0;
   5206 		expanded = NONE;
   5207 		return (0);
   5208 	}
   5209 	if (buf) {
   5210 		free_edstate(buf);
   5211 		buf = 0;
   5212 	}
   5213 
   5214 	i = XCF_COMMAND_FILE | XCF_FULLPATH;
   5215 	nwords = x_cf_glob(&i, es->cbuf, es->linelen, es->cursor,
   5216 	    &start, &end, &words);
   5217 	if (nwords == 0) {
   5218 		vi_error();
   5219 		return (-1);
   5220 	}
   5221 
   5222 	buf = save_edstate(es);
   5223 	expanded = EXPAND;
   5224 	del_range(start, end);
   5225 	es->cursor = start;
   5226 	i = 0;
   5227 	while (i < nwords) {
   5228 		if (x_escape(words[i], strlen(words[i]), x_vi_putbuf) != 0) {
   5229 			rval = -1;
   5230 			break;
   5231 		}
   5232 		if (++i < nwords && putbuf(" ", 1, 0) != 0) {
   5233 			rval = -1;
   5234 			break;
   5235 		}
   5236 	}
   5237 	i = buf->cursor - end;
   5238 	if (rval == 0 && i > 0)
   5239 		es->cursor += i;
   5240 	modified = 1;
   5241 	hnum = hlast;
   5242 	insert = INSERT;
   5243 	lastac = 0;
   5244 	refresh(0);
   5245 	return (rval);
   5246 }
   5247 
   5248 static int
   5249 complete_word(int cmd, int count)
   5250 {
   5251 	static struct edstate *buf;
   5252 	int rval, nwords, start, end, flags;
   5253 	size_t match_len;
   5254 	char **words;
   5255 	char *match;
   5256 	bool is_unique;
   5257 
   5258 	/* Undo previous completion */
   5259 	if (cmd == 0 && expanded == COMPLETE && buf) {
   5260 		print_expansions(buf, 0);
   5261 		expanded = PRINT;
   5262 		return (0);
   5263 	}
   5264 	if (cmd == 0 && expanded == PRINT && buf) {
   5265 		restore_edstate(es, buf);
   5266 		buf = 0;
   5267 		expanded = NONE;
   5268 		return (0);
   5269 	}
   5270 	if (buf) {
   5271 		free_edstate(buf);
   5272 		buf = 0;
   5273 	}
   5274 
   5275 	/*
   5276 	 * XCF_FULLPATH for count 'cause the menu printed by
   5277 	 * print_expansions() was done this way.
   5278 	 */
   5279 	flags = XCF_COMMAND_FILE;
   5280 	if (count)
   5281 		flags |= XCF_FULLPATH;
   5282 	nwords = x_cf_glob(&flags, es->cbuf, es->linelen, es->cursor,
   5283 	    &start, &end, &words);
   5284 	if (nwords == 0) {
   5285 		vi_error();
   5286 		return (-1);
   5287 	}
   5288 	if (count) {
   5289 		int i;
   5290 
   5291 		count--;
   5292 		if (count >= nwords) {
   5293 			vi_error();
   5294 			x_print_expansions(nwords, words,
   5295 			    tobool(flags & XCF_IS_COMMAND));
   5296 			x_free_words(nwords, words);
   5297 			redraw_line(false);
   5298 			return (-1);
   5299 		}
   5300 		/*
   5301 		 * Expand the count'th word to its basename
   5302 		 */
   5303 		if (flags & XCF_IS_COMMAND) {
   5304 			match = words[count] +
   5305 			    x_basename(words[count], NULL);
   5306 			/* If more than one possible match, use full path */
   5307 			for (i = 0; i < nwords; i++)
   5308 				if (i != count &&
   5309 				    strcmp(words[i] + x_basename(words[i],
   5310 				    NULL), match) == 0) {
   5311 					match = words[count];
   5312 					break;
   5313 				}
   5314 		} else
   5315 			match = words[count];
   5316 		match_len = strlen(match);
   5317 		is_unique = true;
   5318 		/* expanded = PRINT;	next call undo */
   5319 	} else {
   5320 		match = words[0];
   5321 		match_len = x_longest_prefix(nwords, words);
   5322 		/* next call will list completions */
   5323 		expanded = COMPLETE;
   5324 		is_unique = nwords == 1;
   5325 	}
   5326 
   5327 	buf = save_edstate(es);
   5328 	del_range(start, end);
   5329 	es->cursor = start;
   5330 
   5331 	/*
   5332 	 * escape all shell-sensitive characters and put the result into
   5333 	 * command buffer
   5334 	 */
   5335 	rval = x_escape(match, match_len, x_vi_putbuf);
   5336 
   5337 	if (rval == 0 && is_unique) {
   5338 		/*
   5339 		 * If exact match, don't undo. Allows directory completions
   5340 		 * to be used (ie, complete the next portion of the path).
   5341 		 */
   5342 		expanded = NONE;
   5343 
   5344 		/*
   5345 		 * append a space if this is a non-directory match
   5346 		 * and not a parameter or homedir substitution
   5347 		 */
   5348 		if (match_len > 0 && match[match_len - 1] != '/' &&
   5349 		    !(flags & XCF_IS_NOSPACE))
   5350 			rval = putbuf(" ", 1, 0);
   5351 	}
   5352 	x_free_words(nwords, words);
   5353 
   5354 	modified = 1;
   5355 	hnum = hlast;
   5356 	insert = INSERT;
   5357 	/* prevent this from being redone... */
   5358 	lastac = 0;
   5359 	refresh(0);
   5360 
   5361 	return (rval);
   5362 }
   5363 
   5364 static int
   5365 print_expansions(struct edstate *est, int cmd MKSH_A_UNUSED)
   5366 {
   5367 	int start, end, nwords, i;
   5368 	char **words;
   5369 
   5370 	i = XCF_COMMAND_FILE | XCF_FULLPATH;
   5371 	nwords = x_cf_glob(&i, est->cbuf, est->linelen, est->cursor,
   5372 	    &start, &end, &words);
   5373 	if (nwords == 0) {
   5374 		vi_error();
   5375 		return (-1);
   5376 	}
   5377 	x_print_expansions(nwords, words, tobool(i & XCF_IS_COMMAND));
   5378 	x_free_words(nwords, words);
   5379 	redraw_line(false);
   5380 	return (0);
   5381 }
   5382 
   5383 /* Similar to x_zotc(emacs.c), but no tab weirdness */
   5384 static void
   5385 x_vi_zotc(int c)
   5386 {
   5387 	if (c < ' ' || c == 0x7f) {
   5388 		x_putc('^');
   5389 		c ^= '@';
   5390 	}
   5391 	x_putc(c);
   5392 }
   5393 
   5394 static void
   5395 vi_error(void)
   5396 {
   5397 	/* Beem out of any macros as soon as an error occurs */
   5398 	vi_macro_reset();
   5399 	x_putc(7);
   5400 	x_flush();
   5401 }
   5402 
   5403 static void
   5404 vi_macro_reset(void)
   5405 {
   5406 	if (macro.p) {
   5407 		afree(macro.buf, APERM);
   5408 		memset((char *)&macro, 0, sizeof(macro));
   5409 	}
   5410 }
   5411 #endif /* !MKSH_S_NOVI */
   5412 
   5413 /* called from main.c */
   5414 void
   5415 x_init(void)
   5416 {
   5417 	int i, j;
   5418 
   5419 	/*
   5420 	 * Set edchars to -2 to force initial binding, except
   5421 	 * we need default values for some deficient systems
   5422 	 */
   5423 	edchars.erase = edchars.kill = edchars.intr = edchars.quit =
   5424 	    edchars.eof = -2;
   5425 	/* ^W */
   5426 	edchars.werase = 027;
   5427 
   5428 	/* initialise Emacs command line editing mode */
   5429 	ainit(AEDIT);
   5430 	x_nextcmd = -1;
   5431 
   5432 	x_tab = alloc2(X_NTABS, sizeof(*x_tab), AEDIT);
   5433 	for (j = 0; j < X_TABSZ; j++)
   5434 		x_tab[0][j] = XFUNC_insert;
   5435 	for (i = 1; i < X_NTABS; i++)
   5436 		for (j = 0; j < X_TABSZ; j++)
   5437 			x_tab[i][j] = XFUNC_error;
   5438 	for (i = 0; i < (int)NELEM(x_defbindings); i++)
   5439 		x_tab[x_defbindings[i].xdb_tab][x_defbindings[i].xdb_char]
   5440 		    = x_defbindings[i].xdb_func;
   5441 
   5442 #ifndef MKSH_SMALL
   5443 	x_atab = alloc2(X_NTABS, sizeof(*x_atab), AEDIT);
   5444 	for (i = 1; i < X_NTABS; i++)
   5445 		for (j = 0; j < X_TABSZ; j++)
   5446 			x_atab[i][j] = NULL;
   5447 #endif
   5448 }
   5449 
   5450 #ifdef DEBUG_LEAKS
   5451 void
   5452 x_done(void)
   5453 {
   5454 	if (x_tab != NULL)
   5455 		afreeall(AEDIT);
   5456 }
   5457 #endif
   5458 #endif /* !MKSH_NO_CMDLINE_EDITING */
   5459