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