OSDN Git Service

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