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\] '
42 * Unicode in PS1 is not fully supported: prompt length calulation is wrong,
43 * resulting in line wrap problems with long (multi-line) input.
45 * Multi-line PS1 (e.g. PS1="\n[\w]\n$ ") has problems with history
46 * browsing: up/down arrows result in scrolling.
47 * It stems from simplistic "cmdedit_y = cmdedit_prmt_len / cmdedit_termw"
48 * calculation of how many lines the prompt takes.
51 #include "NUM_APPLETS.h"
53 #ifndef _POSIX_VDISABLE
54 # define _POSIX_VDISABLE '\0'
59 # define ENABLE_FEATURE_EDITING 0
60 # define ENABLE_FEATURE_TAB_COMPLETION 0
61 # define ENABLE_FEATURE_USERNAME_COMPLETION 0
65 /* Entire file (except TESTing part) sits inside this #if */
66 #if ENABLE_FEATURE_EDITING
69 #define ENABLE_USERNAME_OR_HOMEDIR \
70 (ENABLE_FEATURE_USERNAME_COMPLETION || ENABLE_FEATURE_EDITING_FANCY_PROMPT)
71 #define IF_USERNAME_OR_HOMEDIR(...)
72 #if ENABLE_USERNAME_OR_HOMEDIR
73 # undef IF_USERNAME_OR_HOMEDIR
74 # define IF_USERNAME_OR_HOMEDIR(...) __VA_ARGS__
79 #if ENABLE_UNICODE_SUPPORT
80 # define BB_NUL ((wchar_t)0)
81 # define CHAR_T wchar_t
82 static bool BB_isspace(CHAR_T c) { return ((unsigned)c < 256 && isspace(c)); }
83 # if ENABLE_FEATURE_EDITING_VI
84 static bool BB_isalnum_or_underscore(CHAR_T c) {
85 return ((unsigned)c < 256 && isalnum(c)) || c == '_';
88 static bool BB_ispunct(CHAR_T c) { return ((unsigned)c < 256 && ispunct(c)); }
93 # define isspace isspace_must_not_be_used
94 # define isalnum isalnum_must_not_be_used
95 # define ispunct ispunct_must_not_be_used
96 # define isprint isprint_must_not_be_used
100 # define BB_isspace(c) isspace(c)
101 # if ENABLE_FEATURE_EDITING_VI
102 static bool BB_isalnum_or_underscore(CHAR_T c) {
103 return ((unsigned)c < 256 && isalnum(c)) || c == '_';
106 # define BB_ispunct(c) ispunct(c)
108 #if ENABLE_UNICODE_PRESERVE_BROKEN
109 # define unicode_mark_raw_byte(wc) ((wc) | 0x20000000)
110 # define unicode_is_raw_byte(wc) ((wc) & 0x20000000)
112 # define unicode_is_raw_byte(wc) 0
118 #define SEQ_CLEAR_TILL_END_OF_SCREEN ESC"[J"
119 //#define SEQ_CLEAR_TILL_END_OF_LINE ESC"[K"
123 MAX_LINELEN = CONFIG_FEATURE_EDITING_MAX_LEN < 0x7ff0
124 ? CONFIG_FEATURE_EDITING_MAX_LEN
128 #if ENABLE_USERNAME_OR_HOMEDIR
129 static const char null_str[] ALIGN1 = "";
132 /* We try to minimize both static and stack usage. */
133 struct lineedit_statics {
136 volatile unsigned cmdedit_termw; /* = 80; */ /* actual terminal width */
137 sighandler_t previous_SIGWINCH_handler;
139 unsigned cmdedit_x; /* real x (col) terminal position */
140 unsigned cmdedit_y; /* pseudoreal y (row) terminal position */
141 unsigned cmdedit_prmt_len; /* length of prompt (without colors etc) */
144 int command_len; /* must be signed */
145 /* signed maxsize: we want x in "if (x > S.maxsize)"
146 * to _not_ be promoted to unsigned */
150 const char *cmdedit_prompt;
152 #if ENABLE_USERNAME_OR_HOMEDIR
154 char *home_pwd_buf; /* = (char*)null_str; */
157 #if ENABLE_FEATURE_TAB_COMPLETION
159 unsigned num_matches;
162 #if ENABLE_FEATURE_EDITING_VI
163 # define DELBUFSIZ 128
165 smallint newdelflag; /* whether delbuf should be reused yet */
166 CHAR_T delbuf[DELBUFSIZ]; /* a place to store deleted characters */
168 #if ENABLE_FEATURE_EDITING_ASK_TERMINAL
169 smallint sent_ESC_br6n;
173 /* See lineedit_ptr_hack.c */
174 extern struct lineedit_statics *const lineedit_ptr_to_statics;
176 #define S (*lineedit_ptr_to_statics)
177 #define state (S.state )
178 #define cmdedit_termw (S.cmdedit_termw )
179 #define previous_SIGWINCH_handler (S.previous_SIGWINCH_handler)
180 #define cmdedit_x (S.cmdedit_x )
181 #define cmdedit_y (S.cmdedit_y )
182 #define cmdedit_prmt_len (S.cmdedit_prmt_len)
183 #define cursor (S.cursor )
184 #define command_len (S.command_len )
185 #define command_ps (S.command_ps )
186 #define cmdedit_prompt (S.cmdedit_prompt )
187 #define user_buf (S.user_buf )
188 #define home_pwd_buf (S.home_pwd_buf )
189 #define matches (S.matches )
190 #define num_matches (S.num_matches )
191 #define delptr (S.delptr )
192 #define newdelflag (S.newdelflag )
193 #define delbuf (S.delbuf )
195 #define INIT_S() do { \
196 (*(struct lineedit_statics**)&lineedit_ptr_to_statics) = xzalloc(sizeof(S)); \
198 cmdedit_termw = 80; \
199 IF_USERNAME_OR_HOMEDIR(home_pwd_buf = (char*)null_str;) \
200 IF_FEATURE_EDITING_VI(delptr = delbuf;) \
203 static void deinit_S(void)
205 #if ENABLE_FEATURE_EDITING_FANCY_PROMPT
206 /* This one is allocated only if FANCY_PROMPT is on
207 * (otherwise it points to verbatim prompt (NOT malloced)) */
208 free((char*)cmdedit_prompt);
210 #if ENABLE_USERNAME_OR_HOMEDIR
212 if (home_pwd_buf != null_str)
215 free(lineedit_ptr_to_statics);
217 #define DEINIT_S() deinit_S()
220 #if ENABLE_UNICODE_SUPPORT
221 static size_t load_string(const char *src)
223 if (unicode_status == UNICODE_ON) {
224 ssize_t len = mbstowcs(command_ps, src, S.maxsize - 1);
227 command_ps[len] = BB_NUL;
231 while (src[i] && i < S.maxsize - 1) {
232 command_ps[i] = src[i];
235 command_ps[i] = BB_NUL;
239 static unsigned save_string(char *dst, unsigned maxsize)
241 if (unicode_status == UNICODE_ON) {
242 # if !ENABLE_UNICODE_PRESERVE_BROKEN
243 ssize_t len = wcstombs(dst, command_ps, maxsize - 1);
253 while (dstpos < maxsize) {
257 /* Convert up to 1st invalid byte (or up to end) */
258 while ((wc = command_ps[srcpos]) != BB_NUL
259 && !unicode_is_raw_byte(wc)
263 command_ps[srcpos] = BB_NUL;
264 n = wcstombs(dst + dstpos, command_ps + n, maxsize - dstpos);
265 if (n < 0) /* should not happen */
268 if (wc == BB_NUL) /* usually is */
271 /* We do have invalid byte here! */
272 command_ps[srcpos] = wc; /* restore it */
274 if (dstpos == maxsize)
276 dst[dstpos++] = (char) wc;
283 while ((dst[i] = command_ps[i]) != 0)
288 /* I thought just fputwc(c, stdout) would work. But no... */
289 static void BB_PUTCHAR(wchar_t c)
291 if (unicode_status == UNICODE_ON) {
292 char buf[MB_CUR_MAX + 1];
293 mbstate_t mbst = { 0 };
294 ssize_t len = wcrtomb(buf, c, &mbst);
300 /* In this case, c is always one byte */
304 # if ENABLE_UNICODE_COMBINING_WCHARS || ENABLE_UNICODE_WIDE_WCHARS
305 static wchar_t adjust_width_and_validate_wc(unsigned *width_adj, wchar_t wc)
307 static wchar_t adjust_width_and_validate_wc(wchar_t wc)
308 # define adjust_width_and_validate_wc(width_adj, wc) \
309 ((*(width_adj))++, adjust_width_and_validate_wc(wc))
314 if (unicode_status == UNICODE_ON) {
315 if (wc > CONFIG_LAST_SUPPORTED_WCHAR) {
316 /* note: also true for unicode_is_raw_byte(wc) */
320 if ((ENABLE_UNICODE_COMBINING_WCHARS && w < 0)
321 || (!ENABLE_UNICODE_COMBINING_WCHARS && w <= 0)
322 || (!ENABLE_UNICODE_WIDE_WCHARS && w > 1)
326 wc = CONFIG_SUBST_WCHAR;
330 # if ENABLE_UNICODE_COMBINING_WCHARS || ENABLE_UNICODE_WIDE_WCHARS
336 static size_t load_string(const char *src)
338 safe_strncpy(command_ps, src, S.maxsize);
339 return strlen(command_ps);
341 # if ENABLE_FEATURE_TAB_COMPLETION
342 static void save_string(char *dst, unsigned maxsize)
344 safe_strncpy(dst, command_ps, maxsize);
347 # define BB_PUTCHAR(c) bb_putchar(c)
348 /* Should never be called: */
349 int adjust_width_and_validate_wc(unsigned *width_adj, int wc);
353 /* Put 'command_ps[cursor]', cursor++.
354 * Advance cursor on screen. If we reached right margin, scroll text up
355 * and remove terminal margin effect by printing 'next_char' */
356 #define HACK_FOR_WRONG_WIDTH 1
357 static void put_cur_glyph_and_inc_cursor(void)
359 CHAR_T c = command_ps[cursor];
364 /* erase character after end of input string */
367 /* advance cursor only if we aren't at the end yet */
369 if (unicode_status == UNICODE_ON) {
370 IF_UNICODE_WIDE_WCHARS(width = cmdedit_x;)
371 c = adjust_width_and_validate_wc(&cmdedit_x, c);
372 IF_UNICODE_WIDE_WCHARS(width = cmdedit_x - width;)
378 ofs_to_right = cmdedit_x - cmdedit_termw;
379 if (!ENABLE_UNICODE_WIDE_WCHARS || ofs_to_right <= 0) {
380 /* c fits on this line */
384 if (ofs_to_right >= 0) {
385 /* we go to the next line */
386 #if HACK_FOR_WRONG_WIDTH
387 /* This works better if our idea of term width is wrong
388 * and it is actually wider (often happens on serial lines).
389 * Printing CR,LF *forces* cursor to next line.
390 * OTOH if terminal width is correct AND terminal does NOT
391 * have automargin (IOW: it is moving cursor to next line
392 * by itself (which is wrong for VT-10x terminals)),
393 * this will break things: there will be one extra empty line */
394 puts("\r"); /* + implicit '\n' */
396 /* VT-10x terminals don't wrap cursor to next line when last char
397 * on the line is printed - cursor stays "over" this char.
398 * Need to print _next_ char too (first one to appear on next line)
399 * to make cursor move down to next line.
401 /* Works ok only if cmdedit_termw is correct. */
402 c = command_ps[cursor];
409 if (!ENABLE_UNICODE_WIDE_WCHARS || ofs_to_right == 0) {
411 } else { /* ofs_to_right > 0 */
412 /* wide char c didn't fit on prev line */
419 /* Move to end of line (by printing all chars till the end) */
420 static void put_till_end_and_adv_cursor(void)
422 while (cursor < command_len)
423 put_cur_glyph_and_inc_cursor();
426 /* Go to the next line */
427 static void goto_new_line(void)
429 put_till_end_and_adv_cursor();
434 static void beep(void)
439 static void put_prompt(void)
443 fputs(cmdedit_prompt, stdout);
446 w = cmdedit_termw; /* read volatile var once */
447 cmdedit_y = cmdedit_prmt_len / w; /* new quasireal y */
448 cmdedit_x = cmdedit_prmt_len % w;
451 /* Move back one character */
452 /* (optimized for slow terminals) */
453 static void input_backward(unsigned num)
461 if ((ENABLE_UNICODE_COMBINING_WCHARS || ENABLE_UNICODE_WIDE_WCHARS)
462 && unicode_status == UNICODE_ON
464 /* correct NUM to be equal to _screen_ width */
468 adjust_width_and_validate_wc(&num, command_ps[cursor + n]);
473 if (cmdedit_x >= num) {
476 /* This is longer by 5 bytes on x86.
477 * Also gets miscompiled for ARM users
478 * (busybox.net/bugs/view.php?id=2274).
479 * printf(("\b\b\b\b" + 4) - num);
487 printf(ESC"[%uD", num);
491 /* Need to go one or more lines up */
492 if (ENABLE_UNICODE_WIDE_WCHARS) {
493 /* With wide chars, it is hard to "backtrack"
494 * and reliably figure out where to put cursor.
495 * Example (<> is a wide char; # is an ordinary char, _ cursor):
499 * and user presses left arrow. num = 1, cmdedit_x = 0,
500 * We need to go up one line, and then - how do we know that
501 * we need to go *10* positions to the right? Because
505 * in this situation we need to go *11* positions to the right.
507 * A simpler thing to do is to redraw everything from the start
508 * up to new cursor position (which is already known):
511 /* go to 1st column; go up to first line */
512 printf("\r" ESC"[%uA", cmdedit_y);
515 put_prompt(); /* sets cursor to 0 */
516 while (cursor < sv_cursor)
517 put_cur_glyph_and_inc_cursor();
521 /* num = chars to go back from the beginning of current line: */
523 width = cmdedit_termw; /* read volatile var once */
524 /* num=1...w: one line up, w+1...2w: two, etc: */
525 lines_up = 1 + (num - 1) / width;
526 cmdedit_x = (width * cmdedit_y - num) % width;
527 cmdedit_y -= lines_up;
528 /* go to 1st column; go up */
529 printf("\r" ESC"[%uA", lines_up);
530 /* go to correct column.
531 * xterm, konsole, Linux VT interpret 0 as 1 below! wow.
532 * need to *make sure* we skip it if cmdedit_x == 0 */
534 printf(ESC"[%uC", cmdedit_x);
538 /* draw prompt, editor line, and clear tail */
539 static void redraw(int y, int back_cursor)
541 if (y > 0) /* up y lines */
542 printf(ESC"[%uA", y);
545 put_till_end_and_adv_cursor();
546 printf(SEQ_CLEAR_TILL_END_OF_SCREEN);
547 input_backward(back_cursor);
550 /* Delete the char in front of the cursor, optionally saving it
551 * for later putback */
552 #if !ENABLE_FEATURE_EDITING_VI
553 static void input_delete(void)
554 #define input_delete(save) input_delete()
556 static void input_delete(int save)
561 if (j == (int)command_len)
564 #if ENABLE_FEATURE_EDITING_VI
570 if ((delptr - delbuf) < DELBUFSIZ)
571 *delptr++ = command_ps[j];
575 memmove(command_ps + j, command_ps + j + 1,
576 /* (command_len + 1 [because of NUL]) - (j + 1)
577 * simplified into (command_len - j) */
578 (command_len - j) * sizeof(command_ps[0]));
580 put_till_end_and_adv_cursor();
581 /* Last char is still visible, erase it (and more) */
582 printf(SEQ_CLEAR_TILL_END_OF_SCREEN);
583 input_backward(cursor - j); /* back to old pos cursor */
586 #if ENABLE_FEATURE_EDITING_VI
587 static void put(void)
590 int j = delptr - delbuf;
595 /* open hole and then fill it */
596 memmove(command_ps + cursor + j, command_ps + cursor,
597 (command_len - cursor + 1) * sizeof(command_ps[0]));
598 memcpy(command_ps + cursor, delbuf, j * sizeof(command_ps[0]));
600 put_till_end_and_adv_cursor();
601 input_backward(cursor - ocursor - j + 1); /* at end of new text */
605 /* Delete the char in back of the cursor */
606 static void input_backspace(void)
614 /* Move forward one character */
615 static void input_forward(void)
617 if (cursor < command_len)
618 put_cur_glyph_and_inc_cursor();
621 #if ENABLE_FEATURE_TAB_COMPLETION
624 //needs to be more clever: currently it thinks that "foo\ b<TAB>
625 //matches the file named "foo bar", which is untrue.
626 //Also, perhaps "foo b<TAB> needs to complete to "foo bar" <cursor>,
627 //not "foo bar <cursor>...
629 static void free_tab_completion_data(void)
633 free(matches[--num_matches]);
639 static void add_match(char *matched)
641 matches = xrealloc_vector(matches, 4, num_matches);
642 matches[num_matches] = matched;
646 # if ENABLE_FEATURE_USERNAME_COMPLETION
647 /* Replace "~user/..." with "/homedir/...".
648 * The parameter is malloced, free it or return it
649 * unchanged if no user is matched.
651 static char *username_path_completion(char *ud)
653 struct passwd *entry;
654 char *tilde_name = ud;
658 if (*ud == '/') { /* "~/..." */
662 ud = strchr(ud, '/');
663 *ud = '\0'; /* "~user" */
664 entry = getpwnam(tilde_name + 1);
665 *ud = '/'; /* restore "~user/..." */
667 home = entry->pw_dir;
670 ud = concat_path_file(home, ud);
677 /* ~use<tab> - find all users with this prefix.
678 * Return the length of the prefix used for matching.
680 static NOINLINE unsigned complete_username(const char *ud)
686 userlen = strlen(ud);
689 while ((pw = getpwent()) != NULL) {
690 /* Null usernames should result in all users as possible completions. */
691 if (/* !ud[0] || */ is_prefixed_with(pw->pw_name, ud)) {
692 add_match(xasprintf("~%s/", pw->pw_name));
695 endpwent(); /* don't keep password file open */
699 # endif /* FEATURE_USERNAME_COMPLETION */
707 static int path_parse(char ***p)
714 if (state->flags & WITH_PATH_LOOKUP)
715 pth = state->path_lookup;
717 pth = getenv("PATH");
719 /* PATH="" or PATH=":"? */
720 if (!pth || !pth[0] || LONE_CHAR(pth, ':'))
724 npth = 1; /* path component count */
726 tmp = strchr(tmp, ':');
731 break; /* :<empty> */
735 *p = res = xmalloc(npth * sizeof(res[0]));
736 res[0] = tmp = xstrdup(pth);
739 tmp = strchr(tmp, ':');
742 *tmp++ = '\0'; /* ':' -> '\0' */
744 break; /* :<empty> */
750 /* Complete command, directory or file name.
751 * Return the length of the prefix used for matching.
753 static NOINLINE unsigned complete_cmd_dir_file(const char *command, int type)
756 char **paths = path1;
764 path1[0] = (char*)".";
766 pfind = strrchr(command, '/');
768 if (type == FIND_EXE_ONLY)
769 npaths = path_parse(&paths);
772 /* point to 'l' in "..../last_component" */
774 /* dirbuf = ".../.../.../" */
775 dirbuf = xstrndup(command, pfind - command);
776 # if ENABLE_FEATURE_USERNAME_COMPLETION
777 if (dirbuf[0] == '~') /* ~/... or ~user/... */
778 dirbuf = username_path_completion(dirbuf);
782 pf_len = strlen(pfind);
784 #if ENABLE_FEATURE_SH_STANDALONE && NUM_APPLETS != 1
785 if (type == FIND_EXE_ONLY && !dirbuf) {
786 const char *p = applet_names;
789 if (strncmp(pfind, p, pf_len) == 0)
790 add_match(xstrdup(p));
797 for (i = 0; i < npaths; i++) {
803 dir = opendir(paths[i]);
805 continue; /* don't print an error */
807 while ((next = readdir(dir)) != NULL) {
809 const char *name_found = next->d_name;
811 /* .../<tab>: bash 3.2.0 shows dotfiles, but not . and .. */
812 if (!pfind[0] && DOT_OR_DOTDOT(name_found))
815 if (!is_prefixed_with(name_found, pfind))
818 found = concat_path_file(paths[i], name_found);
819 /* NB: stat() first so that we see is it a directory;
820 * but if that fails, use lstat() so that
821 * we still match dangling links */
822 if (stat(found, &st) && lstat(found, &st))
823 goto cont; /* hmm, remove in progress? */
826 len = strlen(name_found);
827 found = xrealloc(found, len + 2); /* +2: for slash and NUL */
828 strcpy(found, name_found);
830 if (S_ISDIR(st.st_mode)) {
831 /* name is a directory, add slash */
833 found[len + 1] = '\0';
835 /* skip files if looking for dirs only (example: cd) */
836 if (type == FIND_DIR_ONLY)
839 /* add it to the list */
846 } /* for every path */
848 if (paths != path1) {
849 free(paths[0]); /* allocated memory is only in first member */
857 /* build_match_prefix:
858 * On entry, match_buf contains everything up to cursor at the moment <tab>
859 * was pressed. This function looks at it, figures out what part of it
860 * constitutes the command/file/directory prefix to use for completion,
861 * and rewrites match_buf to contain only that part.
865 /* QUOT is used on elements of int_buf[], which are bytes,
866 * not Unicode chars. Therefore it works correctly even in Unicode mode.
868 #define QUOT (UCHAR_MAX+1)
869 static void remove_chunk(int16_t *int_buf, int beg, int end)
871 /* beg must be <= end */
875 while ((int_buf[beg] = int_buf[end]) != 0)
880 for (i = 0; int_buf[i]; i++)
881 bb_putchar((unsigned char)int_buf[i]);
885 /* Caller ensures that match_buf points to a malloced buffer
886 * big enough to hold strlen(match_buf)*2 + 2
888 static NOINLINE int build_match_prefix(char *match_buf)
892 int16_t *int_buf = (int16_t*)match_buf;
894 if (dbg_bmp) printf("\n%s\n", match_buf);
896 /* Copy in reverse order, since they overlap */
897 i = strlen(match_buf);
899 int_buf[i] = (unsigned char)match_buf[i];
903 /* Mark every \c as "quoted c" */
904 for (i = 0; int_buf[i]; i++) {
905 if (int_buf[i] == '\\') {
906 remove_chunk(int_buf, i, i + 1);
910 /* Quote-mark "chars" and 'chars', drop delimiters */
915 int cur = int_buf[i];
918 if (cur == '\'' || cur == '"') {
919 if (!in_quote || (cur == in_quote)) {
921 remove_chunk(int_buf, i, i + 1);
926 int_buf[i] = cur | QUOT;
931 /* Remove everything up to command delimiters:
932 * ';' ';;' '&' '|' '&&' '||',
933 * but careful with '>&' '<&' '>|'
935 for (i = 0; int_buf[i]; i++) {
936 int cur = int_buf[i];
937 if (cur == ';' || cur == '&' || cur == '|') {
938 int prev = i ? int_buf[i - 1] : 0;
939 if (cur == '&' && (prev == '>' || prev == '<')) {
941 } else if (cur == '|' && prev == '>') {
944 remove_chunk(int_buf, 0, i + 1 + (cur == int_buf[i + 1]));
945 i = -1; /* back to square 1 */
948 /* Remove all `cmd` */
949 for (i = 0; int_buf[i]; i++) {
950 if (int_buf[i] == '`') {
951 for (j = i + 1; int_buf[j]; j++) {
952 if (int_buf[j] == '`') {
953 /* `cmd` should count as a word:
954 * `cmd` c<tab> should search for files c*,
955 * not commands c*. Therefore we don't drop
956 * `cmd` entirely, we replace it with single `.
958 remove_chunk(int_buf, i, j);
962 /* No closing ` - command mode, remove all up to ` */
963 remove_chunk(int_buf, 0, i + 1);
969 /* Remove "cmd (" and "cmd {"
970 * Example: "if { c<tab>"
971 * In this example, c should be matched as command pfx.
973 for (i = 0; int_buf[i]; i++) {
974 if (int_buf[i] == '(' || int_buf[i] == '{') {
975 remove_chunk(int_buf, 0, i + 1);
976 i = -1; /* back to square 1 */
980 /* Remove leading unquoted spaces */
981 for (i = 0; int_buf[i]; i++)
982 if (int_buf[i] != ' ')
984 remove_chunk(int_buf, 0, i);
986 /* Determine completion mode */
987 command_mode = FIND_EXE_ONLY;
988 for (i = 0; int_buf[i]; i++) {
989 if (int_buf[i] == ' ' || int_buf[i] == '<' || int_buf[i] == '>') {
990 if (int_buf[i] == ' '
991 && command_mode == FIND_EXE_ONLY
992 && (char)int_buf[0] == 'c'
993 && (char)int_buf[1] == 'd'
994 && i == 2 /* -> int_buf[2] == ' ' */
996 command_mode = FIND_DIR_ONLY;
998 command_mode = FIND_FILE_ONLY;
1003 if (dbg_bmp) printf("command_mode(0:exe/1:dir/2:file):%d\n", command_mode);
1005 /* Remove everything except last word */
1006 for (i = 0; int_buf[i]; i++) /* quasi-strlen(int_buf) */
1008 for (--i; i >= 0; i--) {
1009 int cur = int_buf[i];
1010 if (cur == ' ' || cur == '<' || cur == '>' || cur == '|' || cur == '&') {
1011 remove_chunk(int_buf, 0, i + 1);
1016 /* Convert back to string of _chars_ */
1018 while ((match_buf[i] = int_buf[i]) != '\0')
1021 if (dbg_bmp) printf("final match_buf:'%s'\n", match_buf);
1023 return command_mode;
1027 * Display by column (original idea from ls applet,
1028 * very optimized by me [Vladimir] :)
1030 static void showfiles(void)
1033 int column_width = 0;
1034 int nfiles = num_matches;
1038 /* find the longest file name - use that as the column width */
1039 for (row = 0; row < nrows; row++) {
1040 l = unicode_strwidth(matches[row]);
1041 if (column_width < l)
1044 column_width += 2; /* min space for columns */
1045 ncols = cmdedit_termw / column_width;
1050 nrows++; /* round up fractionals */
1054 for (row = 0; row < nrows; row++) {
1058 for (nc = 1; nc < ncols && n+nrows < nfiles; n += nrows, nc++) {
1059 printf("%s%-*s", matches[n],
1060 (int)(column_width - unicode_strwidth(matches[n])), ""
1063 if (ENABLE_UNICODE_SUPPORT)
1064 puts(printable_string(NULL, matches[n]));
1070 static const char *is_special_char(char c)
1072 return strchr(" `\"#$%^&*()=+{}[]:;'|\\<>", c);
1075 static char *quote_special_chars(char *found)
1078 char *s = xzalloc((strlen(found) + 1) * 2);
1081 if (is_special_char(*found))
1085 /* s[l] = '\0'; - already is */
1089 /* Do TAB completion */
1090 static NOINLINE void input_tab(smallint *lastWasTab)
1095 /* Length of string used for matching */
1096 unsigned match_pfx_len = match_pfx_len;
1098 # if ENABLE_UNICODE_SUPPORT
1099 /* cursor pos in command converted to multibyte form */
1102 if (!(state->flags & TAB_COMPLETION))
1106 /* The last char was a TAB too.
1107 * Print a list of all the available choices.
1109 if (num_matches > 0) {
1110 /* cursor will be changed by goto_new_line() */
1111 int sav_cursor = cursor;
1114 redraw(0, command_len - sav_cursor);
1120 chosen_match = NULL;
1122 /* Make a local copy of the string up to the position of the cursor.
1123 * build_match_prefix will expand it into int16_t's, need to allocate
1124 * twice as much as the string_len+1.
1125 * (we then also (ab)use this extra space later - see (**))
1127 match_buf = xmalloc(MAX_LINELEN * sizeof(int16_t));
1128 # if !ENABLE_UNICODE_SUPPORT
1129 save_string(match_buf, cursor + 1); /* +1 for NUL */
1132 CHAR_T wc = command_ps[cursor];
1133 command_ps[cursor] = BB_NUL;
1134 save_string(match_buf, MAX_LINELEN);
1135 command_ps[cursor] = wc;
1136 cursor_mb = strlen(match_buf);
1139 find_type = build_match_prefix(match_buf);
1141 /* Free up any memory already allocated */
1142 free_tab_completion_data();
1144 # if ENABLE_FEATURE_USERNAME_COMPLETION
1145 /* If the word starts with ~ and there is no slash in the word,
1146 * then try completing this word as a username. */
1147 if (state->flags & USERNAME_COMPLETION)
1148 if (match_buf[0] == '~' && strchr(match_buf, '/') == NULL)
1149 match_pfx_len = complete_username(match_buf);
1151 /* If complete_username() did not match,
1152 * try to match a command in $PATH, or a directory, or a file */
1154 match_pfx_len = complete_cmd_dir_file(match_buf, find_type);
1156 /* Account for backslashes which will be inserted
1157 * by quote_special_chars() later */
1159 const char *e = match_buf + strlen(match_buf);
1160 const char *s = e - match_pfx_len;
1162 if (is_special_char(*s++))
1166 /* Remove duplicates */
1169 qsort_string_vector(matches, num_matches);
1170 for (i = 0; i < num_matches - 1; ++i) {
1171 //if (matches[i] && matches[i+1]) { /* paranoia */
1172 if (strcmp(matches[i], matches[i+1]) == 0) {
1174 //matches[i] = NULL; /* paranoia */
1176 matches[n++] = matches[i];
1180 matches[n++] = matches[i];
1184 /* Did we find exactly one match? */
1185 if (num_matches != 1) { /* no */
1189 goto ret; /* no matches at all */
1190 /* Find common prefix */
1191 chosen_match = xstrdup(matches[0]);
1192 for (cp = chosen_match; *cp; cp++) {
1194 for (n = 1; n < num_matches; n++) {
1195 if (matches[n][cp - chosen_match] != *cp) {
1201 if (cp == chosen_match) { /* have unique prefix? */
1205 cp = quote_special_chars(chosen_match);
1208 len_found = strlen(chosen_match);
1209 } else { /* exactly one match */
1210 /* Next <tab> is not a double-tab */
1213 chosen_match = quote_special_chars(matches[0]);
1214 len_found = strlen(chosen_match);
1215 if (chosen_match[len_found-1] != '/') {
1216 chosen_match[len_found] = ' ';
1217 chosen_match[++len_found] = '\0';
1221 # if !ENABLE_UNICODE_SUPPORT
1222 /* Have space to place the match? */
1223 /* The result consists of three parts with these lengths: */
1224 /* cursor + (len_found - match_pfx_len) + (command_len - cursor) */
1225 /* it simplifies into: */
1226 if ((int)(len_found - match_pfx_len + command_len) < S.maxsize) {
1229 strcpy(match_buf, &command_ps[cursor]);
1230 /* add match and tail */
1231 sprintf(&command_ps[cursor], "%s%s", chosen_match + match_pfx_len, match_buf);
1232 command_len = strlen(command_ps);
1234 pos = cursor + len_found - match_pfx_len;
1235 /* write out the matched command */
1236 redraw(cmdedit_y, command_len - pos);
1240 /* Use 2nd half of match_buf as scratch space - see (**) */
1241 char *command = match_buf + MAX_LINELEN;
1242 int len = save_string(command, MAX_LINELEN);
1243 /* Have space to place the match? */
1244 /* cursor_mb + (len_found - match_pfx_len) + (len - cursor_mb) */
1245 if ((int)(len_found - match_pfx_len + len) < MAX_LINELEN) {
1248 strcpy(match_buf, &command[cursor_mb]);
1249 /* where do we want to have cursor after all? */
1250 strcpy(&command[cursor_mb], chosen_match + match_pfx_len);
1251 len = load_string(command);
1252 /* add match and tail */
1253 sprintf(&command[cursor_mb], "%s%s", chosen_match + match_pfx_len, match_buf);
1254 command_len = load_string(command);
1255 /* write out the matched command */
1256 /* paranoia: load_string can return 0 on conv error,
1257 * prevent passing pos = (0 - 12) to redraw */
1258 pos = command_len - len;
1259 redraw(cmdedit_y, pos >= 0 ? pos : 0);
1268 #endif /* FEATURE_TAB_COMPLETION */
1271 line_input_t* FAST_FUNC new_line_input_t(int flags)
1273 line_input_t *n = xzalloc(sizeof(*n));
1276 n->max_history = MAX_HISTORY;
1284 unsigned FAST_FUNC size_from_HISTFILESIZE(const char *hp)
1286 int size = MAX_HISTORY;
1291 if (size > MAX_HISTORY)
1297 static void save_command_ps_at_cur_history(void)
1299 if (command_ps[0] != BB_NUL) {
1300 int cur = state->cur_history;
1301 free(state->history[cur]);
1303 # if ENABLE_UNICODE_SUPPORT
1305 char tbuf[MAX_LINELEN];
1306 save_string(tbuf, sizeof(tbuf));
1307 state->history[cur] = xstrdup(tbuf);
1310 state->history[cur] = xstrdup(command_ps);
1315 /* state->flags is already checked to be nonzero */
1316 static int get_previous_history(void)
1318 if ((state->flags & DO_HISTORY) && state->cur_history) {
1319 save_command_ps_at_cur_history();
1320 state->cur_history--;
1327 static int get_next_history(void)
1329 if (state->flags & DO_HISTORY) {
1330 if (state->cur_history < state->cnt_history) {
1331 save_command_ps_at_cur_history(); /* save the current history line */
1332 return ++state->cur_history;
1339 /* Lists command history. Used by shell 'history' builtins */
1340 void FAST_FUNC show_history(const line_input_t *st)
1346 for (i = 0; i < st->cnt_history; i++)
1347 printf("%4d %s\n", i, st->history[i]);
1350 # if ENABLE_FEATURE_EDITING_SAVEHISTORY
1351 /* We try to ensure that concurrent additions to the history
1352 * do not overwrite each other.
1353 * Otherwise shell users get unhappy.
1355 * History file is trimmed lazily, when it grows several times longer
1356 * than configured MAX_HISTORY lines.
1359 static void free_line_input_t(line_input_t *n)
1361 int i = n->cnt_history;
1363 free(n->history[--i]);
1367 /* state->flags is already checked to be nonzero */
1368 static void load_history(line_input_t *st_parm)
1370 char *temp_h[MAX_HISTORY];
1373 unsigned idx, i, line_len;
1375 /* NB: do not trash old history if file can't be opened */
1377 fp = fopen_for_read(st_parm->hist_file);
1379 /* clean up old history */
1380 for (idx = st_parm->cnt_history; idx > 0;) {
1382 free(st_parm->history[idx]);
1383 st_parm->history[idx] = NULL;
1386 /* fill temp_h[], retaining only last MAX_HISTORY lines */
1387 memset(temp_h, 0, sizeof(temp_h));
1389 st_parm->cnt_history_in_file = 0;
1390 while ((line = xmalloc_fgetline(fp)) != NULL) {
1391 if (line[0] == '\0') {
1397 st_parm->cnt_history_in_file++;
1399 if (idx == st_parm->max_history)
1404 /* find first non-NULL temp_h[], if any */
1405 if (st_parm->cnt_history_in_file) {
1406 while (temp_h[idx] == NULL) {
1408 if (idx == st_parm->max_history)
1413 /* copy temp_h[] to st_parm->history[] */
1414 for (i = 0; i < st_parm->max_history;) {
1419 if (idx == st_parm->max_history)
1421 line_len = strlen(line);
1422 if (line_len >= MAX_LINELEN)
1423 line[MAX_LINELEN-1] = '\0';
1424 st_parm->history[i++] = line;
1426 st_parm->cnt_history = i;
1427 if (ENABLE_FEATURE_EDITING_SAVE_ON_EXIT)
1428 st_parm->cnt_history_in_file = i;
1432 # if ENABLE_FEATURE_EDITING_SAVE_ON_EXIT
1433 void save_history(line_input_t *st)
1439 if (st->cnt_history <= st->cnt_history_in_file)
1442 fp = fopen(st->hist_file, "a");
1446 line_input_t *st_temp;
1448 for (i = st->cnt_history_in_file; i < st->cnt_history; i++)
1449 fprintf(fp, "%s\n", st->history[i]);
1452 /* we may have concurrently written entries from others.
1454 st_temp = new_line_input_t(st->flags);
1455 st_temp->hist_file = st->hist_file;
1456 st_temp->max_history = st->max_history;
1457 load_history(st_temp);
1459 /* write out temp file and replace hist_file atomically */
1460 new_name = xasprintf("%s.%u.new", st->hist_file, (int) getpid());
1461 fd = open(new_name, O_WRONLY | O_CREAT | O_TRUNC, 0600);
1463 fp = xfdopen_for_write(fd);
1464 for (i = 0; i < st_temp->cnt_history; i++)
1465 fprintf(fp, "%s\n", st_temp->history[i]);
1467 if (rename(new_name, st->hist_file) == 0)
1468 st->cnt_history_in_file = st_temp->cnt_history;
1471 free_line_input_t(st_temp);
1475 static void save_history(char *str)
1480 if (!state->hist_file)
1483 fd = open(state->hist_file, O_WRONLY | O_CREAT | O_APPEND, 0600);
1486 xlseek(fd, 0, SEEK_END); /* paranoia */
1488 str[len] = '\n'; /* we (try to) do atomic write */
1489 len2 = full_write(fd, str, len + 1);
1492 if (len2 != len + 1)
1493 return; /* "wtf?" */
1495 /* did we write so much that history file needs trimming? */
1496 state->cnt_history_in_file++;
1497 if (state->cnt_history_in_file > state->max_history * 4) {
1499 line_input_t *st_temp;
1501 /* we may have concurrently written entries from others.
1503 st_temp = new_line_input_t(state->flags);
1504 st_temp->hist_file = state->hist_file;
1505 st_temp->max_history = state->max_history;
1506 load_history(st_temp);
1508 /* write out temp file and replace hist_file atomically */
1509 new_name = xasprintf("%s.%u.new", state->hist_file, (int) getpid());
1510 fd = open(new_name, O_WRONLY | O_CREAT | O_TRUNC, 0600);
1515 fp = xfdopen_for_write(fd);
1516 for (i = 0; i < st_temp->cnt_history; i++)
1517 fprintf(fp, "%s\n", st_temp->history[i]);
1519 if (rename(new_name, state->hist_file) == 0)
1520 state->cnt_history_in_file = st_temp->cnt_history;
1523 free_line_input_t(st_temp);
1528 # define load_history(a) ((void)0)
1529 # define save_history(a) ((void)0)
1530 # endif /* FEATURE_COMMAND_SAVEHISTORY */
1532 static void remember_in_history(char *str)
1536 if (!(state->flags & DO_HISTORY))
1540 i = state->cnt_history;
1541 /* Don't save dupes */
1542 if (i && strcmp(state->history[i-1], str) == 0)
1545 free(state->history[state->max_history]); /* redundant, paranoia */
1546 state->history[state->max_history] = NULL; /* redundant, paranoia */
1548 /* If history[] is full, remove the oldest command */
1549 /* we need to keep history[state->max_history] empty, hence >=, not > */
1550 if (i >= state->max_history) {
1551 free(state->history[0]);
1552 for (i = 0; i < state->max_history-1; i++)
1553 state->history[i] = state->history[i+1];
1554 /* i == state->max_history-1 */
1555 # if ENABLE_FEATURE_EDITING_SAVE_ON_EXIT
1556 if (state->cnt_history_in_file)
1557 state->cnt_history_in_file--;
1560 /* i <= state->max_history-1 */
1561 state->history[i++] = xstrdup(str);
1562 /* i <= state->max_history */
1563 state->cur_history = i;
1564 state->cnt_history = i;
1565 # if ENABLE_FEATURE_EDITING_SAVEHISTORY && !ENABLE_FEATURE_EDITING_SAVE_ON_EXIT
1570 #else /* MAX_HISTORY == 0 */
1571 # define remember_in_history(a) ((void)0)
1572 #endif /* MAX_HISTORY */
1575 #if ENABLE_FEATURE_EDITING_VI
1577 * vi mode implemented 2005 by Paul Fox <pgf@foxharp.boston.ma.us>
1580 vi_Word_motion(int eat)
1582 CHAR_T *command = command_ps;
1584 while (cursor < command_len && !BB_isspace(command[cursor]))
1586 if (eat) while (cursor < command_len && BB_isspace(command[cursor]))
1591 vi_word_motion(int eat)
1593 CHAR_T *command = command_ps;
1595 if (BB_isalnum_or_underscore(command[cursor])) {
1596 while (cursor < command_len
1597 && (BB_isalnum_or_underscore(command[cursor+1]))
1601 } else if (BB_ispunct(command[cursor])) {
1602 while (cursor < command_len && BB_ispunct(command[cursor+1]))
1606 if (cursor < command_len)
1610 while (cursor < command_len && BB_isspace(command[cursor]))
1618 CHAR_T *command = command_ps;
1621 while (cursor < command_len && BB_isspace(command[cursor]))
1623 while (cursor < command_len-1 && !BB_isspace(command[cursor+1]))
1630 CHAR_T *command = command_ps;
1632 if (cursor >= command_len-1)
1635 while (cursor < command_len-1 && BB_isspace(command[cursor]))
1637 if (cursor >= command_len-1)
1639 if (BB_isalnum_or_underscore(command[cursor])) {
1640 while (cursor < command_len-1
1641 && (BB_isalnum_or_underscore(command[cursor+1]))
1645 } else if (BB_ispunct(command[cursor])) {
1646 while (cursor < command_len-1 && BB_ispunct(command[cursor+1]))
1652 vi_Back_motion(void)
1654 CHAR_T *command = command_ps;
1656 while (cursor > 0 && BB_isspace(command[cursor-1]))
1658 while (cursor > 0 && !BB_isspace(command[cursor-1]))
1663 vi_back_motion(void)
1665 CHAR_T *command = command_ps;
1670 while (cursor > 0 && BB_isspace(command[cursor]))
1674 if (BB_isalnum_or_underscore(command[cursor])) {
1676 && (BB_isalnum_or_underscore(command[cursor-1]))
1680 } else if (BB_ispunct(command[cursor])) {
1681 while (cursor > 0 && BB_ispunct(command[cursor-1]))
1687 /* Modelled after bash 4.0 behavior of Ctrl-<arrow> */
1688 static void ctrl_left(void)
1690 CHAR_T *command = command_ps;
1698 c = command[cursor];
1699 if (c != ' ' && !BB_ispunct(c)) {
1700 /* we reached a "word" delimited by spaces/punct.
1701 * go to its beginning */
1703 c = command[cursor - 1];
1704 if (c == ' ' || BB_ispunct(c))
1714 static void ctrl_right(void)
1716 CHAR_T *command = command_ps;
1721 c = command[cursor];
1724 if (c != ' ' && !BB_ispunct(c)) {
1725 /* we reached a "word" delimited by spaces/punct.
1726 * go to its end + 1 */
1729 c = command[cursor];
1730 if (c == BB_NUL || c == ' ' || BB_ispunct(c))
1741 * read_line_input and its helpers
1744 #if ENABLE_FEATURE_EDITING_ASK_TERMINAL
1745 static void ask_terminal(void)
1747 /* Ask terminal where is the cursor now.
1748 * lineedit_read_key handles response and corrects
1749 * our idea of current cursor position.
1750 * Testcase: run "echo -n long_line_long_line_long_line",
1751 * then type in a long, wrapping command and try to
1752 * delete it using backspace key.
1753 * Note: we print it _after_ prompt, because
1754 * prompt may contain CR. Example: PS1='\[\r\n\]\w '
1756 /* Problem: if there is buffered input on stdin,
1757 * the response will be delivered later,
1758 * possibly to an unsuspecting application.
1759 * Testcase: "sleep 1; busybox ash" + press and hold [Enter].
1761 * ~/srcdevel/bbox/fix/busybox.t4 #
1762 * ~/srcdevel/bbox/fix/busybox.t4 #
1763 * ^[[59;34~/srcdevel/bbox/fix/busybox.t4 # <-- garbage
1764 * ~/srcdevel/bbox/fix/busybox.t4 #
1766 * Checking for input with poll only makes the race narrower,
1767 * I still can trigger it. Strace:
1769 * write(1, "~/srcdevel/bbox/fix/busybox.t4 # ", 33) = 33
1770 * poll([{fd=0, events=POLLIN}], 1, 0) = 0 (Timeout) <-- no input exists
1771 * write(1, "\33[6n", 4) = 4 <-- send the ESC sequence, quick!
1772 * poll([{fd=0, events=POLLIN}], 1, -1) = 1 ([{fd=0, revents=POLLIN}])
1773 * read(0, "\n", 1) = 1 <-- oh crap, user's input got in first
1777 pfd.fd = STDIN_FILENO;
1778 pfd.events = POLLIN;
1779 if (safe_poll(&pfd, 1, 0) == 0) {
1780 S.sent_ESC_br6n = 1;
1781 fputs(ESC"[6n", stdout);
1782 fflush_all(); /* make terminal see it ASAP! */
1786 #define ask_terminal() ((void)0)
1789 /* Called just once at read_line_input() init time */
1790 #if !ENABLE_FEATURE_EDITING_FANCY_PROMPT
1791 static void parse_and_put_prompt(const char *prmt_ptr)
1794 cmdedit_prompt = prmt_ptr;
1795 p = strrchr(prmt_ptr, '\n');
1796 cmdedit_prmt_len = unicode_strwidth(p ? p+1 : prmt_ptr);
1800 static void parse_and_put_prompt(const char *prmt_ptr)
1803 char *prmt_mem_ptr = xzalloc(1);
1804 # if ENABLE_USERNAME_OR_HOMEDIR
1805 char *cwd_buf = NULL;
1807 char flg_not_length = '[';
1810 /*cmdedit_prmt_len = 0; - already is */
1812 cbuf[1] = '\0'; /* never changes */
1815 char timebuf[sizeof("HH:MM:SS")];
1816 char *free_me = NULL;
1826 * Supported via bb_process_escape_sequence:
1827 * \a ASCII bell character (07)
1828 * \e ASCII escape character (033)
1830 * \r carriage return
1832 * \nnn char with octal code nnn
1834 * \$ if the effective UID is 0, a #, otherwise a $
1835 * \w current working directory, with $HOME abbreviated with a tilde
1836 * Note: we do not support $PROMPT_DIRTRIM=n feature
1837 * \W basename of the current working directory, with $HOME abbreviated with a tilde
1838 * \h hostname up to the first '.'
1841 * \[ begin a sequence of non-printing characters
1842 * \] end a sequence of non-printing characters
1843 * \T current time in 12-hour HH:MM:SS format
1844 * \@ current time in 12-hour am/pm format
1845 * \A current time in 24-hour HH:MM format
1846 * \t current time in 24-hour HH:MM:SS format
1847 * (all of the above work as \A)
1849 * \! history number of this command
1850 * \# command number of this command
1851 * \j number of jobs currently managed by the shell
1852 * \l basename of the shell's terminal device name
1853 * \s name of the shell, the basename of $0 (the portion following the final slash)
1854 * \V release of bash, version + patch level (e.g., 2.00.0)
1855 * \d date in "Weekday Month Date" format (e.g., "Tue May 26")
1857 * format is passed to strftime(3).
1858 * An empty format results in a locale-specific time representation.
1859 * The braces are required.
1860 * Mishandled by bb_process_escape_sequence:
1861 * \v version of bash (e.g., 2.00)
1865 if (c != 't') /* don't treat \t as tab */
1866 c = bb_process_escape_sequence(&prmt_ptr);
1867 if (prmt_ptr == cp) {
1873 # if ENABLE_USERNAME_OR_HOMEDIR
1875 pbuf = user_buf ? user_buf : (char*)"";
1880 pbuf = free_me = safe_gethostname();
1882 strchrnul(pbuf, '.')[0] = '\0';
1885 c = (geteuid() == 0 ? '#' : '$');
1887 case 'T': /* 12-hour HH:MM:SS format */
1888 case '@': /* 12-hour am/pm format */
1889 case 'A': /* 24-hour HH:MM format */
1890 case 't': /* 24-hour HH:MM:SS format */
1891 /* We show all of them as 24-hour HH:MM */
1892 strftime_HHMMSS(timebuf, sizeof(timebuf), NULL)[-3] = '\0';
1895 # if ENABLE_USERNAME_OR_HOMEDIR
1896 case 'w': /* current dir */
1897 case 'W': /* basename of cur dir */
1899 cwd_buf = xrealloc_getcwd_or_warn(NULL);
1901 cwd_buf = (char *)bb_msg_unknown;
1902 else if (home_pwd_buf[0]) {
1903 char *after_home_user;
1905 /* /home/user[/something] -> ~[/something] */
1906 after_home_user = is_prefixed_with(cwd_buf, home_pwd_buf);
1908 && (*after_home_user == '/' || *after_home_user == '\0')
1911 overlapping_strcpy(cwd_buf + 1, after_home_user);
1918 cp = strrchr(pbuf, '/');
1920 pbuf = (char*)cp + 1;
1923 // bb_process_escape_sequence does this now:
1924 // case 'e': case 'E': /* \e \E = \033 */
1927 case 'x': case 'X': {
1929 for (l = 0; l < 3;) {
1931 buf2[l++] = *prmt_ptr;
1933 h = strtoul(buf2, &pbuf, 16);
1934 if (h > UCHAR_MAX || (pbuf - buf2) < l) {
1940 c = (char)strtoul(buf2, NULL, 16);
1947 if (c == flg_not_length) {
1948 /* Toggle '['/']' hex 5b/5d */
1949 flg_not_length ^= 6;
1958 int n = strlen(pbuf);
1961 cmdedit_prmt_len = 0;
1962 else if (flg_not_length != ']') {
1963 #if 0 /*ENABLE_UNICODE_SUPPORT*/
1964 /* Won't work, pbuf is one BYTE string here instead of an one Unicode char string. */
1966 cmdedit_prmt_len += unicode_strwidth(pbuf);
1968 cmdedit_prmt_len += n;
1972 prmt_mem_ptr = strcat(xrealloc(prmt_mem_ptr, prmt_size+1), pbuf);
1976 # if ENABLE_USERNAME_OR_HOMEDIR
1977 if (cwd_buf != (char *)bb_msg_unknown)
1980 cmdedit_prompt = prmt_mem_ptr;
1985 static void cmdedit_setwidth(unsigned w, int redraw_flg)
1989 /* new y for current cursor */
1990 int new_y = (cursor + cmdedit_prmt_len) / w;
1992 redraw((new_y >= cmdedit_y ? new_y : cmdedit_y), command_len - cursor);
1997 static void win_changed(int nsig)
1999 int sv_errno = errno;
2002 get_terminal_width_height(0, &width, NULL);
2003 //FIXME: cmdedit_setwidth() -> redraw() -> printf() -> KABOOM! (we are in signal handler!)
2004 cmdedit_setwidth(width, /*redraw_flg:*/ nsig);
2009 static int lineedit_read_key(char *read_key_buffer, int timeout)
2012 #if ENABLE_UNICODE_SUPPORT
2013 char unicode_buf[MB_CUR_MAX + 1];
2014 int unicode_idx = 0;
2018 /* Wait for input. TIMEOUT = -1 makes read_key wait even
2019 * on nonblocking stdin, TIMEOUT = 50 makes sure we won't
2020 * insist on full MB_CUR_MAX buffer to declare input like
2021 * "\xff\n",pause,"ls\n" invalid and thus won't lose "ls".
2023 * Note: read_key sets errno to 0 on success.
2025 ic = read_key(STDIN_FILENO, read_key_buffer, timeout);
2027 #if ENABLE_UNICODE_SUPPORT
2028 if (errno == EAGAIN && unicode_idx != 0)
2034 #if ENABLE_FEATURE_EDITING_ASK_TERMINAL
2035 if ((int32_t)ic == KEYCODE_CURSOR_POS
2038 S.sent_ESC_br6n = 0;
2039 if (cursor == 0) { /* otherwise it may be bogus */
2040 int col = ((ic >> 32) & 0x7fff) - 1;
2042 * Is col > cmdedit_prmt_len?
2043 * If yes (terminal says cursor is farther to the right
2044 * of where we think it should be),
2045 * the prompt wasn't printed starting at col 1,
2046 * there was additional text before it.
2048 if ((int)(col - cmdedit_prmt_len) > 0) {
2049 /* Fix our understanding of current x position */
2050 cmdedit_x += (col - cmdedit_prmt_len);
2051 while (cmdedit_x >= cmdedit_termw) {
2052 cmdedit_x -= cmdedit_termw;
2061 #if ENABLE_UNICODE_SUPPORT
2062 if (unicode_status == UNICODE_ON) {
2065 if ((int32_t)ic < 0) /* KEYCODE_xxx */
2067 // TODO: imagine sequence like: 0xff,<left-arrow>: we are currently losing 0xff...
2069 unicode_buf[unicode_idx++] = ic;
2070 unicode_buf[unicode_idx] = '\0';
2071 if (mbstowcs(&wc, unicode_buf, 1) != 1) {
2072 /* Not (yet?) a valid unicode char */
2073 if (unicode_idx < MB_CUR_MAX) {
2078 /* Invalid sequence. Save all "bad bytes" except first */
2079 read_key_ungets(read_key_buffer, unicode_buf + 1, unicode_idx - 1);
2080 # if !ENABLE_UNICODE_PRESERVE_BROKEN
2081 ic = CONFIG_SUBST_WCHAR;
2083 ic = unicode_mark_raw_byte(unicode_buf[0]);
2086 /* Valid unicode char, return its code */
2097 #if ENABLE_UNICODE_BIDI_SUPPORT
2098 static int isrtl_str(void)
2102 while (idx < command_len && unicode_bidi_is_neutral_wchar(command_ps[idx]))
2104 return unicode_bidi_isrtl(command_ps[idx]);
2107 # define isrtl_str() 0
2110 /* leave out the "vi-mode"-only case labels if vi editing isn't
2112 #define vi_case(caselabel) IF_FEATURE_EDITING_VI(case caselabel)
2114 /* convert uppercase ascii to equivalent control char, for readability */
2116 #define CTRL(a) ((a) & ~0x40)
2119 VI_CMDMODE_BIT = 0x40000000,
2120 /* 0x80000000 bit flags KEYCODE_xxx */
2123 #if ENABLE_FEATURE_REVERSE_SEARCH
2124 /* Mimic readline Ctrl-R reverse history search.
2125 * When invoked, it shows the following prompt:
2126 * (reverse-i-search)'': user_input [cursor pos unchanged by Ctrl-R]
2127 * and typing results in search being performed:
2128 * (reverse-i-search)'tmp': cd /tmp [cursor under t in /tmp]
2129 * Search is performed by looking at progressively older lines in history.
2130 * Ctrl-R again searches for the next match in history.
2131 * Backspace deletes last matched char.
2132 * Control keys exit search and return to normal editing (at current history line).
2134 static int32_t reverse_i_search(void)
2136 char match_buf[128]; /* for user input */
2137 char read_key_buffer[KEYCODE_BUFFER_SIZE];
2138 const char *matched_history_line;
2139 const char *saved_prompt;
2140 unsigned saved_prmt_len;
2143 matched_history_line = NULL;
2144 read_key_buffer[0] = 0;
2145 match_buf[0] = '\0';
2147 /* Save and replace the prompt */
2148 saved_prompt = cmdedit_prompt;
2149 saved_prmt_len = cmdedit_prmt_len;
2154 unsigned match_buf_len = strlen(match_buf);
2157 //FIXME: correct timeout?
2158 ic = lineedit_read_key(read_key_buffer, -1);
2161 case CTRL('R'): /* searching for the next match */
2167 if (unicode_status == UNICODE_ON) {
2168 while (match_buf_len != 0) {
2169 uint8_t c = match_buf[--match_buf_len];
2170 if ((c & 0xc0) != 0x80) /* start of UTF-8 char? */
2174 if (match_buf_len != 0)
2177 match_buf[match_buf_len] = '\0';
2182 || (!ENABLE_UNICODE_SUPPORT && ic >= 256)
2183 || (ENABLE_UNICODE_SUPPORT && ic >= VI_CMDMODE_BIT)
2188 /* Append this char */
2189 #if ENABLE_UNICODE_SUPPORT
2190 if (unicode_status == UNICODE_ON) {
2191 mbstate_t mbstate = { 0 };
2192 char buf[MB_CUR_MAX + 1];
2193 int len = wcrtomb(buf, ic, &mbstate);
2196 if (match_buf_len + len < sizeof(match_buf))
2197 strcpy(match_buf + match_buf_len, buf);
2201 if (match_buf_len < sizeof(match_buf) - 1) {
2202 match_buf[match_buf_len] = ic;
2203 match_buf[match_buf_len + 1] = '\0';
2208 /* Search in history for match_buf */
2209 h = state->cur_history;
2210 if (ic == CTRL('R'))
2213 if (state->history[h]) {
2214 char *match = strstr(state->history[h], match_buf);
2216 state->cur_history = h;
2217 matched_history_line = state->history[h];
2218 command_len = load_string(matched_history_line);
2219 cursor = match - matched_history_line;
2220 //FIXME: cursor position for Unicode case
2222 free((char*)cmdedit_prompt);
2224 cmdedit_prompt = xasprintf("(reverse-i-search)'%s': ", match_buf);
2225 cmdedit_prmt_len = unicode_strwidth(cmdedit_prompt);
2233 match_buf[match_buf_len] = '\0';
2238 redraw(cmdedit_y, command_len - cursor);
2242 if (matched_history_line)
2243 command_len = load_string(matched_history_line);
2245 free((char*)cmdedit_prompt);
2246 cmdedit_prompt = saved_prompt;
2247 cmdedit_prmt_len = saved_prmt_len;
2248 redraw(cmdedit_y, command_len - cursor);
2254 /* maxsize must be >= 2.
2256 * -1 on read errors or EOF, or on bare Ctrl-D,
2257 * 0 on ctrl-C (the line entered is still returned in 'command'),
2258 * >0 length of input string, including terminating '\n'
2260 int FAST_FUNC read_line_input(line_input_t *st, const char *prompt, char *command, int maxsize, int timeout)
2263 #if ENABLE_FEATURE_TAB_COMPLETION
2264 smallint lastWasTab = 0;
2266 smallint break_out = 0;
2267 #if ENABLE_FEATURE_EDITING_VI
2268 smallint vi_cmdmode = 0;
2270 struct termios initial_settings;
2271 struct termios new_settings;
2272 char read_key_buffer[KEYCODE_BUFFER_SIZE];
2276 if (tcgetattr(STDIN_FILENO, &initial_settings) < 0
2277 || (initial_settings.c_lflag & (ECHO|ICANON)) == ICANON
2279 /* Happens when e.g. stty -echo was run before.
2280 * But if ICANON is not set, we don't come here.
2281 * (example: interactive python ^Z-backgrounded,
2282 * tty is still in "raw mode").
2284 parse_and_put_prompt(prompt);
2285 /* fflush_all(); - done by parse_and_put_prompt */
2286 if (fgets(command, maxsize, stdin) == NULL)
2287 len = -1; /* EOF or error */
2289 len = strlen(command);
2296 // FIXME: audit & improve this
2297 if (maxsize > MAX_LINELEN)
2298 maxsize = MAX_LINELEN;
2299 S.maxsize = maxsize;
2301 /* With zero flags, no other fields are ever used */
2302 state = st ? st : (line_input_t*) &const_int_0;
2304 # if ENABLE_FEATURE_EDITING_SAVEHISTORY
2305 if (state->hist_file)
2306 if (state->cnt_history == 0)
2307 load_history(state);
2309 if (state->flags & DO_HISTORY)
2310 state->cur_history = state->cnt_history;
2313 /* prepare before init handlers */
2314 cmdedit_y = 0; /* quasireal y, not true if line > xt*yt */
2316 #if ENABLE_UNICODE_SUPPORT
2317 command_ps = xzalloc(maxsize * sizeof(command_ps[0]));
2319 command_ps = command;
2322 #define command command_must_not_be_used
2324 new_settings = initial_settings;
2325 /* ~ICANON: unbuffered input (most c_cc[] are disabled, VMIN/VTIME are enabled) */
2326 /* ~ECHO, ~ECHONL: turn off echoing, including newline echoing */
2327 /* ~ISIG: turn off INTR (ctrl-C), QUIT, SUSP */
2328 new_settings.c_lflag &= ~(ICANON | ECHO | ECHONL | ISIG);
2329 /* reads would block only if < 1 char is available */
2330 new_settings.c_cc[VMIN] = 1;
2331 /* no timeout (reads block forever) */
2332 new_settings.c_cc[VTIME] = 0;
2333 /* Should be not needed if ISIG is off: */
2334 /* Turn off CTRL-C */
2335 /* new_settings.c_cc[VINTR] = _POSIX_VDISABLE; */
2336 tcsetattr_stdin_TCSANOW(&new_settings);
2338 #if ENABLE_USERNAME_OR_HOMEDIR
2340 struct passwd *entry;
2342 entry = getpwuid(geteuid());
2344 user_buf = xstrdup(entry->pw_name);
2345 home_pwd_buf = xstrdup(entry->pw_dir);
2351 for (i = 0; i <= state->max_history; i++)
2352 bb_error_msg("history[%d]:'%s'", i, state->history[i]);
2353 bb_error_msg("cur_history:%d cnt_history:%d", state->cur_history, state->cnt_history);
2356 /* Print out the command prompt, optionally ask where cursor is */
2357 parse_and_put_prompt(prompt);
2360 /* Install window resize handler (NB: after *all* init is complete) */
2361 //FIXME: save entire sigaction!
2362 previous_SIGWINCH_handler = signal(SIGWINCH, win_changed);
2363 win_changed(0); /* get initial window size */
2365 read_key_buffer[0] = 0;
2368 * The emacs and vi modes share much of the code in the big
2369 * command loop. Commands entered when in vi's command mode
2370 * (aka "escape mode") get an extra bit added to distinguish
2371 * them - this keeps them from being self-inserted. This
2372 * clutters the big switch a bit, but keeps all the code
2378 ic = ic_raw = lineedit_read_key(read_key_buffer, timeout);
2380 #if ENABLE_FEATURE_REVERSE_SEARCH
2383 #if ENABLE_FEATURE_EDITING_VI
2386 /* btw, since KEYCODE_xxx are all < 0, this doesn't
2387 * change ic if it contains one of them: */
2388 ic |= VI_CMDMODE_BIT;
2395 vi_case('\n'|VI_CMDMODE_BIT:)
2396 vi_case('\r'|VI_CMDMODE_BIT:)
2402 vi_case('0'|VI_CMDMODE_BIT:)
2403 /* Control-a -- Beginning of line */
2404 input_backward(cursor);
2407 vi_case('h'|VI_CMDMODE_BIT:)
2408 vi_case('\b'|VI_CMDMODE_BIT:) /* ^H */
2409 vi_case('\x7f'|VI_CMDMODE_BIT:) /* DEL */
2410 input_backward(1); /* Move back one character */
2413 vi_case('$'|VI_CMDMODE_BIT:)
2414 /* Control-e -- End of line */
2415 put_till_end_and_adv_cursor();
2418 vi_case('l'|VI_CMDMODE_BIT:)
2419 vi_case(' '|VI_CMDMODE_BIT:)
2420 input_forward(); /* Move forward one character */
2423 case '\x7f': /* DEL */
2429 case KEYCODE_DELETE:
2435 #if ENABLE_FEATURE_TAB_COMPLETION
2437 input_tab(&lastWasTab);
2441 /* Control-k -- clear to end of line */
2442 command_ps[cursor] = BB_NUL;
2443 command_len = cursor;
2444 printf(SEQ_CLEAR_TILL_END_OF_SCREEN);
2447 vi_case(CTRL('L')|VI_CMDMODE_BIT:)
2448 /* Control-l -- clear screen */
2449 printf(ESC"[H"); /* cursor to top,left */
2450 redraw(0, command_len - cursor);
2454 vi_case(CTRL('N')|VI_CMDMODE_BIT:)
2455 vi_case('j'|VI_CMDMODE_BIT:)
2456 /* Control-n -- Get next command in history */
2457 if (get_next_history())
2461 vi_case(CTRL('P')|VI_CMDMODE_BIT:)
2462 vi_case('k'|VI_CMDMODE_BIT:)
2463 /* Control-p -- Get previous command from history */
2464 if (get_previous_history())
2469 vi_case(CTRL('U')|VI_CMDMODE_BIT:)
2470 /* Control-U -- Clear line before cursor */
2472 command_len -= cursor;
2473 memmove(command_ps, command_ps + cursor,
2474 (command_len + 1) * sizeof(command_ps[0]));
2475 redraw(cmdedit_y, command_len);
2479 vi_case(CTRL('W')|VI_CMDMODE_BIT:)
2480 /* Control-W -- Remove the last word */
2481 while (cursor > 0 && BB_isspace(command_ps[cursor-1]))
2483 while (cursor > 0 && !BB_isspace(command_ps[cursor-1]))
2486 #if ENABLE_FEATURE_REVERSE_SEARCH
2488 ic = ic_raw = reverse_i_search();
2492 #if ENABLE_FEATURE_EDITING_VI
2493 case 'i'|VI_CMDMODE_BIT:
2496 case 'I'|VI_CMDMODE_BIT:
2497 input_backward(cursor);
2500 case 'a'|VI_CMDMODE_BIT:
2504 case 'A'|VI_CMDMODE_BIT:
2505 put_till_end_and_adv_cursor();
2508 case 'x'|VI_CMDMODE_BIT:
2511 case 'X'|VI_CMDMODE_BIT:
2517 case 'W'|VI_CMDMODE_BIT:
2520 case 'w'|VI_CMDMODE_BIT:
2523 case 'E'|VI_CMDMODE_BIT:
2526 case 'e'|VI_CMDMODE_BIT:
2529 case 'B'|VI_CMDMODE_BIT:
2532 case 'b'|VI_CMDMODE_BIT:
2535 case 'C'|VI_CMDMODE_BIT:
2538 case 'D'|VI_CMDMODE_BIT:
2541 case 'c'|VI_CMDMODE_BIT:
2544 case 'd'|VI_CMDMODE_BIT: {
2547 ic = lineedit_read_key(read_key_buffer, timeout);
2548 if (errno) /* error */
2549 goto return_error_indicator;
2550 if (ic == ic_raw) { /* "cc", "dd" */
2551 input_backward(cursor);
2563 case 'w': /* "dw", "cw" */
2564 vi_word_motion(vi_cmdmode);
2566 case 'W': /* 'dW', 'cW' */
2567 vi_Word_motion(vi_cmdmode);
2569 case 'e': /* 'de', 'ce' */
2573 case 'E': /* 'dE', 'cE' */
2579 input_backward(cursor - sc);
2580 while (nc-- > cursor)
2583 case 'b': /* "db", "cb" */
2584 case 'B': /* implemented as B */
2589 while (sc-- > cursor)
2592 case ' ': /* "d ", "c " */
2595 case '$': /* "d$", "c$" */
2597 while (cursor < command_len)
2603 case 'p'|VI_CMDMODE_BIT:
2606 case 'P'|VI_CMDMODE_BIT:
2609 case 'r'|VI_CMDMODE_BIT:
2610 //FIXME: unicode case?
2611 ic = lineedit_read_key(read_key_buffer, timeout);
2612 if (errno) /* error */
2613 goto return_error_indicator;
2614 if (ic < ' ' || ic > 255) {
2617 command_ps[cursor] = ic;
2622 case '\x1b': /* ESC */
2623 if (state->flags & VI_MODE) {
2624 /* insert mode --> command mode */
2628 /* Handle a few ESC-<key> combinations the same way
2629 * standard readline bindings (IOW: bash) do.
2630 * Often, Alt-<key> generates ESC-<key>.
2632 ic = lineedit_read_key(read_key_buffer, 50);
2634 //case KEYCODE_LEFT: - bash doesn't do this
2638 //case KEYCODE_RIGHT: - bash doesn't do this
2642 //case KEYCODE_DELETE: - bash doesn't do this
2643 case 'd': /* Alt-D */
2645 /* Delete word forward */
2646 int nc, sc = cursor;
2654 case '\b': /* Alt-Backspace(?) */
2655 case '\x7f': /* Alt-Backspace(?) */
2656 //case 'w': - bash doesn't do this
2658 /* Delete word backward */
2661 while (sc-- > cursor)
2667 #endif /* FEATURE_COMMAND_EDITING_VI */
2671 if (get_previous_history())
2676 if (!get_next_history())
2679 /* Rewrite the line with the selected history item */
2680 /* change command */
2681 command_len = load_string(state->history[state->cur_history] ?
2682 state->history[state->cur_history] : "");
2683 /* redraw and go to eol (bol, in vi) */
2684 redraw(cmdedit_y, (state->flags & VI_MODE) ? 9999 : 0);
2693 case KEYCODE_CTRL_LEFT:
2694 case KEYCODE_ALT_LEFT: /* bash doesn't do it */
2697 case KEYCODE_CTRL_RIGHT:
2698 case KEYCODE_ALT_RIGHT: /* bash doesn't do it */
2702 input_backward(cursor);
2705 put_till_end_and_adv_cursor();
2709 if (initial_settings.c_cc[VINTR] != 0
2710 && ic_raw == initial_settings.c_cc[VINTR]
2712 /* Ctrl-C (usually) - stop gathering input */
2715 break_out = -1; /* "do not append '\n'" */
2718 if (initial_settings.c_cc[VEOF] != 0
2719 && ic_raw == initial_settings.c_cc[VEOF]
2721 /* Ctrl-D (usually) - delete one character,
2722 * or exit if len=0 and no chars to delete */
2723 if (command_len == 0) {
2726 case -1: /* error (e.g. EIO when tty is destroyed) */
2727 IF_FEATURE_EDITING_VI(return_error_indicator:)
2728 break_out = command_len = -1;
2734 // /* Control-V -- force insert of next char */
2735 // if (c == CTRL('V')) {
2736 // if (safe_read(STDIN_FILENO, &c, 1) < 1)
2737 // goto return_error_indicator;
2744 || (!ENABLE_UNICODE_SUPPORT && ic >= 256)
2745 || (ENABLE_UNICODE_SUPPORT && ic >= VI_CMDMODE_BIT)
2747 /* If VI_CMDMODE_BIT is set, ic is >= 256
2748 * and vi mode ignores unexpected chars.
2749 * Otherwise, we are here if ic is a
2750 * control char or an unhandled ESC sequence,
2751 * which is also ignored.
2755 if ((int)command_len >= (maxsize - 2)) {
2756 /* Not enough space for the char and EOL */
2761 if (cursor == (command_len - 1)) {
2762 /* We are at the end, append */
2763 command_ps[cursor] = ic;
2764 command_ps[cursor + 1] = BB_NUL;
2765 put_cur_glyph_and_inc_cursor();
2766 if (unicode_bidi_isrtl(ic))
2769 /* In the middle, insert */
2772 memmove(command_ps + sc + 1, command_ps + sc,
2773 (command_len - sc) * sizeof(command_ps[0]));
2774 command_ps[sc] = ic;
2775 /* is right-to-left char, or neutral one (e.g. comma) was just added to rtl text? */
2778 put_till_end_and_adv_cursor();
2779 /* to prev x pos + 1 */
2780 input_backward(cursor - sc);
2788 #if ENABLE_FEATURE_TAB_COMPLETION
2794 #if ENABLE_FEATURE_EDITING_ASK_TERMINAL
2795 if (S.sent_ESC_br6n) {
2796 /* "sleep 1; busybox ash" + hold [Enter] to trigger.
2797 * We sent "ESC [ 6 n", but got '\n' first, and
2798 * KEYCODE_CURSOR_POS response is now buffered from terminal.
2799 * It's bad already and not much can be done with it
2800 * (it _will_ be visible for the next process to read stdin),
2801 * but without this delay it even shows up on the screen
2802 * as garbage because we restore echo settings with tcsetattr
2803 * before it comes in. UGLY!
2809 /* End of bug-catching "command_must_not_be_used" trick */
2812 #if ENABLE_UNICODE_SUPPORT
2814 if (command_len > 0)
2815 command_len = save_string(command, maxsize - 1);
2819 if (command_len > 0) {
2820 remember_in_history(command);
2823 if (break_out > 0) {
2824 command[command_len++] = '\n';
2825 command[command_len] = '\0';
2828 #if ENABLE_FEATURE_TAB_COMPLETION
2829 free_tab_completion_data();
2832 /* restore initial_settings */
2833 tcsetattr_stdin_TCSANOW(&initial_settings);
2834 /* restore SIGWINCH handler */
2835 signal(SIGWINCH, previous_SIGWINCH_handler);
2841 return len; /* can't return command_len, DEINIT_S() destroys it */
2844 #else /* !FEATURE_EDITING */
2846 #undef read_line_input
2847 int FAST_FUNC read_line_input(const char* prompt, char* command, int maxsize)
2849 fputs(prompt, stdout);
2851 if (!fgets(command, maxsize, stdin))
2853 return strlen(command);
2856 #endif /* !FEATURE_EDITING */
2867 const char *applet_name = "debug stuff usage";
2869 int main(int argc, char **argv)
2871 char buff[MAX_LINELEN];
2873 #if ENABLE_FEATURE_EDITING_FANCY_PROMPT
2874 "\\[\\033[32;1m\\]\\u@\\[\\x1b[33;1m\\]\\h:"
2875 "\\[\\033[34;1m\\]\\w\\[\\033[35;1m\\] "
2876 "\\!\\[\\e[36;1m\\]\\$ \\[\\E[0m\\]";
2883 l = read_line_input(prompt, buff);
2884 if (l <= 0 || buff[l-1] != '\n')
2887 printf("*** read_line_input() returned line =%s=\n", buff);
2889 printf("*** read_line_input() detect ^D\n");