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
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.292 2015/10/09 16:11:13 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"
42 #ifndef MKSH_CLRTOEOL_STRING
43 #define MKSH_CLRTOEOL_STRING "\033[K"
46 /* tty driver characters we are interested in */
56 static X_chars edchars;
58 /* x_cf_glob() flags */
59 #define XCF_COMMAND BIT(0) /* Do command completion */
60 #define XCF_FILE BIT(1) /* Do file completion */
61 #define XCF_FULLPATH BIT(2) /* command completion: store full path */
62 #define XCF_COMMAND_FILE (XCF_COMMAND | XCF_FILE)
63 #define XCF_IS_COMMAND BIT(3) /* return flag: is command */
64 #define XCF_IS_NOSPACE BIT(4) /* return flag: do not append a space */
67 static int xx_cols; /* for Emacs mode */
68 static int modified; /* buffer has been "modified" */
69 static char *holdbufp; /* place to hold last edit buffer */
71 static int x_getc(void);
72 static void x_putcf(int);
73 static void x_modified(void);
74 static void x_mode(bool);
75 static int x_do_comment(char *, ssize_t, ssize_t *);
76 static void x_print_expansions(int, char * const *, bool);
77 static int x_cf_glob(int *, const char *, int, int, int *, int *, char ***);
78 static size_t x_longest_prefix(int, char * const *);
79 static void x_glob_hlp_add_qchar(char *);
80 static char *x_glob_hlp_tilde_and_rem_qchar(char *, bool);
81 static int x_basename(const char *, const char *);
82 static void x_free_words(int, char **);
83 static int x_escape(const char *, size_t, int (*)(const char *, size_t));
84 static int x_emacs(char *);
85 static void x_init_prompt(bool);
87 static int x_vi(char *);
90 #define x_flush() shf_flush(shl_out)
91 #if defined(MKSH_SMALL) && !defined(MKSH_SMALL_BUT_FAST)
92 #define x_putc(c) x_putcf(c)
94 #define x_putc(c) shf_putc((c), shl_out)
97 static int path_order_cmp(const void *, const void *);
98 static void glob_table(const char *, XPtrV *, struct table *);
99 static void glob_path(int, const char *, XPtrV *, const char *);
100 static int x_file_glob(int *, char *, char ***);
101 static int x_command_glob(int, char *, char ***);
102 static int x_locate_word(const char *, int, int, int *, bool *);
104 static int x_e_getmbc(char *);
105 static int x_e_rebuildline(const char *);
107 /* +++ generic editing functions +++ */
110 * read an edited command line
119 if (Flag(FEMACS) || Flag(FGMACS))
141 while ((n = blocking_read(STDIN_FILENO, &c, 1)) < 0 && errno == EINTR)
148 if (x_cols != xx_cols && editmode == 1) {
149 /* redraw line in Emacs mode */
151 x_init_prompt(false);
152 x_e_rebuildline(MKSH_CLRTOEOL_STRING);
158 return ((n == 1) ? (int)(unsigned char)c : -1);
164 shf_putc(c, shl_out);
167 /*********************************
168 * Misc common code for vi/emacs *
169 *********************************/
172 * Handle the commenting/uncommenting of a line.
174 * 1 if a carriage return is indicated (comment added)
175 * 0 if no return (comment removed)
176 * -1 if there is an error (not enough room for comment chars)
177 * If successful, *lenp contains the new length. Note: cursor should be
178 * moved to the start of the line after (un)commenting.
181 x_do_comment(char *buf, ssize_t bsize, ssize_t *lenp)
183 ssize_t i, j, len = *lenp;
186 /* somewhat arbitrary - it's what AT&T ksh does */
189 /* Already commented? */
193 for (j = 0, i = 1; i < len; i++) {
194 if (!saw_nl || buf[i] != '#')
196 saw_nl = buf[i] == '\n';
203 /* See if there's room for the #s - 1 per \n */
204 for (i = 0; i < len; i++)
207 if (len + n >= bsize)
209 /* Now add them... */
210 for (i = len, j = len + n; --i >= 0; ) {
221 /****************************************************
222 * Common file/command completion code for vi/emacs *
223 ****************************************************/
226 x_print_expansions(int nwords, char * const *words, bool is_command)
228 bool use_copy = false;
230 XPtrV l = { NULL, 0, 0 };
233 * Check if all matches are in the same directory (in this
234 * case, we want to omit the directory name)
237 (prefix_len = x_longest_prefix(nwords, words)) > 0) {
240 /* Special case for 1 match (prefix is whole word) */
242 prefix_len = x_basename(words[0], NULL);
243 /* Any (non-trailing) slashes in non-common word suffixes? */
244 for (i = 0; i < nwords; i++)
245 if (x_basename(words[i] + prefix_len, NULL) >
248 /* All in same directory? */
250 while (prefix_len > 0 && words[0][prefix_len - 1] != '/')
253 XPinit(l, nwords + 1);
254 for (i = 0; i < nwords; i++)
255 XPput(l, words[i] + prefix_len);
260 * Enumerate expansions
264 pr_list(use_copy ? (char **)XPptrv(l) : words);
267 /* not x_free_words() */
272 * Convert backslash-escaped string to QCHAR-escaped
273 * string useful for globbing; loses QCHAR unless it
274 * can squeeze in, eg. by previous loss of backslash
277 x_glob_hlp_add_qchar(char *cp)
280 bool escaping = false;
282 while ((ch = *cp++)) {
283 if (ch == '\\' && !escaping) {
287 if (escaping || (ch == QCHAR && (cp - dp) > 1)) {
289 * empirically made list of chars to escape
290 * for globbing as well as QCHAR itself
311 * Run tilde expansion on argument string, return the result
312 * after unescaping; if the flag is set, the original string
313 * is freed if changed and assumed backslash-escaped, if not
314 * it is assumed QCHAR-escaped
317 x_glob_hlp_tilde_and_rem_qchar(char *s, bool magic_flag)
322 * On the string, check whether we have a tilde expansion,
323 * and if so, discern "~foo/bar" and "~/baz" from "~blah";
324 * if we have a directory part (the former), try to expand
326 if (*s == '~' && (cp = strchr(s, '/')) != NULL) {
327 /* ok, so split into "~foo"/"bar" or "~"/"baz" */
329 /* try to expand the tilde */
330 if (!(dp = do_tilde(s + 1))) {
331 /* nope, revert damage */
334 /* ok, expand and replace */
335 cp = shf_smprintf("%s/%s", dp, cp);
342 /* ... convert it from backslash-escaped via QCHAR-escaped... */
344 x_glob_hlp_add_qchar(s);
345 /* ... to unescaped, for comparison with the matches */
348 while ((ch = *cp++)) {
349 if (ch == QCHAR && !(ch = *cp++))
360 * - does expansion, checks for no match, etc.
361 * - sets *wordsp to array of matching strings
362 * - returns number of matching strings
365 x_file_glob(int *flagsp, char *toglob, char ***wordsp)
370 struct source *s, *sold;
372 /* remove all escaping backward slashes */
373 x_glob_hlp_add_qchar(toglob);
376 * Convert "foo*" (toglob) to an array of strings (words)
379 s = pushs(SWSTR, ATEMP);
380 s->start = s->str = toglob;
382 if (yylex(ONEWORD | LQCHAR) != LWORD) {
384 internal_warningf("%s: %s", "fileglob", "bad substitution");
391 while (*cp == CHAR || *cp == QCHAR)
393 nwords = DOGLOB | DOTILDE | DOMARKDIRS;
395 /* probably a $FOO expansion */
396 *flagsp |= XCF_IS_NOSPACE;
397 /* this always results in at most one match */
400 expand(yylval.cp, &w, nwords);
402 words = (char **)XPclose(w);
404 for (nwords = 0; words[nwords]; nwords++)
409 /* Expand any tilde and drop all QCHAR for comparison */
410 toglob = x_glob_hlp_tilde_and_rem_qchar(toglob, false);
413 * Check if globbing failed (returned glob pattern),
414 * but be careful (e.g. toglob == "ab*" when the file
415 * "ab*" exists is not an error).
416 * Also, check for empty result - happens if we tried
417 * to glob something which evaluated to an empty
418 * string (e.g., "$FOO" when there is no FOO, etc).
420 if ((strcmp(words[0], toglob) == 0 &&
421 stat(words[0], &statb) < 0) ||
422 words[0][0] == '\0') {
423 x_free_words(nwords, words);
429 if ((*wordsp = nwords ? words : NULL) == NULL && words != NULL)
430 x_free_words(nwords, words);
435 /* Data structure used in x_command_glob() */
436 struct path_order_info {
442 /* Compare routine used in x_command_glob() */
444 path_order_cmp(const void *aa, const void *bb)
446 const struct path_order_info *a = (const struct path_order_info *)aa;
447 const struct path_order_info *b = (const struct path_order_info *)bb;
450 t = strcmp(a->word + a->base, b->word + b->base);
451 return (t ? t : a->path_order - b->path_order);
455 x_command_glob(int flags, char *toglob, char ***wordsp)
462 /* Convert "foo*" (toglob) to a pattern for future use */
463 pat = evalstr(toglob, DOPAT | DOTILDE);
467 glob_table(pat, &w, &keywords);
468 glob_table(pat, &w, &aliases);
469 glob_table(pat, &w, &builtins);
470 for (l = e->loc; l; l = l->next)
471 glob_table(pat, &w, &l->funs);
473 glob_path(flags, pat, &w, path);
474 if ((fpath = str_val(global("FPATH"))) != null)
475 glob_path(flags, pat, &w, fpath);
485 if (flags & XCF_FULLPATH) {
486 /* Sort by basename, then path order */
487 struct path_order_info *info, *last_info = NULL;
488 char **words = (char **)XPptrv(w);
489 size_t i, path_order = 0;
491 info = (struct path_order_info *)
492 alloc2(nwords, sizeof(struct path_order_info), ATEMP);
493 for (i = 0; i < nwords; i++) {
494 info[i].word = words[i];
495 info[i].base = x_basename(words[i], NULL);
496 if (!last_info || info[i].base != last_info->base ||
497 strncmp(words[i], last_info->word, info[i].base) != 0) {
498 last_info = &info[i];
501 info[i].path_order = path_order;
503 qsort(info, nwords, sizeof(struct path_order_info),
505 for (i = 0; i < nwords; i++)
506 words[i] = info[i].word;
509 /* Sort and remove duplicate entries */
510 char **words = (char **)XPptrv(w);
513 qsort(words, nwords, sizeof(void *), xstrcmp);
514 for (i = j = 0; i < nwords - 1; i++) {
515 if (strcmp(words[i], words[i + 1]))
516 words[j++] = words[i];
518 afree(words[i], ATEMP);
520 words[j++] = words[i];
525 *wordsp = (char **)XPclose(w);
530 #define IS_WORDC(c) (!ctype(c, C_LEX1) && (c) != '\'' && (c) != '"' && \
531 (c) != '`' && (c) != '=' && (c) != ':')
534 x_locate_word(const char *buf, int buflen, int pos, int *startp,
539 /* Bad call? Probably should report error */
540 if (pos < 0 || pos > buflen) {
542 *is_commandp = false;
545 /* The case where pos == buflen happens to take care of itself... */
549 * Keep going backwards to start of word (has effect of allowing
550 * one blank after the end of a word)
552 for (; (start > 0 && IS_WORDC(buf[start - 1])) ||
553 (start > 1 && buf[start - 2] == '\\'); start--)
555 /* Go forwards to end of word */
556 for (end = start; end < buflen && IS_WORDC(buf[end]); end++) {
557 if (buf[end] == '\\' && (end + 1) < buflen)
565 /* Figure out if this is a command */
566 while (p >= 0 && ksh_isspace(buf[p]))
568 iscmd = p < 0 || vstrchr(";|&()`", buf[p]);
571 * If command has a /, path, etc. is not searched;
572 * only current directory is searched which is just
573 * like file globbing.
575 for (p = start; p < end; p++)
580 *is_commandp = iscmd;
584 return (end - start);
588 x_cf_glob(int *flagsp, const char *buf, int buflen, int pos, int *startp,
589 int *endp, char ***wordsp)
595 len = x_locate_word(buf, buflen, pos, startp, &is_command);
596 if (!((*flagsp) & XCF_COMMAND))
599 * Don't do command globing on zero length strings - it takes too
600 * long and isn't very useful. File globs are more likely to be
601 * useful, so allow these.
603 if (len == 0 && is_command)
610 * Given a string, copy it and possibly add a '*' to the end.
613 strndupx(toglob, buf + *startp, len + /* the '*' */ 1, ATEMP);
617 * If the pathname contains a wildcard (an unquoted '*',
618 * '?', or '[') or an extglob, then it is globbed based
619 * on that value (i.e., without the appended '*'). Same
620 * for parameter substitutions (as in “cat $HOME/.ss↹”)
621 * without appending a trailing space (LP: #710539), as
622 * well as for “~foo” (but not “~foo/”).
624 for (s = toglob; *s; s++) {
625 if (*s == '\\' && s[1])
627 else if (*s == '?' || *s == '*' || *s == '[' ||
629 /* ?() *() +() @() !() but two already checked */
630 (s[1] == '(' /*)*/ &&
631 (*s == '+' || *s == '@' || *s == '!'))) {
633 * just expand based on the extglob
640 if (*toglob == '~' && !vstrchr(toglob, '/')) {
641 /* neither for '~foo' (but '~foo/bar') */
642 *flagsp |= XCF_IS_NOSPACE;
648 toglob[len + 1] = '\0';
651 * Expand (glob) it now.
654 nwords = is_command ?
655 x_command_glob(*flagsp, toglob, &words) :
656 x_file_glob(flagsp, toglob, &words);
657 afree(toglob, ATEMP);
664 *flagsp |= XCF_IS_COMMAND;
666 *endp = *startp + len;
672 * Find longest common prefix
675 x_longest_prefix(int nwords, char * const * words)
678 size_t j, prefix_len;
684 prefix_len = strlen(words[0]);
685 for (i = 1; i < nwords; i++)
686 for (j = 0, p = words[i]; j < prefix_len; j++)
687 if (p[j] != words[0][j]) {
691 /* false for nwords==1 as 0 = words[0][prefix_len] then */
692 if (UTFMODE && prefix_len && (words[0][prefix_len] & 0xC0) == 0x80)
693 while (prefix_len && (words[0][prefix_len] & 0xC0) != 0xC0)
699 x_free_words(int nwords, char **words)
702 afree(words[--nwords], ATEMP);
707 * Return the offset of the basename of string s (which ends at se - need not
708 * be null terminated). Trailing slashes are ignored. If s is just a slash,
709 * then the offset is 0 (actually, length - 1).
720 x_basename(const char *s, const char *se)
729 /* Skip trailing slashes */
730 for (p = se - 1; p > s && *p == '/'; p--)
732 for (; p > s && *p != '/'; p--)
734 if (*p == '/' && p + 1 < se)
741 * Apply pattern matching to a table: all table entries that match a pattern
745 glob_table(const char *pat, XPtrV *wp, struct table *tp)
751 while ((te = ktnext(&ts)))
752 if (gmatchx(te->name, pat, false)) {
755 strdupx(cp, te->name, ATEMP);
761 glob_path(int flags, const char *pat, XPtrV *wp, const char *lpath)
763 const char *sp = lpath, *p;
765 size_t pathlen, patlen, oldsize, newsize, i, j;
768 patlen = strlen(pat);
769 checkoktoadd(patlen, 129 + X_EXTRA);
771 Xinit(xs, xp, patlen + 128, ATEMP);
773 xp = Xstring(xs, xp);
774 if (!(p = cstrchr(sp, MKSH_PATHSEPC)))
779 * Copy sp into xp, stuffing any MAGIC characters
784 XcheckN(xs, xp, pathlen * 2);
794 XcheckN(xs, xp, patlen);
795 memcpy(xp, pat, patlen);
797 oldsize = XPsize(*wp);
799 glob_str(Xstring(xs, xp), wp, true);
800 newsize = XPsize(*wp);
802 /* Check that each match is executable... */
803 words = (char **)XPptrv(*wp);
804 for (i = j = oldsize; i < newsize; i++) {
805 if (ksh_access(words[i], X_OK) == 0) {
807 if (!(flags & XCF_FULLPATH))
808 memmove(words[j], words[j] + pathlen,
809 strlen(words[j] + pathlen) + 1);
812 afree(words[i], ATEMP);
823 * if argument string contains any special characters, they will
824 * be escaped and the result will be put into edit buffer by
825 * keybinding-specific function
828 x_escape(const char *s, size_t len, int (*putbuf_func)(const char *, size_t))
830 size_t add = 0, wlen = len;
831 const char *ifs = str_val(local("IFS", 0));
834 while (wlen - add > 0)
835 if (vstrchr("\"#$&'()*:;<=>?[\\`{|}", s[add]) ||
836 vstrchr(ifs, s[add])) {
837 if (putbuf_func(s, add) != 0) {
841 putbuf_func(s[add] == '\n' ? "'" : "\\", 1);
842 putbuf_func(&s[add], 1);
852 if (wlen > 0 && rval == 0)
853 rval = putbuf_func(s, wlen);
859 /* +++ emacs editing mode +++ */
862 #define AEDIT &aedit /* area for kill ring and macro defns */
864 /* values returned by keyboard functions */
866 #define KEOL 1 /* ^M, ^J */
867 #define KINTR 2 /* ^G, ^C */
870 int (*xf_func)(int c);
875 struct x_defbindings {
876 unsigned char xdb_func; /* XFUNC_* */
877 unsigned char xdb_tab;
878 unsigned char xdb_char;
881 #define XF_ARG 1 /* command takes number prefix */
882 #define XF_NOBIND 2 /* not allowed to bind to function */
883 #define XF_PREFIX 4 /* function sets prefix */
885 /* Separator for completion */
886 #define is_cfs(c) ((c) == ' ' || (c) == '\t' || (c) == '"' || (c) == '\'')
887 /* Separator for motion */
888 #define is_mfs(c) (!(ksh_isalnux(c) || (c) == '$' || ((c) & 0x80)))
890 #define X_NTABS 4 /* normal, meta1, meta2, pc */
891 #define X_TABSZ 256 /* size of keydef tables etc */
894 * Arguments for do_complete()
895 * 0 = enumerate M-= complete as much as possible and then list
900 CT_LIST, /* list the possible completions */
901 CT_COMPLETE, /* complete to longest prefix */
902 CT_COMPLIST /* complete and then list (if non-exact) */
906 * The following are used for my horizontal scrolling stuff
908 static char *xbuf; /* beg input buffer */
909 static char *xend; /* end input buffer */
910 static char *xcp; /* current position */
911 static char *xep; /* current end */
912 static char *xbp; /* start of visible portion of input buffer */
913 static char *xlp; /* last char visible on screen */
914 static bool x_adj_ok;
916 * we use x_adj_done so that functions can tell
917 * whether x_adjust() has been called while they are active.
919 static int x_adj_done; /* is incremented by x_adjust() */
921 static int x_displen;
922 static int x_arg; /* general purpose arg */
923 static bool x_arg_defaulted; /* x_arg not explicitly set; defaulted to 1 */
925 static bool xlp_valid; /* lastvis pointer was recalculated */
927 static char **x_histp; /* history position */
928 static int x_nextcmd; /* for newline-and-next */
929 static char **x_histncp; /* saved x_histp for " */
930 static char *xmp; /* mark pointer */
931 static unsigned char x_last_command;
932 static unsigned char (*x_tab)[X_TABSZ]; /* key definition */
934 static char *(*x_atab)[X_TABSZ]; /* macro definitions */
936 static unsigned char x_bound[(X_TABSZ * X_NTABS + 7) / 8];
938 static char *killstack[KILLSIZE];
939 static int killsp, killtp;
940 static int x_curprefix;
942 static char *macroptr; /* bind key macro active? */
945 static int winwidth; /* width of window */
946 static char *wbuf[2]; /* window buffers */
947 static int wbuf_len; /* length of window buffers (x_cols - 3) */
948 static int win; /* window buffer in use */
949 static char morec; /* more character at right of window */
950 static int lastref; /* argument to last refresh() */
951 static int holdlen; /* length of holdbuf */
953 static int pwidth; /* width of prompt */
954 static int prompt_trunc; /* how much of prompt to truncate or -1 */
955 static int x_col; /* current column on line */
957 static int x_ins(const char *);
958 static void x_delete(size_t, bool);
959 static size_t x_bword(void);
960 static size_t x_fword(bool);
961 static void x_goto(char *);
962 static char *x_bs0(char *, char *) MKSH_A_PURE;
963 static void x_bs3(char **);
964 static int x_size_str(char *);
965 static int x_size2(char *, char **);
966 static void x_zots(char *);
967 static void x_zotc3(char **);
968 static void x_load_hist(char **);
969 static int x_search(char *, int, int);
971 static int x_search_dir(int);
973 static int x_match(char *, char *);
974 static void x_redraw(int);
975 static void x_push(int);
976 static char *x_mapin(const char *, Area *);
977 static char *x_mapout(int);
978 static void x_mapout2(int, char **);
979 static void x_print(int, int);
980 static void x_adjust(void);
981 static void x_e_ungetc(int);
982 static int x_e_getc(void);
983 static void x_e_putc2(int);
984 static void x_e_putc3(const char **);
985 static void x_e_puts(const char *);
987 static int x_fold_case(int);
989 static char *x_lastcp(void);
990 static void do_complete(int, Comp_type);
991 static size_t x_nb2nc(size_t) MKSH_A_PURE;
993 static int unget_char = -1;
995 static int x_do_ins(const char *, size_t);
996 static void bind_if_not_bound(int, int, int);
999 #define EMACSFN_ENUMS
1000 #include "emacsfn.h"
1004 #define EMACSFN_DEFNS
1005 #include "emacsfn.h"
1007 static const struct x_ftab x_ftab[] = {
1008 #define EMACSFN_ITEMS
1009 #include "emacsfn.h"
1012 static struct x_defbindings const x_defbindings[] = {
1013 { XFUNC_del_back, 0, CTRL('?') },
1014 { XFUNC_del_bword, 1, CTRL('?') },
1015 { XFUNC_eot_del, 0, CTRL('D') },
1016 { XFUNC_del_back, 0, CTRL('H') },
1017 { XFUNC_del_bword, 1, CTRL('H') },
1018 { XFUNC_del_bword, 1, 'h' },
1019 { XFUNC_mv_bword, 1, 'b' },
1020 { XFUNC_mv_fword, 1, 'f' },
1021 { XFUNC_del_fword, 1, 'd' },
1022 { XFUNC_mv_back, 0, CTRL('B') },
1023 { XFUNC_mv_forw, 0, CTRL('F') },
1024 { XFUNC_search_char_forw, 0, CTRL(']') },
1025 { XFUNC_search_char_back, 1, CTRL(']') },
1026 { XFUNC_newline, 0, CTRL('M') },
1027 { XFUNC_newline, 0, CTRL('J') },
1028 { XFUNC_end_of_text, 0, CTRL('_') },
1029 { XFUNC_abort, 0, CTRL('G') },
1030 { XFUNC_prev_com, 0, CTRL('P') },
1031 { XFUNC_next_com, 0, CTRL('N') },
1032 { XFUNC_nl_next_com, 0, CTRL('O') },
1033 { XFUNC_search_hist, 0, CTRL('R') },
1034 { XFUNC_beg_hist, 1, '<' },
1035 { XFUNC_end_hist, 1, '>' },
1036 { XFUNC_goto_hist, 1, 'g' },
1037 { XFUNC_mv_end, 0, CTRL('E') },
1038 { XFUNC_mv_begin, 0, CTRL('A') },
1039 { XFUNC_draw_line, 0, CTRL('L') },
1040 { XFUNC_cls, 1, CTRL('L') },
1041 { XFUNC_meta1, 0, CTRL('[') },
1042 { XFUNC_meta2, 0, CTRL('X') },
1043 { XFUNC_kill, 0, CTRL('K') },
1044 { XFUNC_yank, 0, CTRL('Y') },
1045 { XFUNC_meta_yank, 1, 'y' },
1046 { XFUNC_literal, 0, CTRL('^') },
1047 { XFUNC_comment, 1, '#' },
1048 { XFUNC_transpose, 0, CTRL('T') },
1049 { XFUNC_complete, 1, CTRL('[') },
1050 { XFUNC_comp_list, 0, CTRL('I') },
1051 { XFUNC_comp_list, 1, '=' },
1052 { XFUNC_enumerate, 1, '?' },
1053 { XFUNC_expand, 1, '*' },
1054 { XFUNC_comp_file, 1, CTRL('X') },
1055 { XFUNC_comp_comm, 2, CTRL('[') },
1056 { XFUNC_list_comm, 2, '?' },
1057 { XFUNC_list_file, 2, CTRL('Y') },
1058 { XFUNC_set_mark, 1, ' ' },
1059 { XFUNC_kill_region, 0, CTRL('W') },
1060 { XFUNC_xchg_point_mark, 2, CTRL('X') },
1061 { XFUNC_literal, 0, CTRL('V') },
1062 { XFUNC_version, 1, CTRL('V') },
1063 { XFUNC_prev_histword, 1, '.' },
1064 { XFUNC_prev_histword, 1, '_' },
1065 { XFUNC_set_arg, 1, '0' },
1066 { XFUNC_set_arg, 1, '1' },
1067 { XFUNC_set_arg, 1, '2' },
1068 { XFUNC_set_arg, 1, '3' },
1069 { XFUNC_set_arg, 1, '4' },
1070 { XFUNC_set_arg, 1, '5' },
1071 { XFUNC_set_arg, 1, '6' },
1072 { XFUNC_set_arg, 1, '7' },
1073 { XFUNC_set_arg, 1, '8' },
1074 { XFUNC_set_arg, 1, '9' },
1076 { XFUNC_fold_upper, 1, 'U' },
1077 { XFUNC_fold_upper, 1, 'u' },
1078 { XFUNC_fold_lower, 1, 'L' },
1079 { XFUNC_fold_lower, 1, 'l' },
1080 { XFUNC_fold_capitalise, 1, 'C' },
1081 { XFUNC_fold_capitalise, 1, 'c' },
1084 * These for ANSI arrow keys: arguablely shouldn't be here by
1085 * default, but its simpler/faster/smaller than using termcap
1088 { XFUNC_meta2, 1, '[' },
1089 { XFUNC_meta2, 1, 'O' },
1090 { XFUNC_prev_com, 2, 'A' },
1091 { XFUNC_next_com, 2, 'B' },
1092 { XFUNC_mv_forw, 2, 'C' },
1093 { XFUNC_mv_back, 2, 'D' },
1095 { XFUNC_vt_hack, 2, '1' },
1096 { XFUNC_mv_begin | 0x80, 2, '7' },
1097 { XFUNC_mv_begin, 2, 'H' },
1098 { XFUNC_mv_end | 0x80, 2, '4' },
1099 { XFUNC_mv_end | 0x80, 2, '8' },
1100 { XFUNC_mv_end, 2, 'F' },
1101 { XFUNC_del_char | 0x80, 2, '3' },
1102 { XFUNC_del_char, 2, 'P' },
1103 { XFUNC_search_hist_up | 0x80, 2, '5' },
1104 { XFUNC_search_hist_dn | 0x80, 2, '6' },
1107 #if !defined(MKSH_SMALL) || defined(__OS2__)
1108 { XFUNC_meta3, 0, 0 },
1109 { XFUNC_mv_begin, 3, 71 },
1110 { XFUNC_prev_com, 3, 72 },
1112 { XFUNC_search_hist_up, 3, 73 },
1114 { XFUNC_mv_back, 3, 75 },
1115 { XFUNC_mv_forw, 3, 77 },
1116 { XFUNC_mv_end, 3, 79 },
1117 { XFUNC_next_com, 3, 80 },
1119 { XFUNC_search_hist_dn, 3, 81 },
1121 { XFUNC_del_char, 3, 83 },
1124 /* more non-standard ones */
1125 { XFUNC_edit_line, 2, 'e' }
1135 for (cp = xcp; cp < (xcp + nb); ++nc)
1136 cp += utf_ptradj(cp);
1144 x_histp = histptr + 1;
1150 #define XFUNC_VALUE(f) (f)
1152 #define XFUNC_VALUE(f) (f & 0x7F)
1156 x_e_getmbc(char *sbuf)
1159 unsigned char *buf = (unsigned char *)sbuf;
1162 buf[pos++] = c = x_e_getc();
1166 if ((buf[0] >= 0xC2) && (buf[0] < 0xF0)) {
1170 if ((c & 0xC0) != 0x80) {
1176 if ((buf[0] >= 0xE0) && (buf[0] < 0xF0)) {
1177 /* XXX x_e_ungetc is one-octet only */
1178 buf[pos++] = c = x_e_getc();
1187 x_init_prompt(bool doprint)
1189 prompt_trunc = pprompt(prompt, doprint ? 0 : -1);
1190 pwidth = prompt_trunc % x_cols;
1191 prompt_trunc -= pwidth;
1192 if ((mksh_uari_t)pwidth > ((mksh_uari_t)x_cols - 3 - MIN_EDIT_SPACE)) {
1193 /* force newline after prompt */
1209 xlp = xcp = xep = buf;
1214 x_histp = histptr + 1;
1215 x_last_command = XFUNC_error;
1217 x_init_prompt(true);
1218 x_displen = (xx_cols = x_cols) - 2 - (x_col = pwidth);
1223 if (x_nextcmd >= 0) {
1224 int off = source->line - x_nextcmd;
1225 if (histptr - history >= off) {
1226 x_load_hist(histptr - off);
1227 x_histncp = x_histp;
1232 while (/* CONSTCOND */ 1) {
1234 if ((c = x_e_getc()) < 0)
1237 f = x_curprefix == -1 ? XFUNC_insert :
1238 x_tab[x_curprefix][c];
1242 if ((i = x_e_getc()) != '~')
1246 /* avoid bind key macro recursion */
1247 if (macroptr && f == XFUNC_ins_string)
1251 if (!(x_ftab[f].xf_flags & XF_PREFIX) &&
1252 x_last_command != XFUNC_set_arg) {
1254 x_arg_defaulted = true;
1256 i = c | (x_curprefix << 8);
1258 switch ((*x_ftab[f].xf_func)(i)) {
1260 if (!(x_ftab[f].xf_flags & XF_PREFIX))
1267 /* special case for interrupt */
1272 /* ad-hoc hack for fixing the cursor position */
1280 static int left, pos, save_arg;
1284 * Should allow tab and control chars.
1293 if (((c & 0xC0) == 0x80) && left) {
1304 if (x_curprefix == -1) {
1305 /* flush invalid multibyte */
1311 if ((c >= 0xC2) && (c < 0xE0))
1313 else if ((c >= 0xE0) && (c < 0xF0))
1338 macroptr = x_atab[c >> 8][c & 255];
1340 * we no longer need to bother checking if macroptr is
1341 * not NULL but first char is NUL; x_e_getc() does it
1348 x_do_ins(const char *cp, size_t len)
1350 if (xep + len >= xend) {
1354 memmove(xcp + len, xcp, xep - xcp + 1);
1355 memmove(xcp, cp, len);
1363 x_ins(const char *s)
1366 int adj = x_adj_done;
1368 if (x_do_ins(s, strlen(s)) < 0)
1371 * x_zots() may result in a call to x_adjust()
1372 * we want xcp to reflect the new position.
1376 x_adj_ok = tobool(xcp >= xlp);
1378 /* has x_adjust() been called? */
1379 if (adj == x_adj_done) {
1392 x_del_back(int c MKSH_A_UNUSED)
1402 } while ((++i < x_arg) && (xcp != xbuf));
1408 x_del_char(int c MKSH_A_UNUSED)
1414 while (i < (size_t)x_arg) {
1415 utf_ptradjx(cp, cp2);
1430 /* Delete nc chars to the right of the cursor (including cursor position) */
1432 x_delete(size_t nc, bool push)
1442 for (i = 0; i < nc; ++i) {
1446 j = x_size2(cp, &cp2);
1455 if (xmp != NULL && xmp > xcp) {
1462 * This lets us yank a word we have deleted.
1468 /* Copies the NUL */
1469 memmove(xcp, xcp + nb, xep - xcp + 1);
1475 * if we are already filling the line,
1476 * there is no need to ' ', '\b'.
1477 * But if we must, make sure we do the minimum.
1479 if ((i = xx_cols - 2 - x_col) > 0 || xep - xlp == 0) {
1480 nw = i = (nw < i) ? nw : i;
1483 if (x_col == xx_cols - 2) {
1484 x_e_putc2((xep > xlp) ? '>' : (xbp > xbuf) ? '<' : ' ');
1502 x_del_bword(int c MKSH_A_UNUSED)
1504 x_delete(x_bword(), true);
1509 x_mv_bword(int c MKSH_A_UNUSED)
1516 x_mv_fword(int c MKSH_A_UNUSED)
1523 x_del_fword(int c MKSH_A_UNUSED)
1525 x_delete(x_fword(false), true);
1540 while (cp != xbuf && is_mfs(cp[-1])) {
1544 while (cp != xbuf && !is_mfs(cp[-1])) {
1550 return (x_nb2nc(nb));
1564 while (cp != xep && is_mfs(*cp))
1566 while (cp != xep && !is_mfs(*cp))
1569 nc = x_nb2nc(cp - xcp);
1578 cp = cp >= xep ? xep : x_bs0(cp, xbuf);
1579 if (cp < xbp || cp >= utf_skipcols(xbp, x_displen)) {
1580 /* we are heading off screen */
1583 } else if (cp < xcp) {
1587 } else if (cp > xcp) {
1595 x_bs0(char *cp, char *lower_bound)
1598 while ((!lower_bound || (cp > lower_bound)) &&
1599 ((*(unsigned char *)cp & 0xC0) == 0x80))
1609 *p = x_bs0((*p) - 1, NULL);
1610 i = x_size2(*p, NULL);
1616 x_size_str(char *cp)
1620 size += x_size2(cp, &cp);
1625 x_size2(char *cp, char **dcp)
1627 uint8_t c = *(unsigned char *)cp;
1629 if (UTFMODE && (c > 0x7F))
1630 return (utf_widthadj(cp, (const char **)dcp));
1634 /* Kludge, tabs are always four spaces. */
1636 if (ISCTRL(c) && /* but not C1 */ c < 0x80)
1637 /* control unsigned char */
1645 int adj = x_adj_done;
1648 while (*str && str < xlp && x_col < xx_cols && adj == x_adj_done)
1655 unsigned char c = **(unsigned char **)cp;
1658 /* Kludge, tabs are always four spaces. */
1661 } else if (ISCTRL(c) && /* but not C1 */ c < 0x80) {
1663 x_e_putc2(UNCTRL(c));
1666 x_e_putc3((const char **)cp);
1670 x_mv_back(int c MKSH_A_UNUSED)
1685 x_mv_forw(int c MKSH_A_UNUSED)
1687 char *cp = xcp, *cp2;
1694 utf_ptradjx(cp, cp2);
1704 x_search_char_forw(int c MKSH_A_UNUSED)
1710 if (x_e_getmbc(tmp) < 0) {
1715 if ((cp = (cp == xep) ? NULL : strstr(cp + 1, tmp)) == NULL &&
1716 (cp = strstr(xbuf, tmp)) == NULL) {
1726 x_search_char_back(int c MKSH_A_UNUSED)
1728 char *cp = xcp, *p, tmp[4];
1731 if (x_e_getmbc(tmp) < 0) {
1735 for (; x_arg--; cp = p)
1743 if ((tmp[1] && ((p+1) > xep)) ||
1744 (tmp[2] && ((p+2) > xep)))
1749 if (b && tmp[1] && p[1] != tmp[1])
1751 if (b && tmp[2] && p[2] != tmp[2])
1761 x_newline(int c MKSH_A_UNUSED)
1771 x_end_of_text(int c MKSH_A_UNUSED)
1773 char tmp = edchars.eof;
1784 x_beg_hist(int c MKSH_A_UNUSED)
1786 x_load_hist(history);
1791 x_end_hist(int c MKSH_A_UNUSED)
1793 x_load_hist(histptr);
1798 x_prev_com(int c MKSH_A_UNUSED)
1800 x_load_hist(x_histp - x_arg);
1805 x_next_com(int c MKSH_A_UNUSED)
1807 x_load_hist(x_histp + x_arg);
1812 * Goto a particular history number obtained from argument.
1813 * If no argument is given history 1 is probably not what you
1814 * want so we'll simply go to the oldest one.
1817 x_goto_hist(int c MKSH_A_UNUSED)
1819 if (x_arg_defaulted)
1820 x_load_hist(history);
1822 x_load_hist(histptr + x_arg - source->line);
1827 x_load_hist(char **hp)
1832 if (hp == histptr + 1) {
1835 } else if (hp < history || hp > histptr) {
1842 oldsize = x_size_str(xbuf);
1844 strlcpy(holdbufp, xbuf, LINE);
1845 strlcpy(xbuf, sp, xend - xbuf);
1847 xep = xcp = xbuf + strlen(xbuf);
1849 if (xep <= x_lastcp()) {
1857 x_nl_next_com(int c MKSH_A_UNUSED)
1859 if (!x_histncp || (x_histp != x_histncp && x_histp != histptr + 1))
1860 /* fresh start of ^O */
1861 x_histncp = x_histp;
1862 x_nextcmd = source->line - (histptr - x_histncp) + 1;
1863 return (x_newline('\n'));
1869 if (xep == xbuf && x_arg_defaulted)
1870 return (x_end_of_text(c));
1872 return (x_del_char(c));
1875 /* reverse incremental history search */
1877 x_search_hist(int c)
1879 int offset = -1; /* offset of match in xbuf, else -1 */
1880 char pat[80 + 1]; /* pattern buffer */
1885 while (/* CONSTCOND */ 1) {
1887 x_e_puts("\nI-search: ");
1891 if ((c = x_e_getc()) < 0)
1894 if (c == CTRL('[')) {
1895 if ((f & 0x7F) == XFUNC_meta1) {
1896 if ((c = x_e_getc()) < 0)
1898 f = x_tab[1][c] & 0x7F;
1899 if (f == XFUNC_meta1 || f == XFUNC_meta2)
1908 if ((c = x_e_getc()) != '~')
1912 if (f == XFUNC_search_hist)
1913 offset = x_search(pat, 0, offset);
1914 else if (f == XFUNC_del_back) {
1924 offset = x_search(pat, 1, offset);
1926 } else if (f == XFUNC_insert) {
1927 /* add char to pattern */
1928 /* overflow check... */
1929 if ((size_t)(p - pat) >= sizeof(pat) - 1) {
1933 *p++ = c, *p = '\0';
1935 /* already have partial match */
1936 offset = x_match(xbuf, pat);
1938 x_goto(xbuf + offset + (p - pat) -
1943 offset = x_search(pat, 0, offset);
1944 } else if (f == XFUNC_abort) {
1946 x_load_hist(histptr + 1);
1959 /* search backward from current line */
1961 x_search(char *pat, int sameline, int offset)
1966 for (hp = x_histp - (sameline ? 0 : 1); hp >= history; --hp) {
1967 i = x_match(*hp, pat);
1972 x_goto(xbuf + i + strlen(pat) - (*pat == '^'));
1982 /* anchored search up from current line */
1984 x_search_hist_up(int c MKSH_A_UNUSED)
1986 return (x_search_dir(-1));
1989 /* anchored search down from current line */
1991 x_search_hist_dn(int c MKSH_A_UNUSED)
1993 return (x_search_dir(1));
1996 /* anchored search in the indicated direction */
1998 x_search_dir(int search_dir /* should've been bool */)
2000 char **hp = x_histp + search_dir;
2001 size_t curs = xcp - xbuf;
2003 while (histptr >= hp && hp >= history) {
2004 if (strncmp(xbuf, *hp, curs) == 0) {
2006 x_goto(xbuf + curs);
2015 /* return position of first match of pattern in string, else -1 */
2017 x_match(char *str, char *pat)
2020 return ((strncmp(str, pat + 1, strlen(pat + 1)) == 0) ? 0 : -1);
2022 char *q = strstr(str, pat);
2023 return ((q == NULL) ? -1 : q - str);
2028 x_del_line(int c MKSH_A_UNUSED)
2034 j = x_size_str(xbuf);
2037 xlp = xbp = xep = xbuf;
2047 x_mv_end(int c MKSH_A_UNUSED)
2054 x_mv_begin(int c MKSH_A_UNUSED)
2061 x_draw_line(int c MKSH_A_UNUSED)
2068 x_e_rebuildline(const char *clrstr)
2070 shf_puts(clrstr, shl_out);
2076 x_cls(int c MKSH_A_UNUSED)
2078 return (x_e_rebuildline(MKSH_CLS_STRING));
2082 * Redraw (part of) the line. If limit is < 0, the everything is redrawn
2083 * on a NEW line, otherwise limit is the screen column up to which needs
2099 if (prompt_trunc != -1)
2100 pprompt(prompt, prompt_trunc);
2103 x_displen = xx_cols - 2 - x_col;
2106 if (xbp != xbuf || xep > xlp)
2110 /* we fill the line */
2117 i -= x_size2(cpl, &cpl);
2121 while ((j < i) || (x_col < (xx_cols - 2))) {
2122 if (!(x_col < (xx_cols - 2)))
2129 /* more off screen */
2134 } else if (xbp > xbuf)
2149 x_transpose(int c MKSH_A_UNUSED)
2151 unsigned int tmpa, tmpb;
2154 * What transpose is meant to do seems to be up for debate. This
2155 * is a general summary of the options; the text is abcd with the
2156 * upper case character or underscore indicating the cursor position:
2157 * Who Before After Before After
2158 * AT&T ksh in emacs mode: abCd abdC abcd_ (bell)
2159 * AT&T ksh in gmacs mode: abCd baCd abcd_ abdc_
2160 * gnu emacs: abCd acbD abcd_ abdc_
2161 * Pdksh currently goes with GNU behavior since I believe this is the
2162 * most common version of emacs, unless in gmacs mode, in which case
2163 * it does the AT&T ksh gmacs mode.
2164 * This should really be broken up into 3 functions so users can bind
2165 * to the one they want.
2170 } else if (xcp == xep || Flag(FGMACS)) {
2171 if (xcp - xbuf == 1) {
2176 * Gosling/Unipress emacs style: Swap two characters before
2177 * the cursor, do not change cursor position
2180 if (utf_mbtowc(&tmpa, xcp) == (size_t)-1) {
2185 if (utf_mbtowc(&tmpb, xcp) == (size_t)-1) {
2189 utf_wctomb(xcp, tmpa);
2191 utf_wctomb(xcp, tmpb);
2195 * GNU emacs style: Swap the characters before and under the
2196 * cursor, move cursor position along one.
2198 if (utf_mbtowc(&tmpa, xcp) == (size_t)-1) {
2203 if (utf_mbtowc(&tmpb, xcp) == (size_t)-1) {
2207 utf_wctomb(xcp, tmpa);
2209 utf_wctomb(xcp, tmpb);
2217 x_literal(int c MKSH_A_UNUSED)
2224 x_meta1(int c MKSH_A_UNUSED)
2231 x_meta2(int c MKSH_A_UNUSED)
2238 x_meta3(int c MKSH_A_UNUSED)
2245 x_kill(int c MKSH_A_UNUSED)
2247 size_t col = xcp - xbuf;
2248 size_t lastcol = xep - xbuf;
2251 if (x_arg_defaulted || (narg = x_arg) > lastcol)
2254 x_goto(xbuf + narg);
2258 x_delete(x_nb2nc(ndel), true);
2265 afree(killstack[killsp], AEDIT);
2266 strndupx(killstack[killsp], xcp, nchars, AEDIT);
2267 killsp = (killsp + 1) % KILLSIZE;
2271 x_yank(int c MKSH_A_UNUSED)
2278 if (killstack[killtp] == 0) {
2279 x_e_puts("\nnothing to yank");
2284 x_ins(killstack[killtp]);
2289 x_meta_yank(int c MKSH_A_UNUSED)
2293 if ((x_last_command != XFUNC_yank && x_last_command != XFUNC_meta_yank) ||
2294 killstack[killtp] == 0) {
2296 x_e_puts("\nyank something first");
2300 len = strlen(killstack[killtp]);
2302 x_delete(x_nb2nc(len), false);
2305 killtp = KILLSIZE - 1;
2308 } while (killstack[killtp] == 0);
2309 x_ins(killstack[killtp]);
2314 x_abort(int c MKSH_A_UNUSED)
2317 xlp = xep = xcp = xbp = xbuf;
2325 x_error(int c MKSH_A_UNUSED)
2332 /* special VT100 style key sequence hack */
2336 /* we only support PF2-'1' for now */
2337 if (c != (2 << 8 | '1'))
2338 return (x_error(c));
2340 /* what's the next character? */
2341 switch ((c = x_e_getc())) {
2344 x_arg_defaulted = true;
2345 return (x_mv_begin(0));
2347 /* "interesting" sequence detected */
2353 /* XXX x_e_ungetc is one-octet only */
2354 if ((c = x_e_getc()) != '5' && c != '3')
2358 * At this point, we have read the following octets so far:
2359 * - ESC+[ or ESC+O or Ctrl-X (Prefix 2)
2362 * - 5 (Ctrl key combiner) or 3 (Alt key combiner)
2363 * We can now accept one more octet designating the key.
2366 switch ((c = x_e_getc())) {
2368 return (x_mv_fword(c));
2370 return (x_mv_bword(c));
2375 return (x_error(c));
2380 x_mapin(const char *cp, Area *ap)
2384 strdupx(news, cp, ap);
2387 /* XXX -- should handle \^ escape? */
2390 /*XXX or ^^ escape? this is ugly. */
2392 /* includes '?'; ASCII */
2408 x_mapout2(int c, char **buf)
2432 x_print(int prefix, int key)
2434 int f = x_tab[prefix][key];
2437 /* prefix == 1 || prefix == 2 */
2438 shf_puts(x_mapout(prefix == 1 ? CTRL('[') :
2439 prefix == 2 ? CTRL('X') : 0), shl_stdout);
2441 shprintf("%s = ", x_mapout(key));
2443 shprintf("%s%s = ", x_mapout(key), (f & 0x80) ? "~" : "");
2444 if (XFUNC_VALUE(f) != XFUNC_ins_string)
2446 shprintf("%s\n", x_ftab[XFUNC_VALUE(f)].xf_name);
2449 shprintf("'%s'\n", x_atab[prefix][key]);
2454 x_bind(const char *a1, const char *a2,
2470 if (x_tab == NULL) {
2471 bi_errorf("can't bind, not a tty");
2474 /* List function names */
2476 for (f = 0; f < NELEM(x_ftab); f++)
2477 if (!(x_ftab[f].xf_flags & XF_NOBIND))
2478 shprintf("%s\n", x_ftab[f].xf_name);
2482 for (prefix = 0; prefix < X_NTABS; prefix++)
2483 for (key = 0; key < X_TABSZ; key++) {
2484 f = XFUNC_VALUE(x_tab[prefix][key]);
2485 if (f == XFUNC_insert || f == XFUNC_error
2487 || (macro && f != XFUNC_ins_string)
2491 x_print(prefix, key);
2495 m2 = m1 = x_mapin(a1, ATEMP);
2498 key = (unsigned char)*m1;
2499 f = XFUNC_VALUE(x_tab[prefix][key]);
2500 if (f == XFUNC_meta1)
2502 else if (f == XFUNC_meta2)
2504 else if (f == XFUNC_meta3)
2511 && ((*m1 != '~') || *(m1 + 1))
2517 while (*c && (size_t)(m1 - msg) < sizeof(msg) - 3)
2518 x_mapout2(*c++, &m1);
2519 bi_errorf("%s: %s", "too long key sequence", msg);
2523 hastilde = tobool(*m1);
2528 x_print(prefix, key);
2535 f = XFUNC_ins_string;
2536 sp = x_mapin(a2, AEDIT);
2539 for (f = 0; f < NELEM(x_ftab); f++)
2540 if (!strcmp(x_ftab[f].xf_name, a2))
2542 if (f == NELEM(x_ftab) || x_ftab[f].xf_flags & XF_NOBIND) {
2543 bi_errorf("%s: %s %s", a2, "no such", Tfunction);
2549 if (XFUNC_VALUE(x_tab[prefix][key]) == XFUNC_ins_string &&
2550 x_atab[prefix][key])
2551 afree(x_atab[prefix][key], AEDIT);
2553 x_tab[prefix][key] = f
2555 | (hastilde ? 0x80 : 0)
2559 x_atab[prefix][key] = sp;
2562 /* Track what the user has bound so x_mode(true) won't toast things */
2563 if (f == XFUNC_insert)
2564 x_bound[(prefix * X_TABSZ + key) / 8] &=
2565 ~(1 << ((prefix * X_TABSZ + key) % 8));
2567 x_bound[(prefix * X_TABSZ + key) / 8] |=
2568 (1 << ((prefix * X_TABSZ + key) % 8));
2574 bind_if_not_bound(int p, int k, int func)
2579 * Has user already bound this key?
2580 * If so, do not override it.
2582 t = p * X_TABSZ + k;
2583 if (x_bound[t >> 3] & (1 << (t & 7)))
2590 x_set_mark(int c MKSH_A_UNUSED)
2597 x_kill_region(int c MKSH_A_UNUSED)
2614 x_delete(x_nb2nc(rsize), true);
2620 x_xchg_point_mark(int c MKSH_A_UNUSED)
2635 x_noop(int c MKSH_A_UNUSED)
2641 * File/command name completion routines
2644 x_comp_comm(int c MKSH_A_UNUSED)
2646 do_complete(XCF_COMMAND, CT_COMPLETE);
2651 x_list_comm(int c MKSH_A_UNUSED)
2653 do_complete(XCF_COMMAND, CT_LIST);
2658 x_complete(int c MKSH_A_UNUSED)
2660 do_complete(XCF_COMMAND_FILE, CT_COMPLETE);
2665 x_enumerate(int c MKSH_A_UNUSED)
2667 do_complete(XCF_COMMAND_FILE, CT_LIST);
2672 x_comp_file(int c MKSH_A_UNUSED)
2674 do_complete(XCF_FILE, CT_COMPLETE);
2679 x_list_file(int c MKSH_A_UNUSED)
2681 do_complete(XCF_FILE, CT_LIST);
2686 x_comp_list(int c MKSH_A_UNUSED)
2688 do_complete(XCF_COMMAND_FILE, CT_COMPLIST);
2693 x_expand(int c MKSH_A_UNUSED)
2696 int start, end, nwords, i;
2699 nwords = x_cf_glob(&i, xbuf, xep - xbuf, xcp - xbuf,
2700 &start, &end, &words);
2706 x_goto(xbuf + start);
2707 x_delete(x_nb2nc(end - start), false);
2710 while (i < nwords) {
2711 if (x_escape(words[i], strlen(words[i]), x_do_ins) < 0 ||
2712 (++i < nwords && x_ins(" ") < 0)) {
2724 /* XCF_{COMMAND,FILE,COMMAND_FILE} */
2726 /* 0 for list, 1 for complete and 2 for complete-list */
2730 int start, end, nlen, olen, nwords;
2733 nwords = x_cf_glob(&flags, xbuf, xep - xbuf, xcp - xbuf,
2734 &start, &end, &words);
2740 if (type == CT_LIST) {
2741 x_print_expansions(nwords, words,
2742 tobool(flags & XCF_IS_COMMAND));
2744 x_free_words(nwords, words);
2748 nlen = x_longest_prefix(nwords, words);
2751 * always complete single matches;
2752 * any expansion of parameter substitution
2753 * is always at most one result, too
2759 /* make a copy of the original string part */
2760 strndupx(unescaped, xbuf + start, olen, ATEMP);
2762 /* expand any tilde and unescape the string for comparison */
2763 unescaped = x_glob_hlp_tilde_and_rem_qchar(unescaped, true);
2766 * match iff entire original string is part of the
2767 * longest prefix, implying the latter is at least
2768 * the same size (after unescaping)
2770 completed = !strncmp(words[0], unescaped, strlen(unescaped));
2772 afree(unescaped, ATEMP);
2774 if (type == CT_COMPLIST && nwords > 1) {
2776 * print expansions, since we didn't get back
2777 * just a single match
2779 x_print_expansions(nwords, words,
2780 tobool(flags & XCF_IS_COMMAND));
2783 /* expand on the command line */
2787 memmove(xcp, xcp + olen, xep - xcp + 1);
2788 x_escape(words[0], nlen, x_do_ins);
2792 * append a space if this is a single non-directory match
2793 * and not a parameter or homedir substitution
2795 if (nwords == 1 && words[0][nlen - 1] != '/' &&
2796 !(flags & XCF_IS_NOSPACE)) {
2800 x_free_words(nwords, words);
2805 * x_adjust - redraw the line adjusting starting point etc.
2808 * This function is called when we have exceeded the bounds
2809 * of the edit window. It increments x_adj_done so that
2810 * functions like x_ins and x_delete know that we have been
2811 * called and can skip the x_bs() stuff which has already
2812 * been done by x_redraw.
2822 /* flag the fact that we were called */
2826 * calculate the amount of columns we need to "go back"
2827 * from xcp to set xbp to (but never < xbuf) to 2/3 of
2828 * the display width; take care of pwidth though
2830 if ((col_left = xx_cols * 2 / 3) < MIN_EDIT_SPACE) {
2832 * cowardly refuse to do anything
2833 * if the available space is too small;
2834 * fall back to dumb pdksh code
2836 if ((xbp = xcp - (x_displen / 2)) < xbuf)
2838 /* elide UTF-8 fixup as penalty */
2842 /* fix up xbp to just past a character end first */
2843 xbp = xcp >= xep ? xep : x_bs0(xcp, xbuf);
2844 /* walk backwards */
2845 while (xbp > xbuf && col_left > 0) {
2846 xbp = x_bs0(xbp - 1, xbuf);
2847 col_left -= (n = x_size2(xbp, NULL));
2849 /* check if we hit the prompt */
2850 if (xbp == xbuf && xcp != xbuf && col_left >= 0 && col_left < pwidth) {
2851 /* so we did; force scrolling occurs */
2852 xbp += utf_ptradj(xbp);
2864 unget_char = c < 0 ? -1 : (c & 255);
2872 if (unget_char >= 0) {
2880 if ((c = (unsigned char)*macroptr++))
2894 if (c == '\r' || c == '\n')
2896 if (x_col < xx_cols) {
2897 if (UTFMODE && (c > 0x7F)) {
2903 x = utf_wctomb(utf_tmp, c);
2909 width = utf_wcwidth(c);
2926 if (x_adj_ok && (x_col < 0 || x_col >= (xx_cols - 2)))
2931 x_e_putc3(const char **cp)
2933 int width = 1, c = **(const unsigned char **)cp;
2935 if (c == '\r' || c == '\n')
2937 if (x_col < xx_cols) {
2938 if (UTFMODE && (c > 0x7F)) {
2941 width = utf_widthadj(*cp, (const char **)&cp2);
2962 if (x_adj_ok && (x_col < 0 || x_col >= (xx_cols - 2)))
2967 x_e_puts(const char *s)
2969 int adj = x_adj_done;
2971 while (*s && adj == x_adj_done)
2977 * x_set_arg - set an arg value for next function
2980 * This is a simple implementation of M-[0-9].
2991 /* strip command prefix */
2993 while (c >= 0 && ksh_isdigit(c)) {
2994 n = n * 10 + ksh_numdig(c);
2996 /* upper bound for repeat */
2997 goto x_set_arg_too_big;
3001 if (c < 0 || first) {
3005 x_arg_defaulted = true;
3009 x_arg_defaulted = false;
3014 /* Comment or uncomment the current line. */
3016 x_comment(int c MKSH_A_UNUSED)
3018 int oldsize = x_size_str(xbuf);
3019 ssize_t len = xep - xbuf;
3020 int ret = x_do_comment(xbuf, xend - xbuf, &len);
3031 return (x_newline('\n'));
3037 x_version(int c MKSH_A_UNUSED)
3039 char *o_xbuf = xbuf, *o_xend = xend;
3040 char *o_xbp = xbp, *o_xep = xep, *o_xcp = xcp;
3041 int lim = x_lastcp() - xbp;
3045 strdupx(v, KSH_VERSION, ATEMP);
3047 xbuf = xbp = xcp = v;
3048 xend = xep = v + (vlen = strlen(v));
3058 x_redraw((int)vlen);
3062 /* This is what AT&T ksh seems to do... Very bizarre */
3072 x_edit_line(int c MKSH_A_UNUSED)
3074 if (x_arg_defaulted) {
3081 histsave(&source->line, xbuf, HIST_STORE, true);
3084 x_arg = source->line - (histptr - x_histp);
3087 shf_snprintf(xbuf, xend - xbuf, "%s %d",
3088 "fc -e ${VISUAL:-${EDITOR:-vi}} --", x_arg);
3090 strlcpy(xbuf, "fc -e ${VISUAL:-${EDITOR:-vi}} --", xend - xbuf);
3091 xep = xbuf + strlen(xbuf);
3092 return (x_newline('\n'));
3098 * x_prev_histword - recover word from prev command
3101 * This function recovers the last word from the previous
3102 * command and inserts it into the current edit line. If a
3103 * numeric arg is supplied then the n'th word from the
3104 * start of the previous command is used.
3105 * As a side effect, trashes the mark in order to achieve
3106 * being called in a repeatable fashion.
3114 x_prev_histword(int c MKSH_A_UNUSED)
3119 /* -1 = defaulted; 0+ = argument */
3120 static int last_arg = -1;
3122 if (x_last_command == XFUNC_prev_histword) {
3123 if (xmp && modified > 1)
3128 last_arg = x_arg_defaulted ? -1 : x_arg;
3129 xhp = histptr - (m - 1);
3130 if ((xhp < history) || !(cp = *xhp)) {
3136 if ((x_arg = last_arg) == -1) {
3137 /* x_arg_defaulted */
3139 rcp = &cp[strlen(cp) - 1];
3141 * ignore white-space after the last word
3143 while (rcp > cp && is_cfs(*rcp))
3145 while (rcp > cp && !is_cfs(*rcp))
3151 /* not x_arg_defaulted */
3156 * ignore white-space at start of line
3158 while (*rcp && is_cfs(*rcp))
3160 while (x_arg-- > 0) {
3161 while (*rcp && !is_cfs(*rcp))
3163 while (*rcp && is_cfs(*rcp))
3167 while (*rcp && !is_cfs(*rcp))
3179 /* Uppercase N(1) words */
3181 x_fold_upper(int c MKSH_A_UNUSED)
3183 return (x_fold_case('U'));
3186 /* Lowercase N(1) words */
3188 x_fold_lower(int c MKSH_A_UNUSED)
3190 return (x_fold_case('L'));
3193 /* Titlecase N(1) words */
3195 x_fold_capitalise(int c MKSH_A_UNUSED)
3197 return (x_fold_case('C'));
3202 * x_fold_case - convert word to UPPER/lower/Capital case
3205 * This function is used to implement M-U/M-u, M-L/M-l, M-C/M-c
3206 * to UPPER CASE, lower case or Capitalise Words.
3222 * first skip over any white-space
3224 while (cp != xep && is_mfs(*cp))
3227 * do the first char on its own since it may be
3228 * a different action than for the rest.
3233 *cp = ksh_tolower(*cp);
3235 /* uppercase, capitalise */
3236 *cp = ksh_toupper(*cp);
3240 * now for the rest of the word
3242 while (cp != xep && !is_mfs(*cp)) {
3245 *cp = ksh_toupper(*cp);
3247 /* lowercase, capitalise */
3248 *cp = ksh_tolower(*cp);
3260 * x_lastcp - last visible char
3266 * This function returns a pointer to that char in the
3267 * edit buffer that will be the last displayed on the
3268 * screen. The sequence:
3274 * Will position the cursor correctly on the screen.
3288 j = x_size2(xlp, &xlp2);
3289 if ((i + j) > x_displen)
3302 static bool x_cur_mode;
3304 if (x_cur_mode == onoff)
3309 x_mkraw(tty_fd, NULL, false);
3311 edchars.erase = tty_state.c_cc[VERASE];
3312 edchars.kill = tty_state.c_cc[VKILL];
3313 edchars.intr = tty_state.c_cc[VINTR];
3314 edchars.quit = tty_state.c_cc[VQUIT];
3315 edchars.eof = tty_state.c_cc[VEOF];
3317 edchars.werase = tty_state.c_cc[VWERASE];
3323 edchars.erase = CTRL('H');
3325 edchars.kill = CTRL('U');
3327 edchars.intr = CTRL('C');
3329 edchars.quit = CTRL('\\');
3331 edchars.eof = CTRL('D');
3332 if (!edchars.werase)
3333 edchars.werase = CTRL('W');
3335 #ifdef _POSIX_VDISABLE
3336 /* Convert unset values to internal 'unset' value */
3337 if (edchars.erase == _POSIX_VDISABLE)
3339 if (edchars.kill == _POSIX_VDISABLE)
3341 if (edchars.intr == _POSIX_VDISABLE)
3343 if (edchars.quit == _POSIX_VDISABLE)
3345 if (edchars.eof == _POSIX_VDISABLE)
3347 if (edchars.werase == _POSIX_VDISABLE)
3348 edchars.werase = -1;
3351 if (edchars.erase >= 0) {
3352 bind_if_not_bound(0, edchars.erase, XFUNC_del_back);
3353 bind_if_not_bound(1, edchars.erase, XFUNC_del_bword);
3355 if (edchars.kill >= 0)
3356 bind_if_not_bound(0, edchars.kill, XFUNC_del_line);
3357 if (edchars.werase >= 0)
3358 bind_if_not_bound(0, edchars.werase, XFUNC_del_bword);
3359 if (edchars.intr >= 0)
3360 bind_if_not_bound(0, edchars.intr, XFUNC_abort);
3361 if (edchars.quit >= 0)
3362 bind_if_not_bound(0, edchars.quit, XFUNC_noop);
3364 mksh_tcset(tty_fd, &tty_state);
3368 /* +++ vi editing mode +++ */
3378 static int vi_hook(int);
3379 static int nextstate(int);
3380 static int vi_insert(int);
3381 static int vi_cmd(int, const char *);
3382 static int domove(int, const char *, int);
3383 static int redo_insert(int);
3384 static void yank_range(int, int);
3385 static int bracktype(int);
3386 static void save_cbuf(void);
3387 static void restore_cbuf(void);
3388 static int putbuf(const char *, ssize_t, bool);
3389 static void del_range(int, int);
3390 static int findch(int, int, bool, bool) MKSH_A_PURE;
3391 static int forwword(int);
3392 static int backword(int);
3393 static int endword(int);
3394 static int Forwword(int);
3395 static int Backword(int);
3396 static int Endword(int);
3397 static int grabhist(int, int);
3398 static int grabsearch(int, int, int, const char *);
3399 static void redraw_line(bool);
3400 static void refresh(int);
3401 static int outofwin(void);
3402 static void rewindow(void);
3403 static int newcol(unsigned char, int);
3404 static void display(char *, char *, int);
3405 static void ed_mov_opt(int, char *);
3406 static int expand_word(int);
3407 static int complete_word(int, int);
3408 static int print_expansions(struct edstate *, int);
3409 #define char_len(c) ((ISCTRL((unsigned char)c) && \
3410 /* but not C1 */ (unsigned char)c < 0x80) ? 2 : 1)
3411 static void x_vi_zotc(int);
3412 static void vi_error(void);
3413 static void vi_macro_reset(void);
3414 static int x_vi_putbuf(const char *, size_t);
3416 #define vC 0x01 /* a valid command that isn't a vM, vE, vU */
3417 #define vM 0x02 /* movement command (h, l, etc.) */
3418 #define vE 0x04 /* extended command (c, d, y) */
3419 #define vX 0x08 /* long command (@, f, F, t, T, etc.) */
3420 #define vU 0x10 /* an UN-undoable command (that isn't a vM) */
3421 #define vB 0x20 /* bad command (^@) */
3422 #define vZ 0x40 /* repeat count defaults to 0 (not 1) */
3423 #define vS 0x80 /* search (/, ?) */
3425 #define is_bad(c) (classify[(c)&0x7f]&vB)
3426 #define is_cmd(c) (classify[(c)&0x7f]&(vM|vE|vC|vU))
3427 #define is_move(c) (classify[(c)&0x7f]&vM)
3428 #define is_extend(c) (classify[(c)&0x7f]&vE)
3429 #define is_long(c) (classify[(c)&0x7f]&vX)
3430 #define is_undoable(c) (!(classify[(c)&0x7f]&vU))
3431 #define is_srch(c) (classify[(c)&0x7f]&vS)
3432 #define is_zerocount(c) (classify[(c)&0x7f]&vZ)
3434 static const unsigned char classify[128] = {
3435 /* 0 1 2 3 4 5 6 7 */
3436 /* 0 ^@ ^A ^B ^C ^D ^E ^F ^G */
3437 vB, 0, 0, 0, 0, vC|vU, vC|vZ, 0,
3438 /* 1 ^H ^I ^J ^K ^L ^M ^N ^O */
3439 vM, vC|vZ, 0, 0, vC|vU, 0, vC, 0,
3440 /* 2 ^P ^Q ^R ^S ^T ^U ^V ^W */
3441 vC, 0, vC|vU, 0, 0, 0, vC, 0,
3442 /* 3 ^X ^Y ^Z ^[ ^\ ^] ^^ ^_ */
3443 vC, 0, 0, vC|vZ, 0, 0, 0, 0,
3444 /* 4 <space> ! " # $ % & ' */
3445 vM, 0, 0, vC, vM, vM, 0, 0,
3446 /* 5 ( ) * + , - . / */
3447 0, 0, vC, vC, vM, vC, 0, vC|vS,
3448 /* 6 0 1 2 3 4 5 6 7 */
3449 vM, 0, 0, 0, 0, 0, 0, 0,
3450 /* 7 8 9 : ; < = > ? */
3451 0, 0, 0, vM, 0, vC, 0, vC|vS,
3452 /* 8 @ A B C D E F G */
3453 vC|vX, vC, vM, vC, vC, vM, vM|vX, vC|vU|vZ,
3454 /* 9 H I J K L M N O */
3455 0, vC, 0, 0, 0, 0, vC|vU, vU,
3456 /* A P Q R S T U V W */
3457 vC, 0, vC, vC, vM|vX, vC, 0, vM,
3458 /* B X Y Z [ \ ] ^ _ */
3459 vC, vC|vU, 0, vU, vC|vZ, 0, vM, vC|vZ,
3460 /* C ` a b c d e f g */
3461 0, vC, vM, vE, vE, vM, vM|vX, vC|vZ,
3462 /* D h i j k l m n o */
3463 vM, vC, vC|vU, vC|vU, vM, 0, vC|vU, 0,
3464 /* E p q r s t u v w */
3465 vC, 0, vX, vC, vM|vX, vC|vU, vC|vU|vZ, vM,
3466 /* F x y z { | } ~ ^? */
3467 vC, vE|vU, 0, 0, vM|vZ, 0, vC, 0
3476 #define VNORMAL 0 /* command, insert or replace mode */
3477 #define VARG1 1 /* digit prefix (first, eg, 5l) */
3478 #define VEXTCMD 2 /* cmd + movement (eg, cl) */
3479 #define VARG2 3 /* digit prefix (second, eg, 2c3l) */
3480 #define VXCH 4 /* f, F, t, T, @ */
3481 #define VFAIL 5 /* bad command */
3482 #define VCMD 6 /* single char command (eg, X) */
3483 #define VREDO 7 /* . */
3484 #define VLIT 8 /* ^V */
3485 #define VSEARCH 9 /* /, ? */
3486 #define VVERSION 10 /* <ESC> ^V */
3487 #define VPREFIX2 11 /* ^[[ and ^[O in insert mode */
3489 static struct edstate *save_edstate(struct edstate *old);
3490 static void restore_edstate(struct edstate *old, struct edstate *news);
3491 static void free_edstate(struct edstate *old);
3493 static struct edstate ebuf;
3494 static struct edstate undobuf;
3496 static struct edstate *es; /* current editor state */
3497 static struct edstate *undo;
3499 static char *ibuf; /* input buffer */
3500 static bool first_insert; /* set when starting in insert mode */
3501 static int saved_inslen; /* saved inslen for first insert */
3502 static int inslen; /* length of input buffer */
3503 static int srchlen; /* length of current search pattern */
3504 static char *ybuf; /* yank buffer */
3505 static int yanklen; /* length of yank buffer */
3506 static int fsavecmd = ' '; /* last find command */
3507 static int fsavech; /* character to find */
3508 static char lastcmd[MAXVICMD]; /* last non-move command */
3509 static int lastac; /* argcnt for lastcmd */
3510 static int lastsearch = ' '; /* last search command */
3511 static char srchpat[SRCHLEN]; /* last search pattern */
3512 static int insert; /* <>0 in insert mode */
3513 static int hnum; /* position in history */
3514 static int ohnum; /* history line copied (after mod) */
3515 static int hlast; /* 1 past last position in history */
3519 * Information for keeping track of macros that are being expanded.
3520 * The format of buf is the alias contents followed by a NUL byte followed
3521 * by the name (letter) of the alias. The end of the buffer is marked by
3522 * a double NUL. The name of the alias is stored so recursive macros can
3525 struct macro_state {
3526 unsigned char *p; /* current position in buf */
3527 unsigned char *buf; /* pointer to macro(s) being expanded */
3528 size_t len; /* how much data in buffer */
3530 static struct macro_state macro;
3532 /* last input was expanded */
3533 static enum expand_mode {
3534 NONE = 0, EXPAND, COMPLETE, PRINT
3543 ohnum = hnum = hlast = histnum(-1) + 1;
3545 saved_inslen = inslen;
3546 first_insert = true;
3551 if (undobuf.cbuf == NULL) {
3552 ibuf = alloc(LINE, AEDIT);
3553 ybuf = alloc(LINE, AEDIT);
3554 undobuf.cbuf = alloc(LINE, AEDIT);
3556 undobuf.cbufsize = ebuf.cbufsize = LINE;
3557 undobuf.linelen = ebuf.linelen = 0;
3558 undobuf.cursor = ebuf.cursor = 0;
3559 undobuf.winleft = ebuf.winleft = 0;
3563 x_init_prompt(true);
3566 if (wbuf_len != x_cols - 3 && ((wbuf_len = x_cols - 3))) {
3567 wbuf[0] = aresize(wbuf[0], wbuf_len, AEDIT);
3568 wbuf[1] = aresize(wbuf[1], wbuf_len, AEDIT);
3571 memset(wbuf[0], ' ', wbuf_len);
3572 memset(wbuf[1], ' ', wbuf_len);
3574 winwidth = x_cols - pwidth - 3;
3582 while (/* CONSTCOND */ 1) {
3584 c = (unsigned char)*macro.p++;
3585 /* end of current macro? */
3587 /* more macros left to finish? */
3590 /* must be the end of all the macros */
3599 if (state != VLIT) {
3600 if (c == edchars.intr || c == edchars.quit) {
3601 /* pretend we got an interrupt */
3604 trapsig(c == edchars.intr ? SIGINT : SIGQUIT);
3607 } else if (c == edchars.eof && state != VVERSION) {
3608 if (es->linelen == 0) {
3609 x_vi_zotc(edchars.eof);
3625 if (c == -1 || (ssize_t)LINE <= es->linelen)
3628 if (es->cbuf != buf)
3629 memcpy(buf, es->cbuf, es->linelen);
3631 buf[es->linelen++] = '\n';
3633 return (es->linelen);
3639 static char curcmd[MAXVICMD], locpat[SRCHLEN];
3640 static int cmdlen, argc1, argc2;
3646 if (!ch) switch (cmdlen = 0, (ch = x_getc())) {
3647 case 71: ch = '0'; goto pseudo_vi_command;
3648 case 72: ch = 'k'; goto pseudo_vi_command;
3649 case 73: ch = 'A'; goto vi_xfunc_search_up;
3650 case 75: ch = 'h'; goto pseudo_vi_command;
3651 case 77: ch = 'l'; goto pseudo_vi_command;
3652 case 79: ch = '$'; goto pseudo_vi_command;
3653 case 80: ch = 'j'; goto pseudo_vi_command;
3654 case 83: ch = 'x'; goto pseudo_vi_command;
3655 default: ch = 0; goto vi_insert_failed;
3658 if (ch == CTRL('v')) {
3662 switch (vi_insert(ch)) {
3669 if (state == VLIT) {
3673 refresh(insert != 0);
3679 if (ch == '\r' || ch == '\n')
3683 if (ch >= ord('1') && ch <= ord('9')) {
3684 argc1 = ksh_numdig(ch);
3688 curcmd[cmdlen++] = ch;
3689 state = nextstate(ch);
3690 if (state == VSEARCH) {
3694 if (putbuf(ch == '/' ? "/" : "?", 1,
3699 if (state == VVERSION) {
3704 strlen(KSH_VERSION), false);
3713 del_range(es->cursor, es->cursor + 1);
3716 es->cbuf[es->cursor++] = ch;
3728 if (ksh_isdigit(ch))
3729 argc1 = argc1 * 10 + ksh_numdig(ch);
3731 curcmd[cmdlen++] = ch;
3732 state = nextstate(ch);
3738 if (ch >= ord('1') && ch <= ord('9')) {
3739 argc2 = ksh_numdig(ch);
3743 curcmd[cmdlen++] = ch;
3744 if (ch == curcmd[0])
3746 else if (is_move(ch))
3747 state = nextstate(ch);
3754 if (ksh_isdigit(ch))
3755 argc2 = argc2 * 10 + ksh_numdig(ch);
3761 curcmd[cmdlen++] = ch;
3762 if (ch == curcmd[0])
3764 else if (is_move(ch))
3765 state = nextstate(ch);
3772 if (ch == CTRL('['))
3775 curcmd[cmdlen++] = ch;
3781 if (ch == '\r' || ch == '\n' /*|| ch == CTRL('[')*/ ) {
3783 /* Repeat last search? */
3792 locpat[srchlen] = '\0';
3793 memcpy(srchpat, locpat, srchlen + 1);
3796 } else if (ch == edchars.erase || ch == CTRL('h')) {
3799 es->linelen -= char_len(locpat[srchlen]);
3800 es->cursor = es->linelen;
3807 } else if (ch == edchars.kill) {
3813 } else if (ch == edchars.werase) {
3815 struct edstate new_es, *save_es;
3817 new_es.cursor = srchlen;
3818 new_es.cbuf = locpat;
3825 i = (unsigned)srchlen;
3827 es->linelen -= char_len(locpat[i]);
3829 es->cursor = es->linelen;
3833 if (srchlen == SRCHLEN - 1)
3836 locpat[srchlen++] = ch;
3837 if (ISCTRL(ch) && /* but not C1 */ ch < 0x80) {
3838 if ((size_t)es->linelen + 2 >
3839 (size_t)es->cbufsize)
3841 es->cbuf[es->linelen++] = '^';
3842 es->cbuf[es->linelen++] = UNCTRL(ch);
3844 if (es->linelen >= es->cbufsize)
3846 es->cbuf[es->linelen++] = ch;
3848 es->cursor = es->linelen;
3860 /* the cursor may not be at the BOL */
3863 /* nor further in the line than we can search for */
3864 if ((size_t)es->cursor >= sizeof(srchpat) - 1)
3865 es->cursor = sizeof(srchpat) - 2;
3866 /* anchor the search pattern */
3868 /* take the current line up to the cursor */
3869 memmove(srchpat + 1, es->cbuf, es->cursor);
3870 srchpat[es->cursor + 1] = '\0';
3871 /* set a magic flag */
3872 argc1 = 2 + (int)es->cursor;
3873 /* and emulate a backwards history search */
3885 switch (vi_cmd(argc1, curcmd)) {
3893 refresh(insert != 0);
3899 /* back from a 'v' command - don't redraw the screen */
3908 switch (vi_cmd(lastac, lastcmd)) {
3915 if (lastcmd[0] == 's' || lastcmd[0] == 'c' ||
3916 lastcmd[0] == 'C') {
3917 if (redo_insert(1) != 0)
3920 if (redo_insert(lastac) != 0)
3930 /* back from a 'v' command - can't happen */
3948 else if (is_srch(ch))
3950 else if (is_long(ch))
3954 else if (ch == CTRL('v'))
3956 else if (is_cmd(ch))
3967 if (ch == edchars.erase || ch == CTRL('h')) {
3968 if (insert == REPLACE) {
3969 if (es->cursor == undo->cursor) {
3976 if (es->cursor >= undo->linelen)
3979 es->cbuf[es->cursor] = undo->cbuf[es->cursor];
3981 if (es->cursor == 0)
3987 memmove(&es->cbuf[es->cursor], &es->cbuf[es->cursor + 1],
3988 es->linelen - es->cursor + 1);
3993 if (ch == edchars.kill) {
3994 if (es->cursor != 0) {
3996 memmove(es->cbuf, &es->cbuf[es->cursor],
3997 es->linelen - es->cursor);
3998 es->linelen -= es->cursor;
4004 if (ch == edchars.werase) {
4005 if (es->cursor != 0) {
4006 tcursor = backword(1);
4007 memmove(&es->cbuf[tcursor], &es->cbuf[es->cursor],
4008 es->linelen - es->cursor);
4009 es->linelen -= es->cursor - tcursor;
4010 if (inslen < es->cursor - tcursor)
4013 inslen -= es->cursor - tcursor;
4014 es->cursor = tcursor;
4020 * If any chars are entered before escape, trash the saved insert
4021 * buffer (if user inserts & deletes char, ibuf gets trashed and
4022 * we don't want to use it)
4024 if (first_insert && ch != CTRL('['))
4037 first_insert = false;
4039 inslen = saved_inslen;
4040 return (redo_insert(0));
4045 if (lastcmd[0] == 's' || lastcmd[0] == 'c' ||
4047 return (redo_insert(0));
4049 return (redo_insert(lastac - 1));
4051 /* { Begin nonstandard vi commands */
4057 complete_word(0, 0);
4061 print_expansions(es, 0);
4065 if (Flag(FVITABCOMPLETE)) {
4066 complete_word(0, 0);
4070 /* End nonstandard vi commands } */
4073 if (es->linelen >= es->cbufsize - 1)
4075 ibuf[inslen++] = ch;
4076 if (insert == INSERT) {
4077 memmove(&es->cbuf[es->cursor + 1], &es->cbuf[es->cursor],
4078 es->linelen - es->cursor);
4081 es->cbuf[es->cursor++] = ch;
4082 if (insert == REPLACE && es->cursor > es->linelen)
4090 vi_cmd(int argcnt, const char *cmd)
4093 int cur, c1, c2, c3 = 0;
4097 if (argcnt == 0 && !is_zerocount(*cmd))
4100 if (is_move(*cmd)) {
4101 if ((cur = domove(argcnt, cmd, 0)) >= 0) {
4102 if (cur == es->linelen && cur != 0)
4108 /* Don't save state in middle of macro.. */
4109 if (is_undoable(*cmd) && !macro.p) {
4110 undo->winleft = es->winleft;
4111 memmove(undo->cbuf, es->cbuf, es->linelen);
4112 undo->linelen = es->linelen;
4113 undo->cursor = es->cursor;
4115 memmove(lastcmd, cmd, MAXVICMD);
4126 static char alias[] = "_\0";
4131 /* lookup letter in alias list... */
4133 ap = ktsearch(&aliases, alias, hash(alias));
4134 if (!cmd[1] || !ap || !(ap->flag & ISSET))
4136 /* check if this is a recursive call... */
4137 if ((p = (char *)macro.p))
4138 while ((p = strnul(p)) && p[1])
4141 /* insert alias into macro buffer */
4142 nlen = strlen(ap->val.s) + 1;
4143 olen = !macro.p ? 2 :
4144 macro.len - (macro.p - macro.buf);
4146 * at this point, it's fairly reasonable that
4147 * nlen + olen + 2 doesn't overflow
4149 nbuf = alloc(nlen + 1 + olen, AEDIT);
4150 memcpy(nbuf, ap->val.s, nlen);
4151 nbuf[nlen++] = cmd[1];
4153 memcpy(nbuf + nlen, macro.p, olen);
4154 afree(macro.buf, AEDIT);
4157 nbuf[nlen++] = '\0';
4158 nbuf[nlen++] = '\0';
4160 macro.p = macro.buf = (unsigned char *)nbuf;
4168 if (es->linelen != 0)
4177 es->cursor = es->linelen;
4182 es->cursor = domove(1, "^", 1);
4183 del_range(es->cursor, es->linelen);
4195 if (*cmd == cmd[1]) {
4196 c1 = *cmd == 'c' ? domove(1, "^", 1) : 0;
4198 } else if (!is_move(cmd[1]))
4201 if ((ncursor = domove(argcnt, &cmd[1], 1)) < 0)
4204 (cmd[1] == 'w' || cmd[1] == 'W') &&
4205 !ksh_isspace(es->cbuf[es->cursor])) {
4208 } while (ksh_isspace(es->cbuf[ncursor]));
4211 if (ncursor > es->cursor) {
4221 if (*cmd != 'c' && c1 != c2)
4237 if (es->linelen != 0)
4239 while (putbuf(ybuf, yanklen, false) == 0 &&
4242 if (es->cursor != 0)
4252 while (putbuf(ybuf, yanklen, false) == 0 &&
4255 if (any && es->cursor != 0)
4264 del_range(es->cursor, es->linelen);
4269 yank_range(es->cursor, es->linelen);
4270 del_range(es->cursor, es->linelen);
4271 if (es->cursor != 0)
4283 argcnt = hlast - (source->line - argcnt);
4284 if (grabhist(modified, argcnt - 1) < 0)
4301 es->cursor = domove(1, "^", 1);
4308 if (grabhist(modified, hnum + argcnt) < 0)
4319 if (grabhist(modified, hnum - argcnt) < 0)
4328 if (es->linelen == 0)
4337 if (es->cursor + argcnt > es->linelen)
4339 for (n = 0; n < argcnt; ++n)
4340 es->cbuf[es->cursor + n] = cmd[1];
4341 es->cursor += n - 1;
4352 if (es->linelen == 0)
4356 if (es->cursor + argcnt > es->linelen)
4357 argcnt = es->linelen - es->cursor;
4358 del_range(es->cursor, es->cursor + argcnt);
4364 if (es->linelen == 0)
4367 es->cbuf[es->linelen] = '\0';
4368 histsave(&source->line, es->cbuf,
4371 argcnt = source->line + 1 -
4375 shf_snprintf(es->cbuf, es->cbufsize, "%s %d",
4376 "fc -e ${VISUAL:-${EDITOR:-vi}} --",
4380 "fc -e ${VISUAL:-${EDITOR:-vi}} --",
4382 es->linelen = strlen(es->cbuf);
4386 if (es->linelen == 0)
4390 if (es->cursor + argcnt > es->linelen)
4391 argcnt = es->linelen - es->cursor;
4392 yank_range(es->cursor, es->cursor + argcnt);
4393 del_range(es->cursor, es->cursor + argcnt);
4397 if (es->cursor > 0) {
4400 if (es->cursor < argcnt)
4401 argcnt = es->cursor;
4402 yank_range(es->cursor - argcnt, es->cursor);
4403 del_range(es->cursor - argcnt, es->cursor);
4404 es->cursor -= argcnt;
4418 if (grabhist(modified, ohnum) < 0)
4435 if (lastsearch == ' ')
4437 if (lastsearch == '?')
4443 if ((c2 = grabsearch(modified, hnum,
4444 c1, srchpat)) < 0) {
4456 /* flag from cursor-up command */
4457 es->cursor = argcnt - 2;
4466 if (histnum(-1) < 0)
4469 #define issp(c) (ksh_isspace(c) || (c) == '\n')
4471 while (*p && issp(*p))
4473 while (*p && --argcnt) {
4474 while (*p && !issp(*p))
4476 while (*p && issp(*p))
4498 if (es->cursor != es->linelen)
4500 while (*p && !issp(*p)) {
4504 if (putbuf(" ", 1, false) != 0 ||
4505 putbuf(sp, argcnt, false) != 0) {
4506 if (es->cursor != 0)
4519 if (es->linelen == 0)
4521 for (i = 0; i < argcnt; i++) {
4522 p = &es->cbuf[es->cursor];
4523 if (ksh_islower(*p)) {
4526 *p = ksh_toupper(*p);
4527 } else if (ksh_isupper(*p)) {
4530 *p = ksh_tolower(*p);
4532 if (es->cursor < es->linelen - 1)
4540 int ret = x_do_comment(es->cbuf, es->cbufsize,
4549 /* Nonstandard vi/ksh */
4551 print_expansions(es, 1);
4555 /* Nonstandard vi/ksh */
4557 if (!Flag(FVITABCOMPLETE))
4559 complete_word(1, argcnt);
4562 /* some annoying AT&T kshs */
4564 if (!Flag(FVIESCCOMPLETE))
4568 /* Nonstandard vi/ksh */
4570 complete_word(1, argcnt);
4576 /* Nonstandard vi/ksh */
4582 /* mksh: cursor movement */
4586 if (es->linelen != 0)
4591 if (insert == 0 && es->cursor != 0 && es->cursor >= es->linelen)
4598 domove(int argcnt, const char *cmd, int sub)
4600 int bcount, i = 0, t;
4605 if (!sub && es->cursor == 0)
4607 ncursor = backword(argcnt);
4611 if (!sub && es->cursor == 0)
4613 ncursor = Backword(argcnt);
4617 if (!sub && es->cursor + 1 >= es->linelen)
4619 ncursor = endword(argcnt);
4620 if (sub && ncursor < es->linelen)
4625 if (!sub && es->cursor + 1 >= es->linelen)
4627 ncursor = Endword(argcnt);
4628 if (sub && ncursor < es->linelen)
4642 if (fsavecmd == ' ')
4644 i = fsavecmd == 'f' || fsavecmd == 'F';
4648 if ((ncursor = findch(fsavech, argcnt, tobool(t),
4657 if (!sub && es->cursor == 0)
4659 ncursor = es->cursor - argcnt;
4666 if (!sub && es->cursor + 1 >= es->linelen)
4668 if (es->linelen != 0) {
4669 ncursor = es->cursor + argcnt;
4670 if (ncursor > es->linelen)
4671 ncursor = es->linelen;
4676 if (!sub && es->cursor + 1 >= es->linelen)
4678 ncursor = forwword(argcnt);
4682 if (!sub && es->cursor + 1 >= es->linelen)
4684 ncursor = Forwword(argcnt);
4693 while (ncursor < es->linelen - 1 &&
4694 ksh_isspace(es->cbuf[ncursor]))
4700 if (ncursor > es->linelen)
4701 ncursor = es->linelen;
4707 if (es->linelen != 0)
4708 ncursor = es->linelen;
4714 ncursor = es->cursor;
4715 while (ncursor < es->linelen &&
4716 (i = bracktype(es->cbuf[ncursor])) == 0)
4718 if (ncursor == es->linelen)
4723 if (++ncursor >= es->linelen)
4729 t = bracktype(es->cbuf[ncursor]);
4734 } while (bcount != 0);
4746 redo_insert(int count)
4749 if (putbuf(ibuf, inslen, tobool(insert == REPLACE)) != 0)
4758 yank_range(int a, int b)
4762 memmove(ybuf, &es->cbuf[a], yanklen);
4794 * Non user interface editor routines below here
4800 memmove(holdbufp, es->cbuf, es->linelen);
4801 holdlen = es->linelen;
4802 holdbufp[holdlen] = '\0';
4809 es->linelen = holdlen;
4810 memmove(es->cbuf, holdbufp, holdlen);
4813 /* return a new edstate */
4814 static struct edstate *
4815 save_edstate(struct edstate *old)
4817 struct edstate *news;
4819 news = alloc(sizeof(struct edstate), AEDIT);
4820 news->cbuf = alloc(old->cbufsize, AEDIT);
4821 memcpy(news->cbuf, old->cbuf, old->linelen);
4822 news->cbufsize = old->cbufsize;
4823 news->linelen = old->linelen;
4824 news->cursor = old->cursor;
4825 news->winleft = old->winleft;
4830 restore_edstate(struct edstate *news, struct edstate *old)
4832 memcpy(news->cbuf, old->cbuf, old->linelen);
4833 news->linelen = old->linelen;
4834 news->cursor = old->cursor;
4835 news->winleft = old->winleft;
4840 free_edstate(struct edstate *old)
4842 afree(old->cbuf, AEDIT);
4847 * this is used for calling x_escape() in complete_word()
4850 x_vi_putbuf(const char *s, size_t len)
4852 return (putbuf(s, len, false));
4856 putbuf(const char *buf, ssize_t len, bool repl)
4861 if (es->cursor + len >= es->cbufsize)
4863 if (es->cursor + len > es->linelen)
4864 es->linelen = es->cursor + len;
4866 if (es->linelen + len >= es->cbufsize)
4868 memmove(&es->cbuf[es->cursor + len], &es->cbuf[es->cursor],
4869 es->linelen - es->cursor);
4872 memmove(&es->cbuf[es->cursor], buf, len);
4878 del_range(int a, int b)
4880 if (es->linelen != b)
4881 memmove(&es->cbuf[a], &es->cbuf[b], es->linelen - b);
4882 es->linelen -= b - a;
4886 findch(int ch, int cnt, bool forw, bool incl)
4890 if (es->linelen == 0)
4892 ncursor = es->cursor;
4896 if (++ncursor == es->linelen)
4902 } while (es->cbuf[ncursor] != ch);
4914 forwword(int argcnt)
4918 ncursor = es->cursor;
4919 while (ncursor < es->linelen && argcnt--) {
4920 if (ksh_isalnux(es->cbuf[ncursor]))
4921 while (ksh_isalnux(es->cbuf[ncursor]) &&
4922 ncursor < es->linelen)
4924 else if (!ksh_isspace(es->cbuf[ncursor]))
4925 while (!ksh_isalnux(es->cbuf[ncursor]) &&
4926 !ksh_isspace(es->cbuf[ncursor]) &&
4927 ncursor < es->linelen)
4929 while (ksh_isspace(es->cbuf[ncursor]) &&
4930 ncursor < es->linelen)
4937 backword(int argcnt)
4941 ncursor = es->cursor;
4942 while (ncursor > 0 && argcnt--) {
4943 while (--ncursor > 0 && ksh_isspace(es->cbuf[ncursor]))
4946 if (ksh_isalnux(es->cbuf[ncursor]))
4947 while (--ncursor >= 0 &&
4948 ksh_isalnux(es->cbuf[ncursor]))
4951 while (--ncursor >= 0 &&
4952 !ksh_isalnux(es->cbuf[ncursor]) &&
4953 !ksh_isspace(es->cbuf[ncursor]))
4966 ncursor = es->cursor;
4967 while (ncursor < es->linelen && argcnt--) {
4968 while (++ncursor < es->linelen - 1 &&
4969 ksh_isspace(es->cbuf[ncursor]))
4971 if (ncursor < es->linelen - 1) {
4972 if (ksh_isalnux(es->cbuf[ncursor]))
4973 while (++ncursor < es->linelen &&
4974 ksh_isalnux(es->cbuf[ncursor]))
4977 while (++ncursor < es->linelen &&
4978 !ksh_isalnux(es->cbuf[ncursor]) &&
4979 !ksh_isspace(es->cbuf[ncursor]))
4988 Forwword(int argcnt)
4992 ncursor = es->cursor;
4993 while (ncursor < es->linelen && argcnt--) {
4994 while (!ksh_isspace(es->cbuf[ncursor]) &&
4995 ncursor < es->linelen)
4997 while (ksh_isspace(es->cbuf[ncursor]) &&
4998 ncursor < es->linelen)
5005 Backword(int argcnt)
5009 ncursor = es->cursor;
5010 while (ncursor > 0 && argcnt--) {
5011 while (--ncursor >= 0 && ksh_isspace(es->cbuf[ncursor]))
5013 while (ncursor >= 0 && !ksh_isspace(es->cbuf[ncursor]))
5025 ncursor = es->cursor;
5026 while (ncursor < es->linelen - 1 && argcnt--) {
5027 while (++ncursor < es->linelen - 1 &&
5028 ksh_isspace(es->cbuf[ncursor]))
5030 if (ncursor < es->linelen - 1) {
5031 while (++ncursor < es->linelen &&
5032 !ksh_isspace(es->cbuf[ncursor]))
5041 grabhist(int save, int n)
5045 if (n < 0 || n > hlast)
5053 if ((hptr = *histpos()) == NULL) {
5054 internal_warningf("%s: %s", "grabhist", "bad history array");
5059 if ((es->linelen = strlen(hptr)) >= es->cbufsize)
5060 es->linelen = es->cbufsize - 1;
5061 memmove(es->cbuf, hptr, es->linelen);
5068 grabsearch(int save, int start, int fwd, const char *pat)
5074 if ((start == 0 && fwd == 0) || (start >= hlast - 1 && fwd == 1))
5080 anchored = *pat == '^' ? (++pat, true) : false;
5081 if ((hist = findhist(start, fwd, pat, anchored)) < 0) {
5082 /* (start != 0 && fwd && match(holdbufp, pat) >= 0) */
5083 if (start != 0 && fwd && strcmp(holdbufp, pat) >= 0) {
5093 if ((es->linelen = strlen(hptr)) >= es->cbufsize)
5094 es->linelen = es->cbufsize - 1;
5095 memmove(es->cbuf, hptr, es->linelen);
5101 redraw_line(bool newl)
5104 memset(wbuf[win], ' ', wbuf_len);
5109 if (prompt_trunc != -1)
5110 pprompt(prompt, prompt_trunc);
5116 refresh(int leftside)
5124 display(wbuf[1 - win], wbuf[win], leftside);
5133 if (es->cursor < es->winleft)
5137 while (cur < es->cursor)
5138 col = newcol((unsigned char)es->cbuf[cur++], col);
5139 if (col >= winwidth)
5148 int holdcur1, holdcol1;
5149 int holdcur2, holdcol2;
5151 holdcur1 = holdcur2 = tcur = 0;
5152 holdcol1 = holdcol2 = tcol = 0;
5153 while (tcur < es->cursor) {
5154 if (tcol - holdcol2 > winwidth / 2) {
5155 holdcur1 = holdcur2;
5156 holdcol1 = holdcol2;
5160 tcol = newcol((unsigned char)es->cbuf[tcur++], tcol);
5162 while (tcol - holdcol1 > winwidth / 2)
5163 holdcol1 = newcol((unsigned char)es->cbuf[holdcur1++],
5165 es->winleft = holdcur1;
5169 newcol(unsigned char ch, int col)
5172 return ((col | 7) + 1);
5173 return (col + char_len(ch));
5177 display(char *wb1, char *wb2, int leftside)
5180 char *twb1, *twb2, mc;
5189 while (col < winwidth && cur < es->linelen) {
5190 if (cur == es->cursor && leftside)
5191 ncol = col + pwidth;
5192 if ((ch = es->cbuf[cur]) == '\t')
5195 } while (++col < winwidth && (col & 7) != 0);
5196 else if (col < winwidth) {
5197 if (ISCTRL(ch) && /* but not C1 */ ch < 0x80) {
5199 if (++col < winwidth) {
5200 *twb1++ = UNCTRL(ch);
5208 if (cur == es->cursor && !leftside)
5209 ncol = col + pwidth - 1;
5212 if (cur == es->cursor)
5213 ncol = col + pwidth;
5214 if (col < winwidth) {
5215 while (col < winwidth) {
5228 if (*twb1 != *twb2) {
5230 ed_mov_opt(col, wb1);
5238 if (es->winleft > 0 && moreright)
5240 * POSIX says to use * for this but that is a globbing
5241 * character and may confuse people; + is more innocuous
5244 else if (es->winleft > 0)
5251 ed_mov_opt(pwidth + winwidth + 1, wb1);
5257 ed_mov_opt(ncol, wb1);
5261 ed_mov_opt(int col, char *wb)
5264 if (col + 1 < x_col - col) {
5266 if (prompt_trunc != -1)
5267 pprompt(prompt, prompt_trunc);
5269 while (x_col++ < col)
5272 while (x_col-- > col)
5276 wb = &wb[x_col - pwidth];
5277 while (x_col++ < col)
5284 /* replace word with all expansions (ie, expand word*) */
5286 expand_word(int cmd)
5288 static struct edstate *buf;
5289 int rval = 0, nwords, start, end, i;
5292 /* Undo previous expansion */
5293 if (cmd == 0 && expanded == EXPAND && buf) {
5294 restore_edstate(es, buf);
5304 i = XCF_COMMAND_FILE | XCF_FULLPATH;
5305 nwords = x_cf_glob(&i, es->cbuf, es->linelen, es->cursor,
5306 &start, &end, &words);
5312 buf = save_edstate(es);
5314 del_range(start, end);
5317 while (i < nwords) {
5318 if (x_escape(words[i], strlen(words[i]), x_vi_putbuf) != 0) {
5322 if (++i < nwords && putbuf(" ", 1, false) != 0) {
5327 i = buf->cursor - end;
5328 if (rval == 0 && i > 0)
5339 complete_word(int cmd, int count)
5341 static struct edstate *buf;
5342 int rval, nwords, start, end, flags;
5348 /* Undo previous completion */
5349 if (cmd == 0 && expanded == COMPLETE && buf) {
5350 print_expansions(buf, 0);
5354 if (cmd == 0 && expanded == PRINT && buf) {
5355 restore_edstate(es, buf);
5366 * XCF_FULLPATH for count 'cause the menu printed by
5367 * print_expansions() was done this way.
5369 flags = XCF_COMMAND_FILE;
5371 flags |= XCF_FULLPATH;
5372 nwords = x_cf_glob(&flags, es->cbuf, es->linelen, es->cursor,
5373 &start, &end, &words);
5382 if (count >= nwords) {
5384 x_print_expansions(nwords, words,
5385 tobool(flags & XCF_IS_COMMAND));
5386 x_free_words(nwords, words);
5391 * Expand the count'th word to its basename
5393 if (flags & XCF_IS_COMMAND) {
5394 match = words[count] +
5395 x_basename(words[count], NULL);
5396 /* If more than one possible match, use full path */
5397 for (i = 0; i < nwords; i++)
5399 strcmp(words[i] + x_basename(words[i],
5400 NULL), match) == 0) {
5401 match = words[count];
5405 match = words[count];
5406 match_len = strlen(match);
5408 /* expanded = PRINT; next call undo */
5411 match_len = x_longest_prefix(nwords, words);
5412 /* next call will list completions */
5413 expanded = COMPLETE;
5414 is_unique = nwords == 1;
5417 buf = save_edstate(es);
5418 del_range(start, end);
5422 * escape all shell-sensitive characters and put the result into
5425 rval = x_escape(match, match_len, x_vi_putbuf);
5427 if (rval == 0 && is_unique) {
5429 * If exact match, don't undo. Allows directory completions
5430 * to be used (ie, complete the next portion of the path).
5435 * append a space if this is a non-directory match
5436 * and not a parameter or homedir substitution
5438 if (match_len > 0 && match[match_len - 1] != '/' &&
5439 !(flags & XCF_IS_NOSPACE))
5440 rval = putbuf(" ", 1, false);
5442 x_free_words(nwords, words);
5447 /* prevent this from being redone... */
5455 print_expansions(struct edstate *est, int cmd MKSH_A_UNUSED)
5457 int start, end, nwords, i;
5460 i = XCF_COMMAND_FILE | XCF_FULLPATH;
5461 nwords = x_cf_glob(&i, est->cbuf, est->linelen, est->cursor,
5462 &start, &end, &words);
5467 x_print_expansions(nwords, words, tobool(i & XCF_IS_COMMAND));
5468 x_free_words(nwords, words);
5473 /* Similar to x_zotc(emacs.c), but no tab weirdness */
5487 /* Beem out of any macros as soon as an error occurs */
5494 vi_macro_reset(void)
5497 afree(macro.buf, AEDIT);
5498 memset((char *)¯o, 0, sizeof(macro));
5501 #endif /* !MKSH_S_NOVI */
5503 /* called from main.c */
5510 * Set edchars to -2 to force initial binding, except
5511 * we need default values for some deficient systems…
5513 edchars.erase = edchars.kill = edchars.intr = edchars.quit =
5516 edchars.werase = 027;
5518 /* command line editing specific memory allocation */
5520 holdbufp = alloc(LINE, AEDIT);
5522 /* initialise Emacs command line editing mode */
5525 x_tab = alloc2(X_NTABS, sizeof(*x_tab), AEDIT);
5526 for (j = 0; j < X_TABSZ; j++)
5527 x_tab[0][j] = XFUNC_insert;
5528 for (i = 1; i < X_NTABS; i++)
5529 for (j = 0; j < X_TABSZ; j++)
5530 x_tab[i][j] = XFUNC_error;
5531 for (i = 0; i < (int)NELEM(x_defbindings); i++)
5532 x_tab[x_defbindings[i].xdb_tab][x_defbindings[i].xdb_char]
5533 = x_defbindings[i].xdb_func;
5536 x_atab = alloc2(X_NTABS, sizeof(*x_atab), AEDIT);
5537 for (i = 1; i < X_NTABS; i++)
5538 for (j = 0; j < X_TABSZ; j++)
5539 x_atab[i][j] = NULL;
5551 #endif /* !MKSH_NO_CMDLINE_EDITING */