1 /* vi: set sw=4 ts=4: */
3 * Command line 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\] '
44 #ifndef _POSIX_VDISABLE
45 # define _POSIX_VDISABLE '\0'
50 # define ENABLE_FEATURE_EDITING 0
51 # define ENABLE_FEATURE_TAB_COMPLETION 0
52 # define ENABLE_FEATURE_USERNAME_COMPLETION 0
56 /* Entire file (except TESTing part) sits inside this #if */
57 #if ENABLE_FEATURE_EDITING
60 #define ENABLE_USERNAME_OR_HOMEDIR \
61 (ENABLE_FEATURE_USERNAME_COMPLETION || ENABLE_FEATURE_EDITING_FANCY_PROMPT)
62 #define IF_USERNAME_OR_HOMEDIR(...)
63 #if ENABLE_USERNAME_OR_HOMEDIR
64 # undef IF_USERNAME_OR_HOMEDIR
65 # define IF_USERNAME_OR_HOMEDIR(...) __VA_ARGS__
70 #if ENABLE_UNICODE_SUPPORT
71 # define BB_NUL ((wchar_t)0)
72 # define CHAR_T wchar_t
73 static bool BB_isspace(CHAR_T c) { return ((unsigned)c < 256 && isspace(c)); }
74 # if ENABLE_FEATURE_EDITING_VI
75 static bool BB_isalnum(CHAR_T c) { return ((unsigned)c < 256 && isalnum(c)); }
77 static bool BB_ispunct(CHAR_T c) { return ((unsigned)c < 256 && ispunct(c)); }
82 # define isspace isspace_must_not_be_used
83 # define isalnum isalnum_must_not_be_used
84 # define ispunct ispunct_must_not_be_used
85 # define isprint isprint_must_not_be_used
89 # define BB_isspace(c) isspace(c)
90 # define BB_isalnum(c) isalnum(c)
91 # define BB_ispunct(c) ispunct(c)
93 #if ENABLE_UNICODE_PRESERVE_BROKEN
94 # define unicode_mark_raw_byte(wc) ((wc) | 0x20000000)
95 # define unicode_is_raw_byte(wc) ((wc) & 0x20000000)
97 # define unicode_is_raw_byte(wc) 0
103 #define SEQ_CLEAR_TILL_END_OF_SCREEN ESC"[J"
104 //#define SEQ_CLEAR_TILL_END_OF_LINE ESC"[K"
108 MAX_LINELEN = CONFIG_FEATURE_EDITING_MAX_LEN < 0x7ff0
109 ? CONFIG_FEATURE_EDITING_MAX_LEN
113 #if ENABLE_USERNAME_OR_HOMEDIR
114 static const char null_str[] ALIGN1 = "";
117 /* We try to minimize both static and stack usage. */
118 struct lineedit_statics {
121 volatile unsigned cmdedit_termw; /* = 80; */ /* actual terminal width */
122 sighandler_t previous_SIGWINCH_handler;
124 unsigned cmdedit_x; /* real x (col) terminal position */
125 unsigned cmdedit_y; /* pseudoreal y (row) terminal position */
126 unsigned cmdedit_prmt_len; /* length of prompt (without colors etc) */
129 int command_len; /* must be signed */
130 /* signed maxsize: we want x in "if (x > S.maxsize)"
131 * to _not_ be promoted to unsigned */
135 const char *cmdedit_prompt;
137 #if ENABLE_USERNAME_OR_HOMEDIR
139 char *home_pwd_buf; /* = (char*)null_str; */
142 #if ENABLE_FEATURE_TAB_COMPLETION
144 unsigned num_matches;
147 #if ENABLE_FEATURE_EDITING_VI
148 # define DELBUFSIZ 128
150 smallint newdelflag; /* whether delbuf should be reused yet */
151 CHAR_T delbuf[DELBUFSIZ]; /* a place to store deleted characters */
153 #if ENABLE_FEATURE_EDITING_ASK_TERMINAL
154 smallint sent_ESC_br6n;
158 /* See lineedit_ptr_hack.c */
159 extern struct lineedit_statics *const lineedit_ptr_to_statics;
161 #define S (*lineedit_ptr_to_statics)
162 #define state (S.state )
163 #define cmdedit_termw (S.cmdedit_termw )
164 #define previous_SIGWINCH_handler (S.previous_SIGWINCH_handler)
165 #define cmdedit_x (S.cmdedit_x )
166 #define cmdedit_y (S.cmdedit_y )
167 #define cmdedit_prmt_len (S.cmdedit_prmt_len)
168 #define cursor (S.cursor )
169 #define command_len (S.command_len )
170 #define command_ps (S.command_ps )
171 #define cmdedit_prompt (S.cmdedit_prompt )
172 #define user_buf (S.user_buf )
173 #define home_pwd_buf (S.home_pwd_buf )
174 #define matches (S.matches )
175 #define num_matches (S.num_matches )
176 #define delptr (S.delptr )
177 #define newdelflag (S.newdelflag )
178 #define delbuf (S.delbuf )
180 #define INIT_S() do { \
181 (*(struct lineedit_statics**)&lineedit_ptr_to_statics) = xzalloc(sizeof(S)); \
183 cmdedit_termw = 80; \
184 IF_USERNAME_OR_HOMEDIR(home_pwd_buf = (char*)null_str;) \
185 IF_FEATURE_EDITING_VI(delptr = delbuf;) \
188 static void deinit_S(void)
190 #if ENABLE_FEATURE_EDITING_FANCY_PROMPT
191 /* This one is allocated only if FANCY_PROMPT is on
192 * (otherwise it points to verbatim prompt (NOT malloced)) */
193 free((char*)cmdedit_prompt);
195 #if ENABLE_USERNAME_OR_HOMEDIR
197 if (home_pwd_buf != null_str)
200 free(lineedit_ptr_to_statics);
202 #define DEINIT_S() deinit_S()
205 #if ENABLE_UNICODE_SUPPORT
206 static size_t load_string(const char *src)
208 if (unicode_status == UNICODE_ON) {
209 ssize_t len = mbstowcs(command_ps, src, S.maxsize - 1);
212 command_ps[len] = BB_NUL;
216 while (src[i] && i < S.maxsize - 1) {
217 command_ps[i] = src[i];
220 command_ps[i] = BB_NUL;
224 static unsigned save_string(char *dst, unsigned maxsize)
226 if (unicode_status == UNICODE_ON) {
227 # if !ENABLE_UNICODE_PRESERVE_BROKEN
228 ssize_t len = wcstombs(dst, command_ps, maxsize - 1);
238 while (dstpos < maxsize) {
242 /* Convert up to 1st invalid byte (or up to end) */
243 while ((wc = command_ps[srcpos]) != BB_NUL
244 && !unicode_is_raw_byte(wc)
248 command_ps[srcpos] = BB_NUL;
249 n = wcstombs(dst + dstpos, command_ps + n, maxsize - dstpos);
250 if (n < 0) /* should not happen */
253 if (wc == BB_NUL) /* usually is */
256 /* We do have invalid byte here! */
257 command_ps[srcpos] = wc; /* restore it */
259 if (dstpos == maxsize)
261 dst[dstpos++] = (char) wc;
268 while ((dst[i] = command_ps[i]) != 0)
273 /* I thought just fputwc(c, stdout) would work. But no... */
274 static void BB_PUTCHAR(wchar_t c)
276 if (unicode_status == UNICODE_ON) {
277 char buf[MB_CUR_MAX + 1];
278 mbstate_t mbst = { 0 };
279 ssize_t len = wcrtomb(buf, c, &mbst);
285 /* In this case, c is always one byte */
289 # if ENABLE_UNICODE_COMBINING_WCHARS || ENABLE_UNICODE_WIDE_WCHARS
290 static wchar_t adjust_width_and_validate_wc(unsigned *width_adj, wchar_t wc)
292 static wchar_t adjust_width_and_validate_wc(wchar_t wc)
293 # define adjust_width_and_validate_wc(width_adj, wc) \
294 ((*(width_adj))++, adjust_width_and_validate_wc(wc))
299 if (unicode_status == UNICODE_ON) {
300 if (wc > CONFIG_LAST_SUPPORTED_WCHAR) {
301 /* note: also true for unicode_is_raw_byte(wc) */
305 if ((ENABLE_UNICODE_COMBINING_WCHARS && w < 0)
306 || (!ENABLE_UNICODE_COMBINING_WCHARS && w <= 0)
307 || (!ENABLE_UNICODE_WIDE_WCHARS && w > 1)
311 wc = CONFIG_SUBST_WCHAR;
315 # if ENABLE_UNICODE_COMBINING_WCHARS || ENABLE_UNICODE_WIDE_WCHARS
321 static size_t load_string(const char *src)
323 safe_strncpy(command_ps, src, S.maxsize);
324 return strlen(command_ps);
326 # if ENABLE_FEATURE_TAB_COMPLETION
327 static void save_string(char *dst, unsigned maxsize)
329 safe_strncpy(dst, command_ps, maxsize);
332 # define BB_PUTCHAR(c) bb_putchar(c)
333 /* Should never be called: */
334 int adjust_width_and_validate_wc(unsigned *width_adj, int wc);
338 /* Put 'command_ps[cursor]', cursor++.
339 * Advance cursor on screen. If we reached right margin, scroll text up
340 * and remove terminal margin effect by printing 'next_char' */
341 #define HACK_FOR_WRONG_WIDTH 1
342 static void put_cur_glyph_and_inc_cursor(void)
344 CHAR_T c = command_ps[cursor];
349 /* erase character after end of input string */
352 /* advance cursor only if we aren't at the end yet */
354 if (unicode_status == UNICODE_ON) {
355 IF_UNICODE_WIDE_WCHARS(width = cmdedit_x;)
356 c = adjust_width_and_validate_wc(&cmdedit_x, c);
357 IF_UNICODE_WIDE_WCHARS(width = cmdedit_x - width;)
363 ofs_to_right = cmdedit_x - cmdedit_termw;
364 if (!ENABLE_UNICODE_WIDE_WCHARS || ofs_to_right <= 0) {
365 /* c fits on this line */
369 if (ofs_to_right >= 0) {
370 /* we go to the next line */
371 #if HACK_FOR_WRONG_WIDTH
372 /* This works better if our idea of term width is wrong
373 * and it is actually wider (often happens on serial lines).
374 * Printing CR,LF *forces* cursor to next line.
375 * OTOH if terminal width is correct AND terminal does NOT
376 * have automargin (IOW: it is moving cursor to next line
377 * by itself (which is wrong for VT-10x terminals)),
378 * this will break things: there will be one extra empty line */
379 puts("\r"); /* + implicit '\n' */
381 /* VT-10x terminals don't wrap cursor to next line when last char
382 * on the line is printed - cursor stays "over" this char.
383 * Need to print _next_ char too (first one to appear on next line)
384 * to make cursor move down to next line.
386 /* Works ok only if cmdedit_termw is correct. */
387 c = command_ps[cursor];
394 if (!ENABLE_UNICODE_WIDE_WCHARS || ofs_to_right == 0) {
396 } else { /* ofs_to_right > 0 */
397 /* wide char c didn't fit on prev line */
404 /* Move to end of line (by printing all chars till the end) */
405 static void put_till_end_and_adv_cursor(void)
407 while (cursor < command_len)
408 put_cur_glyph_and_inc_cursor();
411 /* Go to the next line */
412 static void goto_new_line(void)
414 put_till_end_and_adv_cursor();
419 static void beep(void)
424 static void put_prompt(void)
428 fputs(cmdedit_prompt, stdout);
431 w = cmdedit_termw; /* read volatile var once */
432 cmdedit_y = cmdedit_prmt_len / w; /* new quasireal y */
433 cmdedit_x = cmdedit_prmt_len % w;
436 /* Move back one character */
437 /* (optimized for slow terminals) */
438 static void input_backward(unsigned num)
446 if ((ENABLE_UNICODE_COMBINING_WCHARS || ENABLE_UNICODE_WIDE_WCHARS)
447 && unicode_status == UNICODE_ON
449 /* correct NUM to be equal to _screen_ width */
453 adjust_width_and_validate_wc(&num, command_ps[cursor + n]);
458 if (cmdedit_x >= num) {
461 /* This is longer by 5 bytes on x86.
462 * Also gets miscompiled for ARM users
463 * (busybox.net/bugs/view.php?id=2274).
464 * printf(("\b\b\b\b" + 4) - num);
472 printf(ESC"[%uD", num);
476 /* Need to go one or more lines up */
477 if (ENABLE_UNICODE_WIDE_WCHARS) {
478 /* With wide chars, it is hard to "backtrack"
479 * and reliably figure out where to put cursor.
480 * Example (<> is a wide char; # is an ordinary char, _ cursor):
484 * and user presses left arrow. num = 1, cmdedit_x = 0,
485 * We need to go up one line, and then - how do we know that
486 * we need to go *10* positions to the right? Because
490 * in this situation we need to go *11* positions to the right.
492 * A simpler thing to do is to redraw everything from the start
493 * up to new cursor position (which is already known):
496 /* go to 1st column; go up to first line */
497 printf("\r" ESC"[%uA", cmdedit_y);
500 put_prompt(); /* sets cursor to 0 */
501 while (cursor < sv_cursor)
502 put_cur_glyph_and_inc_cursor();
506 /* num = chars to go back from the beginning of current line: */
508 width = cmdedit_termw; /* read volatile var once */
509 /* num=1...w: one line up, w+1...2w: two, etc: */
510 lines_up = 1 + (num - 1) / width;
511 cmdedit_x = (width * cmdedit_y - num) % width;
512 cmdedit_y -= lines_up;
513 /* go to 1st column; go up */
514 printf("\r" ESC"[%uA", lines_up);
515 /* go to correct column.
516 * xterm, konsole, Linux VT interpret 0 as 1 below! wow.
517 * need to *make sure* we skip it if cmdedit_x == 0 */
519 printf(ESC"[%uC", cmdedit_x);
523 /* draw prompt, editor line, and clear tail */
524 static void redraw(int y, int back_cursor)
526 if (y > 0) /* up y lines */
527 printf(ESC"[%uA", y);
530 put_till_end_and_adv_cursor();
531 printf(SEQ_CLEAR_TILL_END_OF_SCREEN);
532 input_backward(back_cursor);
535 /* Delete the char in front of the cursor, optionally saving it
536 * for later putback */
537 #if !ENABLE_FEATURE_EDITING_VI
538 static void input_delete(void)
539 #define input_delete(save) input_delete()
541 static void input_delete(int save)
546 if (j == (int)command_len)
549 #if ENABLE_FEATURE_EDITING_VI
555 if ((delptr - delbuf) < DELBUFSIZ)
556 *delptr++ = command_ps[j];
560 memmove(command_ps + j, command_ps + j + 1,
561 /* (command_len + 1 [because of NUL]) - (j + 1)
562 * simplified into (command_len - j) */
563 (command_len - j) * sizeof(command_ps[0]));
565 put_till_end_and_adv_cursor();
566 /* Last char is still visible, erase it (and more) */
567 printf(SEQ_CLEAR_TILL_END_OF_SCREEN);
568 input_backward(cursor - j); /* back to old pos cursor */
571 #if ENABLE_FEATURE_EDITING_VI
572 static void put(void)
575 int j = delptr - delbuf;
580 /* open hole and then fill it */
581 memmove(command_ps + cursor + j, command_ps + cursor,
582 (command_len - cursor + 1) * sizeof(command_ps[0]));
583 memcpy(command_ps + cursor, delbuf, j * sizeof(command_ps[0]));
585 put_till_end_and_adv_cursor();
586 input_backward(cursor - ocursor - j + 1); /* at end of new text */
590 /* Delete the char in back of the cursor */
591 static void input_backspace(void)
599 /* Move forward one character */
600 static void input_forward(void)
602 if (cursor < command_len)
603 put_cur_glyph_and_inc_cursor();
606 #if ENABLE_FEATURE_TAB_COMPLETION
609 //needs to be more clever: currently it thinks that "foo\ b<TAB>
610 //matches the file named "foo bar", which is untrue.
611 //Also, perhaps "foo b<TAB> needs to complete to "foo bar" <cursor>,
612 //not "foo bar <cursor>...
614 static void free_tab_completion_data(void)
618 free(matches[--num_matches]);
624 static void add_match(char *matched)
626 matches = xrealloc_vector(matches, 4, num_matches);
627 matches[num_matches] = matched;
631 # if ENABLE_FEATURE_USERNAME_COMPLETION
632 /* Replace "~user/..." with "/homedir/...".
633 * The parameter is malloced, free it or return it
634 * unchanged if no user is matched.
636 static char *username_path_completion(char *ud)
638 struct passwd *entry;
639 char *tilde_name = ud;
643 if (*ud == '/') { /* "~/..." */
647 ud = strchr(ud, '/');
648 *ud = '\0'; /* "~user" */
649 entry = getpwnam(tilde_name + 1);
650 *ud = '/'; /* restore "~user/..." */
652 home = entry->pw_dir;
655 ud = concat_path_file(home, ud);
662 /* ~use<tab> - find all users with this prefix.
663 * Return the length of the prefix used for matching.
665 static NOINLINE unsigned complete_username(const char *ud)
667 /* Using _r function to avoid pulling in static buffers */
670 struct passwd *result;
674 userlen = strlen(ud);
677 while (!getpwent_r(&pwd, line_buff, sizeof(line_buff), &result)) {
678 /* Null usernames should result in all users as possible completions. */
679 if (/*!userlen || */ strncmp(ud, pwd.pw_name, userlen) == 0) {
680 add_match(xasprintf("~%s/", pwd.pw_name));
687 # endif /* FEATURE_USERNAME_COMPLETION */
695 static int path_parse(char ***p)
702 if (state->flags & WITH_PATH_LOOKUP)
703 pth = state->path_lookup;
705 pth = getenv("PATH");
707 /* PATH="" or PATH=":"? */
708 if (!pth || !pth[0] || LONE_CHAR(pth, ':'))
712 npth = 1; /* path component count */
714 tmp = strchr(tmp, ':');
719 break; /* :<empty> */
723 *p = res = xmalloc(npth * sizeof(res[0]));
724 res[0] = tmp = xstrdup(pth);
727 tmp = strchr(tmp, ':');
730 *tmp++ = '\0'; /* ':' -> '\0' */
732 break; /* :<empty> */
738 /* Complete command, directory or file name.
739 * Return the length of the prefix used for matching.
741 static NOINLINE unsigned complete_cmd_dir_file(const char *command, int type)
744 char **paths = path1;
752 path1[0] = (char*)".";
754 pfind = strrchr(command, '/');
756 if (type == FIND_EXE_ONLY)
757 npaths = path_parse(&paths);
760 /* point to 'l' in "..../last_component" */
762 /* dirbuf = ".../.../.../" */
763 dirbuf = xstrndup(command, pfind - command);
764 # if ENABLE_FEATURE_USERNAME_COMPLETION
765 if (dirbuf[0] == '~') /* ~/... or ~user/... */
766 dirbuf = username_path_completion(dirbuf);
770 pf_len = strlen(pfind);
772 for (i = 0; i < npaths; i++) {
778 dir = opendir(paths[i]);
780 continue; /* don't print an error */
782 while ((next = readdir(dir)) != NULL) {
784 const char *name_found = next->d_name;
786 /* .../<tab>: bash 3.2.0 shows dotfiles, but not . and .. */
787 if (!pfind[0] && DOT_OR_DOTDOT(name_found))
790 if (strncmp(name_found, pfind, pf_len) != 0)
793 found = concat_path_file(paths[i], name_found);
794 /* NB: stat() first so that we see is it a directory;
795 * but if that fails, use lstat() so that
796 * we still match dangling links */
797 if (stat(found, &st) && lstat(found, &st))
798 goto cont; /* hmm, remove in progress? */
801 len = strlen(name_found);
802 found = xrealloc(found, len + 2); /* +2: for slash and NUL */
803 strcpy(found, name_found);
805 if (S_ISDIR(st.st_mode)) {
806 /* name is a directory, add slash */
808 found[len + 1] = '\0';
810 /* skip files if looking for dirs only (example: cd) */
811 if (type == FIND_DIR_ONLY)
814 /* add it to the list */
821 } /* for every path */
823 if (paths != path1) {
824 free(paths[0]); /* allocated memory is only in first member */
832 /* build_match_prefix:
833 * On entry, match_buf contains everything up to cursor at the moment <tab>
834 * was pressed. This function looks at it, figures out what part of it
835 * constitutes the command/file/directory prefix to use for completion,
836 * and rewrites match_buf to contain only that part.
840 /* QUOT is used on elements of int_buf[], which are bytes,
841 * not Unicode chars. Therefore it works correctly even in Unicode mode.
843 #define QUOT (UCHAR_MAX+1)
844 static void remove_chunk(int16_t *int_buf, int beg, int end)
846 /* beg must be <= end */
850 while ((int_buf[beg] = int_buf[end]) != 0)
855 for (i = 0; int_buf[i]; i++)
856 bb_putchar((unsigned char)int_buf[i]);
860 /* Caller ensures that match_buf points to a malloced buffer
861 * big enough to hold strlen(match_buf)*2 + 2
863 static NOINLINE int build_match_prefix(char *match_buf)
867 int16_t *int_buf = (int16_t*)match_buf;
869 if (dbg_bmp) printf("\n%s\n", match_buf);
871 /* Copy in reverse order, since they overlap */
872 i = strlen(match_buf);
874 int_buf[i] = (unsigned char)match_buf[i];
878 /* Mark every \c as "quoted c" */
879 for (i = 0; int_buf[i]; i++) {
880 if (int_buf[i] == '\\') {
881 remove_chunk(int_buf, i, i + 1);
885 /* Quote-mark "chars" and 'chars', drop delimiters */
890 int cur = int_buf[i];
893 if (cur == '\'' || cur == '"') {
894 if (!in_quote || (cur == in_quote)) {
896 remove_chunk(int_buf, i, i + 1);
901 int_buf[i] = cur | QUOT;
906 /* Remove everything up to command delimiters:
907 * ';' ';;' '&' '|' '&&' '||',
908 * but careful with '>&' '<&' '>|'
910 for (i = 0; int_buf[i]; i++) {
911 int cur = int_buf[i];
912 if (cur == ';' || cur == '&' || cur == '|') {
913 int prev = i ? int_buf[i - 1] : 0;
914 if (cur == '&' && (prev == '>' || prev == '<')) {
916 } else if (cur == '|' && prev == '>') {
919 remove_chunk(int_buf, 0, i + 1 + (cur == int_buf[i + 1]));
920 i = -1; /* back to square 1 */
923 /* Remove all `cmd` */
924 for (i = 0; int_buf[i]; i++) {
925 if (int_buf[i] == '`') {
926 for (j = i + 1; int_buf[j]; j++) {
927 if (int_buf[j] == '`') {
928 /* `cmd` should count as a word:
929 * `cmd` c<tab> should search for files c*,
930 * not commands c*. Therefore we don't drop
931 * `cmd` entirely, we replace it with single `.
933 remove_chunk(int_buf, i, j);
937 /* No closing ` - command mode, remove all up to ` */
938 remove_chunk(int_buf, 0, i + 1);
944 /* Remove "cmd (" and "cmd {"
945 * Example: "if { c<tab>"
946 * In this example, c should be matched as command pfx.
948 for (i = 0; int_buf[i]; i++) {
949 if (int_buf[i] == '(' || int_buf[i] == '{') {
950 remove_chunk(int_buf, 0, i + 1);
951 i = -1; /* back to square 1 */
955 /* Remove leading unquoted spaces */
956 for (i = 0; int_buf[i]; i++)
957 if (int_buf[i] != ' ')
959 remove_chunk(int_buf, 0, i);
961 /* Determine completion mode */
962 command_mode = FIND_EXE_ONLY;
963 for (i = 0; int_buf[i]; i++) {
964 if (int_buf[i] == ' ' || int_buf[i] == '<' || int_buf[i] == '>') {
965 if (int_buf[i] == ' '
966 && command_mode == FIND_EXE_ONLY
967 && (char)int_buf[0] == 'c'
968 && (char)int_buf[1] == 'd'
969 && i == 2 /* -> int_buf[2] == ' ' */
971 command_mode = FIND_DIR_ONLY;
973 command_mode = FIND_FILE_ONLY;
978 if (dbg_bmp) printf("command_mode(0:exe/1:dir/2:file):%d\n", command_mode);
980 /* Remove everything except last word */
981 for (i = 0; int_buf[i]; i++) /* quasi-strlen(int_buf) */
983 for (--i; i >= 0; i--) {
984 int cur = int_buf[i];
985 if (cur == ' ' || cur == '<' || cur == '>' || cur == '|' || cur == '&') {
986 remove_chunk(int_buf, 0, i + 1);
991 /* Convert back to string of _chars_ */
993 while ((match_buf[i] = int_buf[i]) != '\0')
996 if (dbg_bmp) printf("final match_buf:'%s'\n", match_buf);
1002 * Display by column (original idea from ls applet,
1003 * very optimized by me [Vladimir] :)
1005 static void showfiles(void)
1008 int column_width = 0;
1009 int nfiles = num_matches;
1013 /* find the longest file name - use that as the column width */
1014 for (row = 0; row < nrows; row++) {
1015 l = unicode_strwidth(matches[row]);
1016 if (column_width < l)
1019 column_width += 2; /* min space for columns */
1020 ncols = cmdedit_termw / column_width;
1025 nrows++; /* round up fractionals */
1029 for (row = 0; row < nrows; row++) {
1033 for (nc = 1; nc < ncols && n+nrows < nfiles; n += nrows, nc++) {
1034 printf("%s%-*s", matches[n],
1035 (int)(column_width - unicode_strwidth(matches[n])), ""
1038 if (ENABLE_UNICODE_SUPPORT)
1039 puts(printable_string(NULL, matches[n]));
1045 static const char *is_special_char(char c)
1047 return strchr(" `\"#$%^&*()=+{}[]:;'|\\<>", c);
1050 static char *quote_special_chars(char *found)
1053 char *s = xzalloc((strlen(found) + 1) * 2);
1056 if (is_special_char(*found))
1060 /* s[l] = '\0'; - already is */
1064 /* Do TAB completion */
1065 static NOINLINE void input_tab(smallint *lastWasTab)
1070 /* Length of string used for matching */
1071 unsigned match_pfx_len = match_pfx_len;
1073 # if ENABLE_UNICODE_SUPPORT
1074 /* cursor pos in command converted to multibyte form */
1077 if (!(state->flags & TAB_COMPLETION))
1081 /* The last char was a TAB too.
1082 * Print a list of all the available choices.
1084 if (num_matches > 0) {
1085 /* cursor will be changed by goto_new_line() */
1086 int sav_cursor = cursor;
1089 redraw(0, command_len - sav_cursor);
1095 chosen_match = NULL;
1097 /* Make a local copy of the string up to the position of the cursor.
1098 * build_match_prefix will expand it into int16_t's, need to allocate
1099 * twice as much as the string_len+1.
1100 * (we then also (ab)use this extra space later - see (**))
1102 match_buf = xmalloc(MAX_LINELEN * sizeof(int16_t));
1103 # if !ENABLE_UNICODE_SUPPORT
1104 save_string(match_buf, cursor + 1); /* +1 for NUL */
1107 CHAR_T wc = command_ps[cursor];
1108 command_ps[cursor] = BB_NUL;
1109 save_string(match_buf, MAX_LINELEN);
1110 command_ps[cursor] = wc;
1111 cursor_mb = strlen(match_buf);
1114 find_type = build_match_prefix(match_buf);
1116 /* Free up any memory already allocated */
1117 free_tab_completion_data();
1119 # if ENABLE_FEATURE_USERNAME_COMPLETION
1120 /* If the word starts with ~ and there is no slash in the word,
1121 * then try completing this word as a username. */
1122 if (state->flags & USERNAME_COMPLETION)
1123 if (match_buf[0] == '~' && strchr(match_buf, '/') == NULL)
1124 match_pfx_len = complete_username(match_buf);
1126 /* If complete_username() did not match,
1127 * try to match a command in $PATH, or a directory, or a file */
1129 match_pfx_len = complete_cmd_dir_file(match_buf, find_type);
1131 /* Account for backslashes which will be inserted
1132 * by quote_special_chars() later */
1134 const char *e = match_buf + strlen(match_buf);
1135 const char *s = e - match_pfx_len;
1137 if (is_special_char(*s++))
1141 /* Remove duplicates */
1144 qsort_string_vector(matches, num_matches);
1145 for (i = 0; i < num_matches - 1; ++i) {
1146 //if (matches[i] && matches[i+1]) { /* paranoia */
1147 if (strcmp(matches[i], matches[i+1]) == 0) {
1149 //matches[i] = NULL; /* paranoia */
1151 matches[n++] = matches[i];
1155 matches[n++] = matches[i];
1159 /* Did we find exactly one match? */
1160 if (num_matches != 1) { /* no */
1164 goto ret; /* no matches at all */
1165 /* Find common prefix */
1166 chosen_match = xstrdup(matches[0]);
1167 for (cp = chosen_match; *cp; cp++) {
1169 for (n = 1; n < num_matches; n++) {
1170 if (matches[n][cp - chosen_match] != *cp) {
1176 if (cp == chosen_match) { /* have unique prefix? */
1180 cp = quote_special_chars(chosen_match);
1183 len_found = strlen(chosen_match);
1184 } else { /* exactly one match */
1185 /* Next <tab> is not a double-tab */
1188 chosen_match = quote_special_chars(matches[0]);
1189 len_found = strlen(chosen_match);
1190 if (chosen_match[len_found-1] != '/') {
1191 chosen_match[len_found] = ' ';
1192 chosen_match[++len_found] = '\0';
1196 # if !ENABLE_UNICODE_SUPPORT
1197 /* Have space to place the match? */
1198 /* The result consists of three parts with these lengths: */
1199 /* cursor + (len_found - match_pfx_len) + (command_len - cursor) */
1200 /* it simplifies into: */
1201 if ((int)(len_found - match_pfx_len + command_len) < S.maxsize) {
1204 strcpy(match_buf, &command_ps[cursor]);
1205 /* add match and tail */
1206 sprintf(&command_ps[cursor], "%s%s", chosen_match + match_pfx_len, match_buf);
1207 command_len = strlen(command_ps);
1209 pos = cursor + len_found - match_pfx_len;
1210 /* write out the matched command */
1211 redraw(cmdedit_y, command_len - pos);
1215 /* Use 2nd half of match_buf as scratch space - see (**) */
1216 char *command = match_buf + MAX_LINELEN;
1217 int len = save_string(command, MAX_LINELEN);
1218 /* Have space to place the match? */
1219 /* cursor_mb + (len_found - match_pfx_len) + (len - cursor_mb) */
1220 if ((int)(len_found - match_pfx_len + len) < MAX_LINELEN) {
1223 strcpy(match_buf, &command[cursor_mb]);
1224 /* where do we want to have cursor after all? */
1225 strcpy(&command[cursor_mb], chosen_match + match_pfx_len);
1226 len = load_string(command);
1227 /* add match and tail */
1228 sprintf(&command[cursor_mb], "%s%s", chosen_match + match_pfx_len, match_buf);
1229 command_len = load_string(command);
1230 /* write out the matched command */
1231 /* paranoia: load_string can return 0 on conv error,
1232 * prevent passing pos = (0 - 12) to redraw */
1233 pos = command_len - len;
1234 redraw(cmdedit_y, pos >= 0 ? pos : 0);
1243 #endif /* FEATURE_TAB_COMPLETION */
1246 line_input_t* FAST_FUNC new_line_input_t(int flags)
1248 line_input_t *n = xzalloc(sizeof(*n));
1250 n->max_history = MAX_HISTORY;
1257 unsigned FAST_FUNC size_from_HISTFILESIZE(const char *hp)
1259 int size = MAX_HISTORY;
1264 if (size > MAX_HISTORY)
1270 static void save_command_ps_at_cur_history(void)
1272 if (command_ps[0] != BB_NUL) {
1273 int cur = state->cur_history;
1274 free(state->history[cur]);
1276 # if ENABLE_UNICODE_SUPPORT
1278 char tbuf[MAX_LINELEN];
1279 save_string(tbuf, sizeof(tbuf));
1280 state->history[cur] = xstrdup(tbuf);
1283 state->history[cur] = xstrdup(command_ps);
1288 /* state->flags is already checked to be nonzero */
1289 static int get_previous_history(void)
1291 if ((state->flags & DO_HISTORY) && state->cur_history) {
1292 save_command_ps_at_cur_history();
1293 state->cur_history--;
1300 static int get_next_history(void)
1302 if (state->flags & DO_HISTORY) {
1303 if (state->cur_history < state->cnt_history) {
1304 save_command_ps_at_cur_history(); /* save the current history line */
1305 return ++state->cur_history;
1312 /* Lists command history. Used by shell 'history' builtins */
1313 void FAST_FUNC show_history(const line_input_t *st)
1319 for (i = 0; i < st->cnt_history; i++)
1320 printf("%4d %s\n", i, st->history[i]);
1323 # if ENABLE_FEATURE_EDITING_SAVEHISTORY
1324 /* We try to ensure that concurrent additions to the history
1325 * do not overwrite each other.
1326 * Otherwise shell users get unhappy.
1328 * History file is trimmed lazily, when it grows several times longer
1329 * than configured MAX_HISTORY lines.
1332 static void free_line_input_t(line_input_t *n)
1334 int i = n->cnt_history;
1336 free(n->history[--i]);
1340 /* state->flags is already checked to be nonzero */
1341 static void load_history(line_input_t *st_parm)
1343 char *temp_h[MAX_HISTORY];
1346 unsigned idx, i, line_len;
1348 /* NB: do not trash old history if file can't be opened */
1350 fp = fopen_for_read(st_parm->hist_file);
1352 /* clean up old history */
1353 for (idx = st_parm->cnt_history; idx > 0;) {
1355 free(st_parm->history[idx]);
1356 st_parm->history[idx] = NULL;
1359 /* fill temp_h[], retaining only last MAX_HISTORY lines */
1360 memset(temp_h, 0, sizeof(temp_h));
1362 st_parm->cnt_history_in_file = 0;
1363 while ((line = xmalloc_fgetline(fp)) != NULL) {
1364 if (line[0] == '\0') {
1370 st_parm->cnt_history_in_file++;
1372 if (idx == st_parm->max_history)
1377 /* find first non-NULL temp_h[], if any */
1378 if (st_parm->cnt_history_in_file) {
1379 while (temp_h[idx] == NULL) {
1381 if (idx == st_parm->max_history)
1386 /* copy temp_h[] to st_parm->history[] */
1387 for (i = 0; i < st_parm->max_history;) {
1392 if (idx == st_parm->max_history)
1394 line_len = strlen(line);
1395 if (line_len >= MAX_LINELEN)
1396 line[MAX_LINELEN-1] = '\0';
1397 st_parm->history[i++] = line;
1399 st_parm->cnt_history = i;
1400 if (ENABLE_FEATURE_EDITING_SAVE_ON_EXIT)
1401 st_parm->cnt_history_in_file = i;
1405 # if ENABLE_FEATURE_EDITING_SAVE_ON_EXIT
1406 void save_history(line_input_t *st)
1412 if (st->cnt_history <= st->cnt_history_in_file)
1415 fp = fopen(st->hist_file, "a");
1419 line_input_t *st_temp;
1421 for (i = st->cnt_history_in_file; i < st->cnt_history; i++)
1422 fprintf(fp, "%s\n", st->history[i]);
1425 /* we may have concurrently written entries from others.
1427 st_temp = new_line_input_t(st->flags);
1428 st_temp->hist_file = st->hist_file;
1429 st_temp->max_history = st->max_history;
1430 load_history(st_temp);
1432 /* write out temp file and replace hist_file atomically */
1433 new_name = xasprintf("%s.%u.new", st->hist_file, (int) getpid());
1434 fd = open(new_name, O_WRONLY | O_CREAT | O_TRUNC, 0600);
1436 fp = xfdopen_for_write(fd);
1437 for (i = 0; i < st_temp->cnt_history; i++)
1438 fprintf(fp, "%s\n", st_temp->history[i]);
1440 if (rename(new_name, st->hist_file) == 0)
1441 st->cnt_history_in_file = st_temp->cnt_history;
1444 free_line_input_t(st_temp);
1448 static void save_history(char *str)
1453 if (!state->hist_file)
1456 fd = open(state->hist_file, O_WRONLY | O_CREAT | O_APPEND, 0600);
1459 xlseek(fd, 0, SEEK_END); /* paranoia */
1461 str[len] = '\n'; /* we (try to) do atomic write */
1462 len2 = full_write(fd, str, len + 1);
1465 if (len2 != len + 1)
1466 return; /* "wtf?" */
1468 /* did we write so much that history file needs trimming? */
1469 state->cnt_history_in_file++;
1470 if (state->cnt_history_in_file > state->max_history * 4) {
1472 line_input_t *st_temp;
1474 /* we may have concurrently written entries from others.
1476 st_temp = new_line_input_t(state->flags);
1477 st_temp->hist_file = state->hist_file;
1478 st_temp->max_history = state->max_history;
1479 load_history(st_temp);
1481 /* write out temp file and replace hist_file atomically */
1482 new_name = xasprintf("%s.%u.new", state->hist_file, (int) getpid());
1483 fd = open(new_name, O_WRONLY | O_CREAT | O_TRUNC, 0600);
1488 fp = xfdopen_for_write(fd);
1489 for (i = 0; i < st_temp->cnt_history; i++)
1490 fprintf(fp, "%s\n", st_temp->history[i]);
1492 if (rename(new_name, state->hist_file) == 0)
1493 state->cnt_history_in_file = st_temp->cnt_history;
1496 free_line_input_t(st_temp);
1501 # define load_history(a) ((void)0)
1502 # define save_history(a) ((void)0)
1503 # endif /* FEATURE_COMMAND_SAVEHISTORY */
1505 static void remember_in_history(char *str)
1509 if (!(state->flags & DO_HISTORY))
1513 i = state->cnt_history;
1514 /* Don't save dupes */
1515 if (i && strcmp(state->history[i-1], str) == 0)
1518 free(state->history[state->max_history]); /* redundant, paranoia */
1519 state->history[state->max_history] = NULL; /* redundant, paranoia */
1521 /* If history[] is full, remove the oldest command */
1522 /* we need to keep history[state->max_history] empty, hence >=, not > */
1523 if (i >= state->max_history) {
1524 free(state->history[0]);
1525 for (i = 0; i < state->max_history-1; i++)
1526 state->history[i] = state->history[i+1];
1527 /* i == state->max_history-1 */
1528 # if ENABLE_FEATURE_EDITING_SAVE_ON_EXIT
1529 if (state->cnt_history_in_file)
1530 state->cnt_history_in_file--;
1533 /* i <= state->max_history-1 */
1534 state->history[i++] = xstrdup(str);
1535 /* i <= state->max_history */
1536 state->cur_history = i;
1537 state->cnt_history = i;
1538 # if ENABLE_FEATURE_EDITING_SAVEHISTORY && !ENABLE_FEATURE_EDITING_SAVE_ON_EXIT
1543 #else /* MAX_HISTORY == 0 */
1544 # define remember_in_history(a) ((void)0)
1545 #endif /* MAX_HISTORY */
1548 #if ENABLE_FEATURE_EDITING_VI
1550 * vi mode implemented 2005 by Paul Fox <pgf@foxharp.boston.ma.us>
1553 vi_Word_motion(int eat)
1555 CHAR_T *command = command_ps;
1557 while (cursor < command_len && !BB_isspace(command[cursor]))
1559 if (eat) while (cursor < command_len && BB_isspace(command[cursor]))
1564 vi_word_motion(int eat)
1566 CHAR_T *command = command_ps;
1568 if (BB_isalnum(command[cursor]) || command[cursor] == '_') {
1569 while (cursor < command_len
1570 && (BB_isalnum(command[cursor+1]) || command[cursor+1] == '_')
1574 } else if (BB_ispunct(command[cursor])) {
1575 while (cursor < command_len && BB_ispunct(command[cursor+1]))
1579 if (cursor < command_len)
1583 while (cursor < command_len && BB_isspace(command[cursor]))
1591 CHAR_T *command = command_ps;
1594 while (cursor < command_len && BB_isspace(command[cursor]))
1596 while (cursor < command_len-1 && !BB_isspace(command[cursor+1]))
1603 CHAR_T *command = command_ps;
1605 if (cursor >= command_len-1)
1608 while (cursor < command_len-1 && BB_isspace(command[cursor]))
1610 if (cursor >= command_len-1)
1612 if (BB_isalnum(command[cursor]) || command[cursor] == '_') {
1613 while (cursor < command_len-1
1614 && (BB_isalnum(command[cursor+1]) || command[cursor+1] == '_')
1618 } else if (BB_ispunct(command[cursor])) {
1619 while (cursor < command_len-1 && BB_ispunct(command[cursor+1]))
1625 vi_Back_motion(void)
1627 CHAR_T *command = command_ps;
1629 while (cursor > 0 && BB_isspace(command[cursor-1]))
1631 while (cursor > 0 && !BB_isspace(command[cursor-1]))
1636 vi_back_motion(void)
1638 CHAR_T *command = command_ps;
1643 while (cursor > 0 && BB_isspace(command[cursor]))
1647 if (BB_isalnum(command[cursor]) || command[cursor] == '_') {
1649 && (BB_isalnum(command[cursor-1]) || command[cursor-1] == '_')
1653 } else if (BB_ispunct(command[cursor])) {
1654 while (cursor > 0 && BB_ispunct(command[cursor-1]))
1660 /* Modelled after bash 4.0 behavior of Ctrl-<arrow> */
1661 static void ctrl_left(void)
1663 CHAR_T *command = command_ps;
1671 c = command[cursor];
1672 if (c != ' ' && !BB_ispunct(c)) {
1673 /* we reached a "word" delimited by spaces/punct.
1674 * go to its beginning */
1676 c = command[cursor - 1];
1677 if (c == ' ' || BB_ispunct(c))
1687 static void ctrl_right(void)
1689 CHAR_T *command = command_ps;
1694 c = command[cursor];
1697 if (c != ' ' && !BB_ispunct(c)) {
1698 /* we reached a "word" delimited by spaces/punct.
1699 * go to its end + 1 */
1702 c = command[cursor];
1703 if (c == BB_NUL || c == ' ' || BB_ispunct(c))
1714 * read_line_input and its helpers
1717 #if ENABLE_FEATURE_EDITING_ASK_TERMINAL
1718 static void ask_terminal(void)
1720 /* Ask terminal where is the cursor now.
1721 * lineedit_read_key handles response and corrects
1722 * our idea of current cursor position.
1723 * Testcase: run "echo -n long_line_long_line_long_line",
1724 * then type in a long, wrapping command and try to
1725 * delete it using backspace key.
1726 * Note: we print it _after_ prompt, because
1727 * prompt may contain CR. Example: PS1='\[\r\n\]\w '
1729 /* Problem: if there is buffered input on stdin,
1730 * the response will be delivered later,
1731 * possibly to an unsuspecting application.
1732 * Testcase: "sleep 1; busybox ash" + press and hold [Enter].
1734 * ~/srcdevel/bbox/fix/busybox.t4 #
1735 * ~/srcdevel/bbox/fix/busybox.t4 #
1736 * ^[[59;34~/srcdevel/bbox/fix/busybox.t4 # <-- garbage
1737 * ~/srcdevel/bbox/fix/busybox.t4 #
1739 * Checking for input with poll only makes the race narrower,
1740 * I still can trigger it. Strace:
1742 * write(1, "~/srcdevel/bbox/fix/busybox.t4 # ", 33) = 33
1743 * poll([{fd=0, events=POLLIN}], 1, 0) = 0 (Timeout) <-- no input exists
1744 * write(1, "\33[6n", 4) = 4 <-- send the ESC sequence, quick!
1745 * poll([{fd=0, events=POLLIN}], 1, -1) = 1 ([{fd=0, revents=POLLIN}])
1746 * read(0, "\n", 1) = 1 <-- oh crap, user's input got in first
1750 pfd.fd = STDIN_FILENO;
1751 pfd.events = POLLIN;
1752 if (safe_poll(&pfd, 1, 0) == 0) {
1753 S.sent_ESC_br6n = 1;
1754 fputs(ESC"[6n", stdout);
1755 fflush_all(); /* make terminal see it ASAP! */
1759 #define ask_terminal() ((void)0)
1762 #if !ENABLE_FEATURE_EDITING_FANCY_PROMPT
1763 static void parse_and_put_prompt(const char *prmt_ptr)
1765 cmdedit_prompt = prmt_ptr;
1766 cmdedit_prmt_len = strlen(prmt_ptr);
1770 static void parse_and_put_prompt(const char *prmt_ptr)
1773 size_t cur_prmt_len = 0;
1774 char flg_not_length = '[';
1775 char *prmt_mem_ptr = xzalloc(1);
1776 # if ENABLE_USERNAME_OR_HOMEDIR
1777 char *cwd_buf = NULL;
1779 char timebuf[sizeof("HH:MM:SS")];
1784 cmdedit_prmt_len = 0;
1786 cbuf[1] = '\0'; /* never changes */
1789 char *free_me = NULL;
1797 * Supported via bb_process_escape_sequence:
1798 * \a ASCII bell character (07)
1799 * \e ASCII escape character (033)
1801 * \r carriage return
1803 * \nnn char with octal code nnn
1805 * \$ if the effective UID is 0, a #, otherwise a $
1806 * \w current working directory, with $HOME abbreviated with a tilde
1807 * Note: we do not support $PROMPT_DIRTRIM=n feature
1808 * \W basename of the current working directory, with $HOME abbreviated with a tilde
1809 * \h hostname up to the first '.'
1812 * \[ begin a sequence of non-printing characters
1813 * \] end a sequence of non-printing characters
1814 * \T current time in 12-hour HH:MM:SS format
1815 * \@ current time in 12-hour am/pm format
1816 * \A current time in 24-hour HH:MM format
1817 * \t current time in 24-hour HH:MM:SS format
1818 * (all of the above work as \A)
1820 * \! history number of this command
1821 * \# command number of this command
1822 * \j number of jobs currently managed by the shell
1823 * \l basename of the shell's terminal device name
1824 * \s name of the shell, the basename of $0 (the portion following the final slash)
1825 * \V release of bash, version + patch level (e.g., 2.00.0)
1826 * \d date in "Weekday Month Date" format (e.g., "Tue May 26")
1828 * format is passed to strftime(3).
1829 * An empty format results in a locale-specific time representation.
1830 * The braces are required.
1831 * Mishandled by bb_process_escape_sequence:
1832 * \v version of bash (e.g., 2.00)
1836 if (c != 't') /* don't treat \t as tab */
1837 c = bb_process_escape_sequence(&prmt_ptr);
1838 if (prmt_ptr == cp) {
1844 # if ENABLE_USERNAME_OR_HOMEDIR
1846 pbuf = user_buf ? user_buf : (char*)"";
1851 pbuf = free_me = safe_gethostname();
1853 strchrnul(pbuf, '.')[0] = '\0';
1856 c = (geteuid() == 0 ? '#' : '$');
1858 case 'T': /* 12-hour HH:MM:SS format */
1859 case '@': /* 12-hour am/pm format */
1860 case 'A': /* 24-hour HH:MM format */
1861 case 't': /* 24-hour HH:MM:SS format */
1862 /* We show all of them as 24-hour HH:MM */
1863 strftime_HHMMSS(timebuf, sizeof(timebuf), NULL)[-3] = '\0';
1866 # if ENABLE_USERNAME_OR_HOMEDIR
1867 case 'w': /* current dir */
1868 case 'W': /* basename of cur dir */
1870 cwd_buf = xrealloc_getcwd_or_warn(NULL);
1872 cwd_buf = (char *)bb_msg_unknown;
1874 /* /home/user[/something] -> ~[/something] */
1875 l = strlen(home_pwd_buf);
1877 && strncmp(home_pwd_buf, cwd_buf, l) == 0
1878 && (cwd_buf[l] == '/' || cwd_buf[l] == '\0')
1881 overlapping_strcpy(cwd_buf + 1, cwd_buf + l);
1888 cp = strrchr(pbuf, '/');
1890 pbuf = (char*)cp + 1;
1893 // bb_process_escape_sequence does this now:
1894 // case 'e': case 'E': /* \e \E = \033 */
1897 case 'x': case 'X': {
1899 for (l = 0; l < 3;) {
1901 buf2[l++] = *prmt_ptr;
1903 h = strtoul(buf2, &pbuf, 16);
1904 if (h > UCHAR_MAX || (pbuf - buf2) < l) {
1910 c = (char)strtoul(buf2, NULL, 16);
1917 if (c == flg_not_length) {
1918 flg_not_length = (flg_not_length == '[' ? ']' : '[');
1926 cur_prmt_len = strlen(pbuf);
1927 prmt_len += cur_prmt_len;
1928 if (flg_not_length != ']')
1929 cmdedit_prmt_len += cur_prmt_len;
1930 prmt_mem_ptr = strcat(xrealloc(prmt_mem_ptr, prmt_len+1), pbuf);
1934 # if ENABLE_USERNAME_OR_HOMEDIR
1935 if (cwd_buf != (char *)bb_msg_unknown)
1938 cmdedit_prompt = prmt_mem_ptr;
1943 static void cmdedit_setwidth(unsigned w, int redraw_flg)
1947 /* new y for current cursor */
1948 int new_y = (cursor + cmdedit_prmt_len) / w;
1950 redraw((new_y >= cmdedit_y ? new_y : cmdedit_y), command_len - cursor);
1955 static void win_changed(int nsig)
1957 int sv_errno = errno;
1960 get_terminal_width_height(0, &width, NULL);
1961 //FIXME: cmdedit_setwidth() -> redraw() -> printf() -> KABOOM! (we are in signal handler!)
1962 cmdedit_setwidth(width, /*redraw_flg:*/ nsig);
1967 static int lineedit_read_key(char *read_key_buffer, int timeout)
1970 #if ENABLE_UNICODE_SUPPORT
1971 char unicode_buf[MB_CUR_MAX + 1];
1972 int unicode_idx = 0;
1976 /* Wait for input. TIMEOUT = -1 makes read_key wait even
1977 * on nonblocking stdin, TIMEOUT = 50 makes sure we won't
1978 * insist on full MB_CUR_MAX buffer to declare input like
1979 * "\xff\n",pause,"ls\n" invalid and thus won't lose "ls".
1981 * Note: read_key sets errno to 0 on success.
1983 ic = read_key(STDIN_FILENO, read_key_buffer, timeout);
1985 #if ENABLE_UNICODE_SUPPORT
1986 if (errno == EAGAIN && unicode_idx != 0)
1992 #if ENABLE_FEATURE_EDITING_ASK_TERMINAL
1993 if ((int32_t)ic == KEYCODE_CURSOR_POS
1996 S.sent_ESC_br6n = 0;
1997 if (cursor == 0) { /* otherwise it may be bogus */
1998 int col = ((ic >> 32) & 0x7fff) - 1;
1999 if (col > cmdedit_prmt_len) {
2000 cmdedit_x += (col - cmdedit_prmt_len);
2001 while (cmdedit_x >= cmdedit_termw) {
2002 cmdedit_x -= cmdedit_termw;
2011 #if ENABLE_UNICODE_SUPPORT
2012 if (unicode_status == UNICODE_ON) {
2015 if ((int32_t)ic < 0) /* KEYCODE_xxx */
2017 // TODO: imagine sequence like: 0xff,<left-arrow>: we are currently losing 0xff...
2019 unicode_buf[unicode_idx++] = ic;
2020 unicode_buf[unicode_idx] = '\0';
2021 if (mbstowcs(&wc, unicode_buf, 1) != 1) {
2022 /* Not (yet?) a valid unicode char */
2023 if (unicode_idx < MB_CUR_MAX) {
2028 /* Invalid sequence. Save all "bad bytes" except first */
2029 read_key_ungets(read_key_buffer, unicode_buf + 1, unicode_idx - 1);
2030 # if !ENABLE_UNICODE_PRESERVE_BROKEN
2031 ic = CONFIG_SUBST_WCHAR;
2033 ic = unicode_mark_raw_byte(unicode_buf[0]);
2036 /* Valid unicode char, return its code */
2047 #if ENABLE_UNICODE_BIDI_SUPPORT
2048 static int isrtl_str(void)
2052 while (idx < command_len && unicode_bidi_is_neutral_wchar(command_ps[idx]))
2054 return unicode_bidi_isrtl(command_ps[idx]);
2057 # define isrtl_str() 0
2060 /* leave out the "vi-mode"-only case labels if vi editing isn't
2062 #define vi_case(caselabel) IF_FEATURE_EDITING_VI(case caselabel)
2064 /* convert uppercase ascii to equivalent control char, for readability */
2066 #define CTRL(a) ((a) & ~0x40)
2069 VI_CMDMODE_BIT = 0x40000000,
2070 /* 0x80000000 bit flags KEYCODE_xxx */
2073 #if ENABLE_FEATURE_REVERSE_SEARCH
2074 /* Mimic readline Ctrl-R reverse history search.
2075 * When invoked, it shows the following prompt:
2076 * (reverse-i-search)'': user_input [cursor pos unchanged by Ctrl-R]
2077 * and typing results in search being performed:
2078 * (reverse-i-search)'tmp': cd /tmp [cursor under t in /tmp]
2079 * Search is performed by looking at progressively older lines in history.
2080 * Ctrl-R again searches for the next match in history.
2081 * Backspace deletes last matched char.
2082 * Control keys exit search and return to normal editing (at current history line).
2084 static int32_t reverse_i_search(void)
2086 char match_buf[128]; /* for user input */
2087 char read_key_buffer[KEYCODE_BUFFER_SIZE];
2088 const char *matched_history_line;
2089 const char *saved_prompt;
2092 matched_history_line = NULL;
2093 read_key_buffer[0] = 0;
2094 match_buf[0] = '\0';
2096 /* Save and replace the prompt */
2097 saved_prompt = cmdedit_prompt;
2102 unsigned match_buf_len = strlen(match_buf);
2105 //FIXME: correct timeout?
2106 ic = lineedit_read_key(read_key_buffer, -1);
2109 case CTRL('R'): /* searching for the next match */
2115 if (unicode_status == UNICODE_ON) {
2116 while (match_buf_len != 0) {
2117 uint8_t c = match_buf[--match_buf_len];
2118 if ((c & 0xc0) != 0x80) /* start of UTF-8 char? */
2122 if (match_buf_len != 0)
2125 match_buf[match_buf_len] = '\0';
2130 || (!ENABLE_UNICODE_SUPPORT && ic >= 256)
2131 || (ENABLE_UNICODE_SUPPORT && ic >= VI_CMDMODE_BIT)
2136 /* Append this char */
2137 #if ENABLE_UNICODE_SUPPORT
2138 if (unicode_status == UNICODE_ON) {
2139 mbstate_t mbstate = { 0 };
2140 char buf[MB_CUR_MAX + 1];
2141 int len = wcrtomb(buf, ic, &mbstate);
2144 if (match_buf_len + len < sizeof(match_buf))
2145 strcpy(match_buf + match_buf_len, buf);
2149 if (match_buf_len < sizeof(match_buf) - 1) {
2150 match_buf[match_buf_len] = ic;
2151 match_buf[match_buf_len + 1] = '\0';
2156 /* Search in history for match_buf */
2157 h = state->cur_history;
2158 if (ic == CTRL('R'))
2161 if (state->history[h]) {
2162 char *match = strstr(state->history[h], match_buf);
2164 state->cur_history = h;
2165 matched_history_line = state->history[h];
2166 command_len = load_string(matched_history_line);
2167 cursor = match - matched_history_line;
2168 //FIXME: cursor position for Unicode case
2170 free((char*)cmdedit_prompt);
2172 cmdedit_prompt = xasprintf("(reverse-i-search)'%s': ", match_buf);
2173 cmdedit_prmt_len = strlen(cmdedit_prompt);
2181 match_buf[match_buf_len] = '\0';
2186 redraw(cmdedit_y, command_len - cursor);
2190 if (matched_history_line)
2191 command_len = load_string(matched_history_line);
2193 free((char*)cmdedit_prompt);
2194 cmdedit_prompt = saved_prompt;
2195 cmdedit_prmt_len = strlen(cmdedit_prompt);
2196 redraw(cmdedit_y, command_len - cursor);
2202 /* maxsize must be >= 2.
2204 * -1 on read errors or EOF, or on bare Ctrl-D,
2205 * 0 on ctrl-C (the line entered is still returned in 'command'),
2206 * >0 length of input string, including terminating '\n'
2208 int FAST_FUNC read_line_input(line_input_t *st, const char *prompt, char *command, int maxsize, int timeout)
2211 #if ENABLE_FEATURE_TAB_COMPLETION
2212 smallint lastWasTab = 0;
2214 smallint break_out = 0;
2215 #if ENABLE_FEATURE_EDITING_VI
2216 smallint vi_cmdmode = 0;
2218 struct termios initial_settings;
2219 struct termios new_settings;
2220 char read_key_buffer[KEYCODE_BUFFER_SIZE];
2224 if (tcgetattr(STDIN_FILENO, &initial_settings) < 0
2225 || !(initial_settings.c_lflag & ECHO)
2227 /* Happens when e.g. stty -echo was run before */
2228 parse_and_put_prompt(prompt);
2229 /* fflush_all(); - done by parse_and_put_prompt */
2230 if (fgets(command, maxsize, stdin) == NULL)
2231 len = -1; /* EOF or error */
2233 len = strlen(command);
2240 // FIXME: audit & improve this
2241 if (maxsize > MAX_LINELEN)
2242 maxsize = MAX_LINELEN;
2243 S.maxsize = maxsize;
2245 /* With zero flags, no other fields are ever used */
2246 state = st ? st : (line_input_t*) &const_int_0;
2248 # if ENABLE_FEATURE_EDITING_SAVEHISTORY
2249 if (state->hist_file)
2250 if (state->cnt_history == 0)
2251 load_history(state);
2253 if (state->flags & DO_HISTORY)
2254 state->cur_history = state->cnt_history;
2257 /* prepare before init handlers */
2258 cmdedit_y = 0; /* quasireal y, not true if line > xt*yt */
2260 #if ENABLE_UNICODE_SUPPORT
2261 command_ps = xzalloc(maxsize * sizeof(command_ps[0]));
2263 command_ps = command;
2266 #define command command_must_not_be_used
2268 new_settings = initial_settings;
2269 /* ~ICANON: unbuffered input (most c_cc[] are disabled, VMIN/VTIME are enabled) */
2270 /* ~ECHO, ~ECHONL: turn off echoing, including newline echoing */
2271 /* ~ISIG: turn off INTR (ctrl-C), QUIT, SUSP */
2272 new_settings.c_lflag &= ~(ICANON | ECHO | ECHONL | ISIG);
2273 /* reads would block only if < 1 char is available */
2274 new_settings.c_cc[VMIN] = 1;
2275 /* no timeout (reads block forever) */
2276 new_settings.c_cc[VTIME] = 0;
2277 /* Should be not needed if ISIG is off: */
2278 /* Turn off CTRL-C */
2279 /* new_settings.c_cc[VINTR] = _POSIX_VDISABLE; */
2280 tcsetattr_stdin_TCSANOW(&new_settings);
2282 #if ENABLE_USERNAME_OR_HOMEDIR
2284 struct passwd *entry;
2286 entry = getpwuid(geteuid());
2288 user_buf = xstrdup(entry->pw_name);
2289 home_pwd_buf = xstrdup(entry->pw_dir);
2295 for (i = 0; i <= state->max_history; i++)
2296 bb_error_msg("history[%d]:'%s'", i, state->history[i]);
2297 bb_error_msg("cur_history:%d cnt_history:%d", state->cur_history, state->cnt_history);
2300 /* Print out the command prompt, optionally ask where cursor is */
2301 parse_and_put_prompt(prompt);
2304 /* Install window resize handler (NB: after *all* init is complete) */
2305 //FIXME: save entire sigaction!
2306 previous_SIGWINCH_handler = signal(SIGWINCH, win_changed);
2307 win_changed(0); /* get initial window size */
2309 read_key_buffer[0] = 0;
2312 * The emacs and vi modes share much of the code in the big
2313 * command loop. Commands entered when in vi's command mode
2314 * (aka "escape mode") get an extra bit added to distinguish
2315 * them - this keeps them from being self-inserted. This
2316 * clutters the big switch a bit, but keeps all the code
2322 ic = ic_raw = lineedit_read_key(read_key_buffer, timeout);
2324 #if ENABLE_FEATURE_REVERSE_SEARCH
2327 #if ENABLE_FEATURE_EDITING_VI
2330 /* btw, since KEYCODE_xxx are all < 0, this doesn't
2331 * change ic if it contains one of them: */
2332 ic |= VI_CMDMODE_BIT;
2339 vi_case('\n'|VI_CMDMODE_BIT:)
2340 vi_case('\r'|VI_CMDMODE_BIT:)
2346 vi_case('0'|VI_CMDMODE_BIT:)
2347 /* Control-a -- Beginning of line */
2348 input_backward(cursor);
2351 vi_case('h'|VI_CMDMODE_BIT:)
2352 vi_case('\b'|VI_CMDMODE_BIT:) /* ^H */
2353 vi_case('\x7f'|VI_CMDMODE_BIT:) /* DEL */
2354 input_backward(1); /* Move back one character */
2357 vi_case('$'|VI_CMDMODE_BIT:)
2358 /* Control-e -- End of line */
2359 put_till_end_and_adv_cursor();
2362 vi_case('l'|VI_CMDMODE_BIT:)
2363 vi_case(' '|VI_CMDMODE_BIT:)
2364 input_forward(); /* Move forward one character */
2367 case '\x7f': /* DEL */
2373 case KEYCODE_DELETE:
2379 #if ENABLE_FEATURE_TAB_COMPLETION
2381 input_tab(&lastWasTab);
2385 /* Control-k -- clear to end of line */
2386 command_ps[cursor] = BB_NUL;
2387 command_len = cursor;
2388 printf(SEQ_CLEAR_TILL_END_OF_SCREEN);
2391 vi_case(CTRL('L')|VI_CMDMODE_BIT:)
2392 /* Control-l -- clear screen */
2393 printf(ESC"[H"); /* cursor to top,left */
2394 redraw(0, command_len - cursor);
2398 vi_case(CTRL('N')|VI_CMDMODE_BIT:)
2399 vi_case('j'|VI_CMDMODE_BIT:)
2400 /* Control-n -- Get next command in history */
2401 if (get_next_history())
2405 vi_case(CTRL('P')|VI_CMDMODE_BIT:)
2406 vi_case('k'|VI_CMDMODE_BIT:)
2407 /* Control-p -- Get previous command from history */
2408 if (get_previous_history())
2413 vi_case(CTRL('U')|VI_CMDMODE_BIT:)
2414 /* Control-U -- Clear line before cursor */
2416 command_len -= cursor;
2417 memmove(command_ps, command_ps + cursor,
2418 (command_len + 1) * sizeof(command_ps[0]));
2419 redraw(cmdedit_y, command_len);
2423 vi_case(CTRL('W')|VI_CMDMODE_BIT:)
2424 /* Control-W -- Remove the last word */
2425 while (cursor > 0 && BB_isspace(command_ps[cursor-1]))
2427 while (cursor > 0 && !BB_isspace(command_ps[cursor-1]))
2430 #if ENABLE_FEATURE_REVERSE_SEARCH
2432 ic = ic_raw = reverse_i_search();
2436 #if ENABLE_FEATURE_EDITING_VI
2437 case 'i'|VI_CMDMODE_BIT:
2440 case 'I'|VI_CMDMODE_BIT:
2441 input_backward(cursor);
2444 case 'a'|VI_CMDMODE_BIT:
2448 case 'A'|VI_CMDMODE_BIT:
2449 put_till_end_and_adv_cursor();
2452 case 'x'|VI_CMDMODE_BIT:
2455 case 'X'|VI_CMDMODE_BIT:
2461 case 'W'|VI_CMDMODE_BIT:
2464 case 'w'|VI_CMDMODE_BIT:
2467 case 'E'|VI_CMDMODE_BIT:
2470 case 'e'|VI_CMDMODE_BIT:
2473 case 'B'|VI_CMDMODE_BIT:
2476 case 'b'|VI_CMDMODE_BIT:
2479 case 'C'|VI_CMDMODE_BIT:
2482 case 'D'|VI_CMDMODE_BIT:
2485 case 'c'|VI_CMDMODE_BIT:
2488 case 'd'|VI_CMDMODE_BIT: {
2491 ic = lineedit_read_key(read_key_buffer, timeout);
2492 if (errno) /* error */
2493 goto return_error_indicator;
2494 if (ic == ic_raw) { /* "cc", "dd" */
2495 input_backward(cursor);
2507 case 'w': /* "dw", "cw" */
2508 vi_word_motion(vi_cmdmode);
2510 case 'W': /* 'dW', 'cW' */
2511 vi_Word_motion(vi_cmdmode);
2513 case 'e': /* 'de', 'ce' */
2517 case 'E': /* 'dE', 'cE' */
2523 input_backward(cursor - sc);
2524 while (nc-- > cursor)
2527 case 'b': /* "db", "cb" */
2528 case 'B': /* implemented as B */
2533 while (sc-- > cursor)
2536 case ' ': /* "d ", "c " */
2539 case '$': /* "d$", "c$" */
2541 while (cursor < command_len)
2547 case 'p'|VI_CMDMODE_BIT:
2550 case 'P'|VI_CMDMODE_BIT:
2553 case 'r'|VI_CMDMODE_BIT:
2554 //FIXME: unicode case?
2555 ic = lineedit_read_key(read_key_buffer, timeout);
2556 if (errno) /* error */
2557 goto return_error_indicator;
2558 if (ic < ' ' || ic > 255) {
2561 command_ps[cursor] = ic;
2566 case '\x1b': /* ESC */
2567 if (state->flags & VI_MODE) {
2568 /* insert mode --> command mode */
2572 /* Handle a few ESC-<key> combinations the same way
2573 * standard readline bindings (IOW: bash) do.
2574 * Often, Alt-<key> generates ESC-<key>.
2576 ic = lineedit_read_key(read_key_buffer, timeout);
2578 //case KEYCODE_LEFT: - bash doesn't do this
2582 //case KEYCODE_RIGHT: - bash doesn't do this
2586 //case KEYCODE_DELETE: - bash doesn't do this
2587 case 'd': /* Alt-D */
2589 /* Delete word forward */
2590 int nc, sc = cursor;
2598 case '\b': /* Alt-Backspace(?) */
2599 case '\x7f': /* Alt-Backspace(?) */
2600 //case 'w': - bash doesn't do this
2602 /* Delete word backward */
2605 while (sc-- > cursor)
2611 #endif /* FEATURE_COMMAND_EDITING_VI */
2615 if (get_previous_history())
2620 if (!get_next_history())
2623 /* Rewrite the line with the selected history item */
2624 /* change command */
2625 command_len = load_string(state->history[state->cur_history] ?
2626 state->history[state->cur_history] : "");
2627 /* redraw and go to eol (bol, in vi) */
2628 redraw(cmdedit_y, (state->flags & VI_MODE) ? 9999 : 0);
2637 case KEYCODE_CTRL_LEFT:
2638 case KEYCODE_ALT_LEFT: /* bash doesn't do it */
2641 case KEYCODE_CTRL_RIGHT:
2642 case KEYCODE_ALT_RIGHT: /* bash doesn't do it */
2646 input_backward(cursor);
2649 put_till_end_and_adv_cursor();
2653 if (initial_settings.c_cc[VINTR] != 0
2654 && ic_raw == initial_settings.c_cc[VINTR]
2656 /* Ctrl-C (usually) - stop gathering input */
2659 break_out = -1; /* "do not append '\n'" */
2662 if (initial_settings.c_cc[VEOF] != 0
2663 && ic_raw == initial_settings.c_cc[VEOF]
2665 /* Ctrl-D (usually) - delete one character,
2666 * or exit if len=0 and no chars to delete */
2667 if (command_len == 0) {
2670 case -1: /* error (e.g. EIO when tty is destroyed) */
2671 IF_FEATURE_EDITING_VI(return_error_indicator:)
2672 break_out = command_len = -1;
2678 // /* Control-V -- force insert of next char */
2679 // if (c == CTRL('V')) {
2680 // if (safe_read(STDIN_FILENO, &c, 1) < 1)
2681 // goto return_error_indicator;
2688 || (!ENABLE_UNICODE_SUPPORT && ic >= 256)
2689 || (ENABLE_UNICODE_SUPPORT && ic >= VI_CMDMODE_BIT)
2691 /* If VI_CMDMODE_BIT is set, ic is >= 256
2692 * and vi mode ignores unexpected chars.
2693 * Otherwise, we are here if ic is a
2694 * control char or an unhandled ESC sequence,
2695 * which is also ignored.
2699 if ((int)command_len >= (maxsize - 2)) {
2700 /* Not enough space for the char and EOL */
2705 if (cursor == (command_len - 1)) {
2706 /* We are at the end, append */
2707 command_ps[cursor] = ic;
2708 command_ps[cursor + 1] = BB_NUL;
2709 put_cur_glyph_and_inc_cursor();
2710 if (unicode_bidi_isrtl(ic))
2713 /* In the middle, insert */
2716 memmove(command_ps + sc + 1, command_ps + sc,
2717 (command_len - sc) * sizeof(command_ps[0]));
2718 command_ps[sc] = ic;
2719 /* is right-to-left char, or neutral one (e.g. comma) was just added to rtl text? */
2722 put_till_end_and_adv_cursor();
2723 /* to prev x pos + 1 */
2724 input_backward(cursor - sc);
2732 #if ENABLE_FEATURE_TAB_COMPLETION
2738 #if ENABLE_FEATURE_EDITING_ASK_TERMINAL
2739 if (S.sent_ESC_br6n) {
2740 /* "sleep 1; busybox ash" + hold [Enter] to trigger.
2741 * We sent "ESC [ 6 n", but got '\n' first, and
2742 * KEYCODE_CURSOR_POS response is now buffered from terminal.
2743 * It's bad already and not much can be done with it
2744 * (it _will_ be visible for the next process to read stdin),
2745 * but without this delay it even shows up on the screen
2746 * as garbage because we restore echo settings with tcsetattr
2747 * before it comes in. UGLY!
2753 /* End of bug-catching "command_must_not_be_used" trick */
2756 #if ENABLE_UNICODE_SUPPORT
2758 if (command_len > 0)
2759 command_len = save_string(command, maxsize - 1);
2763 if (command_len > 0) {
2764 remember_in_history(command);
2767 if (break_out > 0) {
2768 command[command_len++] = '\n';
2769 command[command_len] = '\0';
2772 #if ENABLE_FEATURE_TAB_COMPLETION
2773 free_tab_completion_data();
2776 /* restore initial_settings */
2777 tcsetattr_stdin_TCSANOW(&initial_settings);
2778 /* restore SIGWINCH handler */
2779 signal(SIGWINCH, previous_SIGWINCH_handler);
2785 return len; /* can't return command_len, DEINIT_S() destroys it */
2788 #else /* !FEATURE_EDITING */
2790 #undef read_line_input
2791 int FAST_FUNC read_line_input(const char* prompt, char* command, int maxsize)
2793 fputs(prompt, stdout);
2795 if (!fgets(command, maxsize, stdin))
2797 return strlen(command);
2800 #endif /* !FEATURE_EDITING */
2811 const char *applet_name = "debug stuff usage";
2813 int main(int argc, char **argv)
2815 char buff[MAX_LINELEN];
2817 #if ENABLE_FEATURE_EDITING_FANCY_PROMPT
2818 "\\[\\033[32;1m\\]\\u@\\[\\x1b[33;1m\\]\\h:"
2819 "\\[\\033[34;1m\\]\\w\\[\\033[35;1m\\] "
2820 "\\!\\[\\e[36;1m\\]\\$ \\[\\E[0m\\]";
2827 l = read_line_input(prompt, buff);
2828 if (l <= 0 || buff[l-1] != '\n')
2831 printf("*** read_line_input() returned line =%s=\n", buff);
2833 printf("*** read_line_input() detect ^D\n");