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, and more will probably
20 * need to be added. 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 * lineedit does not know that the terminal escape sequences do not
26 * take up space on the screen. The redisplay code assumes, unless
27 * told otherwise, that each character in the prompt is a printable
28 * character that takes up one character position on the screen.
29 * You need to tell lineedit that some sequences of characters
30 * in the prompt take up no screen space. Compatibly with readline,
31 * use the \[ escape to begin a sequence of non-printing characters,
32 * and the \] escape to signal the end of such a sequence. Example:
34 * PS1='\[\033[01;32m\]\u@\h\[\033[01;34m\] \w \$\[\033[00m\] '
39 /* FIXME: obsolete CONFIG item? */
40 #define ENABLE_FEATURE_NONPRINTABLE_INVERSE_PUT 0
43 # define ENABLE_FEATURE_EDITING 0
44 # define ENABLE_FEATURE_TAB_COMPLETION 0
45 # define ENABLE_FEATURE_USERNAME_COMPLETION 0
46 # define ENABLE_FEATURE_NONPRINTABLE_INVERSE_PUT 0
50 /* Entire file (except TESTing part) sits inside this #if */
51 #if ENABLE_FEATURE_EDITING
54 #define ENABLE_FEATURE_GETUSERNAME_AND_HOMEDIR \
55 (ENABLE_FEATURE_USERNAME_COMPLETION || ENABLE_FEATURE_EDITING_FANCY_PROMPT)
56 #define IF_FEATURE_GETUSERNAME_AND_HOMEDIR(...)
57 #if ENABLE_FEATURE_GETUSERNAME_AND_HOMEDIR
58 #undef IF_FEATURE_GETUSERNAME_AND_HOMEDIR
59 #define IF_FEATURE_GETUSERNAME_AND_HOMEDIR(...) __VA_ARGS__
64 #if ENABLE_FEATURE_ASSUME_UNICODE
66 # define CHAR_T wchar_t
67 # define BB_isspace(c) iswspace(c)
68 # define BB_isalnum(c) iswalnum(c)
69 # define BB_ispunct(c) iswpunct(c)
70 # define BB_isprint(c) iswprint(c)
71 /* this catches bugs */
76 # define isspace isspace_must_not_be_used
77 # define isalnum isalnum_must_not_be_used
78 # define ispunct ispunct_must_not_be_used
79 # define isprint isprint_must_not_be_used
83 # define BB_isspace(c) isspace(c)
84 # define BB_isalnum(c) isalnum(c)
85 # define BB_ispunct(c) ispunct(c)
86 # if ENABLE_LOCALE_SUPPORT
87 # define BB_isprint(c) isprint(c)
89 # define BB_isprint(c) ((c) >= ' ' && (c) != ((unsigned char)'\233'))
95 /* We use int16_t for positions, need to limit line len */
96 MAX_LINELEN = CONFIG_FEATURE_EDITING_MAX_LEN < 0x7ff0
97 ? CONFIG_FEATURE_EDITING_MAX_LEN
101 #if ENABLE_FEATURE_GETUSERNAME_AND_HOMEDIR
102 static const char null_str[] ALIGN1 = "";
105 /* We try to minimize both static and stack usage. */
106 struct lineedit_statics {
109 volatile unsigned cmdedit_termw; /* = 80; */ /* actual terminal width */
110 sighandler_t previous_SIGWINCH_handler;
112 unsigned cmdedit_x; /* real x (col) terminal position */
113 unsigned cmdedit_y; /* pseudoreal y (row) terminal position */
114 unsigned cmdedit_prmt_len; /* length of prompt (without colors etc) */
117 unsigned command_len;
120 const char *cmdedit_prompt;
121 #if ENABLE_FEATURE_EDITING_FANCY_PROMPT
122 int num_ok_lines; /* = 1; */
125 #if ENABLE_FEATURE_GETUSERNAME_AND_HOMEDIR
127 char *home_pwd_buf; /* = (char*)null_str; */
130 #if ENABLE_FEATURE_TAB_COMPLETION
132 unsigned num_matches;
135 #if ENABLE_FEATURE_EDITING_VI
136 #define DELBUFSIZ 128
138 smallint newdelflag; /* whether delbuf should be reused yet */
139 CHAR_T delbuf[DELBUFSIZ]; /* a place to store deleted characters */
142 /* Formerly these were big buffers on stack: */
143 #if ENABLE_FEATURE_TAB_COMPLETION
144 char exe_n_cwd_tab_completion__dirbuf[MAX_LINELEN];
145 char input_tab__matchBuf[MAX_LINELEN];
146 int16_t find_match__int_buf[MAX_LINELEN + 1]; /* need to have 9 bits at least */
147 int16_t find_match__pos_buf[MAX_LINELEN + 1];
151 /* See lineedit_ptr_hack.c */
152 extern struct lineedit_statics *const lineedit_ptr_to_statics;
154 #define S (*lineedit_ptr_to_statics)
155 #define state (S.state )
156 #define cmdedit_termw (S.cmdedit_termw )
157 #define previous_SIGWINCH_handler (S.previous_SIGWINCH_handler)
158 #define cmdedit_x (S.cmdedit_x )
159 #define cmdedit_y (S.cmdedit_y )
160 #define cmdedit_prmt_len (S.cmdedit_prmt_len)
161 #define cursor (S.cursor )
162 #define command_len (S.command_len )
163 #define command_ps (S.command_ps )
164 #define cmdedit_prompt (S.cmdedit_prompt )
165 #define num_ok_lines (S.num_ok_lines )
166 #define user_buf (S.user_buf )
167 #define home_pwd_buf (S.home_pwd_buf )
168 #define matches (S.matches )
169 #define num_matches (S.num_matches )
170 #define delptr (S.delptr )
171 #define newdelflag (S.newdelflag )
172 #define delbuf (S.delbuf )
174 #define INIT_S() do { \
175 (*(struct lineedit_statics**)&lineedit_ptr_to_statics) = xzalloc(sizeof(S)); \
177 cmdedit_termw = 80; \
178 IF_FEATURE_EDITING_FANCY_PROMPT(num_ok_lines = 1;) \
179 IF_FEATURE_GETUSERNAME_AND_HOMEDIR(home_pwd_buf = (char*)null_str;) \
181 static void deinit_S(void)
183 #if ENABLE_FEATURE_EDITING_FANCY_PROMPT
184 /* This one is allocated only if FANCY_PROMPT is on
185 * (otherwise it points to verbatim prompt (NOT malloced) */
186 free((char*)cmdedit_prompt);
188 #if ENABLE_FEATURE_GETUSERNAME_AND_HOMEDIR
190 if (home_pwd_buf != null_str)
193 free(lineedit_ptr_to_statics);
195 #define DEINIT_S() deinit_S()
198 #if ENABLE_FEATURE_ASSUME_UNICODE
199 static size_t load_string(const char *src, int maxsize)
201 ssize_t len = mbstowcs(command_ps, src, maxsize - 1);
204 command_ps[len] = L'\0';
207 static size_t save_string(char *dst, int maxsize)
209 ssize_t len = wcstombs(dst, command_ps, maxsize - 1);
215 /* I thought just fputwc(c, stdout) would work. But no... */
216 static void BB_PUTCHAR(wchar_t c)
218 char buf[MB_CUR_MAX + 1];
219 mbstate_t mbst = { 0 };
220 ssize_t len = wcrtomb(buf, c, &mbst);
228 static size_t load_string(const char *src, int maxsize)
230 safe_strncpy(command_ps, src, maxsize);
231 return strlen(command_ps);
233 static void save_string(char *dst, int maxsize)
235 safe_strncpy(dst, command_ps, maxsize);
237 #define BB_PUTCHAR(c) bb_putchar(c)
241 /* Put 'command_ps[cursor]', cursor++.
242 * Advance cursor on screen. If we reached right margin, scroll text up
243 * and remove terminal margin effect by printing 'next_char' */
244 #define HACK_FOR_WRONG_WIDTH 1
245 #if HACK_FOR_WRONG_WIDTH
246 static void cmdedit_set_out_char(void)
247 #define cmdedit_set_out_char(next_char) cmdedit_set_out_char()
249 static void cmdedit_set_out_char(int next_char)
252 CHAR_T c = command_ps[cursor];
255 /* erase character after end of input string */
258 #if ENABLE_FEATURE_NONPRINTABLE_INVERSE_PUT
259 /* Display non-printable characters in reverse */
260 if (!BB_isprint(c)) {
267 printf("\033[7m%c\033[0m", c);
273 if (++cmdedit_x >= cmdedit_termw) {
274 /* terminal is scrolled down */
277 #if HACK_FOR_WRONG_WIDTH
278 /* This works better if our idea of term width is wrong
279 * and it is actually wider (often happens on serial lines).
280 * Printing CR,LF *forces* cursor to next line.
281 * OTOH if terminal width is correct AND terminal does NOT
282 * have automargin (IOW: it is moving cursor to next line
283 * by itself (which is wrong for VT-10x terminals)),
284 * this will break things: there will be one extra empty line */
285 puts("\r"); /* + implicit '\n' */
287 /* Works ok only if cmdedit_termw is correct */
288 /* destroy "(auto)margin" */
289 bb_putchar(next_char);
293 // Huh? What if command_ps[cursor] == BB_NUL (we are at the end already?)
297 /* Move to end of line (by printing all chars till the end) */
298 static void input_end(void)
300 while (cursor < command_len)
301 cmdedit_set_out_char(' ');
304 /* Go to the next line */
305 static void goto_new_line(void)
313 static void out1str(const char *s)
319 static void beep(void)
324 /* Move back one character */
325 /* (optimized for slow terminals) */
326 static void input_backward(unsigned num)
336 if (cmdedit_x >= num) {
339 /* This is longer by 5 bytes on x86.
340 * Also gets miscompiled for ARM users
341 * (busybox.net/bugs/view.php?id=2274).
342 * printf(("\b\b\b\b" + 4) - num);
350 printf("\033[%uD", num);
354 /* Need to go one or more lines up */
357 unsigned w = cmdedit_termw; /* volatile var */
358 count_y = 1 + (num / w);
359 cmdedit_y -= count_y;
360 cmdedit_x = w * count_y - num;
362 /* go to 1st column; go up; go to correct column */
363 printf("\r" "\033[%dA" "\033[%dC", count_y, cmdedit_x);
366 static void put_prompt(void)
368 out1str(cmdedit_prompt);
369 if (ENABLE_FEATURE_EDITING_ASK_TERMINAL) {
370 /* Ask terminal where is the cursor now.
371 * lineedit_read_key handles response and corrects
372 * our idea of current cursor position.
373 * Testcase: run "echo -n long_line_long_line_long_line",
374 * then type in a long, wrapping command and try to
375 * delete it using backspace key.
376 * Note: we print it _after_ prompt, because
377 * prompt may contain CR. Example: PS1='\[\r\n\]\w '
379 out1str("\033" "[6n");
383 unsigned w = cmdedit_termw; /* volatile var */
384 cmdedit_y = cmdedit_prmt_len / w; /* new quasireal y */
385 cmdedit_x = cmdedit_prmt_len % w;
389 /* draw prompt, editor line, and clear tail */
390 static void redraw(int y, int back_cursor)
392 if (y > 0) /* up to start y */
393 printf("\033[%dA", y);
396 input_end(); /* rewrite */
397 printf("\033[J"); /* erase after cursor */
398 input_backward(back_cursor);
401 /* Delete the char in front of the cursor, optionally saving it
402 * for later putback */
403 #if !ENABLE_FEATURE_EDITING_VI
404 static void input_delete(void)
405 #define input_delete(save) input_delete()
407 static void input_delete(int save)
412 if (j == (int)command_len)
415 #if ENABLE_FEATURE_EDITING_VI
421 if ((delptr - delbuf) < DELBUFSIZ)
422 *delptr++ = command_ps[j];
426 memmove(command_ps + j, command_ps + j + 1,
427 (command_len - j + 1) * sizeof(command_ps[0]));
429 input_end(); /* rewrite new line */
430 cmdedit_set_out_char(' '); /* erase char */
431 input_backward(cursor - j); /* back to old pos cursor */
434 #if ENABLE_FEATURE_EDITING_VI
435 static void put(void)
438 int j = delptr - delbuf;
443 /* open hole and then fill it */
444 memmove(command_ps + cursor + j, command_ps + cursor,
445 (command_len - cursor + 1) * sizeof(command_ps[0]));
446 memcpy(command_ps + cursor, delbuf, j * sizeof(command_ps[0]));
448 input_end(); /* rewrite new line */
449 input_backward(cursor - ocursor - j + 1); /* at end of new text */
453 /* Delete the char in back of the cursor */
454 static void input_backspace(void)
462 /* Move forward one character */
463 static void input_forward(void)
465 if (cursor < command_len)
466 cmdedit_set_out_char(command_ps[cursor + 1]);
469 #if ENABLE_FEATURE_TAB_COMPLETION
471 static void free_tab_completion_data(void)
475 free(matches[--num_matches]);
481 static void add_match(char *matched)
483 matches = xrealloc_vector(matches, 4, num_matches);
484 matches[num_matches] = matched;
488 #if ENABLE_FEATURE_USERNAME_COMPLETION
489 static void username_tab_completion(char *ud, char *with_shash_flg)
491 struct passwd *entry;
494 ud++; /* ~user/... to user/... */
495 userlen = strlen(ud);
497 if (with_shash_flg) { /* "~/..." or "~user/..." */
498 char *sav_ud = ud - 1;
501 if (*ud == '/') { /* "~/..." */
506 temp = strchr(ud, '/');
507 *temp = '\0'; /* ~user\0 */
508 entry = getpwnam(ud);
509 *temp = '/'; /* restore ~user/... */
512 home = entry->pw_dir;
515 if ((userlen + strlen(home) + 1) < MAX_LINELEN) {
517 sprintf(sav_ud, "%s%s", home, ud);
522 /* Using _r function to avoid pulling in static buffers */
525 struct passwd *result;
528 while (!getpwent_r(&pwd, line_buff, sizeof(line_buff), &result)) {
529 /* Null usernames should result in all users as possible completions. */
530 if (/*!userlen || */ strncmp(ud, pwd.pw_name, userlen) == 0) {
531 add_match(xasprintf("~%s/", pwd.pw_name));
537 #endif /* FEATURE_COMMAND_USERNAME_COMPLETION */
545 static int path_parse(char ***p, int flags)
552 /* if not setenv PATH variable, to search cur dir "." */
553 if (flags != FIND_EXE_ONLY)
556 if (state->flags & WITH_PATH_LOOKUP)
557 pth = state->path_lookup;
559 pth = getenv("PATH");
560 /* PATH=<empty> or PATH=:<empty> */
561 if (!pth || !pth[0] || LONE_CHAR(pth, ':'))
565 npth = 1; /* path component count */
567 tmp = strchr(tmp, ':');
571 break; /* :<empty> */
575 res = xmalloc(npth * sizeof(char*));
576 res[0] = tmp = xstrdup(pth);
579 tmp = strchr(tmp, ':');
582 *tmp++ = '\0'; /* ':' -> '\0' */
584 break; /* :<empty> */
591 static void exe_n_cwd_tab_completion(char *command, int type)
597 char **paths = path1;
601 char *pfind = strrchr(command, '/');
602 /* char dirbuf[MAX_LINELEN]; */
603 #define dirbuf (S.exe_n_cwd_tab_completion__dirbuf)
606 path1[0] = (char*)".";
609 /* no dir, if flags==EXE_ONLY - get paths, else "." */
610 npaths = path_parse(&paths, type);
613 /* dirbuf = ".../.../.../" */
614 safe_strncpy(dirbuf, command, (pfind - command) + 2);
615 #if ENABLE_FEATURE_USERNAME_COMPLETION
616 if (dirbuf[0] == '~') /* ~/... or ~user/... */
617 username_tab_completion(dirbuf, dirbuf);
620 /* point to 'l' in "..../last_component" */
624 for (i = 0; i < npaths; i++) {
625 dir = opendir(paths[i]);
627 continue; /* don't print an error */
629 while ((next = readdir(dir)) != NULL) {
631 const char *str_found = next->d_name;
634 if (strncmp(str_found, pfind, strlen(pfind)))
636 /* not see .name without .match */
637 if (*str_found == '.' && *pfind == '\0') {
638 if (NOT_LONE_CHAR(paths[i], '/') || str_found[1])
640 str_found = ""; /* only "/" */
642 found = concat_path_file(paths[i], str_found);
643 /* hmm, remove in progress? */
644 /* NB: stat() first so that we see is it a directory;
645 * but if that fails, use lstat() so that
646 * we still match dangling links */
647 if (stat(found, &st) && lstat(found, &st))
649 /* find with dirs? */
650 if (paths[i] != dirbuf)
651 strcpy(found, next->d_name); /* only name */
653 len1 = strlen(found);
654 found = xrealloc(found, len1 + 2);
656 found[len1+1] = '\0';
658 if (S_ISDIR(st.st_mode)) {
659 /* name is a directory */
660 if (found[len1-1] != '/') {
664 /* not put found file if search only dirs for cd */
665 if (type == FIND_DIR_ONLY)
668 /* Add it to the list */
676 if (paths != path1) {
677 free(paths[0]); /* allocated memory is only in first member */
683 #define QUOT (UCHAR_MAX+1)
685 #define collapse_pos(is, in) do { \
686 memmove(int_buf+(is), int_buf+(in), (MAX_LINELEN+1-(is)-(in)) * sizeof(pos_buf[0])); \
687 memmove(pos_buf+(is), pos_buf+(in), (MAX_LINELEN+1-(is)-(in)) * sizeof(pos_buf[0])); \
690 static int find_match(char *matchBuf, int *len_with_quotes)
695 /* int16_t int_buf[MAX_LINELEN + 1]; */
696 /* int16_t pos_buf[MAX_LINELEN + 1]; */
697 #define int_buf (S.find_match__int_buf)
698 #define pos_buf (S.find_match__pos_buf)
700 /* set to integer dimension characters and own positions */
702 int_buf[i] = (unsigned char)matchBuf[i];
703 if (int_buf[i] == 0) {
704 pos_buf[i] = -1; /* indicator end line */
710 /* mask \+symbol and convert '\t' to ' ' */
711 for (i = j = 0; matchBuf[i]; i++, j++)
712 if (matchBuf[i] == '\\') {
713 collapse_pos(j, j + 1);
716 #if ENABLE_FEATURE_NONPRINTABLE_INVERSE_PUT
717 if (matchBuf[i] == '\t') /* algorithm equivalent */
718 int_buf[j] = ' ' | QUOT;
721 #if ENABLE_FEATURE_NONPRINTABLE_INVERSE_PUT
722 else if (matchBuf[i] == '\t')
726 /* mask "symbols" or 'symbols' */
728 for (i = 0; int_buf[i]; i++) {
730 if (c == '\'' || c == '"') {
739 } else if (c2 != 0 && c != '$')
743 /* skip commands with arguments if line has commands delimiters */
744 /* ';' ';;' '&' '|' '&&' '||' but `>&' `<&' `>|' */
745 for (i = 0; int_buf[i]; i++) {
748 j = i ? int_buf[i - 1] : -1;
750 if (c == ';' || c == '&' || c == '|') {
751 command_mode = 1 + (c == c2);
753 if (j == '>' || j == '<')
755 } else if (c == '|' && j == '>')
759 collapse_pos(0, i + command_mode);
760 i = -1; /* hack incremet */
763 /* collapse `command...` */
764 for (i = 0; int_buf[i]; i++)
765 if (int_buf[i] == '`') {
766 for (j = i + 1; int_buf[j]; j++)
767 if (int_buf[j] == '`') {
768 collapse_pos(i, j + 1);
773 /* not found close ` - command mode, collapse all previous */
774 collapse_pos(0, i + 1);
777 i--; /* hack incremet */
780 /* collapse (command...(command...)...) or {command...{command...}...} */
781 c = 0; /* "recursive" level */
783 for (i = 0; int_buf[i]; i++)
784 if (int_buf[i] == '(' || int_buf[i] == '{') {
785 if (int_buf[i] == '(')
789 collapse_pos(0, i + 1);
790 i = -1; /* hack incremet */
792 for (i = 0; pos_buf[i] >= 0 && (c > 0 || c2 > 0); i++)
793 if ((int_buf[i] == ')' && c > 0) || (int_buf[i] == '}' && c2 > 0)) {
794 if (int_buf[i] == ')')
798 collapse_pos(0, i + 1);
799 i = -1; /* hack incremet */
802 /* skip first not quote space */
803 for (i = 0; int_buf[i]; i++)
804 if (int_buf[i] != ' ')
809 /* set find mode for completion */
810 command_mode = FIND_EXE_ONLY;
811 for (i = 0; int_buf[i]; i++)
812 if (int_buf[i] == ' ' || int_buf[i] == '<' || int_buf[i] == '>') {
813 if (int_buf[i] == ' ' && command_mode == FIND_EXE_ONLY
814 && matchBuf[pos_buf[0]] == 'c'
815 && matchBuf[pos_buf[1]] == 'd'
817 command_mode = FIND_DIR_ONLY;
819 command_mode = FIND_FILE_ONLY;
823 for (i = 0; int_buf[i]; i++)
826 for (--i; i >= 0; i--) {
828 if (c == ' ' || c == '<' || c == '>' || c == '|' || c == '&') {
829 collapse_pos(0, i + 1);
833 /* skip first not quoted '\'' or '"' */
834 for (i = 0; int_buf[i] == '\'' || int_buf[i] == '"'; i++)
836 /* collapse quote or unquote // or /~ */
837 while ((int_buf[i] & ~QUOT) == '/'
838 && ((int_buf[i+1] & ~QUOT) == '/' || (int_buf[i+1] & ~QUOT) == '~')
843 /* set only match and destroy quotes */
845 for (c = 0; pos_buf[i] >= 0; i++) {
846 matchBuf[c++] = matchBuf[pos_buf[i]];
850 /* old length matchBuf with quotes symbols */
851 *len_with_quotes = j ? j - pos_buf[0] : 0;
859 * display by column (original idea from ls applet,
860 * very optimized by me :)
862 static void showfiles(void)
865 int column_width = 0;
866 int nfiles = num_matches;
870 /* find the longest file name- use that as the column width */
871 for (row = 0; row < nrows; row++) {
872 l = strlen(matches[row]);
873 if (column_width < l)
876 column_width += 2; /* min space for columns */
877 ncols = cmdedit_termw / column_width;
882 nrows++; /* round up fractionals */
886 for (row = 0; row < nrows; row++) {
890 for (nc = 1; nc < ncols && n+nrows < nfiles; n += nrows, nc++) {
891 printf("%s%-*s", matches[n],
892 (int)(column_width - strlen(matches[n])), "");
898 static char *add_quote_for_spec_chars(char *found)
901 char *s = xmalloc((strlen(found) + 1) * 2);
904 if (strchr(" `\"#$%^&*()=+{}[]:;\'|\\<>", *found))
912 /* Do TAB completion */
913 static void input_tab(smallint *lastWasTab)
915 if (!(state->flags & TAB_COMPLETION))
921 /* char matchBuf[MAX_LINELEN]; */
922 #define matchBuf (S.input_tab__matchBuf)
926 *lastWasTab = TRUE; /* flop trigger */
928 /* Make a local copy of the string --
929 * up to the position of the cursor */
930 save_string(matchBuf, cursor + 1);
933 find_type = find_match(matchBuf, &recalc_pos);
935 /* Free up any memory already allocated */
936 free_tab_completion_data();
938 #if ENABLE_FEATURE_USERNAME_COMPLETION
939 /* If the word starts with `~' and there is no slash in the word,
940 * then try completing this word as a username. */
941 if (state->flags & USERNAME_COMPLETION)
942 if (matchBuf[0] == '~' && strchr(matchBuf, '/') == 0)
943 username_tab_completion(matchBuf, NULL);
945 /* Try to match any executable in our path and everything
946 * in the current working directory */
948 exe_n_cwd_tab_completion(matchBuf, find_type);
949 /* Sort, then remove any duplicates found */
953 qsort_string_vector(matches, num_matches);
954 for (i = 0; i < num_matches - 1; ++i) {
955 if (matches[i] && matches[i+1]) { /* paranoia */
956 if (strcmp(matches[i], matches[i+1]) == 0) {
958 matches[i] = NULL; /* paranoia */
960 matches[n++] = matches[i];
964 matches[n] = matches[i];
967 /* Did we find exactly one match? */
968 if (!matches || num_matches > 1) {
971 return; /* not found */
972 /* find minimal match */
973 tmp1 = xstrdup(matches[0]);
974 for (tmp = tmp1; *tmp; tmp++)
975 for (len_found = 1; len_found < num_matches; len_found++)
976 if (matches[len_found][(tmp - tmp1)] != *tmp) {
980 if (*tmp1 == '\0') { /* have unique */
984 tmp = add_quote_for_spec_chars(tmp1);
986 } else { /* one match */
987 tmp = add_quote_for_spec_chars(matches[0]);
988 /* for next completion current found */
991 len_found = strlen(tmp);
992 if (tmp[len_found-1] != '/') {
993 tmp[len_found] = ' ';
994 tmp[len_found+1] = '\0';
997 len_found = strlen(tmp);
998 /* have space to placed match? */
999 if ((len_found - strlen(matchBuf) + command_len) < MAX_LINELEN) {
1000 /* before word for match */
1002 #if !ENABLE_FEATURE_ASSUME_UNICODE
1003 command_ps[cursor - recalc_pos] = '\0';
1004 /* save tail line */
1005 strcpy(matchBuf, command_ps + cursor);
1007 strcat(command_ps, tmp);
1009 strcat(command_ps, matchBuf);
1010 /* back to begin word for match */
1011 input_backward(recalc_pos);
1013 recalc_pos = cursor + len_found;
1015 command_len = strlen(command_ps);
1016 /* write out the matched command */
1018 redraw(cmdedit_y, command_len - recalc_pos);
1023 /* Ok -- the last char was a TAB. Since they
1024 * just hit TAB again, print a list of all the
1025 * available choices... */
1026 if (matches && num_matches > 0) {
1027 int sav_cursor = cursor; /* change goto_new_line() */
1029 /* Go to the next line */
1032 redraw(0, command_len - sav_cursor);
1037 #endif /* FEATURE_COMMAND_TAB_COMPLETION */
1040 line_input_t* FAST_FUNC new_line_input_t(int flags)
1042 line_input_t *n = xzalloc(sizeof(*n));
1050 static void save_command_ps_at_cur_history(void)
1052 if (command_ps[0] != BB_NUL) {
1053 int cur = state->cur_history;
1054 free(state->history[cur]);
1056 #if ENABLE_FEATURE_ASSUME_UNICODE
1058 char tbuf[MAX_LINELEN];
1059 save_string(tbuf, sizeof(tbuf));
1060 state->history[cur] = xstrdup(tbuf);
1063 state->history[cur] = xstrdup(command_ps);
1068 /* state->flags is already checked to be nonzero */
1069 static int get_previous_history(void)
1071 if ((state->flags & DO_HISTORY) && state->cur_history) {
1072 save_command_ps_at_cur_history();
1073 state->cur_history--;
1080 static int get_next_history(void)
1082 if (state->flags & DO_HISTORY) {
1083 if (state->cur_history < state->cnt_history) {
1084 save_command_ps_at_cur_history(); /* save the current history line */
1085 return ++state->cur_history;
1092 #if ENABLE_FEATURE_EDITING_SAVEHISTORY
1093 /* We try to ensure that concurrent additions to the history
1094 * do not overwrite each other.
1095 * Otherwise shell users get unhappy.
1097 * History file is trimmed lazily, when it grows several times longer
1098 * than configured MAX_HISTORY lines.
1101 static void free_line_input_t(line_input_t *n)
1103 int i = n->cnt_history;
1105 free(n->history[--i]);
1109 /* state->flags is already checked to be nonzero */
1110 static void load_history(line_input_t *st_parm)
1112 char *temp_h[MAX_HISTORY];
1115 unsigned idx, i, line_len;
1117 /* NB: do not trash old history if file can't be opened */
1119 fp = fopen_for_read(st_parm->hist_file);
1121 /* clean up old history */
1122 for (idx = st_parm->cnt_history; idx > 0;) {
1124 free(st_parm->history[idx]);
1125 st_parm->history[idx] = NULL;
1128 /* fill temp_h[], retaining only last MAX_HISTORY lines */
1129 memset(temp_h, 0, sizeof(temp_h));
1130 st_parm->cnt_history_in_file = idx = 0;
1131 while ((line = xmalloc_fgetline(fp)) != NULL) {
1132 if (line[0] == '\0') {
1138 st_parm->cnt_history_in_file++;
1140 if (idx == MAX_HISTORY)
1145 /* find first non-NULL temp_h[], if any */
1146 if (st_parm->cnt_history_in_file) {
1147 while (temp_h[idx] == NULL) {
1149 if (idx == MAX_HISTORY)
1154 /* copy temp_h[] to st_parm->history[] */
1155 for (i = 0; i < MAX_HISTORY;) {
1160 if (idx == MAX_HISTORY)
1162 line_len = strlen(line);
1163 if (line_len >= MAX_LINELEN)
1164 line[MAX_LINELEN-1] = '\0';
1165 st_parm->history[i++] = line;
1167 st_parm->cnt_history = i;
1171 /* state->flags is already checked to be nonzero */
1172 static void save_history(char *str)
1177 fd = open(state->hist_file, O_WRONLY | O_CREAT | O_APPEND, 0666);
1180 xlseek(fd, 0, SEEK_END); /* paranoia */
1182 str[len] = '\n'; /* we (try to) do atomic write */
1183 len2 = full_write(fd, str, len + 1);
1186 if (len2 != len + 1)
1187 return; /* "wtf?" */
1189 /* did we write so much that history file needs trimming? */
1190 state->cnt_history_in_file++;
1191 if (state->cnt_history_in_file > MAX_HISTORY * 4) {
1194 line_input_t *st_temp;
1197 /* we may have concurrently written entries from others.
1199 st_temp = new_line_input_t(state->flags);
1200 st_temp->hist_file = state->hist_file;
1201 load_history(st_temp);
1203 /* write out temp file and replace hist_file atomically */
1204 new_name = xasprintf("%s.%u.new", state->hist_file, (int) getpid());
1205 fp = fopen_for_write(new_name);
1207 for (i = 0; i < st_temp->cnt_history; i++)
1208 fprintf(fp, "%s\n", st_temp->history[i]);
1210 if (rename(new_name, state->hist_file) == 0)
1211 state->cnt_history_in_file = st_temp->cnt_history;
1214 free_line_input_t(st_temp);
1218 #define load_history(a) ((void)0)
1219 #define save_history(a) ((void)0)
1220 #endif /* FEATURE_COMMAND_SAVEHISTORY */
1222 static void remember_in_history(char *str)
1226 if (!(state->flags & DO_HISTORY))
1230 i = state->cnt_history;
1231 /* Don't save dupes */
1232 if (i && strcmp(state->history[i-1], str) == 0)
1235 free(state->history[MAX_HISTORY]); /* redundant, paranoia */
1236 state->history[MAX_HISTORY] = NULL; /* redundant, paranoia */
1238 /* If history[] is full, remove the oldest command */
1239 /* we need to keep history[MAX_HISTORY] empty, hence >=, not > */
1240 if (i >= MAX_HISTORY) {
1241 free(state->history[0]);
1242 for (i = 0; i < MAX_HISTORY-1; i++)
1243 state->history[i] = state->history[i+1];
1244 /* i == MAX_HISTORY-1 */
1246 /* i <= MAX_HISTORY-1 */
1247 state->history[i++] = xstrdup(str);
1248 /* i <= MAX_HISTORY */
1249 state->cur_history = i;
1250 state->cnt_history = i;
1251 #if ENABLE_FEATURE_EDITING_SAVEHISTORY
1252 if ((state->flags & SAVE_HISTORY) && state->hist_file)
1255 IF_FEATURE_EDITING_FANCY_PROMPT(num_ok_lines++;)
1258 #else /* MAX_HISTORY == 0 */
1259 #define remember_in_history(a) ((void)0)
1260 #endif /* MAX_HISTORY */
1264 * This function is used to grab a character buffer
1265 * from the input file descriptor and allows you to
1266 * a string with full command editing (sort of like
1269 * The following standard commands are not implemented:
1270 * ESC-b -- Move back one word
1271 * ESC-f -- Move forward one word
1272 * ESC-d -- Delete back one word
1273 * ESC-h -- Delete forward one word
1274 * CTL-t -- Transpose two characters
1276 * Minimalist vi-style command line editing available if configured.
1277 * vi mode implemented 2005 by Paul Fox <pgf@foxharp.boston.ma.us>
1280 #if ENABLE_FEATURE_EDITING_VI
1282 vi_Word_motion(int eat)
1284 CHAR_T *command = command_ps;
1286 while (cursor < command_len && !BB_isspace(command[cursor]))
1288 if (eat) while (cursor < command_len && BB_isspace(command[cursor]))
1293 vi_word_motion(int eat)
1295 CHAR_T *command = command_ps;
1297 if (BB_isalnum(command[cursor]) || command[cursor] == '_') {
1298 while (cursor < command_len
1299 && (BB_isalnum(command[cursor+1]) || command[cursor+1] == '_'))
1301 } else if (BB_ispunct(command[cursor])) {
1302 while (cursor < command_len && BB_ispunct(command[cursor+1]))
1306 if (cursor < command_len)
1309 if (eat && cursor < command_len && BB_isspace(command[cursor]))
1310 while (cursor < command_len && BB_isspace(command[cursor]))
1317 CHAR_T *command = command_ps;
1320 while (cursor < command_len && BB_isspace(command[cursor]))
1322 while (cursor < command_len-1 && !BB_isspace(command[cursor+1]))
1329 CHAR_T *command = command_ps;
1331 if (cursor >= command_len-1)
1334 while (cursor < command_len-1 && BB_isspace(command[cursor]))
1336 if (cursor >= command_len-1)
1338 if (BB_isalnum(command[cursor]) || command[cursor] == '_') {
1339 while (cursor < command_len-1
1340 && (BB_isalnum(command[cursor+1]) || command[cursor+1] == '_')
1344 } else if (BB_ispunct(command[cursor])) {
1345 while (cursor < command_len-1 && BB_ispunct(command[cursor+1]))
1351 vi_Back_motion(void)
1353 CHAR_T *command = command_ps;
1355 while (cursor > 0 && BB_isspace(command[cursor-1]))
1357 while (cursor > 0 && !BB_isspace(command[cursor-1]))
1362 vi_back_motion(void)
1364 CHAR_T *command = command_ps;
1369 while (cursor > 0 && BB_isspace(command[cursor]))
1373 if (BB_isalnum(command[cursor]) || command[cursor] == '_') {
1375 && (BB_isalnum(command[cursor-1]) || command[cursor-1] == '_')
1379 } else if (BB_ispunct(command[cursor])) {
1380 while (cursor > 0 && BB_ispunct(command[cursor-1]))
1388 * read_line_input and its helpers
1391 #if !ENABLE_FEATURE_EDITING_FANCY_PROMPT
1392 static void parse_and_put_prompt(const char *prmt_ptr)
1394 cmdedit_prompt = prmt_ptr;
1395 cmdedit_prmt_len = strlen(prmt_ptr);
1399 static void parse_and_put_prompt(const char *prmt_ptr)
1402 size_t cur_prmt_len = 0;
1403 char flg_not_length = '[';
1404 char *prmt_mem_ptr = xzalloc(1);
1405 char *cwd_buf = xrealloc_getcwd_or_warn(NULL);
1410 cmdedit_prmt_len = 0;
1413 cwd_buf = (char *)bb_msg_unknown;
1416 cbuf[1] = '\0'; /* never changes */
1419 char *free_me = NULL;
1424 const char *cp = prmt_ptr;
1427 c = bb_process_escape_sequence(&prmt_ptr);
1428 if (prmt_ptr == cp) {
1434 #if ENABLE_FEATURE_GETUSERNAME_AND_HOMEDIR
1436 pbuf = user_buf ? user_buf : (char*)"";
1440 pbuf = free_me = safe_gethostname();
1441 *strchrnul(pbuf, '.') = '\0';
1444 c = (geteuid() == 0 ? '#' : '$');
1446 #if ENABLE_FEATURE_GETUSERNAME_AND_HOMEDIR
1448 /* /home/user[/something] -> ~[/something] */
1450 l = strlen(home_pwd_buf);
1452 && strncmp(home_pwd_buf, cwd_buf, l) == 0
1453 && (cwd_buf[l]=='/' || cwd_buf[l]=='\0')
1454 && strlen(cwd_buf + l) < PATH_MAX
1456 pbuf = free_me = xasprintf("~%s", cwd_buf + l);
1462 cp = strrchr(pbuf, '/');
1463 if (cp != NULL && cp != pbuf)
1464 pbuf += (cp-pbuf) + 1;
1467 pbuf = free_me = xasprintf("%d", num_ok_lines);
1469 case 'e': case 'E': /* \e \E = \033 */
1472 case 'x': case 'X': {
1474 for (l = 0; l < 3;) {
1476 buf2[l++] = *prmt_ptr;
1478 h = strtoul(buf2, &pbuf, 16);
1479 if (h > UCHAR_MAX || (pbuf - buf2) < l) {
1485 c = (char)strtoul(buf2, NULL, 16);
1492 if (c == flg_not_length) {
1493 flg_not_length = (flg_not_length == '[' ? ']' : '[');
1501 cur_prmt_len = strlen(pbuf);
1502 prmt_len += cur_prmt_len;
1503 if (flg_not_length != ']')
1504 cmdedit_prmt_len += cur_prmt_len;
1505 prmt_mem_ptr = strcat(xrealloc(prmt_mem_ptr, prmt_len+1), pbuf);
1509 if (cwd_buf != (char *)bb_msg_unknown)
1511 cmdedit_prompt = prmt_mem_ptr;
1516 static void cmdedit_setwidth(unsigned w, int redraw_flg)
1520 /* new y for current cursor */
1521 int new_y = (cursor + cmdedit_prmt_len) / w;
1523 redraw((new_y >= cmdedit_y ? new_y : cmdedit_y), command_len - cursor);
1528 static void win_changed(int nsig)
1531 get_terminal_width_height(0, &width, NULL);
1532 cmdedit_setwidth(width, nsig /* - just a yes/no flag */);
1533 if (nsig == SIGWINCH)
1534 signal(SIGWINCH, win_changed); /* rearm ourself */
1537 static int lineedit_read_key(char *read_key_buffer)
1542 #if ENABLE_FEATURE_ASSUME_UNICODE
1543 char unicode_buf[MB_CUR_MAX + 1];
1544 int unicode_idx = 0;
1547 pfd.fd = STDIN_FILENO;
1548 pfd.events = POLLIN;
1551 if (read_key_buffer[0] == 0) {
1552 /* Wait for input. Can't just call read_key,
1553 * it returns at once if stdin
1554 * is in non-blocking mode. */
1555 safe_poll(&pfd, 1, delay);
1557 /* Note: read_key sets errno to 0 on success: */
1558 ic = read_key(STDIN_FILENO, read_key_buffer);
1559 if (ENABLE_FEATURE_EDITING_ASK_TERMINAL
1560 && (int32_t)ic == KEYCODE_CURSOR_POS
1562 int col = ((ic >> 32) & 0x7fff) - 1;
1563 if (col > cmdedit_prmt_len) {
1564 cmdedit_x += (col - cmdedit_prmt_len);
1565 while (cmdedit_x >= cmdedit_termw) {
1566 cmdedit_x -= cmdedit_termw;
1573 #if ENABLE_FEATURE_ASSUME_UNICODE
1577 if ((int32_t)ic < 0) /* KEYCODE_xxx */
1579 unicode_buf[unicode_idx++] = ic;
1580 unicode_buf[unicode_idx] = '\0';
1581 if (mbstowcs(&wc, unicode_buf, 1) != 1 && unicode_idx < MB_CUR_MAX) {
1588 } while (errno == EAGAIN);
1593 /* leave out the "vi-mode"-only case labels if vi editing isn't
1595 #define vi_case(caselabel) IF_FEATURE_EDITING(case caselabel)
1597 /* convert uppercase ascii to equivalent control char, for readability */
1599 #define CTRL(a) ((a) & ~0x40)
1602 * -1 on read errors or EOF, or on bare Ctrl-D,
1603 * 0 on ctrl-C (the line entered is still returned in 'command'),
1604 * >0 length of input string, including terminating '\n'
1606 int FAST_FUNC read_line_input(const char *prompt, char *command, int maxsize, line_input_t *st)
1609 #if ENABLE_FEATURE_TAB_COMPLETION
1610 smallint lastWasTab = FALSE;
1612 smallint break_out = 0;
1613 #if ENABLE_FEATURE_EDITING_VI
1614 smallint vi_cmdmode = 0;
1616 struct termios initial_settings;
1617 struct termios new_settings;
1618 char read_key_buffer[KEYCODE_BUFFER_SIZE];
1622 if (tcgetattr(STDIN_FILENO, &initial_settings) < 0
1623 || !(initial_settings.c_lflag & ECHO)
1625 /* Happens when e.g. stty -echo was run before */
1626 parse_and_put_prompt(prompt);
1628 if (fgets(command, maxsize, stdin) == NULL)
1629 len = -1; /* EOF or error */
1631 len = strlen(command);
1636 check_unicode_in_env();
1638 // FIXME: audit & improve this
1639 if (maxsize > MAX_LINELEN)
1640 maxsize = MAX_LINELEN;
1642 /* With null flags, no other fields are ever used */
1643 state = st ? st : (line_input_t*) &const_int_0;
1644 #if ENABLE_FEATURE_EDITING_SAVEHISTORY
1645 if ((state->flags & SAVE_HISTORY) && state->hist_file)
1646 if (state->cnt_history == 0)
1647 load_history(state);
1649 if (state->flags & DO_HISTORY)
1650 state->cur_history = state->cnt_history;
1652 /* prepare before init handlers */
1653 cmdedit_y = 0; /* quasireal y, not true if line > xt*yt */
1655 #if ENABLE_FEATURE_ASSUME_UNICODE
1656 command_ps = xzalloc(maxsize * sizeof(command_ps[0]));
1658 command_ps = command;
1661 #define command command_must_not_be_used
1663 new_settings = initial_settings;
1664 new_settings.c_lflag &= ~ICANON; /* unbuffered input */
1665 /* Turn off echoing and CTRL-C, so we can trap it */
1666 new_settings.c_lflag &= ~(ECHO | ECHONL | ISIG);
1667 /* Hmm, in linux c_cc[] is not parsed if ICANON is off */
1668 new_settings.c_cc[VMIN] = 1;
1669 new_settings.c_cc[VTIME] = 0;
1670 /* Turn off CTRL-C, so we can trap it */
1671 #ifndef _POSIX_VDISABLE
1672 #define _POSIX_VDISABLE '\0'
1674 new_settings.c_cc[VINTR] = _POSIX_VDISABLE;
1675 tcsetattr_stdin_TCSANOW(&new_settings);
1677 /* Now initialize things */
1678 previous_SIGWINCH_handler = signal(SIGWINCH, win_changed);
1679 win_changed(0); /* do initial resizing */
1680 #if ENABLE_FEATURE_GETUSERNAME_AND_HOMEDIR
1682 struct passwd *entry;
1684 entry = getpwuid(geteuid());
1686 user_buf = xstrdup(entry->pw_name);
1687 home_pwd_buf = xstrdup(entry->pw_dir);
1693 for (i = 0; i <= MAX_HISTORY; i++)
1694 bb_error_msg("history[%d]:'%s'", i, state->history[i]);
1695 bb_error_msg("cur_history:%d cnt_history:%d", state->cur_history, state->cnt_history);
1698 /* Print out the command prompt */
1699 parse_and_put_prompt(prompt);
1701 read_key_buffer[0] = 0;
1704 * The emacs and vi modes share much of the code in the big
1705 * command loop. Commands entered when in vi's command mode
1706 * (aka "escape mode") get an extra bit added to distinguish
1707 * them - this keeps them from being self-inserted. This
1708 * clutters the big switch a bit, but keeps all the code
1712 VI_CMDMODE_BIT = 0x40000000,
1713 /* 0x80000000 bit flags KEYCODE_xxx */
1718 ic = lineedit_read_key(read_key_buffer);
1720 #if ENABLE_FEATURE_EDITING_VI
1723 /* btw, since KEYCODE_xxx are all < 0, this doesn't
1724 * change ic if it contains one of them: */
1725 ic |= VI_CMDMODE_BIT;
1732 vi_case('\n'|VI_CMDMODE_BIT:)
1733 vi_case('\r'|VI_CMDMODE_BIT:)
1739 vi_case('0'|VI_CMDMODE_BIT:)
1740 /* Control-a -- Beginning of line */
1741 input_backward(cursor);
1744 vi_case('h'|VI_CMDMODE_BIT:)
1745 vi_case('\b'|VI_CMDMODE_BIT:)
1746 vi_case('\x7f'|VI_CMDMODE_BIT:) /* DEL */
1747 /* Control-b -- Move back one character */
1751 vi_case(CTRL('C')|VI_CMDMODE_BIT:)
1752 /* Control-c -- stop gathering input */
1755 break_out = -1; /* "do not append '\n'" */
1758 /* Control-d -- Delete one character, or exit
1759 * if the len=0 and no chars to delete */
1760 if (command_len == 0) {
1762 #if ENABLE_FEATURE_EDITING_VI
1765 /* to control stopped jobs */
1766 break_out = command_len = -1;
1772 vi_case('$'|VI_CMDMODE_BIT:)
1773 /* Control-e -- End of line */
1777 vi_case('l'|VI_CMDMODE_BIT:)
1778 vi_case(' '|VI_CMDMODE_BIT:)
1779 /* Control-f -- Move forward one character */
1783 case '\x7f': /* DEL */
1784 /* Control-h and DEL */
1787 #if ENABLE_FEATURE_TAB_COMPLETION
1789 input_tab(&lastWasTab);
1793 /* Control-k -- clear to end of line */
1794 command_ps[cursor] = BB_NUL;
1795 command_len = cursor;
1799 vi_case(CTRL('L')|VI_CMDMODE_BIT:)
1800 /* Control-l -- clear screen */
1802 redraw(0, command_len - cursor);
1806 vi_case(CTRL('N')|VI_CMDMODE_BIT:)
1807 vi_case('j'|VI_CMDMODE_BIT:)
1808 /* Control-n -- Get next command in history */
1809 if (get_next_history())
1813 vi_case(CTRL('P')|VI_CMDMODE_BIT:)
1814 vi_case('k'|VI_CMDMODE_BIT:)
1815 /* Control-p -- Get previous command from history */
1816 if (get_previous_history())
1821 vi_case(CTRL('U')|VI_CMDMODE_BIT:)
1822 /* Control-U -- Clear line before cursor */
1824 command_len -= cursor;
1825 memmove(command_ps, command_ps + cursor,
1826 (command_len + 1) * sizeof(command_ps[0]));
1827 redraw(cmdedit_y, command_len);
1831 vi_case(CTRL('W')|VI_CMDMODE_BIT:)
1832 /* Control-W -- Remove the last word */
1833 while (cursor > 0 && BB_isspace(command_ps[cursor-1]))
1835 while (cursor > 0 && !BB_isspace(command_ps[cursor-1]))
1839 #if ENABLE_FEATURE_EDITING_VI
1840 case 'i'|VI_CMDMODE_BIT:
1843 case 'I'|VI_CMDMODE_BIT:
1844 input_backward(cursor);
1847 case 'a'|VI_CMDMODE_BIT:
1851 case 'A'|VI_CMDMODE_BIT:
1855 case 'x'|VI_CMDMODE_BIT:
1858 case 'X'|VI_CMDMODE_BIT:
1864 case 'W'|VI_CMDMODE_BIT:
1867 case 'w'|VI_CMDMODE_BIT:
1870 case 'E'|VI_CMDMODE_BIT:
1873 case 'e'|VI_CMDMODE_BIT:
1876 case 'B'|VI_CMDMODE_BIT:
1879 case 'b'|VI_CMDMODE_BIT:
1882 case 'C'|VI_CMDMODE_BIT:
1885 case 'D'|VI_CMDMODE_BIT:
1888 case 'c'|VI_CMDMODE_BIT:
1891 case 'd'|VI_CMDMODE_BIT: {
1898 ic = lineedit_read_key(read_key_buffer);
1899 if (errno) /* error */
1900 goto prepare_to_die;
1902 if ((ic | VI_CMDMODE_BIT) == prev_ic) {
1904 input_backward(cursor);
1914 case 'w': /* "dw", "cw" */
1915 vi_word_motion(vi_cmdmode);
1917 case 'W': /* 'dW', 'cW' */
1918 vi_Word_motion(vi_cmdmode);
1920 case 'e': /* 'de', 'ce' */
1924 case 'E': /* 'dE', 'cE' */
1930 input_backward(cursor - sc);
1931 while (nc-- > cursor)
1934 case 'b': /* "db", "cb" */
1935 case 'B': /* implemented as B */
1940 while (sc-- > cursor)
1943 case ' ': /* "d ", "c " */
1946 case '$': /* "d$", "c$" */
1948 while (cursor < command_len)
1954 case 'p'|VI_CMDMODE_BIT:
1957 case 'P'|VI_CMDMODE_BIT:
1960 case 'r'|VI_CMDMODE_BIT:
1961 ic = lineedit_read_key(read_key_buffer);
1962 if (errno) /* error */
1963 goto prepare_to_die;
1964 if (ic < ' ' || ic > 255) {
1967 command_ps[cursor] = ic;
1972 case '\x1b': /* ESC */
1973 if (state->flags & VI_MODE) {
1974 /* insert mode --> command mode */
1979 #endif /* FEATURE_COMMAND_EDITING_VI */
1983 if (get_previous_history())
1988 if (!get_next_history())
1991 /* Rewrite the line with the selected history item */
1992 /* change command */
1993 command_len = load_string(state->history[state->cur_history] ? : "", maxsize);
1994 /* redraw and go to eol (bol, in vi) */
1995 redraw(cmdedit_y, (state->flags & VI_MODE) ? 9999 : 0);
2004 case KEYCODE_DELETE:
2008 input_backward(cursor);
2015 // /* Control-V -- force insert of next char */
2016 // if (c == CTRL('V')) {
2017 // if (safe_read(STDIN_FILENO, &c, 1) < 1)
2018 // goto prepare_to_die;
2025 || (!ENABLE_FEATURE_ASSUME_UNICODE && ic >= 256)
2026 || (ENABLE_FEATURE_ASSUME_UNICODE && ic >= VI_CMDMODE_BIT)
2028 /* If VI_CMDMODE_BIT is set, ic is >= 256
2029 * and command mode ignores unexpected chars.
2030 * Otherwise, we are here if ic is a
2031 * control char or an unhandled ESC sequence,
2032 * which is also ignored.
2036 if ((int)command_len >= (maxsize - 2)) {
2037 /* Not enough space for the char and EOL */
2042 if (cursor == (command_len - 1)) {
2043 /* We are at the end, append */
2044 command_ps[cursor] = ic;
2045 command_ps[cursor + 1] = BB_NUL;
2046 cmdedit_set_out_char(' ');
2048 /* In the middle, insert */
2051 memmove(command_ps + sc + 1, command_ps + sc,
2052 (command_len - sc) * sizeof(command_ps[0]));
2053 command_ps[sc] = ic;
2055 /* rewrite from cursor */
2057 /* to prev x pos + 1 */
2058 input_backward(cursor - sc);
2061 } /* switch (input_key) */
2066 #if ENABLE_FEATURE_TAB_COMPLETION
2067 ic &= ~VI_CMDMODE_BIT;
2073 /* Stop bug catching using "command_must_not_be_used" trick */
2076 #if ENABLE_FEATURE_ASSUME_UNICODE
2077 command_len = save_string(command, maxsize - 1);
2081 if (command_len > 0)
2082 remember_in_history(command);
2084 if (break_out > 0) {
2085 command[command_len++] = '\n';
2086 command[command_len] = '\0';
2089 #if ENABLE_FEATURE_TAB_COMPLETION
2090 free_tab_completion_data();
2093 /* restore initial_settings */
2094 tcsetattr_stdin_TCSANOW(&initial_settings);
2095 /* restore SIGWINCH handler */
2096 signal(SIGWINCH, previous_SIGWINCH_handler);
2102 return len; /* can't return command_len, DEINIT_S() destroys it */
2107 #undef read_line_input
2108 int FAST_FUNC read_line_input(const char* prompt, char* command, int maxsize)
2110 fputs(prompt, stdout);
2112 fgets(command, maxsize, stdin);
2113 return strlen(command);
2116 #endif /* FEATURE_EDITING */
2127 const char *applet_name = "debug stuff usage";
2129 int main(int argc, char **argv)
2131 char buff[MAX_LINELEN];
2133 #if ENABLE_FEATURE_EDITING_FANCY_PROMPT
2134 "\\[\\033[32;1m\\]\\u@\\[\\x1b[33;1m\\]\\h:"
2135 "\\[\\033[34;1m\\]\\w\\[\\033[35;1m\\] "
2136 "\\!\\[\\e[36;1m\\]\\$ \\[\\E[0m\\]";
2141 #if ENABLE_FEATURE_NONPRINTABLE_INVERSE_PUT
2142 setlocale(LC_ALL, "");
2146 l = read_line_input(prompt, buff);
2147 if (l <= 0 || buff[l-1] != '\n')
2150 printf("*** read_line_input() returned line =%s=\n", buff);
2152 printf("*** read_line_input() detect ^D\n");