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