1 /* vi: set sw=4 ts=4: */
3 * Termios command line History and Editing.
5 * Copyright (c) 1986-2003 may safely be consumed by a BSD or GPL license.
6 * Written by: Vladimir Oleynik <dzo@simtreas.ru>
9 * Adam Rogoyski <rogoyski@cs.utexas.edu>
10 * Dave Cinege <dcinege@psychosis.com>
11 * Jakub Jelinek (c) 1995
12 * Erik Andersen <andersen@codepoet.org> (Majorly adjusted for busybox)
14 * This code is 'as is' with no warranty.
18 * Usage and known bugs:
19 * Terminal key codes are not extensive, more needs to be added.
20 * This version was created on Debian GNU/Linux 2.x.
21 * Delete, Backspace, Home, End, and the arrow keys were tested
22 * to work in an Xterm and console. Ctrl-A also works as Home.
23 * Ctrl-E also works as End.
25 * The following readline-like commands are not implemented:
26 * ESC-b -- Move back one word
27 * ESC-f -- Move forward one word
28 * ESC-d -- Delete forward one word
29 * CTL-t -- Transpose two characters
31 * lineedit does not know that the terminal escape sequences do not
32 * take up space on the screen. The redisplay code assumes, unless
33 * told otherwise, that each character in the prompt is a printable
34 * character that takes up one character position on the screen.
35 * You need to tell lineedit that some sequences of characters
36 * in the prompt take up no screen space. Compatibly with readline,
37 * use the \[ escape to begin a sequence of non-printing characters,
38 * and the \] escape to signal the end of such a sequence. Example:
40 * PS1='\[\033[01;32m\]\u@\h\[\033[01;34m\] \w \$\[\033[00m\] '
45 /* FIXME: obsolete CONFIG item? */
46 #define ENABLE_FEATURE_NONPRINTABLE_INVERSE_PUT 0
49 # define ENABLE_FEATURE_EDITING 0
50 # define ENABLE_FEATURE_TAB_COMPLETION 0
51 # define ENABLE_FEATURE_USERNAME_COMPLETION 0
52 # define ENABLE_FEATURE_NONPRINTABLE_INVERSE_PUT 0
56 /* Entire file (except TESTing part) sits inside this #if */
57 #if ENABLE_FEATURE_EDITING
60 #define ENABLE_FEATURE_GETUSERNAME_AND_HOMEDIR \
61 (ENABLE_FEATURE_USERNAME_COMPLETION || ENABLE_FEATURE_EDITING_FANCY_PROMPT)
62 #define IF_FEATURE_GETUSERNAME_AND_HOMEDIR(...)
63 #if ENABLE_FEATURE_GETUSERNAME_AND_HOMEDIR
64 #undef IF_FEATURE_GETUSERNAME_AND_HOMEDIR
65 #define IF_FEATURE_GETUSERNAME_AND_HOMEDIR(...) __VA_ARGS__
70 #if ENABLE_FEATURE_ASSUME_UNICODE
72 # define CHAR_T wchar_t
73 static bool BB_isspace(CHAR_T c) { return ((unsigned)c < 256 && isspace(c)); }
74 static bool BB_isalnum(CHAR_T c) { return ((unsigned)c < 256 && isalnum(c)); }
75 static bool BB_ispunct(CHAR_T c) { return ((unsigned)c < 256 && ispunct(c)); }
80 # define isspace isspace_must_not_be_used
81 # define isalnum isalnum_must_not_be_used
82 # define ispunct ispunct_must_not_be_used
83 # define isprint isprint_must_not_be_used
87 # define BB_isspace(c) isspace(c)
88 # define BB_isalnum(c) isalnum(c)
89 # define BB_ispunct(c) ispunct(c)
94 /* We use int16_t for positions, need to limit line len */
95 MAX_LINELEN = CONFIG_FEATURE_EDITING_MAX_LEN < 0x7ff0
96 ? CONFIG_FEATURE_EDITING_MAX_LEN
100 #if ENABLE_FEATURE_GETUSERNAME_AND_HOMEDIR
101 static const char null_str[] ALIGN1 = "";
104 /* We try to minimize both static and stack usage. */
105 struct lineedit_statics {
108 volatile unsigned cmdedit_termw; /* = 80; */ /* actual terminal width */
109 sighandler_t previous_SIGWINCH_handler;
111 unsigned cmdedit_x; /* real x (col) terminal position */
112 unsigned cmdedit_y; /* pseudoreal y (row) terminal position */
113 unsigned cmdedit_prmt_len; /* length of prompt (without colors etc) */
116 int command_len; /* must be signed */
117 /* signed maxsize: we want x in "if (x > S.maxsize)"
118 * to _not_ be promoted to unsigned */
122 const char *cmdedit_prompt;
123 #if ENABLE_FEATURE_EDITING_FANCY_PROMPT
124 int num_ok_lines; /* = 1; */
127 #if ENABLE_FEATURE_GETUSERNAME_AND_HOMEDIR
129 char *home_pwd_buf; /* = (char*)null_str; */
132 #if ENABLE_FEATURE_TAB_COMPLETION
134 unsigned num_matches;
137 #if ENABLE_FEATURE_EDITING_VI
138 #define DELBUFSIZ 128
140 smallint newdelflag; /* whether delbuf should be reused yet */
141 CHAR_T delbuf[DELBUFSIZ]; /* a place to store deleted characters */
143 #if ENABLE_FEATURE_EDITING_ASK_TERMINAL
144 smallint sent_ESC_br6n;
147 /* Formerly these were big buffers on stack: */
148 #if ENABLE_FEATURE_TAB_COMPLETION
149 char exe_n_cwd_tab_completion__dirbuf[MAX_LINELEN];
150 char input_tab__matchBuf[MAX_LINELEN];
151 int16_t find_match__int_buf[MAX_LINELEN + 1]; /* need to have 9 bits at least */
152 int16_t find_match__pos_buf[MAX_LINELEN + 1];
156 /* See lineedit_ptr_hack.c */
157 extern struct lineedit_statics *const lineedit_ptr_to_statics;
159 #define S (*lineedit_ptr_to_statics)
160 #define state (S.state )
161 #define cmdedit_termw (S.cmdedit_termw )
162 #define previous_SIGWINCH_handler (S.previous_SIGWINCH_handler)
163 #define cmdedit_x (S.cmdedit_x )
164 #define cmdedit_y (S.cmdedit_y )
165 #define cmdedit_prmt_len (S.cmdedit_prmt_len)
166 #define cursor (S.cursor )
167 #define command_len (S.command_len )
168 #define command_ps (S.command_ps )
169 #define cmdedit_prompt (S.cmdedit_prompt )
170 #define num_ok_lines (S.num_ok_lines )
171 #define user_buf (S.user_buf )
172 #define home_pwd_buf (S.home_pwd_buf )
173 #define matches (S.matches )
174 #define num_matches (S.num_matches )
175 #define delptr (S.delptr )
176 #define newdelflag (S.newdelflag )
177 #define delbuf (S.delbuf )
179 #define INIT_S() do { \
180 (*(struct lineedit_statics**)&lineedit_ptr_to_statics) = xzalloc(sizeof(S)); \
182 cmdedit_termw = 80; \
183 IF_FEATURE_EDITING_FANCY_PROMPT(num_ok_lines = 1;) \
184 IF_FEATURE_GETUSERNAME_AND_HOMEDIR(home_pwd_buf = (char*)null_str;) \
186 static void deinit_S(void)
188 #if ENABLE_FEATURE_EDITING_FANCY_PROMPT
189 /* This one is allocated only if FANCY_PROMPT is on
190 * (otherwise it points to verbatim prompt (NOT malloced) */
191 free((char*)cmdedit_prompt);
193 #if ENABLE_FEATURE_GETUSERNAME_AND_HOMEDIR
195 if (home_pwd_buf != null_str)
198 free(lineedit_ptr_to_statics);
200 #define DEINIT_S() deinit_S()
203 #if ENABLE_FEATURE_ASSUME_UNICODE
204 static size_t load_string(const char *src, int maxsize)
206 ssize_t len = mbstowcs(command_ps, src, maxsize - 1);
209 command_ps[len] = L'\0';
212 static size_t save_string(char *dst, int maxsize)
214 ssize_t len = wcstombs(dst, command_ps, maxsize - 1);
220 /* I thought just fputwc(c, stdout) would work. But no... */
221 static void BB_PUTCHAR(wchar_t c)
223 char buf[MB_CUR_MAX + 1];
224 mbstate_t mbst = { 0 };
225 ssize_t len = wcrtomb(buf, c, &mbst);
233 static size_t load_string(const char *src, int maxsize)
235 safe_strncpy(command_ps, src, maxsize);
236 return strlen(command_ps);
238 # if ENABLE_FEATURE_TAB_COMPLETION
239 static void save_string(char *dst, int maxsize)
241 safe_strncpy(dst, command_ps, maxsize);
244 # define BB_PUTCHAR(c) bb_putchar(c)
248 /* Put 'command_ps[cursor]', cursor++.
249 * Advance cursor on screen. If we reached right margin, scroll text up
250 * and remove terminal margin effect by printing 'next_char' */
251 #define HACK_FOR_WRONG_WIDTH 1
252 #if HACK_FOR_WRONG_WIDTH
253 static void cmdedit_set_out_char(void)
254 #define cmdedit_set_out_char(next_char) cmdedit_set_out_char()
256 static void cmdedit_set_out_char(int next_char)
259 CHAR_T c = command_ps[cursor];
262 /* erase character after end of input string */
265 #if ENABLE_FEATURE_NONPRINTABLE_INVERSE_PUT
266 /* Display non-printable characters in reverse */
267 if (!BB_isprint(c)) {
274 printf("\033[7m%c\033[0m", c);
280 if (++cmdedit_x >= cmdedit_termw) {
281 /* terminal is scrolled down */
284 #if HACK_FOR_WRONG_WIDTH
285 /* This works better if our idea of term width is wrong
286 * and it is actually wider (often happens on serial lines).
287 * Printing CR,LF *forces* cursor to next line.
288 * OTOH if terminal width is correct AND terminal does NOT
289 * have automargin (IOW: it is moving cursor to next line
290 * by itself (which is wrong for VT-10x terminals)),
291 * this will break things: there will be one extra empty line */
292 puts("\r"); /* + implicit '\n' */
294 /* Works ok only if cmdedit_termw is correct */
295 /* destroy "(auto)margin" */
296 bb_putchar(next_char);
300 // Huh? What if command_ps[cursor] == BB_NUL (we are at the end already?)
304 /* Move to end of line (by printing all chars till the end) */
305 static void input_end(void)
307 while (cursor < command_len)
308 cmdedit_set_out_char(' ');
311 /* Go to the next line */
312 static void goto_new_line(void)
320 static void out1str(const char *s)
326 static void beep(void)
331 /* Move back one character */
332 /* (optimized for slow terminals) */
333 static void input_backward(unsigned num)
343 if (cmdedit_x >= num) {
346 /* This is longer by 5 bytes on x86.
347 * Also gets miscompiled for ARM users
348 * (busybox.net/bugs/view.php?id=2274).
349 * printf(("\b\b\b\b" + 4) - num);
357 printf("\033[%uD", num);
361 /* Need to go one or more lines up */
364 unsigned w = cmdedit_termw; /* volatile var */
365 count_y = 1 + (num / w);
366 cmdedit_y -= count_y;
367 cmdedit_x = w * count_y - num;
369 /* go to 1st column; go up; go to correct column */
370 printf("\r" "\033[%dA" "\033[%dC", count_y, cmdedit_x);
373 static void put_prompt(void)
375 out1str(cmdedit_prompt);
377 #if ENABLE_FEATURE_EDITING_ASK_TERMINAL
379 /* Ask terminal where is the cursor now.
380 * lineedit_read_key handles response and corrects
381 * our idea of current cursor position.
382 * Testcase: run "echo -n long_line_long_line_long_line",
383 * then type in a long, wrapping command and try to
384 * delete it using backspace key.
385 * Note: we print it _after_ prompt, because
386 * prompt may contain CR. Example: PS1='\[\r\n\]\w '
388 /* Problem: if there is buffered input on stdin,
389 * the response will be delivered later,
390 * possibly to an unsuspecting application.
391 * Testcase: "sleep 1; busybox ash" + press and hold [Enter].
393 * ~/srcdevel/bbox/fix/busybox.t4 #
394 * ~/srcdevel/bbox/fix/busybox.t4 #
395 * ^[[59;34~/srcdevel/bbox/fix/busybox.t4 # <-- garbage
396 * ~/srcdevel/bbox/fix/busybox.t4 #
398 * Checking for input with poll only makes the race narrower,
399 * I still can trigger it. Strace:
401 * write(1, "~/srcdevel/bbox/fix/busybox.t4 # ", 33) = 33
402 * poll([{fd=0, events=POLLIN}], 1, 0) = 0 (Timeout) <-- no input exists
403 * write(1, "\33[6n", 4) = 4 <-- send the ESC sequence, quick!
404 * poll([{fd=0, events=POLLIN}], 1, 4294967295) = 1 ([{fd=0, revents=POLLIN}])
405 * read(0, "\n", 1) = 1 <-- oh crap, user's input got in first
409 pfd.fd = STDIN_FILENO;
411 if (safe_poll(&pfd, 1, 0) == 0) {
413 out1str("\033" "[6n");
414 fflush(NULL); /* make terminal see it ASAP! */
420 unsigned w = cmdedit_termw; /* volatile var */
421 cmdedit_y = cmdedit_prmt_len / w; /* new quasireal y */
422 cmdedit_x = cmdedit_prmt_len % w;
426 /* draw prompt, editor line, and clear tail */
427 static void redraw(int y, int back_cursor)
429 if (y > 0) /* up to start y */
430 printf("\033[%uA", y);
433 input_end(); /* rewrite */
434 printf("\033[J"); /* erase after cursor */
435 input_backward(back_cursor);
438 /* Delete the char in front of the cursor, optionally saving it
439 * for later putback */
440 #if !ENABLE_FEATURE_EDITING_VI
441 static void input_delete(void)
442 #define input_delete(save) input_delete()
444 static void input_delete(int save)
449 if (j == (int)command_len)
452 #if ENABLE_FEATURE_EDITING_VI
458 if ((delptr - delbuf) < DELBUFSIZ)
459 *delptr++ = command_ps[j];
463 memmove(command_ps + j, command_ps + j + 1,
464 /* (command_len + 1 [because of NUL]) - (j + 1)
465 * simplified into (command_len - j) */
466 (command_len - j) * sizeof(command_ps[0]));
468 input_end(); /* rewrite new line */
469 cmdedit_set_out_char(' '); /* erase char */
470 input_backward(cursor - j); /* back to old pos cursor */
473 #if ENABLE_FEATURE_EDITING_VI
474 static void put(void)
477 int j = delptr - delbuf;
482 /* open hole and then fill it */
483 memmove(command_ps + cursor + j, command_ps + cursor,
484 (command_len - cursor + 1) * sizeof(command_ps[0]));
485 memcpy(command_ps + cursor, delbuf, j * sizeof(command_ps[0]));
487 input_end(); /* rewrite new line */
488 input_backward(cursor - ocursor - j + 1); /* at end of new text */
492 /* Delete the char in back of the cursor */
493 static void input_backspace(void)
501 /* Move forward one character */
502 static void input_forward(void)
504 if (cursor < command_len)
505 cmdedit_set_out_char(command_ps[cursor + 1]);
508 #if ENABLE_FEATURE_TAB_COMPLETION
510 static void free_tab_completion_data(void)
514 free(matches[--num_matches]);
520 static void add_match(char *matched)
522 matches = xrealloc_vector(matches, 4, num_matches);
523 matches[num_matches] = matched;
527 #if ENABLE_FEATURE_USERNAME_COMPLETION
528 static void username_tab_completion(char *ud, char *with_shash_flg)
530 struct passwd *entry;
533 ud++; /* ~user/... to user/... */
534 userlen = strlen(ud);
536 if (with_shash_flg) { /* "~/..." or "~user/..." */
537 char *sav_ud = ud - 1;
540 if (*ud == '/') { /* "~/..." */
545 temp = strchr(ud, '/');
546 *temp = '\0'; /* ~user\0 */
547 entry = getpwnam(ud);
548 *temp = '/'; /* restore ~user/... */
551 home = entry->pw_dir;
554 if ((userlen + strlen(home) + 1) < MAX_LINELEN) {
556 sprintf(sav_ud, "%s%s", home, ud);
561 /* Using _r function to avoid pulling in static buffers */
564 struct passwd *result;
567 while (!getpwent_r(&pwd, line_buff, sizeof(line_buff), &result)) {
568 /* Null usernames should result in all users as possible completions. */
569 if (/*!userlen || */ strncmp(ud, pwd.pw_name, userlen) == 0) {
570 add_match(xasprintf("~%s/", pwd.pw_name));
576 #endif /* FEATURE_COMMAND_USERNAME_COMPLETION */
584 static int path_parse(char ***p, int flags)
591 /* if not setenv PATH variable, to search cur dir "." */
592 if (flags != FIND_EXE_ONLY)
595 if (state->flags & WITH_PATH_LOOKUP)
596 pth = state->path_lookup;
598 pth = getenv("PATH");
599 /* PATH=<empty> or PATH=:<empty> */
600 if (!pth || !pth[0] || LONE_CHAR(pth, ':'))
604 npth = 1; /* path component count */
606 tmp = strchr(tmp, ':');
610 break; /* :<empty> */
614 res = xmalloc(npth * sizeof(char*));
615 res[0] = tmp = xstrdup(pth);
618 tmp = strchr(tmp, ':');
621 *tmp++ = '\0'; /* ':' -> '\0' */
623 break; /* :<empty> */
630 static void exe_n_cwd_tab_completion(char *command, int type)
636 char **paths = path1;
640 char *pfind = strrchr(command, '/');
641 /* char dirbuf[MAX_LINELEN]; */
642 #define dirbuf (S.exe_n_cwd_tab_completion__dirbuf)
645 path1[0] = (char*)".";
648 /* no dir, if flags==EXE_ONLY - get paths, else "." */
649 npaths = path_parse(&paths, type);
652 /* dirbuf = ".../.../.../" */
653 safe_strncpy(dirbuf, command, (pfind - command) + 2);
654 #if ENABLE_FEATURE_USERNAME_COMPLETION
655 if (dirbuf[0] == '~') /* ~/... or ~user/... */
656 username_tab_completion(dirbuf, dirbuf);
659 /* point to 'l' in "..../last_component" */
663 for (i = 0; i < npaths; i++) {
664 dir = opendir(paths[i]);
666 continue; /* don't print an error */
668 while ((next = readdir(dir)) != NULL) {
670 const char *str_found = next->d_name;
673 if (strncmp(str_found, pfind, strlen(pfind)))
675 /* not see .name without .match */
676 if (*str_found == '.' && *pfind == '\0') {
677 if (NOT_LONE_CHAR(paths[i], '/') || str_found[1])
679 str_found = ""; /* only "/" */
681 found = concat_path_file(paths[i], str_found);
682 /* hmm, remove in progress? */
683 /* NB: stat() first so that we see is it a directory;
684 * but if that fails, use lstat() so that
685 * we still match dangling links */
686 if (stat(found, &st) && lstat(found, &st))
688 /* find with dirs? */
689 if (paths[i] != dirbuf)
690 strcpy(found, next->d_name); /* only name */
692 len1 = strlen(found);
693 found = xrealloc(found, len1 + 2);
695 found[len1+1] = '\0';
697 if (S_ISDIR(st.st_mode)) {
698 /* name is a directory */
699 if (found[len1-1] != '/') {
703 /* not put found file if search only dirs for cd */
704 if (type == FIND_DIR_ONLY)
707 /* Add it to the list */
715 if (paths != path1) {
716 free(paths[0]); /* allocated memory is only in first member */
722 /* QUOT is used on elements of int_buf[], which are bytes,
723 * not Unicode chars. Therefore it works correctly even in Unicode mode.
725 #define QUOT (UCHAR_MAX+1)
727 #define int_buf (S.find_match__int_buf)
728 #define pos_buf (S.find_match__pos_buf)
729 /* is must be <= in */
730 static void collapse_pos(int is, int in)
732 memmove(int_buf+is, int_buf+in, (MAX_LINELEN+1-in)*sizeof(int_buf[0]));
733 memmove(pos_buf+is, pos_buf+in, (MAX_LINELEN+1-in)*sizeof(pos_buf[0]));
735 static NOINLINE int find_match(char *matchBuf, int *len_with_quotes)
740 /* Were local, but it uses too much stack */
741 /* int16_t int_buf[MAX_LINELEN + 1]; */
742 /* int16_t pos_buf[MAX_LINELEN + 1]; */
744 /* set to integer dimension characters and own positions */
746 int_buf[i] = (unsigned char)matchBuf[i];
747 if (int_buf[i] == 0) {
748 pos_buf[i] = -1; /* end-fo-line indicator */
754 /* mask \+symbol and convert '\t' to ' ' */
755 for (i = j = 0; matchBuf[i]; i++, j++)
756 if (matchBuf[i] == '\\') {
757 collapse_pos(j, j + 1);
760 #if ENABLE_FEATURE_NONPRINTABLE_INVERSE_PUT
761 if (matchBuf[i] == '\t') /* algorithm equivalent */
762 int_buf[j] = ' ' | QUOT;
765 #if ENABLE_FEATURE_NONPRINTABLE_INVERSE_PUT
766 else if (matchBuf[i] == '\t')
770 /* mask "symbols" or 'symbols' */
772 for (i = 0; int_buf[i]; i++) {
774 if (c == '\'' || c == '"') {
783 } else if (c2 != 0 && c != '$')
787 /* skip commands with arguments if line has commands delimiters */
788 /* ';' ';;' '&' '|' '&&' '||' but `>&' `<&' `>|' */
789 for (i = 0; int_buf[i]; i++) {
792 j = i ? int_buf[i - 1] : -1;
794 if (c == ';' || c == '&' || c == '|') {
795 command_mode = 1 + (c == c2);
797 if (j == '>' || j == '<')
799 } else if (c == '|' && j == '>')
803 collapse_pos(0, i + command_mode);
804 i = -1; /* hack incremet */
807 /* collapse `command...` */
808 for (i = 0; int_buf[i]; i++) {
809 if (int_buf[i] == '`') {
810 for (j = i + 1; int_buf[j]; j++)
811 if (int_buf[j] == '`') {
812 collapse_pos(i, j + 1);
817 /* not found closing ` - command mode, collapse all previous */
818 collapse_pos(0, i + 1);
821 i--; /* hack incremet */
825 /* collapse (command...(command...)...) or {command...{command...}...} */
826 c = 0; /* "recursive" level */
828 for (i = 0; int_buf[i]; i++) {
829 if (int_buf[i] == '(' || int_buf[i] == '{') {
830 if (int_buf[i] == '(')
834 collapse_pos(0, i + 1);
835 i = -1; /* hack incremet */
838 for (i = 0; pos_buf[i] >= 0 && (c > 0 || c2 > 0); i++) {
839 if ((int_buf[i] == ')' && c > 0) || (int_buf[i] == '}' && c2 > 0)) {
840 if (int_buf[i] == ')')
844 collapse_pos(0, i + 1);
845 i = -1; /* hack incremet */
849 /* skip first not quote space */
850 for (i = 0; int_buf[i]; i++)
851 if (int_buf[i] != ' ')
856 /* set find mode for completion */
857 command_mode = FIND_EXE_ONLY;
858 for (i = 0; int_buf[i]; i++) {
859 if (int_buf[i] == ' ' || int_buf[i] == '<' || int_buf[i] == '>') {
860 if (int_buf[i] == ' ' && command_mode == FIND_EXE_ONLY
861 && matchBuf[pos_buf[0]] == 'c'
862 && matchBuf[pos_buf[1]] == 'd'
864 command_mode = FIND_DIR_ONLY;
866 command_mode = FIND_FILE_ONLY;
871 for (i = 0; int_buf[i]; i++)
874 for (--i; i >= 0; i--) {
876 if (c == ' ' || c == '<' || c == '>' || c == '|' || c == '&') {
877 collapse_pos(0, i + 1);
881 /* skip first not quoted '\'' or '"' */
882 for (i = 0; int_buf[i] == '\'' || int_buf[i] == '"'; i++)
884 /* collapse quote or unquote // or /~ */
885 while ((int_buf[i] & ~QUOT) == '/'
886 && ((int_buf[i+1] & ~QUOT) == '/' || (int_buf[i+1] & ~QUOT) == '~')
891 /* set only match and destroy quotes */
893 for (c = 0; pos_buf[i] >= 0; i++) {
894 matchBuf[c++] = matchBuf[pos_buf[i]];
898 /* old length matchBuf with quotes symbols */
899 *len_with_quotes = j ? j - pos_buf[0] : 0;
907 * display by column (original idea from ls applet,
908 * very optimized by me :)
910 static void showfiles(void)
913 int column_width = 0;
914 int nfiles = num_matches;
918 /* find the longest file name - use that as the column width */
919 for (row = 0; row < nrows; row++) {
920 l = bb_mbstrlen(matches[row]);
921 if (column_width < l)
924 column_width += 2; /* min space for columns */
925 ncols = cmdedit_termw / column_width;
930 nrows++; /* round up fractionals */
934 for (row = 0; row < nrows; row++) {
938 for (nc = 1; nc < ncols && n+nrows < nfiles; n += nrows, nc++) {
939 printf("%s%-*s", matches[n],
940 (int)(column_width - bb_mbstrlen(matches[n])), ""
947 static char *add_quote_for_spec_chars(char *found)
950 char *s = xzalloc((strlen(found) + 1) * 2);
953 if (strchr(" `\"#$%^&*()=+{}[]:;'|\\<>", *found))
957 /* s[l] = '\0'; - already is */
961 /* Do TAB completion */
962 static void input_tab(smallint *lastWasTab)
964 if (!(state->flags & TAB_COMPLETION))
970 /* char matchBuf[MAX_LINELEN]; */
971 #define matchBuf (S.input_tab__matchBuf)
974 #if ENABLE_FEATURE_ASSUME_UNICODE
975 /* cursor pos in command converted to multibyte form */
979 *lastWasTab = TRUE; /* flop trigger */
981 /* Make a local copy of the string --
982 * up to the position of the cursor */
983 save_string(matchBuf, cursor + 1);
984 #if ENABLE_FEATURE_ASSUME_UNICODE
985 cursor_mb = strlen(matchBuf);
989 find_type = find_match(matchBuf, &recalc_pos);
991 /* Free up any memory already allocated */
992 free_tab_completion_data();
994 #if ENABLE_FEATURE_USERNAME_COMPLETION
995 /* If the word starts with `~' and there is no slash in the word,
996 * then try completing this word as a username. */
997 if (state->flags & USERNAME_COMPLETION)
998 if (matchBuf[0] == '~' && strchr(matchBuf, '/') == NULL)
999 username_tab_completion(matchBuf, NULL);
1001 /* Try to match any executable in our path and everything
1002 * in the current working directory */
1004 exe_n_cwd_tab_completion(matchBuf, find_type);
1005 /* Sort, then remove any duplicates found */
1009 qsort_string_vector(matches, num_matches);
1010 for (i = 0; i < num_matches - 1; ++i) {
1011 if (matches[i] && matches[i+1]) { /* paranoia */
1012 if (strcmp(matches[i], matches[i+1]) == 0) {
1014 matches[i] = NULL; /* paranoia */
1016 matches[n++] = matches[i];
1020 matches[n] = matches[i];
1021 num_matches = n + 1;
1023 /* Did we find exactly one match? */
1024 if (!matches || num_matches > 1) { /* no */
1027 return; /* not found */
1028 /* find minimal match */
1029 tmp1 = xstrdup(matches[0]);
1030 for (tmp = tmp1; *tmp; tmp++) {
1031 for (len_found = 1; len_found < num_matches; len_found++) {
1032 if (matches[len_found][tmp - tmp1] != *tmp) {
1038 if (*tmp1 == '\0') { /* have unique */
1042 tmp = add_quote_for_spec_chars(tmp1);
1044 } else { /* one match */
1045 tmp = add_quote_for_spec_chars(matches[0]);
1046 /* for next completion current found */
1047 *lastWasTab = FALSE;
1049 len_found = strlen(tmp);
1050 if (tmp[len_found-1] != '/') {
1051 tmp[len_found] = ' ';
1052 tmp[len_found+1] = '\0';
1056 len_found = strlen(tmp);
1057 #if !ENABLE_FEATURE_ASSUME_UNICODE
1058 /* have space to place the match? */
1059 /* The result consists of three parts with these lengths: */
1060 /* (cursor - recalc_pos) + len_found + (command_len - cursor) */
1061 /* it simplifies into: */
1062 if ((int)(len_found + command_len - recalc_pos) < S.maxsize) {
1064 strcpy(matchBuf, command_ps + cursor);
1065 /* add match and tail */
1066 sprintf(&command_ps[cursor - recalc_pos], "%s%s", tmp, matchBuf);
1067 command_len = strlen(command_ps);
1069 recalc_pos = cursor - recalc_pos + len_found;
1070 /* write out the matched command */
1071 redraw(cmdedit_y, command_len - recalc_pos);
1075 char command[MAX_LINELEN];
1076 int len = save_string(command, sizeof(command));
1077 /* have space to place the match? */
1078 /* (cursor_mb - recalc_pos) + len_found + (len - cursor_mb) */
1079 if ((int)(len_found + len - recalc_pos) < MAX_LINELEN) {
1081 strcpy(matchBuf, command + cursor_mb);
1082 /* where do we want to have cursor after all? */
1083 strcpy(&command[cursor_mb - recalc_pos], tmp);
1084 len = load_string(command, S.maxsize);
1085 /* add match and tail */
1086 sprintf(&command[cursor_mb - recalc_pos], "%s%s", tmp, matchBuf);
1087 command_len = load_string(command, S.maxsize);
1088 /* write out the matched command */
1089 redraw(cmdedit_y, command_len - len);
1096 /* Ok -- the last char was a TAB. Since they
1097 * just hit TAB again, print a list of all the
1098 * available choices... */
1099 if (matches && num_matches > 0) {
1100 /* changed by goto_new_line() */
1101 int sav_cursor = cursor;
1103 /* Go to the next line */
1106 redraw(0, command_len - sav_cursor);
1111 #endif /* FEATURE_COMMAND_TAB_COMPLETION */
1114 line_input_t* FAST_FUNC new_line_input_t(int flags)
1116 line_input_t *n = xzalloc(sizeof(*n));
1124 static void save_command_ps_at_cur_history(void)
1126 if (command_ps[0] != BB_NUL) {
1127 int cur = state->cur_history;
1128 free(state->history[cur]);
1130 # if ENABLE_FEATURE_ASSUME_UNICODE
1132 char tbuf[MAX_LINELEN];
1133 save_string(tbuf, sizeof(tbuf));
1134 state->history[cur] = xstrdup(tbuf);
1137 state->history[cur] = xstrdup(command_ps);
1142 /* state->flags is already checked to be nonzero */
1143 static int get_previous_history(void)
1145 if ((state->flags & DO_HISTORY) && state->cur_history) {
1146 save_command_ps_at_cur_history();
1147 state->cur_history--;
1154 static int get_next_history(void)
1156 if (state->flags & DO_HISTORY) {
1157 if (state->cur_history < state->cnt_history) {
1158 save_command_ps_at_cur_history(); /* save the current history line */
1159 return ++state->cur_history;
1166 # if ENABLE_FEATURE_EDITING_SAVEHISTORY
1167 /* We try to ensure that concurrent additions to the history
1168 * do not overwrite each other.
1169 * Otherwise shell users get unhappy.
1171 * History file is trimmed lazily, when it grows several times longer
1172 * than configured MAX_HISTORY lines.
1175 static void free_line_input_t(line_input_t *n)
1177 int i = n->cnt_history;
1179 free(n->history[--i]);
1183 /* state->flags is already checked to be nonzero */
1184 static void load_history(line_input_t *st_parm)
1186 char *temp_h[MAX_HISTORY];
1189 unsigned idx, i, line_len;
1191 /* NB: do not trash old history if file can't be opened */
1193 fp = fopen_for_read(st_parm->hist_file);
1195 /* clean up old history */
1196 for (idx = st_parm->cnt_history; idx > 0;) {
1198 free(st_parm->history[idx]);
1199 st_parm->history[idx] = NULL;
1202 /* fill temp_h[], retaining only last MAX_HISTORY lines */
1203 memset(temp_h, 0, sizeof(temp_h));
1204 st_parm->cnt_history_in_file = idx = 0;
1205 while ((line = xmalloc_fgetline(fp)) != NULL) {
1206 if (line[0] == '\0') {
1212 st_parm->cnt_history_in_file++;
1214 if (idx == MAX_HISTORY)
1219 /* find first non-NULL temp_h[], if any */
1220 if (st_parm->cnt_history_in_file) {
1221 while (temp_h[idx] == NULL) {
1223 if (idx == MAX_HISTORY)
1228 /* copy temp_h[] to st_parm->history[] */
1229 for (i = 0; i < MAX_HISTORY;) {
1234 if (idx == MAX_HISTORY)
1236 line_len = strlen(line);
1237 if (line_len >= MAX_LINELEN)
1238 line[MAX_LINELEN-1] = '\0';
1239 st_parm->history[i++] = line;
1241 st_parm->cnt_history = i;
1245 /* state->flags is already checked to be nonzero */
1246 static void save_history(char *str)
1251 fd = open(state->hist_file, O_WRONLY | O_CREAT | O_APPEND, 0666);
1254 xlseek(fd, 0, SEEK_END); /* paranoia */
1256 str[len] = '\n'; /* we (try to) do atomic write */
1257 len2 = full_write(fd, str, len + 1);
1260 if (len2 != len + 1)
1261 return; /* "wtf?" */
1263 /* did we write so much that history file needs trimming? */
1264 state->cnt_history_in_file++;
1265 if (state->cnt_history_in_file > MAX_HISTORY * 4) {
1268 line_input_t *st_temp;
1271 /* we may have concurrently written entries from others.
1273 st_temp = new_line_input_t(state->flags);
1274 st_temp->hist_file = state->hist_file;
1275 load_history(st_temp);
1277 /* write out temp file and replace hist_file atomically */
1278 new_name = xasprintf("%s.%u.new", state->hist_file, (int) getpid());
1279 fp = fopen_for_write(new_name);
1281 for (i = 0; i < st_temp->cnt_history; i++)
1282 fprintf(fp, "%s\n", st_temp->history[i]);
1284 if (rename(new_name, state->hist_file) == 0)
1285 state->cnt_history_in_file = st_temp->cnt_history;
1288 free_line_input_t(st_temp);
1292 # define load_history(a) ((void)0)
1293 # define save_history(a) ((void)0)
1294 # endif /* FEATURE_COMMAND_SAVEHISTORY */
1296 static void remember_in_history(char *str)
1300 if (!(state->flags & DO_HISTORY))
1304 i = state->cnt_history;
1305 /* Don't save dupes */
1306 if (i && strcmp(state->history[i-1], str) == 0)
1309 free(state->history[MAX_HISTORY]); /* redundant, paranoia */
1310 state->history[MAX_HISTORY] = NULL; /* redundant, paranoia */
1312 /* If history[] is full, remove the oldest command */
1313 /* we need to keep history[MAX_HISTORY] empty, hence >=, not > */
1314 if (i >= MAX_HISTORY) {
1315 free(state->history[0]);
1316 for (i = 0; i < MAX_HISTORY-1; i++)
1317 state->history[i] = state->history[i+1];
1318 /* i == MAX_HISTORY-1 */
1320 /* i <= MAX_HISTORY-1 */
1321 state->history[i++] = xstrdup(str);
1322 /* i <= MAX_HISTORY */
1323 state->cur_history = i;
1324 state->cnt_history = i;
1325 # if MAX_HISTORY > 0 && ENABLE_FEATURE_EDITING_SAVEHISTORY
1326 if ((state->flags & SAVE_HISTORY) && state->hist_file)
1329 IF_FEATURE_EDITING_FANCY_PROMPT(num_ok_lines++;)
1332 #else /* MAX_HISTORY == 0 */
1333 # define remember_in_history(a) ((void)0)
1334 #endif /* MAX_HISTORY */
1337 #if ENABLE_FEATURE_EDITING_VI
1339 * vi mode implemented 2005 by Paul Fox <pgf@foxharp.boston.ma.us>
1342 vi_Word_motion(int eat)
1344 CHAR_T *command = command_ps;
1346 while (cursor < command_len && !BB_isspace(command[cursor]))
1348 if (eat) while (cursor < command_len && BB_isspace(command[cursor]))
1353 vi_word_motion(int eat)
1355 CHAR_T *command = command_ps;
1357 if (BB_isalnum(command[cursor]) || command[cursor] == '_') {
1358 while (cursor < command_len
1359 && (BB_isalnum(command[cursor+1]) || command[cursor+1] == '_')
1363 } else if (BB_ispunct(command[cursor])) {
1364 while (cursor < command_len && BB_ispunct(command[cursor+1]))
1368 if (cursor < command_len)
1372 while (cursor < command_len && BB_isspace(command[cursor]))
1380 CHAR_T *command = command_ps;
1383 while (cursor < command_len && BB_isspace(command[cursor]))
1385 while (cursor < command_len-1 && !BB_isspace(command[cursor+1]))
1392 CHAR_T *command = command_ps;
1394 if (cursor >= command_len-1)
1397 while (cursor < command_len-1 && BB_isspace(command[cursor]))
1399 if (cursor >= command_len-1)
1401 if (BB_isalnum(command[cursor]) || command[cursor] == '_') {
1402 while (cursor < command_len-1
1403 && (BB_isalnum(command[cursor+1]) || command[cursor+1] == '_')
1407 } else if (BB_ispunct(command[cursor])) {
1408 while (cursor < command_len-1 && BB_ispunct(command[cursor+1]))
1414 vi_Back_motion(void)
1416 CHAR_T *command = command_ps;
1418 while (cursor > 0 && BB_isspace(command[cursor-1]))
1420 while (cursor > 0 && !BB_isspace(command[cursor-1]))
1425 vi_back_motion(void)
1427 CHAR_T *command = command_ps;
1432 while (cursor > 0 && BB_isspace(command[cursor]))
1436 if (BB_isalnum(command[cursor]) || command[cursor] == '_') {
1438 && (BB_isalnum(command[cursor-1]) || command[cursor-1] == '_')
1442 } else if (BB_ispunct(command[cursor])) {
1443 while (cursor > 0 && BB_ispunct(command[cursor-1]))
1449 /* Modelled after bash 4.0 behavior of Ctrl-<arrow> */
1450 static void ctrl_left(void)
1452 CHAR_T *command = command_ps;
1460 c = command[cursor];
1461 if (c != ' ' && !BB_ispunct(c)) {
1462 /* we reached a "word" delimited by spaces/punct.
1463 * go to its beginning */
1465 c = command[cursor - 1];
1466 if (c == ' ' || BB_ispunct(c))
1476 static void ctrl_right(void)
1478 CHAR_T *command = command_ps;
1483 c = command[cursor];
1486 if (c != ' ' && !BB_ispunct(c)) {
1487 /* we reached a "word" delimited by spaces/punct.
1488 * go to its end + 1 */
1491 c = command[cursor];
1492 if (c == BB_NUL || c == ' ' || BB_ispunct(c))
1503 * read_line_input and its helpers
1506 #if !ENABLE_FEATURE_EDITING_FANCY_PROMPT
1507 static void parse_and_put_prompt(const char *prmt_ptr)
1509 cmdedit_prompt = prmt_ptr;
1510 cmdedit_prmt_len = strlen(prmt_ptr);
1514 static void parse_and_put_prompt(const char *prmt_ptr)
1517 size_t cur_prmt_len = 0;
1518 char flg_not_length = '[';
1519 char *prmt_mem_ptr = xzalloc(1);
1520 char *cwd_buf = xrealloc_getcwd_or_warn(NULL);
1525 cmdedit_prmt_len = 0;
1528 cwd_buf = (char *)bb_msg_unknown;
1531 cbuf[1] = '\0'; /* never changes */
1534 char *free_me = NULL;
1539 const char *cp = prmt_ptr;
1542 c = bb_process_escape_sequence(&prmt_ptr);
1543 if (prmt_ptr == cp) {
1549 # if ENABLE_FEATURE_GETUSERNAME_AND_HOMEDIR
1551 pbuf = user_buf ? user_buf : (char*)"";
1555 pbuf = free_me = safe_gethostname();
1556 *strchrnul(pbuf, '.') = '\0';
1559 c = (geteuid() == 0 ? '#' : '$');
1561 # if ENABLE_FEATURE_GETUSERNAME_AND_HOMEDIR
1563 /* /home/user[/something] -> ~[/something] */
1565 l = strlen(home_pwd_buf);
1567 && strncmp(home_pwd_buf, cwd_buf, l) == 0
1568 && (cwd_buf[l]=='/' || cwd_buf[l]=='\0')
1569 && strlen(cwd_buf + l) < PATH_MAX
1571 pbuf = free_me = xasprintf("~%s", cwd_buf + l);
1577 cp = strrchr(pbuf, '/');
1578 if (cp != NULL && cp != pbuf)
1579 pbuf += (cp-pbuf) + 1;
1582 pbuf = free_me = xasprintf("%d", num_ok_lines);
1584 case 'e': case 'E': /* \e \E = \033 */
1587 case 'x': case 'X': {
1589 for (l = 0; l < 3;) {
1591 buf2[l++] = *prmt_ptr;
1593 h = strtoul(buf2, &pbuf, 16);
1594 if (h > UCHAR_MAX || (pbuf - buf2) < l) {
1600 c = (char)strtoul(buf2, NULL, 16);
1607 if (c == flg_not_length) {
1608 flg_not_length = (flg_not_length == '[' ? ']' : '[');
1616 cur_prmt_len = strlen(pbuf);
1617 prmt_len += cur_prmt_len;
1618 if (flg_not_length != ']')
1619 cmdedit_prmt_len += cur_prmt_len;
1620 prmt_mem_ptr = strcat(xrealloc(prmt_mem_ptr, prmt_len+1), pbuf);
1624 if (cwd_buf != (char *)bb_msg_unknown)
1626 cmdedit_prompt = prmt_mem_ptr;
1631 static void cmdedit_setwidth(unsigned w, int redraw_flg)
1635 /* new y for current cursor */
1636 int new_y = (cursor + cmdedit_prmt_len) / w;
1638 redraw((new_y >= cmdedit_y ? new_y : cmdedit_y), command_len - cursor);
1643 static void win_changed(int nsig)
1646 get_terminal_width_height(0, &width, NULL);
1647 cmdedit_setwidth(width, nsig /* - just a yes/no flag */);
1648 if (nsig == SIGWINCH)
1649 signal(SIGWINCH, win_changed); /* rearm ourself */
1652 static int lineedit_read_key(char *read_key_buffer)
1657 #if ENABLE_FEATURE_ASSUME_UNICODE
1658 char unicode_buf[MB_CUR_MAX + 1];
1659 int unicode_idx = 0;
1662 pfd.fd = STDIN_FILENO;
1663 pfd.events = POLLIN;
1665 #if ENABLE_FEATURE_EDITING_ASK_TERMINAL || ENABLE_FEATURE_ASSUME_UNICODE
1668 if (read_key_buffer[0] == 0) {
1669 /* Wait for input. Can't just call read_key,
1670 * it returns at once if stdin
1671 * is in non-blocking mode. */
1672 safe_poll(&pfd, 1, delay);
1674 /* Note: read_key sets errno to 0 on success: */
1675 ic = read_key(STDIN_FILENO, read_key_buffer);
1677 #if ENABLE_FEATURE_EDITING_ASK_TERMINAL
1678 if ((int32_t)ic == KEYCODE_CURSOR_POS
1681 S.sent_ESC_br6n = 0;
1682 if (cursor == 0) { /* otherwise it may be bogus */
1683 int col = ((ic >> 32) & 0x7fff) - 1;
1684 if (col > cmdedit_prmt_len) {
1685 cmdedit_x += (col - cmdedit_prmt_len);
1686 while (cmdedit_x >= cmdedit_termw) {
1687 cmdedit_x -= cmdedit_termw;
1696 #if ENABLE_FEATURE_ASSUME_UNICODE
1700 if ((int32_t)ic < 0) /* KEYCODE_xxx */
1702 unicode_buf[unicode_idx++] = ic;
1703 unicode_buf[unicode_idx] = '\0';
1704 if (mbstowcs(&wc, unicode_buf, 1) != 1 && unicode_idx < MB_CUR_MAX) {
1711 } while (errno == EAGAIN);
1716 /* leave out the "vi-mode"-only case labels if vi editing isn't
1718 #define vi_case(caselabel) IF_FEATURE_EDITING_VI(case caselabel)
1720 /* convert uppercase ascii to equivalent control char, for readability */
1722 #define CTRL(a) ((a) & ~0x40)
1724 /* maxsize must be >= 2.
1726 * -1 on read errors or EOF, or on bare Ctrl-D,
1727 * 0 on ctrl-C (the line entered is still returned in 'command'),
1728 * >0 length of input string, including terminating '\n'
1730 int FAST_FUNC read_line_input(const char *prompt, char *command, int maxsize, line_input_t *st)
1733 #if ENABLE_FEATURE_TAB_COMPLETION
1734 smallint lastWasTab = FALSE;
1736 smallint break_out = 0;
1737 #if ENABLE_FEATURE_EDITING_VI
1738 smallint vi_cmdmode = 0;
1740 struct termios initial_settings;
1741 struct termios new_settings;
1742 char read_key_buffer[KEYCODE_BUFFER_SIZE];
1746 if (tcgetattr(STDIN_FILENO, &initial_settings) < 0
1747 || !(initial_settings.c_lflag & ECHO)
1749 /* Happens when e.g. stty -echo was run before */
1750 parse_and_put_prompt(prompt);
1751 /* fflush(stdout); - done by parse_and_put_prompt */
1752 if (fgets(command, maxsize, stdin) == NULL)
1753 len = -1; /* EOF or error */
1755 len = strlen(command);
1760 check_unicode_in_env();
1762 // FIXME: audit & improve this
1763 if (maxsize > MAX_LINELEN)
1764 maxsize = MAX_LINELEN;
1765 S.maxsize = maxsize;
1767 /* With null flags, no other fields are ever used */
1768 state = st ? st : (line_input_t*) &const_int_0;
1770 # if ENABLE_FEATURE_EDITING_SAVEHISTORY
1771 if ((state->flags & SAVE_HISTORY) && state->hist_file)
1772 if (state->cnt_history == 0)
1773 load_history(state);
1775 if (state->flags & DO_HISTORY)
1776 state->cur_history = state->cnt_history;
1779 /* prepare before init handlers */
1780 cmdedit_y = 0; /* quasireal y, not true if line > xt*yt */
1782 #if ENABLE_FEATURE_ASSUME_UNICODE
1783 command_ps = xzalloc(maxsize * sizeof(command_ps[0]));
1785 command_ps = command;
1788 #define command command_must_not_be_used
1790 new_settings = initial_settings;
1791 new_settings.c_lflag &= ~ICANON; /* unbuffered input */
1792 /* Turn off echoing and CTRL-C, so we can trap it */
1793 new_settings.c_lflag &= ~(ECHO | ECHONL | ISIG);
1794 /* Hmm, in linux c_cc[] is not parsed if ICANON is off */
1795 new_settings.c_cc[VMIN] = 1;
1796 new_settings.c_cc[VTIME] = 0;
1797 /* Turn off CTRL-C, so we can trap it */
1798 #ifndef _POSIX_VDISABLE
1799 # define _POSIX_VDISABLE '\0'
1801 new_settings.c_cc[VINTR] = _POSIX_VDISABLE;
1802 tcsetattr_stdin_TCSANOW(&new_settings);
1804 /* Now initialize things */
1805 previous_SIGWINCH_handler = signal(SIGWINCH, win_changed);
1806 win_changed(0); /* do initial resizing */
1807 #if ENABLE_FEATURE_GETUSERNAME_AND_HOMEDIR
1809 struct passwd *entry;
1811 entry = getpwuid(geteuid());
1813 user_buf = xstrdup(entry->pw_name);
1814 home_pwd_buf = xstrdup(entry->pw_dir);
1820 for (i = 0; i <= MAX_HISTORY; i++)
1821 bb_error_msg("history[%d]:'%s'", i, state->history[i]);
1822 bb_error_msg("cur_history:%d cnt_history:%d", state->cur_history, state->cnt_history);
1825 /* Print out the command prompt */
1826 parse_and_put_prompt(prompt);
1828 read_key_buffer[0] = 0;
1831 * The emacs and vi modes share much of the code in the big
1832 * command loop. Commands entered when in vi's command mode
1833 * (aka "escape mode") get an extra bit added to distinguish
1834 * them - this keeps them from being self-inserted. This
1835 * clutters the big switch a bit, but keeps all the code
1839 VI_CMDMODE_BIT = 0x40000000,
1840 /* 0x80000000 bit flags KEYCODE_xxx */
1845 ic = ic_raw = lineedit_read_key(read_key_buffer);
1847 #if ENABLE_FEATURE_EDITING_VI
1850 /* btw, since KEYCODE_xxx are all < 0, this doesn't
1851 * change ic if it contains one of them: */
1852 ic |= VI_CMDMODE_BIT;
1859 vi_case('\n'|VI_CMDMODE_BIT:)
1860 vi_case('\r'|VI_CMDMODE_BIT:)
1866 vi_case('0'|VI_CMDMODE_BIT:)
1867 /* Control-a -- Beginning of line */
1868 input_backward(cursor);
1871 vi_case('h'|VI_CMDMODE_BIT:)
1872 vi_case('\b'|VI_CMDMODE_BIT:)
1873 vi_case('\x7f'|VI_CMDMODE_BIT:) /* DEL */
1874 /* Control-b -- Move back one character */
1878 vi_case('$'|VI_CMDMODE_BIT:)
1879 /* Control-e -- End of line */
1883 vi_case('l'|VI_CMDMODE_BIT:)
1884 vi_case(' '|VI_CMDMODE_BIT:)
1885 /* Control-f -- Move forward one character */
1889 case '\x7f': /* DEL */
1890 /* Control-h and DEL */
1893 #if ENABLE_FEATURE_TAB_COMPLETION
1895 input_tab(&lastWasTab);
1899 /* Control-k -- clear to end of line */
1900 command_ps[cursor] = BB_NUL;
1901 command_len = cursor;
1905 vi_case(CTRL('L')|VI_CMDMODE_BIT:)
1906 /* Control-l -- clear screen */
1908 redraw(0, command_len - cursor);
1912 vi_case(CTRL('N')|VI_CMDMODE_BIT:)
1913 vi_case('j'|VI_CMDMODE_BIT:)
1914 /* Control-n -- Get next command in history */
1915 if (get_next_history())
1919 vi_case(CTRL('P')|VI_CMDMODE_BIT:)
1920 vi_case('k'|VI_CMDMODE_BIT:)
1921 /* Control-p -- Get previous command from history */
1922 if (get_previous_history())
1927 vi_case(CTRL('U')|VI_CMDMODE_BIT:)
1928 /* Control-U -- Clear line before cursor */
1930 command_len -= cursor;
1931 memmove(command_ps, command_ps + cursor,
1932 (command_len + 1) * sizeof(command_ps[0]));
1933 redraw(cmdedit_y, command_len);
1937 vi_case(CTRL('W')|VI_CMDMODE_BIT:)
1938 /* Control-W -- Remove the last word */
1939 while (cursor > 0 && BB_isspace(command_ps[cursor-1]))
1941 while (cursor > 0 && !BB_isspace(command_ps[cursor-1]))
1945 #if ENABLE_FEATURE_EDITING_VI
1946 case 'i'|VI_CMDMODE_BIT:
1949 case 'I'|VI_CMDMODE_BIT:
1950 input_backward(cursor);
1953 case 'a'|VI_CMDMODE_BIT:
1957 case 'A'|VI_CMDMODE_BIT:
1961 case 'x'|VI_CMDMODE_BIT:
1964 case 'X'|VI_CMDMODE_BIT:
1970 case 'W'|VI_CMDMODE_BIT:
1973 case 'w'|VI_CMDMODE_BIT:
1976 case 'E'|VI_CMDMODE_BIT:
1979 case 'e'|VI_CMDMODE_BIT:
1982 case 'B'|VI_CMDMODE_BIT:
1985 case 'b'|VI_CMDMODE_BIT:
1988 case 'C'|VI_CMDMODE_BIT:
1991 case 'D'|VI_CMDMODE_BIT:
1994 case 'c'|VI_CMDMODE_BIT:
1997 case 'd'|VI_CMDMODE_BIT: {
2000 ic = lineedit_read_key(read_key_buffer);
2001 if (errno) /* error */
2002 goto prepare_to_die;
2003 if (ic == ic_raw) { /* "cc", "dd" */
2004 input_backward(cursor);
2016 case 'w': /* "dw", "cw" */
2017 vi_word_motion(vi_cmdmode);
2019 case 'W': /* 'dW', 'cW' */
2020 vi_Word_motion(vi_cmdmode);
2022 case 'e': /* 'de', 'ce' */
2026 case 'E': /* 'dE', 'cE' */
2032 input_backward(cursor - sc);
2033 while (nc-- > cursor)
2036 case 'b': /* "db", "cb" */
2037 case 'B': /* implemented as B */
2042 while (sc-- > cursor)
2045 case ' ': /* "d ", "c " */
2048 case '$': /* "d$", "c$" */
2050 while (cursor < command_len)
2056 case 'p'|VI_CMDMODE_BIT:
2059 case 'P'|VI_CMDMODE_BIT:
2062 case 'r'|VI_CMDMODE_BIT:
2063 //FIXME: unicode case?
2064 ic = lineedit_read_key(read_key_buffer);
2065 if (errno) /* error */
2066 goto prepare_to_die;
2067 if (ic < ' ' || ic > 255) {
2070 command_ps[cursor] = ic;
2075 case '\x1b': /* ESC */
2076 if (state->flags & VI_MODE) {
2077 /* insert mode --> command mode */
2082 #endif /* FEATURE_COMMAND_EDITING_VI */
2086 if (get_previous_history())
2091 if (!get_next_history())
2094 /* Rewrite the line with the selected history item */
2095 /* change command */
2096 command_len = load_string(state->history[state->cur_history] ?
2097 state->history[state->cur_history] : "", maxsize);
2098 /* redraw and go to eol (bol, in vi) */
2099 redraw(cmdedit_y, (state->flags & VI_MODE) ? 9999 : 0);
2108 case KEYCODE_CTRL_LEFT:
2111 case KEYCODE_CTRL_RIGHT:
2114 case KEYCODE_DELETE:
2118 input_backward(cursor);
2125 if (initial_settings.c_cc[VINTR] != 0
2126 && ic_raw == initial_settings.c_cc[VINTR]
2128 /* Ctrl-C (usually) - stop gathering input */
2131 break_out = -1; /* "do not append '\n'" */
2134 if (initial_settings.c_cc[VEOF] != 0
2135 && ic_raw == initial_settings.c_cc[VEOF]
2137 /* Ctrl-D (usually) - delete one character,
2138 * or exit if len=0 and no chars to delete */
2139 if (command_len == 0) {
2141 #if ENABLE_FEATURE_EDITING_VI
2144 break_out = command_len = -1;
2150 // /* Control-V -- force insert of next char */
2151 // if (c == CTRL('V')) {
2152 // if (safe_read(STDIN_FILENO, &c, 1) < 1)
2153 // goto prepare_to_die;
2160 || (!ENABLE_FEATURE_ASSUME_UNICODE && ic >= 256)
2161 || (ENABLE_FEATURE_ASSUME_UNICODE && ic >= VI_CMDMODE_BIT)
2163 /* If VI_CMDMODE_BIT is set, ic is >= 256
2164 * and vi mode ignores unexpected chars.
2165 * Otherwise, we are here if ic is a
2166 * control char or an unhandled ESC sequence,
2167 * which is also ignored.
2171 if ((int)command_len >= (maxsize - 2)) {
2172 /* Not enough space for the char and EOL */
2177 if (cursor == (command_len - 1)) {
2178 /* We are at the end, append */
2179 command_ps[cursor] = ic;
2180 command_ps[cursor + 1] = BB_NUL;
2181 cmdedit_set_out_char(' ');
2183 /* In the middle, insert */
2186 memmove(command_ps + sc + 1, command_ps + sc,
2187 (command_len - sc) * sizeof(command_ps[0]));
2188 command_ps[sc] = ic;
2190 /* rewrite from cursor */
2192 /* to prev x pos + 1 */
2193 input_backward(cursor - sc);
2201 #if ENABLE_FEATURE_TAB_COMPLETION
2207 #if ENABLE_FEATURE_EDITING_ASK_TERMINAL
2208 if (S.sent_ESC_br6n) {
2209 /* "sleep 1; busybox ash" + hold [Enter] to trigger.
2210 * We sent "ESC [ 6 n", but got '\n' first, and
2211 * KEYCODE_CURSOR_POS response is now buffered from terminal.
2212 * It's bad already and not much can be done with it
2213 * (it _will_ be visible for the next process to read stdin),
2214 * but without this delay it even shows up on the screen
2215 * as garbage because we restore echo settings with tcsetattr
2216 * before it comes in. UGLY!
2222 /* Stop bug catching using "command_must_not_be_used" trick */
2225 #if ENABLE_FEATURE_ASSUME_UNICODE
2227 if (command_len > 0)
2228 command_len = save_string(command, maxsize - 1);
2232 if (command_len > 0)
2233 remember_in_history(command);
2235 if (break_out > 0) {
2236 command[command_len++] = '\n';
2237 command[command_len] = '\0';
2240 #if ENABLE_FEATURE_TAB_COMPLETION
2241 free_tab_completion_data();
2244 /* restore initial_settings */
2245 tcsetattr_stdin_TCSANOW(&initial_settings);
2246 /* restore SIGWINCH handler */
2247 signal(SIGWINCH, previous_SIGWINCH_handler);
2253 return len; /* can't return command_len, DEINIT_S() destroys it */
2258 #undef read_line_input
2259 int FAST_FUNC read_line_input(const char* prompt, char* command, int maxsize)
2261 fputs(prompt, stdout);
2263 fgets(command, maxsize, stdin);
2264 return strlen(command);
2267 #endif /* FEATURE_EDITING */
2278 const char *applet_name = "debug stuff usage";
2280 int main(int argc, char **argv)
2282 char buff[MAX_LINELEN];
2284 #if ENABLE_FEATURE_EDITING_FANCY_PROMPT
2285 "\\[\\033[32;1m\\]\\u@\\[\\x1b[33;1m\\]\\h:"
2286 "\\[\\033[34;1m\\]\\w\\[\\033[35;1m\\] "
2287 "\\!\\[\\e[36;1m\\]\\$ \\[\\E[0m\\]";
2292 #if ENABLE_FEATURE_NONPRINTABLE_INVERSE_PUT
2293 setlocale(LC_ALL, "");
2297 l = read_line_input(prompt, buff);
2298 if (l <= 0 || buff[l-1] != '\n')
2301 printf("*** read_line_input() returned line =%s=\n", buff);
2303 printf("*** read_line_input() detect ^D\n");