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 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 # if ENABLE_FEATURE_EDITING_SAVEHISTORY
1313 /* We try to ensure that concurrent additions to the history
1314 * do not overwrite each other.
1315 * Otherwise shell users get unhappy.
1317 * History file is trimmed lazily, when it grows several times longer
1318 * than configured MAX_HISTORY lines.
1321 static void free_line_input_t(line_input_t *n)
1323 int i = n->cnt_history;
1325 free(n->history[--i]);
1329 /* state->flags is already checked to be nonzero */
1330 static void load_history(line_input_t *st_parm)
1332 char *temp_h[MAX_HISTORY];
1335 unsigned idx, i, line_len;
1337 /* NB: do not trash old history if file can't be opened */
1339 fp = fopen_for_read(st_parm->hist_file);
1341 /* clean up old history */
1342 for (idx = st_parm->cnt_history; idx > 0;) {
1344 free(st_parm->history[idx]);
1345 st_parm->history[idx] = NULL;
1348 /* fill temp_h[], retaining only last MAX_HISTORY lines */
1349 memset(temp_h, 0, sizeof(temp_h));
1351 st_parm->cnt_history_in_file = 0;
1352 while ((line = xmalloc_fgetline(fp)) != NULL) {
1353 if (line[0] == '\0') {
1359 st_parm->cnt_history_in_file++;
1361 if (idx == st_parm->max_history)
1366 /* find first non-NULL temp_h[], if any */
1367 if (st_parm->cnt_history_in_file) {
1368 while (temp_h[idx] == NULL) {
1370 if (idx == st_parm->max_history)
1375 /* copy temp_h[] to st_parm->history[] */
1376 for (i = 0; i < st_parm->max_history;) {
1381 if (idx == st_parm->max_history)
1383 line_len = strlen(line);
1384 if (line_len >= MAX_LINELEN)
1385 line[MAX_LINELEN-1] = '\0';
1386 st_parm->history[i++] = line;
1388 st_parm->cnt_history = i;
1389 if (ENABLE_FEATURE_EDITING_SAVE_ON_EXIT)
1390 st_parm->cnt_history_in_file = i;
1394 # if ENABLE_FEATURE_EDITING_SAVE_ON_EXIT
1395 void save_history(line_input_t *st)
1401 if (st->cnt_history <= st->cnt_history_in_file)
1404 fp = fopen(st->hist_file, "a");
1408 line_input_t *st_temp;
1410 for (i = st->cnt_history_in_file; i < st->cnt_history; i++)
1411 fprintf(fp, "%s\n", st->history[i]);
1414 /* we may have concurrently written entries from others.
1416 st_temp = new_line_input_t(st->flags);
1417 st_temp->hist_file = st->hist_file;
1418 st_temp->max_history = st->max_history;
1419 load_history(st_temp);
1421 /* write out temp file and replace hist_file atomically */
1422 new_name = xasprintf("%s.%u.new", st->hist_file, (int) getpid());
1423 fd = open(new_name, O_WRONLY | O_CREAT | O_TRUNC, 0600);
1425 fp = xfdopen_for_write(fd);
1426 for (i = 0; i < st_temp->cnt_history; i++)
1427 fprintf(fp, "%s\n", st_temp->history[i]);
1429 if (rename(new_name, st->hist_file) == 0)
1430 st->cnt_history_in_file = st_temp->cnt_history;
1433 free_line_input_t(st_temp);
1437 static void save_history(char *str)
1442 if (!state->hist_file)
1445 fd = open(state->hist_file, O_WRONLY | O_CREAT | O_APPEND, 0600);
1448 xlseek(fd, 0, SEEK_END); /* paranoia */
1450 str[len] = '\n'; /* we (try to) do atomic write */
1451 len2 = full_write(fd, str, len + 1);
1454 if (len2 != len + 1)
1455 return; /* "wtf?" */
1457 /* did we write so much that history file needs trimming? */
1458 state->cnt_history_in_file++;
1459 if (state->cnt_history_in_file > state->max_history * 4) {
1461 line_input_t *st_temp;
1463 /* we may have concurrently written entries from others.
1465 st_temp = new_line_input_t(state->flags);
1466 st_temp->hist_file = state->hist_file;
1467 st_temp->max_history = state->max_history;
1468 load_history(st_temp);
1470 /* write out temp file and replace hist_file atomically */
1471 new_name = xasprintf("%s.%u.new", state->hist_file, (int) getpid());
1472 fd = open(new_name, O_WRONLY | O_CREAT | O_TRUNC, 0600);
1477 fp = xfdopen_for_write(fd);
1478 for (i = 0; i < st_temp->cnt_history; i++)
1479 fprintf(fp, "%s\n", st_temp->history[i]);
1481 if (rename(new_name, state->hist_file) == 0)
1482 state->cnt_history_in_file = st_temp->cnt_history;
1485 free_line_input_t(st_temp);
1490 # define load_history(a) ((void)0)
1491 # define save_history(a) ((void)0)
1492 # endif /* FEATURE_COMMAND_SAVEHISTORY */
1494 static void remember_in_history(char *str)
1498 if (!(state->flags & DO_HISTORY))
1502 i = state->cnt_history;
1503 /* Don't save dupes */
1504 if (i && strcmp(state->history[i-1], str) == 0)
1507 free(state->history[state->max_history]); /* redundant, paranoia */
1508 state->history[state->max_history] = NULL; /* redundant, paranoia */
1510 /* If history[] is full, remove the oldest command */
1511 /* we need to keep history[state->max_history] empty, hence >=, not > */
1512 if (i >= state->max_history) {
1513 free(state->history[0]);
1514 for (i = 0; i < state->max_history-1; i++)
1515 state->history[i] = state->history[i+1];
1516 /* i == state->max_history-1 */
1517 # if ENABLE_FEATURE_EDITING_SAVE_ON_EXIT
1518 if (state->cnt_history_in_file)
1519 state->cnt_history_in_file--;
1522 /* i <= state->max_history-1 */
1523 state->history[i++] = xstrdup(str);
1524 /* i <= state->max_history */
1525 state->cur_history = i;
1526 state->cnt_history = i;
1527 # if ENABLE_FEATURE_EDITING_SAVEHISTORY && !ENABLE_FEATURE_EDITING_SAVE_ON_EXIT
1532 #else /* MAX_HISTORY == 0 */
1533 # define remember_in_history(a) ((void)0)
1534 #endif /* MAX_HISTORY */
1537 #if ENABLE_FEATURE_EDITING_VI
1539 * vi mode implemented 2005 by Paul Fox <pgf@foxharp.boston.ma.us>
1542 vi_Word_motion(int eat)
1544 CHAR_T *command = command_ps;
1546 while (cursor < command_len && !BB_isspace(command[cursor]))
1548 if (eat) while (cursor < command_len && BB_isspace(command[cursor]))
1553 vi_word_motion(int eat)
1555 CHAR_T *command = command_ps;
1557 if (BB_isalnum(command[cursor]) || command[cursor] == '_') {
1558 while (cursor < command_len
1559 && (BB_isalnum(command[cursor+1]) || command[cursor+1] == '_')
1563 } else if (BB_ispunct(command[cursor])) {
1564 while (cursor < command_len && BB_ispunct(command[cursor+1]))
1568 if (cursor < command_len)
1572 while (cursor < command_len && BB_isspace(command[cursor]))
1580 CHAR_T *command = command_ps;
1583 while (cursor < command_len && BB_isspace(command[cursor]))
1585 while (cursor < command_len-1 && !BB_isspace(command[cursor+1]))
1592 CHAR_T *command = command_ps;
1594 if (cursor >= command_len-1)
1597 while (cursor < command_len-1 && BB_isspace(command[cursor]))
1599 if (cursor >= command_len-1)
1601 if (BB_isalnum(command[cursor]) || command[cursor] == '_') {
1602 while (cursor < command_len-1
1603 && (BB_isalnum(command[cursor+1]) || command[cursor+1] == '_')
1607 } else if (BB_ispunct(command[cursor])) {
1608 while (cursor < command_len-1 && BB_ispunct(command[cursor+1]))
1614 vi_Back_motion(void)
1616 CHAR_T *command = command_ps;
1618 while (cursor > 0 && BB_isspace(command[cursor-1]))
1620 while (cursor > 0 && !BB_isspace(command[cursor-1]))
1625 vi_back_motion(void)
1627 CHAR_T *command = command_ps;
1632 while (cursor > 0 && BB_isspace(command[cursor]))
1636 if (BB_isalnum(command[cursor]) || command[cursor] == '_') {
1638 && (BB_isalnum(command[cursor-1]) || command[cursor-1] == '_')
1642 } else if (BB_ispunct(command[cursor])) {
1643 while (cursor > 0 && BB_ispunct(command[cursor-1]))
1649 /* Modelled after bash 4.0 behavior of Ctrl-<arrow> */
1650 static void ctrl_left(void)
1652 CHAR_T *command = command_ps;
1660 c = command[cursor];
1661 if (c != ' ' && !BB_ispunct(c)) {
1662 /* we reached a "word" delimited by spaces/punct.
1663 * go to its beginning */
1665 c = command[cursor - 1];
1666 if (c == ' ' || BB_ispunct(c))
1676 static void ctrl_right(void)
1678 CHAR_T *command = command_ps;
1683 c = command[cursor];
1686 if (c != ' ' && !BB_ispunct(c)) {
1687 /* we reached a "word" delimited by spaces/punct.
1688 * go to its end + 1 */
1691 c = command[cursor];
1692 if (c == BB_NUL || c == ' ' || BB_ispunct(c))
1703 * read_line_input and its helpers
1706 #if ENABLE_FEATURE_EDITING_ASK_TERMINAL
1707 static void ask_terminal(void)
1709 /* Ask terminal where is the cursor now.
1710 * lineedit_read_key handles response and corrects
1711 * our idea of current cursor position.
1712 * Testcase: run "echo -n long_line_long_line_long_line",
1713 * then type in a long, wrapping command and try to
1714 * delete it using backspace key.
1715 * Note: we print it _after_ prompt, because
1716 * prompt may contain CR. Example: PS1='\[\r\n\]\w '
1718 /* Problem: if there is buffered input on stdin,
1719 * the response will be delivered later,
1720 * possibly to an unsuspecting application.
1721 * Testcase: "sleep 1; busybox ash" + press and hold [Enter].
1723 * ~/srcdevel/bbox/fix/busybox.t4 #
1724 * ~/srcdevel/bbox/fix/busybox.t4 #
1725 * ^[[59;34~/srcdevel/bbox/fix/busybox.t4 # <-- garbage
1726 * ~/srcdevel/bbox/fix/busybox.t4 #
1728 * Checking for input with poll only makes the race narrower,
1729 * I still can trigger it. Strace:
1731 * write(1, "~/srcdevel/bbox/fix/busybox.t4 # ", 33) = 33
1732 * poll([{fd=0, events=POLLIN}], 1, 0) = 0 (Timeout) <-- no input exists
1733 * write(1, "\33[6n", 4) = 4 <-- send the ESC sequence, quick!
1734 * poll([{fd=0, events=POLLIN}], 1, -1) = 1 ([{fd=0, revents=POLLIN}])
1735 * read(0, "\n", 1) = 1 <-- oh crap, user's input got in first
1739 pfd.fd = STDIN_FILENO;
1740 pfd.events = POLLIN;
1741 if (safe_poll(&pfd, 1, 0) == 0) {
1742 S.sent_ESC_br6n = 1;
1743 fputs(ESC"[6n", stdout);
1744 fflush_all(); /* make terminal see it ASAP! */
1748 #define ask_terminal() ((void)0)
1751 #if !ENABLE_FEATURE_EDITING_FANCY_PROMPT
1752 static void parse_and_put_prompt(const char *prmt_ptr)
1754 cmdedit_prompt = prmt_ptr;
1755 cmdedit_prmt_len = strlen(prmt_ptr);
1759 static void parse_and_put_prompt(const char *prmt_ptr)
1762 size_t cur_prmt_len = 0;
1763 char flg_not_length = '[';
1764 char *prmt_mem_ptr = xzalloc(1);
1765 # if ENABLE_USERNAME_OR_HOMEDIR
1766 char *cwd_buf = NULL;
1768 char timebuf[sizeof("HH:MM:SS")];
1773 cmdedit_prmt_len = 0;
1775 cbuf[1] = '\0'; /* never changes */
1778 char *free_me = NULL;
1786 * Supported via bb_process_escape_sequence:
1787 * \a ASCII bell character (07)
1788 * \e ASCII escape character (033)
1790 * \r carriage return
1792 * \nnn char with octal code nnn
1794 * \$ if the effective UID is 0, a #, otherwise a $
1795 * \w current working directory, with $HOME abbreviated with a tilde
1796 * Note: we do not support $PROMPT_DIRTRIM=n feature
1797 * \W basename of the current working directory, with $HOME abbreviated with a tilde
1798 * \h hostname up to the first '.'
1801 * \[ begin a sequence of non-printing characters
1802 * \] end a sequence of non-printing characters
1803 * \T current time in 12-hour HH:MM:SS format
1804 * \@ current time in 12-hour am/pm format
1805 * \A current time in 24-hour HH:MM format
1806 * \t current time in 24-hour HH:MM:SS format
1807 * (all of the above work as \A)
1809 * \! history number of this command
1810 * \# command number of this command
1811 * \j number of jobs currently managed by the shell
1812 * \l basename of the shell's terminal device name
1813 * \s name of the shell, the basename of $0 (the portion following the final slash)
1814 * \V release of bash, version + patch level (e.g., 2.00.0)
1815 * \d date in "Weekday Month Date" format (e.g., "Tue May 26")
1817 * format is passed to strftime(3).
1818 * An empty format results in a locale-specific time representation.
1819 * The braces are required.
1820 * Mishandled by bb_process_escape_sequence:
1821 * \v version of bash (e.g., 2.00)
1825 if (c != 't') /* don't treat \t as tab */
1826 c = bb_process_escape_sequence(&prmt_ptr);
1827 if (prmt_ptr == cp) {
1833 # if ENABLE_USERNAME_OR_HOMEDIR
1835 pbuf = user_buf ? user_buf : (char*)"";
1840 pbuf = free_me = safe_gethostname();
1842 strchrnul(pbuf, '.')[0] = '\0';
1845 c = (geteuid() == 0 ? '#' : '$');
1847 case 'T': /* 12-hour HH:MM:SS format */
1848 case '@': /* 12-hour am/pm format */
1849 case 'A': /* 24-hour HH:MM format */
1850 case 't': /* 24-hour HH:MM:SS format */
1851 /* We show all of them as 24-hour HH:MM */
1852 strftime_HHMMSS(timebuf, sizeof(timebuf), NULL)[-3] = '\0';
1855 # if ENABLE_USERNAME_OR_HOMEDIR
1856 case 'w': /* current dir */
1857 case 'W': /* basename of cur dir */
1859 cwd_buf = xrealloc_getcwd_or_warn(NULL);
1861 cwd_buf = (char *)bb_msg_unknown;
1863 /* /home/user[/something] -> ~[/something] */
1864 l = strlen(home_pwd_buf);
1866 && strncmp(home_pwd_buf, cwd_buf, l) == 0
1867 && (cwd_buf[l] == '/' || cwd_buf[l] == '\0')
1870 overlapping_strcpy(cwd_buf + 1, cwd_buf + l);
1877 cp = strrchr(pbuf, '/');
1879 pbuf = (char*)cp + 1;
1882 // bb_process_escape_sequence does this now:
1883 // case 'e': case 'E': /* \e \E = \033 */
1886 case 'x': case 'X': {
1888 for (l = 0; l < 3;) {
1890 buf2[l++] = *prmt_ptr;
1892 h = strtoul(buf2, &pbuf, 16);
1893 if (h > UCHAR_MAX || (pbuf - buf2) < l) {
1899 c = (char)strtoul(buf2, NULL, 16);
1906 if (c == flg_not_length) {
1907 flg_not_length = (flg_not_length == '[' ? ']' : '[');
1915 cur_prmt_len = strlen(pbuf);
1916 prmt_len += cur_prmt_len;
1917 if (flg_not_length != ']')
1918 cmdedit_prmt_len += cur_prmt_len;
1919 prmt_mem_ptr = strcat(xrealloc(prmt_mem_ptr, prmt_len+1), pbuf);
1923 # if ENABLE_USERNAME_OR_HOMEDIR
1924 if (cwd_buf != (char *)bb_msg_unknown)
1927 cmdedit_prompt = prmt_mem_ptr;
1932 static void cmdedit_setwidth(unsigned w, int redraw_flg)
1936 /* new y for current cursor */
1937 int new_y = (cursor + cmdedit_prmt_len) / w;
1939 redraw((new_y >= cmdedit_y ? new_y : cmdedit_y), command_len - cursor);
1944 static void win_changed(int nsig)
1946 int sv_errno = errno;
1949 get_terminal_width_height(0, &width, NULL);
1950 //FIXME: cmdedit_setwidth() -> redraw() -> printf() -> KABOOM! (we are in signal handler!)
1951 cmdedit_setwidth(width, /*redraw_flg:*/ nsig);
1956 static int lineedit_read_key(char *read_key_buffer, int timeout)
1959 #if ENABLE_UNICODE_SUPPORT
1960 char unicode_buf[MB_CUR_MAX + 1];
1961 int unicode_idx = 0;
1965 /* Wait for input. TIMEOUT = -1 makes read_key wait even
1966 * on nonblocking stdin, TIMEOUT = 50 makes sure we won't
1967 * insist on full MB_CUR_MAX buffer to declare input like
1968 * "\xff\n",pause,"ls\n" invalid and thus won't lose "ls".
1970 * Note: read_key sets errno to 0 on success.
1972 ic = read_key(STDIN_FILENO, read_key_buffer, timeout);
1974 #if ENABLE_UNICODE_SUPPORT
1975 if (errno == EAGAIN && unicode_idx != 0)
1981 #if ENABLE_FEATURE_EDITING_ASK_TERMINAL
1982 if ((int32_t)ic == KEYCODE_CURSOR_POS
1985 S.sent_ESC_br6n = 0;
1986 if (cursor == 0) { /* otherwise it may be bogus */
1987 int col = ((ic >> 32) & 0x7fff) - 1;
1988 if (col > cmdedit_prmt_len) {
1989 cmdedit_x += (col - cmdedit_prmt_len);
1990 while (cmdedit_x >= cmdedit_termw) {
1991 cmdedit_x -= cmdedit_termw;
2000 #if ENABLE_UNICODE_SUPPORT
2001 if (unicode_status == UNICODE_ON) {
2004 if ((int32_t)ic < 0) /* KEYCODE_xxx */
2006 // TODO: imagine sequence like: 0xff,<left-arrow>: we are currently losing 0xff...
2008 unicode_buf[unicode_idx++] = ic;
2009 unicode_buf[unicode_idx] = '\0';
2010 if (mbstowcs(&wc, unicode_buf, 1) != 1) {
2011 /* Not (yet?) a valid unicode char */
2012 if (unicode_idx < MB_CUR_MAX) {
2017 /* Invalid sequence. Save all "bad bytes" except first */
2018 read_key_ungets(read_key_buffer, unicode_buf + 1, unicode_idx - 1);
2019 # if !ENABLE_UNICODE_PRESERVE_BROKEN
2020 ic = CONFIG_SUBST_WCHAR;
2022 ic = unicode_mark_raw_byte(unicode_buf[0]);
2025 /* Valid unicode char, return its code */
2036 #if ENABLE_UNICODE_BIDI_SUPPORT
2037 static int isrtl_str(void)
2041 while (idx < command_len && unicode_bidi_is_neutral_wchar(command_ps[idx]))
2043 return unicode_bidi_isrtl(command_ps[idx]);
2046 # define isrtl_str() 0
2049 /* leave out the "vi-mode"-only case labels if vi editing isn't
2051 #define vi_case(caselabel) IF_FEATURE_EDITING_VI(case caselabel)
2053 /* convert uppercase ascii to equivalent control char, for readability */
2055 #define CTRL(a) ((a) & ~0x40)
2058 VI_CMDMODE_BIT = 0x40000000,
2059 /* 0x80000000 bit flags KEYCODE_xxx */
2062 #if ENABLE_FEATURE_REVERSE_SEARCH
2063 /* Mimic readline Ctrl-R reverse history search.
2064 * When invoked, it shows the following prompt:
2065 * (reverse-i-search)'': user_input [cursor pos unchanged by Ctrl-R]
2066 * and typing results in search being performed:
2067 * (reverse-i-search)'tmp': cd /tmp [cursor under t in /tmp]
2068 * Search is performed by looking at progressively older lines in history.
2069 * Ctrl-R again searches for the next match in history.
2070 * Backspace deletes last matched char.
2071 * Control keys exit search and return to normal editing (at current history line).
2073 static int32_t reverse_i_search(void)
2075 char match_buf[128]; /* for user input */
2076 char read_key_buffer[KEYCODE_BUFFER_SIZE];
2077 const char *matched_history_line;
2078 const char *saved_prompt;
2081 matched_history_line = NULL;
2082 read_key_buffer[0] = 0;
2083 match_buf[0] = '\0';
2085 /* Save and replace the prompt */
2086 saved_prompt = cmdedit_prompt;
2091 unsigned match_buf_len = strlen(match_buf);
2094 //FIXME: correct timeout?
2095 ic = lineedit_read_key(read_key_buffer, -1);
2098 case CTRL('R'): /* searching for the next match */
2104 if (unicode_status == UNICODE_ON) {
2105 while (match_buf_len != 0) {
2106 uint8_t c = match_buf[--match_buf_len];
2107 if ((c & 0xc0) != 0x80) /* start of UTF-8 char? */
2111 if (match_buf_len != 0)
2114 match_buf[match_buf_len] = '\0';
2119 || (!ENABLE_UNICODE_SUPPORT && ic >= 256)
2120 || (ENABLE_UNICODE_SUPPORT && ic >= VI_CMDMODE_BIT)
2125 /* Append this char */
2126 #if ENABLE_UNICODE_SUPPORT
2127 if (unicode_status == UNICODE_ON) {
2128 mbstate_t mbstate = { 0 };
2129 char buf[MB_CUR_MAX + 1];
2130 int len = wcrtomb(buf, ic, &mbstate);
2133 if (match_buf_len + len < sizeof(match_buf))
2134 strcpy(match_buf + match_buf_len, buf);
2138 if (match_buf_len < sizeof(match_buf) - 1) {
2139 match_buf[match_buf_len] = ic;
2140 match_buf[match_buf_len + 1] = '\0';
2145 /* Search in history for match_buf */
2146 h = state->cur_history;
2147 if (ic == CTRL('R'))
2150 if (state->history[h]) {
2151 char *match = strstr(state->history[h], match_buf);
2153 state->cur_history = h;
2154 matched_history_line = state->history[h];
2155 command_len = load_string(matched_history_line);
2156 cursor = match - matched_history_line;
2157 //FIXME: cursor position for Unicode case
2159 free((char*)cmdedit_prompt);
2161 cmdedit_prompt = xasprintf("(reverse-i-search)'%s': ", match_buf);
2162 cmdedit_prmt_len = strlen(cmdedit_prompt);
2170 match_buf[match_buf_len] = '\0';
2175 redraw(cmdedit_y, command_len - cursor);
2179 if (matched_history_line)
2180 command_len = load_string(matched_history_line);
2182 free((char*)cmdedit_prompt);
2183 cmdedit_prompt = saved_prompt;
2184 cmdedit_prmt_len = strlen(cmdedit_prompt);
2185 redraw(cmdedit_y, command_len - cursor);
2191 /* maxsize must be >= 2.
2193 * -1 on read errors or EOF, or on bare Ctrl-D,
2194 * 0 on ctrl-C (the line entered is still returned in 'command'),
2195 * >0 length of input string, including terminating '\n'
2197 int FAST_FUNC read_line_input(line_input_t *st, const char *prompt, char *command, int maxsize, int timeout)
2200 #if ENABLE_FEATURE_TAB_COMPLETION
2201 smallint lastWasTab = 0;
2203 smallint break_out = 0;
2204 #if ENABLE_FEATURE_EDITING_VI
2205 smallint vi_cmdmode = 0;
2207 struct termios initial_settings;
2208 struct termios new_settings;
2209 char read_key_buffer[KEYCODE_BUFFER_SIZE];
2213 if (tcgetattr(STDIN_FILENO, &initial_settings) < 0
2214 || !(initial_settings.c_lflag & ECHO)
2216 /* Happens when e.g. stty -echo was run before */
2217 parse_and_put_prompt(prompt);
2218 /* fflush_all(); - done by parse_and_put_prompt */
2219 if (fgets(command, maxsize, stdin) == NULL)
2220 len = -1; /* EOF or error */
2222 len = strlen(command);
2229 // FIXME: audit & improve this
2230 if (maxsize > MAX_LINELEN)
2231 maxsize = MAX_LINELEN;
2232 S.maxsize = maxsize;
2234 /* With zero flags, no other fields are ever used */
2235 state = st ? st : (line_input_t*) &const_int_0;
2237 # if ENABLE_FEATURE_EDITING_SAVEHISTORY
2238 if (state->hist_file)
2239 if (state->cnt_history == 0)
2240 load_history(state);
2242 if (state->flags & DO_HISTORY)
2243 state->cur_history = state->cnt_history;
2246 /* prepare before init handlers */
2247 cmdedit_y = 0; /* quasireal y, not true if line > xt*yt */
2249 #if ENABLE_UNICODE_SUPPORT
2250 command_ps = xzalloc(maxsize * sizeof(command_ps[0]));
2252 command_ps = command;
2255 #define command command_must_not_be_used
2257 new_settings = initial_settings;
2258 /* ~ICANON: unbuffered input (most c_cc[] are disabled, VMIN/VTIME are enabled) */
2259 /* ~ECHO, ~ECHONL: turn off echoing, including newline echoing */
2260 /* ~ISIG: turn off INTR (ctrl-C), QUIT, SUSP */
2261 new_settings.c_lflag &= ~(ICANON | ECHO | ECHONL | ISIG);
2262 /* reads would block only if < 1 char is available */
2263 new_settings.c_cc[VMIN] = 1;
2264 /* no timeout (reads block forever) */
2265 new_settings.c_cc[VTIME] = 0;
2266 /* Should be not needed if ISIG is off: */
2267 /* Turn off CTRL-C */
2268 /* new_settings.c_cc[VINTR] = _POSIX_VDISABLE; */
2269 tcsetattr_stdin_TCSANOW(&new_settings);
2271 #if ENABLE_USERNAME_OR_HOMEDIR
2273 struct passwd *entry;
2275 entry = getpwuid(geteuid());
2277 user_buf = xstrdup(entry->pw_name);
2278 home_pwd_buf = xstrdup(entry->pw_dir);
2284 for (i = 0; i <= state->max_history; i++)
2285 bb_error_msg("history[%d]:'%s'", i, state->history[i]);
2286 bb_error_msg("cur_history:%d cnt_history:%d", state->cur_history, state->cnt_history);
2289 /* Print out the command prompt, optionally ask where cursor is */
2290 parse_and_put_prompt(prompt);
2293 /* Install window resize handler (NB: after *all* init is complete) */
2294 //FIXME: save entire sigaction!
2295 previous_SIGWINCH_handler = signal(SIGWINCH, win_changed);
2296 win_changed(0); /* get initial window size */
2298 read_key_buffer[0] = 0;
2301 * The emacs and vi modes share much of the code in the big
2302 * command loop. Commands entered when in vi's command mode
2303 * (aka "escape mode") get an extra bit added to distinguish
2304 * them - this keeps them from being self-inserted. This
2305 * clutters the big switch a bit, but keeps all the code
2311 ic = ic_raw = lineedit_read_key(read_key_buffer, timeout);
2313 #if ENABLE_FEATURE_REVERSE_SEARCH
2316 #if ENABLE_FEATURE_EDITING_VI
2319 /* btw, since KEYCODE_xxx are all < 0, this doesn't
2320 * change ic if it contains one of them: */
2321 ic |= VI_CMDMODE_BIT;
2328 vi_case('\n'|VI_CMDMODE_BIT:)
2329 vi_case('\r'|VI_CMDMODE_BIT:)
2335 vi_case('0'|VI_CMDMODE_BIT:)
2336 /* Control-a -- Beginning of line */
2337 input_backward(cursor);
2340 vi_case('h'|VI_CMDMODE_BIT:)
2341 vi_case('\b'|VI_CMDMODE_BIT:) /* ^H */
2342 vi_case('\x7f'|VI_CMDMODE_BIT:) /* DEL */
2343 input_backward(1); /* Move back one character */
2346 vi_case('$'|VI_CMDMODE_BIT:)
2347 /* Control-e -- End of line */
2348 put_till_end_and_adv_cursor();
2351 vi_case('l'|VI_CMDMODE_BIT:)
2352 vi_case(' '|VI_CMDMODE_BIT:)
2353 input_forward(); /* Move forward one character */
2356 case '\x7f': /* DEL */
2362 case KEYCODE_DELETE:
2368 #if ENABLE_FEATURE_TAB_COMPLETION
2370 input_tab(&lastWasTab);
2374 /* Control-k -- clear to end of line */
2375 command_ps[cursor] = BB_NUL;
2376 command_len = cursor;
2377 printf(SEQ_CLEAR_TILL_END_OF_SCREEN);
2380 vi_case(CTRL('L')|VI_CMDMODE_BIT:)
2381 /* Control-l -- clear screen */
2382 printf(ESC"[H"); /* cursor to top,left */
2383 redraw(0, command_len - cursor);
2387 vi_case(CTRL('N')|VI_CMDMODE_BIT:)
2388 vi_case('j'|VI_CMDMODE_BIT:)
2389 /* Control-n -- Get next command in history */
2390 if (get_next_history())
2394 vi_case(CTRL('P')|VI_CMDMODE_BIT:)
2395 vi_case('k'|VI_CMDMODE_BIT:)
2396 /* Control-p -- Get previous command from history */
2397 if (get_previous_history())
2402 vi_case(CTRL('U')|VI_CMDMODE_BIT:)
2403 /* Control-U -- Clear line before cursor */
2405 command_len -= cursor;
2406 memmove(command_ps, command_ps + cursor,
2407 (command_len + 1) * sizeof(command_ps[0]));
2408 redraw(cmdedit_y, command_len);
2412 vi_case(CTRL('W')|VI_CMDMODE_BIT:)
2413 /* Control-W -- Remove the last word */
2414 while (cursor > 0 && BB_isspace(command_ps[cursor-1]))
2416 while (cursor > 0 && !BB_isspace(command_ps[cursor-1]))
2419 #if ENABLE_FEATURE_REVERSE_SEARCH
2421 ic = ic_raw = reverse_i_search();
2425 #if ENABLE_FEATURE_EDITING_VI
2426 case 'i'|VI_CMDMODE_BIT:
2429 case 'I'|VI_CMDMODE_BIT:
2430 input_backward(cursor);
2433 case 'a'|VI_CMDMODE_BIT:
2437 case 'A'|VI_CMDMODE_BIT:
2438 put_till_end_and_adv_cursor();
2441 case 'x'|VI_CMDMODE_BIT:
2444 case 'X'|VI_CMDMODE_BIT:
2450 case 'W'|VI_CMDMODE_BIT:
2453 case 'w'|VI_CMDMODE_BIT:
2456 case 'E'|VI_CMDMODE_BIT:
2459 case 'e'|VI_CMDMODE_BIT:
2462 case 'B'|VI_CMDMODE_BIT:
2465 case 'b'|VI_CMDMODE_BIT:
2468 case 'C'|VI_CMDMODE_BIT:
2471 case 'D'|VI_CMDMODE_BIT:
2474 case 'c'|VI_CMDMODE_BIT:
2477 case 'd'|VI_CMDMODE_BIT: {
2480 ic = lineedit_read_key(read_key_buffer, timeout);
2481 if (errno) /* error */
2482 goto return_error_indicator;
2483 if (ic == ic_raw) { /* "cc", "dd" */
2484 input_backward(cursor);
2496 case 'w': /* "dw", "cw" */
2497 vi_word_motion(vi_cmdmode);
2499 case 'W': /* 'dW', 'cW' */
2500 vi_Word_motion(vi_cmdmode);
2502 case 'e': /* 'de', 'ce' */
2506 case 'E': /* 'dE', 'cE' */
2512 input_backward(cursor - sc);
2513 while (nc-- > cursor)
2516 case 'b': /* "db", "cb" */
2517 case 'B': /* implemented as B */
2522 while (sc-- > cursor)
2525 case ' ': /* "d ", "c " */
2528 case '$': /* "d$", "c$" */
2530 while (cursor < command_len)
2536 case 'p'|VI_CMDMODE_BIT:
2539 case 'P'|VI_CMDMODE_BIT:
2542 case 'r'|VI_CMDMODE_BIT:
2543 //FIXME: unicode case?
2544 ic = lineedit_read_key(read_key_buffer, timeout);
2545 if (errno) /* error */
2546 goto return_error_indicator;
2547 if (ic < ' ' || ic > 255) {
2550 command_ps[cursor] = ic;
2555 case '\x1b': /* ESC */
2556 if (state->flags & VI_MODE) {
2557 /* insert mode --> command mode */
2561 /* Handle a few ESC-<key> combinations the same way
2562 * standard readline bindings (IOW: bash) do.
2563 * Often, Alt-<key> generates ESC-<key>.
2565 ic = lineedit_read_key(read_key_buffer, timeout);
2567 //case KEYCODE_LEFT: - bash doesn't do this
2571 //case KEYCODE_RIGHT: - bash doesn't do this
2575 //case KEYCODE_DELETE: - bash doesn't do this
2576 case 'd': /* Alt-D */
2578 /* Delete word forward */
2579 int nc, sc = cursor;
2587 case '\b': /* Alt-Backspace(?) */
2588 case '\x7f': /* Alt-Backspace(?) */
2589 //case 'w': - bash doesn't do this
2591 /* Delete word backward */
2594 while (sc-- > cursor)
2600 #endif /* FEATURE_COMMAND_EDITING_VI */
2604 if (get_previous_history())
2609 if (!get_next_history())
2612 /* Rewrite the line with the selected history item */
2613 /* change command */
2614 command_len = load_string(state->history[state->cur_history] ?
2615 state->history[state->cur_history] : "");
2616 /* redraw and go to eol (bol, in vi) */
2617 redraw(cmdedit_y, (state->flags & VI_MODE) ? 9999 : 0);
2626 case KEYCODE_CTRL_LEFT:
2627 case KEYCODE_ALT_LEFT: /* bash doesn't do it */
2630 case KEYCODE_CTRL_RIGHT:
2631 case KEYCODE_ALT_RIGHT: /* bash doesn't do it */
2635 input_backward(cursor);
2638 put_till_end_and_adv_cursor();
2642 if (initial_settings.c_cc[VINTR] != 0
2643 && ic_raw == initial_settings.c_cc[VINTR]
2645 /* Ctrl-C (usually) - stop gathering input */
2648 break_out = -1; /* "do not append '\n'" */
2651 if (initial_settings.c_cc[VEOF] != 0
2652 && ic_raw == initial_settings.c_cc[VEOF]
2654 /* Ctrl-D (usually) - delete one character,
2655 * or exit if len=0 and no chars to delete */
2656 if (command_len == 0) {
2659 case -1: /* error (e.g. EIO when tty is destroyed) */
2660 IF_FEATURE_EDITING_VI(return_error_indicator:)
2661 break_out = command_len = -1;
2667 // /* Control-V -- force insert of next char */
2668 // if (c == CTRL('V')) {
2669 // if (safe_read(STDIN_FILENO, &c, 1) < 1)
2670 // goto return_error_indicator;
2677 || (!ENABLE_UNICODE_SUPPORT && ic >= 256)
2678 || (ENABLE_UNICODE_SUPPORT && ic >= VI_CMDMODE_BIT)
2680 /* If VI_CMDMODE_BIT is set, ic is >= 256
2681 * and vi mode ignores unexpected chars.
2682 * Otherwise, we are here if ic is a
2683 * control char or an unhandled ESC sequence,
2684 * which is also ignored.
2688 if ((int)command_len >= (maxsize - 2)) {
2689 /* Not enough space for the char and EOL */
2694 if (cursor == (command_len - 1)) {
2695 /* We are at the end, append */
2696 command_ps[cursor] = ic;
2697 command_ps[cursor + 1] = BB_NUL;
2698 put_cur_glyph_and_inc_cursor();
2699 if (unicode_bidi_isrtl(ic))
2702 /* In the middle, insert */
2705 memmove(command_ps + sc + 1, command_ps + sc,
2706 (command_len - sc) * sizeof(command_ps[0]));
2707 command_ps[sc] = ic;
2708 /* is right-to-left char, or neutral one (e.g. comma) was just added to rtl text? */
2711 put_till_end_and_adv_cursor();
2712 /* to prev x pos + 1 */
2713 input_backward(cursor - sc);
2721 #if ENABLE_FEATURE_TAB_COMPLETION
2727 #if ENABLE_FEATURE_EDITING_ASK_TERMINAL
2728 if (S.sent_ESC_br6n) {
2729 /* "sleep 1; busybox ash" + hold [Enter] to trigger.
2730 * We sent "ESC [ 6 n", but got '\n' first, and
2731 * KEYCODE_CURSOR_POS response is now buffered from terminal.
2732 * It's bad already and not much can be done with it
2733 * (it _will_ be visible for the next process to read stdin),
2734 * but without this delay it even shows up on the screen
2735 * as garbage because we restore echo settings with tcsetattr
2736 * before it comes in. UGLY!
2742 /* End of bug-catching "command_must_not_be_used" trick */
2745 #if ENABLE_UNICODE_SUPPORT
2747 if (command_len > 0)
2748 command_len = save_string(command, maxsize - 1);
2752 if (command_len > 0)
2753 remember_in_history(command);
2755 if (break_out > 0) {
2756 command[command_len++] = '\n';
2757 command[command_len] = '\0';
2760 #if ENABLE_FEATURE_TAB_COMPLETION
2761 free_tab_completion_data();
2764 /* restore initial_settings */
2765 tcsetattr_stdin_TCSANOW(&initial_settings);
2766 /* restore SIGWINCH handler */
2767 signal(SIGWINCH, previous_SIGWINCH_handler);
2773 return len; /* can't return command_len, DEINIT_S() destroys it */
2776 #else /* !FEATURE_EDITING */
2778 #undef read_line_input
2779 int FAST_FUNC read_line_input(const char* prompt, char* command, int maxsize)
2781 fputs(prompt, stdout);
2783 if (!fgets(command, maxsize, stdin))
2785 return strlen(command);
2788 #endif /* !FEATURE_EDITING */
2799 const char *applet_name = "debug stuff usage";
2801 int main(int argc, char **argv)
2803 char buff[MAX_LINELEN];
2805 #if ENABLE_FEATURE_EDITING_FANCY_PROMPT
2806 "\\[\\033[32;1m\\]\\u@\\[\\x1b[33;1m\\]\\h:"
2807 "\\[\\033[34;1m\\]\\w\\[\\033[35;1m\\] "
2808 "\\!\\[\\e[36;1m\\]\\$ \\[\\E[0m\\]";
2815 l = read_line_input(prompt, buff);
2816 if (l <= 0 || buff[l-1] != '\n')
2819 printf("*** read_line_input() returned line =%s=\n", buff);
2821 printf("*** read_line_input() detect ^D\n");