1 /* vi: set sw=4 ts=4: */
3 * Termios command line History and Editing.
5 * Copyright (c) 1986-2003 may safely be consumed by a BSD or GPL license.
6 * Written by: Vladimir Oleynik <dzo@simtreas.ru>
9 * Adam Rogoyski <rogoyski@cs.utexas.edu>
10 * Dave Cinege <dcinege@psychosis.com>
11 * Jakub Jelinek (c) 1995
12 * Erik Andersen <andersen@codepoet.org> (Majorly adjusted for busybox)
14 * This code is 'as is' with no warranty.
18 * Usage and known bugs:
19 * Terminal key codes are not extensive, more needs to be added.
20 * This version was created on Debian GNU/Linux 2.x.
21 * Delete, Backspace, Home, End, and the arrow keys were tested
22 * to work in an Xterm and console. Ctrl-A also works as Home.
23 * Ctrl-E also works as End.
25 * The following readline-like commands are not implemented:
26 * ESC-b -- Move back one word
27 * ESC-f -- Move forward one word
28 * ESC-d -- Delete forward one word
29 * CTL-t -- Transpose two characters
31 * lineedit does not know that the terminal escape sequences do not
32 * take up space on the screen. The redisplay code assumes, unless
33 * told otherwise, that each character in the prompt is a printable
34 * character that takes up one character position on the screen.
35 * You need to tell lineedit that some sequences of characters
36 * in the prompt take up no screen space. Compatibly with readline,
37 * use the \[ escape to begin a sequence of non-printing characters,
38 * and the \] escape to signal the end of such a sequence. Example:
40 * PS1='\[\033[01;32m\]\u@\h\[\033[01;34m\] \w \$\[\033[00m\] '
45 /* FIXME: obsolete CONFIG item? */
46 #define ENABLE_FEATURE_NONPRINTABLE_INVERSE_PUT 0
49 # define ENABLE_FEATURE_EDITING 0
50 # define ENABLE_FEATURE_TAB_COMPLETION 0
51 # define ENABLE_FEATURE_USERNAME_COMPLETION 0
52 # define ENABLE_FEATURE_NONPRINTABLE_INVERSE_PUT 0
56 /* Entire file (except TESTing part) sits inside this #if */
57 #if ENABLE_FEATURE_EDITING
60 #define ENABLE_FEATURE_GETUSERNAME_AND_HOMEDIR \
61 (ENABLE_FEATURE_USERNAME_COMPLETION || ENABLE_FEATURE_EDITING_FANCY_PROMPT)
62 #define IF_FEATURE_GETUSERNAME_AND_HOMEDIR(...)
63 #if ENABLE_FEATURE_GETUSERNAME_AND_HOMEDIR
64 #undef IF_FEATURE_GETUSERNAME_AND_HOMEDIR
65 #define IF_FEATURE_GETUSERNAME_AND_HOMEDIR(...) __VA_ARGS__
70 #if ENABLE_FEATURE_ASSUME_UNICODE
72 # define CHAR_T wchar_t
73 static bool BB_isspace(CHAR_T c) { return ((unsigned)c < 256 && isspace(c)); }
74 static bool BB_isalnum(CHAR_T c) { return ((unsigned)c < 256 && isalnum(c)); }
75 static bool BB_ispunct(CHAR_T c) { return ((unsigned)c < 256 && ispunct(c)); }
80 # define isspace isspace_must_not_be_used
81 # define isalnum isalnum_must_not_be_used
82 # define ispunct ispunct_must_not_be_used
83 # define isprint isprint_must_not_be_used
87 # define BB_isspace(c) isspace(c)
88 # define BB_isalnum(c) isalnum(c)
89 # define BB_ispunct(c) ispunct(c)
94 /* We use int16_t for positions, need to limit line len */
95 MAX_LINELEN = CONFIG_FEATURE_EDITING_MAX_LEN < 0x7ff0
96 ? CONFIG_FEATURE_EDITING_MAX_LEN
100 #if ENABLE_FEATURE_GETUSERNAME_AND_HOMEDIR
101 static const char null_str[] ALIGN1 = "";
104 /* We try to minimize both static and stack usage. */
105 struct lineedit_statics {
108 volatile unsigned cmdedit_termw; /* = 80; */ /* actual terminal width */
109 sighandler_t previous_SIGWINCH_handler;
111 unsigned cmdedit_x; /* real x (col) terminal position */
112 unsigned cmdedit_y; /* pseudoreal y (row) terminal position */
113 unsigned cmdedit_prmt_len; /* length of prompt (without colors etc) */
116 int command_len; /* must be signed */
117 /* signed maxsize: we want x in "if (x > S.maxsize)"
118 * to _not_ be promoted to unsigned */
122 const char *cmdedit_prompt;
123 #if ENABLE_FEATURE_EDITING_FANCY_PROMPT
124 int num_ok_lines; /* = 1; */
127 #if ENABLE_FEATURE_GETUSERNAME_AND_HOMEDIR
129 char *home_pwd_buf; /* = (char*)null_str; */
132 #if ENABLE_FEATURE_TAB_COMPLETION
134 unsigned num_matches;
137 #if ENABLE_FEATURE_EDITING_VI
138 #define DELBUFSIZ 128
140 smallint newdelflag; /* whether delbuf should be reused yet */
141 CHAR_T delbuf[DELBUFSIZ]; /* a place to store deleted characters */
143 #if ENABLE_FEATURE_EDITING_ASK_TERMINAL
144 smallint sent_ESC_br6n;
147 /* Formerly these were big buffers on stack: */
148 #if ENABLE_FEATURE_TAB_COMPLETION
149 char exe_n_cwd_tab_completion__dirbuf[MAX_LINELEN];
150 char input_tab__matchBuf[MAX_LINELEN];
151 int16_t find_match__int_buf[MAX_LINELEN + 1]; /* need to have 9 bits at least */
152 int16_t find_match__pos_buf[MAX_LINELEN + 1];
156 /* See lineedit_ptr_hack.c */
157 extern struct lineedit_statics *const lineedit_ptr_to_statics;
159 #define S (*lineedit_ptr_to_statics)
160 #define state (S.state )
161 #define cmdedit_termw (S.cmdedit_termw )
162 #define previous_SIGWINCH_handler (S.previous_SIGWINCH_handler)
163 #define cmdedit_x (S.cmdedit_x )
164 #define cmdedit_y (S.cmdedit_y )
165 #define cmdedit_prmt_len (S.cmdedit_prmt_len)
166 #define cursor (S.cursor )
167 #define command_len (S.command_len )
168 #define command_ps (S.command_ps )
169 #define cmdedit_prompt (S.cmdedit_prompt )
170 #define num_ok_lines (S.num_ok_lines )
171 #define user_buf (S.user_buf )
172 #define home_pwd_buf (S.home_pwd_buf )
173 #define matches (S.matches )
174 #define num_matches (S.num_matches )
175 #define delptr (S.delptr )
176 #define newdelflag (S.newdelflag )
177 #define delbuf (S.delbuf )
179 #define INIT_S() do { \
180 (*(struct lineedit_statics**)&lineedit_ptr_to_statics) = xzalloc(sizeof(S)); \
182 cmdedit_termw = 80; \
183 IF_FEATURE_EDITING_FANCY_PROMPT(num_ok_lines = 1;) \
184 IF_FEATURE_GETUSERNAME_AND_HOMEDIR(home_pwd_buf = (char*)null_str;) \
186 static void deinit_S(void)
188 #if ENABLE_FEATURE_EDITING_FANCY_PROMPT
189 /* This one is allocated only if FANCY_PROMPT is on
190 * (otherwise it points to verbatim prompt (NOT malloced) */
191 free((char*)cmdedit_prompt);
193 #if ENABLE_FEATURE_GETUSERNAME_AND_HOMEDIR
195 if (home_pwd_buf != null_str)
198 free(lineedit_ptr_to_statics);
200 #define DEINIT_S() deinit_S()
203 #if ENABLE_FEATURE_ASSUME_UNICODE
204 static size_t load_string(const char *src, int maxsize)
206 ssize_t len = mbstowcs(command_ps, src, maxsize - 1);
209 command_ps[len] = L'\0';
212 static size_t save_string(char *dst, int maxsize)
214 ssize_t len = wcstombs(dst, command_ps, maxsize - 1);
220 /* I thought just fputwc(c, stdout) would work. But no... */
221 static void BB_PUTCHAR(wchar_t c)
223 char buf[MB_CUR_MAX + 1];
224 mbstate_t mbst = { 0 };
225 ssize_t len = wcrtomb(buf, c, &mbst);
233 static size_t load_string(const char *src, int maxsize)
235 safe_strncpy(command_ps, src, maxsize);
236 return strlen(command_ps);
238 # if ENABLE_FEATURE_TAB_COMPLETION
239 static void save_string(char *dst, int maxsize)
241 safe_strncpy(dst, command_ps, maxsize);
244 # define BB_PUTCHAR(c) bb_putchar(c)
248 /* Put 'command_ps[cursor]', cursor++.
249 * Advance cursor on screen. If we reached right margin, scroll text up
250 * and remove terminal margin effect by printing 'next_char' */
251 #define HACK_FOR_WRONG_WIDTH 1
252 #if HACK_FOR_WRONG_WIDTH
253 static void cmdedit_set_out_char(void)
254 #define cmdedit_set_out_char(next_char) cmdedit_set_out_char()
256 static void cmdedit_set_out_char(int next_char)
259 CHAR_T c = command_ps[cursor];
262 /* erase character after end of input string */
265 #if ENABLE_FEATURE_NONPRINTABLE_INVERSE_PUT
266 /* Display non-printable characters in reverse */
267 if (!BB_isprint(c)) {
274 printf("\033[7m%c\033[0m", c);
280 if (++cmdedit_x >= cmdedit_termw) {
281 /* terminal is scrolled down */
284 #if HACK_FOR_WRONG_WIDTH
285 /* This works better if our idea of term width is wrong
286 * and it is actually wider (often happens on serial lines).
287 * Printing CR,LF *forces* cursor to next line.
288 * OTOH if terminal width is correct AND terminal does NOT
289 * have automargin (IOW: it is moving cursor to next line
290 * by itself (which is wrong for VT-10x terminals)),
291 * this will break things: there will be one extra empty line */
292 puts("\r"); /* + implicit '\n' */
294 /* Works ok only if cmdedit_termw is correct */
295 /* destroy "(auto)margin" */
296 bb_putchar(next_char);
300 // Huh? What if command_ps[cursor] == BB_NUL (we are at the end already?)
304 /* Move to end of line (by printing all chars till the end) */
305 static void input_end(void)
307 while (cursor < command_len)
308 cmdedit_set_out_char(' ');
311 /* Go to the next line */
312 static void goto_new_line(void)
320 static void out1str(const char *s)
326 static void beep(void)
331 /* Move back one character */
332 /* (optimized for slow terminals) */
333 static void input_backward(unsigned num)
343 if (cmdedit_x >= num) {
346 /* This is longer by 5 bytes on x86.
347 * Also gets miscompiled for ARM users
348 * (busybox.net/bugs/view.php?id=2274).
349 * printf(("\b\b\b\b" + 4) - num);
357 printf("\033[%uD", num);
361 /* Need to go one or more lines up */
364 unsigned w = cmdedit_termw; /* volatile var */
365 count_y = 1 + (num / w);
366 cmdedit_y -= count_y;
367 cmdedit_x = w * count_y - num;
369 /* go to 1st column; go up; go to correct column */
370 printf("\r" "\033[%dA" "\033[%dC", count_y, cmdedit_x);
373 static void put_prompt(void)
377 out1str(cmdedit_prompt);
380 w = cmdedit_termw; /* read volatile var once */
381 cmdedit_y = cmdedit_prmt_len / w; /* new quasireal y */
382 cmdedit_x = cmdedit_prmt_len % w;
385 /* draw prompt, editor line, and clear tail */
386 static void redraw(int y, int back_cursor)
388 if (y > 0) /* up to start y */
389 printf("\033[%uA", y);
392 input_end(); /* rewrite */
393 printf("\033[J"); /* erase after cursor */
394 input_backward(back_cursor);
397 /* Delete the char in front of the cursor, optionally saving it
398 * for later putback */
399 #if !ENABLE_FEATURE_EDITING_VI
400 static void input_delete(void)
401 #define input_delete(save) input_delete()
403 static void input_delete(int save)
408 if (j == (int)command_len)
411 #if ENABLE_FEATURE_EDITING_VI
417 if ((delptr - delbuf) < DELBUFSIZ)
418 *delptr++ = command_ps[j];
422 memmove(command_ps + j, command_ps + j + 1,
423 /* (command_len + 1 [because of NUL]) - (j + 1)
424 * simplified into (command_len - j) */
425 (command_len - j) * sizeof(command_ps[0]));
427 input_end(); /* rewrite new line */
428 cmdedit_set_out_char(' '); /* erase char */
429 input_backward(cursor - j); /* back to old pos cursor */
432 #if ENABLE_FEATURE_EDITING_VI
433 static void put(void)
436 int j = delptr - delbuf;
441 /* open hole and then fill it */
442 memmove(command_ps + cursor + j, command_ps + cursor,
443 (command_len - cursor + 1) * sizeof(command_ps[0]));
444 memcpy(command_ps + cursor, delbuf, j * sizeof(command_ps[0]));
446 input_end(); /* rewrite new line */
447 input_backward(cursor - ocursor - j + 1); /* at end of new text */
451 /* Delete the char in back of the cursor */
452 static void input_backspace(void)
460 /* Move forward one character */
461 static void input_forward(void)
463 if (cursor < command_len)
464 cmdedit_set_out_char(command_ps[cursor + 1]);
467 #if ENABLE_FEATURE_TAB_COMPLETION
469 static void free_tab_completion_data(void)
473 free(matches[--num_matches]);
479 static void add_match(char *matched)
481 matches = xrealloc_vector(matches, 4, num_matches);
482 matches[num_matches] = matched;
486 #if ENABLE_FEATURE_USERNAME_COMPLETION
487 static void username_tab_completion(char *ud, char *with_shash_flg)
489 struct passwd *entry;
492 ud++; /* ~user/... to user/... */
493 userlen = strlen(ud);
495 if (with_shash_flg) { /* "~/..." or "~user/..." */
496 char *sav_ud = ud - 1;
499 if (*ud == '/') { /* "~/..." */
504 temp = strchr(ud, '/');
505 *temp = '\0'; /* ~user\0 */
506 entry = getpwnam(ud);
507 *temp = '/'; /* restore ~user/... */
510 home = entry->pw_dir;
513 if ((userlen + strlen(home) + 1) < MAX_LINELEN) {
515 sprintf(sav_ud, "%s%s", home, ud);
520 /* Using _r function to avoid pulling in static buffers */
523 struct passwd *result;
526 while (!getpwent_r(&pwd, line_buff, sizeof(line_buff), &result)) {
527 /* Null usernames should result in all users as possible completions. */
528 if (/*!userlen || */ strncmp(ud, pwd.pw_name, userlen) == 0) {
529 add_match(xasprintf("~%s/", pwd.pw_name));
535 #endif /* FEATURE_COMMAND_USERNAME_COMPLETION */
543 static int path_parse(char ***p, int flags)
550 /* if not setenv PATH variable, to search cur dir "." */
551 if (flags != FIND_EXE_ONLY)
554 if (state->flags & WITH_PATH_LOOKUP)
555 pth = state->path_lookup;
557 pth = getenv("PATH");
558 /* PATH=<empty> or PATH=:<empty> */
559 if (!pth || !pth[0] || LONE_CHAR(pth, ':'))
563 npth = 1; /* path component count */
565 tmp = strchr(tmp, ':');
569 break; /* :<empty> */
573 res = xmalloc(npth * sizeof(char*));
574 res[0] = tmp = xstrdup(pth);
577 tmp = strchr(tmp, ':');
580 *tmp++ = '\0'; /* ':' -> '\0' */
582 break; /* :<empty> */
589 static void exe_n_cwd_tab_completion(char *command, int type)
595 char **paths = path1;
599 char *pfind = strrchr(command, '/');
600 /* char dirbuf[MAX_LINELEN]; */
601 #define dirbuf (S.exe_n_cwd_tab_completion__dirbuf)
604 path1[0] = (char*)".";
607 /* no dir, if flags==EXE_ONLY - get paths, else "." */
608 npaths = path_parse(&paths, type);
611 /* dirbuf = ".../.../.../" */
612 safe_strncpy(dirbuf, command, (pfind - command) + 2);
613 #if ENABLE_FEATURE_USERNAME_COMPLETION
614 if (dirbuf[0] == '~') /* ~/... or ~user/... */
615 username_tab_completion(dirbuf, dirbuf);
618 /* point to 'l' in "..../last_component" */
622 for (i = 0; i < npaths; i++) {
623 dir = opendir(paths[i]);
625 continue; /* don't print an error */
627 while ((next = readdir(dir)) != NULL) {
629 const char *str_found = next->d_name;
632 if (strncmp(str_found, pfind, strlen(pfind)))
634 /* not see .name without .match */
635 if (*str_found == '.' && *pfind == '\0') {
636 if (NOT_LONE_CHAR(paths[i], '/') || str_found[1])
638 str_found = ""; /* only "/" */
640 found = concat_path_file(paths[i], str_found);
641 /* hmm, remove in progress? */
642 /* NB: stat() first so that we see is it a directory;
643 * but if that fails, use lstat() so that
644 * we still match dangling links */
645 if (stat(found, &st) && lstat(found, &st))
647 /* find with dirs? */
648 if (paths[i] != dirbuf)
649 strcpy(found, next->d_name); /* only name */
651 len1 = strlen(found);
652 found = xrealloc(found, len1 + 2);
654 found[len1+1] = '\0';
656 if (S_ISDIR(st.st_mode)) {
657 /* name is a directory */
658 if (found[len1-1] != '/') {
662 /* not put found file if search only dirs for cd */
663 if (type == FIND_DIR_ONLY)
666 /* Add it to the list */
674 if (paths != path1) {
675 free(paths[0]); /* allocated memory is only in first member */
681 /* QUOT is used on elements of int_buf[], which are bytes,
682 * not Unicode chars. Therefore it works correctly even in Unicode mode.
684 #define QUOT (UCHAR_MAX+1)
686 #define int_buf (S.find_match__int_buf)
687 #define pos_buf (S.find_match__pos_buf)
688 /* is must be <= in */
689 static void collapse_pos(int is, int in)
691 memmove(int_buf+is, int_buf+in, (MAX_LINELEN+1-in)*sizeof(int_buf[0]));
692 memmove(pos_buf+is, pos_buf+in, (MAX_LINELEN+1-in)*sizeof(pos_buf[0]));
694 static NOINLINE int find_match(char *matchBuf, int *len_with_quotes)
699 /* Were local, but it uses too much stack */
700 /* int16_t int_buf[MAX_LINELEN + 1]; */
701 /* int16_t pos_buf[MAX_LINELEN + 1]; */
703 /* set to integer dimension characters and own positions */
705 int_buf[i] = (unsigned char)matchBuf[i];
706 if (int_buf[i] == 0) {
707 pos_buf[i] = -1; /* end-fo-line indicator */
713 /* mask \+symbol and convert '\t' to ' ' */
714 for (i = j = 0; matchBuf[i]; i++, j++)
715 if (matchBuf[i] == '\\') {
716 collapse_pos(j, j + 1);
719 #if ENABLE_FEATURE_NONPRINTABLE_INVERSE_PUT
720 if (matchBuf[i] == '\t') /* algorithm equivalent */
721 int_buf[j] = ' ' | QUOT;
724 #if ENABLE_FEATURE_NONPRINTABLE_INVERSE_PUT
725 else if (matchBuf[i] == '\t')
729 /* mask "symbols" or 'symbols' */
731 for (i = 0; int_buf[i]; i++) {
733 if (c == '\'' || c == '"') {
742 } else if (c2 != 0 && c != '$')
746 /* skip commands with arguments if line has commands delimiters */
747 /* ';' ';;' '&' '|' '&&' '||' but `>&' `<&' `>|' */
748 for (i = 0; int_buf[i]; i++) {
751 j = i ? int_buf[i - 1] : -1;
753 if (c == ';' || c == '&' || c == '|') {
754 command_mode = 1 + (c == c2);
756 if (j == '>' || j == '<')
758 } else if (c == '|' && j == '>')
762 collapse_pos(0, i + command_mode);
763 i = -1; /* hack incremet */
766 /* collapse `command...` */
767 for (i = 0; int_buf[i]; i++) {
768 if (int_buf[i] == '`') {
769 for (j = i + 1; int_buf[j]; j++)
770 if (int_buf[j] == '`') {
771 collapse_pos(i, j + 1);
776 /* not found closing ` - command mode, collapse all previous */
777 collapse_pos(0, i + 1);
780 i--; /* hack incremet */
784 /* collapse (command...(command...)...) or {command...{command...}...} */
785 c = 0; /* "recursive" level */
787 for (i = 0; int_buf[i]; i++) {
788 if (int_buf[i] == '(' || int_buf[i] == '{') {
789 if (int_buf[i] == '(')
793 collapse_pos(0, i + 1);
794 i = -1; /* hack incremet */
797 for (i = 0; pos_buf[i] >= 0 && (c > 0 || c2 > 0); i++) {
798 if ((int_buf[i] == ')' && c > 0) || (int_buf[i] == '}' && c2 > 0)) {
799 if (int_buf[i] == ')')
803 collapse_pos(0, i + 1);
804 i = -1; /* hack incremet */
808 /* skip first not quote space */
809 for (i = 0; int_buf[i]; i++)
810 if (int_buf[i] != ' ')
815 /* set find mode for completion */
816 command_mode = FIND_EXE_ONLY;
817 for (i = 0; int_buf[i]; i++) {
818 if (int_buf[i] == ' ' || int_buf[i] == '<' || int_buf[i] == '>') {
819 if (int_buf[i] == ' ' && command_mode == FIND_EXE_ONLY
820 && matchBuf[pos_buf[0]] == 'c'
821 && matchBuf[pos_buf[1]] == 'd'
823 command_mode = FIND_DIR_ONLY;
825 command_mode = FIND_FILE_ONLY;
830 for (i = 0; int_buf[i]; i++)
833 for (--i; i >= 0; i--) {
835 if (c == ' ' || c == '<' || c == '>' || c == '|' || c == '&') {
836 collapse_pos(0, i + 1);
840 /* skip first not quoted '\'' or '"' */
841 for (i = 0; int_buf[i] == '\'' || int_buf[i] == '"'; i++)
843 /* collapse quote or unquote // or /~ */
844 while ((int_buf[i] & ~QUOT) == '/'
845 && ((int_buf[i+1] & ~QUOT) == '/' || (int_buf[i+1] & ~QUOT) == '~')
850 /* set only match and destroy quotes */
852 for (c = 0; pos_buf[i] >= 0; i++) {
853 matchBuf[c++] = matchBuf[pos_buf[i]];
857 /* old length matchBuf with quotes symbols */
858 *len_with_quotes = j ? j - pos_buf[0] : 0;
866 * display by column (original idea from ls applet,
867 * very optimized by me :)
869 static void showfiles(void)
872 int column_width = 0;
873 int nfiles = num_matches;
877 /* find the longest file name - use that as the column width */
878 for (row = 0; row < nrows; row++) {
879 l = bb_mbstrlen(matches[row]);
880 if (column_width < l)
883 column_width += 2; /* min space for columns */
884 ncols = cmdedit_termw / column_width;
889 nrows++; /* round up fractionals */
893 for (row = 0; row < nrows; row++) {
897 for (nc = 1; nc < ncols && n+nrows < nfiles; n += nrows, nc++) {
898 printf("%s%-*s", matches[n],
899 (int)(column_width - bb_mbstrlen(matches[n])), ""
906 static char *add_quote_for_spec_chars(char *found)
909 char *s = xzalloc((strlen(found) + 1) * 2);
912 if (strchr(" `\"#$%^&*()=+{}[]:;'|\\<>", *found))
916 /* s[l] = '\0'; - already is */
920 /* Do TAB completion */
921 static void input_tab(smallint *lastWasTab)
923 if (!(state->flags & TAB_COMPLETION))
929 /* char matchBuf[MAX_LINELEN]; */
930 #define matchBuf (S.input_tab__matchBuf)
933 #if ENABLE_FEATURE_ASSUME_UNICODE
934 /* cursor pos in command converted to multibyte form */
938 *lastWasTab = TRUE; /* flop trigger */
940 /* Make a local copy of the string --
941 * up to the position of the cursor */
942 save_string(matchBuf, cursor + 1);
943 #if ENABLE_FEATURE_ASSUME_UNICODE
944 cursor_mb = strlen(matchBuf);
948 find_type = find_match(matchBuf, &recalc_pos);
950 /* Free up any memory already allocated */
951 free_tab_completion_data();
953 #if ENABLE_FEATURE_USERNAME_COMPLETION
954 /* If the word starts with `~' and there is no slash in the word,
955 * then try completing this word as a username. */
956 if (state->flags & USERNAME_COMPLETION)
957 if (matchBuf[0] == '~' && strchr(matchBuf, '/') == NULL)
958 username_tab_completion(matchBuf, NULL);
960 /* Try to match any executable in our path and everything
961 * in the current working directory */
963 exe_n_cwd_tab_completion(matchBuf, find_type);
964 /* Sort, then remove any duplicates found */
968 qsort_string_vector(matches, num_matches);
969 for (i = 0; i < num_matches - 1; ++i) {
970 if (matches[i] && matches[i+1]) { /* paranoia */
971 if (strcmp(matches[i], matches[i+1]) == 0) {
973 matches[i] = NULL; /* paranoia */
975 matches[n++] = matches[i];
979 matches[n] = matches[i];
982 /* Did we find exactly one match? */
983 if (!matches || num_matches > 1) { /* no */
986 return; /* not found */
987 /* find minimal match */
988 tmp1 = xstrdup(matches[0]);
989 for (tmp = tmp1; *tmp; tmp++) {
990 for (len_found = 1; len_found < num_matches; len_found++) {
991 if (matches[len_found][tmp - tmp1] != *tmp) {
997 if (*tmp1 == '\0') { /* have unique */
1001 tmp = add_quote_for_spec_chars(tmp1);
1003 } else { /* one match */
1004 tmp = add_quote_for_spec_chars(matches[0]);
1005 /* for next completion current found */
1006 *lastWasTab = FALSE;
1008 len_found = strlen(tmp);
1009 if (tmp[len_found-1] != '/') {
1010 tmp[len_found] = ' ';
1011 tmp[len_found+1] = '\0';
1015 len_found = strlen(tmp);
1016 #if !ENABLE_FEATURE_ASSUME_UNICODE
1017 /* have space to place the match? */
1018 /* The result consists of three parts with these lengths: */
1019 /* (cursor - recalc_pos) + len_found + (command_len - cursor) */
1020 /* it simplifies into: */
1021 if ((int)(len_found + command_len - recalc_pos) < S.maxsize) {
1023 strcpy(matchBuf, command_ps + cursor);
1024 /* add match and tail */
1025 sprintf(&command_ps[cursor - recalc_pos], "%s%s", tmp, matchBuf);
1026 command_len = strlen(command_ps);
1028 recalc_pos = cursor - recalc_pos + len_found;
1029 /* write out the matched command */
1030 redraw(cmdedit_y, command_len - recalc_pos);
1034 char command[MAX_LINELEN];
1035 int len = save_string(command, sizeof(command));
1036 /* have space to place the match? */
1037 /* (cursor_mb - recalc_pos) + len_found + (len - cursor_mb) */
1038 if ((int)(len_found + len - recalc_pos) < MAX_LINELEN) {
1040 strcpy(matchBuf, command + cursor_mb);
1041 /* where do we want to have cursor after all? */
1042 strcpy(&command[cursor_mb - recalc_pos], tmp);
1043 len = load_string(command, S.maxsize);
1044 /* add match and tail */
1045 sprintf(&command[cursor_mb - recalc_pos], "%s%s", tmp, matchBuf);
1046 command_len = load_string(command, S.maxsize);
1047 /* write out the matched command */
1048 redraw(cmdedit_y, command_len - len);
1055 /* Ok -- the last char was a TAB. Since they
1056 * just hit TAB again, print a list of all the
1057 * available choices... */
1058 if (matches && num_matches > 0) {
1059 /* changed by goto_new_line() */
1060 int sav_cursor = cursor;
1062 /* Go to the next line */
1065 redraw(0, command_len - sav_cursor);
1070 #endif /* FEATURE_COMMAND_TAB_COMPLETION */
1073 line_input_t* FAST_FUNC new_line_input_t(int flags)
1075 line_input_t *n = xzalloc(sizeof(*n));
1083 static void save_command_ps_at_cur_history(void)
1085 if (command_ps[0] != BB_NUL) {
1086 int cur = state->cur_history;
1087 free(state->history[cur]);
1089 # if ENABLE_FEATURE_ASSUME_UNICODE
1091 char tbuf[MAX_LINELEN];
1092 save_string(tbuf, sizeof(tbuf));
1093 state->history[cur] = xstrdup(tbuf);
1096 state->history[cur] = xstrdup(command_ps);
1101 /* state->flags is already checked to be nonzero */
1102 static int get_previous_history(void)
1104 if ((state->flags & DO_HISTORY) && state->cur_history) {
1105 save_command_ps_at_cur_history();
1106 state->cur_history--;
1113 static int get_next_history(void)
1115 if (state->flags & DO_HISTORY) {
1116 if (state->cur_history < state->cnt_history) {
1117 save_command_ps_at_cur_history(); /* save the current history line */
1118 return ++state->cur_history;
1125 # if ENABLE_FEATURE_EDITING_SAVEHISTORY
1126 /* We try to ensure that concurrent additions to the history
1127 * do not overwrite each other.
1128 * Otherwise shell users get unhappy.
1130 * History file is trimmed lazily, when it grows several times longer
1131 * than configured MAX_HISTORY lines.
1134 static void free_line_input_t(line_input_t *n)
1136 int i = n->cnt_history;
1138 free(n->history[--i]);
1142 /* state->flags is already checked to be nonzero */
1143 static void load_history(line_input_t *st_parm)
1145 char *temp_h[MAX_HISTORY];
1148 unsigned idx, i, line_len;
1150 /* NB: do not trash old history if file can't be opened */
1152 fp = fopen_for_read(st_parm->hist_file);
1154 /* clean up old history */
1155 for (idx = st_parm->cnt_history; idx > 0;) {
1157 free(st_parm->history[idx]);
1158 st_parm->history[idx] = NULL;
1161 /* fill temp_h[], retaining only last MAX_HISTORY lines */
1162 memset(temp_h, 0, sizeof(temp_h));
1163 st_parm->cnt_history_in_file = idx = 0;
1164 while ((line = xmalloc_fgetline(fp)) != NULL) {
1165 if (line[0] == '\0') {
1171 st_parm->cnt_history_in_file++;
1173 if (idx == MAX_HISTORY)
1178 /* find first non-NULL temp_h[], if any */
1179 if (st_parm->cnt_history_in_file) {
1180 while (temp_h[idx] == NULL) {
1182 if (idx == MAX_HISTORY)
1187 /* copy temp_h[] to st_parm->history[] */
1188 for (i = 0; i < MAX_HISTORY;) {
1193 if (idx == MAX_HISTORY)
1195 line_len = strlen(line);
1196 if (line_len >= MAX_LINELEN)
1197 line[MAX_LINELEN-1] = '\0';
1198 st_parm->history[i++] = line;
1200 st_parm->cnt_history = i;
1204 /* state->flags is already checked to be nonzero */
1205 static void save_history(char *str)
1210 fd = open(state->hist_file, O_WRONLY | O_CREAT | O_APPEND, 0666);
1213 xlseek(fd, 0, SEEK_END); /* paranoia */
1215 str[len] = '\n'; /* we (try to) do atomic write */
1216 len2 = full_write(fd, str, len + 1);
1219 if (len2 != len + 1)
1220 return; /* "wtf?" */
1222 /* did we write so much that history file needs trimming? */
1223 state->cnt_history_in_file++;
1224 if (state->cnt_history_in_file > MAX_HISTORY * 4) {
1227 line_input_t *st_temp;
1230 /* we may have concurrently written entries from others.
1232 st_temp = new_line_input_t(state->flags);
1233 st_temp->hist_file = state->hist_file;
1234 load_history(st_temp);
1236 /* write out temp file and replace hist_file atomically */
1237 new_name = xasprintf("%s.%u.new", state->hist_file, (int) getpid());
1238 fp = fopen_for_write(new_name);
1240 for (i = 0; i < st_temp->cnt_history; i++)
1241 fprintf(fp, "%s\n", st_temp->history[i]);
1243 if (rename(new_name, state->hist_file) == 0)
1244 state->cnt_history_in_file = st_temp->cnt_history;
1247 free_line_input_t(st_temp);
1251 # define load_history(a) ((void)0)
1252 # define save_history(a) ((void)0)
1253 # endif /* FEATURE_COMMAND_SAVEHISTORY */
1255 static void remember_in_history(char *str)
1259 if (!(state->flags & DO_HISTORY))
1263 i = state->cnt_history;
1264 /* Don't save dupes */
1265 if (i && strcmp(state->history[i-1], str) == 0)
1268 free(state->history[MAX_HISTORY]); /* redundant, paranoia */
1269 state->history[MAX_HISTORY] = NULL; /* redundant, paranoia */
1271 /* If history[] is full, remove the oldest command */
1272 /* we need to keep history[MAX_HISTORY] empty, hence >=, not > */
1273 if (i >= MAX_HISTORY) {
1274 free(state->history[0]);
1275 for (i = 0; i < MAX_HISTORY-1; i++)
1276 state->history[i] = state->history[i+1];
1277 /* i == MAX_HISTORY-1 */
1279 /* i <= MAX_HISTORY-1 */
1280 state->history[i++] = xstrdup(str);
1281 /* i <= MAX_HISTORY */
1282 state->cur_history = i;
1283 state->cnt_history = i;
1284 # if MAX_HISTORY > 0 && ENABLE_FEATURE_EDITING_SAVEHISTORY
1285 if ((state->flags & SAVE_HISTORY) && state->hist_file)
1288 IF_FEATURE_EDITING_FANCY_PROMPT(num_ok_lines++;)
1291 #else /* MAX_HISTORY == 0 */
1292 # define remember_in_history(a) ((void)0)
1293 #endif /* MAX_HISTORY */
1296 #if ENABLE_FEATURE_EDITING_VI
1298 * vi mode implemented 2005 by Paul Fox <pgf@foxharp.boston.ma.us>
1301 vi_Word_motion(int eat)
1303 CHAR_T *command = command_ps;
1305 while (cursor < command_len && !BB_isspace(command[cursor]))
1307 if (eat) while (cursor < command_len && BB_isspace(command[cursor]))
1312 vi_word_motion(int eat)
1314 CHAR_T *command = command_ps;
1316 if (BB_isalnum(command[cursor]) || command[cursor] == '_') {
1317 while (cursor < command_len
1318 && (BB_isalnum(command[cursor+1]) || command[cursor+1] == '_')
1322 } else if (BB_ispunct(command[cursor])) {
1323 while (cursor < command_len && BB_ispunct(command[cursor+1]))
1327 if (cursor < command_len)
1331 while (cursor < command_len && BB_isspace(command[cursor]))
1339 CHAR_T *command = command_ps;
1342 while (cursor < command_len && BB_isspace(command[cursor]))
1344 while (cursor < command_len-1 && !BB_isspace(command[cursor+1]))
1351 CHAR_T *command = command_ps;
1353 if (cursor >= command_len-1)
1356 while (cursor < command_len-1 && BB_isspace(command[cursor]))
1358 if (cursor >= command_len-1)
1360 if (BB_isalnum(command[cursor]) || command[cursor] == '_') {
1361 while (cursor < command_len-1
1362 && (BB_isalnum(command[cursor+1]) || command[cursor+1] == '_')
1366 } else if (BB_ispunct(command[cursor])) {
1367 while (cursor < command_len-1 && BB_ispunct(command[cursor+1]))
1373 vi_Back_motion(void)
1375 CHAR_T *command = command_ps;
1377 while (cursor > 0 && BB_isspace(command[cursor-1]))
1379 while (cursor > 0 && !BB_isspace(command[cursor-1]))
1384 vi_back_motion(void)
1386 CHAR_T *command = command_ps;
1391 while (cursor > 0 && BB_isspace(command[cursor]))
1395 if (BB_isalnum(command[cursor]) || command[cursor] == '_') {
1397 && (BB_isalnum(command[cursor-1]) || command[cursor-1] == '_')
1401 } else if (BB_ispunct(command[cursor])) {
1402 while (cursor > 0 && BB_ispunct(command[cursor-1]))
1408 /* Modelled after bash 4.0 behavior of Ctrl-<arrow> */
1409 static void ctrl_left(void)
1411 CHAR_T *command = command_ps;
1419 c = command[cursor];
1420 if (c != ' ' && !BB_ispunct(c)) {
1421 /* we reached a "word" delimited by spaces/punct.
1422 * go to its beginning */
1424 c = command[cursor - 1];
1425 if (c == ' ' || BB_ispunct(c))
1435 static void ctrl_right(void)
1437 CHAR_T *command = command_ps;
1442 c = command[cursor];
1445 if (c != ' ' && !BB_ispunct(c)) {
1446 /* we reached a "word" delimited by spaces/punct.
1447 * go to its end + 1 */
1450 c = command[cursor];
1451 if (c == BB_NUL || c == ' ' || BB_ispunct(c))
1462 * read_line_input and its helpers
1465 #if ENABLE_FEATURE_EDITING_ASK_TERMINAL
1466 static void ask_terminal(void)
1468 /* Ask terminal where is the cursor now.
1469 * lineedit_read_key handles response and corrects
1470 * our idea of current cursor position.
1471 * Testcase: run "echo -n long_line_long_line_long_line",
1472 * then type in a long, wrapping command and try to
1473 * delete it using backspace key.
1474 * Note: we print it _after_ prompt, because
1475 * prompt may contain CR. Example: PS1='\[\r\n\]\w '
1477 /* Problem: if there is buffered input on stdin,
1478 * the response will be delivered later,
1479 * possibly to an unsuspecting application.
1480 * Testcase: "sleep 1; busybox ash" + press and hold [Enter].
1482 * ~/srcdevel/bbox/fix/busybox.t4 #
1483 * ~/srcdevel/bbox/fix/busybox.t4 #
1484 * ^[[59;34~/srcdevel/bbox/fix/busybox.t4 # <-- garbage
1485 * ~/srcdevel/bbox/fix/busybox.t4 #
1487 * Checking for input with poll only makes the race narrower,
1488 * I still can trigger it. Strace:
1490 * write(1, "~/srcdevel/bbox/fix/busybox.t4 # ", 33) = 33
1491 * poll([{fd=0, events=POLLIN}], 1, 0) = 0 (Timeout) <-- no input exists
1492 * write(1, "\33[6n", 4) = 4 <-- send the ESC sequence, quick!
1493 * poll([{fd=0, events=POLLIN}], 1, 4294967295) = 1 ([{fd=0, revents=POLLIN}])
1494 * read(0, "\n", 1) = 1 <-- oh crap, user's input got in first
1498 pfd.fd = STDIN_FILENO;
1499 pfd.events = POLLIN;
1500 if (safe_poll(&pfd, 1, 0) == 0) {
1501 S.sent_ESC_br6n = 1;
1502 out1str("\033" "[6n");
1503 fflush_all(); /* make terminal see it ASAP! */
1507 #define ask_terminal() ((void)0)
1510 #if !ENABLE_FEATURE_EDITING_FANCY_PROMPT
1511 static void parse_and_put_prompt(const char *prmt_ptr)
1513 cmdedit_prompt = prmt_ptr;
1514 cmdedit_prmt_len = strlen(prmt_ptr);
1518 static void parse_and_put_prompt(const char *prmt_ptr)
1521 size_t cur_prmt_len = 0;
1522 char flg_not_length = '[';
1523 char *prmt_mem_ptr = xzalloc(1);
1524 char *cwd_buf = xrealloc_getcwd_or_warn(NULL);
1529 cmdedit_prmt_len = 0;
1532 cwd_buf = (char *)bb_msg_unknown;
1535 cbuf[1] = '\0'; /* never changes */
1538 char *free_me = NULL;
1543 const char *cp = prmt_ptr;
1546 c = bb_process_escape_sequence(&prmt_ptr);
1547 if (prmt_ptr == cp) {
1553 # if ENABLE_FEATURE_GETUSERNAME_AND_HOMEDIR
1555 pbuf = user_buf ? user_buf : (char*)"";
1559 pbuf = free_me = safe_gethostname();
1560 *strchrnul(pbuf, '.') = '\0';
1563 c = (geteuid() == 0 ? '#' : '$');
1565 # if ENABLE_FEATURE_GETUSERNAME_AND_HOMEDIR
1567 /* /home/user[/something] -> ~[/something] */
1569 l = strlen(home_pwd_buf);
1571 && strncmp(home_pwd_buf, cwd_buf, l) == 0
1572 && (cwd_buf[l]=='/' || cwd_buf[l]=='\0')
1573 && strlen(cwd_buf + l) < PATH_MAX
1575 pbuf = free_me = xasprintf("~%s", cwd_buf + l);
1581 cp = strrchr(pbuf, '/');
1582 if (cp != NULL && cp != pbuf)
1583 pbuf += (cp-pbuf) + 1;
1586 pbuf = free_me = xasprintf("%d", num_ok_lines);
1588 case 'e': case 'E': /* \e \E = \033 */
1591 case 'x': case 'X': {
1593 for (l = 0; l < 3;) {
1595 buf2[l++] = *prmt_ptr;
1597 h = strtoul(buf2, &pbuf, 16);
1598 if (h > UCHAR_MAX || (pbuf - buf2) < l) {
1604 c = (char)strtoul(buf2, NULL, 16);
1611 if (c == flg_not_length) {
1612 flg_not_length = (flg_not_length == '[' ? ']' : '[');
1620 cur_prmt_len = strlen(pbuf);
1621 prmt_len += cur_prmt_len;
1622 if (flg_not_length != ']')
1623 cmdedit_prmt_len += cur_prmt_len;
1624 prmt_mem_ptr = strcat(xrealloc(prmt_mem_ptr, prmt_len+1), pbuf);
1628 if (cwd_buf != (char *)bb_msg_unknown)
1630 cmdedit_prompt = prmt_mem_ptr;
1635 static void cmdedit_setwidth(unsigned w, int redraw_flg)
1639 /* new y for current cursor */
1640 int new_y = (cursor + cmdedit_prmt_len) / w;
1642 redraw((new_y >= cmdedit_y ? new_y : cmdedit_y), command_len - cursor);
1647 static void win_changed(int nsig)
1650 get_terminal_width_height(0, &width, NULL);
1651 cmdedit_setwidth(width, nsig /* - just a yes/no flag */);
1652 if (nsig == SIGWINCH)
1653 signal(SIGWINCH, win_changed); /* rearm ourself */
1656 static int lineedit_read_key(char *read_key_buffer)
1661 #if ENABLE_FEATURE_ASSUME_UNICODE
1662 char unicode_buf[MB_CUR_MAX + 1];
1663 int unicode_idx = 0;
1666 pfd.fd = STDIN_FILENO;
1667 pfd.events = POLLIN;
1669 #if ENABLE_FEATURE_EDITING_ASK_TERMINAL || ENABLE_FEATURE_ASSUME_UNICODE
1672 if (read_key_buffer[0] == 0) {
1673 /* Wait for input. Can't just call read_key,
1674 * it returns at once if stdin
1675 * is in non-blocking mode. */
1676 safe_poll(&pfd, 1, delay);
1678 /* Note: read_key sets errno to 0 on success: */
1679 ic = read_key(STDIN_FILENO, read_key_buffer);
1681 #if ENABLE_FEATURE_EDITING_ASK_TERMINAL
1682 if ((int32_t)ic == KEYCODE_CURSOR_POS
1685 S.sent_ESC_br6n = 0;
1686 if (cursor == 0) { /* otherwise it may be bogus */
1687 int col = ((ic >> 32) & 0x7fff) - 1;
1688 if (col > cmdedit_prmt_len) {
1689 cmdedit_x += (col - cmdedit_prmt_len);
1690 while (cmdedit_x >= cmdedit_termw) {
1691 cmdedit_x -= cmdedit_termw;
1700 #if ENABLE_FEATURE_ASSUME_UNICODE
1704 if ((int32_t)ic < 0) /* KEYCODE_xxx */
1706 unicode_buf[unicode_idx++] = ic;
1707 unicode_buf[unicode_idx] = '\0';
1708 if (mbstowcs(&wc, unicode_buf, 1) != 1 && unicode_idx < MB_CUR_MAX) {
1715 } while (errno == EAGAIN);
1720 /* leave out the "vi-mode"-only case labels if vi editing isn't
1722 #define vi_case(caselabel) IF_FEATURE_EDITING_VI(case caselabel)
1724 /* convert uppercase ascii to equivalent control char, for readability */
1726 #define CTRL(a) ((a) & ~0x40)
1728 /* maxsize must be >= 2.
1730 * -1 on read errors or EOF, or on bare Ctrl-D,
1731 * 0 on ctrl-C (the line entered is still returned in 'command'),
1732 * >0 length of input string, including terminating '\n'
1734 int FAST_FUNC read_line_input(const char *prompt, char *command, int maxsize, line_input_t *st)
1737 #if ENABLE_FEATURE_TAB_COMPLETION
1738 smallint lastWasTab = FALSE;
1740 smallint break_out = 0;
1741 #if ENABLE_FEATURE_EDITING_VI
1742 smallint vi_cmdmode = 0;
1744 struct termios initial_settings;
1745 struct termios new_settings;
1746 char read_key_buffer[KEYCODE_BUFFER_SIZE];
1750 if (tcgetattr(STDIN_FILENO, &initial_settings) < 0
1751 || !(initial_settings.c_lflag & ECHO)
1753 /* Happens when e.g. stty -echo was run before */
1754 parse_and_put_prompt(prompt);
1755 /* fflush_all(); - done by parse_and_put_prompt */
1756 if (fgets(command, maxsize, stdin) == NULL)
1757 len = -1; /* EOF or error */
1759 len = strlen(command);
1764 check_unicode_in_env();
1766 // FIXME: audit & improve this
1767 if (maxsize > MAX_LINELEN)
1768 maxsize = MAX_LINELEN;
1769 S.maxsize = maxsize;
1771 /* With null flags, no other fields are ever used */
1772 state = st ? st : (line_input_t*) &const_int_0;
1774 # if ENABLE_FEATURE_EDITING_SAVEHISTORY
1775 if ((state->flags & SAVE_HISTORY) && state->hist_file)
1776 if (state->cnt_history == 0)
1777 load_history(state);
1779 if (state->flags & DO_HISTORY)
1780 state->cur_history = state->cnt_history;
1783 /* prepare before init handlers */
1784 cmdedit_y = 0; /* quasireal y, not true if line > xt*yt */
1786 #if ENABLE_FEATURE_ASSUME_UNICODE
1787 command_ps = xzalloc(maxsize * sizeof(command_ps[0]));
1789 command_ps = command;
1792 #define command command_must_not_be_used
1794 new_settings = initial_settings;
1795 new_settings.c_lflag &= ~ICANON; /* unbuffered input */
1796 /* Turn off echoing and CTRL-C, so we can trap it */
1797 new_settings.c_lflag &= ~(ECHO | ECHONL | ISIG);
1798 /* Hmm, in linux c_cc[] is not parsed if ICANON is off */
1799 new_settings.c_cc[VMIN] = 1;
1800 new_settings.c_cc[VTIME] = 0;
1801 /* Turn off CTRL-C, so we can trap it */
1802 #ifndef _POSIX_VDISABLE
1803 # define _POSIX_VDISABLE '\0'
1805 new_settings.c_cc[VINTR] = _POSIX_VDISABLE;
1806 tcsetattr_stdin_TCSANOW(&new_settings);
1808 /* Now initialize things */
1809 previous_SIGWINCH_handler = signal(SIGWINCH, win_changed);
1810 win_changed(0); /* do initial resizing */
1811 #if ENABLE_FEATURE_GETUSERNAME_AND_HOMEDIR
1813 struct passwd *entry;
1815 entry = getpwuid(geteuid());
1817 user_buf = xstrdup(entry->pw_name);
1818 home_pwd_buf = xstrdup(entry->pw_dir);
1824 for (i = 0; i <= MAX_HISTORY; i++)
1825 bb_error_msg("history[%d]:'%s'", i, state->history[i]);
1826 bb_error_msg("cur_history:%d cnt_history:%d", state->cur_history, state->cnt_history);
1829 /* Print out the command prompt, optionally ask where cursor is */
1830 parse_and_put_prompt(prompt);
1833 read_key_buffer[0] = 0;
1836 * The emacs and vi modes share much of the code in the big
1837 * command loop. Commands entered when in vi's command mode
1838 * (aka "escape mode") get an extra bit added to distinguish
1839 * them - this keeps them from being self-inserted. This
1840 * clutters the big switch a bit, but keeps all the code
1844 VI_CMDMODE_BIT = 0x40000000,
1845 /* 0x80000000 bit flags KEYCODE_xxx */
1850 ic = ic_raw = lineedit_read_key(read_key_buffer);
1852 #if ENABLE_FEATURE_EDITING_VI
1855 /* btw, since KEYCODE_xxx are all < 0, this doesn't
1856 * change ic if it contains one of them: */
1857 ic |= VI_CMDMODE_BIT;
1864 vi_case('\n'|VI_CMDMODE_BIT:)
1865 vi_case('\r'|VI_CMDMODE_BIT:)
1871 vi_case('0'|VI_CMDMODE_BIT:)
1872 /* Control-a -- Beginning of line */
1873 input_backward(cursor);
1876 vi_case('h'|VI_CMDMODE_BIT:)
1877 vi_case('\b'|VI_CMDMODE_BIT:)
1878 vi_case('\x7f'|VI_CMDMODE_BIT:) /* DEL */
1879 /* Control-b -- Move back one character */
1883 vi_case('$'|VI_CMDMODE_BIT:)
1884 /* Control-e -- End of line */
1888 vi_case('l'|VI_CMDMODE_BIT:)
1889 vi_case(' '|VI_CMDMODE_BIT:)
1890 /* Control-f -- Move forward one character */
1894 case '\x7f': /* DEL */
1895 /* Control-h and DEL */
1898 #if ENABLE_FEATURE_TAB_COMPLETION
1900 input_tab(&lastWasTab);
1904 /* Control-k -- clear to end of line */
1905 command_ps[cursor] = BB_NUL;
1906 command_len = cursor;
1910 vi_case(CTRL('L')|VI_CMDMODE_BIT:)
1911 /* Control-l -- clear screen */
1913 redraw(0, command_len - cursor);
1917 vi_case(CTRL('N')|VI_CMDMODE_BIT:)
1918 vi_case('j'|VI_CMDMODE_BIT:)
1919 /* Control-n -- Get next command in history */
1920 if (get_next_history())
1924 vi_case(CTRL('P')|VI_CMDMODE_BIT:)
1925 vi_case('k'|VI_CMDMODE_BIT:)
1926 /* Control-p -- Get previous command from history */
1927 if (get_previous_history())
1932 vi_case(CTRL('U')|VI_CMDMODE_BIT:)
1933 /* Control-U -- Clear line before cursor */
1935 command_len -= cursor;
1936 memmove(command_ps, command_ps + cursor,
1937 (command_len + 1) * sizeof(command_ps[0]));
1938 redraw(cmdedit_y, command_len);
1942 vi_case(CTRL('W')|VI_CMDMODE_BIT:)
1943 /* Control-W -- Remove the last word */
1944 while (cursor > 0 && BB_isspace(command_ps[cursor-1]))
1946 while (cursor > 0 && !BB_isspace(command_ps[cursor-1]))
1950 #if ENABLE_FEATURE_EDITING_VI
1951 case 'i'|VI_CMDMODE_BIT:
1954 case 'I'|VI_CMDMODE_BIT:
1955 input_backward(cursor);
1958 case 'a'|VI_CMDMODE_BIT:
1962 case 'A'|VI_CMDMODE_BIT:
1966 case 'x'|VI_CMDMODE_BIT:
1969 case 'X'|VI_CMDMODE_BIT:
1975 case 'W'|VI_CMDMODE_BIT:
1978 case 'w'|VI_CMDMODE_BIT:
1981 case 'E'|VI_CMDMODE_BIT:
1984 case 'e'|VI_CMDMODE_BIT:
1987 case 'B'|VI_CMDMODE_BIT:
1990 case 'b'|VI_CMDMODE_BIT:
1993 case 'C'|VI_CMDMODE_BIT:
1996 case 'D'|VI_CMDMODE_BIT:
1999 case 'c'|VI_CMDMODE_BIT:
2002 case 'd'|VI_CMDMODE_BIT: {
2005 ic = lineedit_read_key(read_key_buffer);
2006 if (errno) /* error */
2007 goto prepare_to_die;
2008 if (ic == ic_raw) { /* "cc", "dd" */
2009 input_backward(cursor);
2021 case 'w': /* "dw", "cw" */
2022 vi_word_motion(vi_cmdmode);
2024 case 'W': /* 'dW', 'cW' */
2025 vi_Word_motion(vi_cmdmode);
2027 case 'e': /* 'de', 'ce' */
2031 case 'E': /* 'dE', 'cE' */
2037 input_backward(cursor - sc);
2038 while (nc-- > cursor)
2041 case 'b': /* "db", "cb" */
2042 case 'B': /* implemented as B */
2047 while (sc-- > cursor)
2050 case ' ': /* "d ", "c " */
2053 case '$': /* "d$", "c$" */
2055 while (cursor < command_len)
2061 case 'p'|VI_CMDMODE_BIT:
2064 case 'P'|VI_CMDMODE_BIT:
2067 case 'r'|VI_CMDMODE_BIT:
2068 //FIXME: unicode case?
2069 ic = lineedit_read_key(read_key_buffer);
2070 if (errno) /* error */
2071 goto prepare_to_die;
2072 if (ic < ' ' || ic > 255) {
2075 command_ps[cursor] = ic;
2080 case '\x1b': /* ESC */
2081 if (state->flags & VI_MODE) {
2082 /* insert mode --> command mode */
2087 #endif /* FEATURE_COMMAND_EDITING_VI */
2091 if (get_previous_history())
2096 if (!get_next_history())
2099 /* Rewrite the line with the selected history item */
2100 /* change command */
2101 command_len = load_string(state->history[state->cur_history] ?
2102 state->history[state->cur_history] : "", maxsize);
2103 /* redraw and go to eol (bol, in vi) */
2104 redraw(cmdedit_y, (state->flags & VI_MODE) ? 9999 : 0);
2113 case KEYCODE_CTRL_LEFT:
2116 case KEYCODE_CTRL_RIGHT:
2119 case KEYCODE_DELETE:
2123 input_backward(cursor);
2130 if (initial_settings.c_cc[VINTR] != 0
2131 && ic_raw == initial_settings.c_cc[VINTR]
2133 /* Ctrl-C (usually) - stop gathering input */
2136 break_out = -1; /* "do not append '\n'" */
2139 if (initial_settings.c_cc[VEOF] != 0
2140 && ic_raw == initial_settings.c_cc[VEOF]
2142 /* Ctrl-D (usually) - delete one character,
2143 * or exit if len=0 and no chars to delete */
2144 if (command_len == 0) {
2146 #if ENABLE_FEATURE_EDITING_VI
2149 break_out = command_len = -1;
2155 // /* Control-V -- force insert of next char */
2156 // if (c == CTRL('V')) {
2157 // if (safe_read(STDIN_FILENO, &c, 1) < 1)
2158 // goto prepare_to_die;
2165 || (!ENABLE_FEATURE_ASSUME_UNICODE && ic >= 256)
2166 || (ENABLE_FEATURE_ASSUME_UNICODE && ic >= VI_CMDMODE_BIT)
2168 /* If VI_CMDMODE_BIT is set, ic is >= 256
2169 * and vi mode ignores unexpected chars.
2170 * Otherwise, we are here if ic is a
2171 * control char or an unhandled ESC sequence,
2172 * which is also ignored.
2176 if ((int)command_len >= (maxsize - 2)) {
2177 /* Not enough space for the char and EOL */
2182 if (cursor == (command_len - 1)) {
2183 /* We are at the end, append */
2184 command_ps[cursor] = ic;
2185 command_ps[cursor + 1] = BB_NUL;
2186 cmdedit_set_out_char(' ');
2188 /* In the middle, insert */
2191 memmove(command_ps + sc + 1, command_ps + sc,
2192 (command_len - sc) * sizeof(command_ps[0]));
2193 command_ps[sc] = ic;
2195 /* rewrite from cursor */
2197 /* to prev x pos + 1 */
2198 input_backward(cursor - sc);
2206 #if ENABLE_FEATURE_TAB_COMPLETION
2212 #if ENABLE_FEATURE_EDITING_ASK_TERMINAL
2213 if (S.sent_ESC_br6n) {
2214 /* "sleep 1; busybox ash" + hold [Enter] to trigger.
2215 * We sent "ESC [ 6 n", but got '\n' first, and
2216 * KEYCODE_CURSOR_POS response is now buffered from terminal.
2217 * It's bad already and not much can be done with it
2218 * (it _will_ be visible for the next process to read stdin),
2219 * but without this delay it even shows up on the screen
2220 * as garbage because we restore echo settings with tcsetattr
2221 * before it comes in. UGLY!
2227 /* Stop bug catching using "command_must_not_be_used" trick */
2230 #if ENABLE_FEATURE_ASSUME_UNICODE
2232 if (command_len > 0)
2233 command_len = save_string(command, maxsize - 1);
2237 if (command_len > 0)
2238 remember_in_history(command);
2240 if (break_out > 0) {
2241 command[command_len++] = '\n';
2242 command[command_len] = '\0';
2245 #if ENABLE_FEATURE_TAB_COMPLETION
2246 free_tab_completion_data();
2249 /* restore initial_settings */
2250 tcsetattr_stdin_TCSANOW(&initial_settings);
2251 /* restore SIGWINCH handler */
2252 signal(SIGWINCH, previous_SIGWINCH_handler);
2258 return len; /* can't return command_len, DEINIT_S() destroys it */
2263 #undef read_line_input
2264 int FAST_FUNC read_line_input(const char* prompt, char* command, int maxsize)
2266 fputs(prompt, stdout);
2268 fgets(command, maxsize, stdin);
2269 return strlen(command);
2272 #endif /* FEATURE_EDITING */
2283 const char *applet_name = "debug stuff usage";
2285 int main(int argc, char **argv)
2287 char buff[MAX_LINELEN];
2289 #if ENABLE_FEATURE_EDITING_FANCY_PROMPT
2290 "\\[\\033[32;1m\\]\\u@\\[\\x1b[33;1m\\]\\h:"
2291 "\\[\\033[34;1m\\]\\w\\[\\033[35;1m\\] "
2292 "\\!\\[\\e[36;1m\\]\\$ \\[\\E[0m\\]";
2297 #if ENABLE_FEATURE_NONPRINTABLE_INVERSE_PUT
2298 setlocale(LC_ALL, "");
2302 l = read_line_input(prompt, buff);
2303 if (l <= 0 || buff[l-1] != '\n')
2306 printf("*** read_line_input() returned line =%s=\n", buff);
2308 printf("*** read_line_input() detect ^D\n");