xref: /openbsd-src/bin/ksh/emacs.c (revision 99fd087599a8791921855f21bd7e36130f39aadc)
1 /*	$OpenBSD: emacs.c,v 1.86 2019/04/03 14:55:12 jca Exp $	*/
2 
3 /*
4  *  Emacs-like command line editing and history
5  *
6  *  created by Ron Natalie at BRL
7  *  modified by Doug Kingston, Doug Gwyn, and Lou Salkind
8  *  adapted to PD ksh by Eric Gisin
9  *
10  * partial rewrite by Marco Peereboom <marco@openbsd.org>
11  * under the same license
12  */
13 
14 #include "config.h"
15 #ifdef EMACS
16 
17 #include <sys/queue.h>
18 #include <sys/stat.h>
19 
20 #include <ctype.h>
21 #include <stdio.h>
22 #include <stdlib.h>
23 #include <string.h>
24 #ifndef SMALL
25 # include <term.h>
26 # include <curses.h>
27 #endif
28 
29 #include "sh.h"
30 #include "edit.h"
31 
32 static	Area	aedit;
33 #define	AEDIT	&aedit		/* area for kill ring and macro defns */
34 
35 #undef CTRL
36 #define	CTRL(x)		((x) == '?' ? 0x7F : (x) & 0x1F)	/* ASCII */
37 #define	UNCTRL(x)	((x) == 0x7F ? '?' : (x) | 0x40)	/* ASCII */
38 
39 /* values returned by keyboard functions */
40 #define	KSTD	0
41 #define	KEOL	1		/* ^M, ^J */
42 #define	KINTR	2		/* ^G, ^C */
43 
44 struct	x_ftab {
45 	int		(*xf_func)(int c);
46 	const char	*xf_name;
47 	short		xf_flags;
48 };
49 
50 #define XF_ARG		1	/* command takes number prefix */
51 #define	XF_NOBIND	2	/* not allowed to bind to function */
52 #define	XF_PREFIX	4	/* function sets prefix */
53 
54 /* Separator for completion */
55 #define	is_cfs(c)	(c == ' ' || c == '\t' || c == '"' || c == '\'')
56 
57 /* Separator for motion */
58 #define	is_mfs(c)	(!(isalnum((unsigned char)c) || \
59 			c == '_' || c == '$' || c & 0x80))
60 
61 /* Arguments for do_complete()
62  * 0 = enumerate  M-= complete as much as possible and then list
63  * 1 = complete   M-Esc
64  * 2 = list       M-?
65  */
66 typedef enum {
67 	CT_LIST,	/* list the possible completions */
68 	CT_COMPLETE,	/* complete to longest prefix */
69 	CT_COMPLIST	/* complete and then list (if non-exact) */
70 } Comp_type;
71 
72 /* keybindings */
73 struct kb_entry {
74 	TAILQ_ENTRY(kb_entry)	entry;
75 	unsigned char		*seq;
76 	int			len;
77 	struct x_ftab		*ftab;
78 	void			*args;
79 };
80 TAILQ_HEAD(kb_list, kb_entry);
81 struct kb_list			kblist = TAILQ_HEAD_INITIALIZER(kblist);
82 
83 /* { from 4.9 edit.h */
84 /*
85  * The following are used for my horizontal scrolling stuff
86  */
87 static char    *xbuf;		/* beg input buffer */
88 static char    *xend;		/* end input buffer */
89 static char    *xcp;		/* current position */
90 static char    *xep;		/* current end */
91 static char    *xbp;		/* start of visible portion of input buffer */
92 static char    *xlp;		/* last byte visible on screen */
93 static int	x_adj_ok;
94 /*
95  * we use x_adj_done so that functions can tell
96  * whether x_adjust() has been called while they are active.
97  */
98 static int	x_adj_done;
99 
100 static int	xx_cols;
101 static int	x_col;
102 static int	x_displen;
103 static int	x_arg;		/* general purpose arg */
104 static int	x_arg_defaulted;/* x_arg not explicitly set; defaulted to 1 */
105 
106 static int	xlp_valid;
107 /* end from 4.9 edit.h } */
108 static	int	x_tty;		/* are we on a tty? */
109 static	int	x_bind_quiet;	/* be quiet when binding keys */
110 static int	(*x_last_command)(int);
111 
112 static	char   **x_histp;	/* history position */
113 static	int	x_nextcmd;	/* for newline-and-next */
114 static	char	*xmp;		/* mark pointer */
115 #define	KILLSIZE	20
116 static	char	*killstack[KILLSIZE];
117 static	int	killsp, killtp;
118 static	int	x_literal_set;
119 static	int	x_arg_set;
120 static	char	*macro_args;
121 static	int	prompt_skip;
122 static	int	prompt_redraw;
123 
124 static int	x_ins(char *);
125 static void	x_delete(int, int);
126 static int	x_bword(void);
127 static int	x_fword(void);
128 static void	x_goto(char *);
129 static void	x_bs(int);
130 static int	x_size_str(char *);
131 static int	x_size(int);
132 static void	x_zots(char *);
133 static void	x_zotc(int);
134 static void	x_load_hist(char **);
135 static int	x_search(char *, int, int);
136 static int	x_match(char *, char *);
137 static void	x_redraw(int);
138 static void	x_push(int);
139 static void	x_adjust(void);
140 static void	x_e_ungetc(int);
141 static int	x_e_getc(void);
142 static int	x_e_getu8(char *, int);
143 static void	x_e_putc(int);
144 static void	x_e_puts(const char *);
145 static int	x_comment(int);
146 static int	x_fold_case(int);
147 static char	*x_lastcp(void);
148 static void	do_complete(int, Comp_type);
149 static int	isu8cont(unsigned char);
150 
151 /* proto's for keybindings */
152 static int	x_abort(int);
153 static int	x_beg_hist(int);
154 static int	x_clear_screen(int);
155 static int	x_comp_comm(int);
156 static int	x_comp_file(int);
157 static int	x_complete(int);
158 static int	x_del_back(int);
159 static int	x_del_bword(int);
160 static int	x_del_char(int);
161 static int	x_del_fword(int);
162 static int	x_del_line(int);
163 static int	x_draw_line(int);
164 static int	x_end_hist(int);
165 static int	x_end_of_text(int);
166 static int	x_enumerate(int);
167 static int	x_eot_del(int);
168 static int	x_error(int);
169 static int	x_goto_hist(int);
170 static int	x_ins_string(int);
171 static int	x_insert(int);
172 static int	x_kill(int);
173 static int	x_kill_region(int);
174 static int	x_list_comm(int);
175 static int	x_list_file(int);
176 static int	x_literal(int);
177 static int	x_meta_yank(int);
178 static int	x_mv_back(int);
179 static int	x_mv_begin(int);
180 static int	x_mv_bword(int);
181 static int	x_mv_end(int);
182 static int	x_mv_forw(int);
183 static int	x_mv_fword(int);
184 static int	x_newline(int);
185 static int	x_next_com(int);
186 static int	x_nl_next_com(int);
187 static int	x_noop(int);
188 static int	x_prev_com(int);
189 static int	x_prev_histword(int);
190 static int	x_search_char_forw(int);
191 static int	x_search_char_back(int);
192 static int	x_search_hist(int);
193 static int	x_set_mark(int);
194 static int	x_transpose(int);
195 static int	x_xchg_point_mark(int);
196 static int	x_yank(int);
197 static int	x_comp_list(int);
198 static int	x_expand(int);
199 static int	x_fold_capitalize(int);
200 static int	x_fold_lower(int);
201 static int	x_fold_upper(int);
202 static int	x_set_arg(int);
203 static int	x_comment(int);
204 #ifdef DEBUG
205 static int	x_debug_info(int);
206 #endif
207 
208 static const struct x_ftab x_ftab[] = {
209 	{ x_abort,		"abort",			0 },
210 	{ x_beg_hist,		"beginning-of-history",		0 },
211 	{ x_clear_screen,	"clear-screen",			0 },
212 	{ x_comp_comm,		"complete-command",		0 },
213 	{ x_comp_file,		"complete-file",		0 },
214 	{ x_complete,		"complete",			0 },
215 	{ x_del_back,		"delete-char-backward",		XF_ARG },
216 	{ x_del_bword,		"delete-word-backward",		XF_ARG },
217 	{ x_del_char,		"delete-char-forward",		XF_ARG },
218 	{ x_del_fword,		"delete-word-forward",		XF_ARG },
219 	{ x_del_line,		"kill-line",			0 },
220 	{ x_draw_line,		"redraw",			0 },
221 	{ x_end_hist,		"end-of-history",		0 },
222 	{ x_end_of_text,	"eot",				0 },
223 	{ x_enumerate,		"list",				0 },
224 	{ x_eot_del,		"eot-or-delete",		XF_ARG },
225 	{ x_error,		"error",			0 },
226 	{ x_goto_hist,		"goto-history",			XF_ARG },
227 	{ x_ins_string,		"macro-string",			XF_NOBIND },
228 	{ x_insert,		"auto-insert",			XF_ARG },
229 	{ x_kill,		"kill-to-eol",			XF_ARG },
230 	{ x_kill_region,	"kill-region",			0 },
231 	{ x_list_comm,		"list-command",			0 },
232 	{ x_list_file,		"list-file",			0 },
233 	{ x_literal,		"quote",			0 },
234 	{ x_meta_yank,		"yank-pop",			0 },
235 	{ x_mv_back,		"backward-char",		XF_ARG },
236 	{ x_mv_begin,		"beginning-of-line",		0 },
237 	{ x_mv_bword,		"backward-word",		XF_ARG },
238 	{ x_mv_end,		"end-of-line",			0 },
239 	{ x_mv_forw,		"forward-char",			XF_ARG },
240 	{ x_mv_fword,		"forward-word",			XF_ARG },
241 	{ x_newline,		"newline",			0 },
242 	{ x_next_com,		"down-history",			XF_ARG },
243 	{ x_nl_next_com,	"newline-and-next",		0 },
244 	{ x_noop,		"no-op",			0 },
245 	{ x_prev_com,		"up-history",			XF_ARG },
246 	{ x_prev_histword,	"prev-hist-word",		XF_ARG },
247 	{ x_search_char_forw,	"search-character-forward",	XF_ARG },
248 	{ x_search_char_back,	"search-character-backward",	XF_ARG },
249 	{ x_search_hist,	"search-history",		0 },
250 	{ x_set_mark,		"set-mark-command",		0 },
251 	{ x_transpose,		"transpose-chars",		0 },
252 	{ x_xchg_point_mark,	"exchange-point-and-mark",	0 },
253 	{ x_yank,		"yank",				0 },
254 	{ x_comp_list,		"complete-list",		0 },
255 	{ x_expand,		"expand-file",			0 },
256 	{ x_fold_capitalize,	"capitalize-word",		XF_ARG },
257 	{ x_fold_lower,		"downcase-word",		XF_ARG },
258 	{ x_fold_upper,		"upcase-word",			XF_ARG },
259 	{ x_set_arg,		"set-arg",			XF_NOBIND },
260 	{ x_comment,		"comment",			0 },
261 	{ 0, 0, 0 },
262 #ifdef DEBUG
263 	{ x_debug_info,		"debug-info",			0 },
264 #else
265 	{ 0, 0, 0 },
266 #endif
267 	{ 0, 0, 0 },
268 };
269 
270 int
271 isu8cont(unsigned char c)
272 {
273 	return (c & (0x80 | 0x40)) == 0x80;
274 }
275 
276 int
277 x_emacs(char *buf, size_t len)
278 {
279 	struct kb_entry		*k, *kmatch = NULL;
280 	char			line[LINE + 1];
281 	int			at = 0, ntries = 0, submatch, ret;
282 	const char		*p;
283 
284 	xbp = xbuf = buf; xend = buf + len;
285 	xlp = xcp = xep = buf;
286 	*xcp = 0;
287 	xlp_valid = true;
288 	xmp = NULL;
289 	x_histp = histptr + 1;
290 
291 	xx_cols = x_cols;
292 	x_col = promptlen(prompt, &p);
293 	prompt_skip = p - prompt;
294 	x_adj_ok = 1;
295 	prompt_redraw = 1;
296 	if (x_col > xx_cols)
297 		x_col = x_col - (x_col / xx_cols) * xx_cols;
298 	x_displen = xx_cols - 2 - x_col;
299 	x_adj_done = 0;
300 
301 	pprompt(prompt, 0);
302 	if (x_displen < 1) {
303 		x_col = 0;
304 		x_displen = xx_cols - 2;
305 		x_e_putc('\n');
306 		prompt_redraw = 0;
307 	}
308 
309 	if (x_nextcmd >= 0) {
310 		int off = source->line - x_nextcmd;
311 		if (histptr - history >= off)
312 			x_load_hist(histptr - off);
313 		x_nextcmd = -1;
314 	}
315 
316 	x_literal_set = 0;
317 	x_arg = -1;
318 	x_last_command = NULL;
319 	while (1) {
320 		x_flush();
321 		if ((at = x_e_getu8(line, at)) < 0)
322 			return 0;
323 		ntries++;
324 
325 		if (x_arg == -1) {
326 			x_arg = 1;
327 			x_arg_defaulted = 1;
328 		}
329 
330 		if (x_literal_set) {
331 			/* literal, so insert it */
332 			x_literal_set = 0;
333 			submatch = 0;
334 		} else {
335 			submatch = 0;
336 			kmatch = NULL;
337 			TAILQ_FOREACH(k, &kblist, entry) {
338 				if (at > k->len)
339 					continue;
340 
341 				if (memcmp(k->seq, line, at) == 0) {
342 					/* sub match */
343 					submatch++;
344 					if (k->len == at)
345 						kmatch = k;
346 				}
347 
348 				/* see if we can abort search early */
349 				if (submatch > 1)
350 					break;
351 			}
352 		}
353 
354 		if (submatch == 1 && kmatch) {
355 			if (kmatch->ftab->xf_func == x_ins_string &&
356 			    kmatch->args && !macro_args) {
357 				/* treat macro string as input */
358 				macro_args = kmatch->args;
359 				ret = KSTD;
360 			} else
361 				ret = kmatch->ftab->xf_func(line[at - 1]);
362 		} else {
363 			if (submatch)
364 				continue;
365 			if (ntries > 1) {
366 				ret = x_error(0); /* unmatched meta sequence */
367 			} else if (at > 1) {
368 				x_ins(line);
369 				ret = KSTD;
370 			} else {
371 				ret = x_insert(line[0]);
372 			}
373 		}
374 
375 		switch (ret) {
376 		case KSTD:
377 			if (kmatch)
378 				x_last_command = kmatch->ftab->xf_func;
379 			else
380 				x_last_command = NULL;
381 			break;
382 		case KEOL:
383 			ret = xep - xbuf;
384 			return (ret);
385 			break;
386 		case KINTR:
387 			trapsig(SIGINT);
388 			x_mode(false);
389 			unwind(LSHELL);
390 			x_arg = -1;
391 			break;
392 		default:
393 			bi_errorf("invalid return code"); /* can't happen */
394 		}
395 
396 		/* reset meta sequence */
397 		at = ntries = 0;
398 		if (x_arg_set)
399 			x_arg_set = 0; /* reset args next time around */
400 		else
401 			x_arg = -1;
402 	}
403 }
404 
405 static int
406 x_insert(int c)
407 {
408 	char	str[2];
409 
410 	/*
411 	 *  Should allow tab and control chars.
412 	 */
413 	if (c == 0) {
414 		x_e_putc(BEL);
415 		return KSTD;
416 	}
417 	str[0] = c;
418 	str[1] = '\0';
419 	while (x_arg--)
420 		x_ins(str);
421 	return KSTD;
422 }
423 
424 static int
425 x_ins_string(int c)
426 {
427 	return x_insert(c);
428 }
429 
430 static int
431 x_do_ins(const char *cp, size_t len)
432 {
433 	if (xep+len >= xend) {
434 		x_e_putc(BEL);
435 		return -1;
436 	}
437 
438 	memmove(xcp+len, xcp, xep - xcp + 1);
439 	memmove(xcp, cp, len);
440 	xcp += len;
441 	xep += len;
442 	return 0;
443 }
444 
445 static int
446 x_ins(char *s)
447 {
448 	char	*cp = xcp;
449 	int	adj = x_adj_done;
450 
451 	if (x_do_ins(s, strlen(s)) < 0)
452 		return -1;
453 	/*
454 	 * x_zots() may result in a call to x_adjust()
455 	 * we want xcp to reflect the new position.
456 	 */
457 	xlp_valid = false;
458 	x_lastcp();
459 	x_adj_ok = (xcp >= xlp);
460 	x_zots(cp);
461 	if (adj == x_adj_done) {	/* has x_adjust() been called? */
462 		/* no */
463 		for (cp = xlp; cp > xcp; )
464 			x_bs(*--cp);
465 	}
466 
467 	x_adj_ok = 1;
468 	return 0;
469 }
470 
471 static int
472 x_del_back(int c)
473 {
474 	int col = xcp - xbuf;
475 
476 	if (col == 0) {
477 		x_e_putc(BEL);
478 		return KSTD;
479 	}
480 	if (x_arg > col)
481 		x_arg = col;
482 	while (x_arg < col && isu8cont(xcp[-x_arg]))
483 		x_arg++;
484 	x_goto(xcp - x_arg);
485 	x_delete(x_arg, false);
486 	return KSTD;
487 }
488 
489 static int
490 x_del_char(int c)
491 {
492 	int nleft = xep - xcp;
493 
494 	if (!nleft) {
495 		x_e_putc(BEL);
496 		return KSTD;
497 	}
498 	if (x_arg > nleft)
499 		x_arg = nleft;
500 	while (x_arg < nleft && isu8cont(xcp[x_arg]))
501 		x_arg++;
502 	x_delete(x_arg, false);
503 	return KSTD;
504 }
505 
506 /* Delete nc bytes to the right of the cursor (including cursor position) */
507 static void
508 x_delete(int nc, int push)
509 {
510 	int	i,j;
511 	char	*cp;
512 
513 	if (nc == 0)
514 		return;
515 	if (xmp != NULL && xmp > xcp) {
516 		if (xcp + nc > xmp)
517 			xmp = xcp;
518 		else
519 			xmp -= nc;
520 	}
521 
522 	/*
523 	 * This lets us yank a word we have deleted.
524 	 */
525 	if (push)
526 		x_push(nc);
527 
528 	xep -= nc;
529 	cp = xcp;
530 	j = 0;
531 	i = nc;
532 	while (i--) {
533 		j += x_size((unsigned char)*cp++);
534 	}
535 	memmove(xcp, xcp+nc, xep - xcp + 1);	/* Copies the null */
536 	x_adj_ok = 0;			/* don't redraw */
537 	xlp_valid = false;
538 	x_zots(xcp);
539 	/*
540 	 * if we are already filling the line,
541 	 * there is no need to ' ','\b'.
542 	 * But if we must, make sure we do the minimum.
543 	 */
544 	if ((i = xx_cols - 2 - x_col) > 0) {
545 		j = (j < i) ? j : i;
546 		i = j;
547 		while (i--)
548 			x_e_putc(' ');
549 		i = j;
550 		while (i--)
551 			x_e_putc('\b');
552 	}
553 	/*x_goto(xcp);*/
554 	x_adj_ok = 1;
555 	xlp_valid = false;
556 	for (cp = x_lastcp(); cp > xcp; )
557 		x_bs(*--cp);
558 
559 	return;
560 }
561 
562 static int
563 x_del_bword(int c)
564 {
565 	x_delete(x_bword(), true);
566 	return KSTD;
567 }
568 
569 static int
570 x_mv_bword(int c)
571 {
572 	(void)x_bword();
573 	return KSTD;
574 }
575 
576 static int
577 x_mv_fword(int c)
578 {
579 	x_goto(xcp + x_fword());
580 	return KSTD;
581 }
582 
583 static int
584 x_del_fword(int c)
585 {
586 	x_delete(x_fword(), true);
587 	return KSTD;
588 }
589 
590 static int
591 x_bword(void)
592 {
593 	int	nc = 0;
594 	char	*cp = xcp;
595 
596 	if (cp == xbuf) {
597 		x_e_putc(BEL);
598 		return 0;
599 	}
600 	while (x_arg--) {
601 		while (cp != xbuf && is_mfs(cp[-1])) {
602 			cp--;
603 			nc++;
604 		}
605 		while (cp != xbuf && !is_mfs(cp[-1])) {
606 			cp--;
607 			nc++;
608 		}
609 	}
610 	x_goto(cp);
611 	return nc;
612 }
613 
614 static int
615 x_fword(void)
616 {
617 	int	nc = 0;
618 	char	*cp = xcp;
619 
620 	if (cp == xep) {
621 		x_e_putc(BEL);
622 		return 0;
623 	}
624 	while (x_arg--) {
625 		while (cp != xep && is_mfs(*cp)) {
626 			cp++;
627 			nc++;
628 		}
629 		while (cp != xep && !is_mfs(*cp)) {
630 			cp++;
631 			nc++;
632 		}
633 	}
634 	return nc;
635 }
636 
637 static void
638 x_goto(char *cp)
639 {
640 	if (cp < xbp || cp >= (xbp + x_displen)) {
641 		/* we are heading off screen */
642 		xcp = cp;
643 		x_adjust();
644 	} else if (cp < xcp) {		/* move back */
645 		while (cp < xcp)
646 			x_bs((unsigned char)*--xcp);
647 	} else if (cp > xcp) {		/* move forward */
648 		while (cp > xcp)
649 			x_zotc((unsigned char)*xcp++);
650 	}
651 }
652 
653 static void
654 x_bs(int c)
655 {
656 	int i;
657 
658 	i = x_size(c);
659 	while (i--)
660 		x_e_putc('\b');
661 }
662 
663 static int
664 x_size_str(char *cp)
665 {
666 	int size = 0;
667 	while (*cp)
668 		size += x_size(*cp++);
669 	return size;
670 }
671 
672 static int
673 x_size(int c)
674 {
675 	if (c=='\t')
676 		return 4;	/* Kludge, tabs are always four spaces. */
677 	if (iscntrl(c))		/* control char */
678 		return 2;
679 	if (isu8cont(c))
680 		return 0;
681 	return 1;
682 }
683 
684 static void
685 x_zots(char *str)
686 {
687 	int	adj = x_adj_done;
688 
689 	if (str > xbuf && isu8cont(*str)) {
690 		while (str > xbuf && isu8cont(*str))
691 			str--;
692 		x_e_putc('\b');
693 	}
694 	x_lastcp();
695 	while (*str && str < xlp && adj == x_adj_done)
696 		x_zotc(*str++);
697 }
698 
699 static void
700 x_zotc(int c)
701 {
702 	if (c == '\t') {
703 		/*  Kludge, tabs are always four spaces.  */
704 		x_e_puts("    ");
705 	} else if (iscntrl(c)) {
706 		x_e_putc('^');
707 		x_e_putc(UNCTRL(c));
708 	} else
709 		x_e_putc(c);
710 }
711 
712 static int
713 x_mv_back(int c)
714 {
715 	int col = xcp - xbuf;
716 
717 	if (col == 0) {
718 		x_e_putc(BEL);
719 		return KSTD;
720 	}
721 	if (x_arg > col)
722 		x_arg = col;
723 	while (x_arg < col && isu8cont(xcp[-x_arg]))
724 		x_arg++;
725 	x_goto(xcp - x_arg);
726 	return KSTD;
727 }
728 
729 static int
730 x_mv_forw(int c)
731 {
732 	int nleft = xep - xcp;
733 
734 	if (!nleft) {
735 		x_e_putc(BEL);
736 		return KSTD;
737 	}
738 	if (x_arg > nleft)
739 		x_arg = nleft;
740 	while (x_arg < nleft && isu8cont(xcp[x_arg]))
741 		x_arg++;
742 	x_goto(xcp + x_arg);
743 	return KSTD;
744 }
745 
746 static int
747 x_search_char_forw(int c)
748 {
749 	char *cp = xcp;
750 
751 	*xep = '\0';
752 	c = x_e_getc();
753 	while (x_arg--) {
754 		if (c < 0 ||
755 		    ((cp = (cp == xep) ? NULL : strchr(cp + 1, c)) == NULL &&
756 		    (cp = strchr(xbuf, c)) == NULL)) {
757 			x_e_putc(BEL);
758 			return KSTD;
759 		}
760 	}
761 	x_goto(cp);
762 	return KSTD;
763 }
764 
765 static int
766 x_search_char_back(int c)
767 {
768 	char *cp = xcp, *p;
769 
770 	c = x_e_getc();
771 	for (; x_arg--; cp = p)
772 		for (p = cp; ; ) {
773 			if (p-- == xbuf)
774 				p = xep;
775 			if (c < 0 || p == cp) {
776 				x_e_putc(BEL);
777 				return KSTD;
778 			}
779 			if (*p == c)
780 				break;
781 		}
782 	x_goto(cp);
783 	return KSTD;
784 }
785 
786 static int
787 x_newline(int c)
788 {
789 	x_e_putc('\r');
790 	x_e_putc('\n');
791 	x_flush();
792 	*xep++ = '\n';
793 	return KEOL;
794 }
795 
796 static int
797 x_end_of_text(int c)
798 {
799 	x_zotc(edchars.eof);
800 	x_putc('\r');
801 	x_putc('\n');
802 	x_flush();
803 	return KEOL;
804 }
805 
806 static int x_beg_hist(int c) { x_load_hist(history); return KSTD;}
807 
808 static int x_end_hist(int c) { x_load_hist(histptr); return KSTD;}
809 
810 static int x_prev_com(int c) { x_load_hist(x_histp - x_arg); return KSTD;}
811 
812 static int x_next_com(int c) { x_load_hist(x_histp + x_arg); return KSTD;}
813 
814 /* Goto a particular history number obtained from argument.
815  * If no argument is given history 1 is probably not what you
816  * want so we'll simply go to the oldest one.
817  */
818 static int
819 x_goto_hist(int c)
820 {
821 	if (x_arg_defaulted)
822 		x_load_hist(history);
823 	else
824 		x_load_hist(histptr + x_arg - source->line);
825 	return KSTD;
826 }
827 
828 static void
829 x_load_hist(char **hp)
830 {
831 	int	oldsize;
832 
833 	if (hp < history || hp > histptr) {
834 		x_e_putc(BEL);
835 		return;
836 	}
837 	x_histp = hp;
838 	oldsize = x_size_str(xbuf);
839 	strlcpy(xbuf, *hp, xend - xbuf);
840 	xbp = xbuf;
841 	xep = xcp = xbuf + strlen(xbuf);
842 	xlp_valid = false;
843 	if (xep <= x_lastcp())
844 		x_redraw(oldsize);
845 	x_goto(xep);
846 }
847 
848 static int
849 x_nl_next_com(int c)
850 {
851 	x_nextcmd = source->line - (histptr - x_histp) + 1;
852 	return (x_newline(c));
853 }
854 
855 static int
856 x_eot_del(int c)
857 {
858 	if (xep == xbuf && x_arg_defaulted)
859 		return (x_end_of_text(c));
860 	else
861 		return (x_del_char(c));
862 }
863 
864 static void *
865 kb_find_hist_func(char c)
866 {
867 	struct kb_entry		*k;
868 	char			line[LINE + 1];
869 
870 	line[0] = c;
871 	line[1] = '\0';
872 	TAILQ_FOREACH(k, &kblist, entry)
873 		if (!strcmp(k->seq, line))
874 			return (k->ftab->xf_func);
875 
876 	return (x_insert);
877 }
878 
879 /* reverse incremental history search */
880 static int
881 x_search_hist(int c)
882 {
883 	int offset = -1;	/* offset of match in xbuf, else -1 */
884 	char pat [256+1];	/* pattern buffer */
885 	char *p = pat;
886 	int (*f)(int);
887 
888 	*p = '\0';
889 	while (1) {
890 		if (offset < 0) {
891 			x_e_puts("\nI-search: ");
892 			x_e_puts(pat);
893 		}
894 		x_flush();
895 		if ((c = x_e_getc()) < 0)
896 			return KSTD;
897 		f = kb_find_hist_func(c);
898 		if (c == CTRL('[')) {
899 			x_e_ungetc(c);
900 			break;
901 		} else if (f == x_search_hist)
902 			offset = x_search(pat, 0, offset);
903 		else if (f == x_del_back) {
904 			if (p == pat) {
905 				offset = -1;
906 				break;
907 			}
908 			if (p > pat)
909 				*--p = '\0';
910 			if (p == pat)
911 				offset = -1;
912 			else
913 				offset = x_search(pat, 1, offset);
914 			continue;
915 		} else if (f == x_insert) {
916 			/* add char to pattern */
917 			/* overflow check... */
918 			if (p >= &pat[sizeof(pat) - 1]) {
919 				x_e_putc(BEL);
920 				continue;
921 			}
922 			*p++ = c, *p = '\0';
923 			if (offset >= 0) {
924 				/* already have partial match */
925 				offset = x_match(xbuf, pat);
926 				if (offset >= 0) {
927 					x_goto(xbuf + offset + (p - pat) -
928 					    (*pat == '^'));
929 					continue;
930 				}
931 			}
932 			offset = x_search(pat, 0, offset);
933 		} else { /* other command */
934 			x_e_ungetc(c);
935 			break;
936 		}
937 	}
938 	if (offset < 0)
939 		x_redraw(-1);
940 	return KSTD;
941 }
942 
943 /* search backward from current line */
944 static int
945 x_search(char *pat, int sameline, int offset)
946 {
947 	char **hp;
948 	int i;
949 
950 	for (hp = x_histp - (sameline ? 0 : 1) ; hp >= history; --hp) {
951 		i = x_match(*hp, pat);
952 		if (i >= 0) {
953 			if (offset < 0)
954 				x_e_putc('\n');
955 			x_load_hist(hp);
956 			x_goto(xbuf + i + strlen(pat) - (*pat == '^'));
957 			return i;
958 		}
959 	}
960 	x_e_putc(BEL);
961 	x_histp = histptr;
962 	return -1;
963 }
964 
965 /* return position of first match of pattern in string, else -1 */
966 static int
967 x_match(char *str, char *pat)
968 {
969 	if (*pat == '^') {
970 		return (strncmp(str, pat+1, strlen(pat+1)) == 0) ? 0 : -1;
971 	} else {
972 		char *q = strstr(str, pat);
973 		return (q == NULL) ? -1 : q - str;
974 	}
975 }
976 
977 static int
978 x_del_line(int c)
979 {
980 	int	i, j;
981 
982 	*xep = 0;
983 	i = xep - xbuf;
984 	j = x_size_str(xbuf);
985 	xcp = xbuf;
986 	x_push(i);
987 	xlp = xbp = xep = xbuf;
988 	xlp_valid = true;
989 	*xcp = 0;
990 	xmp = NULL;
991 	x_redraw(j);
992 	return KSTD;
993 }
994 
995 static int
996 x_mv_end(int c)
997 {
998 	x_goto(xep);
999 	return KSTD;
1000 }
1001 
1002 static int
1003 x_mv_begin(int c)
1004 {
1005 	x_goto(xbuf);
1006 	return KSTD;
1007 }
1008 
1009 static int
1010 x_draw_line(int c)
1011 {
1012 	x_redraw(-1);
1013 	return KSTD;
1014 }
1015 
1016 static int
1017 x_clear_screen(int c)
1018 {
1019 	x_redraw(-2);
1020 	return KSTD;
1021 }
1022 
1023 /* Redraw (part of) the line.
1024  * A non-negative limit is the screen column up to which needs
1025  * redrawing. A limit of -1 redraws on a new line, while a limit
1026  * of -2 (attempts to) clear the screen.
1027  */
1028 static void
1029 x_redraw(int limit)
1030 {
1031 	int	i, j, truncate = 0;
1032 	char	*cp;
1033 
1034 	x_adj_ok = 0;
1035 	if (limit == -2) {
1036 		int cleared = 0;
1037 #ifndef SMALL
1038 		if (cur_term != NULL && clear_screen != NULL) {
1039 			if (tputs(clear_screen, 1, x_putc) != ERR)
1040 				cleared = 1;
1041 		}
1042 #endif
1043 		if (!cleared)
1044 			x_e_putc('\n');
1045 	}
1046 	else if (limit == -1)
1047 		x_e_putc('\n');
1048 	else if (limit >= 0)
1049 		x_e_putc('\r');
1050 	x_flush();
1051 	if (xbp == xbuf) {
1052 		x_col = promptlen(prompt, NULL);
1053 		if (x_col > xx_cols)
1054 			truncate = (x_col / xx_cols) * xx_cols;
1055 		if (prompt_redraw)
1056 			pprompt(prompt + prompt_skip, truncate);
1057 	}
1058 	if (x_col > xx_cols)
1059 		x_col = x_col - (x_col / xx_cols) * xx_cols;
1060 	x_displen = xx_cols - 2 - x_col;
1061 	if (x_displen < 1) {
1062 		x_col = 0;
1063 		x_displen = xx_cols - 2;
1064 	}
1065 	xlp_valid = false;
1066 	x_lastcp();
1067 	x_zots(xbp);
1068 	if (xbp != xbuf || xep > xlp)
1069 		limit = xx_cols;
1070 	if (limit >= 0) {
1071 		if (xep > xlp)
1072 			i = 0;			/* we fill the line */
1073 		else
1074 			i = limit - (xlp - xbp);
1075 
1076 		for (j = 0; j < i && x_col < (xx_cols - 2); j++)
1077 			x_e_putc(' ');
1078 		i = ' ';
1079 		if (xep > xlp) {		/* more off screen */
1080 			if (xbp > xbuf)
1081 				i = '*';
1082 			else
1083 				i = '>';
1084 		} else if (xbp > xbuf)
1085 			i = '<';
1086 		x_e_putc(i);
1087 		j++;
1088 		while (j--)
1089 			x_e_putc('\b');
1090 	}
1091 	for (cp = xlp; cp > xcp; )
1092 		x_bs(*--cp);
1093 	x_adj_ok = 1;
1094 #ifdef DEBUG
1095 	x_flush();
1096 #endif
1097 	return;
1098 }
1099 
1100 static int
1101 x_transpose(int c)
1102 {
1103 	char	tmp;
1104 
1105 	/* What transpose is meant to do seems to be up for debate. This
1106 	 * is a general summary of the options; the text is abcd with the
1107 	 * upper case character or underscore indicating the cursor position:
1108 	 *     Who			Before	After  Before	After
1109 	 *     at&t ksh in emacs mode:	abCd	abdC   abcd_	(bell)
1110 	 *     at&t ksh in gmacs mode:	abCd	baCd   abcd_	abdc_
1111 	 *     gnu emacs:		abCd	acbD   abcd_	abdc_
1112 	 * Pdksh currently goes with GNU behavior since I believe this is the
1113 	 * most common version of emacs, unless in gmacs mode, in which case
1114 	 * it does the at&t ksh gmacs mode.
1115 	 * This should really be broken up into 3 functions so users can bind
1116 	 * to the one they want.
1117 	 */
1118 	if (xcp == xbuf) {
1119 		x_e_putc(BEL);
1120 		return KSTD;
1121 	} else if (xcp == xep || Flag(FGMACS)) {
1122 		if (xcp - xbuf == 1) {
1123 			x_e_putc(BEL);
1124 			return KSTD;
1125 		}
1126 		/* Gosling/Unipress emacs style: Swap two characters before the
1127 		 * cursor, do not change cursor position
1128 		 */
1129 		x_bs(xcp[-1]);
1130 		x_bs(xcp[-2]);
1131 		x_zotc(xcp[-1]);
1132 		x_zotc(xcp[-2]);
1133 		tmp = xcp[-1];
1134 		xcp[-1] = xcp[-2];
1135 		xcp[-2] = tmp;
1136 	} else {
1137 		/* GNU emacs style: Swap the characters before and under the
1138 		 * cursor, move cursor position along one.
1139 		 */
1140 		x_bs(xcp[-1]);
1141 		x_zotc(xcp[0]);
1142 		x_zotc(xcp[-1]);
1143 		tmp = xcp[-1];
1144 		xcp[-1] = xcp[0];
1145 		xcp[0] = tmp;
1146 		x_bs(xcp[0]);
1147 		x_goto(xcp + 1);
1148 	}
1149 	return KSTD;
1150 }
1151 
1152 static int
1153 x_literal(int c)
1154 {
1155 	x_literal_set = 1;
1156 	return KSTD;
1157 }
1158 
1159 static int
1160 x_kill(int c)
1161 {
1162 	int col = xcp - xbuf;
1163 	int lastcol = xep - xbuf;
1164 	int ndel;
1165 
1166 	if (x_arg_defaulted)
1167 		x_arg = lastcol;
1168 	else if (x_arg > lastcol)
1169 		x_arg = lastcol;
1170 	while (x_arg < lastcol && isu8cont(xbuf[x_arg]))
1171 		x_arg++;
1172 	ndel = x_arg - col;
1173 	if (ndel < 0) {
1174 		x_goto(xbuf + x_arg);
1175 		ndel = -ndel;
1176 	}
1177 	x_delete(ndel, true);
1178 	return KSTD;
1179 }
1180 
1181 static void
1182 x_push(int nchars)
1183 {
1184 	char	*cp = str_nsave(xcp, nchars, AEDIT);
1185 	afree(killstack[killsp], AEDIT);
1186 	killstack[killsp] = cp;
1187 	killsp = (killsp + 1) % KILLSIZE;
1188 }
1189 
1190 static int
1191 x_yank(int c)
1192 {
1193 	if (killsp == 0)
1194 		killtp = KILLSIZE;
1195 	else
1196 		killtp = killsp;
1197 	killtp --;
1198 	if (killstack[killtp] == 0) {
1199 		x_e_puts("\nnothing to yank");
1200 		x_redraw(-1);
1201 		return KSTD;
1202 	}
1203 	xmp = xcp;
1204 	x_ins(killstack[killtp]);
1205 	return KSTD;
1206 }
1207 
1208 static int
1209 x_meta_yank(int c)
1210 {
1211 	int	len;
1212 	if ((x_last_command != x_yank && x_last_command != x_meta_yank) ||
1213 	    killstack[killtp] == 0) {
1214 		killtp = killsp;
1215 		x_e_puts("\nyank something first");
1216 		x_redraw(-1);
1217 		return KSTD;
1218 	}
1219 	len = strlen(killstack[killtp]);
1220 	x_goto(xcp - len);
1221 	x_delete(len, false);
1222 	do {
1223 		if (killtp == 0)
1224 			killtp = KILLSIZE - 1;
1225 		else
1226 			killtp--;
1227 	} while (killstack[killtp] == 0);
1228 	x_ins(killstack[killtp]);
1229 	return KSTD;
1230 }
1231 
1232 static int
1233 x_abort(int c)
1234 {
1235 	/* x_zotc(c); */
1236 	xlp = xep = xcp = xbp = xbuf;
1237 	xlp_valid = true;
1238 	*xcp = 0;
1239 	return KINTR;
1240 }
1241 
1242 static int
1243 x_error(int c)
1244 {
1245 	x_e_putc(BEL);
1246 	return KSTD;
1247 }
1248 
1249 static char *
1250 kb_encode(const char *s)
1251 {
1252 	static char		l[LINE + 1];
1253 	int			at = 0;
1254 
1255 	l[at] = '\0';
1256 	while (*s) {
1257 		if (*s == '^') {
1258 			s++;
1259 			if (*s >= '?')
1260 				l[at++] = CTRL(*s);
1261 			else {
1262 				l[at++] = '^';
1263 				s--;
1264 			}
1265 		} else
1266 			l[at++] = *s;
1267 		l[at] = '\0';
1268 		s++;
1269 	}
1270 	return (l);
1271 }
1272 
1273 static char *
1274 kb_decode(const char *s)
1275 {
1276 	static char		l[LINE + 1];
1277 	unsigned int		i, at = 0;
1278 
1279 	l[0] = '\0';
1280 	for (i = 0; i < strlen(s); i++) {
1281 		if (iscntrl((unsigned char)s[i])) {
1282 			l[at++] = '^';
1283 			l[at++] = UNCTRL(s[i]);
1284 		} else
1285 			l[at++] = s[i];
1286 		l[at] = '\0';
1287 	}
1288 
1289 	return (l);
1290 }
1291 
1292 static int
1293 kb_match(char *s)
1294 {
1295 	int			len = strlen(s);
1296 	struct kb_entry		*k;
1297 
1298 	TAILQ_FOREACH(k, &kblist, entry) {
1299 		if (len > k->len)
1300 			continue;
1301 
1302 		if (memcmp(k->seq, s, len) == 0)
1303 			return (1);
1304 	}
1305 
1306 	return (0);
1307 }
1308 
1309 static void
1310 kb_del(struct kb_entry *k)
1311 {
1312 	TAILQ_REMOVE(&kblist, k, entry);
1313 	free(k->args);
1314 	afree(k, AEDIT);
1315 }
1316 
1317 static struct kb_entry *
1318 kb_add_string(void *func, void *args, char *str)
1319 {
1320 	unsigned int		ele, count;
1321 	struct kb_entry		*k;
1322 	struct x_ftab		*xf = NULL;
1323 
1324 	for (ele = 0; ele < NELEM(x_ftab); ele++)
1325 		if (x_ftab[ele].xf_func == func) {
1326 			xf = (struct x_ftab *)&x_ftab[ele];
1327 			break;
1328 		}
1329 	if (xf == NULL)
1330 		return (NULL);
1331 
1332 	if (kb_match(str)) {
1333 		if (x_bind_quiet == 0)
1334 			bi_errorf("duplicate binding for %s", kb_decode(str));
1335 		return (NULL);
1336 	}
1337 	count = strlen(str);
1338 
1339 	k = alloc(sizeof *k + count + 1, AEDIT);
1340 	k->seq = (unsigned char *)(k + 1);
1341 	k->len = count;
1342 	k->ftab = xf;
1343 	k->args = args ? strdup(args) : NULL;
1344 
1345 	strlcpy(k->seq, str, count + 1);
1346 
1347 	TAILQ_INSERT_TAIL(&kblist, k, entry);
1348 
1349 	return (k);
1350 }
1351 
1352 static struct kb_entry *
1353 kb_add(void *func, ...)
1354 {
1355 	va_list			ap;
1356 	unsigned char		ch;
1357 	unsigned int		i;
1358 	char			line[LINE + 1];
1359 
1360 	va_start(ap, func);
1361 	for (i = 0; i < sizeof(line) - 1; i++) {
1362 		ch = va_arg(ap, unsigned int);
1363 		if (ch == 0)
1364 			break;
1365 		line[i] = ch;
1366 	}
1367 	va_end(ap);
1368 	line[i] = '\0';
1369 
1370 	return (kb_add_string(func, NULL, line));
1371 }
1372 
1373 static void
1374 kb_print(struct kb_entry *k)
1375 {
1376 	if (!(k->ftab->xf_flags & XF_NOBIND))
1377 		shprintf("%s = %s\n",
1378 		    kb_decode(k->seq), k->ftab->xf_name);
1379 	else if (k->args) {
1380 		shprintf("%s = ", kb_decode(k->seq));
1381 		shprintf("'%s'\n", kb_decode(k->args));
1382 	}
1383 }
1384 
1385 int
1386 x_bind(const char *a1, const char *a2,
1387 	int macro,		/* bind -m */
1388 	int list)		/* bind -l */
1389 {
1390 	unsigned int		i;
1391 	struct kb_entry		*k, *kb;
1392 	char			in[LINE + 1];
1393 
1394 	if (x_tty == 0) {
1395 		bi_errorf("cannot bind, not a tty");
1396 		return (1);
1397 	}
1398 
1399 	if (list) {
1400 		/* show all function names */
1401 		for (i = 0; i < NELEM(x_ftab); i++) {
1402 			if (x_ftab[i].xf_name == NULL)
1403 				continue;
1404 			if (x_ftab[i].xf_name &&
1405 			    !(x_ftab[i].xf_flags & XF_NOBIND))
1406 				shprintf("%s\n", x_ftab[i].xf_name);
1407 		}
1408 		return (0);
1409 	}
1410 
1411 	if (a1 == NULL) {
1412 		/* show all bindings */
1413 		TAILQ_FOREACH(k, &kblist, entry)
1414 			kb_print(k);
1415 		return (0);
1416 	}
1417 
1418 	snprintf(in, sizeof in, "%s", kb_encode(a1));
1419 	if (a2 == NULL) {
1420 		/* print binding */
1421 		TAILQ_FOREACH(k, &kblist, entry)
1422 			if (!strcmp(k->seq, in)) {
1423 				kb_print(k);
1424 				return (0);
1425 			}
1426 		shprintf("%s = %s\n", kb_decode(a1), "auto-insert");
1427 		return (0);
1428 	}
1429 
1430 	if (strlen(a2) == 0) {
1431 		/* clear binding */
1432 		TAILQ_FOREACH_SAFE(k, &kblist, entry, kb)
1433 			if (!strcmp(k->seq, in)) {
1434 				kb_del(k);
1435 				break;
1436 			}
1437 		return (0);
1438 	}
1439 
1440 	/* set binding */
1441 	if (macro) {
1442 		/* delete old mapping */
1443 		TAILQ_FOREACH_SAFE(k, &kblist, entry, kb)
1444 			if (!strcmp(k->seq, in)) {
1445 				kb_del(k);
1446 				break;
1447 			}
1448 		kb_add_string(x_ins_string, kb_encode(a2), in);
1449 		return (0);
1450 	}
1451 
1452 	/* set non macro binding */
1453 	for (i = 0; i < NELEM(x_ftab); i++) {
1454 		if (x_ftab[i].xf_name == NULL)
1455 			continue;
1456 		if (!strcmp(x_ftab[i].xf_name, a2)) {
1457 			/* delete old mapping */
1458 			TAILQ_FOREACH_SAFE(k, &kblist, entry, kb)
1459 				if (!strcmp(k->seq, in)) {
1460 					kb_del(k);
1461 					break;
1462 				}
1463 			kb_add_string(x_ftab[i].xf_func, NULL, in);
1464 			return (0);
1465 		}
1466 	}
1467 	bi_errorf("%s: no such function", a2);
1468 	return (1);
1469 }
1470 
1471 void
1472 x_init_emacs(void)
1473 {
1474 	x_tty = 1;
1475 	ainit(AEDIT);
1476 	x_nextcmd = -1;
1477 
1478 	TAILQ_INIT(&kblist);
1479 
1480 	/* man page order */
1481 	kb_add(x_abort,			CTRL('G'), 0);
1482 	kb_add(x_mv_back,		CTRL('B'), 0);
1483 	kb_add(x_mv_back,		CTRL('X'), CTRL('D'), 0);
1484 	kb_add(x_mv_bword,		CTRL('['), 'b', 0);
1485 	kb_add(x_beg_hist,		CTRL('['), '<', 0);
1486 	kb_add(x_mv_begin,		CTRL('A'), 0);
1487 	kb_add(x_fold_capitalize,	CTRL('['), 'C', 0);
1488 	kb_add(x_fold_capitalize,	CTRL('['), 'c', 0);
1489 	kb_add(x_comment,		CTRL('['), '#', 0);
1490 	kb_add(x_complete,		CTRL('['), CTRL('['), 0);
1491 	kb_add(x_comp_comm,		CTRL('X'), CTRL('['), 0);
1492 	kb_add(x_comp_file,		CTRL('['), CTRL('X'), 0);
1493 	kb_add(x_comp_list,		CTRL('I'), 0);
1494 	kb_add(x_comp_list,		CTRL('['), '=', 0);
1495 	kb_add(x_del_back,		CTRL('?'), 0);
1496 	kb_add(x_del_back,		CTRL('H'), 0);
1497 	kb_add(x_del_char,		CTRL('['), '[', '3', '~', 0); /* delete */
1498 	kb_add(x_del_bword,		CTRL('W'), 0);
1499 	kb_add(x_del_bword,		CTRL('['), CTRL('?'), 0);
1500 	kb_add(x_del_bword,		CTRL('['), CTRL('H'), 0);
1501 	kb_add(x_del_bword,		CTRL('['), 'h', 0);
1502 	kb_add(x_del_fword,		CTRL('['), 'd', 0);
1503 	kb_add(x_next_com,		CTRL('N'), 0);
1504 	kb_add(x_next_com,		CTRL('X'), 'B', 0);
1505 	kb_add(x_fold_lower,		CTRL('['), 'L', 0);
1506 	kb_add(x_fold_lower,		CTRL('['), 'l', 0);
1507 	kb_add(x_end_hist,		CTRL('['), '>', 0);
1508 	kb_add(x_mv_end,		CTRL('E'), 0);
1509 	/* how to handle: eot: ^_, underneath copied from original keybindings */
1510 	kb_add(x_end_of_text,		CTRL('_'), 0);
1511 	kb_add(x_eot_del,		CTRL('D'), 0);
1512 	/* error */
1513 	kb_add(x_xchg_point_mark,	CTRL('X'), CTRL('X'), 0);
1514 	kb_add(x_expand,		CTRL('['), '*', 0);
1515 	kb_add(x_mv_forw,		CTRL('F'), 0);
1516 	kb_add(x_mv_forw,		CTRL('X'), 'C', 0);
1517 	kb_add(x_mv_fword,		CTRL('['), 'f', 0);
1518 	kb_add(x_goto_hist,		CTRL('['), 'g', 0);
1519 	/* kill-line */
1520 	kb_add(x_kill,			CTRL('K'), 0);
1521 	kb_add(x_enumerate,		CTRL('['), '?', 0);
1522 	kb_add(x_list_comm,		CTRL('X'), '?', 0);
1523 	kb_add(x_list_file,		CTRL('X'), CTRL('Y'), 0);
1524 	kb_add(x_newline,		CTRL('J'), 0);
1525 	kb_add(x_newline,		CTRL('M'), 0);
1526 	kb_add(x_nl_next_com,		CTRL('O'), 0);
1527 	/* no-op */
1528 	kb_add(x_prev_histword,		CTRL('['), '.', 0);
1529 	kb_add(x_prev_histword,		CTRL('['), '_', 0);
1530 	/* how to handle: quote: ^^ */
1531 	kb_add(x_literal,		CTRL('^'), 0);
1532 	kb_add(x_clear_screen,		CTRL('L'), 0);
1533 	kb_add(x_search_char_back,	CTRL('['), CTRL(']'), 0);
1534 	kb_add(x_search_char_forw,	CTRL(']'), 0);
1535 	kb_add(x_search_hist,		CTRL('R'), 0);
1536 	kb_add(x_set_mark,		CTRL('['), ' ', 0);
1537 	kb_add(x_transpose,		CTRL('T'), 0);
1538 	kb_add(x_prev_com,		CTRL('P'), 0);
1539 	kb_add(x_prev_com,		CTRL('X'), 'A', 0);
1540 	kb_add(x_fold_upper,		CTRL('['), 'U', 0);
1541 	kb_add(x_fold_upper,		CTRL('['), 'u', 0);
1542 	kb_add(x_literal,		CTRL('V'), 0);
1543 	kb_add(x_yank,			CTRL('Y'), 0);
1544 	kb_add(x_meta_yank,		CTRL('['), 'y', 0);
1545 	/* man page ends here */
1546 
1547 	/* arrow keys */
1548 	kb_add(x_prev_com,		CTRL('['), '[', 'A', 0); /* up */
1549 	kb_add(x_next_com,		CTRL('['), '[', 'B', 0); /* down */
1550 	kb_add(x_mv_forw,		CTRL('['), '[', 'C', 0); /* right */
1551 	kb_add(x_mv_back,		CTRL('['), '[', 'D', 0); /* left */
1552 	kb_add(x_prev_com,		CTRL('['), 'O', 'A', 0); /* up */
1553 	kb_add(x_next_com,		CTRL('['), 'O', 'B', 0); /* down */
1554 	kb_add(x_mv_forw,		CTRL('['), 'O', 'C', 0); /* right */
1555 	kb_add(x_mv_back,		CTRL('['), 'O', 'D', 0); /* left */
1556 
1557 	/* more navigation keys */
1558 	kb_add(x_mv_begin,		CTRL('['), '[', 'H', 0); /* home */
1559 	kb_add(x_mv_end,		CTRL('['), '[', 'F', 0); /* end */
1560 	kb_add(x_mv_begin,		CTRL('['), 'O', 'H', 0); /* home */
1561 	kb_add(x_mv_end,		CTRL('['), 'O', 'F', 0); /* end */
1562 	kb_add(x_mv_begin,		CTRL('['), '[', '1', '~', 0); /* home */
1563 	kb_add(x_mv_end,		CTRL('['), '[', '4', '~', 0); /* end */
1564 	kb_add(x_mv_begin,		CTRL('['), '[', '7', '~', 0); /* home */
1565 	kb_add(x_mv_end,		CTRL('['), '[', '8', '~', 0); /* end */
1566 
1567 	/* can't be bound */
1568 	kb_add(x_set_arg,		CTRL('['), '0', 0);
1569 	kb_add(x_set_arg,		CTRL('['), '1', 0);
1570 	kb_add(x_set_arg,		CTRL('['), '2', 0);
1571 	kb_add(x_set_arg,		CTRL('['), '3', 0);
1572 	kb_add(x_set_arg,		CTRL('['), '4', 0);
1573 	kb_add(x_set_arg,		CTRL('['), '5', 0);
1574 	kb_add(x_set_arg,		CTRL('['), '6', 0);
1575 	kb_add(x_set_arg,		CTRL('['), '7', 0);
1576 	kb_add(x_set_arg,		CTRL('['), '8', 0);
1577 	kb_add(x_set_arg,		CTRL('['), '9', 0);
1578 
1579 	/* ctrl arrow keys */
1580 	kb_add(x_mv_end,		CTRL('['), '[', '1', ';', '5', 'A', 0); /* ctrl up */
1581 	kb_add(x_mv_begin,		CTRL('['), '[', '1', ';', '5', 'B', 0); /* ctrl down */
1582 	kb_add(x_mv_fword,		CTRL('['), '[', '1', ';', '5', 'C', 0); /* ctrl right */
1583 	kb_add(x_mv_bword,		CTRL('['), '[', '1', ';', '5', 'D', 0); /* ctrl left */
1584 }
1585 
1586 void
1587 x_emacs_keys(X_chars *ec)
1588 {
1589 	x_bind_quiet = 1;
1590 	if (ec->erase >= 0) {
1591 		kb_add(x_del_back, ec->erase, 0);
1592 		kb_add(x_del_bword, CTRL('['), ec->erase, 0);
1593 	}
1594 	if (ec->kill >= 0)
1595 		kb_add(x_del_line, ec->kill, 0);
1596 	if (ec->werase >= 0)
1597 		kb_add(x_del_bword, ec->werase, 0);
1598 	if (ec->intr >= 0)
1599 		kb_add(x_abort, ec->intr, 0);
1600 	if (ec->quit >= 0)
1601 		kb_add(x_noop, ec->quit, 0);
1602 	x_bind_quiet = 0;
1603 }
1604 
1605 static int
1606 x_set_mark(int c)
1607 {
1608 	xmp = xcp;
1609 	return KSTD;
1610 }
1611 
1612 static int
1613 x_kill_region(int c)
1614 {
1615 	int	rsize;
1616 	char	*xr;
1617 
1618 	if (xmp == NULL) {
1619 		x_e_putc(BEL);
1620 		return KSTD;
1621 	}
1622 	if (xmp > xcp) {
1623 		rsize = xmp - xcp;
1624 		xr = xcp;
1625 	} else {
1626 		rsize = xcp - xmp;
1627 		xr = xmp;
1628 	}
1629 	x_goto(xr);
1630 	x_delete(rsize, true);
1631 	xmp = xr;
1632 	return KSTD;
1633 }
1634 
1635 static int
1636 x_xchg_point_mark(int c)
1637 {
1638 	char	*tmp;
1639 
1640 	if (xmp == NULL) {
1641 		x_e_putc(BEL);
1642 		return KSTD;
1643 	}
1644 	tmp = xmp;
1645 	xmp = xcp;
1646 	x_goto( tmp );
1647 	return KSTD;
1648 }
1649 
1650 static int
1651 x_noop(int c)
1652 {
1653 	return KSTD;
1654 }
1655 
1656 /*
1657  *	File/command name completion routines
1658  */
1659 
1660 static int
1661 x_comp_comm(int c)
1662 {
1663 	do_complete(XCF_COMMAND, CT_COMPLETE);
1664 	return KSTD;
1665 }
1666 static int
1667 x_list_comm(int c)
1668 {
1669 	do_complete(XCF_COMMAND, CT_LIST);
1670 	return KSTD;
1671 }
1672 static int
1673 x_complete(int c)
1674 {
1675 	do_complete(XCF_COMMAND_FILE, CT_COMPLETE);
1676 	return KSTD;
1677 }
1678 static int
1679 x_enumerate(int c)
1680 {
1681 	do_complete(XCF_COMMAND_FILE, CT_LIST);
1682 	return KSTD;
1683 }
1684 static int
1685 x_comp_file(int c)
1686 {
1687 	do_complete(XCF_FILE, CT_COMPLETE);
1688 	return KSTD;
1689 }
1690 static int
1691 x_list_file(int c)
1692 {
1693 	do_complete(XCF_FILE, CT_LIST);
1694 	return KSTD;
1695 }
1696 static int
1697 x_comp_list(int c)
1698 {
1699 	do_complete(XCF_COMMAND_FILE, CT_COMPLIST);
1700 	return KSTD;
1701 }
1702 static int
1703 x_expand(int c)
1704 {
1705 	char **words;
1706 	int nwords = 0;
1707 	int start, end;
1708 	int is_command;
1709 	int i;
1710 
1711 	nwords = x_cf_glob(XCF_FILE, xbuf, xep - xbuf, xcp - xbuf,
1712 	    &start, &end, &words, &is_command);
1713 
1714 	if (nwords == 0) {
1715 		x_e_putc(BEL);
1716 		return KSTD;
1717 	}
1718 
1719 	x_goto(xbuf + start);
1720 	x_delete(end - start, false);
1721 	for (i = 0; i < nwords;) {
1722 		if (x_escape(words[i], strlen(words[i]), x_do_ins) < 0 ||
1723 		    (++i < nwords && x_ins(" ") < 0)) {
1724 			x_e_putc(BEL);
1725 			return KSTD;
1726 		}
1727 	}
1728 	x_adjust();
1729 
1730 	return KSTD;
1731 }
1732 
1733 /* type == 0 for list, 1 for complete and 2 for complete-list */
1734 static void
1735 do_complete(int flags,	/* XCF_{COMMAND,FILE,COMMAND_FILE} */
1736     Comp_type type)
1737 {
1738 	char **words;
1739 	int nwords;
1740 	int start, end, nlen, olen;
1741 	int is_command;
1742 	int completed = 0;
1743 
1744 	nwords = x_cf_glob(flags, xbuf, xep - xbuf, xcp - xbuf,
1745 	    &start, &end, &words, &is_command);
1746 	/* no match */
1747 	if (nwords == 0) {
1748 		x_e_putc(BEL);
1749 		return;
1750 	}
1751 
1752 	if (type == CT_LIST) {
1753 		x_print_expansions(nwords, words, is_command);
1754 		x_redraw(0);
1755 		x_free_words(nwords, words);
1756 		return;
1757 	}
1758 
1759 	olen = end - start;
1760 	nlen = x_longest_prefix(nwords, words);
1761 	/* complete */
1762 	if (nwords == 1 || nlen > olen) {
1763 		x_goto(xbuf + start);
1764 		x_delete(olen, false);
1765 		x_escape(words[0], nlen, x_do_ins);
1766 		x_adjust();
1767 		completed = 1;
1768 	}
1769 	/* add space if single non-dir match */
1770 	if (nwords == 1 && words[0][nlen - 1] != '/') {
1771 		x_ins(" ");
1772 		completed = 1;
1773 	}
1774 
1775 	if (type == CT_COMPLIST && !completed) {
1776 		x_print_expansions(nwords, words, is_command);
1777 		completed = 1;
1778 	}
1779 
1780 	if (completed)
1781 		x_redraw(0);
1782 
1783 	x_free_words(nwords, words);
1784 }
1785 
1786 /* NAME:
1787  *      x_adjust - redraw the line adjusting starting point etc.
1788  *
1789  * DESCRIPTION:
1790  *      This function is called when we have exceeded the bounds
1791  *      of the edit window.  It increments x_adj_done so that
1792  *      functions like x_ins and x_delete know that we have been
1793  *      called and can skip the x_bs() stuff which has already
1794  *      been done by x_redraw.
1795  *
1796  * RETURN VALUE:
1797  *      None
1798  */
1799 
1800 static void
1801 x_adjust(void)
1802 {
1803 	x_adj_done++;			/* flag the fact that we were called. */
1804 	/*
1805 	 * we had a problem if the prompt length > xx_cols / 2
1806 	 */
1807 	if ((xbp = xcp - (x_displen / 2)) < xbuf)
1808 		xbp = xbuf;
1809 	xlp_valid = false;
1810 	x_redraw(xx_cols);
1811 	x_flush();
1812 }
1813 
1814 static int unget_char = -1;
1815 
1816 static void
1817 x_e_ungetc(int c)
1818 {
1819 	unget_char = c;
1820 }
1821 
1822 static int
1823 x_e_getc(void)
1824 {
1825 	int c;
1826 
1827 	if (unget_char >= 0) {
1828 		c = unget_char;
1829 		unget_char = -1;
1830 	} else if (macro_args) {
1831 		c = *macro_args++;
1832 		if (!c) {
1833 			macro_args = NULL;
1834 			c = x_getc();
1835 		}
1836 	} else
1837 		c = x_getc();
1838 
1839 	return c;
1840 }
1841 
1842 static int
1843 x_e_getu8(char *buf, int off)
1844 {
1845 	int	c, cc, len;
1846 
1847 	c = x_e_getc();
1848 	if (c == -1)
1849 		return -1;
1850 	buf[off++] = c;
1851 
1852 	if (c == 0xf4)
1853 		len = 4;
1854 	else if ((c & 0xf0) == 0xe0)
1855 		len = 3;
1856 	else if ((c & 0xe0) == 0xc0 && c > 0xc1)
1857 		len = 2;
1858 	else
1859 		len = 1;
1860 
1861 	for (; len > 1; len--) {
1862 		cc = x_e_getc();
1863 		if (cc == -1)
1864 			break;
1865 		if (isu8cont(cc) == 0 ||
1866 		    (c == 0xe0 && len == 3 && cc < 0xa0) ||
1867 		    (c == 0xed && len == 3 && cc & 0x20) ||
1868 		    (c == 0xf4 && len == 4 && cc & 0x30)) {
1869 			x_e_ungetc(cc);
1870 			break;
1871 		}
1872 		buf[off++] = cc;
1873 	}
1874 	buf[off] = '\0';
1875 
1876 	return off;
1877 }
1878 
1879 static void
1880 x_e_putc(int c)
1881 {
1882 	if (c == '\r' || c == '\n')
1883 		x_col = 0;
1884 	if (x_col < xx_cols) {
1885 		x_putc(c);
1886 		switch (c) {
1887 		case BEL:
1888 			break;
1889 		case '\r':
1890 		case '\n':
1891 			break;
1892 		case '\b':
1893 			x_col--;
1894 			break;
1895 		default:
1896 			if (!isu8cont(c))
1897 				x_col++;
1898 			break;
1899 		}
1900 	}
1901 	if (x_adj_ok && (x_col < 0 || x_col >= (xx_cols - 2)))
1902 		x_adjust();
1903 }
1904 
1905 #ifdef DEBUG
1906 static int
1907 x_debug_info(int c)
1908 {
1909 	x_flush();
1910 	shellf("\nksh debug:\n");
1911 	shellf("\tx_col == %d,\t\tx_cols == %d,\tx_displen == %d\n",
1912 	    x_col, xx_cols, x_displen);
1913 	shellf("\txcp == 0x%lx,\txep == 0x%lx\n", (long) xcp, (long) xep);
1914 	shellf("\txbp == 0x%lx,\txbuf == 0x%lx\n", (long) xbp, (long) xbuf);
1915 	shellf("\txlp == 0x%lx\n", (long) xlp);
1916 	shellf("\txlp == 0x%lx\n", (long) x_lastcp());
1917 	shellf("\n");
1918 	x_redraw(-1);
1919 	return 0;
1920 }
1921 #endif
1922 
1923 static void
1924 x_e_puts(const char *s)
1925 {
1926 	int	adj = x_adj_done;
1927 
1928 	while (*s && adj == x_adj_done)
1929 		x_e_putc(*s++);
1930 }
1931 
1932 /* NAME:
1933  *      x_set_arg - set an arg value for next function
1934  *
1935  * DESCRIPTION:
1936  *      This is a simple implementation of M-[0-9].
1937  *
1938  * RETURN VALUE:
1939  *      KSTD
1940  */
1941 
1942 static int
1943 x_set_arg(int c)
1944 {
1945 	int n = 0;
1946 	int first = 1;
1947 
1948 	for (; c >= 0 && isdigit(c); c = x_e_getc(), first = 0)
1949 		n = n * 10 + (c - '0');
1950 	if (c < 0 || first) {
1951 		x_e_putc(BEL);
1952 		x_arg = 1;
1953 		x_arg_defaulted = 1;
1954 	} else {
1955 		x_e_ungetc(c);
1956 		x_arg = n;
1957 		x_arg_defaulted = 0;
1958 		x_arg_set = 1;
1959 	}
1960 	return KSTD;
1961 }
1962 
1963 
1964 /* Comment or uncomment the current line. */
1965 static int
1966 x_comment(int c)
1967 {
1968 	int oldsize = x_size_str(xbuf);
1969 	int len = xep - xbuf;
1970 	int ret = x_do_comment(xbuf, xend - xbuf, &len);
1971 
1972 	if (ret < 0)
1973 		x_e_putc(BEL);
1974 	else {
1975 		xep = xbuf + len;
1976 		*xep = '\0';
1977 		xcp = xbp = xbuf;
1978 		x_redraw(oldsize);
1979 		if (ret > 0)
1980 			return x_newline('\n');
1981 	}
1982 	return KSTD;
1983 }
1984 
1985 
1986 /* NAME:
1987  *      x_prev_histword - recover word from prev command
1988  *
1989  * DESCRIPTION:
1990  *      This function recovers the last word from the previous
1991  *      command and inserts it into the current edit line.  If a
1992  *      numeric arg is supplied then the n'th word from the
1993  *      start of the previous command is used.
1994  *
1995  *      Bound to M-.
1996  *
1997  * RETURN VALUE:
1998  *      KSTD
1999  */
2000 
2001 static int
2002 x_prev_histword(int c)
2003 {
2004 	char *rcp;
2005 	char *cp;
2006 
2007 	cp = *histptr;
2008 	if (!cp)
2009 		x_e_putc(BEL);
2010 	else if (x_arg_defaulted) {
2011 		rcp = &cp[strlen(cp) - 1];
2012 		/*
2013 		 * ignore white-space after the last word
2014 		 */
2015 		while (rcp > cp && is_cfs(*rcp))
2016 			rcp--;
2017 		while (rcp > cp && !is_cfs(*rcp))
2018 			rcp--;
2019 		if (is_cfs(*rcp))
2020 			rcp++;
2021 		x_ins(rcp);
2022 	} else {
2023 		rcp = cp;
2024 		/*
2025 		 * ignore white-space at start of line
2026 		 */
2027 		while (*rcp && is_cfs(*rcp))
2028 			rcp++;
2029 		while (x_arg-- > 1) {
2030 			while (*rcp && !is_cfs(*rcp))
2031 				rcp++;
2032 			while (*rcp && is_cfs(*rcp))
2033 				rcp++;
2034 		}
2035 		cp = rcp;
2036 		while (*rcp && !is_cfs(*rcp))
2037 			rcp++;
2038 		c = *rcp;
2039 		*rcp = '\0';
2040 		x_ins(cp);
2041 		*rcp = c;
2042 	}
2043 	return KSTD;
2044 }
2045 
2046 /* Uppercase N(1) words */
2047 static int
2048 x_fold_upper(int c)
2049 {
2050 	return x_fold_case('U');
2051 }
2052 
2053 /* Lowercase N(1) words */
2054 static int
2055 x_fold_lower(int c)
2056 {
2057 	return x_fold_case('L');
2058 }
2059 
2060 /* Lowercase N(1) words */
2061 static int
2062 x_fold_capitalize(int c)
2063 {
2064 	return x_fold_case('C');
2065 }
2066 
2067 /* NAME:
2068  *      x_fold_case - convert word to UPPER/lower/Capital case
2069  *
2070  * DESCRIPTION:
2071  *      This function is used to implement M-U,M-u,M-L,M-l,M-C and M-c
2072  *      to UPPER case, lower case or Capitalize words.
2073  *
2074  * RETURN VALUE:
2075  *      None
2076  */
2077 
2078 static int
2079 x_fold_case(int c)
2080 {
2081 	char *cp = xcp;
2082 
2083 	if (cp == xep) {
2084 		x_e_putc(BEL);
2085 		return KSTD;
2086 	}
2087 	while (x_arg--) {
2088 		/*
2089 		 * first skip over any white-space
2090 		 */
2091 		while (cp != xep && is_mfs(*cp))
2092 			cp++;
2093 		/*
2094 		 * do the first char on its own since it may be
2095 		 * a different action than for the rest.
2096 		 */
2097 		if (cp != xep) {
2098 			if (c == 'L') {		/* lowercase */
2099 				if (isupper((unsigned char)*cp))
2100 					*cp = tolower((unsigned char)*cp);
2101 			} else {		/* uppercase, capitalize */
2102 				if (islower((unsigned char)*cp))
2103 					*cp = toupper((unsigned char)*cp);
2104 			}
2105 			cp++;
2106 		}
2107 		/*
2108 		 * now for the rest of the word
2109 		 */
2110 		while (cp != xep && !is_mfs(*cp)) {
2111 			if (c == 'U') {		/* uppercase */
2112 				if (islower((unsigned char)*cp))
2113 					*cp = toupper((unsigned char)*cp);
2114 			} else {		/* lowercase, capitalize */
2115 				if (isupper((unsigned char)*cp))
2116 					*cp = tolower((unsigned char)*cp);
2117 			}
2118 			cp++;
2119 		}
2120 	}
2121 	x_goto(cp);
2122 	return KSTD;
2123 }
2124 
2125 /* NAME:
2126  *      x_lastcp - last visible byte
2127  *
2128  * SYNOPSIS:
2129  *      x_lastcp()
2130  *
2131  * DESCRIPTION:
2132  *      This function returns a pointer to that byte in the
2133  *      edit buffer that will be the last displayed on the
2134  *      screen.  The sequence:
2135  *
2136  *      for (cp = x_lastcp(); cp > xcp; cp)
2137  *        x_bs(*--cp);
2138  *
2139  *      Will position the cursor correctly on the screen.
2140  *
2141  * RETURN VALUE:
2142  *      cp or NULL
2143  */
2144 
2145 static char *
2146 x_lastcp(void)
2147 {
2148 	char *rcp;
2149 	int i;
2150 
2151 	if (!xlp_valid) {
2152 		for (i = 0, rcp = xbp; rcp < xep && i < x_displen; rcp++)
2153 			i += x_size((unsigned char)*rcp);
2154 		xlp = rcp;
2155 	}
2156 	xlp_valid = true;
2157 	return (xlp);
2158 }
2159 
2160 #endif /* EMACS */
2161