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
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.306 2016/08/01 18:42:40 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))
151 while ((n = blocking_read(STDIN_FILENO, &c, 1)) < 0 && errno == EINTR)
158 if (x_cols != xx_cols && editmode == 1) {
159 /* redraw line in Emacs mode */
161 x_init_prompt(false);
168 return ((n == 1) ? (int)(unsigned char)c : -1);
174 shf_putc(c, shl_out);
177 /*********************************
178 * Misc common code for vi/emacs *
179 *********************************/
182 * Handle the commenting/uncommenting of a line.
184 * 1 if a carriage return is indicated (comment added)
185 * 0 if no return (comment removed)
186 * -1 if there is an error (not enough room for comment chars)
187 * If successful, *lenp contains the new length. Note: cursor should be
188 * moved to the start of the line after (un)commenting.
191 x_do_comment(char *buf, ssize_t bsize, ssize_t *lenp)
193 ssize_t i, j, len = *lenp;
196 /* somewhat arbitrary - it's what AT&T ksh does */
199 /* Already commented? */
203 for (j = 0, i = 1; i < len; i++) {
204 if (!saw_nl || buf[i] != '#')
206 saw_nl = buf[i] == '\n';
213 /* See if there's room for the #s - 1 per \n */
214 for (i = 0; i < len; i++)
217 if (len + n >= bsize)
219 /* Now add them... */
220 for (i = len, j = len + n; --i >= 0; ) {
231 /****************************************************
232 * Common file/command completion code for vi/emacs *
233 ****************************************************/
236 x_print_expansions(int nwords, char * const *words, bool is_command)
238 bool use_copy = false;
240 XPtrV l = { NULL, 0, 0 };
243 * Check if all matches are in the same directory (in this
244 * case, we want to omit the directory name)
247 (prefix_len = x_longest_prefix(nwords, words)) > 0) {
250 /* Special case for 1 match (prefix is whole word) */
252 prefix_len = x_basename(words[0], NULL);
253 /* Any (non-trailing) slashes in non-common word suffixes? */
254 for (i = 0; i < nwords; i++)
255 if (x_basename(words[i] + prefix_len, NULL) >
258 /* All in same directory? */
260 while (prefix_len > 0 && words[0][prefix_len - 1] != '/')
263 XPinit(l, nwords + 1);
264 for (i = 0; i < nwords; i++)
265 XPput(l, words[i] + prefix_len);
270 * Enumerate expansions
274 pr_list(use_copy ? (char **)XPptrv(l) : words);
277 /* not x_free_words() */
282 * Convert backslash-escaped string to QCHAR-escaped
283 * string useful for globbing; loses QCHAR unless it
284 * can squeeze in, eg. by previous loss of backslash
287 x_glob_hlp_add_qchar(char *cp)
290 bool escaping = false;
292 while ((ch = *cp++)) {
293 if (ch == '\\' && !escaping) {
297 if (escaping || (ch == QCHAR && (cp - dp) > 1)) {
299 * empirically made list of chars to escape
300 * for globbing as well as QCHAR itself
321 * Run tilde expansion on argument string, return the result
322 * after unescaping; if the flag is set, the original string
323 * is freed if changed and assumed backslash-escaped, if not
324 * it is assumed QCHAR-escaped
327 x_glob_hlp_tilde_and_rem_qchar(char *s, bool magic_flag)
332 * On the string, check whether we have a tilde expansion,
333 * and if so, discern "~foo/bar" and "~/baz" from "~blah";
334 * if we have a directory part (the former), try to expand
336 if (*s == '~' && (cp = strchr(s, '/')) != NULL) {
337 /* ok, so split into "~foo"/"bar" or "~"/"baz" */
339 /* try to expand the tilde */
340 if (!(dp = do_tilde(s + 1))) {
341 /* nope, revert damage */
344 /* ok, expand and replace */
345 cp = shf_smprintf(Tf_sSs, dp, cp);
352 /* ... convert it from backslash-escaped via QCHAR-escaped... */
354 x_glob_hlp_add_qchar(s);
355 /* ... to unescaped, for comparison with the matches */
358 while ((ch = *cp++)) {
359 if (ch == QCHAR && !(ch = *cp++))
370 * - does expansion, checks for no match, etc.
371 * - sets *wordsp to array of matching strings
372 * - returns number of matching strings
375 x_file_glob(int *flagsp, char *toglob, char ***wordsp)
380 struct source *s, *sold;
382 /* remove all escaping backward slashes */
383 x_glob_hlp_add_qchar(toglob);
386 * Convert "foo*" (toglob) to an array of strings (words)
389 s = pushs(SWSTR, ATEMP);
390 s->start = s->str = toglob;
392 if (yylex(ONEWORD | LQCHAR) != LWORD) {
394 internal_warningf(Tfg_badsubst);
401 while (*cp == CHAR || *cp == QCHAR)
403 nwords = DOGLOB | DOTILDE | DOMARKDIRS;
405 /* probably a $FOO expansion */
406 *flagsp |= XCF_IS_NOSPACE;
407 /* this always results in at most one match */
410 expand(yylval.cp, &w, nwords);
412 words = (char **)XPclose(w);
414 for (nwords = 0; words[nwords]; nwords++)
419 /* Expand any tilde and drop all QCHAR for comparison */
420 toglob = x_glob_hlp_tilde_and_rem_qchar(toglob, false);
423 * Check if globbing failed (returned glob pattern),
424 * but be careful (e.g. toglob == "ab*" when the file
425 * "ab*" exists is not an error).
426 * Also, check for empty result - happens if we tried
427 * to glob something which evaluated to an empty
428 * string (e.g., "$FOO" when there is no FOO, etc).
430 if ((strcmp(words[0], toglob) == 0 &&
431 stat(words[0], &statb) < 0) ||
432 words[0][0] == '\0') {
433 x_free_words(nwords, words);
439 if ((*wordsp = nwords ? words : NULL) == NULL && words != NULL)
440 x_free_words(nwords, words);
445 /* Data structure used in x_command_glob() */
446 struct path_order_info {
452 /* Compare routine used in x_command_glob() */
454 path_order_cmp(const void *aa, const void *bb)
456 const struct path_order_info *a = (const struct path_order_info *)aa;
457 const struct path_order_info *b = (const struct path_order_info *)bb;
460 if ((t = strcmp(a->word + a->base, b->word + b->base)))
462 if (a->path_order > b->path_order)
464 if (a->path_order < b->path_order)
470 x_command_glob(int flags, char *toglob, char ***wordsp)
477 /* Convert "foo*" (toglob) to a pattern for future use */
478 pat = evalstr(toglob, DOPAT | DOTILDE);
482 glob_table(pat, &w, &keywords);
483 glob_table(pat, &w, &aliases);
484 glob_table(pat, &w, &builtins);
485 for (l = e->loc; l; l = l->next)
486 glob_table(pat, &w, &l->funs);
488 glob_path(flags, pat, &w, path);
489 if ((fpath = str_val(global(TFPATH))) != null)
490 glob_path(flags, pat, &w, fpath);
500 if (flags & XCF_FULLPATH) {
501 /* Sort by basename, then path order */
502 struct path_order_info *info, *last_info = NULL;
503 char **words = (char **)XPptrv(w);
504 size_t i, path_order = 0;
506 info = (struct path_order_info *)
507 alloc2(nwords, sizeof(struct path_order_info), ATEMP);
508 for (i = 0; i < nwords; i++) {
509 info[i].word = words[i];
510 info[i].base = x_basename(words[i], NULL);
511 if (!last_info || info[i].base != last_info->base ||
512 strncmp(words[i], last_info->word, info[i].base) != 0) {
513 last_info = &info[i];
516 info[i].path_order = path_order;
518 qsort(info, nwords, sizeof(struct path_order_info),
520 for (i = 0; i < nwords; i++)
521 words[i] = info[i].word;
524 /* Sort and remove duplicate entries */
525 char **words = (char **)XPptrv(w);
528 qsort(words, nwords, sizeof(void *), xstrcmp);
529 for (i = j = 0; i < nwords - 1; i++) {
530 if (strcmp(words[i], words[i + 1]))
531 words[j++] = words[i];
533 afree(words[i], ATEMP);
535 words[j++] = words[i];
540 *wordsp = (char **)XPclose(w);
545 #define IS_WORDC(c) (!ctype(c, C_LEX1) && (c) != '\'' && (c) != '"' && \
546 (c) != '`' && (c) != '=' && (c) != ':')
549 x_locate_word(const char *buf, int buflen, int pos, int *startp,
554 /* Bad call? Probably should report error */
555 if (pos < 0 || pos > buflen) {
557 *is_commandp = false;
560 /* The case where pos == buflen happens to take care of itself... */
564 * Keep going backwards to start of word (has effect of allowing
565 * one blank after the end of a word)
567 for (; (start > 0 && IS_WORDC(buf[start - 1])) ||
568 (start > 1 && buf[start - 2] == '\\'); start--)
570 /* Go forwards to end of word */
571 for (end = start; end < buflen && IS_WORDC(buf[end]); end++) {
572 if (buf[end] == '\\' && (end + 1) < buflen)
580 /* Figure out if this is a command */
581 while (p >= 0 && ksh_isspace(buf[p]))
583 iscmd = p < 0 || vstrchr(";|&()`", buf[p]);
586 * If command has a /, path, etc. is not searched;
587 * only current directory is searched which is just
588 * like file globbing.
590 for (p = start; p < end; p++)
595 *is_commandp = iscmd;
599 return (end - start);
603 x_cf_glob(int *flagsp, const char *buf, int buflen, int pos, int *startp,
604 int *endp, char ***wordsp)
610 len = x_locate_word(buf, buflen, pos, startp, &is_command);
611 if (!((*flagsp) & XCF_COMMAND))
614 * Don't do command globing on zero length strings - it takes too
615 * long and isn't very useful. File globs are more likely to be
616 * useful, so allow these.
618 if (len == 0 && is_command)
625 * Given a string, copy it and possibly add a '*' to the end.
628 strndupx(toglob, buf + *startp, len + /* the '*' */ 1, ATEMP);
632 * If the pathname contains a wildcard (an unquoted '*',
633 * '?', or '[') or an extglob, then it is globbed based
634 * on that value (i.e., without the appended '*'). Same
635 * for parameter substitutions (as in “cat $HOME/.ss↹”)
636 * without appending a trailing space (LP: #710539), as
637 * well as for “~foo” (but not “~foo/”).
639 for (s = toglob; *s; s++) {
640 if (*s == '\\' && s[1])
642 else if (*s == '?' || *s == '*' || *s == '[' ||
644 /* ?() *() +() @() !() but two already checked */
645 (s[1] == '(' /*)*/ &&
646 (*s == '+' || *s == '@' || *s == '!'))) {
648 * just expand based on the extglob
655 if (*toglob == '~' && !vstrchr(toglob, '/')) {
656 /* neither for '~foo' (but '~foo/bar') */
657 *flagsp |= XCF_IS_NOSPACE;
663 toglob[len + 1] = '\0';
666 * Expand (glob) it now.
669 nwords = is_command ?
670 x_command_glob(*flagsp, toglob, &words) :
671 x_file_glob(flagsp, toglob, &words);
672 afree(toglob, ATEMP);
679 *flagsp |= XCF_IS_COMMAND;
681 *endp = *startp + len;
687 * Find longest common prefix
690 x_longest_prefix(int nwords, char * const * words)
693 size_t j, prefix_len;
699 prefix_len = strlen(words[0]);
700 for (i = 1; i < nwords; i++)
701 for (j = 0, p = words[i]; j < prefix_len; j++)
702 if (p[j] != words[0][j]) {
706 /* false for nwords==1 as 0 = words[0][prefix_len] then */
707 if (UTFMODE && prefix_len && (words[0][prefix_len] & 0xC0) == 0x80)
708 while (prefix_len && (words[0][prefix_len] & 0xC0) != 0xC0)
714 x_free_words(int nwords, char **words)
717 afree(words[--nwords], ATEMP);
722 * Return the offset of the basename of string s (which ends at se - need not
723 * be null terminated). Trailing slashes are ignored. If s is just a slash,
724 * then the offset is 0 (actually, length - 1).
735 x_basename(const char *s, const char *se)
744 /* Skip trailing slashes */
745 for (p = se - 1; p > s && *p == '/'; p--)
747 for (; p > s && *p != '/'; p--)
749 if (*p == '/' && p + 1 < se)
756 * Apply pattern matching to a table: all table entries that match a pattern
760 glob_table(const char *pat, XPtrV *wp, struct table *tp)
766 while ((te = ktnext(&ts)))
767 if (gmatchx(te->name, pat, false)) {
770 strdupx(cp, te->name, ATEMP);
776 glob_path(int flags, const char *pat, XPtrV *wp, const char *lpath)
778 const char *sp = lpath, *p;
780 size_t pathlen, patlen, oldsize, newsize, i, j;
783 patlen = strlen(pat);
784 checkoktoadd(patlen, 129 + X_EXTRA);
786 Xinit(xs, xp, patlen + 128, ATEMP);
788 xp = Xstring(xs, xp);
789 if (!(p = cstrchr(sp, MKSH_PATHSEPC)))
794 * Copy sp into xp, stuffing any MAGIC characters
799 XcheckN(xs, xp, pathlen * 2);
809 XcheckN(xs, xp, patlen);
810 memcpy(xp, pat, patlen);
812 oldsize = XPsize(*wp);
814 glob_str(Xstring(xs, xp), wp, true);
815 newsize = XPsize(*wp);
817 /* Check that each match is executable... */
818 words = (char **)XPptrv(*wp);
819 for (i = j = oldsize; i < newsize; i++) {
820 if (ksh_access(words[i], X_OK) == 0) {
822 if (!(flags & XCF_FULLPATH))
823 memmove(words[j], words[j] + pathlen,
824 strlen(words[j] + pathlen) + 1);
827 afree(words[i], ATEMP);
838 * if argument string contains any special characters, they will
839 * be escaped and the result will be put into edit buffer by
840 * keybinding-specific function
843 x_escape(const char *s, size_t len, int (*putbuf_func)(const char *, size_t))
845 size_t add = 0, wlen = len;
848 while (wlen - add > 0)
849 if (vstrchr("\"#$&'()*:;<=>?[\\`{|}", s[add]) ||
850 ctype(s[add], C_IFS)) {
851 if (putbuf_func(s, add) != 0) {
855 putbuf_func(s[add] == '\n' ? "'" : "\\", 1);
856 putbuf_func(&s[add], 1);
866 if (wlen > 0 && rval == 0)
867 rval = putbuf_func(s, wlen);
873 /* +++ emacs editing mode +++ */
876 #define AEDIT &aedit /* area for kill ring and macro defns */
878 /* values returned by keyboard functions */
880 #define KEOL 1 /* ^M, ^J */
881 #define KINTR 2 /* ^G, ^C */
884 int (*xf_func)(int c);
889 struct x_defbindings {
890 unsigned char xdb_func; /* XFUNC_* */
891 unsigned char xdb_tab;
892 unsigned char xdb_char;
895 #define XF_ARG 1 /* command takes number prefix */
896 #define XF_NOBIND 2 /* not allowed to bind to function */
897 #define XF_PREFIX 4 /* function sets prefix */
899 /* Separator for completion */
900 #define is_cfs(c) ((c) == ' ' || (c) == '\t' || (c) == '"' || (c) == '\'')
901 /* Separator for motion */
902 #define is_mfs(c) (!(ksh_isalnux(c) || (c) == '$' || ((c) & 0x80)))
904 #define X_NTABS 4 /* normal, meta1, meta2, pc */
905 #define X_TABSZ 256 /* size of keydef tables etc */
908 * Arguments for do_complete()
909 * 0 = enumerate M-= complete as much as possible and then list
914 CT_LIST, /* list the possible completions */
915 CT_COMPLETE, /* complete to longest prefix */
916 CT_COMPLIST /* complete and then list (if non-exact) */
920 * The following are used for my horizontal scrolling stuff
922 static char *xbuf; /* beg input buffer */
923 static char *xend; /* end input buffer */
924 static char *xcp; /* current position */
925 static char *xep; /* current end */
926 static char *xbp; /* start of visible portion of input buffer */
927 static char *xlp; /* last char visible on screen */
928 static bool x_adj_ok;
930 * we use x_adj_done so that functions can tell
931 * whether x_adjust() has been called while they are active.
933 static int x_adj_done; /* is incremented by x_adjust() */
935 static int x_displen;
936 static int x_arg; /* general purpose arg */
937 static bool x_arg_defaulted; /* x_arg not explicitly set; defaulted to 1 */
939 static bool xlp_valid; /* lastvis pointer was recalculated */
941 static char **x_histp; /* history position */
942 static int x_nextcmd; /* for newline-and-next */
943 static char **x_histncp; /* saved x_histp for " */
944 static char *xmp; /* mark pointer */
945 static unsigned char x_last_command;
946 static unsigned char (*x_tab)[X_TABSZ]; /* key definition */
948 static char *(*x_atab)[X_TABSZ]; /* macro definitions */
950 static unsigned char x_bound[(X_TABSZ * X_NTABS + 7) / 8];
952 static char *killstack[KILLSIZE];
953 static int killsp, killtp;
954 static int x_curprefix;
956 static char *macroptr; /* bind key macro active? */
959 static int winwidth; /* width of window */
960 static char *wbuf[2]; /* window buffers */
961 static int wbuf_len; /* length of window buffers (x_cols - 3) */
962 static int win; /* window buffer in use */
963 static char morec; /* more character at right of window */
964 static int lastref; /* argument to last refresh() */
965 static int holdlen; /* length of holdbuf */
967 static int pwidth; /* width of prompt */
968 static int prompt_trunc; /* how much of prompt to truncate or -1 */
969 static int x_col; /* current column on line */
971 static int x_ins(const char *);
972 static void x_delete(size_t, bool);
973 static size_t x_bword(void);
974 static size_t x_fword(bool);
975 static void x_goto(char *);
976 static char *x_bs0(char *, char *) MKSH_A_PURE;
977 static void x_bs3(char **);
978 static int x_size2(char *, char **);
979 static void x_zots(char *);
980 static void x_zotc3(char **);
981 static void x_load_hist(char **);
982 static int x_search(char *, int, int);
984 static int x_search_dir(int);
986 static int x_match(char *, char *);
987 static void x_redraw(int);
988 static void x_push(size_t);
989 static char *x_mapin(const char *, Area *);
990 static char *x_mapout(int);
991 static void x_mapout2(int, char **);
992 static void x_print(int, int);
993 static void x_e_ungetc(int);
994 static int x_e_getc(void);
995 static void x_e_putc2(int);
996 static void x_e_putc3(const char **);
997 static void x_e_puts(const char *);
999 static int x_fold_case(int);
1001 static char *x_lastcp(void);
1002 static void x_lastpos(void);
1003 static void do_complete(int, Comp_type);
1004 static size_t x_nb2nc(size_t) MKSH_A_PURE;
1006 static int unget_char = -1;
1008 static int x_do_ins(const char *, size_t);
1009 static void bind_if_not_bound(int, int, int);
1012 #define EMACSFN_ENUMS
1013 #include "emacsfn.h"
1017 #define EMACSFN_DEFNS
1018 #include "emacsfn.h"
1020 static const struct x_ftab x_ftab[] = {
1021 #define EMACSFN_ITEMS
1022 #include "emacsfn.h"
1025 static struct x_defbindings const x_defbindings[] = {
1026 { XFUNC_del_back, 0, CTRL('?') },
1027 { XFUNC_del_bword, 1, CTRL('?') },
1028 { XFUNC_eot_del, 0, CTRL('D') },
1029 { XFUNC_del_back, 0, CTRL('H') },
1030 { XFUNC_del_bword, 1, CTRL('H') },
1031 { XFUNC_del_bword, 1, 'h' },
1032 { XFUNC_mv_bword, 1, 'b' },
1033 { XFUNC_mv_fword, 1, 'f' },
1034 { XFUNC_del_fword, 1, 'd' },
1035 { XFUNC_mv_back, 0, CTRL('B') },
1036 { XFUNC_mv_forw, 0, CTRL('F') },
1037 { XFUNC_search_char_forw, 0, CTRL(']') },
1038 { XFUNC_search_char_back, 1, CTRL(']') },
1039 { XFUNC_newline, 0, CTRL('M') },
1040 { XFUNC_newline, 0, CTRL('J') },
1041 { XFUNC_end_of_text, 0, CTRL('_') },
1042 { XFUNC_abort, 0, CTRL('G') },
1043 { XFUNC_prev_com, 0, CTRL('P') },
1044 { XFUNC_next_com, 0, CTRL('N') },
1045 { XFUNC_nl_next_com, 0, CTRL('O') },
1046 { XFUNC_search_hist, 0, CTRL('R') },
1047 { XFUNC_beg_hist, 1, '<' },
1048 { XFUNC_end_hist, 1, '>' },
1049 { XFUNC_goto_hist, 1, 'g' },
1050 { XFUNC_mv_end, 0, CTRL('E') },
1051 { XFUNC_mv_begin, 0, CTRL('A') },
1052 { XFUNC_draw_line, 0, CTRL('L') },
1053 { XFUNC_cls, 1, CTRL('L') },
1054 { XFUNC_meta1, 0, CTRL('[') },
1055 { XFUNC_meta2, 0, CTRL('X') },
1056 { XFUNC_kill, 0, CTRL('K') },
1057 { XFUNC_yank, 0, CTRL('Y') },
1058 { XFUNC_meta_yank, 1, 'y' },
1059 { XFUNC_literal, 0, CTRL('^') },
1060 { XFUNC_comment, 1, '#' },
1061 { XFUNC_transpose, 0, CTRL('T') },
1062 { XFUNC_complete, 1, CTRL('[') },
1063 { XFUNC_comp_list, 0, CTRL('I') },
1064 { XFUNC_comp_list, 1, '=' },
1065 { XFUNC_enumerate, 1, '?' },
1066 { XFUNC_expand, 1, '*' },
1067 { XFUNC_comp_file, 1, CTRL('X') },
1068 { XFUNC_comp_comm, 2, CTRL('[') },
1069 { XFUNC_list_comm, 2, '?' },
1070 { XFUNC_list_file, 2, CTRL('Y') },
1071 { XFUNC_set_mark, 1, ' ' },
1072 { XFUNC_kill_region, 0, CTRL('W') },
1073 { XFUNC_xchg_point_mark, 2, CTRL('X') },
1074 { XFUNC_literal, 0, CTRL('V') },
1075 { XFUNC_version, 1, CTRL('V') },
1076 { XFUNC_prev_histword, 1, '.' },
1077 { XFUNC_prev_histword, 1, '_' },
1078 { XFUNC_set_arg, 1, '0' },
1079 { XFUNC_set_arg, 1, '1' },
1080 { XFUNC_set_arg, 1, '2' },
1081 { XFUNC_set_arg, 1, '3' },
1082 { XFUNC_set_arg, 1, '4' },
1083 { XFUNC_set_arg, 1, '5' },
1084 { XFUNC_set_arg, 1, '6' },
1085 { XFUNC_set_arg, 1, '7' },
1086 { XFUNC_set_arg, 1, '8' },
1087 { XFUNC_set_arg, 1, '9' },
1089 { XFUNC_fold_upper, 1, 'U' },
1090 { XFUNC_fold_upper, 1, 'u' },
1091 { XFUNC_fold_lower, 1, 'L' },
1092 { XFUNC_fold_lower, 1, 'l' },
1093 { XFUNC_fold_capitalise, 1, 'C' },
1094 { XFUNC_fold_capitalise, 1, 'c' },
1097 * These for ANSI arrow keys: arguablely shouldn't be here by
1098 * default, but its simpler/faster/smaller than using termcap
1101 { XFUNC_meta2, 1, '[' },
1102 { XFUNC_meta2, 1, 'O' },
1103 { XFUNC_prev_com, 2, 'A' },
1104 { XFUNC_next_com, 2, 'B' },
1105 { XFUNC_mv_forw, 2, 'C' },
1106 { XFUNC_mv_back, 2, 'D' },
1108 { XFUNC_vt_hack, 2, '1' },
1109 { XFUNC_mv_begin | 0x80, 2, '7' },
1110 { XFUNC_mv_begin, 2, 'H' },
1111 { XFUNC_mv_end | 0x80, 2, '4' },
1112 { XFUNC_mv_end | 0x80, 2, '8' },
1113 { XFUNC_mv_end, 2, 'F' },
1114 { XFUNC_del_char | 0x80, 2, '3' },
1115 { XFUNC_del_char, 2, 'P' },
1116 { XFUNC_search_hist_up | 0x80, 2, '5' },
1117 { XFUNC_search_hist_dn | 0x80, 2, '6' },
1120 #if !defined(MKSH_SMALL) || defined(__OS2__)
1121 { XFUNC_meta3, 0, 0 },
1122 { XFUNC_mv_begin, 3, 71 },
1123 { XFUNC_prev_com, 3, 72 },
1125 { XFUNC_search_hist_up, 3, 73 },
1127 { XFUNC_mv_back, 3, 75 },
1128 { XFUNC_mv_forw, 3, 77 },
1129 { XFUNC_mv_end, 3, 79 },
1130 { XFUNC_next_com, 3, 80 },
1132 { XFUNC_search_hist_dn, 3, 81 },
1134 { XFUNC_del_char, 3, 83 },
1137 /* more non-standard ones */
1138 { XFUNC_eval_region, 1, CTRL('E') },
1139 { XFUNC_edit_line, 2, 'e' }
1149 for (cp = xcp; cp < (xcp + nb); ++nc)
1150 cp += utf_ptradj(cp);
1158 x_histp = histptr + 1;
1164 #define XFUNC_VALUE(f) (f)
1166 #define XFUNC_VALUE(f) (f & 0x7F)
1170 x_e_getmbc(char *sbuf)
1173 unsigned char *buf = (unsigned char *)sbuf;
1176 buf[pos++] = c = x_e_getc();
1180 if ((buf[0] >= 0xC2) && (buf[0] < 0xF0)) {
1184 if ((c & 0xC0) != 0x80) {
1190 if ((buf[0] >= 0xE0) && (buf[0] < 0xF0)) {
1191 /* XXX x_e_ungetc is one-octet only */
1192 buf[pos++] = c = x_e_getc();
1201 * minimum required space to work with on a line - if the prompt
1202 * leaves less space than this on a line, the prompt is truncated
1204 #define MIN_EDIT_SPACE 7
1207 x_init_prompt(bool doprint)
1209 prompt_trunc = pprompt(prompt, doprint ? 0 : -1);
1210 pwidth = prompt_trunc % x_cols;
1211 prompt_trunc -= pwidth;
1212 if ((mksh_uari_t)pwidth > ((mksh_uari_t)x_cols - 3 - MIN_EDIT_SPACE)) {
1213 /* force newline after prompt */
1229 xlp = xcp = xep = buf;
1234 x_histp = histptr + 1;
1235 x_last_command = XFUNC_error;
1237 x_init_prompt(true);
1238 x_displen = (xx_cols = x_cols) - 2 - (x_col = pwidth);
1243 if (x_nextcmd >= 0) {
1244 int off = source->line - x_nextcmd;
1245 if (histptr - history >= off) {
1246 x_load_hist(histptr - off);
1247 x_histncp = x_histp;
1252 while (/* CONSTCOND */ 1) {
1254 if ((c = x_e_getc()) < 0)
1257 f = x_curprefix == -1 ? XFUNC_insert :
1258 x_tab[x_curprefix][c];
1262 if ((i = x_e_getc()) != '~')
1266 /* avoid bind key macro recursion */
1267 if (macroptr && f == XFUNC_ins_string)
1271 if (!(x_ftab[f].xf_flags & XF_PREFIX) &&
1272 x_last_command != XFUNC_set_arg) {
1274 x_arg_defaulted = true;
1276 i = c | (x_curprefix << 8);
1278 switch ((*x_ftab[f].xf_func)(i)) {
1280 if (!(x_ftab[f].xf_flags & XF_PREFIX))
1287 /* special case for interrupt */
1292 /* ad-hoc hack for fixing the cursor position */
1300 static int left, pos, save_arg;
1304 * Should allow tab and control chars.
1313 if (((c & 0xC0) == 0x80) && left) {
1324 if (x_curprefix == -1) {
1325 /* flush invalid multibyte */
1331 if ((c >= 0xC2) && (c < 0xE0))
1333 else if ((c >= 0xE0) && (c < 0xF0))
1358 macroptr = x_atab[c >> 8][c & 255];
1360 * we no longer need to bother checking if macroptr is
1361 * not NULL but first char is NUL; x_e_getc() does it
1368 x_do_ins(const char *cp, size_t len)
1370 if (xep + len >= xend) {
1374 memmove(xcp + len, xcp, xep - xcp + 1);
1375 memmove(xcp, cp, len);
1383 x_ins(const char *s)
1386 int adj = x_adj_done;
1388 if (x_do_ins(s, strlen(s)) < 0)
1391 * x_zots() may result in a call to x_adjust()
1392 * we want xcp to reflect the new position.
1396 x_adj_ok = tobool(xcp >= xlp);
1398 if (adj == x_adj_done)
1399 /* x_adjust() has not been called */
1406 x_del_back(int c MKSH_A_UNUSED)
1416 } while ((++i < x_arg) && (xcp != xbuf));
1422 x_del_char(int c MKSH_A_UNUSED)
1428 while (i < (size_t)x_arg) {
1429 utf_ptradjx(cp, cp2);
1444 /* Delete nc chars to the right of the cursor (including cursor position) */
1446 x_delete(size_t nc, bool push)
1456 for (i = 0; i < nc; ++i) {
1460 j = x_size2(cp, &cp2);
1469 if (xmp != NULL && xmp > xcp) {
1476 * This lets us yank a word we have deleted.
1482 /* Copies the NUL */
1483 memmove(xcp, xcp + nb, xep - xcp + 1);
1489 * if we are already filling the line,
1490 * there is no need to ' ', '\b'.
1491 * But if we must, make sure we do the minimum.
1493 if ((i = xx_cols - 2 - x_col) > 0 || xep - xlp == 0) {
1494 nw = i = (nw < i) ? nw : i;
1497 if (x_col == xx_cols - 2) {
1498 x_e_putc2((xep > xlp) ? '>' : (xbp > xbuf) ? '<' : ' ');
1513 x_del_bword(int c MKSH_A_UNUSED)
1515 x_delete(x_bword(), true);
1520 x_mv_bword(int c MKSH_A_UNUSED)
1527 x_mv_fword(int c MKSH_A_UNUSED)
1534 x_del_fword(int c MKSH_A_UNUSED)
1536 x_delete(x_fword(false), true);
1551 while (cp != xbuf && is_mfs(cp[-1])) {
1555 while (cp != xbuf && !is_mfs(cp[-1])) {
1561 return (x_nb2nc(nb));
1575 while (cp != xep && is_mfs(*cp))
1577 while (cp != xep && !is_mfs(*cp))
1580 nc = x_nb2nc(cp - xcp);
1589 cp = cp >= xep ? xep : x_bs0(cp, xbuf);
1590 if (cp < xbp || cp >= utf_skipcols(xbp, x_displen, NULL)) {
1591 /* we are heading off screen */
1594 } else if (cp < xcp) {
1598 } else if (cp > xcp) {
1606 x_bs0(char *cp, char *lower_bound)
1609 while ((!lower_bound || (cp > lower_bound)) &&
1610 ((*(unsigned char *)cp & 0xC0) == 0x80))
1620 *p = x_bs0((*p) - 1, NULL);
1621 i = x_size2(*p, NULL);
1627 x_size2(char *cp, char **dcp)
1629 uint8_t c = *(unsigned char *)cp;
1631 if (UTFMODE && (c > 0x7F))
1632 return (utf_widthadj(cp, (const char **)dcp));
1636 /* Kludge, tabs are always four spaces. */
1638 if (ISCTRL(c) && /* but not C1 */ c < 0x80)
1639 /* control unsigned char */
1647 int adj = x_adj_done;
1650 while (*str && str < xlp && x_col < xx_cols && adj == x_adj_done)
1657 unsigned char c = **(unsigned char **)cp;
1660 /* Kludge, tabs are always four spaces. */
1663 } else if (ISCTRL(c) && /* but not C1 */ c < 0x80) {
1665 x_e_putc2(UNCTRL(c));
1668 x_e_putc3((const char **)cp);
1672 x_mv_back(int c MKSH_A_UNUSED)
1687 x_mv_forw(int c MKSH_A_UNUSED)
1689 char *cp = xcp, *cp2;
1696 utf_ptradjx(cp, cp2);
1706 x_search_char_forw(int c MKSH_A_UNUSED)
1712 if (x_e_getmbc(tmp) < 0) {
1717 if ((cp = (cp == xep) ? NULL : strstr(cp + 1, tmp)) == NULL &&
1718 (cp = strstr(xbuf, tmp)) == NULL) {
1728 x_search_char_back(int c MKSH_A_UNUSED)
1730 char *cp = xcp, *p, tmp[4];
1733 if (x_e_getmbc(tmp) < 0) {
1737 for (; x_arg--; cp = p)
1745 if ((tmp[1] && ((p+1) > xep)) ||
1746 (tmp[2] && ((p+2) > xep)))
1751 if (b && tmp[1] && p[1] != tmp[1])
1753 if (b && tmp[2] && p[2] != tmp[2])
1763 x_newline(int c MKSH_A_UNUSED)
1773 x_end_of_text(int c MKSH_A_UNUSED)
1776 char *cp = (void *)&tmp;
1778 tmp = isedchar(edchars.eof) ? (unsigned char)edchars.eof :
1779 (unsigned char)CTRL('D');
1788 x_beg_hist(int c MKSH_A_UNUSED)
1790 x_load_hist(history);
1795 x_end_hist(int c MKSH_A_UNUSED)
1797 x_load_hist(histptr);
1802 x_prev_com(int c MKSH_A_UNUSED)
1804 x_load_hist(x_histp - x_arg);
1809 x_next_com(int c MKSH_A_UNUSED)
1811 x_load_hist(x_histp + x_arg);
1816 * Goto a particular history number obtained from argument.
1817 * If no argument is given history 1 is probably not what you
1818 * want so we'll simply go to the oldest one.
1821 x_goto_hist(int c MKSH_A_UNUSED)
1823 if (x_arg_defaulted)
1824 x_load_hist(history);
1826 x_load_hist(histptr + x_arg - source->line);
1831 x_load_hist(char **hp)
1835 if (hp == histptr + 1) {
1838 } else if (hp < history || hp > histptr) {
1846 strlcpy(holdbufp, xbuf, LINE);
1847 strlcpy(xbuf, sp, xend - xbuf);
1849 xep = xcp = xbuf + strlen(xbuf);
1855 x_nl_next_com(int c MKSH_A_UNUSED)
1857 if (!x_histncp || (x_histp != x_histncp && x_histp != histptr + 1))
1858 /* fresh start of ^O */
1859 x_histncp = x_histp;
1860 x_nextcmd = source->line - (histptr - x_histncp) + 1;
1861 return (x_newline('\n'));
1867 if (xep == xbuf && x_arg_defaulted)
1868 return (x_end_of_text(c));
1870 return (x_del_char(c));
1873 /* reverse incremental history search */
1875 x_search_hist(int c)
1877 int offset = -1; /* offset of match in xbuf, else -1 */
1878 char pat[80 + 1]; /* pattern buffer */
1883 while (/* CONSTCOND */ 1) {
1885 x_e_puts("\nI-search: ");
1889 if ((c = x_e_getc()) < 0)
1892 if (c == CTRL('[')) {
1893 if ((f & 0x7F) == XFUNC_meta1) {
1894 if ((c = x_e_getc()) < 0)
1896 f = x_tab[1][c] & 0x7F;
1897 if (f == XFUNC_meta1 || f == XFUNC_meta2)
1906 if ((c = x_e_getc()) != '~')
1910 if (f == XFUNC_search_hist)
1911 offset = x_search(pat, 0, offset);
1912 else if (f == XFUNC_del_back) {
1922 offset = x_search(pat, 1, offset);
1924 } else if (f == XFUNC_insert) {
1925 /* add char to pattern */
1926 /* overflow check... */
1927 if ((size_t)(p - pat) >= sizeof(pat) - 1) {
1931 *p++ = c, *p = '\0';
1933 /* already have partial match */
1934 offset = x_match(xbuf, pat);
1936 x_goto(xbuf + offset + (p - pat) -
1941 offset = x_search(pat, 0, offset);
1942 } else if (f == XFUNC_abort) {
1944 x_load_hist(histptr + 1);
1957 /* search backward from current line */
1959 x_search(char *pat, int sameline, int offset)
1964 for (hp = x_histp - (sameline ? 0 : 1); hp >= history; --hp) {
1965 i = x_match(*hp, pat);
1970 x_goto(xbuf + i + strlen(pat) - (*pat == '^'));
1980 /* anchored search up from current line */
1982 x_search_hist_up(int c MKSH_A_UNUSED)
1984 return (x_search_dir(-1));
1987 /* anchored search down from current line */
1989 x_search_hist_dn(int c MKSH_A_UNUSED)
1991 return (x_search_dir(1));
1994 /* anchored search in the indicated direction */
1996 x_search_dir(int search_dir /* should've been bool */)
1998 char **hp = x_histp + search_dir;
1999 size_t curs = xcp - xbuf;
2001 while (histptr >= hp && hp >= history) {
2002 if (strncmp(xbuf, *hp, curs) == 0) {
2004 x_goto(xbuf + curs);
2013 /* return position of first match of pattern in string, else -1 */
2015 x_match(char *str, char *pat)
2018 return ((strncmp(str, pat + 1, strlen(pat + 1)) == 0) ? 0 : -1);
2020 char *q = strstr(str, pat);
2021 return ((q == NULL) ? -1 : q - str);
2026 x_del_line(int c MKSH_A_UNUSED)
2029 x_push(xep - (xcp = xbuf));
2030 xlp = xbp = xep = xbuf;
2040 x_mv_end(int c MKSH_A_UNUSED)
2047 x_mv_begin(int c MKSH_A_UNUSED)
2054 x_draw_line(int c MKSH_A_UNUSED)
2061 x_cls(int c MKSH_A_UNUSED)
2063 shf_puts(MKSH_CLS_STRING, shl_out);
2069 * clear line from x_col (current cursor position) to xx_cols - 2,
2070 * then output lastch, then go back to x_col; if lastch is space,
2071 * clear with termcap instead of spaces, or not if line_was_cleared;
2072 * lastch MUST be an ASCII character with wcwidth(lastch) == 1
2075 x_clrtoeol(int lastch, bool line_was_cleared)
2079 if (lastch == ' ' && !line_was_cleared && x_term_mode == 1) {
2080 shf_puts("\033[K", shl_out);
2081 line_was_cleared = true;
2083 if (lastch == ' ' && line_was_cleared)
2087 while (col < (xx_cols - 2)) {
2093 while (col > x_col) {
2099 /* output the prompt, assuming a line has just been started */
2103 if (prompt_trunc != -1)
2104 pprompt(prompt, prompt_trunc);
2108 /* output CR, then redraw the line, clearing to EOL if needed (cr ≠0, LF) */
2115 /* clear the line */
2116 x_e_putc2(cr ? cr : '\r');
2118 /* display the prompt */
2121 x_displen = xx_cols - 2 - x_col;
2122 /* display the line content */
2125 /* check whether there is more off-screen */
2126 lch = xep > xlp ? (xbp > xbuf ? '*' : '>') : (xbp > xbuf) ? '<' : ' ';
2127 /* clear the rest of the line */
2128 x_clrtoeol(lch, !cr || cr == '\n');
2129 /* go back to actual cursor position */
2135 x_transpose(int c MKSH_A_UNUSED)
2137 unsigned int tmpa, tmpb;
2140 * What transpose is meant to do seems to be up for debate. This
2141 * is a general summary of the options; the text is abcd with the
2142 * upper case character or underscore indicating the cursor position:
2143 * Who Before After Before After
2144 * AT&T ksh in emacs mode: abCd abdC abcd_ (bell)
2145 * AT&T ksh in gmacs mode: abCd baCd abcd_ abdc_
2146 * gnu emacs: abCd acbD abcd_ abdc_
2147 * Pdksh currently goes with GNU behavior since I believe this is the
2148 * most common version of emacs, unless in gmacs mode, in which case
2149 * it does the AT&T ksh gmacs mode.
2150 * This should really be broken up into 3 functions so users can bind
2151 * to the one they want.
2156 } else if (xcp == xep || Flag(FGMACS)) {
2157 if (xcp - xbuf == 1) {
2162 * Gosling/Unipress emacs style: Swap two characters before
2163 * the cursor, do not change cursor position
2166 if (utf_mbtowc(&tmpa, xcp) == (size_t)-1) {
2171 if (utf_mbtowc(&tmpb, xcp) == (size_t)-1) {
2175 utf_wctomb(xcp, tmpa);
2177 utf_wctomb(xcp, tmpb);
2181 * GNU emacs style: Swap the characters before and under the
2182 * cursor, move cursor position along one.
2184 if (utf_mbtowc(&tmpa, xcp) == (size_t)-1) {
2189 if (utf_mbtowc(&tmpb, xcp) == (size_t)-1) {
2193 utf_wctomb(xcp, tmpa);
2195 utf_wctomb(xcp, tmpb);
2203 x_literal(int c MKSH_A_UNUSED)
2210 x_meta1(int c MKSH_A_UNUSED)
2217 x_meta2(int c MKSH_A_UNUSED)
2224 x_meta3(int c MKSH_A_UNUSED)
2231 x_kill(int c MKSH_A_UNUSED)
2233 size_t col = xcp - xbuf;
2234 size_t lastcol = xep - xbuf;
2237 if (x_arg_defaulted || (narg = x_arg) > lastcol)
2240 x_goto(xbuf + narg);
2244 x_delete(x_nb2nc(ndel), true);
2249 x_push(size_t nchars)
2251 afree(killstack[killsp], AEDIT);
2252 strndupx(killstack[killsp], xcp, nchars, AEDIT);
2253 killsp = (killsp + 1) % KILLSIZE;
2257 x_yank(int c MKSH_A_UNUSED)
2264 if (killstack[killtp] == 0) {
2265 x_e_puts("\nnothing to yank");
2270 x_ins(killstack[killtp]);
2275 x_meta_yank(int c MKSH_A_UNUSED)
2279 if ((x_last_command != XFUNC_yank && x_last_command != XFUNC_meta_yank) ||
2280 killstack[killtp] == 0) {
2282 x_e_puts("\nyank something first");
2286 len = strlen(killstack[killtp]);
2288 x_delete(x_nb2nc(len), false);
2291 killtp = KILLSIZE - 1;
2294 } while (killstack[killtp] == 0);
2295 x_ins(killstack[killtp]);
2300 x_abort(int c MKSH_A_UNUSED)
2303 xlp = xep = xcp = xbp = xbuf;
2311 x_error(int c MKSH_A_UNUSED)
2318 /* special VT100 style key sequence hack */
2322 /* we only support PF2-'1' for now */
2323 if (c != (2 << 8 | '1'))
2324 return (x_error(c));
2326 /* what's the next character? */
2327 switch ((c = x_e_getc())) {
2330 x_arg_defaulted = true;
2331 return (x_mv_begin(0));
2333 /* "interesting" sequence detected */
2339 /* XXX x_e_ungetc is one-octet only */
2340 if ((c = x_e_getc()) != '5' && c != '3')
2344 * At this point, we have read the following octets so far:
2345 * - ESC+[ or ESC+O or Ctrl-X (Prefix 2)
2348 * - 5 (Ctrl key combiner) or 3 (Alt key combiner)
2349 * We can now accept one more octet designating the key.
2352 switch ((c = x_e_getc())) {
2354 return (x_mv_fword(c));
2356 return (x_mv_bword(c));
2361 return (x_error(c));
2366 x_mapin(const char *cp, Area *ap)
2370 strdupx(news, cp, ap);
2373 /* XXX -- should handle \^ escape? */
2376 /*XXX or ^^ escape? this is ugly. */
2378 /* includes '?'; ASCII */
2394 x_mapout2(int c, char **buf)
2418 x_print(int prefix, int key)
2420 int f = x_tab[prefix][key];
2423 /* prefix == 1 || prefix == 2 */
2424 shf_puts(x_mapout(prefix == 1 ? CTRL('[') :
2425 prefix == 2 ? CTRL('X') : 0), shl_stdout);
2427 shprintf("%s = ", x_mapout(key));
2429 shprintf("%s%s = ", x_mapout(key), (f & 0x80) ? "~" : "");
2430 if (XFUNC_VALUE(f) != XFUNC_ins_string)
2432 shprintf(Tf_sN, x_ftab[XFUNC_VALUE(f)].xf_name);
2435 shprintf("'%s'\n", x_atab[prefix][key]);
2440 x_bind(const char *a1, const char *a2,
2456 if (x_tab == NULL) {
2457 bi_errorf("can't bind, not a tty");
2460 /* List function names */
2462 for (f = 0; f < NELEM(x_ftab); f++)
2463 if (!(x_ftab[f].xf_flags & XF_NOBIND))
2464 shprintf(Tf_sN, x_ftab[f].xf_name);
2468 for (prefix = 0; prefix < X_NTABS; prefix++)
2469 for (key = 0; key < X_TABSZ; key++) {
2470 f = XFUNC_VALUE(x_tab[prefix][key]);
2471 if (f == XFUNC_insert || f == XFUNC_error
2473 || (macro && f != XFUNC_ins_string)
2477 x_print(prefix, key);
2481 m2 = m1 = x_mapin(a1, ATEMP);
2484 key = (unsigned char)*m1;
2485 f = XFUNC_VALUE(x_tab[prefix][key]);
2486 if (f == XFUNC_meta1)
2488 else if (f == XFUNC_meta2)
2490 else if (f == XFUNC_meta3)
2497 && ((*m1 != '~') || *(m1 + 1))
2503 while (*c && (size_t)(m1 - msg) < sizeof(msg) - 3)
2504 x_mapout2(*c++, &m1);
2505 bi_errorf("too long key sequence: %s", msg);
2509 hastilde = tobool(*m1);
2514 x_print(prefix, key);
2521 f = XFUNC_ins_string;
2522 sp = x_mapin(a2, AEDIT);
2525 for (f = 0; f < NELEM(x_ftab); f++)
2526 if (!strcmp(x_ftab[f].xf_name, a2))
2528 if (f == NELEM(x_ftab) || x_ftab[f].xf_flags & XF_NOBIND) {
2529 bi_errorf("%s: no such function", a2);
2535 if (XFUNC_VALUE(x_tab[prefix][key]) == XFUNC_ins_string &&
2536 x_atab[prefix][key])
2537 afree(x_atab[prefix][key], AEDIT);
2539 x_tab[prefix][key] = f
2541 | (hastilde ? 0x80 : 0)
2545 x_atab[prefix][key] = sp;
2548 /* Track what the user has bound so x_mode(true) won't toast things */
2549 if (f == XFUNC_insert)
2550 x_bound[(prefix * X_TABSZ + key) / 8] &=
2551 ~(1 << ((prefix * X_TABSZ + key) % 8));
2553 x_bound[(prefix * X_TABSZ + key) / 8] |=
2554 (1 << ((prefix * X_TABSZ + key) % 8));
2560 bind_if_not_bound(int p, int k, int func)
2565 * Has user already bound this key?
2566 * If so, do not override it.
2568 t = p * X_TABSZ + k;
2569 if (x_bound[t >> 3] & (1 << (t & 7)))
2576 x_set_mark(int c MKSH_A_UNUSED)
2583 x_kill_region(int c MKSH_A_UNUSED)
2600 x_delete(x_nb2nc(rsize), true);
2606 x_xchg_point_mark(int c MKSH_A_UNUSED)
2621 x_noop(int c MKSH_A_UNUSED)
2627 * File/command name completion routines
2630 x_comp_comm(int c MKSH_A_UNUSED)
2632 do_complete(XCF_COMMAND, CT_COMPLETE);
2637 x_list_comm(int c MKSH_A_UNUSED)
2639 do_complete(XCF_COMMAND, CT_LIST);
2644 x_complete(int c MKSH_A_UNUSED)
2646 do_complete(XCF_COMMAND_FILE, CT_COMPLETE);
2651 x_enumerate(int c MKSH_A_UNUSED)
2653 do_complete(XCF_COMMAND_FILE, CT_LIST);
2658 x_comp_file(int c MKSH_A_UNUSED)
2660 do_complete(XCF_FILE, CT_COMPLETE);
2665 x_list_file(int c MKSH_A_UNUSED)
2667 do_complete(XCF_FILE, CT_LIST);
2672 x_comp_list(int c MKSH_A_UNUSED)
2674 do_complete(XCF_COMMAND_FILE, CT_COMPLIST);
2679 x_expand(int c MKSH_A_UNUSED)
2682 int start, end, nwords, i;
2685 nwords = x_cf_glob(&i, xbuf, xep - xbuf, xcp - xbuf,
2686 &start, &end, &words);
2692 x_goto(xbuf + start);
2693 x_delete(x_nb2nc(end - start), false);
2696 while (i < nwords) {
2697 if (x_escape(words[i], strlen(words[i]), x_do_ins) < 0 ||
2698 (++i < nwords && x_ins(T1space) < 0)) {
2710 /* XCF_{COMMAND,FILE,COMMAND_FILE} */
2712 /* 0 for list, 1 for complete and 2 for complete-list */
2716 int start, end, nlen, olen, nwords;
2719 nwords = x_cf_glob(&flags, xbuf, xep - xbuf, xcp - xbuf,
2720 &start, &end, &words);
2726 if (type == CT_LIST) {
2727 x_print_expansions(nwords, words,
2728 tobool(flags & XCF_IS_COMMAND));
2730 x_free_words(nwords, words);
2734 nlen = x_longest_prefix(nwords, words);
2737 * always complete single matches;
2738 * any expansion of parameter substitution
2739 * is always at most one result, too
2745 /* make a copy of the original string part */
2746 strndupx(unescaped, xbuf + start, olen, ATEMP);
2748 /* expand any tilde and unescape the string for comparison */
2749 unescaped = x_glob_hlp_tilde_and_rem_qchar(unescaped, true);
2752 * match iff entire original string is part of the
2753 * longest prefix, implying the latter is at least
2754 * the same size (after unescaping)
2756 completed = !strncmp(words[0], unescaped, strlen(unescaped));
2758 afree(unescaped, ATEMP);
2760 if (type == CT_COMPLIST && nwords > 1) {
2762 * print expansions, since we didn't get back
2763 * just a single match
2765 x_print_expansions(nwords, words,
2766 tobool(flags & XCF_IS_COMMAND));
2769 /* expand on the command line */
2773 memmove(xcp, xcp + olen, xep - xcp + 1);
2774 x_escape(words[0], nlen, x_do_ins);
2778 * append a space if this is a single non-directory match
2779 * and not a parameter or homedir substitution
2781 if (nwords == 1 && words[0][nlen - 1] != '/' &&
2782 !(flags & XCF_IS_NOSPACE)) {
2786 x_free_words(nwords, words);
2791 * x_adjust - redraw the line adjusting starting point etc.
2794 * This function is called when we have exceeded the bounds
2795 * of the edit window. It increments x_adj_done so that
2796 * functions like x_ins and x_delete know that we have been
2797 * called and can skip the x_bs() stuff which has already
2798 * been done by x_redraw.
2808 /* flag the fact that we were called */
2812 * calculate the amount of columns we need to "go back"
2813 * from xcp to set xbp to (but never < xbuf) to 2/3 of
2814 * the display width; take care of pwidth though
2816 if ((col_left = xx_cols * 2 / 3) < MIN_EDIT_SPACE) {
2818 * cowardly refuse to do anything
2819 * if the available space is too small;
2820 * fall back to dumb pdksh code
2822 if ((xbp = xcp - (x_displen / 2)) < xbuf)
2824 /* elide UTF-8 fixup as penalty */
2828 /* fix up xbp to just past a character end first */
2829 xbp = xcp >= xep ? xep : x_bs0(xcp, xbuf);
2830 /* walk backwards */
2831 while (xbp > xbuf && col_left > 0) {
2832 xbp = x_bs0(xbp - 1, xbuf);
2833 col_left -= (n = x_size2(xbp, NULL));
2835 /* check if we hit the prompt */
2836 if (xbp == xbuf && xcp != xbuf && col_left >= 0 && col_left < pwidth) {
2837 /* so we did; force scrolling occurs */
2838 xbp += utf_ptradj(xbp);
2850 unget_char = c < 0 ? -1 : (c & 255);
2858 if (unget_char >= 0) {
2866 if ((c = (unsigned char)*macroptr++))
2880 if (c == '\r' || c == '\n')
2882 if (x_col < xx_cols) {
2883 if (UTFMODE && (c > 0x7F)) {
2889 x = utf_wctomb(utf_tmp, c);
2895 width = utf_wcwidth(c);
2912 if (x_adj_ok && (x_col < 0 || x_col >= (xx_cols - 2)))
2917 x_e_putc3(const char **cp)
2919 int width = 1, c = **(const unsigned char **)cp;
2921 if (c == '\r' || c == '\n')
2923 if (x_col < xx_cols) {
2924 if (UTFMODE && (c > 0x7F)) {
2927 width = utf_widthadj(*cp, (const char **)&cp2);
2948 if (x_adj_ok && (x_col < 0 || x_col >= (xx_cols - 2)))
2953 x_e_puts(const char *s)
2955 int adj = x_adj_done;
2957 while (*s && adj == x_adj_done)
2963 * x_set_arg - set an arg value for next function
2966 * This is a simple implementation of M-[0-9].
2977 /* strip command prefix */
2979 while (c >= 0 && ksh_isdigit(c)) {
2980 n = n * 10 + ksh_numdig(c);
2982 /* upper bound for repeat */
2983 goto x_set_arg_too_big;
2987 if (c < 0 || first) {
2991 x_arg_defaulted = true;
2995 x_arg_defaulted = false;
3000 /* Comment or uncomment the current line. */
3002 x_comment(int c MKSH_A_UNUSED)
3004 ssize_t len = xep - xbuf;
3005 int ret = x_do_comment(xbuf, xend - xbuf, &len);
3016 return (x_newline('\n'));
3022 x_version(int c MKSH_A_UNUSED)
3024 char *o_xbuf = xbuf, *o_xend = xend;
3025 char *o_xbp = xbp, *o_xep = xep, *o_xcp = xcp;
3028 strdupx(v, KSH_VERSION, ATEMP);
3030 xbuf = xbp = xcp = v;
3031 xend = xep = v + strlen(v);
3045 /* This is what AT&T ksh seems to do... Very bizarre */
3055 x_edit_line(int c MKSH_A_UNUSED)
3057 if (x_arg_defaulted) {
3064 histsave(&source->line, xbuf, HIST_STORE, true);
3067 x_arg = source->line - (histptr - x_histp);
3070 shf_snprintf(xbuf, xend - xbuf, Tf_sd,
3071 "fc -e ${VISUAL:-${EDITOR:-vi}} --", x_arg);
3073 strlcpy(xbuf, "fc -e ${VISUAL:-${EDITOR:-vi}} --", xend - xbuf);
3074 xep = xbuf + strlen(xbuf);
3075 return (x_newline('\n'));
3081 * x_prev_histword - recover word from prev command
3084 * This function recovers the last word from the previous
3085 * command and inserts it into the current edit line. If a
3086 * numeric arg is supplied then the n'th word from the
3087 * start of the previous command is used.
3088 * As a side effect, trashes the mark in order to achieve
3089 * being called in a repeatable fashion.
3097 x_prev_histword(int c MKSH_A_UNUSED)
3102 /* -1 = defaulted; 0+ = argument */
3103 static int last_arg = -1;
3105 if (x_last_command == XFUNC_prev_histword) {
3106 if (xmp && modified > 1)
3111 last_arg = x_arg_defaulted ? -1 : x_arg;
3112 xhp = histptr - (m - 1);
3113 if ((xhp < history) || !(cp = *xhp)) {
3119 if ((x_arg = last_arg) == -1) {
3120 /* x_arg_defaulted */
3122 rcp = &cp[strlen(cp) - 1];
3124 * ignore white-space after the last word
3126 while (rcp > cp && is_cfs(*rcp))
3128 while (rcp > cp && !is_cfs(*rcp))
3134 /* not x_arg_defaulted */
3139 * ignore white-space at start of line
3141 while (*rcp && is_cfs(*rcp))
3143 while (x_arg-- > 0) {
3144 while (*rcp && !is_cfs(*rcp))
3146 while (*rcp && is_cfs(*rcp))
3150 while (*rcp && !is_cfs(*rcp))
3162 /* Uppercase N(1) words */
3164 x_fold_upper(int c MKSH_A_UNUSED)
3166 return (x_fold_case('U'));
3169 /* Lowercase N(1) words */
3171 x_fold_lower(int c MKSH_A_UNUSED)
3173 return (x_fold_case('L'));
3176 /* Titlecase N(1) words */
3178 x_fold_capitalise(int c MKSH_A_UNUSED)
3180 return (x_fold_case('C'));
3185 * x_fold_case - convert word to UPPER/lower/Capital case
3188 * This function is used to implement M-U/M-u, M-L/M-l, M-C/M-c
3189 * to UPPER CASE, lower case or Capitalise Words.
3205 * first skip over any white-space
3207 while (cp != xep && is_mfs(*cp))
3210 * do the first char on its own since it may be
3211 * a different action than for the rest.
3216 *cp = ksh_tolower(*cp);
3218 /* uppercase, capitalise */
3219 *cp = ksh_toupper(*cp);
3223 * now for the rest of the word
3225 while (cp != xep && !is_mfs(*cp)) {
3228 *cp = ksh_toupper(*cp);
3230 /* lowercase, capitalise */
3231 *cp = ksh_tolower(*cp);
3243 * x_lastcp - last visible char
3246 * This function returns a pointer to that char in the
3247 * edit buffer that will be the last displayed on the
3259 j = x_size2(xlp, &xlp2);
3260 if ((i + j) > x_displen)
3270 /* correctly position the cursor on the screen from end of visible area */
3274 char *cp = x_lastcp();
3283 static bool x_cur_mode;
3285 if (x_cur_mode == onoff)
3290 x_mkraw(tty_fd, NULL, false);
3292 edchars.erase = toedchar(tty_state.c_cc[VERASE]);
3293 edchars.kill = toedchar(tty_state.c_cc[VKILL]);
3294 edchars.intr = toedchar(tty_state.c_cc[VINTR]);
3295 edchars.quit = toedchar(tty_state.c_cc[VQUIT]);
3296 edchars.eof = toedchar(tty_state.c_cc[VEOF]);
3298 edchars.werase = toedchar(tty_state.c_cc[VWERASE]);
3304 edchars.erase = CTRL('H');
3306 edchars.kill = CTRL('U');
3308 edchars.intr = CTRL('C');
3310 edchars.quit = CTRL('\\');
3312 edchars.eof = CTRL('D');
3313 if (!edchars.werase)
3314 edchars.werase = CTRL('W');
3316 if (isedchar(edchars.erase)) {
3317 bind_if_not_bound(0, edchars.erase, XFUNC_del_back);
3318 bind_if_not_bound(1, edchars.erase, XFUNC_del_bword);
3320 if (isedchar(edchars.kill))
3321 bind_if_not_bound(0, edchars.kill, XFUNC_del_line);
3322 if (isedchar(edchars.werase))
3323 bind_if_not_bound(0, edchars.werase, XFUNC_del_bword);
3324 if (isedchar(edchars.intr))
3325 bind_if_not_bound(0, edchars.intr, XFUNC_abort);
3326 if (isedchar(edchars.quit))
3327 bind_if_not_bound(0, edchars.quit, XFUNC_noop);
3329 mksh_tcset(tty_fd, &tty_state);
3333 /* +++ vi editing mode +++ */
3343 static int vi_hook(int);
3344 static int nextstate(int);
3345 static int vi_insert(int);
3346 static int vi_cmd(int, const char *);
3347 static int domove(int, const char *, int);
3348 static int redo_insert(int);
3349 static void yank_range(int, int);
3350 static int bracktype(int);
3351 static void save_cbuf(void);
3352 static void restore_cbuf(void);
3353 static int putbuf(const char *, ssize_t, bool);
3354 static void del_range(int, int);
3355 static int findch(int, int, bool, bool) MKSH_A_PURE;
3356 static int forwword(int);
3357 static int backword(int);
3358 static int endword(int);
3359 static int Forwword(int);
3360 static int Backword(int);
3361 static int Endword(int);
3362 static int grabhist(int, int);
3363 static int grabsearch(int, int, int, const char *);
3364 static void redraw_line(bool);
3365 static void refresh(int);
3366 static int outofwin(void);
3367 static void rewindow(void);
3368 static int newcol(unsigned char, int);
3369 static void display(char *, char *, int);
3370 static void ed_mov_opt(int, char *);
3371 static int expand_word(int);
3372 static int complete_word(int, int);
3373 static int print_expansions(struct edstate *, int);
3374 #define char_len(c) ((ISCTRL((unsigned char)c) && \
3375 /* but not C1 */ (unsigned char)c < 0x80) ? 2 : 1)
3376 static void x_vi_zotc(int);
3377 static void vi_error(void);
3378 static void vi_macro_reset(void);
3379 static int x_vi_putbuf(const char *, size_t);
3381 #define vC 0x01 /* a valid command that isn't a vM, vE, vU */
3382 #define vM 0x02 /* movement command (h, l, etc.) */
3383 #define vE 0x04 /* extended command (c, d, y) */
3384 #define vX 0x08 /* long command (@, f, F, t, T, etc.) */
3385 #define vU 0x10 /* an UN-undoable command (that isn't a vM) */
3386 #define vB 0x20 /* bad command (^@) */
3387 #define vZ 0x40 /* repeat count defaults to 0 (not 1) */
3388 #define vS 0x80 /* search (/, ?) */
3390 #define is_bad(c) (classify[(c)&0x7f]&vB)
3391 #define is_cmd(c) (classify[(c)&0x7f]&(vM|vE|vC|vU))
3392 #define is_move(c) (classify[(c)&0x7f]&vM)
3393 #define is_extend(c) (classify[(c)&0x7f]&vE)
3394 #define is_long(c) (classify[(c)&0x7f]&vX)
3395 #define is_undoable(c) (!(classify[(c)&0x7f]&vU))
3396 #define is_srch(c) (classify[(c)&0x7f]&vS)
3397 #define is_zerocount(c) (classify[(c)&0x7f]&vZ)
3399 static const unsigned char classify[128] = {
3400 /* 0 1 2 3 4 5 6 7 */
3401 /* 0 ^@ ^A ^B ^C ^D ^E ^F ^G */
3402 vB, 0, 0, 0, 0, vC|vU, vC|vZ, 0,
3403 /* 1 ^H ^I ^J ^K ^L ^M ^N ^O */
3404 vM, vC|vZ, 0, 0, vC|vU, 0, vC, 0,
3405 /* 2 ^P ^Q ^R ^S ^T ^U ^V ^W */
3406 vC, 0, vC|vU, 0, 0, 0, vC, 0,
3407 /* 3 ^X ^Y ^Z ^[ ^\ ^] ^^ ^_ */
3408 vC, 0, 0, vC|vZ, 0, 0, 0, 0,
3409 /* 4 <space> ! " # $ % & ' */
3410 vM, 0, 0, vC, vM, vM, 0, 0,
3411 /* 5 ( ) * + , - . / */
3412 0, 0, vC, vC, vM, vC, 0, vC|vS,
3413 /* 6 0 1 2 3 4 5 6 7 */
3414 vM, 0, 0, 0, 0, 0, 0, 0,
3415 /* 7 8 9 : ; < = > ? */
3416 0, 0, 0, vM, 0, vC, 0, vC|vS,
3417 /* 8 @ A B C D E F G */
3418 vC|vX, vC, vM, vC, vC, vM, vM|vX, vC|vU|vZ,
3419 /* 9 H I J K L M N O */
3420 0, vC, 0, 0, 0, 0, vC|vU, vU,
3421 /* A P Q R S T U V W */
3422 vC, 0, vC, vC, vM|vX, vC, 0, vM,
3423 /* B X Y Z [ \ ] ^ _ */
3424 vC, vC|vU, 0, vU, vC|vZ, 0, vM, vC|vZ,
3425 /* C ` a b c d e f g */
3426 0, vC, vM, vE, vE, vM, vM|vX, vC|vZ,
3427 /* D h i j k l m n o */
3428 vM, vC, vC|vU, vC|vU, vM, 0, vC|vU, 0,
3429 /* E p q r s t u v w */
3430 vC, 0, vX, vC, vM|vX, vC|vU, vC|vU|vZ, vM,
3431 /* F x y z { | } ~ ^? */
3432 vC, vE|vU, 0, 0, vM|vZ, 0, vC, 0
3441 #define VNORMAL 0 /* command, insert or replace mode */
3442 #define VARG1 1 /* digit prefix (first, eg, 5l) */
3443 #define VEXTCMD 2 /* cmd + movement (eg, cl) */
3444 #define VARG2 3 /* digit prefix (second, eg, 2c3l) */
3445 #define VXCH 4 /* f, F, t, T, @ */
3446 #define VFAIL 5 /* bad command */
3447 #define VCMD 6 /* single char command (eg, X) */
3448 #define VREDO 7 /* . */
3449 #define VLIT 8 /* ^V */
3450 #define VSEARCH 9 /* /, ? */
3451 #define VVERSION 10 /* <ESC> ^V */
3452 #define VPREFIX2 11 /* ^[[ and ^[O in insert mode */
3454 static struct edstate *save_edstate(struct edstate *old);
3455 static void restore_edstate(struct edstate *old, struct edstate *news);
3456 static void free_edstate(struct edstate *old);
3458 static struct edstate ebuf;
3459 static struct edstate undobuf;
3461 static struct edstate *es; /* current editor state */
3462 static struct edstate *undo;
3464 static char *ibuf; /* input buffer */
3465 static bool first_insert; /* set when starting in insert mode */
3466 static int saved_inslen; /* saved inslen for first insert */
3467 static int inslen; /* length of input buffer */
3468 static int srchlen; /* length of current search pattern */
3469 static char *ybuf; /* yank buffer */
3470 static int yanklen; /* length of yank buffer */
3471 static int fsavecmd = ' '; /* last find command */
3472 static int fsavech; /* character to find */
3473 static char lastcmd[MAXVICMD]; /* last non-move command */
3474 static int lastac; /* argcnt for lastcmd */
3475 static int lastsearch = ' '; /* last search command */
3476 static char srchpat[SRCHLEN]; /* last search pattern */
3477 static int insert; /* <>0 in insert mode */
3478 static int hnum; /* position in history */
3479 static int ohnum; /* history line copied (after mod) */
3480 static int hlast; /* 1 past last position in history */
3484 * Information for keeping track of macros that are being expanded.
3485 * The format of buf is the alias contents followed by a NUL byte followed
3486 * by the name (letter) of the alias. The end of the buffer is marked by
3487 * a double NUL. The name of the alias is stored so recursive macros can
3490 struct macro_state {
3491 unsigned char *p; /* current position in buf */
3492 unsigned char *buf; /* pointer to macro(s) being expanded */
3493 size_t len; /* how much data in buffer */
3495 static struct macro_state macro;
3497 /* last input was expanded */
3498 static enum expand_mode {
3499 NONE = 0, EXPAND, COMPLETE, PRINT
3508 ohnum = hnum = hlast = histnum(-1) + 1;
3510 saved_inslen = inslen;
3511 first_insert = true;
3516 if (undobuf.cbuf == NULL) {
3517 ibuf = alloc(LINE, AEDIT);
3518 ybuf = alloc(LINE, AEDIT);
3519 undobuf.cbuf = alloc(LINE, AEDIT);
3521 undobuf.cbufsize = ebuf.cbufsize = LINE;
3522 undobuf.linelen = ebuf.linelen = 0;
3523 undobuf.cursor = ebuf.cursor = 0;
3524 undobuf.winleft = ebuf.winleft = 0;
3528 x_init_prompt(true);
3531 if (wbuf_len != x_cols - 3 && ((wbuf_len = x_cols - 3))) {
3532 wbuf[0] = aresize(wbuf[0], wbuf_len, AEDIT);
3533 wbuf[1] = aresize(wbuf[1], wbuf_len, AEDIT);
3536 memset(wbuf[0], ' ', wbuf_len);
3537 memset(wbuf[1], ' ', wbuf_len);
3539 winwidth = x_cols - pwidth - 3;
3547 while (/* CONSTCOND */ 1) {
3549 c = (unsigned char)*macro.p++;
3550 /* end of current macro? */
3552 /* more macros left to finish? */
3555 /* must be the end of all the macros */
3564 if (state != VLIT) {
3565 if (isched(c, edchars.intr) ||
3566 isched(c, edchars.quit)) {
3567 /* pretend we got an interrupt */
3570 trapsig(isched(c, edchars.intr) ?
3574 } else if (isched(c, edchars.eof) &&
3575 state != VVERSION) {
3576 if (es->linelen == 0) {
3593 if (c == -1 || (ssize_t)LINE <= es->linelen)
3596 if (es->cbuf != buf)
3597 memcpy(buf, es->cbuf, es->linelen);
3599 buf[es->linelen++] = '\n';
3601 return (es->linelen);
3607 static char curcmd[MAXVICMD], locpat[SRCHLEN];
3608 static int cmdlen, argc1, argc2;
3614 if (!ch) switch (cmdlen = 0, (ch = x_getc())) {
3615 case 71: ch = '0'; goto pseudo_vi_command;
3616 case 72: ch = 'k'; goto pseudo_vi_command;
3617 case 73: ch = 'A'; goto vi_xfunc_search_up;
3618 case 75: ch = 'h'; goto pseudo_vi_command;
3619 case 77: ch = 'l'; goto pseudo_vi_command;
3620 case 79: ch = '$'; goto pseudo_vi_command;
3621 case 80: ch = 'j'; goto pseudo_vi_command;
3622 case 83: ch = 'x'; goto pseudo_vi_command;
3623 default: ch = 0; goto vi_insert_failed;
3626 if (ch == CTRL('v')) {
3630 switch (vi_insert(ch)) {
3637 if (state == VLIT) {
3641 refresh(insert != 0);
3647 if (ch == '\r' || ch == '\n')
3651 if (ch >= ord('1') && ch <= ord('9')) {
3652 argc1 = ksh_numdig(ch);
3656 curcmd[cmdlen++] = ch;
3657 state = nextstate(ch);
3658 if (state == VSEARCH) {
3662 if (putbuf(ch == '/' ? "/" : "?", 1,
3667 if (state == VVERSION) {
3672 strlen(KSH_VERSION), false);
3681 del_range(es->cursor, es->cursor + 1);
3684 es->cbuf[es->cursor++] = ch;
3696 if (ksh_isdigit(ch))
3697 argc1 = argc1 * 10 + ksh_numdig(ch);
3699 curcmd[cmdlen++] = ch;
3700 state = nextstate(ch);
3706 if (ch >= ord('1') && ch <= ord('9')) {
3707 argc2 = ksh_numdig(ch);
3711 curcmd[cmdlen++] = ch;
3712 if (ch == curcmd[0])
3714 else if (is_move(ch))
3715 state = nextstate(ch);
3722 if (ksh_isdigit(ch))
3723 argc2 = argc2 * 10 + ksh_numdig(ch);
3729 curcmd[cmdlen++] = ch;
3730 if (ch == curcmd[0])
3732 else if (is_move(ch))
3733 state = nextstate(ch);
3740 if (ch == CTRL('['))
3743 curcmd[cmdlen++] = ch;
3749 if (ch == '\r' || ch == '\n' /*|| ch == CTRL('[')*/ ) {
3751 /* Repeat last search? */
3760 locpat[srchlen] = '\0';
3761 memcpy(srchpat, locpat, srchlen + 1);
3764 } else if (isched(ch, edchars.erase) || ch == CTRL('h')) {
3767 es->linelen -= char_len(locpat[srchlen]);
3768 es->cursor = es->linelen;
3775 } else if (isched(ch, edchars.kill)) {
3781 } else if (isched(ch, edchars.werase)) {
3783 struct edstate new_es, *save_es;
3785 new_es.cursor = srchlen;
3786 new_es.cbuf = locpat;
3793 i = (unsigned)srchlen;
3795 es->linelen -= char_len(locpat[i]);
3797 es->cursor = es->linelen;
3801 if (srchlen == SRCHLEN - 1)
3804 locpat[srchlen++] = ch;
3805 if (ISCTRL(ch) && /* but not C1 */ ch < 0x80) {
3806 if ((size_t)es->linelen + 2 >
3807 (size_t)es->cbufsize)
3809 es->cbuf[es->linelen++] = '^';
3810 es->cbuf[es->linelen++] = UNCTRL(ch);
3812 if (es->linelen >= es->cbufsize)
3814 es->cbuf[es->linelen++] = ch;
3816 es->cursor = es->linelen;
3828 /* the cursor may not be at the BOL */
3831 /* nor further in the line than we can search for */
3832 if ((size_t)es->cursor >= sizeof(srchpat) - 1)
3833 es->cursor = sizeof(srchpat) - 2;
3834 /* anchor the search pattern */
3836 /* take the current line up to the cursor */
3837 memmove(srchpat + 1, es->cbuf, es->cursor);
3838 srchpat[es->cursor + 1] = '\0';
3839 /* set a magic flag */
3840 argc1 = 2 + (int)es->cursor;
3841 /* and emulate a backwards history search */
3853 switch (vi_cmd(argc1, curcmd)) {
3861 refresh(insert != 0);
3867 /* back from a 'v' command - don't redraw the screen */
3876 switch (vi_cmd(lastac, lastcmd)) {
3883 if (lastcmd[0] == 's' || lastcmd[0] == 'c' ||
3884 lastcmd[0] == 'C') {
3885 if (redo_insert(1) != 0)
3888 if (redo_insert(lastac) != 0)
3898 /* back from a 'v' command - can't happen */
3916 else if (is_srch(ch))
3918 else if (is_long(ch))
3922 else if (ch == CTRL('v'))
3924 else if (is_cmd(ch))
3935 if (isched(ch, edchars.erase) || ch == CTRL('h')) {
3936 if (insert == REPLACE) {
3937 if (es->cursor == undo->cursor) {
3944 if (es->cursor >= undo->linelen)
3947 es->cbuf[es->cursor] = undo->cbuf[es->cursor];
3949 if (es->cursor == 0)
3955 memmove(&es->cbuf[es->cursor], &es->cbuf[es->cursor + 1],
3956 es->linelen - es->cursor + 1);
3961 if (isched(ch, edchars.kill)) {
3962 if (es->cursor != 0) {
3964 memmove(es->cbuf, &es->cbuf[es->cursor],
3965 es->linelen - es->cursor);
3966 es->linelen -= es->cursor;
3972 if (isched(ch, edchars.werase)) {
3973 if (es->cursor != 0) {
3974 tcursor = backword(1);
3975 memmove(&es->cbuf[tcursor], &es->cbuf[es->cursor],
3976 es->linelen - es->cursor);
3977 es->linelen -= es->cursor - tcursor;
3978 if (inslen < es->cursor - tcursor)
3981 inslen -= es->cursor - tcursor;
3982 es->cursor = tcursor;
3988 * If any chars are entered before escape, trash the saved insert
3989 * buffer (if user inserts & deletes char, ibuf gets trashed and
3990 * we don't want to use it)
3992 if (first_insert && ch != CTRL('['))
4005 first_insert = false;
4007 inslen = saved_inslen;
4008 return (redo_insert(0));
4013 if (lastcmd[0] == 's' || lastcmd[0] == 'c' ||
4015 return (redo_insert(0));
4017 return (redo_insert(lastac - 1));
4019 /* { Begin nonstandard vi commands */
4025 complete_word(0, 0);
4029 print_expansions(es, 0);
4033 if (Flag(FVITABCOMPLETE)) {
4034 complete_word(0, 0);
4038 /* End nonstandard vi commands } */
4041 if (es->linelen >= es->cbufsize - 1)
4043 ibuf[inslen++] = ch;
4044 if (insert == INSERT) {
4045 memmove(&es->cbuf[es->cursor + 1], &es->cbuf[es->cursor],
4046 es->linelen - es->cursor);
4049 es->cbuf[es->cursor++] = ch;
4050 if (insert == REPLACE && es->cursor > es->linelen)
4058 vi_cmd(int argcnt, const char *cmd)
4061 int cur, c1, c2, c3 = 0;
4065 if (argcnt == 0 && !is_zerocount(*cmd))
4068 if (is_move(*cmd)) {
4069 if ((cur = domove(argcnt, cmd, 0)) >= 0) {
4070 if (cur == es->linelen && cur != 0)
4076 /* Don't save state in middle of macro.. */
4077 if (is_undoable(*cmd) && !macro.p) {
4078 undo->winleft = es->winleft;
4079 memmove(undo->cbuf, es->cbuf, es->linelen);
4080 undo->linelen = es->linelen;
4081 undo->cursor = es->cursor;
4083 memmove(lastcmd, cmd, MAXVICMD);
4094 static char alias[] = "_\0";
4099 /* lookup letter in alias list... */
4101 ap = ktsearch(&aliases, alias, hash(alias));
4102 if (!cmd[1] || !ap || !(ap->flag & ISSET))
4104 /* check if this is a recursive call... */
4105 if ((p = (char *)macro.p))
4106 while ((p = strnul(p)) && p[1])
4109 /* insert alias into macro buffer */
4110 nlen = strlen(ap->val.s) + 1;
4111 olen = !macro.p ? 2 :
4112 macro.len - (macro.p - macro.buf);
4114 * at this point, it's fairly reasonable that
4115 * nlen + olen + 2 doesn't overflow
4117 nbuf = alloc(nlen + 1 + olen, AEDIT);
4118 memcpy(nbuf, ap->val.s, nlen);
4119 nbuf[nlen++] = cmd[1];
4121 memcpy(nbuf + nlen, macro.p, olen);
4122 afree(macro.buf, AEDIT);
4125 nbuf[nlen++] = '\0';
4126 nbuf[nlen++] = '\0';
4128 macro.p = macro.buf = (unsigned char *)nbuf;
4136 if (es->linelen != 0)
4145 es->cursor = es->linelen;
4150 es->cursor = domove(1, "^", 1);
4151 del_range(es->cursor, es->linelen);
4163 if (*cmd == cmd[1]) {
4164 c1 = *cmd == 'c' ? domove(1, "^", 1) : 0;
4166 } else if (!is_move(cmd[1]))
4169 if ((ncursor = domove(argcnt, &cmd[1], 1)) < 0)
4172 (cmd[1] == 'w' || cmd[1] == 'W') &&
4173 !ksh_isspace(es->cbuf[es->cursor])) {
4176 } while (ksh_isspace(es->cbuf[ncursor]));
4179 if (ncursor > es->cursor) {
4189 if (*cmd != 'c' && c1 != c2)
4205 if (es->linelen != 0)
4207 while (putbuf(ybuf, yanklen, false) == 0 &&
4210 if (es->cursor != 0)
4220 while (putbuf(ybuf, yanklen, false) == 0 &&
4223 if (any && es->cursor != 0)
4232 del_range(es->cursor, es->linelen);
4237 yank_range(es->cursor, es->linelen);
4238 del_range(es->cursor, es->linelen);
4239 if (es->cursor != 0)
4251 argcnt = hlast - (source->line - argcnt);
4252 if (grabhist(modified, argcnt - 1) < 0)
4269 es->cursor = domove(1, "^", 1);
4276 if (grabhist(modified, hnum + argcnt) < 0)
4287 if (grabhist(modified, hnum - argcnt) < 0)
4296 if (es->linelen == 0)
4305 if (es->cursor + argcnt > es->linelen)
4307 for (n = 0; n < argcnt; ++n)
4308 es->cbuf[es->cursor + n] = cmd[1];
4309 es->cursor += n - 1;
4320 if (es->linelen == 0)
4324 if (es->cursor + argcnt > es->linelen)
4325 argcnt = es->linelen - es->cursor;
4326 del_range(es->cursor, es->cursor + argcnt);
4332 if (es->linelen == 0)
4335 es->cbuf[es->linelen] = '\0';
4336 histsave(&source->line, es->cbuf,
4339 argcnt = source->line + 1 -
4343 shf_snprintf(es->cbuf, es->cbufsize, Tf_sd,
4344 "fc -e ${VISUAL:-${EDITOR:-vi}} --",
4348 "fc -e ${VISUAL:-${EDITOR:-vi}} --",
4350 es->linelen = strlen(es->cbuf);
4354 if (es->linelen == 0)
4358 if (es->cursor + argcnt > es->linelen)
4359 argcnt = es->linelen - es->cursor;
4360 yank_range(es->cursor, es->cursor + argcnt);
4361 del_range(es->cursor, es->cursor + argcnt);
4365 if (es->cursor > 0) {
4368 if (es->cursor < argcnt)
4369 argcnt = es->cursor;
4370 yank_range(es->cursor - argcnt, es->cursor);
4371 del_range(es->cursor - argcnt, es->cursor);
4372 es->cursor -= argcnt;
4386 if (grabhist(modified, ohnum) < 0)
4403 if (lastsearch == ' ')
4405 if (lastsearch == '?')
4411 if ((c2 = grabsearch(modified, hnum,
4412 c1, srchpat)) < 0) {
4424 /* flag from cursor-up command */
4425 es->cursor = argcnt - 2;
4434 if (histnum(-1) < 0)
4437 #define issp(c) (ksh_isspace(c) || (c) == '\n')
4439 while (*p && issp(*p))
4441 while (*p && --argcnt) {
4442 while (*p && !issp(*p))
4444 while (*p && issp(*p))
4466 if (es->cursor != es->linelen)
4468 while (*p && !issp(*p)) {
4472 if (putbuf(T1space, 1, false) != 0 ||
4473 putbuf(sp, argcnt, false) != 0) {
4474 if (es->cursor != 0)
4487 if (es->linelen == 0)
4489 for (i = 0; i < argcnt; i++) {
4490 p = &es->cbuf[es->cursor];
4491 if (ksh_islower(*p)) {
4494 *p = ksh_toupper(*p);
4495 } else if (ksh_isupper(*p)) {
4498 *p = ksh_tolower(*p);
4500 if (es->cursor < es->linelen - 1)
4508 int ret = x_do_comment(es->cbuf, es->cbufsize,
4517 /* Nonstandard vi/ksh */
4519 print_expansions(es, 1);
4523 /* Nonstandard vi/ksh */
4525 if (!Flag(FVITABCOMPLETE))
4527 complete_word(1, argcnt);
4530 /* some annoying AT&T kshs */
4532 if (!Flag(FVIESCCOMPLETE))
4536 /* Nonstandard vi/ksh */
4538 complete_word(1, argcnt);
4544 /* Nonstandard vi/ksh */
4550 /* mksh: cursor movement */
4554 if (es->linelen != 0)
4559 if (insert == 0 && es->cursor != 0 && es->cursor >= es->linelen)
4566 domove(int argcnt, const char *cmd, int sub)
4568 int ncursor = 0, i = 0, t;
4569 unsigned int bcount;
4573 if (!sub && es->cursor == 0)
4575 ncursor = backword(argcnt);
4579 if (!sub && es->cursor == 0)
4581 ncursor = Backword(argcnt);
4585 if (!sub && es->cursor + 1 >= es->linelen)
4587 ncursor = endword(argcnt);
4588 if (sub && ncursor < es->linelen)
4593 if (!sub && es->cursor + 1 >= es->linelen)
4595 ncursor = Endword(argcnt);
4596 if (sub && ncursor < es->linelen)
4610 if (fsavecmd == ' ')
4612 i = fsavecmd == 'f' || fsavecmd == 'F';
4616 if ((ncursor = findch(fsavech, argcnt, tobool(t),
4625 if (!sub && es->cursor == 0)
4627 ncursor = es->cursor - argcnt;
4634 if (!sub && es->cursor + 1 >= es->linelen)
4636 if (es->linelen != 0) {
4637 ncursor = es->cursor + argcnt;
4638 if (ncursor > es->linelen)
4639 ncursor = es->linelen;
4644 if (!sub && es->cursor + 1 >= es->linelen)
4646 ncursor = forwword(argcnt);
4650 if (!sub && es->cursor + 1 >= es->linelen)
4652 ncursor = Forwword(argcnt);
4661 while (ncursor < es->linelen - 1 &&
4662 ksh_isspace(es->cbuf[ncursor]))
4668 if (ncursor > es->linelen)
4669 ncursor = es->linelen;
4675 if (es->linelen != 0)
4676 ncursor = es->linelen;
4682 ncursor = es->cursor;
4683 while (ncursor < es->linelen &&
4684 (i = bracktype(es->cbuf[ncursor])) == 0)
4686 if (ncursor == es->linelen)
4691 if (++ncursor >= es->linelen)
4697 t = bracktype(es->cbuf[ncursor]);
4702 } while (bcount != 0);
4714 redo_insert(int count)
4717 if (putbuf(ibuf, inslen, tobool(insert == REPLACE)) != 0)
4726 yank_range(int a, int b)
4730 memmove(ybuf, &es->cbuf[a], yanklen);
4762 * Non user interface editor routines below here
4768 memmove(holdbufp, es->cbuf, es->linelen);
4769 holdlen = es->linelen;
4770 holdbufp[holdlen] = '\0';
4777 es->linelen = holdlen;
4778 memmove(es->cbuf, holdbufp, holdlen);
4781 /* return a new edstate */
4782 static struct edstate *
4783 save_edstate(struct edstate *old)
4785 struct edstate *news;
4787 news = alloc(sizeof(struct edstate), AEDIT);
4788 news->cbuf = alloc(old->cbufsize, AEDIT);
4789 memcpy(news->cbuf, old->cbuf, old->linelen);
4790 news->cbufsize = old->cbufsize;
4791 news->linelen = old->linelen;
4792 news->cursor = old->cursor;
4793 news->winleft = old->winleft;
4798 restore_edstate(struct edstate *news, struct edstate *old)
4800 memcpy(news->cbuf, old->cbuf, old->linelen);
4801 news->linelen = old->linelen;
4802 news->cursor = old->cursor;
4803 news->winleft = old->winleft;
4808 free_edstate(struct edstate *old)
4810 afree(old->cbuf, AEDIT);
4815 * this is used for calling x_escape() in complete_word()
4818 x_vi_putbuf(const char *s, size_t len)
4820 return (putbuf(s, len, false));
4824 putbuf(const char *buf, ssize_t len, bool repl)
4829 if (es->cursor + len >= es->cbufsize)
4831 if (es->cursor + len > es->linelen)
4832 es->linelen = es->cursor + len;
4834 if (es->linelen + len >= es->cbufsize)
4836 memmove(&es->cbuf[es->cursor + len], &es->cbuf[es->cursor],
4837 es->linelen - es->cursor);
4840 memmove(&es->cbuf[es->cursor], buf, len);
4846 del_range(int a, int b)
4848 if (es->linelen != b)
4849 memmove(&es->cbuf[a], &es->cbuf[b], es->linelen - b);
4850 es->linelen -= b - a;
4854 findch(int ch, int cnt, bool forw, bool incl)
4858 if (es->linelen == 0)
4860 ncursor = es->cursor;
4864 if (++ncursor == es->linelen)
4870 } while (es->cbuf[ncursor] != ch);
4882 forwword(int argcnt)
4886 ncursor = es->cursor;
4887 while (ncursor < es->linelen && argcnt--) {
4888 if (ksh_isalnux(es->cbuf[ncursor]))
4889 while (ncursor < es->linelen &&
4890 ksh_isalnux(es->cbuf[ncursor]))
4892 else if (!ksh_isspace(es->cbuf[ncursor]))
4893 while (ncursor < es->linelen &&
4894 !ksh_isalnux(es->cbuf[ncursor]) &&
4895 !ksh_isspace(es->cbuf[ncursor]))
4897 while (ncursor < es->linelen &&
4898 ksh_isspace(es->cbuf[ncursor]))
4905 backword(int argcnt)
4909 ncursor = es->cursor;
4910 while (ncursor > 0 && argcnt--) {
4911 while (--ncursor > 0 && ksh_isspace(es->cbuf[ncursor]))
4914 if (ksh_isalnux(es->cbuf[ncursor]))
4915 while (--ncursor >= 0 &&
4916 ksh_isalnux(es->cbuf[ncursor]))
4919 while (--ncursor >= 0 &&
4920 !ksh_isalnux(es->cbuf[ncursor]) &&
4921 !ksh_isspace(es->cbuf[ncursor]))
4934 ncursor = es->cursor;
4935 while (ncursor < es->linelen && argcnt--) {
4936 while (++ncursor < es->linelen - 1 &&
4937 ksh_isspace(es->cbuf[ncursor]))
4939 if (ncursor < es->linelen - 1) {
4940 if (ksh_isalnux(es->cbuf[ncursor]))
4941 while (++ncursor < es->linelen &&
4942 ksh_isalnux(es->cbuf[ncursor]))
4945 while (++ncursor < es->linelen &&
4946 !ksh_isalnux(es->cbuf[ncursor]) &&
4947 !ksh_isspace(es->cbuf[ncursor]))
4956 Forwword(int argcnt)
4960 ncursor = es->cursor;
4961 while (ncursor < es->linelen && argcnt--) {
4962 while (ncursor < es->linelen &&
4963 !ksh_isspace(es->cbuf[ncursor]))
4965 while (ncursor < es->linelen &&
4966 ksh_isspace(es->cbuf[ncursor]))
4973 Backword(int argcnt)
4977 ncursor = es->cursor;
4978 while (ncursor > 0 && argcnt--) {
4979 while (--ncursor >= 0 && ksh_isspace(es->cbuf[ncursor]))
4981 while (ncursor >= 0 && !ksh_isspace(es->cbuf[ncursor]))
4993 ncursor = es->cursor;
4994 while (ncursor < es->linelen - 1 && argcnt--) {
4995 while (++ncursor < es->linelen - 1 &&
4996 ksh_isspace(es->cbuf[ncursor]))
4998 if (ncursor < es->linelen - 1) {
4999 while (++ncursor < es->linelen &&
5000 !ksh_isspace(es->cbuf[ncursor]))
5009 grabhist(int save, int n)
5013 if (n < 0 || n > hlast)
5021 if ((hptr = *histpos()) == NULL) {
5022 internal_warningf("grabhist: bad history array");
5027 if ((es->linelen = strlen(hptr)) >= es->cbufsize)
5028 es->linelen = es->cbufsize - 1;
5029 memmove(es->cbuf, hptr, es->linelen);
5036 grabsearch(int save, int start, int fwd, const char *pat)
5042 if ((start == 0 && fwd == 0) || (start >= hlast - 1 && fwd == 1))
5048 anchored = *pat == '^' ? (++pat, true) : false;
5049 if ((hist = findhist(start, fwd, pat, anchored)) < 0) {
5050 /* (start != 0 && fwd && match(holdbufp, pat) >= 0) */
5051 if (start != 0 && fwd && strcmp(holdbufp, pat) >= 0) {
5061 if ((es->linelen = strlen(hptr)) >= es->cbufsize)
5062 es->linelen = es->cbufsize - 1;
5063 memmove(es->cbuf, hptr, es->linelen);
5069 redraw_line(bool newl)
5072 memset(wbuf[win], ' ', wbuf_len);
5082 refresh(int leftside)
5090 display(wbuf[1 - win], wbuf[win], leftside);
5099 if (es->cursor < es->winleft)
5103 while (cur < es->cursor)
5104 col = newcol((unsigned char)es->cbuf[cur++], col);
5105 if (col >= winwidth)
5114 int holdcur1, holdcol1;
5115 int holdcur2, holdcol2;
5117 holdcur1 = holdcur2 = tcur = 0;
5118 holdcol1 = holdcol2 = tcol = 0;
5119 while (tcur < es->cursor) {
5120 if (tcol - holdcol2 > winwidth / 2) {
5121 holdcur1 = holdcur2;
5122 holdcol1 = holdcol2;
5126 tcol = newcol((unsigned char)es->cbuf[tcur++], tcol);
5128 while (tcol - holdcol1 > winwidth / 2)
5129 holdcol1 = newcol((unsigned char)es->cbuf[holdcur1++],
5131 es->winleft = holdcur1;
5135 newcol(unsigned char ch, int col)
5138 return ((col | 7) + 1);
5139 return (col + char_len(ch));
5143 display(char *wb1, char *wb2, int leftside)
5146 char *twb1, *twb2, mc;
5155 while (col < winwidth && cur < es->linelen) {
5156 if (cur == es->cursor && leftside)
5157 ncol = col + pwidth;
5158 if ((ch = es->cbuf[cur]) == '\t')
5161 } while (++col < winwidth && (col & 7) != 0);
5162 else if (col < winwidth) {
5163 if (ISCTRL(ch) && /* but not C1 */ ch < 0x80) {
5165 if (++col < winwidth) {
5166 *twb1++ = UNCTRL(ch);
5174 if (cur == es->cursor && !leftside)
5175 ncol = col + pwidth - 1;
5178 if (cur == es->cursor)
5179 ncol = col + pwidth;
5180 if (col < winwidth) {
5181 while (col < winwidth) {
5194 if (*twb1 != *twb2) {
5196 ed_mov_opt(col, wb1);
5204 if (es->winleft > 0 && moreright)
5206 * POSIX says to use * for this but that is a globbing
5207 * character and may confuse people; + is more innocuous
5210 else if (es->winleft > 0)
5217 ed_mov_opt(pwidth + winwidth + 1, wb1);
5223 ed_mov_opt(ncol, wb1);
5227 ed_mov_opt(int col, char *wb)
5230 if (col + 1 < x_col - col) {
5233 while (x_col++ < col)
5236 while (x_col-- > col)
5240 wb = &wb[x_col - pwidth];
5241 while (x_col++ < col)
5248 /* replace word with all expansions (ie, expand word*) */
5250 expand_word(int cmd)
5252 static struct edstate *buf;
5253 int rval = 0, nwords, start, end, i;
5256 /* Undo previous expansion */
5257 if (cmd == 0 && expanded == EXPAND && buf) {
5258 restore_edstate(es, buf);
5268 i = XCF_COMMAND_FILE | XCF_FULLPATH;
5269 nwords = x_cf_glob(&i, es->cbuf, es->linelen, es->cursor,
5270 &start, &end, &words);
5276 buf = save_edstate(es);
5278 del_range(start, end);
5281 while (i < nwords) {
5282 if (x_escape(words[i], strlen(words[i]), x_vi_putbuf) != 0) {
5286 if (++i < nwords && putbuf(T1space, 1, false) != 0) {
5291 i = buf->cursor - end;
5292 if (rval == 0 && i > 0)
5303 complete_word(int cmd, int count)
5305 static struct edstate *buf;
5306 int rval, nwords, start, end, flags;
5312 /* Undo previous completion */
5313 if (cmd == 0 && expanded == COMPLETE && buf) {
5314 print_expansions(buf, 0);
5318 if (cmd == 0 && expanded == PRINT && buf) {
5319 restore_edstate(es, buf);
5330 * XCF_FULLPATH for count 'cause the menu printed by
5331 * print_expansions() was done this way.
5333 flags = XCF_COMMAND_FILE;
5335 flags |= XCF_FULLPATH;
5336 nwords = x_cf_glob(&flags, es->cbuf, es->linelen, es->cursor,
5337 &start, &end, &words);
5346 if (count >= nwords) {
5348 x_print_expansions(nwords, words,
5349 tobool(flags & XCF_IS_COMMAND));
5350 x_free_words(nwords, words);
5355 * Expand the count'th word to its basename
5357 if (flags & XCF_IS_COMMAND) {
5358 match = words[count] +
5359 x_basename(words[count], NULL);
5360 /* If more than one possible match, use full path */
5361 for (i = 0; i < nwords; i++)
5363 strcmp(words[i] + x_basename(words[i],
5364 NULL), match) == 0) {
5365 match = words[count];
5369 match = words[count];
5370 match_len = strlen(match);
5372 /* expanded = PRINT; next call undo */
5375 match_len = x_longest_prefix(nwords, words);
5376 /* next call will list completions */
5377 expanded = COMPLETE;
5378 is_unique = nwords == 1;
5381 buf = save_edstate(es);
5382 del_range(start, end);
5386 * escape all shell-sensitive characters and put the result into
5389 rval = x_escape(match, match_len, x_vi_putbuf);
5391 if (rval == 0 && is_unique) {
5393 * If exact match, don't undo. Allows directory completions
5394 * to be used (ie, complete the next portion of the path).
5399 * append a space if this is a non-directory match
5400 * and not a parameter or homedir substitution
5402 if (match_len > 0 && match[match_len - 1] != '/' &&
5403 !(flags & XCF_IS_NOSPACE))
5404 rval = putbuf(T1space, 1, false);
5406 x_free_words(nwords, words);
5411 /* prevent this from being redone... */
5419 print_expansions(struct edstate *est, int cmd MKSH_A_UNUSED)
5421 int start, end, nwords, i;
5424 i = XCF_COMMAND_FILE | XCF_FULLPATH;
5425 nwords = x_cf_glob(&i, est->cbuf, est->linelen, est->cursor,
5426 &start, &end, &words);
5431 x_print_expansions(nwords, words, tobool(i & XCF_IS_COMMAND));
5432 x_free_words(nwords, words);
5437 /* Similar to x_zotc(emacs.c), but no tab weirdness */
5451 /* Beem out of any macros as soon as an error occurs */
5458 vi_macro_reset(void)
5461 afree(macro.buf, AEDIT);
5462 memset((char *)¯o, 0, sizeof(macro));
5465 #endif /* !MKSH_S_NOVI */
5467 /* called from main.c */
5474 * set edchars to force initial binding, except we need
5475 * default values for ^W for some deficient systems…
5477 edchars.erase = edchars.kill = edchars.intr = edchars.quit =
5478 edchars.eof = EDCHAR_INITIAL;
5479 edchars.werase = 027;
5481 /* command line editing specific memory allocation */
5483 holdbufp = alloc(LINE, AEDIT);
5485 /* initialise Emacs command line editing mode */
5488 x_tab = alloc2(X_NTABS, sizeof(*x_tab), AEDIT);
5489 for (j = 0; j < X_TABSZ; j++)
5490 x_tab[0][j] = XFUNC_insert;
5491 for (i = 1; i < X_NTABS; i++)
5492 for (j = 0; j < X_TABSZ; j++)
5493 x_tab[i][j] = XFUNC_error;
5494 for (i = 0; i < (int)NELEM(x_defbindings); i++)
5495 x_tab[x_defbindings[i].xdb_tab][x_defbindings[i].xdb_char]
5496 = x_defbindings[i].xdb_func;
5499 x_atab = alloc2(X_NTABS, sizeof(*x_atab), AEDIT);
5500 for (i = 1; i < X_NTABS; i++)
5501 for (j = 0; j < X_TABSZ; j++)
5502 x_atab[i][j] = NULL;
5516 x_initterm(const char *termtype)
5518 /* default must be 0 (bss) */
5520 /* this is what tmux uses, don't ask me about it */
5521 if (!strcmp(termtype, "screen") || !strncmp(termtype, "screen-", 7))
5527 x_eval_region_helper(const char *cmd, size_t len)
5532 if (!kshsetjmp(e->jbuf)) {
5533 char *wds = alloc(len + 3, ATEMP);
5536 memcpy(wds + 1, cmd, len);
5537 wds[len + 1] = '\0';
5540 cp = evalstr(wds, DOSCALAR);
5541 strdupx(cp, cp, AEDIT);
5549 x_eval_region(int c MKSH_A_UNUSED)
5551 char *evbeg, *evend, *cp;
5553 /* only for LINE overflow checking */
5559 } else if (xmp < xcp) {
5568 x_clrtoeol(' ', false);
5571 cp = x_eval_region_helper(evbeg, evend - evbeg);
5575 /* command cannot be parsed */
5582 newlen = strlen(cp);
5583 restlen = xep - evend;
5584 /* check for LINE overflow, until this is dynamically allocated */
5585 if (evbeg + newlen + restlen >= xend)
5586 goto x_eval_region_err;
5589 xcp = evbeg + newlen;
5590 xep = xcp + restlen;
5591 memmove(xcp, evend, restlen + /* NUL */ 1);
5592 memcpy(xmp, cp, newlen);
5598 #endif /* !MKSH_SMALL */
5599 #endif /* !MKSH_NO_CMDLINE_EDITING */