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\] '
40 /* FIXME: obsolete CONFIG item? */
41 #define ENABLE_FEATURE_NONPRINTABLE_INVERSE_PUT 0
46 #define ENABLE_FEATURE_EDITING 0
47 #define ENABLE_FEATURE_TAB_COMPLETION 0
48 #define ENABLE_FEATURE_USERNAME_COMPLETION 0
49 #define ENABLE_FEATURE_NONPRINTABLE_INVERSE_PUT 0
54 /* Entire file (except TESTing part) sits inside this #if */
55 #if ENABLE_FEATURE_EDITING
57 #if ENABLE_LOCALE_SUPPORT
58 #define Isprint(c) isprint(c)
60 #define Isprint(c) ((c) >= ' ' && (c) != ((unsigned char)'\233'))
63 #define ENABLE_FEATURE_GETUSERNAME_AND_HOMEDIR \
64 (ENABLE_FEATURE_USERNAME_COMPLETION || ENABLE_FEATURE_EDITING_FANCY_PROMPT)
65 #define USE_FEATURE_GETUSERNAME_AND_HOMEDIR(...)
66 #if ENABLE_FEATURE_GETUSERNAME_AND_HOMEDIR
67 #undef USE_FEATURE_GETUSERNAME_AND_HOMEDIR
68 #define USE_FEATURE_GETUSERNAME_AND_HOMEDIR(...) __VA_ARGS__
72 /* We use int16_t for positions, need to limit line len */
73 MAX_LINELEN = CONFIG_FEATURE_EDITING_MAX_LEN < 0x7ff0
74 ? CONFIG_FEATURE_EDITING_MAX_LEN
78 #if ENABLE_FEATURE_GETUSERNAME_AND_HOMEDIR
79 static const char null_str[] ALIGN1 = "";
82 /* We try to minimize both static and stack usage. */
83 struct lineedit_statics {
86 volatile unsigned cmdedit_termw; /* = 80; */ /* actual terminal width */
87 sighandler_t previous_SIGWINCH_handler;
89 unsigned cmdedit_x; /* real x terminal position */
90 unsigned cmdedit_y; /* pseudoreal y terminal position */
91 unsigned cmdedit_prmt_len; /* length of prompt (without colors etc) */
97 const char *cmdedit_prompt;
98 #if ENABLE_FEATURE_EDITING_FANCY_PROMPT
99 int num_ok_lines; /* = 1; */
102 #if ENABLE_FEATURE_GETUSERNAME_AND_HOMEDIR
104 char *home_pwd_buf; /* = (char*)null_str; */
107 #if ENABLE_FEATURE_TAB_COMPLETION
109 unsigned num_matches;
112 #if ENABLE_FEATURE_EDITING_VI
113 #define DELBUFSIZ 128
115 smallint newdelflag; /* whether delbuf should be reused yet */
116 char delbuf[DELBUFSIZ]; /* a place to store deleted characters */
119 /* Formerly these were big buffers on stack: */
120 #if ENABLE_FEATURE_TAB_COMPLETION
121 char exe_n_cwd_tab_completion__dirbuf[MAX_LINELEN];
122 char input_tab__matchBuf[MAX_LINELEN];
123 int16_t find_match__int_buf[MAX_LINELEN + 1]; /* need to have 9 bits at least */
124 int16_t find_match__pos_buf[MAX_LINELEN + 1];
128 /* See lineedit_ptr_hack.c */
129 extern struct lineedit_statics *const lineedit_ptr_to_statics;
131 #define S (*lineedit_ptr_to_statics)
132 #define state (S.state )
133 #define cmdedit_termw (S.cmdedit_termw )
134 #define previous_SIGWINCH_handler (S.previous_SIGWINCH_handler)
135 #define cmdedit_x (S.cmdedit_x )
136 #define cmdedit_y (S.cmdedit_y )
137 #define cmdedit_prmt_len (S.cmdedit_prmt_len)
138 #define cursor (S.cursor )
139 #define command_len (S.command_len )
140 #define command_ps (S.command_ps )
141 #define cmdedit_prompt (S.cmdedit_prompt )
142 #define num_ok_lines (S.num_ok_lines )
143 #define user_buf (S.user_buf )
144 #define home_pwd_buf (S.home_pwd_buf )
145 #define matches (S.matches )
146 #define num_matches (S.num_matches )
147 #define delptr (S.delptr )
148 #define newdelflag (S.newdelflag )
149 #define delbuf (S.delbuf )
151 #define INIT_S() do { \
152 (*(struct lineedit_statics**)&lineedit_ptr_to_statics) = xzalloc(sizeof(S)); \
154 cmdedit_termw = 80; \
155 USE_FEATURE_EDITING_FANCY_PROMPT(num_ok_lines = 1;) \
156 USE_FEATURE_GETUSERNAME_AND_HOMEDIR(home_pwd_buf = (char*)null_str;) \
158 static void deinit_S(void)
160 #if ENABLE_FEATURE_EDITING_FANCY_PROMPT
161 /* This one is allocated only if FANCY_PROMPT is on
162 * (otherwise it points to verbatim prompt (NOT malloced) */
163 free((char*)cmdedit_prompt);
165 #if ENABLE_FEATURE_GETUSERNAME_AND_HOMEDIR
167 if (home_pwd_buf != null_str)
170 free(lineedit_ptr_to_statics);
172 #define DEINIT_S() deinit_S()
175 /* Put 'command_ps[cursor]', cursor++.
176 * Advance cursor on screen. If we reached right margin, scroll text up
177 * and remove terminal margin effect by printing 'next_char' */
178 #define HACK_FOR_WRONG_WIDTH 1
179 #if HACK_FOR_WRONG_WIDTH
180 static void cmdedit_set_out_char(void)
181 #define cmdedit_set_out_char(next_char) cmdedit_set_out_char()
183 static void cmdedit_set_out_char(int next_char)
186 int c = (unsigned char)command_ps[cursor];
189 /* erase character after end of input string */
192 #if ENABLE_FEATURE_NONPRINTABLE_INVERSE_PUT
193 /* Display non-printable characters in reverse */
201 printf("\033[7m%c\033[0m", c);
207 if (++cmdedit_x >= cmdedit_termw) {
208 /* terminal is scrolled down */
211 #if HACK_FOR_WRONG_WIDTH
212 /* This works better if our idea of term width is wrong
213 * and it is actually wider (often happens on serial lines).
214 * Printing CR,LF *forces* cursor to next line.
215 * OTOH if terminal width is correct AND terminal does NOT
216 * have automargin (IOW: it is moving cursor to next line
217 * by itself (which is wrong for VT-10x terminals)),
218 * this will break things: there will be one extra empty line */
219 puts("\r"); /* + implicit '\n' */
221 /* Works ok only if cmdedit_termw is correct */
222 /* destroy "(auto)margin" */
223 bb_putchar(next_char);
227 // Huh? What if command_ps[cursor] == '\0' (we are at the end already?)
231 /* Move to end of line (by printing all chars till the end) */
232 static void input_end(void)
234 while (cursor < command_len)
235 cmdedit_set_out_char(' ');
238 /* Go to the next line */
239 static void goto_new_line(void)
247 static void out1str(const char *s)
253 static void beep(void)
258 /* Move back one character */
259 /* (optimized for slow terminals) */
260 static void input_backward(unsigned num)
270 if (cmdedit_x >= num) {
273 /* This is longer by 5 bytes on x86.
274 * Also gets miscompiled for ARM users
275 * (busybox.net/bugs/view.php?id=2274).
276 * printf(("\b\b\b\b" + 4) - num);
284 printf("\033[%uD", num);
288 /* Need to go one or more lines up */
291 unsigned w = cmdedit_termw; /* volatile var */
292 count_y = 1 + (num / w);
293 cmdedit_y -= count_y;
294 cmdedit_x = w * count_y - num;
296 /* go to 1st column; go up; go to correct column */
297 printf("\r" "\033[%dA" "\033[%dC", count_y, cmdedit_x);
300 static void put_prompt(void)
302 out1str(cmdedit_prompt);
305 unsigned w = cmdedit_termw; /* volatile var */
306 cmdedit_y = cmdedit_prmt_len / w; /* new quasireal y */
307 cmdedit_x = cmdedit_prmt_len % w;
311 /* draw prompt, editor line, and clear tail */
312 static void redraw(int y, int back_cursor)
314 if (y > 0) /* up to start y */
315 printf("\033[%dA", y);
318 input_end(); /* rewrite */
319 printf("\033[J"); /* erase after cursor */
320 input_backward(back_cursor);
323 /* Delete the char in front of the cursor, optionally saving it
324 * for later putback */
325 #if !ENABLE_FEATURE_EDITING_VI
326 static void input_delete(void)
327 #define input_delete(save) input_delete()
329 static void input_delete(int save)
334 if (j == (int)command_len)
337 #if ENABLE_FEATURE_EDITING_VI
343 if ((delptr - delbuf) < DELBUFSIZ)
344 *delptr++ = command_ps[j];
348 strcpy(command_ps + j, command_ps + j + 1);
350 input_end(); /* rewrite new line */
351 cmdedit_set_out_char(' '); /* erase char */
352 input_backward(cursor - j); /* back to old pos cursor */
355 #if ENABLE_FEATURE_EDITING_VI
356 static void put(void)
359 int j = delptr - delbuf;
364 /* open hole and then fill it */
365 memmove(command_ps + cursor + j, command_ps + cursor, command_len - cursor + 1);
366 strncpy(command_ps + cursor, delbuf, j);
368 input_end(); /* rewrite new line */
369 input_backward(cursor - ocursor - j + 1); /* at end of new text */
373 /* Delete the char in back of the cursor */
374 static void input_backspace(void)
382 /* Move forward one character */
383 static void input_forward(void)
385 if (cursor < command_len)
386 cmdedit_set_out_char(command_ps[cursor + 1]);
389 #if ENABLE_FEATURE_TAB_COMPLETION
391 static void free_tab_completion_data(void)
395 free(matches[--num_matches]);
401 static void add_match(char *matched)
403 matches = xrealloc_vector(matches, 4, num_matches);
404 matches[num_matches] = matched;
408 #if ENABLE_FEATURE_USERNAME_COMPLETION
409 static void username_tab_completion(char *ud, char *with_shash_flg)
411 struct passwd *entry;
414 ud++; /* ~user/... to user/... */
415 userlen = strlen(ud);
417 if (with_shash_flg) { /* "~/..." or "~user/..." */
418 char *sav_ud = ud - 1;
421 if (*ud == '/') { /* "~/..." */
426 temp = strchr(ud, '/');
427 *temp = '\0'; /* ~user\0 */
428 entry = getpwnam(ud);
429 *temp = '/'; /* restore ~user/... */
432 home = entry->pw_dir;
435 if ((userlen + strlen(home) + 1) < MAX_LINELEN) {
437 sprintf(sav_ud, "%s%s", home, ud);
442 /* Using _r function to avoid pulling in static buffers */
445 struct passwd *result;
448 while (!getpwent_r(&pwd, line_buff, sizeof(line_buff), &result)) {
449 /* Null usernames should result in all users as possible completions. */
450 if (/*!userlen || */ strncmp(ud, pwd.pw_name, userlen) == 0) {
451 add_match(xasprintf("~%s/", pwd.pw_name));
457 #endif /* FEATURE_COMMAND_USERNAME_COMPLETION */
465 static int path_parse(char ***p, int flags)
472 /* if not setenv PATH variable, to search cur dir "." */
473 if (flags != FIND_EXE_ONLY)
476 if (state->flags & WITH_PATH_LOOKUP)
477 pth = state->path_lookup;
479 pth = getenv("PATH");
480 /* PATH=<empty> or PATH=:<empty> */
481 if (!pth || !pth[0] || LONE_CHAR(pth, ':'))
485 npth = 1; /* path component count */
487 tmp = strchr(tmp, ':');
491 break; /* :<empty> */
495 res = xmalloc(npth * sizeof(char*));
496 res[0] = tmp = xstrdup(pth);
499 tmp = strchr(tmp, ':');
502 *tmp++ = '\0'; /* ':' -> '\0' */
504 break; /* :<empty> */
511 static void exe_n_cwd_tab_completion(char *command, int type)
517 char **paths = path1;
521 char *pfind = strrchr(command, '/');
522 /* char dirbuf[MAX_LINELEN]; */
523 #define dirbuf (S.exe_n_cwd_tab_completion__dirbuf)
526 path1[0] = (char*)".";
529 /* no dir, if flags==EXE_ONLY - get paths, else "." */
530 npaths = path_parse(&paths, type);
533 /* dirbuf = ".../.../.../" */
534 safe_strncpy(dirbuf, command, (pfind - command) + 2);
535 #if ENABLE_FEATURE_USERNAME_COMPLETION
536 if (dirbuf[0] == '~') /* ~/... or ~user/... */
537 username_tab_completion(dirbuf, dirbuf);
540 /* point to 'l' in "..../last_component" */
544 for (i = 0; i < npaths; i++) {
545 dir = opendir(paths[i]);
547 continue; /* don't print an error */
549 while ((next = readdir(dir)) != NULL) {
551 const char *str_found = next->d_name;
554 if (strncmp(str_found, pfind, strlen(pfind)))
556 /* not see .name without .match */
557 if (*str_found == '.' && *pfind == '\0') {
558 if (NOT_LONE_CHAR(paths[i], '/') || str_found[1])
560 str_found = ""; /* only "/" */
562 found = concat_path_file(paths[i], str_found);
563 /* hmm, remove in progress? */
564 /* NB: stat() first so that we see is it a directory;
565 * but if that fails, use lstat() so that
566 * we still match dangling links */
567 if (stat(found, &st) && lstat(found, &st))
569 /* find with dirs? */
570 if (paths[i] != dirbuf)
571 strcpy(found, next->d_name); /* only name */
573 len1 = strlen(found);
574 found = xrealloc(found, len1 + 2);
576 found[len1+1] = '\0';
578 if (S_ISDIR(st.st_mode)) {
579 /* name is a directory */
580 if (found[len1-1] != '/') {
584 /* not put found file if search only dirs for cd */
585 if (type == FIND_DIR_ONLY)
588 /* Add it to the list */
596 if (paths != path1) {
597 free(paths[0]); /* allocated memory is only in first member */
603 #define QUOT (UCHAR_MAX+1)
605 #define collapse_pos(is, in) do { \
606 memmove(int_buf+(is), int_buf+(in), (MAX_LINELEN+1-(is)-(in)) * sizeof(pos_buf[0])); \
607 memmove(pos_buf+(is), pos_buf+(in), (MAX_LINELEN+1-(is)-(in)) * sizeof(pos_buf[0])); \
610 static int find_match(char *matchBuf, int *len_with_quotes)
615 /* int16_t int_buf[MAX_LINELEN + 1]; */
616 /* int16_t pos_buf[MAX_LINELEN + 1]; */
617 #define int_buf (S.find_match__int_buf)
618 #define pos_buf (S.find_match__pos_buf)
620 /* set to integer dimension characters and own positions */
622 int_buf[i] = (unsigned char)matchBuf[i];
623 if (int_buf[i] == 0) {
624 pos_buf[i] = -1; /* indicator end line */
630 /* mask \+symbol and convert '\t' to ' ' */
631 for (i = j = 0; matchBuf[i]; i++, j++)
632 if (matchBuf[i] == '\\') {
633 collapse_pos(j, j + 1);
636 #if ENABLE_FEATURE_NONPRINTABLE_INVERSE_PUT
637 if (matchBuf[i] == '\t') /* algorithm equivalent */
638 int_buf[j] = ' ' | QUOT;
641 #if ENABLE_FEATURE_NONPRINTABLE_INVERSE_PUT
642 else if (matchBuf[i] == '\t')
646 /* mask "symbols" or 'symbols' */
648 for (i = 0; int_buf[i]; i++) {
650 if (c == '\'' || c == '"') {
659 } else if (c2 != 0 && c != '$')
663 /* skip commands with arguments if line has commands delimiters */
664 /* ';' ';;' '&' '|' '&&' '||' but `>&' `<&' `>|' */
665 for (i = 0; int_buf[i]; i++) {
668 j = i ? int_buf[i - 1] : -1;
670 if (c == ';' || c == '&' || c == '|') {
671 command_mode = 1 + (c == c2);
673 if (j == '>' || j == '<')
675 } else if (c == '|' && j == '>')
679 collapse_pos(0, i + command_mode);
680 i = -1; /* hack incremet */
683 /* collapse `command...` */
684 for (i = 0; int_buf[i]; i++)
685 if (int_buf[i] == '`') {
686 for (j = i + 1; int_buf[j]; j++)
687 if (int_buf[j] == '`') {
688 collapse_pos(i, j + 1);
693 /* not found close ` - command mode, collapse all previous */
694 collapse_pos(0, i + 1);
697 i--; /* hack incremet */
700 /* collapse (command...(command...)...) or {command...{command...}...} */
701 c = 0; /* "recursive" level */
703 for (i = 0; int_buf[i]; i++)
704 if (int_buf[i] == '(' || int_buf[i] == '{') {
705 if (int_buf[i] == '(')
709 collapse_pos(0, i + 1);
710 i = -1; /* hack incremet */
712 for (i = 0; pos_buf[i] >= 0 && (c > 0 || c2 > 0); i++)
713 if ((int_buf[i] == ')' && c > 0) || (int_buf[i] == '}' && c2 > 0)) {
714 if (int_buf[i] == ')')
718 collapse_pos(0, i + 1);
719 i = -1; /* hack incremet */
722 /* skip first not quote space */
723 for (i = 0; int_buf[i]; i++)
724 if (int_buf[i] != ' ')
729 /* set find mode for completion */
730 command_mode = FIND_EXE_ONLY;
731 for (i = 0; int_buf[i]; i++)
732 if (int_buf[i] == ' ' || int_buf[i] == '<' || int_buf[i] == '>') {
733 if (int_buf[i] == ' ' && command_mode == FIND_EXE_ONLY
734 && matchBuf[pos_buf[0]] == 'c'
735 && matchBuf[pos_buf[1]] == 'd'
737 command_mode = FIND_DIR_ONLY;
739 command_mode = FIND_FILE_ONLY;
743 for (i = 0; int_buf[i]; i++)
746 for (--i; i >= 0; i--) {
748 if (c == ' ' || c == '<' || c == '>' || c == '|' || c == '&') {
749 collapse_pos(0, i + 1);
753 /* skip first not quoted '\'' or '"' */
754 for (i = 0; int_buf[i] == '\'' || int_buf[i] == '"'; i++)
756 /* collapse quote or unquote // or /~ */
757 while ((int_buf[i] & ~QUOT) == '/'
758 && ((int_buf[i+1] & ~QUOT) == '/' || (int_buf[i+1] & ~QUOT) == '~')
763 /* set only match and destroy quotes */
765 for (c = 0; pos_buf[i] >= 0; i++) {
766 matchBuf[c++] = matchBuf[pos_buf[i]];
770 /* old length matchBuf with quotes symbols */
771 *len_with_quotes = j ? j - pos_buf[0] : 0;
779 * display by column (original idea from ls applet,
780 * very optimized by me :)
782 static void showfiles(void)
785 int column_width = 0;
786 int nfiles = num_matches;
790 /* find the longest file name- use that as the column width */
791 for (row = 0; row < nrows; row++) {
792 l = strlen(matches[row]);
793 if (column_width < l)
796 column_width += 2; /* min space for columns */
797 ncols = cmdedit_termw / column_width;
802 nrows++; /* round up fractionals */
806 for (row = 0; row < nrows; row++) {
810 for (nc = 1; nc < ncols && n+nrows < nfiles; n += nrows, nc++) {
811 printf("%s%-*s", matches[n],
812 (int)(column_width - strlen(matches[n])), "");
818 static char *add_quote_for_spec_chars(char *found)
821 char *s = xmalloc((strlen(found) + 1) * 2);
824 if (strchr(" `\"#$%^&*()=+{}[]:;\'|\\<>", *found))
832 /* Do TAB completion */
833 static void input_tab(smallint *lastWasTab)
835 if (!(state->flags & TAB_COMPLETION))
841 /* char matchBuf[MAX_LINELEN]; */
842 #define matchBuf (S.input_tab__matchBuf)
846 *lastWasTab = TRUE; /* flop trigger */
848 /* Make a local copy of the string -- up
849 * to the position of the cursor */
850 tmp = strncpy(matchBuf, command_ps, cursor);
853 find_type = find_match(matchBuf, &recalc_pos);
855 /* Free up any memory already allocated */
856 free_tab_completion_data();
858 #if ENABLE_FEATURE_USERNAME_COMPLETION
859 /* If the word starts with `~' and there is no slash in the word,
860 * then try completing this word as a username. */
861 if (state->flags & USERNAME_COMPLETION)
862 if (matchBuf[0] == '~' && strchr(matchBuf, '/') == 0)
863 username_tab_completion(matchBuf, NULL);
865 /* Try to match any executable in our path and everything
866 * in the current working directory */
868 exe_n_cwd_tab_completion(matchBuf, find_type);
869 /* Sort, then remove any duplicates found */
873 qsort_string_vector(matches, num_matches);
874 for (i = 0; i < num_matches - 1; ++i) {
875 if (matches[i] && matches[i+1]) { /* paranoia */
876 if (strcmp(matches[i], matches[i+1]) == 0) {
878 matches[i] = NULL; /* paranoia */
880 matches[n++] = matches[i];
884 matches[n] = matches[i];
887 /* Did we find exactly one match? */
888 if (!matches || num_matches > 1) {
891 return; /* not found */
892 /* find minimal match */
893 tmp1 = xstrdup(matches[0]);
894 for (tmp = tmp1; *tmp; tmp++)
895 for (len_found = 1; len_found < num_matches; len_found++)
896 if (matches[len_found][(tmp - tmp1)] != *tmp) {
900 if (*tmp1 == '\0') { /* have unique */
904 tmp = add_quote_for_spec_chars(tmp1);
906 } else { /* one match */
907 tmp = add_quote_for_spec_chars(matches[0]);
908 /* for next completion current found */
911 len_found = strlen(tmp);
912 if (tmp[len_found-1] != '/') {
913 tmp[len_found] = ' ';
914 tmp[len_found+1] = '\0';
917 len_found = strlen(tmp);
918 /* have space to placed match? */
919 if ((len_found - strlen(matchBuf) + command_len) < MAX_LINELEN) {
920 /* before word for match */
921 command_ps[cursor - recalc_pos] = '\0';
923 strcpy(matchBuf, command_ps + cursor);
925 strcat(command_ps, tmp);
927 strcat(command_ps, matchBuf);
928 /* back to begin word for match */
929 input_backward(recalc_pos);
931 recalc_pos = cursor + len_found;
933 command_len = strlen(command_ps);
934 /* write out the matched command */
935 redraw(cmdedit_y, command_len - recalc_pos);
940 /* Ok -- the last char was a TAB. Since they
941 * just hit TAB again, print a list of all the
942 * available choices... */
943 if (matches && num_matches > 0) {
944 int sav_cursor = cursor; /* change goto_new_line() */
946 /* Go to the next line */
949 redraw(0, command_len - sav_cursor);
954 #endif /* FEATURE_COMMAND_TAB_COMPLETION */
959 /* state->flags is already checked to be nonzero */
960 static void get_previous_history(void)
962 if (command_ps[0] != '\0' || state->history[state->cur_history] == NULL) {
963 free(state->history[state->cur_history]);
964 state->history[state->cur_history] = xstrdup(command_ps);
966 state->cur_history--;
969 static int get_next_history(void)
971 if (state->flags & DO_HISTORY) {
972 int ch = state->cur_history;
973 if (ch < state->cnt_history) {
974 get_previous_history(); /* save the current history line */
975 state->cur_history = ch + 1;
976 return state->cur_history;
983 #if ENABLE_FEATURE_EDITING_SAVEHISTORY
984 /* state->flags is already checked to be nonzero */
985 static void load_history(const char *fromfile)
990 /* NB: do not trash old history if file can't be opened */
992 fp = fopen(fromfile, "r");
994 /* clean up old history */
995 for (hi = state->cnt_history; hi > 0;) {
997 free(state->history[hi]);
1000 for (hi = 0; hi < MAX_HISTORY;) {
1001 char *hl = xmalloc_fgetline(fp);
1007 if (l >= MAX_LINELEN)
1008 hl[MAX_LINELEN-1] = '\0';
1009 if (l == 0 || hl[0] == ' ') {
1013 state->history[hi++] = hl;
1016 state->cur_history = state->cnt_history = hi;
1020 /* state->flags is already checked to be nonzero */
1021 static void save_history(const char *tofile)
1025 fp = fopen(tofile, "w");
1029 for (i = 0; i < state->cnt_history; i++) {
1030 fprintf(fp, "%s\n", state->history[i]);
1036 #define load_history(a) ((void)0)
1037 #define save_history(a) ((void)0)
1038 #endif /* FEATURE_COMMAND_SAVEHISTORY */
1040 static void remember_in_history(const char *str)
1044 if (!(state->flags & DO_HISTORY))
1047 i = state->cnt_history;
1048 free(state->history[MAX_HISTORY]);
1049 state->history[MAX_HISTORY] = NULL;
1050 /* After max history, remove the oldest command */
1051 if (i >= MAX_HISTORY) {
1052 free(state->history[0]);
1053 for (i = 0; i < MAX_HISTORY-1; i++)
1054 state->history[i] = state->history[i+1];
1056 // Maybe "if (!i || strcmp(history[i-1], command) != 0) ..."
1057 // (i.e. do not save dups?)
1058 state->history[i++] = xstrdup(str);
1059 state->cur_history = i;
1060 state->cnt_history = i;
1061 #if ENABLE_FEATURE_EDITING_SAVEHISTORY
1062 if ((state->flags & SAVE_HISTORY) && state->hist_file)
1063 save_history(state->hist_file);
1065 USE_FEATURE_EDITING_FANCY_PROMPT(num_ok_lines++;)
1068 #else /* MAX_HISTORY == 0 */
1069 #define remember_in_history(a) ((void)0)
1070 #endif /* MAX_HISTORY */
1074 * This function is used to grab a character buffer
1075 * from the input file descriptor and allows you to
1076 * a string with full command editing (sort of like
1079 * The following standard commands are not implemented:
1080 * ESC-b -- Move back one word
1081 * ESC-f -- Move forward one word
1082 * ESC-d -- Delete back one word
1083 * ESC-h -- Delete forward one word
1084 * CTL-t -- Transpose two characters
1086 * Minimalist vi-style command line editing available if configured.
1087 * vi mode implemented 2005 by Paul Fox <pgf@foxharp.boston.ma.us>
1090 #if ENABLE_FEATURE_EDITING_VI
1092 vi_Word_motion(char *command, int eat)
1094 while (cursor < command_len && !isspace(command[cursor]))
1096 if (eat) while (cursor < command_len && isspace(command[cursor]))
1101 vi_word_motion(char *command, int eat)
1103 if (isalnum(command[cursor]) || command[cursor] == '_') {
1104 while (cursor < command_len
1105 && (isalnum(command[cursor+1]) || command[cursor+1] == '_'))
1107 } else if (ispunct(command[cursor])) {
1108 while (cursor < command_len && ispunct(command[cursor+1]))
1112 if (cursor < command_len)
1115 if (eat && cursor < command_len && isspace(command[cursor]))
1116 while (cursor < command_len && isspace(command[cursor]))
1121 vi_End_motion(char *command)
1124 while (cursor < command_len && isspace(command[cursor]))
1126 while (cursor < command_len-1 && !isspace(command[cursor+1]))
1131 vi_end_motion(char *command)
1133 if (cursor >= command_len-1)
1136 while (cursor < command_len-1 && isspace(command[cursor]))
1138 if (cursor >= command_len-1)
1140 if (isalnum(command[cursor]) || command[cursor] == '_') {
1141 while (cursor < command_len-1
1142 && (isalnum(command[cursor+1]) || command[cursor+1] == '_')
1146 } else if (ispunct(command[cursor])) {
1147 while (cursor < command_len-1 && ispunct(command[cursor+1]))
1153 vi_Back_motion(char *command)
1155 while (cursor > 0 && isspace(command[cursor-1]))
1157 while (cursor > 0 && !isspace(command[cursor-1]))
1162 vi_back_motion(char *command)
1167 while (cursor > 0 && isspace(command[cursor]))
1171 if (isalnum(command[cursor]) || command[cursor] == '_') {
1173 && (isalnum(command[cursor-1]) || command[cursor-1] == '_')
1177 } else if (ispunct(command[cursor])) {
1178 while (cursor > 0 && ispunct(command[cursor-1]))
1186 * read_line_input and its helpers
1189 #if !ENABLE_FEATURE_EDITING_FANCY_PROMPT
1190 static void parse_and_put_prompt(const char *prmt_ptr)
1192 cmdedit_prompt = prmt_ptr;
1193 cmdedit_prmt_len = strlen(prmt_ptr);
1197 static void parse_and_put_prompt(const char *prmt_ptr)
1200 size_t cur_prmt_len = 0;
1201 char flg_not_length = '[';
1202 char *prmt_mem_ptr = xzalloc(1);
1203 char *cwd_buf = xrealloc_getcwd_or_warn(NULL);
1208 cmdedit_prmt_len = 0;
1211 cwd_buf = (char *)bb_msg_unknown;
1214 cbuf[1] = '\0'; /* never changes */
1217 char *free_me = NULL;
1222 const char *cp = prmt_ptr;
1225 c = bb_process_escape_sequence(&prmt_ptr);
1226 if (prmt_ptr == cp) {
1232 #if ENABLE_FEATURE_GETUSERNAME_AND_HOMEDIR
1234 pbuf = user_buf ? user_buf : (char*)"";
1238 pbuf = free_me = safe_gethostname();
1239 *strchrnul(pbuf, '.') = '\0';
1242 c = (geteuid() == 0 ? '#' : '$');
1244 #if ENABLE_FEATURE_GETUSERNAME_AND_HOMEDIR
1246 /* /home/user[/something] -> ~[/something] */
1248 l = strlen(home_pwd_buf);
1250 && strncmp(home_pwd_buf, cwd_buf, l) == 0
1251 && (cwd_buf[l]=='/' || cwd_buf[l]=='\0')
1252 && strlen(cwd_buf + l) < PATH_MAX
1254 pbuf = free_me = xasprintf("~%s", cwd_buf + l);
1260 cp = strrchr(pbuf, '/');
1261 if (cp != NULL && cp != pbuf)
1262 pbuf += (cp-pbuf) + 1;
1265 pbuf = free_me = xasprintf("%d", num_ok_lines);
1267 case 'e': case 'E': /* \e \E = \033 */
1270 case 'x': case 'X': {
1272 for (l = 0; l < 3;) {
1274 buf2[l++] = *prmt_ptr;
1276 h = strtoul(buf2, &pbuf, 16);
1277 if (h > UCHAR_MAX || (pbuf - buf2) < l) {
1283 c = (char)strtoul(buf2, NULL, 16);
1290 if (c == flg_not_length) {
1291 flg_not_length = (flg_not_length == '[' ? ']' : '[');
1299 cur_prmt_len = strlen(pbuf);
1300 prmt_len += cur_prmt_len;
1301 if (flg_not_length != ']')
1302 cmdedit_prmt_len += cur_prmt_len;
1303 prmt_mem_ptr = strcat(xrealloc(prmt_mem_ptr, prmt_len+1), pbuf);
1307 if (cwd_buf != (char *)bb_msg_unknown)
1309 cmdedit_prompt = prmt_mem_ptr;
1314 static void cmdedit_setwidth(unsigned w, int redraw_flg)
1318 /* new y for current cursor */
1319 int new_y = (cursor + cmdedit_prmt_len) / w;
1321 redraw((new_y >= cmdedit_y ? new_y : cmdedit_y), command_len - cursor);
1326 static void win_changed(int nsig)
1329 get_terminal_width_height(0, &width, NULL);
1330 cmdedit_setwidth(width, nsig /* - just a yes/no flag */);
1331 if (nsig == SIGWINCH)
1332 signal(SIGWINCH, win_changed); /* rearm ourself */
1336 * The emacs and vi modes share much of the code in the big
1337 * command loop. Commands entered when in vi's command mode (aka
1338 * "escape mode") get an extra bit added to distinguish them --
1339 * this keeps them from being self-inserted. This clutters the
1340 * big switch a bit, but keeps all the code in one place.
1345 /* leave out the "vi-mode"-only case labels if vi editing isn't
1347 #define vi_case(caselabel) USE_FEATURE_EDITING(case caselabel)
1349 /* convert uppercase ascii to equivalent control char, for readability */
1351 #define CTRL(a) ((a) & ~0x40)
1354 * -1 on read errors or EOF, or on bare Ctrl-D,
1355 * 0 on ctrl-C (the line entered is still returned in 'command'),
1356 * >0 length of input string, including terminating '\n'
1358 int FAST_FUNC read_line_input(const char *prompt, char *command, int maxsize, line_input_t *st)
1360 #if ENABLE_FEATURE_TAB_COMPLETION
1361 smallint lastWasTab = FALSE;
1365 smallint break_out = 0;
1366 #if ENABLE_FEATURE_EDITING_VI
1367 smallint vi_cmdmode = 0;
1370 struct termios initial_settings;
1371 struct termios new_settings;
1375 if (tcgetattr(STDIN_FILENO, &initial_settings) < 0
1376 || !(initial_settings.c_lflag & ECHO)
1378 /* Happens when e.g. stty -echo was run before */
1380 parse_and_put_prompt(prompt);
1382 if (fgets(command, maxsize, stdin) == NULL)
1383 len = -1; /* EOF or error */
1385 len = strlen(command);
1390 // FIXME: audit & improve this
1391 if (maxsize > MAX_LINELEN)
1392 maxsize = MAX_LINELEN;
1394 /* With null flags, no other fields are ever used */
1395 state = st ? st : (line_input_t*) &const_int_0;
1396 #if ENABLE_FEATURE_EDITING_SAVEHISTORY
1397 if ((state->flags & SAVE_HISTORY) && state->hist_file)
1398 load_history(state->hist_file);
1401 /* prepare before init handlers */
1402 cmdedit_y = 0; /* quasireal y, not true if line > xt*yt */
1404 command_ps = command;
1407 new_settings = initial_settings;
1408 new_settings.c_lflag &= ~ICANON; /* unbuffered input */
1409 /* Turn off echoing and CTRL-C, so we can trap it */
1410 new_settings.c_lflag &= ~(ECHO | ECHONL | ISIG);
1411 /* Hmm, in linux c_cc[] is not parsed if ICANON is off */
1412 new_settings.c_cc[VMIN] = 1;
1413 new_settings.c_cc[VTIME] = 0;
1414 /* Turn off CTRL-C, so we can trap it */
1415 #ifndef _POSIX_VDISABLE
1416 #define _POSIX_VDISABLE '\0'
1418 new_settings.c_cc[VINTR] = _POSIX_VDISABLE;
1419 tcsetattr(STDIN_FILENO, TCSANOW, &new_settings);
1421 /* Now initialize things */
1422 previous_SIGWINCH_handler = signal(SIGWINCH, win_changed);
1423 win_changed(0); /* do initial resizing */
1424 #if ENABLE_FEATURE_GETUSERNAME_AND_HOMEDIR
1426 struct passwd *entry;
1428 entry = getpwuid(geteuid());
1430 user_buf = xstrdup(entry->pw_name);
1431 home_pwd_buf = xstrdup(entry->pw_dir);
1435 /* Print out the command prompt */
1436 parse_and_put_prompt(prompt);
1441 if (nonblock_safe_read(STDIN_FILENO, &c, 1) < 1) {
1442 /* if we can't read input then exit */
1443 goto prepare_to_die;
1448 #if ENABLE_FEATURE_EDITING_VI
1464 /* Control-a -- Beginning of line */
1465 input_backward(cursor);
1470 vi_case('\x7f'|vbit:) /* DEL */
1471 /* Control-b -- Move back one character */
1475 vi_case(CTRL('C')|vbit:)
1476 /* Control-c -- stop gathering input */
1479 break_out = -1; /* "do not append '\n'" */
1482 /* Control-d -- Delete one character, or exit
1483 * if the len=0 and no chars to delete */
1484 if (command_len == 0) {
1487 /* to control stopped jobs */
1488 break_out = command_len = -1;
1496 /* Control-e -- End of line */
1502 /* Control-f -- Move forward one character */
1507 case '\x7f': /* DEL */
1508 /* Control-h and DEL */
1512 #if ENABLE_FEATURE_TAB_COMPLETION
1514 input_tab(&lastWasTab);
1519 /* Control-k -- clear to end of line */
1520 command[cursor] = 0;
1521 command_len = cursor;
1525 vi_case(CTRL('L')|vbit:)
1526 /* Control-l -- clear screen */
1528 redraw(0, command_len - cursor);
1533 vi_case(CTRL('N')|vbit:)
1535 /* Control-n -- Get next command in history */
1536 if (get_next_history())
1540 vi_case(CTRL('P')|vbit:)
1542 /* Control-p -- Get previous command from history */
1543 if ((state->flags & DO_HISTORY) && state->cur_history > 0) {
1544 get_previous_history();
1552 vi_case(CTRL('U')|vbit:)
1553 /* Control-U -- Clear line before cursor */
1555 strcpy(command, command + cursor);
1556 command_len -= cursor;
1557 redraw(cmdedit_y, command_len);
1561 vi_case(CTRL('W')|vbit:)
1562 /* Control-W -- Remove the last word */
1563 while (cursor > 0 && isspace(command[cursor-1]))
1565 while (cursor > 0 && !isspace(command[cursor-1]))
1569 #if ENABLE_FEATURE_EDITING_VI
1574 input_backward(cursor);
1595 vi_Word_motion(command, 1);
1598 vi_word_motion(command, 1);
1601 vi_End_motion(command);
1604 vi_end_motion(command);
1607 vi_Back_motion(command);
1610 vi_back_motion(command);
1625 if (safe_read(STDIN_FILENO, &c, 1) < 1)
1626 goto prepare_to_die;
1627 if (c == (prevc & 0xff)) {
1629 input_backward(cursor);
1639 case 'w': /* "dw", "cw" */
1640 vi_word_motion(command, vi_cmdmode);
1642 case 'W': /* 'dW', 'cW' */
1643 vi_Word_motion(command, vi_cmdmode);
1645 case 'e': /* 'de', 'ce' */
1646 vi_end_motion(command);
1649 case 'E': /* 'dE', 'cE' */
1650 vi_End_motion(command);
1655 input_backward(cursor - sc);
1656 while (nc-- > cursor)
1659 case 'b': /* "db", "cb" */
1660 case 'B': /* implemented as B */
1662 vi_back_motion(command);
1664 vi_Back_motion(command);
1665 while (sc-- > cursor)
1668 case ' ': /* "d ", "c " */
1671 case '$': /* "d$", "c$" */
1673 while (cursor < command_len)
1686 if (safe_read(STDIN_FILENO, &c, 1) < 1)
1687 goto prepare_to_die;
1691 *(command + cursor) = c;
1696 #endif /* FEATURE_COMMAND_EDITING_VI */
1698 case '\x1b': /* ESC */
1700 #if ENABLE_FEATURE_EDITING_VI
1701 if (state->flags & VI_MODE) {
1702 /* ESC: insert mode --> command mode */
1708 /* escape sequence follows */
1709 if (safe_read(STDIN_FILENO, &c, 1) < 1)
1710 goto prepare_to_die;
1711 /* different vt100 emulations */
1712 if (c == '[' || c == 'O') {
1715 if (safe_read(STDIN_FILENO, &c, 1) < 1)
1716 goto prepare_to_die;
1718 if (c >= '1' && c <= '9') {
1719 unsigned char dummy;
1721 if (safe_read(STDIN_FILENO, &dummy, 1) < 1)
1722 goto prepare_to_die;
1728 #if ENABLE_FEATURE_TAB_COMPLETION
1729 case '\t': /* Alt-Tab */
1730 input_tab(&lastWasTab);
1735 /* Up Arrow -- Get previous command from history */
1736 if ((state->flags & DO_HISTORY) && state->cur_history > 0) {
1737 get_previous_history();
1743 /* Down Arrow -- Get next command in history */
1744 if (!get_next_history())
1747 /* Rewrite the line with the selected history item */
1748 /* change command */
1749 command_len = strlen(strcpy(command, state->history[state->cur_history]));
1750 /* redraw and go to eol (bol, in vi */
1751 redraw(cmdedit_y, (state->flags & VI_MODE) ? 9999 : 0);
1755 /* Right Arrow -- Move forward one character */
1759 /* Left Arrow -- Move back one character */
1766 case '1': // vt100? linux vt? or what?
1767 case '7': // vt100? linux vt? or what?
1768 case 'H': /* xterm's <Home> */
1769 input_backward(cursor);
1771 case '4': // vt100? linux vt? or what?
1772 case '8': // vt100? linux vt? or what?
1773 case 'F': /* xterm's <End> */
1782 default: /* If it's regular input, do the normal thing */
1784 /* Control-V -- force insert of next char */
1785 if (c == CTRL('V')) {
1786 if (safe_read(STDIN_FILENO, &c, 1) < 1)
1787 goto prepare_to_die;
1794 #if ENABLE_FEATURE_EDITING_VI
1795 if (vi_cmdmode) /* Don't self-insert */
1798 if ((int)command_len >= (maxsize - 2)) /* Need to leave space for enter */
1802 if (cursor == (command_len - 1)) { /* Append if at the end of the line */
1803 command[cursor] = c;
1804 command[cursor+1] = '\0';
1805 cmdedit_set_out_char(' ');
1806 } else { /* Insert otherwise */
1809 memmove(command + sc + 1, command + sc, command_len - sc);
1812 /* rewrite from cursor */
1814 /* to prev x pos + 1 */
1815 input_backward(cursor - sc);
1819 if (break_out) /* Enter is the command terminator, no more input. */
1822 #if ENABLE_FEATURE_TAB_COMPLETION
1828 if (command_len > 0)
1829 remember_in_history(command);
1831 if (break_out > 0) {
1832 command[command_len++] = '\n';
1833 command[command_len] = '\0';
1836 #if ENABLE_FEATURE_TAB_COMPLETION
1837 free_tab_completion_data();
1840 /* restore initial_settings */
1841 tcsetattr(STDIN_FILENO, TCSANOW, &initial_settings);
1842 /* restore SIGWINCH handler */
1843 signal(SIGWINCH, previous_SIGWINCH_handler);
1851 line_input_t* FAST_FUNC new_line_input_t(int flags)
1853 line_input_t *n = xzalloc(sizeof(*n));
1860 #undef read_line_input
1861 int FAST_FUNC read_line_input(const char* prompt, char* command, int maxsize)
1863 fputs(prompt, stdout);
1865 fgets(command, maxsize, stdin);
1866 return strlen(command);
1869 #endif /* FEATURE_COMMAND_EDITING */
1880 const char *applet_name = "debug stuff usage";
1882 int main(int argc, char **argv)
1884 char buff[MAX_LINELEN];
1886 #if ENABLE_FEATURE_EDITING_FANCY_PROMPT
1887 "\\[\\033[32;1m\\]\\u@\\[\\x1b[33;1m\\]\\h:"
1888 "\\[\\033[34;1m\\]\\w\\[\\033[35;1m\\] "
1889 "\\!\\[\\e[36;1m\\]\\$ \\[\\E[0m\\]";
1894 #if ENABLE_FEATURE_NONPRINTABLE_INVERSE_PUT
1895 setlocale(LC_ALL, "");
1899 l = read_line_input(prompt, buff);
1900 if (l <= 0 || buff[l-1] != '\n')
1903 printf("*** read_line_input() returned line =%s=\n", buff);
1905 printf("*** read_line_input() detect ^D\n");