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 $ */
7 * Copyright (c) 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010,
8 * 2011, 2012, 2013, 2014, 2015, 2016, 2017
9 * mirabilos <m@mirbsd.org>
11 * Provided that these terms and disclaimer and all copyright notices
12 * are retained or reproduced in an accompanying document, permission
13 * is granted to deal in this work without restriction, including un-
14 * limited rights to use, publicly perform, distribute, sell, modify,
15 * merge, give away, or sublicence.
17 * This work is provided "AS IS" and WITHOUT WARRANTY of any kind, to
18 * the utmost extent permitted by applicable law, neither express nor
19 * implied; without malicious intent or gross negligence. In no event
20 * may a licensor, author or contributor be held liable for indirect,
21 * direct, other damage, loss, or other issues arising in any way out
22 * of dealing in the work, even if advised of the possibility of such
23 * damage or existence of a defect, except proven that it results out
24 * of said person's immediate fault when using the work as intended.
29 #ifndef MKSH_NO_CMDLINE_EDITING
31 __RCSID("$MirOS: src/bin/mksh/edit.c,v 1.321 2017/04/12 16:46:20 tg Exp $");
34 * in later versions we might use libtermcap for this, but since external
35 * dependencies are problematic, this has not yet been decided on; another
36 * good string is "\033c" except on hardware terminals like the DEC VT420
37 * which do a full power cycle then...
39 #ifndef MKSH_CLS_STRING
40 #define MKSH_CLS_STRING "\033[;H\033[J"
43 /* tty driver characters we are interested in */
44 #define EDCHAR_DISABLED 0xFFFFU
45 #define EDCHAR_INITIAL 0xFFFEU
49 unsigned short werase;
55 #define isched(x,e) ((unsigned short)(unsigned char)(x) == (e))
56 #define isedchar(x) (!((x) & ~0xFF))
57 #ifndef _POSIX_VDISABLE
58 #define toedchar(x) ((unsigned short)(unsigned char)(x))
60 #define toedchar(x) (((_POSIX_VDISABLE != -1) && ((x) == _POSIX_VDISABLE)) ? \
61 ((unsigned short)EDCHAR_DISABLED) : \
62 ((unsigned short)(unsigned char)(x)))
65 /* x_cf_glob() flags */
66 #define XCF_COMMAND BIT(0) /* Do command completion */
67 #define XCF_FILE BIT(1) /* Do file completion */
68 #define XCF_FULLPATH BIT(2) /* command completion: store full path */
69 #define XCF_COMMAND_FILE (XCF_COMMAND | XCF_FILE)
70 #define XCF_IS_COMMAND BIT(3) /* return flag: is command */
71 #define XCF_IS_NOSPACE BIT(4) /* return flag: do not append a space */
74 static int xx_cols; /* for Emacs mode */
75 static int modified; /* buffer has been "modified" */
76 static char *holdbufp; /* place to hold last edit buffer */
78 /* 0=dumb 1=tmux (for now) */
79 static bool x_term_mode;
81 static void x_adjust(void);
82 static int x_getc(void);
83 static void x_putcf(int);
84 static void x_modified(void);
85 static void x_mode(bool);
86 static int x_do_comment(char *, ssize_t, ssize_t *);
87 static void x_print_expansions(int, char * const *, bool);
88 static int x_cf_glob(int *, const char *, int, int, int *, int *, char ***);
89 static size_t x_longest_prefix(int, char * const *);
90 static void x_glob_hlp_add_qchar(char *);
91 static char *x_glob_hlp_tilde_and_rem_qchar(char *, bool);
92 static size_t x_basename(const char *, const char *);
93 static void x_free_words(int, char **);
94 static int x_escape(const char *, size_t, int (*)(const char *, size_t));
95 static int x_emacs(char *);
96 static void x_init_prompt(bool);
98 static int x_vi(char *);
101 #define x_flush() shf_flush(shl_out)
102 #if defined(MKSH_SMALL) && !defined(MKSH_SMALL_BUT_FAST)
103 #define x_putc(c) x_putcf(c)
105 #define x_putc(c) shf_putc((c), shl_out)
108 static int path_order_cmp(const void *, const void *);
109 static void glob_table(const char *, XPtrV *, struct table *);
110 static void glob_path(int, const char *, XPtrV *, const char *);
111 static int x_file_glob(int *, char *, char ***);
112 static int x_command_glob(int, char *, char ***);
113 static int x_locate_word(const char *, int, int, int *, bool *);
115 static int x_e_getmbc(char *);
117 /* +++ generic editing functions +++ */
120 * read an edited command line
129 if (Flag(FEMACS) || Flag(FGMACS))
149 return (_read_kbd(0, 1, 0));
154 while ((n = blocking_read(STDIN_FILENO, &c, 1)) < 0 && errno == EINTR)
161 if (x_cols != xx_cols && editmode == 1) {
162 /* redraw line in Emacs mode */
164 x_init_prompt(false);
171 return ((n == 1) ? (int)(unsigned char)c : -1);
178 shf_putc(c, shl_out);
181 /*********************************
182 * Misc common code for vi/emacs *
183 *********************************/
186 * Handle the commenting/uncommenting of a line.
188 * 1 if a carriage return is indicated (comment added)
189 * 0 if no return (comment removed)
190 * -1 if there is an error (not enough room for comment chars)
191 * If successful, *lenp contains the new length. Note: cursor should be
192 * moved to the start of the line after (un)commenting.
195 x_do_comment(char *buf, ssize_t bsize, ssize_t *lenp)
197 ssize_t i, j, len = *lenp;
200 /* somewhat arbitrary - it's what AT&T ksh does */
203 /* Already commented? */
207 for (j = 0, i = 1; i < len; i++) {
208 if (!saw_nl || buf[i] != '#')
210 saw_nl = buf[i] == '\n';
217 /* See if there's room for the #s - 1 per \n */
218 for (i = 0; i < len; i++)
221 if (len + n >= bsize)
223 /* Now add them... */
224 for (i = len, j = len + n; --i >= 0; ) {
235 /****************************************************
236 * Common file/command completion code for vi/emacs *
237 ****************************************************/
240 x_print_expansions(int nwords, char * const *words, bool is_command)
242 bool use_copy = false;
244 XPtrV l = { NULL, 0, 0 };
245 struct columnise_opts co;
248 * Check if all matches are in the same directory (in this
249 * case, we want to omit the directory name)
252 (prefix_len = x_longest_prefix(nwords, words)) > 0) {
255 /* Special case for 1 match (prefix is whole word) */
257 prefix_len = x_basename(words[0], NULL);
258 /* Any (non-trailing) slashes in non-common word suffixes? */
259 for (i = 0; i < nwords; i++)
260 if (x_basename(words[i] + prefix_len, NULL) >
263 /* All in same directory? */
265 while (prefix_len > 0 &&
266 !mksh_cdirsep(words[0][prefix_len - 1]))
269 XPinit(l, nwords + 1);
270 for (i = 0; i < nwords; i++)
271 XPput(l, words[i] + prefix_len);
276 * Enumerate expansions
284 pr_list(&co, use_copy ? (char **)XPptrv(l) : words);
287 /* not x_free_words() */
292 * Convert backslash-escaped string to QCHAR-escaped
293 * string useful for globbing; loses QCHAR unless it
294 * can squeeze in, eg. by previous loss of backslash
297 x_glob_hlp_add_qchar(char *cp)
300 bool escaping = false;
302 while ((ch = *cp++)) {
303 if (ch == '\\' && !escaping) {
307 if (escaping || (ch == QCHAR && (cp - dp) > 1)) {
309 * empirically made list of chars to escape
310 * for globbing as well as QCHAR itself
331 * Run tilde expansion on argument string, return the result
332 * after unescaping; if the flag is set, the original string
333 * is freed if changed and assumed backslash-escaped, if not
334 * it is assumed QCHAR-escaped
337 x_glob_hlp_tilde_and_rem_qchar(char *s, bool magic_flag)
342 * On the string, check whether we have a tilde expansion,
343 * and if so, discern "~foo/bar" and "~/baz" from "~blah";
344 * if we have a directory part (the former), try to expand
346 if (*s == '~' && (cp = /* not sdirsep */ strchr(s, '/')) != NULL) {
347 /* ok, so split into "~foo"/"bar" or "~"/"baz" */
349 /* try to expand the tilde */
350 if (!(dp = do_tilde(s + 1))) {
351 /* nope, revert damage */
354 /* ok, expand and replace */
355 cp = shf_smprintf(Tf_sSs, dp, cp);
362 /* ... convert it from backslash-escaped via QCHAR-escaped... */
364 x_glob_hlp_add_qchar(s);
365 /* ... to unescaped, for comparison with the matches */
368 while ((ch = *cp++)) {
369 if (ch == QCHAR && !(ch = *cp++))
380 * - does expansion, checks for no match, etc.
381 * - sets *wordsp to array of matching strings
382 * - returns number of matching strings
385 x_file_glob(int *flagsp, char *toglob, char ***wordsp)
390 struct source *s, *sold;
392 /* remove all escaping backward slashes */
393 x_glob_hlp_add_qchar(toglob);
396 * Convert "foo*" (toglob) to an array of strings (words)
399 s = pushs(SWSTR, ATEMP);
400 s->start = s->str = toglob;
402 if (yylex(ONEWORD | LQCHAR) != LWORD) {
404 internal_warningf(Tfg_badsubst);
411 while (*cp == CHAR || *cp == QCHAR)
413 nwords = DOGLOB | DOTILDE | DOMARKDIRS;
415 /* probably a $FOO expansion */
416 *flagsp |= XCF_IS_NOSPACE;
417 /* this always results in at most one match */
420 expand(yylval.cp, &w, nwords);
422 words = (char **)XPclose(w);
424 for (nwords = 0; words[nwords]; nwords++)
429 /* Expand any tilde and drop all QCHAR for comparison */
430 toglob = x_glob_hlp_tilde_and_rem_qchar(toglob, false);
433 * Check if globbing failed (returned glob pattern),
434 * but be careful (e.g. toglob == "ab*" when the file
435 * "ab*" exists is not an error).
436 * Also, check for empty result - happens if we tried
437 * to glob something which evaluated to an empty
438 * string (e.g., "$FOO" when there is no FOO, etc).
440 if ((strcmp(words[0], toglob) == 0 &&
441 stat(words[0], &statb) < 0) ||
442 words[0][0] == '\0') {
443 x_free_words(nwords, words);
449 if ((*wordsp = nwords ? words : NULL) == NULL && words != NULL)
450 x_free_words(nwords, words);
455 /* Data structure used in x_command_glob() */
456 struct path_order_info {
462 /* Compare routine used in x_command_glob() */
464 path_order_cmp(const void *aa, const void *bb)
466 const struct path_order_info *a = (const struct path_order_info *)aa;
467 const struct path_order_info *b = (const struct path_order_info *)bb;
470 if ((t = strcmp(a->word + a->base, b->word + b->base)))
472 if (a->path_order > b->path_order)
474 if (a->path_order < b->path_order)
480 x_command_glob(int flags, char *toglob, char ***wordsp)
487 /* Convert "foo*" (toglob) to a pattern for future use */
488 pat = evalstr(toglob, DOPAT | DOTILDE);
492 glob_table(pat, &w, &keywords);
493 glob_table(pat, &w, &aliases);
494 glob_table(pat, &w, &builtins);
495 for (l = e->loc; l; l = l->next)
496 glob_table(pat, &w, &l->funs);
498 glob_path(flags, pat, &w, path);
499 if ((fpath = str_val(global(TFPATH))) != null)
500 glob_path(flags, pat, &w, fpath);
510 if (flags & XCF_FULLPATH) {
511 /* Sort by basename, then path order */
512 struct path_order_info *info, *last_info = NULL;
513 char **words = (char **)XPptrv(w);
514 size_t i, path_order = 0;
516 info = (struct path_order_info *)
517 alloc2(nwords, sizeof(struct path_order_info), ATEMP);
518 for (i = 0; i < nwords; i++) {
519 info[i].word = words[i];
520 info[i].base = x_basename(words[i], NULL);
521 if (!last_info || info[i].base != last_info->base ||
522 strncmp(words[i], last_info->word, info[i].base) != 0) {
523 last_info = &info[i];
526 info[i].path_order = path_order;
528 qsort(info, nwords, sizeof(struct path_order_info),
530 for (i = 0; i < nwords; i++)
531 words[i] = info[i].word;
534 /* Sort and remove duplicate entries */
535 char **words = (char **)XPptrv(w);
538 qsort(words, nwords, sizeof(void *), xstrcmp);
539 for (i = j = 0; i < nwords - 1; i++) {
540 if (strcmp(words[i], words[i + 1]))
541 words[j++] = words[i];
543 afree(words[i], ATEMP);
545 words[j++] = words[i];
550 *wordsp = (char **)XPclose(w);
555 #define IS_WORDC(c) (!ctype(c, C_LEX1) && (c) != '\'' && (c) != '"' && \
556 (c) != '`' && (c) != '=' && (c) != ':')
559 x_locate_word(const char *buf, int buflen, int pos, int *startp,
564 /* Bad call? Probably should report error */
565 if (pos < 0 || pos > buflen) {
567 *is_commandp = false;
570 /* The case where pos == buflen happens to take care of itself... */
574 * Keep going backwards to start of word (has effect of allowing
575 * one blank after the end of a word)
577 for (; (start > 0 && IS_WORDC(buf[start - 1])) ||
578 (start > 1 && buf[start - 2] == '\\'); start--)
580 /* Go forwards to end of word */
581 for (end = start; end < buflen && IS_WORDC(buf[end]); end++) {
582 if (buf[end] == '\\' && (end + 1) < buflen)
590 /* Figure out if this is a command */
591 while (p >= 0 && ksh_isspace(buf[p]))
593 iscmd = p < 0 || vstrchr(";|&()`", buf[p]);
596 * If command has a /, path, etc. is not searched;
597 * only current directory is searched which is just
598 * like file globbing.
600 for (p = start; p < end; p++)
601 if (mksh_cdirsep(buf[p]))
605 *is_commandp = iscmd;
609 return (end - start);
613 x_cf_glob(int *flagsp, const char *buf, int buflen, int pos, int *startp,
614 int *endp, char ***wordsp)
620 len = x_locate_word(buf, buflen, pos, startp, &is_command);
621 if (!((*flagsp) & XCF_COMMAND))
624 * Don't do command globing on zero length strings - it takes too
625 * long and isn't very useful. File globs are more likely to be
626 * useful, so allow these.
628 if (len == 0 && is_command)
635 * Given a string, copy it and possibly add a '*' to the end.
638 strndupx(toglob, buf + *startp, len + /* the '*' */ 1, ATEMP);
642 * If the pathname contains a wildcard (an unquoted '*',
643 * '?', or '[') or an extglob, then it is globbed based
644 * on that value (i.e., without the appended '*'). Same
645 * for parameter substitutions (as in “cat $HOME/.ss↹”)
646 * without appending a trailing space (LP: #710539), as
647 * well as for “~foo” (but not “~foo/”).
649 for (s = toglob; *s; s++) {
650 if (*s == '\\' && s[1])
652 else if (*s == '?' || *s == '*' || *s == '[' ||
654 /* ?() *() +() @() !() but two already checked */
655 (s[1] == '(' /*)*/ &&
656 (*s == '+' || *s == '@' || *s == '!'))) {
658 * just expand based on the extglob
665 if (*toglob == '~' && /* not vdirsep */ !vstrchr(toglob, '/')) {
666 /* neither for '~foo' (but '~foo/bar') */
667 *flagsp |= XCF_IS_NOSPACE;
673 toglob[len + 1] = '\0';
676 * Expand (glob) it now.
679 nwords = is_command ?
680 x_command_glob(*flagsp, toglob, &words) :
681 x_file_glob(flagsp, toglob, &words);
682 afree(toglob, ATEMP);
689 *flagsp |= XCF_IS_COMMAND;
691 *endp = *startp + len;
697 * Find longest common prefix
700 x_longest_prefix(int nwords, char * const * words)
703 size_t j, prefix_len;
709 prefix_len = strlen(words[0]);
710 for (i = 1; i < nwords; i++)
711 for (j = 0, p = words[i]; j < prefix_len; j++)
712 if (p[j] != words[0][j]) {
716 /* false for nwords==1 as 0 = words[0][prefix_len] then */
717 if (UTFMODE && prefix_len && (words[0][prefix_len] & 0xC0) == 0x80)
718 while (prefix_len && (words[0][prefix_len] & 0xC0) != 0xC0)
724 x_free_words(int nwords, char **words)
727 afree(words[--nwords], ATEMP);
732 * Return the offset of the basename of string s (which ends at se - need not
733 * be null terminated). Trailing slashes are ignored. If s is just a slash,
734 * then the offset is 0 (actually, length - 1).
745 x_basename(const char *s, const char *se)
754 /* skip trailing directory separators */
756 while (p > s && mksh_cdirsep(*p))
758 /* drop last component */
759 while (p > s && !mksh_cdirsep(*p))
761 if (mksh_cdirsep(*p) && p + 1 < se)
768 * Apply pattern matching to a table: all table entries that match a pattern
772 glob_table(const char *pat, XPtrV *wp, struct table *tp)
778 while ((te = ktnext(&ts)))
779 if (gmatchx(te->name, pat, false)) {
782 strdupx(cp, te->name, ATEMP);
788 glob_path(int flags, const char *pat, XPtrV *wp, const char *lpath)
790 const char *sp = lpath, *p;
792 size_t pathlen, patlen, oldsize, newsize, i, j;
795 patlen = strlen(pat);
796 checkoktoadd(patlen, 129 + X_EXTRA);
798 Xinit(xs, xp, patlen + 128, ATEMP);
800 xp = Xstring(xs, xp);
801 if (!(p = cstrchr(sp, MKSH_PATHSEPC)))
806 * Copy sp into xp, stuffing any MAGIC characters
811 XcheckN(xs, xp, pathlen * 2);
821 XcheckN(xs, xp, patlen);
822 memcpy(xp, pat, patlen);
824 oldsize = XPsize(*wp);
826 glob_str(Xstring(xs, xp), wp, true);
827 newsize = XPsize(*wp);
829 /* Check that each match is executable... */
830 words = (char **)XPptrv(*wp);
831 for (i = j = oldsize; i < newsize; i++) {
832 if (ksh_access(words[i], X_OK) == 0) {
834 if (!(flags & XCF_FULLPATH))
835 memmove(words[j], words[j] + pathlen,
836 strlen(words[j] + pathlen) + 1);
839 afree(words[i], ATEMP);
850 * if argument string contains any special characters, they will
851 * be escaped and the result will be put into edit buffer by
852 * keybinding-specific function
855 x_escape(const char *s, size_t len, int (*putbuf_func)(const char *, size_t))
857 size_t add = 0, wlen = len;
860 while (wlen - add > 0)
861 if (vstrchr("\"#$&'()*:;<=>?[\\`{|}", s[add]) ||
862 ctype(s[add], C_IFS)) {
863 if (putbuf_func(s, add) != 0) {
867 putbuf_func(s[add] == '\n' ? "'" : "\\", 1);
868 putbuf_func(&s[add], 1);
878 if (wlen > 0 && rval == 0)
879 rval = putbuf_func(s, wlen);
885 /* +++ emacs editing mode +++ */
888 #define AEDIT &aedit /* area for kill ring and macro defns */
890 /* values returned by keyboard functions */
892 #define KEOL 1 /* ^M, ^J */
893 #define KINTR 2 /* ^G, ^C */
896 int (*xf_func)(int c);
901 struct x_defbindings {
902 unsigned char xdb_func; /* XFUNC_* */
903 unsigned char xdb_tab;
904 unsigned char xdb_char;
907 #define XF_ARG 1 /* command takes number prefix */
908 #define XF_NOBIND 2 /* not allowed to bind to function */
909 #define XF_PREFIX 4 /* function sets prefix */
911 /* Separator for completion */
912 #define is_cfs(c) ((c) == ' ' || (c) == '\t' || (c) == '"' || (c) == '\'')
913 /* Separator for motion */
914 #define is_mfs(c) (!(ksh_isalnux(c) || (c) == '$' || ((c) & 0x80)))
916 #define X_NTABS 4 /* normal, meta1, meta2, pc */
917 #define X_TABSZ 256 /* size of keydef tables etc */
920 * Arguments for do_complete()
921 * 0 = enumerate M-= complete as much as possible and then list
926 CT_LIST, /* list the possible completions */
927 CT_COMPLETE, /* complete to longest prefix */
928 CT_COMPLIST /* complete and then list (if non-exact) */
932 * The following are used for my horizontal scrolling stuff
934 static char *xbuf; /* beg input buffer */
935 static char *xend; /* end input buffer */
936 static char *xcp; /* current position */
937 static char *xep; /* current end */
938 static char *xbp; /* start of visible portion of input buffer */
939 static char *xlp; /* last char visible on screen */
940 static bool x_adj_ok;
942 * we use x_adj_done so that functions can tell
943 * whether x_adjust() has been called while they are active.
945 static int x_adj_done; /* is incremented by x_adjust() */
947 static int x_displen;
948 static int x_arg; /* general purpose arg */
949 static bool x_arg_defaulted; /* x_arg not explicitly set; defaulted to 1 */
951 static bool xlp_valid; /* lastvis pointer was recalculated */
953 static char **x_histp; /* history position */
954 static int x_nextcmd; /* for newline-and-next */
955 static char **x_histncp; /* saved x_histp for " */
956 static char **x_histmcp; /* saved x_histp for " */
957 static char *xmp; /* mark pointer */
958 static unsigned char x_last_command;
959 static unsigned char (*x_tab)[X_TABSZ]; /* key definition */
961 static char *(*x_atab)[X_TABSZ]; /* macro definitions */
963 static unsigned char x_bound[(X_TABSZ * X_NTABS + 7) / 8];
965 static char *killstack[KILLSIZE];
966 static int killsp, killtp;
967 static int x_curprefix;
969 static char *macroptr; /* bind key macro active? */
972 static int winwidth; /* width of window */
973 static char *wbuf[2]; /* window buffers */
974 static int wbuf_len; /* length of window buffers (x_cols - 3) */
975 static int win; /* window buffer in use */
976 static char morec; /* more character at right of window */
977 static int lastref; /* argument to last refresh() */
978 static int holdlen; /* length of holdbuf */
980 static int pwidth; /* width of prompt */
981 static int prompt_trunc; /* how much of prompt to truncate or -1 */
982 static int x_col; /* current column on line */
984 static int x_ins(const char *);
985 static void x_delete(size_t, bool);
986 static size_t x_bword(void);
987 static size_t x_fword(bool);
988 static void x_goto(char *);
989 static char *x_bs0(char *, char *) MKSH_A_PURE;
990 static void x_bs3(char **);
991 static int x_size2(char *, char **);
992 static void x_zots(char *);
993 static void x_zotc3(char **);
994 static void x_load_hist(char **);
995 static int x_search(char *, int, int);
997 static int x_search_dir(int);
999 static int x_match(char *, char *);
1000 static void x_redraw(int);
1001 static void x_push(size_t);
1002 static char *x_mapin(const char *, Area *);
1003 static char *x_mapout(int);
1004 static void x_mapout2(int, char **);
1005 static void x_print(int, int);
1006 static void x_e_ungetc(int);
1007 static int x_e_getc(void);
1008 static void x_e_putc2(int);
1009 static void x_e_putc3(const char **);
1010 static void x_e_puts(const char *);
1012 static int x_fold_case(int);
1014 static char *x_lastcp(void);
1015 static void x_lastpos(void);
1016 static void do_complete(int, Comp_type);
1017 static size_t x_nb2nc(size_t) MKSH_A_PURE;
1019 static int unget_char = -1;
1021 static int x_do_ins(const char *, size_t);
1022 static void bind_if_not_bound(int, int, int);
1025 #define EMACSFN_ENUMS
1026 #include "emacsfn.h"
1030 #define EMACSFN_DEFNS
1031 #include "emacsfn.h"
1033 static const struct x_ftab x_ftab[] = {
1034 #define EMACSFN_ITEMS
1035 #include "emacsfn.h"
1038 static struct x_defbindings const x_defbindings[] = {
1039 { XFUNC_del_back, 0, CTRL('?') },
1040 { XFUNC_del_bword, 1, CTRL('?') },
1041 { XFUNC_eot_del, 0, CTRL('D') },
1042 { XFUNC_del_back, 0, CTRL('H') },
1043 { XFUNC_del_bword, 1, CTRL('H') },
1044 { XFUNC_del_bword, 1, 'h' },
1045 { XFUNC_mv_bword, 1, 'b' },
1046 { XFUNC_mv_fword, 1, 'f' },
1047 { XFUNC_del_fword, 1, 'd' },
1048 { XFUNC_mv_back, 0, CTRL('B') },
1049 { XFUNC_mv_forw, 0, CTRL('F') },
1050 { XFUNC_search_char_forw, 0, CTRL(']') },
1051 { XFUNC_search_char_back, 1, CTRL(']') },
1052 { XFUNC_newline, 0, CTRL('M') },
1053 { XFUNC_newline, 0, CTRL('J') },
1054 { XFUNC_end_of_text, 0, CTRL('_') },
1055 { XFUNC_abort, 0, CTRL('G') },
1056 { XFUNC_prev_com, 0, CTRL('P') },
1057 { XFUNC_next_com, 0, CTRL('N') },
1058 { XFUNC_nl_next_com, 0, CTRL('O') },
1059 { XFUNC_search_hist, 0, CTRL('R') },
1060 { XFUNC_beg_hist, 1, '<' },
1061 { XFUNC_end_hist, 1, '>' },
1062 { XFUNC_goto_hist, 1, 'g' },
1063 { XFUNC_mv_end, 0, CTRL('E') },
1064 { XFUNC_mv_beg, 0, CTRL('A') },
1065 { XFUNC_draw_line, 0, CTRL('L') },
1066 { XFUNC_cls, 1, CTRL('L') },
1067 { XFUNC_meta1, 0, CTRL('[') },
1068 { XFUNC_meta2, 0, CTRL('X') },
1069 { XFUNC_kill, 0, CTRL('K') },
1070 { XFUNC_yank, 0, CTRL('Y') },
1071 { XFUNC_meta_yank, 1, 'y' },
1072 { XFUNC_literal, 0, CTRL('^') },
1073 { XFUNC_comment, 1, '#' },
1074 { XFUNC_transpose, 0, CTRL('T') },
1075 { XFUNC_complete, 1, CTRL('[') },
1076 { XFUNC_comp_list, 0, CTRL('I') },
1077 { XFUNC_comp_list, 1, '=' },
1078 { XFUNC_enumerate, 1, '?' },
1079 { XFUNC_expand, 1, '*' },
1080 { XFUNC_comp_file, 1, CTRL('X') },
1081 { XFUNC_comp_comm, 2, CTRL('[') },
1082 { XFUNC_list_comm, 2, '?' },
1083 { XFUNC_list_file, 2, CTRL('Y') },
1084 { XFUNC_set_mark, 1, ' ' },
1085 { XFUNC_kill_region, 0, CTRL('W') },
1086 { XFUNC_xchg_point_mark, 2, CTRL('X') },
1087 { XFUNC_literal, 0, CTRL('V') },
1088 { XFUNC_version, 1, CTRL('V') },
1089 { XFUNC_prev_histword, 1, '.' },
1090 { XFUNC_prev_histword, 1, '_' },
1091 { XFUNC_set_arg, 1, '0' },
1092 { XFUNC_set_arg, 1, '1' },
1093 { XFUNC_set_arg, 1, '2' },
1094 { XFUNC_set_arg, 1, '3' },
1095 { XFUNC_set_arg, 1, '4' },
1096 { XFUNC_set_arg, 1, '5' },
1097 { XFUNC_set_arg, 1, '6' },
1098 { XFUNC_set_arg, 1, '7' },
1099 { XFUNC_set_arg, 1, '8' },
1100 { XFUNC_set_arg, 1, '9' },
1102 { XFUNC_fold_upper, 1, 'U' },
1103 { XFUNC_fold_upper, 1, 'u' },
1104 { XFUNC_fold_lower, 1, 'L' },
1105 { XFUNC_fold_lower, 1, 'l' },
1106 { XFUNC_fold_capitalise, 1, 'C' },
1107 { XFUNC_fold_capitalise, 1, 'c' },
1110 * These for ANSI arrow keys: arguablely shouldn't be here by
1111 * default, but its simpler/faster/smaller than using termcap
1114 { XFUNC_meta2, 1, '[' },
1115 { XFUNC_meta2, 1, 'O' },
1116 { XFUNC_prev_com, 2, 'A' },
1117 { XFUNC_next_com, 2, 'B' },
1118 { XFUNC_mv_forw, 2, 'C' },
1119 { XFUNC_mv_back, 2, 'D' },
1121 { XFUNC_vt_hack, 2, '1' },
1122 { XFUNC_mv_beg | 0x80, 2, '7' },
1123 { XFUNC_mv_beg, 2, 'H' },
1124 { XFUNC_mv_end | 0x80, 2, '4' },
1125 { XFUNC_mv_end | 0x80, 2, '8' },
1126 { XFUNC_mv_end, 2, 'F' },
1127 { XFUNC_del_char | 0x80, 2, '3' },
1128 { XFUNC_del_char, 2, 'P' },
1129 { XFUNC_search_hist_up | 0x80, 2, '5' },
1130 { XFUNC_search_hist_dn | 0x80, 2, '6' },
1133 #if !defined(MKSH_SMALL) || defined(__OS2__)
1134 { XFUNC_meta3, 0, 0 },
1135 { XFUNC_mv_beg, 3, 71 },
1136 { XFUNC_prev_com, 3, 72 },
1138 { XFUNC_search_hist_up, 3, 73 },
1140 { XFUNC_mv_back, 3, 75 },
1141 { XFUNC_mv_forw, 3, 77 },
1142 { XFUNC_mv_end, 3, 79 },
1143 { XFUNC_next_com, 3, 80 },
1145 { XFUNC_search_hist_dn, 3, 81 },
1147 { XFUNC_del_char, 3, 83 },
1150 /* more non-standard ones */
1151 { XFUNC_eval_region, 1, CTRL('E') },
1152 { XFUNC_edit_line, 2, 'e' }
1162 for (cp = xcp; cp < (xcp + nb); ++nc)
1163 cp += utf_ptradj(cp);
1171 x_histmcp = x_histp;
1172 x_histp = histptr + 1;
1178 #define XFUNC_VALUE(f) (f)
1180 #define XFUNC_VALUE(f) (f & 0x7F)
1184 x_e_getmbc(char *sbuf)
1187 unsigned char *buf = (unsigned char *)sbuf;
1190 buf[pos++] = c = x_e_getc();
1194 if ((buf[0] >= 0xC2) && (buf[0] < 0xF0)) {
1198 if ((c & 0xC0) != 0x80) {
1204 if ((buf[0] >= 0xE0) && (buf[0] < 0xF0)) {
1205 /* XXX x_e_ungetc is one-octet only */
1206 buf[pos++] = c = x_e_getc();
1215 * minimum required space to work with on a line - if the prompt
1216 * leaves less space than this on a line, the prompt is truncated
1218 #define MIN_EDIT_SPACE 7
1221 x_init_prompt(bool doprint)
1223 prompt_trunc = pprompt(prompt, doprint ? 0 : -1);
1224 pwidth = prompt_trunc % x_cols;
1225 prompt_trunc -= pwidth;
1226 if ((mksh_uari_t)pwidth > ((mksh_uari_t)x_cols - 3 - MIN_EDIT_SPACE)) {
1227 /* force newline after prompt */
1243 xlp = xcp = xep = buf;
1248 x_histmcp = x_histp = histptr + 1;
1249 x_last_command = XFUNC_error;
1251 x_init_prompt(true);
1252 x_displen = (xx_cols = x_cols) - 2 - (x_col = pwidth);
1257 if (x_nextcmd >= 0) {
1258 int off = source->line - x_nextcmd;
1259 if (histptr - history >= off) {
1260 x_load_hist(histptr - off);
1261 x_histncp = x_histp;
1266 while (/* CONSTCOND */ 1) {
1268 if ((c = x_e_getc()) < 0)
1271 f = x_curprefix == -1 ? XFUNC_insert :
1272 x_tab[x_curprefix][c];
1276 if ((i = x_e_getc()) != '~')
1280 /* avoid bind key macro recursion */
1281 if (macroptr && f == XFUNC_ins_string)
1285 if (!(x_ftab[f].xf_flags & XF_PREFIX) &&
1286 x_last_command != XFUNC_set_arg) {
1288 x_arg_defaulted = true;
1290 i = c | (x_curprefix << 8);
1292 switch ((*x_ftab[f].xf_func)(i)) {
1294 if (!(x_ftab[f].xf_flags & XF_PREFIX))
1301 /* special case for interrupt */
1306 /* ad-hoc hack for fixing the cursor position */
1314 static int left, pos, save_arg;
1318 * Should allow tab and control chars.
1327 if (((c & 0xC0) == 0x80) && left) {
1338 if (x_curprefix == -1) {
1339 /* flush invalid multibyte */
1345 if ((c >= 0xC2) && (c < 0xE0))
1347 else if ((c >= 0xE0) && (c < 0xF0))
1372 macroptr = x_atab[c >> 8][c & 255];
1374 * we no longer need to bother checking if macroptr is
1375 * not NULL but first char is NUL; x_e_getc() does it
1382 x_do_ins(const char *cp, size_t len)
1384 if (xep + len >= xend) {
1388 memmove(xcp + len, xcp, xep - xcp + 1);
1389 memmove(xcp, cp, len);
1397 x_ins(const char *s)
1400 int adj = x_adj_done;
1402 if (x_do_ins(s, strlen(s)) < 0)
1405 * x_zots() may result in a call to x_adjust()
1406 * we want xcp to reflect the new position.
1410 x_adj_ok = tobool(xcp >= xlp);
1412 if (adj == x_adj_done)
1413 /* x_adjust() has not been called */
1420 x_del_back(int c MKSH_A_UNUSED)
1430 } while ((++i < x_arg) && (xcp != xbuf));
1436 x_del_char(int c MKSH_A_UNUSED)
1442 while (i < (size_t)x_arg) {
1443 utf_ptradjx(cp, cp2);
1458 /* Delete nc chars to the right of the cursor (including cursor position) */
1460 x_delete(size_t nc, bool push)
1470 for (i = 0; i < nc; ++i) {
1474 j = x_size2(cp, &cp2);
1483 if (xmp != NULL && xmp > xcp) {
1490 * This lets us yank a word we have deleted.
1496 /* Copies the NUL */
1497 memmove(xcp, xcp + nb, xep - xcp + 1);
1503 * if we are already filling the line,
1504 * there is no need to ' ', '\b'.
1505 * But if we must, make sure we do the minimum.
1507 if ((i = xx_cols - 2 - x_col) > 0 || xep - xlp == 0) {
1508 nw = i = (nw < i) ? nw : i;
1511 if (x_col == xx_cols - 2) {
1512 x_e_putc2((xep > xlp) ? '>' : (xbp > xbuf) ? '<' : ' ');
1527 x_del_bword(int c MKSH_A_UNUSED)
1529 x_delete(x_bword(), true);
1534 x_mv_bword(int c MKSH_A_UNUSED)
1541 x_mv_fword(int c MKSH_A_UNUSED)
1548 x_del_fword(int c MKSH_A_UNUSED)
1550 x_delete(x_fword(false), true);
1565 while (cp != xbuf && is_mfs(cp[-1])) {
1569 while (cp != xbuf && !is_mfs(cp[-1])) {
1575 return (x_nb2nc(nb));
1589 while (cp != xep && is_mfs(*cp))
1591 while (cp != xep && !is_mfs(*cp))
1594 nc = x_nb2nc(cp - xcp);
1603 cp = cp >= xep ? xep : x_bs0(cp, xbuf);
1604 if (cp < xbp || cp >= utf_skipcols(xbp, x_displen, NULL)) {
1605 /* we are heading off screen */
1608 } else if (cp < xcp) {
1612 } else if (cp > xcp) {
1620 x_bs0(char *cp, char *lower_bound)
1623 while ((!lower_bound || (cp > lower_bound)) &&
1624 ((*(unsigned char *)cp & 0xC0) == 0x80))
1634 *p = x_bs0((*p) - 1, NULL);
1635 i = x_size2(*p, NULL);
1641 x_size2(char *cp, char **dcp)
1643 uint8_t c = *(unsigned char *)cp;
1645 if (UTFMODE && (c > 0x7F))
1646 return (utf_widthadj(cp, (const char **)dcp));
1650 /* Kludge, tabs are always four spaces. */
1652 if (ISCTRL(c) && /* but not C1 */ c < 0x80)
1653 /* control unsigned char */
1661 int adj = x_adj_done;
1664 while (*str && str < xlp && x_col < xx_cols && adj == x_adj_done)
1671 unsigned char c = **(unsigned char **)cp;
1674 /* Kludge, tabs are always four spaces. */
1677 } else if (ISCTRL(c) && /* but not C1 */ c < 0x80) {
1679 x_e_putc2(UNCTRL(c));
1682 x_e_putc3((const char **)cp);
1686 x_mv_back(int c MKSH_A_UNUSED)
1701 x_mv_forw(int c MKSH_A_UNUSED)
1703 char *cp = xcp, *cp2;
1710 utf_ptradjx(cp, cp2);
1720 x_search_char_forw(int c MKSH_A_UNUSED)
1726 if (x_e_getmbc(tmp) < 0) {
1731 if ((cp = (cp == xep) ? NULL : strstr(cp + 1, tmp)) == NULL &&
1732 (cp = strstr(xbuf, tmp)) == NULL) {
1742 x_search_char_back(int c MKSH_A_UNUSED)
1744 char *cp = xcp, *p, tmp[4];
1747 if (x_e_getmbc(tmp) < 0) {
1751 for (; x_arg--; cp = p)
1759 if ((tmp[1] && ((p+1) > xep)) ||
1760 (tmp[2] && ((p+2) > xep)))
1765 if (b && tmp[1] && p[1] != tmp[1])
1767 if (b && tmp[2] && p[2] != tmp[2])
1777 x_newline(int c MKSH_A_UNUSED)
1787 x_end_of_text(int c MKSH_A_UNUSED)
1789 unsigned char tmp[1], *cp = tmp;
1791 *tmp = isedchar(edchars.eof) ? (unsigned char)edchars.eof :
1792 (unsigned char)CTRL('D');
1793 x_zotc3((char **)&cp);
1801 x_beg_hist(int c MKSH_A_UNUSED)
1803 x_load_hist(history);
1808 x_end_hist(int c MKSH_A_UNUSED)
1810 x_load_hist(histptr);
1815 x_prev_com(int c MKSH_A_UNUSED)
1817 x_load_hist(x_histp - x_arg);
1822 x_next_com(int c MKSH_A_UNUSED)
1824 x_load_hist(x_histp + x_arg);
1829 * Goto a particular history number obtained from argument.
1830 * If no argument is given history 1 is probably not what you
1831 * want so we'll simply go to the oldest one.
1834 x_goto_hist(int c MKSH_A_UNUSED)
1836 if (x_arg_defaulted)
1837 x_load_hist(history);
1839 x_load_hist(histptr + x_arg - source->line);
1844 x_load_hist(char **hp)
1848 if (hp == histptr + 1) {
1851 } else if (hp < history || hp > histptr) {
1859 strlcpy(holdbufp, xbuf, LINE);
1860 strlcpy(xbuf, sp, xend - xbuf);
1862 xep = xcp = xbuf + strlen(xbuf);
1868 x_nl_next_com(int c MKSH_A_UNUSED)
1871 x_histmcp = x_histp;
1872 if (!x_histncp || (x_histmcp != x_histncp && x_histmcp != histptr + 1))
1873 /* fresh start of ^O */
1874 x_histncp = x_histmcp;
1875 x_nextcmd = source->line - (histptr - x_histncp) + 1;
1876 return (x_newline('\n'));
1882 if (xep == xbuf && x_arg_defaulted)
1883 return (x_end_of_text(c));
1885 return (x_del_char(c));
1888 /* reverse incremental history search */
1890 x_search_hist(int c)
1892 int offset = -1; /* offset of match in xbuf, else -1 */
1893 char pat[80 + 1]; /* pattern buffer */
1898 while (/* CONSTCOND */ 1) {
1900 x_e_puts("\nI-search: ");
1904 if ((c = x_e_getc()) < 0)
1907 if (c == CTRL('[')) {
1908 if ((f & 0x7F) == XFUNC_meta1) {
1909 if ((c = x_e_getc()) < 0)
1911 f = x_tab[1][c] & 0x7F;
1912 if (f == XFUNC_meta1 || f == XFUNC_meta2)
1921 if ((c = x_e_getc()) != '~')
1925 if (f == XFUNC_search_hist)
1926 offset = x_search(pat, 0, offset);
1927 else if (f == XFUNC_del_back) {
1933 p = x_bs0(p - 1, pat);
1939 offset = x_search(pat, 1, offset);
1941 } else if (f == XFUNC_insert) {
1942 /* add char to pattern */
1943 /* overflow check... */
1944 if ((size_t)(p - pat) >= sizeof(pat) - 1) {
1948 *p++ = c, *p = '\0';
1950 /* already have partial match */
1951 offset = x_match(xbuf, pat);
1953 x_goto(xbuf + offset + (p - pat) -
1958 offset = x_search(pat, 0, offset);
1959 } else if (f == XFUNC_abort) {
1961 x_load_hist(histptr + 1);
1974 /* search backward from current line */
1976 x_search(char *pat, int sameline, int offset)
1981 for (hp = x_histp - (sameline ? 0 : 1); hp >= history; --hp) {
1982 i = x_match(*hp, pat);
1987 x_goto(xbuf + i + strlen(pat) - (*pat == '^'));
1997 /* anchored search up from current line */
1999 x_search_hist_up(int c MKSH_A_UNUSED)
2001 return (x_search_dir(-1));
2004 /* anchored search down from current line */
2006 x_search_hist_dn(int c MKSH_A_UNUSED)
2008 return (x_search_dir(1));
2011 /* anchored search in the indicated direction */
2013 x_search_dir(int search_dir /* should've been bool */)
2015 char **hp = x_histp + search_dir;
2016 size_t curs = xcp - xbuf;
2018 while (histptr >= hp && hp >= history) {
2019 if (strncmp(xbuf, *hp, curs) == 0) {
2021 x_goto(xbuf + curs);
2030 /* return position of first match of pattern in string, else -1 */
2032 x_match(char *str, char *pat)
2035 return ((strncmp(str, pat + 1, strlen(pat + 1)) == 0) ? 0 : -1);
2037 char *q = strstr(str, pat);
2038 return ((q == NULL) ? -1 : q - str);
2043 x_del_line(int c MKSH_A_UNUSED)
2046 x_push(xep - (xcp = xbuf));
2047 xlp = xbp = xep = xbuf;
2057 x_mv_end(int c MKSH_A_UNUSED)
2064 x_mv_beg(int c MKSH_A_UNUSED)
2071 x_draw_line(int c MKSH_A_UNUSED)
2078 x_cls(int c MKSH_A_UNUSED)
2080 shf_puts(MKSH_CLS_STRING, shl_out);
2086 * clear line from x_col (current cursor position) to xx_cols - 2,
2087 * then output lastch, then go back to x_col; if lastch is space,
2088 * clear with termcap instead of spaces, or not if line_was_cleared;
2089 * lastch MUST be an ASCII character with wcwidth(lastch) == 1
2092 x_clrtoeol(int lastch, bool line_was_cleared)
2096 if (lastch == ' ' && !line_was_cleared && x_term_mode == 1) {
2097 shf_puts("\033[K", shl_out);
2098 line_was_cleared = true;
2100 if (lastch == ' ' && line_was_cleared)
2104 while (col < (xx_cols - 2)) {
2110 while (col > x_col) {
2116 /* output the prompt, assuming a line has just been started */
2120 if (prompt_trunc != -1)
2121 pprompt(prompt, prompt_trunc);
2125 /* output CR, then redraw the line, clearing to EOL if needed (cr ≠0, LF) */
2132 /* clear the line */
2133 x_e_putc2(cr ? cr : '\r');
2135 /* display the prompt */
2138 x_displen = xx_cols - 2 - x_col;
2139 /* display the line content */
2142 /* check whether there is more off-screen */
2143 lch = xep > xlp ? (xbp > xbuf ? '*' : '>') : (xbp > xbuf) ? '<' : ' ';
2144 /* clear the rest of the line */
2145 x_clrtoeol(lch, !cr || cr == '\n');
2146 /* go back to actual cursor position */
2152 x_transpose(int c MKSH_A_UNUSED)
2154 unsigned int tmpa, tmpb;
2157 * What transpose is meant to do seems to be up for debate. This
2158 * is a general summary of the options; the text is abcd with the
2159 * upper case character or underscore indicating the cursor position:
2160 * Who Before After Before After
2161 * AT&T ksh in emacs mode: abCd abdC abcd_ (bell)
2162 * AT&T ksh in gmacs mode: abCd baCd abcd_ abdc_
2163 * gnu emacs: abCd acbD abcd_ abdc_
2164 * Pdksh currently goes with GNU behavior since I believe this is the
2165 * most common version of emacs, unless in gmacs mode, in which case
2166 * it does the AT&T ksh gmacs mode.
2167 * This should really be broken up into 3 functions so users can bind
2168 * to the one they want.
2173 } else if (xcp == xep || Flag(FGMACS)) {
2174 if (xcp - xbuf == 1) {
2179 * Gosling/Unipress emacs style: Swap two characters before
2180 * the cursor, do not change cursor position
2183 if (utf_mbtowc(&tmpa, xcp) == (size_t)-1) {
2188 if (utf_mbtowc(&tmpb, xcp) == (size_t)-1) {
2192 utf_wctomb(xcp, tmpa);
2194 utf_wctomb(xcp, tmpb);
2198 * GNU emacs style: Swap the characters before and under the
2199 * cursor, move cursor position along one.
2201 if (utf_mbtowc(&tmpa, xcp) == (size_t)-1) {
2206 if (utf_mbtowc(&tmpb, xcp) == (size_t)-1) {
2210 utf_wctomb(xcp, tmpa);
2212 utf_wctomb(xcp, tmpb);
2220 x_literal(int c MKSH_A_UNUSED)
2227 x_meta1(int c MKSH_A_UNUSED)
2234 x_meta2(int c MKSH_A_UNUSED)
2241 x_meta3(int c MKSH_A_UNUSED)
2248 x_kill(int c MKSH_A_UNUSED)
2250 size_t col = xcp - xbuf;
2251 size_t lastcol = xep - xbuf;
2254 if (x_arg_defaulted || (narg = x_arg) > lastcol)
2257 x_goto(xbuf + narg);
2261 x_delete(x_nb2nc(ndel), true);
2266 x_push(size_t nchars)
2268 afree(killstack[killsp], AEDIT);
2269 strndupx(killstack[killsp], xcp, nchars, AEDIT);
2270 killsp = (killsp + 1) % KILLSIZE;
2274 x_yank(int c MKSH_A_UNUSED)
2281 if (killstack[killtp] == 0) {
2282 x_e_puts("\nnothing to yank");
2287 x_ins(killstack[killtp]);
2292 x_meta_yank(int c MKSH_A_UNUSED)
2296 if ((x_last_command != XFUNC_yank && x_last_command != XFUNC_meta_yank) ||
2297 killstack[killtp] == 0) {
2299 x_e_puts("\nyank something first");
2303 len = strlen(killstack[killtp]);
2305 x_delete(x_nb2nc(len), false);
2308 killtp = KILLSIZE - 1;
2311 } while (killstack[killtp] == 0);
2312 x_ins(killstack[killtp]);
2317 x_abort(int c MKSH_A_UNUSED)
2320 xlp = xep = xcp = xbp = xbuf;
2328 x_error(int c MKSH_A_UNUSED)
2335 /* special VT100 style key sequence hack */
2339 /* we only support PF2-'1' for now */
2340 if (c != (2 << 8 | '1'))
2341 return (x_error(c));
2343 /* what's the next character? */
2344 switch ((c = x_e_getc())) {
2347 x_arg_defaulted = true;
2348 return (x_mv_beg(0));
2350 /* "interesting" sequence detected */
2356 /* XXX x_e_ungetc is one-octet only */
2357 if ((c = x_e_getc()) != '5' && c != '3')
2361 * At this point, we have read the following octets so far:
2362 * - ESC+[ or ESC+O or Ctrl-X (Prefix 2)
2365 * - 5 (Ctrl key combiner) or 3 (Alt key combiner)
2366 * We can now accept one more octet designating the key.
2369 switch ((c = x_e_getc())) {
2371 return (x_mv_fword(c));
2373 return (x_mv_bword(c));
2378 return (x_error(c));
2383 x_mapin(const char *cp, Area *ap)
2387 strdupx(news, cp, ap);
2390 /* XXX -- should handle \^ escape? */
2393 /*XXX or ^^ escape? this is ugly. */
2395 /* includes '?'; ASCII */
2411 x_mapout2(int c, char **buf)
2435 x_print(int prefix, int key)
2437 int f = x_tab[prefix][key];
2440 /* prefix == 1 || prefix == 2 */
2441 shf_puts(x_mapout(prefix == 1 ? CTRL('[') :
2442 prefix == 2 ? CTRL('X') : 0), shl_stdout);
2444 shprintf("%s = ", x_mapout(key));
2446 shprintf("%s%s = ", x_mapout(key), (f & 0x80) ? "~" : "");
2447 if (XFUNC_VALUE(f) != XFUNC_ins_string)
2449 shprintf(Tf_sN, x_ftab[XFUNC_VALUE(f)].xf_name);
2452 shprintf("'%s'\n", x_atab[prefix][key]);
2457 x_bind(const char *a1, const char *a2,
2473 if (x_tab == NULL) {
2474 bi_errorf("can't bind, not a tty");
2477 /* List function names */
2479 for (f = 0; f < NELEM(x_ftab); f++)
2480 if (!(x_ftab[f].xf_flags & XF_NOBIND))
2481 shprintf(Tf_sN, x_ftab[f].xf_name);
2485 for (prefix = 0; prefix < X_NTABS; prefix++)
2486 for (key = 0; key < X_TABSZ; key++) {
2487 f = XFUNC_VALUE(x_tab[prefix][key]);
2488 if (f == XFUNC_insert || f == XFUNC_error
2490 || (macro && f != XFUNC_ins_string)
2494 x_print(prefix, key);
2498 m2 = m1 = x_mapin(a1, ATEMP);
2501 key = (unsigned char)*m1;
2502 f = XFUNC_VALUE(x_tab[prefix][key]);
2503 if (f == XFUNC_meta1)
2505 else if (f == XFUNC_meta2)
2507 else if (f == XFUNC_meta3)
2514 && ((*m1 != '~') || *(m1 + 1))
2520 while (*c && (size_t)(m1 - msg) < sizeof(msg) - 3)
2521 x_mapout2(*c++, &m1);
2522 bi_errorf("too long key sequence: %s", msg);
2526 hastilde = tobool(*m1);
2531 x_print(prefix, key);
2538 f = XFUNC_ins_string;
2539 sp = x_mapin(a2, AEDIT);
2542 for (f = 0; f < NELEM(x_ftab); f++)
2543 if (!strcmp(x_ftab[f].xf_name, a2))
2545 if (f == NELEM(x_ftab) || x_ftab[f].xf_flags & XF_NOBIND) {
2546 bi_errorf("%s: no such function", a2);
2552 if (XFUNC_VALUE(x_tab[prefix][key]) == XFUNC_ins_string &&
2553 x_atab[prefix][key])
2554 afree(x_atab[prefix][key], AEDIT);
2556 x_tab[prefix][key] = f
2558 | (hastilde ? 0x80 : 0)
2562 x_atab[prefix][key] = sp;
2565 /* Track what the user has bound so x_mode(true) won't toast things */
2566 if (f == XFUNC_insert)
2567 x_bound[(prefix * X_TABSZ + key) / 8] &=
2568 ~(1 << ((prefix * X_TABSZ + key) % 8));
2570 x_bound[(prefix * X_TABSZ + key) / 8] |=
2571 (1 << ((prefix * X_TABSZ + key) % 8));
2577 bind_if_not_bound(int p, int k, int func)
2582 * Has user already bound this key?
2583 * If so, do not override it.
2585 t = p * X_TABSZ + k;
2586 if (x_bound[t >> 3] & (1 << (t & 7)))
2593 x_set_mark(int c MKSH_A_UNUSED)
2600 x_kill_region(int c MKSH_A_UNUSED)
2617 x_delete(x_nb2nc(rsize), true);
2623 x_xchg_point_mark(int c MKSH_A_UNUSED)
2638 x_noop(int c MKSH_A_UNUSED)
2644 * File/command name completion routines
2647 x_comp_comm(int c MKSH_A_UNUSED)
2649 do_complete(XCF_COMMAND, CT_COMPLETE);
2654 x_list_comm(int c MKSH_A_UNUSED)
2656 do_complete(XCF_COMMAND, CT_LIST);
2661 x_complete(int c MKSH_A_UNUSED)
2663 do_complete(XCF_COMMAND_FILE, CT_COMPLETE);
2668 x_enumerate(int c MKSH_A_UNUSED)
2670 do_complete(XCF_COMMAND_FILE, CT_LIST);
2675 x_comp_file(int c MKSH_A_UNUSED)
2677 do_complete(XCF_FILE, CT_COMPLETE);
2682 x_list_file(int c MKSH_A_UNUSED)
2684 do_complete(XCF_FILE, CT_LIST);
2689 x_comp_list(int c MKSH_A_UNUSED)
2691 do_complete(XCF_COMMAND_FILE, CT_COMPLIST);
2696 x_expand(int c MKSH_A_UNUSED)
2699 int start, end, nwords, i;
2702 nwords = x_cf_glob(&i, xbuf, xep - xbuf, xcp - xbuf,
2703 &start, &end, &words);
2709 x_goto(xbuf + start);
2710 x_delete(x_nb2nc(end - start), false);
2713 while (i < nwords) {
2714 if (x_escape(words[i], strlen(words[i]), x_do_ins) < 0 ||
2715 (++i < nwords && x_ins(T1space) < 0)) {
2727 /* XCF_{COMMAND,FILE,COMMAND_FILE} */
2729 /* 0 for list, 1 for complete and 2 for complete-list */
2733 int start, end, nlen, olen, nwords;
2736 nwords = x_cf_glob(&flags, xbuf, xep - xbuf, xcp - xbuf,
2737 &start, &end, &words);
2743 if (type == CT_LIST) {
2744 x_print_expansions(nwords, words,
2745 tobool(flags & XCF_IS_COMMAND));
2747 x_free_words(nwords, words);
2751 nlen = x_longest_prefix(nwords, words);
2754 * always complete single matches;
2755 * any expansion of parameter substitution
2756 * is always at most one result, too
2762 /* make a copy of the original string part */
2763 strndupx(unescaped, xbuf + start, olen, ATEMP);
2765 /* expand any tilde and unescape the string for comparison */
2766 unescaped = x_glob_hlp_tilde_and_rem_qchar(unescaped, true);
2769 * match iff entire original string is part of the
2770 * longest prefix, implying the latter is at least
2771 * the same size (after unescaping)
2773 completed = !strncmp(words[0], unescaped, strlen(unescaped));
2775 afree(unescaped, ATEMP);
2777 if (type == CT_COMPLIST && nwords > 1) {
2779 * print expansions, since we didn't get back
2780 * just a single match
2782 x_print_expansions(nwords, words,
2783 tobool(flags & XCF_IS_COMMAND));
2786 /* expand on the command line */
2790 memmove(xcp, xcp + olen, xep - xcp + 1);
2791 x_escape(words[0], nlen, x_do_ins);
2795 * append a space if this is a single non-directory match
2796 * and not a parameter or homedir substitution
2798 if (nwords == 1 && !mksh_cdirsep(words[0][nlen - 1]) &&
2799 !(flags & XCF_IS_NOSPACE)) {
2803 x_free_words(nwords, words);
2808 * x_adjust - redraw the line adjusting starting point etc.
2811 * This function is called when we have exceeded the bounds
2812 * of the edit window. It increments x_adj_done so that
2813 * functions like x_ins and x_delete know that we have been
2814 * called and can skip the x_bs() stuff which has already
2815 * been done by x_redraw.
2825 /* flag the fact that we were called */
2829 * calculate the amount of columns we need to "go back"
2830 * from xcp to set xbp to (but never < xbuf) to 2/3 of
2831 * the display width; take care of pwidth though
2833 if ((col_left = xx_cols * 2 / 3) < MIN_EDIT_SPACE) {
2835 * cowardly refuse to do anything
2836 * if the available space is too small;
2837 * fall back to dumb pdksh code
2839 if ((xbp = xcp - (x_displen / 2)) < xbuf)
2841 /* elide UTF-8 fixup as penalty */
2845 /* fix up xbp to just past a character end first */
2846 xbp = xcp >= xep ? xep : x_bs0(xcp, xbuf);
2847 /* walk backwards */
2848 while (xbp > xbuf && col_left > 0) {
2849 xbp = x_bs0(xbp - 1, xbuf);
2850 col_left -= (n = x_size2(xbp, NULL));
2852 /* check if we hit the prompt */
2853 if (xbp == xbuf && xcp != xbuf && col_left >= 0 && col_left < pwidth) {
2854 /* so we did; force scrolling occurs */
2855 xbp += utf_ptradj(xbp);
2867 unget_char = c < 0 ? -1 : (c & 255);
2875 if (unget_char >= 0) {
2883 if ((c = (unsigned char)*macroptr++))
2897 if (c == '\r' || c == '\n')
2899 if (x_col < xx_cols) {
2900 if (UTFMODE && (c > 0x7F)) {
2906 x = utf_wctomb(utf_tmp, c);
2912 width = utf_wcwidth(c);
2929 if (x_adj_ok && (x_col < 0 || x_col >= (xx_cols - 2)))
2934 x_e_putc3(const char **cp)
2936 int width = 1, c = **(const unsigned char **)cp;
2938 if (c == '\r' || c == '\n')
2940 if (x_col < xx_cols) {
2941 if (UTFMODE && (c > 0x7F)) {
2944 width = utf_widthadj(*cp, (const char **)&cp2);
2945 if (cp2 == *cp + 1) {
2947 shf_puts("\xEF\xBF\xBD", shl_out);
2969 if (x_adj_ok && (x_col < 0 || x_col >= (xx_cols - 2)))
2974 x_e_puts(const char *s)
2976 int adj = x_adj_done;
2978 while (*s && adj == x_adj_done)
2984 * x_set_arg - set an arg value for next function
2987 * This is a simple implementation of M-[0-9].
2998 /* strip command prefix */
3000 while (c >= 0 && ksh_isdigit(c)) {
3001 n = n * 10 + ksh_numdig(c);
3003 /* upper bound for repeat */
3004 goto x_set_arg_too_big;
3008 if (c < 0 || first) {
3012 x_arg_defaulted = true;
3016 x_arg_defaulted = false;
3021 /* Comment or uncomment the current line. */
3023 x_comment(int c MKSH_A_UNUSED)
3025 ssize_t len = xep - xbuf;
3026 int ret = x_do_comment(xbuf, xend - xbuf, &len);
3037 return (x_newline('\n'));
3043 x_version(int c MKSH_A_UNUSED)
3045 char *o_xbuf = xbuf, *o_xend = xend;
3046 char *o_xbp = xbp, *o_xep = xep, *o_xcp = xcp;
3049 strdupx(v, KSH_VERSION, ATEMP);
3051 xbuf = xbp = xcp = v;
3052 xend = xep = v + strlen(v);
3066 /* This is what AT&T ksh seems to do... Very bizarre */
3076 x_edit_line(int c MKSH_A_UNUSED)
3078 if (x_arg_defaulted) {
3085 histsave(&source->line, xbuf, HIST_STORE, true);
3088 x_arg = source->line - (histptr - x_histp);
3091 shf_snprintf(xbuf, xend - xbuf, Tf_sd,
3092 "fc -e ${VISUAL:-${EDITOR:-vi}} --", x_arg);
3094 strlcpy(xbuf, "fc -e ${VISUAL:-${EDITOR:-vi}} --", xend - xbuf);
3095 xep = xbuf + strlen(xbuf);
3096 return (x_newline('\n'));
3102 * x_prev_histword - recover word from prev command
3105 * This function recovers the last word from the previous
3106 * command and inserts it into the current edit line. If a
3107 * numeric arg is supplied then the n'th word from the
3108 * start of the previous command is used.
3109 * As a side effect, trashes the mark in order to achieve
3110 * being called in a repeatable fashion.
3118 x_prev_histword(int c MKSH_A_UNUSED)
3123 /* -1 = defaulted; 0+ = argument */
3124 static int last_arg = -1;
3126 if (x_last_command == XFUNC_prev_histword) {
3127 if (xmp && modified > 1)
3132 last_arg = x_arg_defaulted ? -1 : x_arg;
3133 xhp = histptr - (m - 1);
3134 if ((xhp < history) || !(cp = *xhp)) {
3140 if ((x_arg = last_arg) == -1) {
3141 /* x_arg_defaulted */
3143 rcp = &cp[strlen(cp) - 1];
3145 * ignore white-space after the last word
3147 while (rcp > cp && is_cfs(*rcp))
3149 while (rcp > cp && !is_cfs(*rcp))
3155 /* not x_arg_defaulted */
3160 * ignore white-space at start of line
3162 while (*rcp && is_cfs(*rcp))
3164 while (x_arg-- > 0) {
3165 while (*rcp && !is_cfs(*rcp))
3167 while (*rcp && is_cfs(*rcp))
3171 while (*rcp && !is_cfs(*rcp))
3179 x_histmcp = x_histp;
3185 /* Uppercase N(1) words */
3187 x_fold_upper(int c MKSH_A_UNUSED)
3189 return (x_fold_case('U'));
3192 /* Lowercase N(1) words */
3194 x_fold_lower(int c MKSH_A_UNUSED)
3196 return (x_fold_case('L'));
3199 /* Titlecase N(1) words */
3201 x_fold_capitalise(int c MKSH_A_UNUSED)
3203 return (x_fold_case('C'));
3208 * x_fold_case - convert word to UPPER/lower/Capital case
3211 * This function is used to implement M-U/M-u, M-L/M-l, M-C/M-c
3212 * to UPPER CASE, lower case or Capitalise Words.
3228 * first skip over any white-space
3230 while (cp != xep && is_mfs(*cp))
3233 * do the first char on its own since it may be
3234 * a different action than for the rest.
3239 *cp = ksh_tolower(*cp);
3241 /* uppercase, capitalise */
3242 *cp = ksh_toupper(*cp);
3246 * now for the rest of the word
3248 while (cp != xep && !is_mfs(*cp)) {
3251 *cp = ksh_toupper(*cp);
3253 /* lowercase, capitalise */
3254 *cp = ksh_tolower(*cp);
3266 * x_lastcp - last visible char
3269 * This function returns a pointer to that char in the
3270 * edit buffer that will be the last displayed on the
3282 j = x_size2(xlp, &xlp2);
3283 if ((i + j) > x_displen)
3293 /* correctly position the cursor on the screen from end of visible area */
3297 char *cp = x_lastcp();
3306 static bool x_cur_mode;
3308 if (x_cur_mode == onoff)
3313 x_mkraw(tty_fd, NULL, false);
3315 edchars.erase = toedchar(tty_state.c_cc[VERASE]);
3316 edchars.kill = toedchar(tty_state.c_cc[VKILL]);
3317 edchars.intr = toedchar(tty_state.c_cc[VINTR]);
3318 edchars.quit = toedchar(tty_state.c_cc[VQUIT]);
3319 edchars.eof = toedchar(tty_state.c_cc[VEOF]);
3321 edchars.werase = toedchar(tty_state.c_cc[VWERASE]);
3327 edchars.erase = CTRL('H');
3329 edchars.kill = CTRL('U');
3331 edchars.intr = CTRL('C');
3333 edchars.quit = CTRL('\\');
3335 edchars.eof = CTRL('D');
3336 if (!edchars.werase)
3337 edchars.werase = CTRL('W');
3339 if (isedchar(edchars.erase)) {
3340 bind_if_not_bound(0, edchars.erase, XFUNC_del_back);
3341 bind_if_not_bound(1, edchars.erase, XFUNC_del_bword);
3343 if (isedchar(edchars.kill))
3344 bind_if_not_bound(0, edchars.kill, XFUNC_del_line);
3345 if (isedchar(edchars.werase))
3346 bind_if_not_bound(0, edchars.werase, XFUNC_del_bword);
3347 if (isedchar(edchars.intr))
3348 bind_if_not_bound(0, edchars.intr, XFUNC_abort);
3349 if (isedchar(edchars.quit))
3350 bind_if_not_bound(0, edchars.quit, XFUNC_noop);
3352 mksh_tcset(tty_fd, &tty_state);
3356 /* +++ vi editing mode +++ */
3366 static int vi_hook(int);
3367 static int nextstate(int);
3368 static int vi_insert(int);
3369 static int vi_cmd(int, const char *);
3370 static int domove(int, const char *, int);
3371 static int redo_insert(int);
3372 static void yank_range(int, int);
3373 static int bracktype(int);
3374 static void save_cbuf(void);
3375 static void restore_cbuf(void);
3376 static int putbuf(const char *, ssize_t, bool);
3377 static void del_range(int, int);
3378 static int findch(int, int, bool, bool) MKSH_A_PURE;
3379 static int forwword(int);
3380 static int backword(int);
3381 static int endword(int);
3382 static int Forwword(int);
3383 static int Backword(int);
3384 static int Endword(int);
3385 static int grabhist(int, int);
3386 static int grabsearch(int, int, int, const char *);
3387 static void redraw_line(bool);
3388 static void refresh(int);
3389 static int outofwin(void);
3390 static void rewindow(void);
3391 static int newcol(unsigned char, int);
3392 static void display(char *, char *, int);
3393 static void ed_mov_opt(int, char *);
3394 static int expand_word(int);
3395 static int complete_word(int, int);
3396 static int print_expansions(struct edstate *, int);
3397 #define char_len(c) ((ISCTRL((unsigned char)c) && \
3398 /* but not C1 */ (unsigned char)c < 0x80) ? 2 : 1)
3399 static void x_vi_zotc(int);
3400 static void vi_error(void);
3401 static void vi_macro_reset(void);
3402 static int x_vi_putbuf(const char *, size_t);
3404 #define vC 0x01 /* a valid command that isn't a vM, vE, vU */
3405 #define vM 0x02 /* movement command (h, l, etc.) */
3406 #define vE 0x04 /* extended command (c, d, y) */
3407 #define vX 0x08 /* long command (@, f, F, t, T, etc.) */
3408 #define vU 0x10 /* an UN-undoable command (that isn't a vM) */
3409 #define vB 0x20 /* bad command (^@) */
3410 #define vZ 0x40 /* repeat count defaults to 0 (not 1) */
3411 #define vS 0x80 /* search (/, ?) */
3413 #define is_bad(c) (classify[(c)&0x7f]&vB)
3414 #define is_cmd(c) (classify[(c)&0x7f]&(vM|vE|vC|vU))
3415 #define is_move(c) (classify[(c)&0x7f]&vM)
3416 #define is_extend(c) (classify[(c)&0x7f]&vE)
3417 #define is_long(c) (classify[(c)&0x7f]&vX)
3418 #define is_undoable(c) (!(classify[(c)&0x7f]&vU))
3419 #define is_srch(c) (classify[(c)&0x7f]&vS)
3420 #define is_zerocount(c) (classify[(c)&0x7f]&vZ)
3422 static const unsigned char classify[128] = {
3423 /* 0 1 2 3 4 5 6 7 */
3424 /* 0 ^@ ^A ^B ^C ^D ^E ^F ^G */
3425 vB, 0, 0, 0, 0, vC|vU, vC|vZ, 0,
3426 /* 1 ^H ^I ^J ^K ^L ^M ^N ^O */
3427 vM, vC|vZ, 0, 0, vC|vU, 0, vC, 0,
3428 /* 2 ^P ^Q ^R ^S ^T ^U ^V ^W */
3429 vC, 0, vC|vU, 0, 0, 0, vC, 0,
3430 /* 3 ^X ^Y ^Z ^[ ^\ ^] ^^ ^_ */
3431 vC, 0, 0, vC|vZ, 0, 0, 0, 0,
3432 /* 4 <space> ! " # $ % & ' */
3433 vM, 0, 0, vC, vM, vM, 0, 0,
3434 /* 5 ( ) * + , - . / */
3435 0, 0, vC, vC, vM, vC, 0, vC|vS,
3436 /* 6 0 1 2 3 4 5 6 7 */
3437 vM, 0, 0, 0, 0, 0, 0, 0,
3438 /* 7 8 9 : ; < = > ? */
3439 0, 0, 0, vM, 0, vC, 0, vC|vS,
3440 /* 8 @ A B C D E F G */
3441 vC|vX, vC, vM, vC, vC, vM, vM|vX, vC|vU|vZ,
3442 /* 9 H I J K L M N O */
3443 0, vC, 0, 0, 0, 0, vC|vU, vU,
3444 /* A P Q R S T U V W */
3445 vC, 0, vC, vC, vM|vX, vC, 0, vM,
3446 /* B X Y Z [ \ ] ^ _ */
3447 vC, vC|vU, 0, vU, vC|vZ, 0, vM, vC|vZ,
3448 /* C ` a b c d e f g */
3449 0, vC, vM, vE, vE, vM, vM|vX, vC|vZ,
3450 /* D h i j k l m n o */
3451 vM, vC, vC|vU, vC|vU, vM, 0, vC|vU, 0,
3452 /* E p q r s t u v w */
3453 vC, 0, vX, vC, vM|vX, vC|vU, vC|vU|vZ, vM,
3454 /* F x y z { | } ~ ^? */
3455 vC, vE|vU, 0, 0, vM|vZ, 0, vC, 0
3464 #define VNORMAL 0 /* command, insert or replace mode */
3465 #define VARG1 1 /* digit prefix (first, eg, 5l) */
3466 #define VEXTCMD 2 /* cmd + movement (eg, cl) */
3467 #define VARG2 3 /* digit prefix (second, eg, 2c3l) */
3468 #define VXCH 4 /* f, F, t, T, @ */
3469 #define VFAIL 5 /* bad command */
3470 #define VCMD 6 /* single char command (eg, X) */
3471 #define VREDO 7 /* . */
3472 #define VLIT 8 /* ^V */
3473 #define VSEARCH 9 /* /, ? */
3474 #define VVERSION 10 /* <ESC> ^V */
3475 #define VPREFIX2 11 /* ^[[ and ^[O in insert mode */
3477 static struct edstate *save_edstate(struct edstate *old);
3478 static void restore_edstate(struct edstate *old, struct edstate *news);
3479 static void free_edstate(struct edstate *old);
3481 static struct edstate ebuf;
3482 static struct edstate undobuf;
3484 static struct edstate *vs; /* current Vi editing mode state */
3485 static struct edstate *undo;
3487 static char *ibuf; /* input buffer */
3488 static bool first_insert; /* set when starting in insert mode */
3489 static int saved_inslen; /* saved inslen for first insert */
3490 static int inslen; /* length of input buffer */
3491 static int srchlen; /* length of current search pattern */
3492 static char *ybuf; /* yank buffer */
3493 static int yanklen; /* length of yank buffer */
3494 static int fsavecmd = ' '; /* last find command */
3495 static int fsavech; /* character to find */
3496 static char lastcmd[MAXVICMD]; /* last non-move command */
3497 static int lastac; /* argcnt for lastcmd */
3498 static int lastsearch = ' '; /* last search command */
3499 static char srchpat[SRCHLEN]; /* last search pattern */
3500 static int insert; /* <>0 in insert mode */
3501 static int hnum; /* position in history */
3502 static int ohnum; /* history line copied (after mod) */
3503 static int hlast; /* 1 past last position in history */
3507 * Information for keeping track of macros that are being expanded.
3508 * The format of buf is the alias contents followed by a NUL byte followed
3509 * by the name (letter) of the alias. The end of the buffer is marked by
3510 * a double NUL. The name of the alias is stored so recursive macros can
3513 struct macro_state {
3514 unsigned char *p; /* current position in buf */
3515 unsigned char *buf; /* pointer to macro(s) being expanded */
3516 size_t len; /* how much data in buffer */
3518 static struct macro_state macro;
3520 /* last input was expanded */
3521 static enum expand_mode {
3522 NONE = 0, EXPAND, COMPLETE, PRINT
3531 ohnum = hnum = hlast = histnum(-1) + 1;
3533 saved_inslen = inslen;
3534 first_insert = true;
3539 if (undobuf.cbuf == NULL) {
3540 ibuf = alloc(LINE, AEDIT);
3541 ybuf = alloc(LINE, AEDIT);
3542 undobuf.cbuf = alloc(LINE, AEDIT);
3544 undobuf.cbufsize = ebuf.cbufsize = LINE;
3545 undobuf.linelen = ebuf.linelen = 0;
3546 undobuf.cursor = ebuf.cursor = 0;
3547 undobuf.winleft = ebuf.winleft = 0;
3551 x_init_prompt(true);
3554 if (wbuf_len != x_cols - 3 && ((wbuf_len = x_cols - 3))) {
3555 wbuf[0] = aresize(wbuf[0], wbuf_len, AEDIT);
3556 wbuf[1] = aresize(wbuf[1], wbuf_len, AEDIT);
3559 memset(wbuf[0], ' ', wbuf_len);
3560 memset(wbuf[1], ' ', wbuf_len);
3562 winwidth = x_cols - pwidth - 3;
3570 while (/* CONSTCOND */ 1) {
3572 c = (unsigned char)*macro.p++;
3573 /* end of current macro? */
3575 /* more macros left to finish? */
3578 /* must be the end of all the macros */
3587 if (state != VLIT) {
3588 if (isched(c, edchars.intr) ||
3589 isched(c, edchars.quit)) {
3590 /* pretend we got an interrupt */
3593 trapsig(isched(c, edchars.intr) ?
3597 } else if (isched(c, edchars.eof) &&
3598 state != VVERSION) {
3599 if (vs->linelen == 0) {
3616 if (c == -1 || (ssize_t)LINE <= vs->linelen)
3619 if (vs->cbuf != buf)
3620 memcpy(buf, vs->cbuf, vs->linelen);
3622 buf[vs->linelen++] = '\n';
3624 return (vs->linelen);
3630 static char curcmd[MAXVICMD], locpat[SRCHLEN];
3631 static int cmdlen, argc1, argc2;
3637 if (!ch) switch (cmdlen = 0, (ch = x_getc())) {
3638 case 71: ch = '0'; goto pseudo_vi_command;
3639 case 72: ch = 'k'; goto pseudo_vi_command;
3640 case 73: ch = 'A'; goto vi_xfunc_search_up;
3641 case 75: ch = 'h'; goto pseudo_vi_command;
3642 case 77: ch = 'l'; goto pseudo_vi_command;
3643 case 79: ch = '$'; goto pseudo_vi_command;
3644 case 80: ch = 'j'; goto pseudo_vi_command;
3645 case 83: ch = 'x'; goto pseudo_vi_command;
3646 default: ch = 0; goto vi_insert_failed;
3649 if (ch == CTRL('v')) {
3653 switch (vi_insert(ch)) {
3660 if (state == VLIT) {
3664 refresh(insert != 0);
3670 if (ch == '\r' || ch == '\n')
3674 if (ch >= ord('1') && ch <= ord('9')) {
3675 argc1 = ksh_numdig(ch);
3679 curcmd[cmdlen++] = ch;
3680 state = nextstate(ch);
3681 if (state == VSEARCH) {
3685 if (putbuf(ch == '/' ? "/" : "?", 1,
3690 if (state == VVERSION) {
3695 strlen(KSH_VERSION), false);
3704 del_range(vs->cursor, vs->cursor + 1);
3707 vs->cbuf[vs->cursor++] = ch;
3719 if (ksh_isdigit(ch))
3720 argc1 = argc1 * 10 + ksh_numdig(ch);
3722 curcmd[cmdlen++] = ch;
3723 state = nextstate(ch);
3729 if (ch >= ord('1') && ch <= ord('9')) {
3730 argc2 = ksh_numdig(ch);
3734 curcmd[cmdlen++] = ch;
3735 if (ch == curcmd[0])
3737 else if (is_move(ch))
3738 state = nextstate(ch);
3745 if (ksh_isdigit(ch))
3746 argc2 = argc2 * 10 + ksh_numdig(ch);
3752 curcmd[cmdlen++] = ch;
3753 if (ch == curcmd[0])
3755 else if (is_move(ch))
3756 state = nextstate(ch);
3763 if (ch == CTRL('['))
3766 curcmd[cmdlen++] = ch;
3772 if (ch == '\r' || ch == '\n' /*|| ch == CTRL('[')*/ ) {
3774 /* Repeat last search? */
3783 locpat[srchlen] = '\0';
3784 memcpy(srchpat, locpat, srchlen + 1);
3787 } else if (isched(ch, edchars.erase) || ch == CTRL('h')) {
3790 vs->linelen -= char_len(locpat[srchlen]);
3791 vs->cursor = vs->linelen;
3798 } else if (isched(ch, edchars.kill)) {
3804 } else if (isched(ch, edchars.werase)) {
3806 struct edstate new_es, *save_es;
3808 new_es.cursor = srchlen;
3809 new_es.cbuf = locpat;
3816 i = (unsigned)srchlen;
3818 vs->linelen -= char_len(locpat[i]);
3820 vs->cursor = vs->linelen;
3824 if (srchlen == SRCHLEN - 1)
3827 locpat[srchlen++] = ch;
3828 if (ISCTRL(ch) && /* but not C1 */ ch < 0x80) {
3829 if ((size_t)vs->linelen + 2 >
3830 (size_t)vs->cbufsize)
3832 vs->cbuf[vs->linelen++] = '^';
3833 vs->cbuf[vs->linelen++] = UNCTRL(ch);
3835 if (vs->linelen >= vs->cbufsize)
3837 vs->cbuf[vs->linelen++] = ch;
3839 vs->cursor = vs->linelen;
3851 /* the cursor may not be at the BOL */
3854 /* nor further in the line than we can search for */
3855 if ((size_t)vs->cursor >= sizeof(srchpat) - 1)
3856 vs->cursor = sizeof(srchpat) - 2;
3857 /* anchor the search pattern */
3859 /* take the current line up to the cursor */
3860 memmove(srchpat + 1, vs->cbuf, vs->cursor);
3861 srchpat[vs->cursor + 1] = '\0';
3862 /* set a magic flag */
3863 argc1 = 2 + (int)vs->cursor;
3864 /* and emulate a backwards history search */
3876 switch (vi_cmd(argc1, curcmd)) {
3884 refresh(insert != 0);
3890 /* back from a 'v' command - don't redraw the screen */
3899 switch (vi_cmd(lastac, lastcmd)) {
3906 if (lastcmd[0] == 's' || lastcmd[0] == 'c' ||
3907 lastcmd[0] == 'C') {
3908 if (redo_insert(1) != 0)
3911 if (redo_insert(lastac) != 0)
3921 /* back from a 'v' command - can't happen */
3939 else if (is_srch(ch))
3941 else if (is_long(ch))
3945 else if (ch == CTRL('v'))
3947 else if (is_cmd(ch))
3958 if (isched(ch, edchars.erase) || ch == CTRL('h')) {
3959 if (insert == REPLACE) {
3960 if (vs->cursor == undo->cursor) {
3967 if (vs->cursor >= undo->linelen)
3970 vs->cbuf[vs->cursor] = undo->cbuf[vs->cursor];
3972 if (vs->cursor == 0)
3978 memmove(&vs->cbuf[vs->cursor], &vs->cbuf[vs->cursor + 1],
3979 vs->linelen - vs->cursor + 1);
3984 if (isched(ch, edchars.kill)) {
3985 if (vs->cursor != 0) {
3987 memmove(vs->cbuf, &vs->cbuf[vs->cursor],
3988 vs->linelen - vs->cursor);
3989 vs->linelen -= vs->cursor;
3995 if (isched(ch, edchars.werase)) {
3996 if (vs->cursor != 0) {
3997 tcursor = backword(1);
3998 memmove(&vs->cbuf[tcursor], &vs->cbuf[vs->cursor],
3999 vs->linelen - vs->cursor);
4000 vs->linelen -= vs->cursor - tcursor;
4001 if (inslen < vs->cursor - tcursor)
4004 inslen -= vs->cursor - tcursor;
4005 vs->cursor = tcursor;
4011 * If any chars are entered before escape, trash the saved insert
4012 * buffer (if user inserts & deletes char, ibuf gets trashed and
4013 * we don't want to use it)
4015 if (first_insert && ch != CTRL('['))
4028 first_insert = false;
4030 inslen = saved_inslen;
4031 return (redo_insert(0));
4036 if (lastcmd[0] == 's' || lastcmd[0] == 'c' ||
4038 return (redo_insert(0));
4040 return (redo_insert(lastac - 1));
4042 /* { start nonstandard vi commands */
4048 complete_word(0, 0);
4052 print_expansions(vs, 0);
4056 if (Flag(FVITABCOMPLETE)) {
4057 complete_word(0, 0);
4061 /* end nonstandard vi commands } */
4064 if (vs->linelen >= vs->cbufsize - 1)
4066 ibuf[inslen++] = ch;
4067 if (insert == INSERT) {
4068 memmove(&vs->cbuf[vs->cursor + 1], &vs->cbuf[vs->cursor],
4069 vs->linelen - vs->cursor);
4072 vs->cbuf[vs->cursor++] = ch;
4073 if (insert == REPLACE && vs->cursor > vs->linelen)
4081 vi_cmd(int argcnt, const char *cmd)
4084 int cur, c1, c2, c3 = 0;
4088 if (argcnt == 0 && !is_zerocount(*cmd))
4091 if (is_move(*cmd)) {
4092 if ((cur = domove(argcnt, cmd, 0)) >= 0) {
4093 if (cur == vs->linelen && cur != 0)
4099 /* Don't save state in middle of macro.. */
4100 if (is_undoable(*cmd) && !macro.p) {
4101 undo->winleft = vs->winleft;
4102 memmove(undo->cbuf, vs->cbuf, vs->linelen);
4103 undo->linelen = vs->linelen;
4104 undo->cursor = vs->cursor;
4106 memmove(lastcmd, cmd, MAXVICMD);
4117 static char alias[] = "_\0";
4122 /* lookup letter in alias list... */
4124 ap = ktsearch(&aliases, alias, hash(alias));
4125 if (!cmd[1] || !ap || !(ap->flag & ISSET))
4127 /* check if this is a recursive call... */
4128 if ((p = (char *)macro.p))
4129 while ((p = strnul(p)) && p[1])
4132 /* insert alias into macro buffer */
4133 nlen = strlen(ap->val.s) + 1;
4134 olen = !macro.p ? 2 :
4135 macro.len - (macro.p - macro.buf);
4137 * at this point, it's fairly reasonable that
4138 * nlen + olen + 2 doesn't overflow
4140 nbuf = alloc(nlen + 1 + olen, AEDIT);
4141 memcpy(nbuf, ap->val.s, nlen);
4142 nbuf[nlen++] = cmd[1];
4144 memcpy(nbuf + nlen, macro.p, olen);
4145 afree(macro.buf, AEDIT);
4148 nbuf[nlen++] = '\0';
4149 nbuf[nlen++] = '\0';
4151 macro.p = macro.buf = (unsigned char *)nbuf;
4159 if (vs->linelen != 0)
4168 vs->cursor = vs->linelen;
4173 vs->cursor = domove(1, "^", 1);
4174 del_range(vs->cursor, vs->linelen);
4188 if (*cmd == cmd[1]) {
4189 c1 = *cmd == 'c' ? domove(1, "^", 1) : 0;
4191 } else if (!is_move(cmd[1]))
4194 if ((ncursor = domove(argcnt, &cmd[1], 1)) < 0)
4197 (cmd[1] == 'w' || cmd[1] == 'W') &&
4198 !ksh_isspace(vs->cbuf[vs->cursor])) {
4201 } while (ksh_isspace(vs->cbuf[ncursor]));
4204 if (ncursor > vs->cursor) {
4214 if (*cmd != 'c' && c1 != c2)
4230 if (vs->linelen != 0)
4232 while (putbuf(ybuf, yanklen, false) == 0 &&
4235 if (vs->cursor != 0)
4245 while (putbuf(ybuf, yanklen, false) == 0 &&
4248 if (any && vs->cursor != 0)
4257 del_range(vs->cursor, vs->linelen);
4262 yank_range(vs->cursor, vs->linelen);
4263 del_range(vs->cursor, vs->linelen);
4264 if (vs->cursor != 0)
4276 argcnt = hlast - (source->line - argcnt);
4277 if (grabhist(modified, argcnt - 1) < 0)
4294 vs->cursor = domove(1, "^", 1);
4301 if (grabhist(modified, hnum + argcnt) < 0)
4312 if (grabhist(modified, hnum - argcnt) < 0)
4321 if (vs->linelen == 0)
4330 if (vs->cursor + argcnt > vs->linelen)
4332 for (n = 0; n < argcnt; ++n)
4333 vs->cbuf[vs->cursor + n] = cmd[1];
4334 vs->cursor += n - 1;
4345 if (vs->linelen == 0)
4349 if (vs->cursor + argcnt > vs->linelen)
4350 argcnt = vs->linelen - vs->cursor;
4351 del_range(vs->cursor, vs->cursor + argcnt);
4357 if (vs->linelen == 0)
4360 vs->cbuf[vs->linelen] = '\0';
4361 histsave(&source->line, vs->cbuf,
4364 argcnt = source->line + 1 -
4368 shf_snprintf(vs->cbuf, vs->cbufsize, Tf_sd,
4369 "fc -e ${VISUAL:-${EDITOR:-vi}} --",
4373 "fc -e ${VISUAL:-${EDITOR:-vi}} --",
4375 vs->linelen = strlen(vs->cbuf);
4379 if (vs->linelen == 0)
4383 if (vs->cursor + argcnt > vs->linelen)
4384 argcnt = vs->linelen - vs->cursor;
4385 yank_range(vs->cursor, vs->cursor + argcnt);
4386 del_range(vs->cursor, vs->cursor + argcnt);
4390 if (vs->cursor > 0) {
4393 if (vs->cursor < argcnt)
4394 argcnt = vs->cursor;
4395 yank_range(vs->cursor - argcnt, vs->cursor);
4396 del_range(vs->cursor - argcnt, vs->cursor);
4397 vs->cursor -= argcnt;
4411 if (grabhist(modified, ohnum) < 0)
4430 if (lastsearch == ' ')
4432 if (lastsearch == '?')
4438 if ((c2 = grabsearch(modified, hnum,
4439 c1, srchpat)) < 0) {
4451 /* flag from cursor-up command */
4452 vs->cursor = argcnt - 2;
4461 if (histnum(-1) < 0)
4464 #define issp(c) (ksh_isspace(c) || (c) == '\n')
4466 while (*p && issp(*p))
4468 while (*p && --argcnt) {
4469 while (*p && !issp(*p))
4471 while (*p && issp(*p))
4493 if (vs->cursor != vs->linelen)
4495 while (*p && !issp(*p)) {
4499 if (putbuf(T1space, 1, false) != 0 ||
4500 putbuf(sp, argcnt, false) != 0) {
4501 if (vs->cursor != 0)
4514 if (vs->linelen == 0)
4516 for (i = 0; i < argcnt; i++) {
4517 p = &vs->cbuf[vs->cursor];
4518 if (ksh_islower(*p)) {
4521 *p = ksh_toupper(*p);
4522 } else if (ksh_isupper(*p)) {
4525 *p = ksh_tolower(*p);
4527 if (vs->cursor < vs->linelen - 1)
4535 int ret = x_do_comment(vs->cbuf, vs->cbufsize,
4544 /* Nonstandard vi/ksh */
4546 print_expansions(vs, 1);
4550 /* Nonstandard vi/ksh */
4552 if (!Flag(FVITABCOMPLETE))
4554 complete_word(1, argcnt);
4557 /* some annoying AT&T kshs */
4559 if (!Flag(FVIESCCOMPLETE))
4564 /* Nonstandard vi/ksh */
4566 complete_word(1, argcnt);
4572 /* Nonstandard vi/ksh */
4578 /* mksh: cursor movement */
4582 if (vs->linelen != 0)
4587 if (insert == 0 && vs->cursor != 0 && vs->cursor >= vs->linelen)
4594 domove(int argcnt, const char *cmd, int sub)
4596 int ncursor = 0, i = 0, t;
4597 unsigned int bcount;
4601 if (!sub && vs->cursor == 0)
4603 ncursor = backword(argcnt);
4607 if (!sub && vs->cursor == 0)
4609 ncursor = Backword(argcnt);
4613 if (!sub && vs->cursor + 1 >= vs->linelen)
4615 ncursor = endword(argcnt);
4616 if (sub && ncursor < vs->linelen)
4621 if (!sub && vs->cursor + 1 >= vs->linelen)
4623 ncursor = Endword(argcnt);
4624 if (sub && ncursor < vs->linelen)
4637 if (fsavecmd == ' ')
4639 i = fsavecmd == 'f' || fsavecmd == 'F';
4643 if ((ncursor = findch(fsavech, argcnt, tobool(t),
4652 if (!sub && vs->cursor == 0)
4654 ncursor = vs->cursor - argcnt;
4661 if (!sub && vs->cursor + 1 >= vs->linelen)
4663 if (vs->linelen != 0) {
4664 ncursor = vs->cursor + argcnt;
4665 if (ncursor > vs->linelen)
4666 ncursor = vs->linelen;
4671 if (!sub && vs->cursor + 1 >= vs->linelen)
4673 ncursor = forwword(argcnt);
4677 if (!sub && vs->cursor + 1 >= vs->linelen)
4679 ncursor = Forwword(argcnt);
4688 while (ncursor < vs->linelen - 1 &&
4689 ksh_isspace(vs->cbuf[ncursor]))
4695 if (ncursor > vs->linelen)
4696 ncursor = vs->linelen;
4702 if (vs->linelen != 0)
4703 ncursor = vs->linelen;
4709 ncursor = vs->cursor;
4710 while (ncursor < vs->linelen &&
4711 (i = bracktype(vs->cbuf[ncursor])) == 0)
4713 if (ncursor == vs->linelen)
4718 if (++ncursor >= vs->linelen)
4724 t = bracktype(vs->cbuf[ncursor]);
4729 } while (bcount != 0);
4741 redo_insert(int count)
4744 if (putbuf(ibuf, inslen, tobool(insert == REPLACE)) != 0)
4753 yank_range(int a, int b)
4757 memmove(ybuf, &vs->cbuf[a], yanklen);
4789 * Non user interface editor routines below here
4795 memmove(holdbufp, vs->cbuf, vs->linelen);
4796 holdlen = vs->linelen;
4797 holdbufp[holdlen] = '\0';
4804 vs->linelen = holdlen;
4805 memmove(vs->cbuf, holdbufp, holdlen);
4808 /* return a new edstate */
4809 static struct edstate *
4810 save_edstate(struct edstate *old)
4812 struct edstate *news;
4814 news = alloc(sizeof(struct edstate), AEDIT);
4815 news->cbuf = alloc(old->cbufsize, AEDIT);
4816 memcpy(news->cbuf, old->cbuf, old->linelen);
4817 news->cbufsize = old->cbufsize;
4818 news->linelen = old->linelen;
4819 news->cursor = old->cursor;
4820 news->winleft = old->winleft;
4825 restore_edstate(struct edstate *news, struct edstate *old)
4827 memcpy(news->cbuf, old->cbuf, old->linelen);
4828 news->linelen = old->linelen;
4829 news->cursor = old->cursor;
4830 news->winleft = old->winleft;
4835 free_edstate(struct edstate *old)
4837 afree(old->cbuf, AEDIT);
4842 * this is used for calling x_escape() in complete_word()
4845 x_vi_putbuf(const char *s, size_t len)
4847 return (putbuf(s, len, false));
4851 putbuf(const char *buf, ssize_t len, bool repl)
4856 if (vs->cursor + len >= vs->cbufsize)
4858 if (vs->cursor + len > vs->linelen)
4859 vs->linelen = vs->cursor + len;
4861 if (vs->linelen + len >= vs->cbufsize)
4863 memmove(&vs->cbuf[vs->cursor + len], &vs->cbuf[vs->cursor],
4864 vs->linelen - vs->cursor);
4867 memmove(&vs->cbuf[vs->cursor], buf, len);
4873 del_range(int a, int b)
4875 if (vs->linelen != b)
4876 memmove(&vs->cbuf[a], &vs->cbuf[b], vs->linelen - b);
4877 vs->linelen -= b - a;
4881 findch(int ch, int cnt, bool forw, bool incl)
4885 if (vs->linelen == 0)
4887 ncursor = vs->cursor;
4891 if (++ncursor == vs->linelen)
4897 } while (vs->cbuf[ncursor] != ch);
4909 forwword(int argcnt)
4913 ncursor = vs->cursor;
4914 while (ncursor < vs->linelen && argcnt--) {
4915 if (ksh_isalnux(vs->cbuf[ncursor]))
4916 while (ncursor < vs->linelen &&
4917 ksh_isalnux(vs->cbuf[ncursor]))
4919 else if (!ksh_isspace(vs->cbuf[ncursor]))
4920 while (ncursor < vs->linelen &&
4921 !ksh_isalnux(vs->cbuf[ncursor]) &&
4922 !ksh_isspace(vs->cbuf[ncursor]))
4924 while (ncursor < vs->linelen &&
4925 ksh_isspace(vs->cbuf[ncursor]))
4932 backword(int argcnt)
4936 ncursor = vs->cursor;
4937 while (ncursor > 0 && argcnt--) {
4938 while (--ncursor > 0 && ksh_isspace(vs->cbuf[ncursor]))
4941 if (ksh_isalnux(vs->cbuf[ncursor]))
4942 while (--ncursor >= 0 &&
4943 ksh_isalnux(vs->cbuf[ncursor]))
4946 while (--ncursor >= 0 &&
4947 !ksh_isalnux(vs->cbuf[ncursor]) &&
4948 !ksh_isspace(vs->cbuf[ncursor]))
4961 ncursor = vs->cursor;
4962 while (ncursor < vs->linelen && argcnt--) {
4963 while (++ncursor < vs->linelen - 1 &&
4964 ksh_isspace(vs->cbuf[ncursor]))
4966 if (ncursor < vs->linelen - 1) {
4967 if (ksh_isalnux(vs->cbuf[ncursor]))
4968 while (++ncursor < vs->linelen &&
4969 ksh_isalnux(vs->cbuf[ncursor]))
4972 while (++ncursor < vs->linelen &&
4973 !ksh_isalnux(vs->cbuf[ncursor]) &&
4974 !ksh_isspace(vs->cbuf[ncursor]))
4983 Forwword(int argcnt)
4987 ncursor = vs->cursor;
4988 while (ncursor < vs->linelen && argcnt--) {
4989 while (ncursor < vs->linelen &&
4990 !ksh_isspace(vs->cbuf[ncursor]))
4992 while (ncursor < vs->linelen &&
4993 ksh_isspace(vs->cbuf[ncursor]))
5000 Backword(int argcnt)
5004 ncursor = vs->cursor;
5005 while (ncursor > 0 && argcnt--) {
5006 while (--ncursor >= 0 && ksh_isspace(vs->cbuf[ncursor]))
5008 while (ncursor >= 0 && !ksh_isspace(vs->cbuf[ncursor]))
5020 ncursor = vs->cursor;
5021 while (ncursor < vs->linelen - 1 && argcnt--) {
5022 while (++ncursor < vs->linelen - 1 &&
5023 ksh_isspace(vs->cbuf[ncursor]))
5025 if (ncursor < vs->linelen - 1) {
5026 while (++ncursor < vs->linelen &&
5027 !ksh_isspace(vs->cbuf[ncursor]))
5036 grabhist(int save, int n)
5040 if (n < 0 || n > hlast)
5048 if ((hptr = *histpos()) == NULL) {
5049 internal_warningf("grabhist: bad history array");
5054 if ((vs->linelen = strlen(hptr)) >= vs->cbufsize)
5055 vs->linelen = vs->cbufsize - 1;
5056 memmove(vs->cbuf, hptr, vs->linelen);
5063 grabsearch(int save, int start, int fwd, const char *pat)
5069 if ((start == 0 && fwd == 0) || (start >= hlast - 1 && fwd == 1))
5075 anchored = *pat == '^' ? (++pat, true) : false;
5076 if ((hist = findhist(start, fwd, pat, anchored)) < 0) {
5077 /* (start != 0 && fwd && match(holdbufp, pat) >= 0) */
5078 if (start != 0 && fwd && strcmp(holdbufp, pat) >= 0) {
5088 if ((vs->linelen = strlen(hptr)) >= vs->cbufsize)
5089 vs->linelen = vs->cbufsize - 1;
5090 memmove(vs->cbuf, hptr, vs->linelen);
5096 redraw_line(bool newl)
5099 memset(wbuf[win], ' ', wbuf_len);
5109 refresh(int leftside)
5117 display(wbuf[1 - win], wbuf[win], leftside);
5126 if (vs->cursor < vs->winleft)
5130 while (cur < vs->cursor)
5131 col = newcol((unsigned char)vs->cbuf[cur++], col);
5132 if (col >= winwidth)
5141 int holdcur1, holdcol1;
5142 int holdcur2, holdcol2;
5144 holdcur1 = holdcur2 = tcur = 0;
5145 holdcol1 = holdcol2 = tcol = 0;
5146 while (tcur < vs->cursor) {
5147 if (tcol - holdcol2 > winwidth / 2) {
5148 holdcur1 = holdcur2;
5149 holdcol1 = holdcol2;
5153 tcol = newcol((unsigned char)vs->cbuf[tcur++], tcol);
5155 while (tcol - holdcol1 > winwidth / 2)
5156 holdcol1 = newcol((unsigned char)vs->cbuf[holdcur1++],
5158 vs->winleft = holdcur1;
5162 newcol(unsigned char ch, int col)
5165 return ((col | 7) + 1);
5166 return (col + char_len(ch));
5170 display(char *wb1, char *wb2, int leftside)
5173 char *twb1, *twb2, mc;
5182 while (col < winwidth && cur < vs->linelen) {
5183 if (cur == vs->cursor && leftside)
5184 ncol = col + pwidth;
5185 if ((ch = vs->cbuf[cur]) == '\t')
5188 } while (++col < winwidth && (col & 7) != 0);
5189 else if (col < winwidth) {
5190 if (ISCTRL(ch) && /* but not C1 */ ch < 0x80) {
5192 if (++col < winwidth) {
5193 *twb1++ = UNCTRL(ch);
5201 if (cur == vs->cursor && !leftside)
5202 ncol = col + pwidth - 1;
5205 if (cur == vs->cursor)
5206 ncol = col + pwidth;
5207 if (col < winwidth) {
5208 while (col < winwidth) {
5221 if (*twb1 != *twb2) {
5223 ed_mov_opt(col, wb1);
5231 if (vs->winleft > 0 && moreright)
5233 * POSIX says to use * for this but that is a globbing
5234 * character and may confuse people; + is more innocuous
5237 else if (vs->winleft > 0)
5244 ed_mov_opt(pwidth + winwidth + 1, wb1);
5250 ed_mov_opt(ncol, wb1);
5254 ed_mov_opt(int col, char *wb)
5257 if (col + 1 < x_col - col) {
5260 while (x_col++ < col)
5263 while (x_col-- > col)
5267 wb = &wb[x_col - pwidth];
5268 while (x_col++ < col)
5275 /* replace word with all expansions (ie, expand word*) */
5277 expand_word(int cmd)
5279 static struct edstate *buf;
5280 int rval = 0, nwords, start, end, i;
5283 /* Undo previous expansion */
5284 if (cmd == 0 && expanded == EXPAND && buf) {
5285 restore_edstate(vs, buf);
5295 i = XCF_COMMAND_FILE | XCF_FULLPATH;
5296 nwords = x_cf_glob(&i, vs->cbuf, vs->linelen, vs->cursor,
5297 &start, &end, &words);
5303 buf = save_edstate(vs);
5305 del_range(start, end);
5308 while (i < nwords) {
5309 if (x_escape(words[i], strlen(words[i]), x_vi_putbuf) != 0) {
5313 if (++i < nwords && putbuf(T1space, 1, false) != 0) {
5318 i = buf->cursor - end;
5319 if (rval == 0 && i > 0)
5330 complete_word(int cmd, int count)
5332 static struct edstate *buf;
5333 int rval, nwords, start, end, flags;
5339 /* Undo previous completion */
5340 if (cmd == 0 && expanded == COMPLETE && buf) {
5341 print_expansions(buf, 0);
5345 if (cmd == 0 && expanded == PRINT && buf) {
5346 restore_edstate(vs, buf);
5357 * XCF_FULLPATH for count 'cause the menu printed by
5358 * print_expansions() was done this way.
5360 flags = XCF_COMMAND_FILE;
5362 flags |= XCF_FULLPATH;
5363 nwords = x_cf_glob(&flags, vs->cbuf, vs->linelen, vs->cursor,
5364 &start, &end, &words);
5373 if (count >= nwords) {
5375 x_print_expansions(nwords, words,
5376 tobool(flags & XCF_IS_COMMAND));
5377 x_free_words(nwords, words);
5382 * Expand the count'th word to its basename
5384 if (flags & XCF_IS_COMMAND) {
5385 match = words[count] +
5386 x_basename(words[count], NULL);
5387 /* If more than one possible match, use full path */
5388 for (i = 0; i < nwords; i++)
5390 strcmp(words[i] + x_basename(words[i],
5391 NULL), match) == 0) {
5392 match = words[count];
5396 match = words[count];
5397 match_len = strlen(match);
5399 /* expanded = PRINT; next call undo */
5402 match_len = x_longest_prefix(nwords, words);
5403 /* next call will list completions */
5404 expanded = COMPLETE;
5405 is_unique = nwords == 1;
5408 buf = save_edstate(vs);
5409 del_range(start, end);
5413 * escape all shell-sensitive characters and put the result into
5416 rval = x_escape(match, match_len, x_vi_putbuf);
5418 if (rval == 0 && is_unique) {
5420 * If exact match, don't undo. Allows directory completions
5421 * to be used (ie, complete the next portion of the path).
5426 * append a space if this is a non-directory match
5427 * and not a parameter or homedir substitution
5429 if (match_len > 0 && !mksh_cdirsep(match[match_len - 1]) &&
5430 !(flags & XCF_IS_NOSPACE))
5431 rval = putbuf(T1space, 1, false);
5433 x_free_words(nwords, words);
5438 /* prevent this from being redone... */
5446 print_expansions(struct edstate *est, int cmd MKSH_A_UNUSED)
5448 int start, end, nwords, i;
5451 i = XCF_COMMAND_FILE | XCF_FULLPATH;
5452 nwords = x_cf_glob(&i, est->cbuf, est->linelen, est->cursor,
5453 &start, &end, &words);
5458 x_print_expansions(nwords, words, tobool(i & XCF_IS_COMMAND));
5459 x_free_words(nwords, words);
5464 /* Similar to x_zotc(emacs.c), but no tab weirdness */
5478 /* Beem out of any macros as soon as an error occurs */
5485 vi_macro_reset(void)
5488 afree(macro.buf, AEDIT);
5489 memset((char *)¯o, 0, sizeof(macro));
5492 #endif /* !MKSH_S_NOVI */
5494 /* called from main.c */
5501 * set edchars to force initial binding, except we need
5502 * default values for ^W for some deficient systems…
5504 edchars.erase = edchars.kill = edchars.intr = edchars.quit =
5505 edchars.eof = EDCHAR_INITIAL;
5506 edchars.werase = 027;
5508 /* command line editing specific memory allocation */
5510 holdbufp = alloc(LINE, AEDIT);
5512 /* initialise Emacs command line editing mode */
5515 x_tab = alloc2(X_NTABS, sizeof(*x_tab), AEDIT);
5516 for (j = 0; j < X_TABSZ; j++)
5517 x_tab[0][j] = XFUNC_insert;
5518 for (i = 1; i < X_NTABS; i++)
5519 for (j = 0; j < X_TABSZ; j++)
5520 x_tab[i][j] = XFUNC_error;
5521 for (i = 0; i < (int)NELEM(x_defbindings); i++)
5522 x_tab[x_defbindings[i].xdb_tab][x_defbindings[i].xdb_char]
5523 = x_defbindings[i].xdb_func;
5526 x_atab = alloc2(X_NTABS, sizeof(*x_atab), AEDIT);
5527 for (i = 1; i < X_NTABS; i++)
5528 for (j = 0; j < X_TABSZ; j++)
5529 x_atab[i][j] = NULL;
5543 x_initterm(const char *termtype)
5545 /* default must be 0 (bss) */
5547 /* this is what tmux uses, don't ask me about it */
5548 if (!strcmp(termtype, "screen") || !strncmp(termtype, "screen-", 7))
5554 x_eval_region_helper(const char *cmd, size_t len)
5559 if (!kshsetjmp(e->jbuf)) {
5560 char *wds = alloc(len + 3, ATEMP);
5563 memcpy(wds + 1, cmd, len);
5564 wds[len + 1] = '\0';
5567 cp = evalstr(wds, DOSCALAR);
5569 strdupx(cp, cp, AEDIT);
5577 x_eval_region(int c MKSH_A_UNUSED)
5579 char *evbeg, *evend, *cp;
5581 /* only for LINE overflow checking */
5587 } else if (xmp < xcp) {
5596 x_clrtoeol(' ', false);
5599 cp = x_eval_region_helper(evbeg, evend - evbeg);
5603 /* command cannot be parsed */
5610 newlen = strlen(cp);
5611 restlen = xep - evend;
5612 /* check for LINE overflow, until this is dynamically allocated */
5613 if (evbeg + newlen + restlen >= xend)
5614 goto x_eval_region_err;
5617 xcp = evbeg + newlen;
5618 xep = xcp + restlen;
5619 memmove(xcp, evend, restlen + /* NUL */ 1);
5620 memcpy(xmp, cp, newlen);
5626 #endif /* !MKSH_SMALL */
5627 #endif /* !MKSH_NO_CMDLINE_EDITING */