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