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