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