1 /* vi: set sw=4 ts=4: */
3 * Termios command line History and Editting.
5 * Copyright (c) 1986-2001 may safely be consumed by a BSD or GPL license.
6 * Written by: Vladimir Oleynik <vodz@usa.net>
9 * Adam Rogoyski <rogoyski@cs.utexas.edu>
10 * Dave Cinege <dcinege@psychosis.com>
11 * Jakub Jelinek (c) 1995
12 * Erik Andersen <andersee@debian.org> (Majorly adjusted for busybox)
14 * This code is 'as is' with no warranty.
21 Terminal key codes are not extensive, and more will probably
22 need to be added. This version was created on Debian GNU/Linux 2.x.
23 Delete, Backspace, Home, End, and the arrow keys were tested
24 to work in an Xterm and console. Ctrl-A also works as Home.
25 Ctrl-E also works as End.
27 Small bugs (simple effect):
28 - not true viewing if terminal size (x*y symbols) less
29 size (prompt + editor`s line + 2 symbols)
30 - not true viewing if length prompt less terminal width
41 #include <sys/ioctl.h>
54 #define BB_FEATURE_COMMAND_EDITING
55 #define BB_FEATURE_COMMAND_TAB_COMPLETION
56 #define BB_FEATURE_COMMAND_USERNAME_COMPLETION
57 #define BB_FEATURE_NONPRINTABLE_INVERSE_PUT
58 #define BB_FEATURE_CLEAN_UP
71 #ifdef BB_FEATURE_COMMAND_TAB_COMPLETION
76 #ifdef BB_FEATURE_COMMAND_EDITING
78 #ifndef BB_FEATURE_COMMAND_TAB_COMPLETION
79 #undef BB_FEATURE_COMMAND_USERNAME_COMPLETION
82 #if defined(BB_FEATURE_COMMAND_USERNAME_COMPLETION) || !defined(BB_FEATURE_SH_SIMPLE_PROMPT)
83 #define BB_FEATURE_GETUSERNAME_AND_HOMEDIR
86 #ifdef BB_FEATURE_GETUSERNAME_AND_HOMEDIR
88 #include "pwd_grp/pwd.h"
92 #endif /* advanced FEATURES */
96 void *xrealloc(void *old, size_t size)
98 return realloc(old, size);
101 void *xmalloc(size_t size)
105 char *xstrdup(const char *s)
110 void *xcalloc(size_t size, size_t se)
112 return calloc(size, se);
115 #define error_msg(s, d) fprintf(stderr, s, d)
125 /* Maximum length of the linked list for the command line history */
126 static const int MAX_HISTORY = 15;
128 /* First element in command line list */
129 static struct history *his_front = NULL;
131 /* Last element in command line list */
132 static struct history *his_end = NULL;
135 /* ED: sparc termios is broken: revert back to old termio handling. */
139 # define termios termio
140 # define setTermSettings(fd,argp) ioctl(fd,TCSETAF,argp)
141 # define getTermSettings(fd,argp) ioctl(fd,TCGETA,argp)
143 # include <termios.h>
144 # define setTermSettings(fd,argp) tcsetattr(fd,TCSANOW,argp)
145 # define getTermSettings(fd,argp) tcgetattr(fd, argp);
148 /* Current termio and the previous termio before starting sh */
149 static struct termios initial_settings, new_settings;
152 #ifndef _POSIX_VDISABLE
153 #define _POSIX_VDISABLE '\0'
158 volatile int cmdedit_termw = 80; /* actual terminal width */
159 static int history_counter = 0; /* Number of commands in history list */
161 volatile int handlers_sets = 0; /* Set next bites: */
164 SET_ATEXIT = 1, /* when atexit() has been called
165 and get euid,uid,gid to fast compare */
166 SET_TERM_HANDLERS = 2, /* set many terminates signal handlers */
167 SET_WCHG_HANDLERS = 4, /* winchg signal handler */
168 SET_RESET_TERM = 8, /* if the terminal needs to be reset upon exit */
172 static int cmdedit_x; /* real x terminal position */
173 static int cmdedit_y; /* pseudoreal y terminal position */
174 static int cmdedit_prmt_len; /* lenght prompt without colores string */
176 static int cursor; /* required global for signal handler */
177 static int len; /* --- "" - - "" - -"- --""-- --""--- */
178 static char *command_ps; /* --- "" - - "" - -"- --""-- --""--- */
180 #ifdef BB_FEATURE_SH_SIMPLE_PROMPT
183 char *cmdedit_prompt; /* --- "" - - "" - -"- --""-- --""--- */
185 /* Link into lash to reset context to 0 on ^C and such */
186 extern unsigned int shell_context;
189 #ifdef BB_FEATURE_GETUSERNAME_AND_HOMEDIR
190 static char *user_buf = "";
191 static char *home_pwd_buf = "";
195 #ifndef BB_FEATURE_SH_SIMPLE_PROMPT
196 static char *hostname_buf = "";
197 static int num_ok_lines = 1;
201 #ifdef BB_FEATURE_COMMAND_TAB_COMPLETION
203 #ifndef BB_FEATURE_GETUSERNAME_AND_HOMEDIR
210 #endif /* BB_FEATURE_COMMAND_TAB_COMPLETION */
213 static void cmdedit_setwidth(int w, int redraw_flg);
215 static void win_changed(int nsig)
217 struct winsize win = { 0, 0, 0, 0 };
218 static __sighandler_t previous_SIGWINCH_handler; /* for reset */
220 /* emulate || signal call */
221 if (nsig == -SIGWINCH || nsig == SIGWINCH) {
222 ioctl(0, TIOCGWINSZ, &win);
223 if (win.ws_col > 0) {
224 cmdedit_setwidth(win.ws_col, nsig == SIGWINCH);
227 /* Unix not all standart in recall signal */
229 if (nsig == -SIGWINCH) /* save previous handler */
230 previous_SIGWINCH_handler = signal(SIGWINCH, win_changed);
231 else if (nsig == SIGWINCH) /* signaled called handler */
232 signal(SIGWINCH, win_changed); /* set for next call */
234 /* set previous handler */
235 signal(SIGWINCH, previous_SIGWINCH_handler); /* reset */
238 static void cmdedit_reset_term(void)
240 if ((handlers_sets & SET_RESET_TERM) != 0) {
241 /* sparc and other have broken termios support: use old termio handling. */
242 setTermSettings(fileno(stdin), (void *) &initial_settings);
243 handlers_sets &= ~SET_RESET_TERM;
245 if ((handlers_sets & SET_WCHG_HANDLERS) != 0) {
246 /* reset SIGWINCH handler to previous (default) */
248 handlers_sets &= ~SET_WCHG_HANDLERS;
251 #ifdef BB_FEATURE_CLEAN_UP
255 while (his_front != his_end) {
266 /* special for recount position for scroll and remove terminal margin effect */
267 static void cmdedit_set_out_char(int next_char)
270 int c = (int)((unsigned char) command_ps[cursor]);
273 c = ' '; /* destroy end char? */
274 #ifdef BB_FEATURE_NONPRINTABLE_INVERSE_PUT
275 if (!isprint(c)) { /* Inverse put non-printable characters */
282 printf("\033[7m%c\033[0m", c);
286 if (++cmdedit_x >= cmdedit_termw) {
287 /* terminal is scrolled down */
293 /* destroy "(auto)margin" */
300 /* Move to end line. Bonus: rewrite line from cursor */
301 static void input_end(void)
304 cmdedit_set_out_char(0);
307 /* Go to the next line */
308 static void goto_new_line(void)
316 static inline void out1str(const char *s)
320 static inline void beep(void)
325 /* Move back one charactor */
326 /* special for slow terminal */
327 static void input_backward(int num)
331 cursor -= num; /* new cursor (in command, not terminal) */
333 if (cmdedit_x >= num) { /* no to up line */
340 printf("\033[%dD", num);
345 putchar('\r'); /* back to first terminal pos. */
346 num -= cmdedit_x; /* set previous backward */
348 count_y = 1 + num / cmdedit_termw;
349 printf("\033[%dA", count_y);
350 cmdedit_y -= count_y;
351 /* require forward after uping */
352 cmdedit_x = cmdedit_termw * count_y - num;
353 printf("\033[%dC", cmdedit_x); /* set term cursor */
357 static void put_prompt(void)
359 out1str(cmdedit_prompt);
360 cmdedit_x = cmdedit_prmt_len; /* count real x terminal position */
364 #ifdef BB_FEATURE_SH_SIMPLE_PROMPT
365 static void parse_prompt(const char *prmt_ptr)
367 cmdedit_prompt = prmt_ptr;
368 cmdedit_prmt_len = strlen(prmt_ptr);
372 static void add_to_prompt(char **prmt_mem_ptr, int *alm,
373 int *prmt_len, const char *addb)
375 *prmt_len += strlen(addb);
376 if (*alm < (*prmt_len) + 1) {
377 *alm = (*prmt_len) + 1;
378 *prmt_mem_ptr = xrealloc(*prmt_mem_ptr, *alm);
380 strcat(*prmt_mem_ptr, addb);
383 static void parse_prompt(const char *prmt_ptr)
385 int alm = strlen(prmt_ptr) + 1; /* supposedly require memory */
388 int flg_not_length = '[';
389 char *prmt_mem_ptr = xstrdup(prmt_ptr);
390 char pwd_buf[PATH_MAX + 1];
405 #ifdef BB_FEATURE_GETUSERNAME_AND_HOMEDIR
407 add_to_prompt(&prmt_mem_ptr, &alm, &prmt_len, user_buf);
411 if (hostname_buf[0] == 0) {
412 hostname_buf = xcalloc(256, 1);
413 if (gethostname(hostname_buf, 255) < 0) {
414 strcpy(hostname_buf, "?");
416 char *s = strchr(hostname_buf, '.');
422 add_to_prompt(&prmt_mem_ptr, &alm, &prmt_len,
426 c = my_euid == 0 ? '#' : '$';
428 #ifdef BB_FEATURE_GETUSERNAME_AND_HOMEDIR
430 if (pwd_buf[0] == 0) {
433 getcwd(pwd_buf, PATH_MAX);
434 l = strlen(home_pwd_buf);
435 if (home_pwd_buf[0] != 0 &&
436 strncmp(home_pwd_buf, pwd_buf, l) == 0) {
437 strcpy(pwd_buf + 1, pwd_buf + l);
441 add_to_prompt(&prmt_mem_ptr, &alm, &prmt_len, pwd_buf);
445 snprintf(buf, sizeof(buf), "%d", num_ok_lines);
446 add_to_prompt(&prmt_mem_ptr, &alm, &prmt_len, buf);
449 case 'E': /* \e \E = \033 */
469 for (l = 0; l < 3;) {
471 buf[l++] = *prmt_ptr;
473 ho = strtol(buf, &eho, c == 'x' ? 16 : 8);
474 if (ho > UCHAR_MAX || (eho - buf) < l) {
481 ho = strtol(buf, 0, c == 'x' ? 16 : 8);
482 c = ho == 0 ? '?' : (char) ho;
487 if (c == flg_not_length) {
488 flg_not_length = flg_not_length == '[' ? ']' : '[';
496 add_to_prompt(&prmt_mem_ptr, &alm, &prmt_len, buf);
497 if (flg_not_length == ']')
500 cmdedit_prompt = prmt_mem_ptr;
501 cmdedit_prmt_len = prmt_len - sub_len;
507 /* draw promt, editor line, and clear tail */
508 static void redraw(int y, int back_cursor)
510 if (y > 0) /* up to start y */
511 printf("\033[%dA", y);
512 cmdedit_y = 0; /* new quasireal y */
515 input_end(); /* rewrite */
516 printf("\033[J"); /* destroy tail after cursor */
517 input_backward(back_cursor);
520 /* Delete the char in front of the cursor */
521 static void input_delete(void)
528 strcpy(command_ps + j, command_ps + j + 1);
530 input_end(); /* rewtite new line */
531 cmdedit_set_out_char(0); /* destroy end char */
532 input_backward(cursor - j); /* back to old pos cursor */
535 /* Delete the char in back of the cursor */
536 static void input_backspace(void)
545 /* Move forward one charactor */
546 static void input_forward(void)
549 cmdedit_set_out_char(command_ps[cursor + 1]);
553 static void clean_up_and_die(int sig)
557 exit(EXIT_SUCCESS); /* cmdedit_reset_term() called in atexit */
558 cmdedit_reset_term();
561 static void cmdedit_setwidth(int w, int redraw_flg)
563 cmdedit_termw = cmdedit_prmt_len + 2;
564 if (w <= cmdedit_termw) {
565 cmdedit_termw = cmdedit_termw % w;
567 if (w > cmdedit_termw) {
571 /* new y for current cursor */
572 int new_y = (cursor + cmdedit_prmt_len) / w;
575 redraw((new_y >= cmdedit_y ? new_y : cmdedit_y), len - cursor);
581 extern void cmdedit_init(void)
583 if ((handlers_sets & SET_WCHG_HANDLERS) == 0) {
584 /* emulate usage handler to set handler and call yours work */
585 win_changed(-SIGWINCH);
586 handlers_sets |= SET_WCHG_HANDLERS;
589 if ((handlers_sets & SET_ATEXIT) == 0) {
590 #ifdef BB_FEATURE_GETUSERNAME_AND_HOMEDIR
591 struct passwd *entry;
594 entry = getpwuid(my_euid);
596 user_buf = xstrdup(entry->pw_name);
597 home_pwd_buf = xstrdup(entry->pw_dir);
601 #ifdef BB_FEATURE_COMMAND_TAB_COMPLETION
603 #ifndef BB_FEATURE_GETUSERNAME_AND_HOMEDIR
608 #endif /* BB_FEATURE_COMMAND_TAB_COMPLETION */
609 handlers_sets |= SET_ATEXIT;
610 atexit(cmdedit_reset_term); /* be sure to do this only once */
613 if ((handlers_sets & SET_TERM_HANDLERS) == 0) {
614 signal(SIGKILL, clean_up_and_die);
615 signal(SIGINT, clean_up_and_die);
616 signal(SIGQUIT, clean_up_and_die);
617 signal(SIGTERM, clean_up_and_die);
618 handlers_sets |= SET_TERM_HANDLERS;
623 #ifdef BB_FEATURE_COMMAND_TAB_COMPLETION
625 static int is_execute(const struct stat *st)
627 if ((!my_euid && (st->st_mode & (S_IXUSR | S_IXGRP | S_IXOTH))) ||
628 (my_uid == st->st_uid && (st->st_mode & S_IXUSR)) ||
629 (my_gid == st->st_gid && (st->st_mode & S_IXGRP)) ||
630 (st->st_mode & S_IXOTH)) return TRUE;
634 #ifdef BB_FEATURE_COMMAND_USERNAME_COMPLETION
636 static char **username_tab_completion(char *ud, int *num_matches)
638 struct passwd *entry;
643 ud++; /* ~user/... to user/... */
644 userlen = strlen(ud);
646 if (num_matches == 0) { /* "~/..." or "~user/..." */
647 char *sav_ud = ud - 1;
650 if (*ud == '/') { /* "~/..." */
654 temp = strchr(ud, '/');
655 *temp = 0; /* ~user\0 */
656 entry = getpwnam(ud);
657 *temp = '/'; /* restore ~user/... */
660 home = entry->pw_dir;
663 if ((userlen + strlen(home) + 1) < BUFSIZ) {
664 char temp2[BUFSIZ]; /* argument size */
667 sprintf(temp2, "%s%s", home, ud);
668 strcpy(sav_ud, temp2);
671 return 0; /* void, result save to argument :-) */
674 char **matches = (char **) NULL;
679 while ((entry = getpwent()) != NULL) {
680 /* Null usernames should result in all users as possible completions. */
681 if ( /*!userlen || */ !strncmp(ud, entry->pw_name, userlen)) {
683 temp = xmalloc(3 + strlen(entry->pw_name));
684 sprintf(temp, "~%s/", entry->pw_name);
685 matches = xrealloc(matches, (nm + 1) * sizeof(char *));
687 matches[nm++] = temp;
696 #endif /* BB_FEATURE_COMMAND_USERNAME_COMPLETION */
704 static int path_parse(char ***p, int flags)
710 /* if not setenv PATH variable, to search cur dir "." */
711 if (flags != FIND_EXE_ONLY || (pth = getenv("PATH")) == 0 ||
712 /* PATH=<empty> or PATH=:<empty> */
713 *pth == 0 || (*pth == ':' && *(pth + 1) == 0)) {
721 npth++; /* count words is + 1 count ':' */
722 tmp = strchr(tmp, ':');
725 break; /* :<empty> */
730 *p = xmalloc(npth * sizeof(char *));
733 (*p)[0] = xstrdup(tmp);
734 npth = 1; /* count words is + 1 count ':' */
737 tmp = strchr(tmp, ':');
739 (*p)[0][(tmp - pth)] = 0; /* ':' -> '\0' */
741 break; /* :<empty> */
744 (*p)[npth++] = &(*p)[0][(tmp - pth)]; /* p[next]=p[0][&'\0'+1] */
750 static char *add_quote_for_spec_chars(char *found)
753 char *s = xmalloc((strlen(found) + 1) * 2);
756 if (strchr(" `\"#$%^&*()=+{}[]:;\'|\\<>", *found))
764 static char **exe_n_cwd_tab_completion(char *command, int *num_matches,
772 int nm = *num_matches;
775 char **paths = path1;
778 char found[BUFSIZ + 4 + PATH_MAX];
779 char *pfind = strrchr(command, '/');
784 /* no dir, if flags==EXE_ONLY - get paths, else "." */
785 npaths = path_parse(&paths, type);
789 /* save for change */
790 strcpy(dirbuf, command);
792 dirbuf[(pfind - command) + 1] = 0;
793 #ifdef BB_FEATURE_COMMAND_USERNAME_COMPLETION
794 if (dirbuf[0] == '~') /* ~/... or ~user/... */
795 username_tab_completion(dirbuf, 0);
797 /* "strip" dirname in command */
801 npaths = 1; /* only 1 dir */
804 for (i = 0; i < npaths; i++) {
806 dir = opendir(paths[i]);
807 if (!dir) /* Don't print an error */
810 while ((next = readdir(dir)) != NULL) {
811 const char *str_merge = "%s/%s";
812 char *str_found = next->d_name;
815 if (strncmp(str_found, pfind, strlen(pfind)))
817 /* not see .name without .match */
818 if (*str_found == '.' && *pfind == 0) {
819 if (*paths[i] == '/' && paths[i][1] == 0
820 && str_found[1] == 0) str_found = ""; /* only "/" */
824 if (paths[i][strlen(paths[i]) - 1] == '/')
826 sprintf(found, str_merge, paths[i], str_found);
827 /* hmm, remover in progress? */
828 if (stat(found, &st) < 0)
830 /* find with dirs ? */
831 if (paths[i] != dirbuf)
832 strcpy(found, next->d_name); /* only name */
833 if (S_ISDIR(st.st_mode)) {
834 /* name is directory */
835 /* algorithmic only "/" ? */
838 str_found = add_quote_for_spec_chars(found);
840 /* not put found file if search only dirs for cd */
841 if (type == FIND_DIR_ONLY)
843 str_found = add_quote_for_spec_chars(found);
844 if (type == FIND_FILE_ONLY ||
845 (type == FIND_EXE_ONLY && is_execute(&st) == TRUE))
846 strcat(str_found, " ");
848 /* Add it to the list */
849 matches = xrealloc(matches, (nm + 1) * sizeof(char *));
851 matches[nm++] = str_found;
855 if (paths != path1) {
856 free(paths[0]); /* allocated memory only in first member */
863 static int match_compare(const void *a, const void *b)
865 return strcmp(*(char **) a, *(char **) b);
870 #define QUOT (UCHAR_MAX+1)
872 #define collapse_pos(is, in) { \
873 memcpy(int_buf+is, int_buf+in, (BUFSIZ+1-is-in)*sizeof(int)); \
874 memcpy(pos_buf+is, pos_buf+in, (BUFSIZ+1-is-in)*sizeof(int)); }
876 static int find_match(char *matchBuf, int *len_with_quotes)
881 int int_buf[BUFSIZ + 1];
882 int pos_buf[BUFSIZ + 1];
884 /* set to integer dimension characters and own positions */
886 int_buf[i] = (int) ((unsigned char) matchBuf[i]);
887 if (int_buf[i] == 0) {
888 pos_buf[i] = -1; /* indicator end line */
894 /* mask \+symbol and convert '\t' to ' ' */
895 for (i = j = 0; matchBuf[i]; i++, j++)
896 if (matchBuf[i] == '\\') {
897 collapse_pos(j, j + 1);
900 #ifdef BB_FEATURE_NONPRINTABLE_INVERSE_PUT
901 if (matchBuf[i] == '\t') /* algorithm equivalent */
902 int_buf[j] = ' ' | QUOT;
905 #ifdef BB_FEATURE_NONPRINTABLE_INVERSE_PUT
906 else if (matchBuf[i] == '\t')
910 /* mask "symbols" or 'symbols' */
912 for (i = 0; int_buf[i]; i++) {
914 if (c == '\'' || c == '"') {
923 } else if (c2 != 0 && c != '$')
927 /* skip commands with arguments if line have commands delimiters */
928 /* ';' ';;' '&' '|' '&&' '||' but `>&' `<&' `>|' */
929 for (i = 0; int_buf[i]; i++) {
932 j = i ? int_buf[i - 1] : -1;
934 if (c == ';' || c == '&' || c == '|') {
935 command_mode = 1 + (c == c2);
937 if (j == '>' || j == '<')
939 } else if (c == '|' && j == '>')
943 collapse_pos(0, i + command_mode);
944 i = -1; /* hack incremet */
947 /* collapse `command...` */
948 for (i = 0; int_buf[i]; i++)
949 if (int_buf[i] == '`') {
950 for (j = i + 1; int_buf[j]; j++)
951 if (int_buf[j] == '`') {
952 collapse_pos(i, j + 1);
957 /* not found close ` - command mode, collapse all previous */
958 collapse_pos(0, i + 1);
961 i--; /* hack incremet */
964 /* collapse (command...(command...)...) or {command...{command...}...} */
965 c = 0; /* "recursive" level */
967 for (i = 0; int_buf[i]; i++)
968 if (int_buf[i] == '(' || int_buf[i] == '{') {
969 if (int_buf[i] == '(')
973 collapse_pos(0, i + 1);
974 i = -1; /* hack incremet */
976 for (i = 0; pos_buf[i] >= 0 && (c > 0 || c2 > 0); i++)
977 if ((int_buf[i] == ')' && c > 0) || (int_buf[i] == '}' && c2 > 0)) {
978 if (int_buf[i] == ')')
982 collapse_pos(0, i + 1);
983 i = -1; /* hack incremet */
986 /* skip first not quote space */
987 for (i = 0; int_buf[i]; i++)
988 if (int_buf[i] != ' ')
993 /* set find mode for completion */
994 command_mode = FIND_EXE_ONLY;
995 for (i = 0; int_buf[i]; i++)
996 if (int_buf[i] == ' ' || int_buf[i] == '<' || int_buf[i] == '>') {
997 if (int_buf[i] == ' ' && command_mode == FIND_EXE_ONLY
998 && matchBuf[pos_buf[0]]=='c'
999 && matchBuf[pos_buf[1]]=='d' )
1000 command_mode = FIND_DIR_ONLY;
1002 command_mode = FIND_FILE_ONLY;
1007 for (i = 0; int_buf[i]; i++);
1008 /* find last word */
1009 for (--i; i >= 0; i--) {
1011 if (c == ' ' || c == '<' || c == '>' || c == '|' || c == '&') {
1012 collapse_pos(0, i + 1);
1016 /* skip first not quoted '\'' or '"' */
1017 for (i = 0; int_buf[i] == '\'' || int_buf[i] == '"'; i++);
1018 /* collapse quote or unquote // or /~ */
1019 while ((int_buf[i] & ~QUOT) == '/' &&
1020 ((int_buf[i + 1] & ~QUOT) == '/'
1021 || (int_buf[i + 1] & ~QUOT) == '~')) {
1028 /* set only match and destroy quotes */
1030 for (i = 0; pos_buf[i] >= 0; i++) {
1031 matchBuf[i] = matchBuf[pos_buf[i]];
1035 /* old lenght matchBuf with quotes symbols */
1036 *len_with_quotes = j ? j - pos_buf[0] : 0;
1038 return command_mode;
1042 static void input_tab(int *lastWasTab)
1044 /* Do TAB completion */
1045 static int num_matches;
1046 static char **matches;
1048 if (lastWasTab == 0) { /* free all memory */
1050 while (num_matches > 0)
1051 free(matches[--num_matches]);
1053 matches = (char **) NULL;
1057 if (*lastWasTab == FALSE) {
1061 char matchBuf[BUFSIZ];
1065 *lastWasTab = TRUE; /* flop trigger */
1067 /* Make a local copy of the string -- up
1068 * to the position of the cursor */
1069 tmp = strncpy(matchBuf, command_ps, cursor);
1072 find_type = find_match(matchBuf, &recalc_pos);
1074 /* Free up any memory already allocated */
1077 #ifdef BB_FEATURE_COMMAND_USERNAME_COMPLETION
1078 /* If the word starts with `~' and there is no slash in the word,
1079 * then try completing this word as a username. */
1081 if (matchBuf[0] == '~' && strchr(matchBuf, '/') == 0)
1082 matches = username_tab_completion(matchBuf, &num_matches);
1084 /* Try to match any executable in our path and everything
1085 * in the current working directory that matches. */
1088 exe_n_cwd_tab_completion(matchBuf, &num_matches,
1091 /* Did we find exactly one match? */
1092 if (!matches || num_matches > 1) {
1097 return; /* not found */
1099 qsort(matches, num_matches, sizeof(char *), match_compare);
1101 /* find minimal match */
1102 tmp = xstrdup(matches[0]);
1103 for (tmp1 = tmp; *tmp1; tmp1++)
1104 for (len_found = 1; len_found < num_matches; len_found++)
1105 if (matches[len_found][(tmp1 - tmp)] != *tmp1) {
1109 if (*tmp == 0) { /* have unique */
1113 } else { /* one match */
1115 /* for next completion current found */
1116 *lastWasTab = FALSE;
1119 len_found = strlen(tmp);
1120 /* have space to placed match? */
1121 if ((len_found - strlen(matchBuf) + len) < BUFSIZ) {
1123 /* before word for match */
1124 command_ps[cursor - recalc_pos] = 0;
1125 /* save tail line */
1126 strcpy(matchBuf, command_ps + cursor);
1128 strcat(command_ps, tmp);
1130 strcat(command_ps, matchBuf);
1131 /* back to begin word for match */
1132 input_backward(recalc_pos);
1134 recalc_pos = cursor + len_found;
1136 len = strlen(command_ps);
1137 /* write out the matched command */
1139 input_backward(cursor - recalc_pos);
1141 if (tmp != matches[0])
1144 /* Ok -- the last char was a TAB. Since they
1145 * just hit TAB again, print a list of all the
1146 * available choices... */
1147 if (matches && num_matches > 0) {
1149 int sav_cursor = cursor; /* change goto_new_line() */
1151 /* Go to the next line */
1153 for (i = 0, col = 0; i < num_matches; i++) {
1154 l = strlen(matches[i]);
1157 printf("%-14s ", matches[i]);
1164 col -= (col / cmdedit_termw) * cmdedit_termw;
1165 if (col > 60 && matches[i + 1] != NULL) {
1170 /* Go to the next line and rewrite */
1172 redraw(0, len - sav_cursor);
1176 #endif /* BB_FEATURE_COMMAND_TAB_COMPLETION */
1178 static void get_previous_history(struct history **hp, struct history *p)
1182 (*hp)->s = xstrdup(command_ps);
1186 static inline void get_next_history(struct history **hp)
1188 get_previous_history(hp, (*hp)->n);
1198 * This function is used to grab a character buffer
1199 * from the input file descriptor and allows you to
1200 * a string with full command editing (sortof like
1203 * The following standard commands are not implemented:
1204 * ESC-b -- Move back one word
1205 * ESC-f -- Move forward one word
1206 * ESC-d -- Delete back one word
1207 * ESC-h -- Delete forward one word
1208 * CTL-t -- Transpose two characters
1210 * Furthermore, the "vi" command editing keys are not implemented.
1214 extern void cmdedit_read_input(char *prompt, char command[BUFSIZ])
1217 int inputFd = fileno(stdin);
1220 int lastWasTab = FALSE;
1221 unsigned char c = 0;
1222 struct history *hp = his_end;
1224 /* prepare before init handlers */
1225 cmdedit_y = 0; /* quasireal y, not true work if line > xt*yt */
1227 command_ps = command;
1229 if (new_settings.c_cc[VMIN] == 0) { /* first call */
1231 getTermSettings(inputFd, (void *) &initial_settings);
1232 memcpy(&new_settings, &initial_settings, sizeof(struct termios));
1234 new_settings.c_cc[VMIN] = 1;
1235 new_settings.c_cc[VTIME] = 0;
1236 /* Turn off CTRL-C, so we can trap it */
1237 new_settings.c_cc[VINTR] = _POSIX_VDISABLE;
1238 new_settings.c_lflag &= ~ICANON; /* unbuffered input */
1239 /* Turn off echoing */
1240 new_settings.c_lflag &= ~(ECHO | ECHOCTL | ECHONL);
1245 setTermSettings(inputFd, (void *) &new_settings);
1246 handlers_sets |= SET_RESET_TERM;
1248 /* Now initialize things */
1250 /* Print out the command prompt */
1251 parse_prompt(prompt);
1255 fflush(stdout); /* buffered out to fast */
1257 if (read(inputFd, &c, 1) < 1)
1268 /* Control-a -- Beginning of line */
1269 input_backward(cursor);
1272 /* Control-b -- Move back one character */
1276 /* Control-c -- stop gathering input */
1278 /* Link into lash to reset context to 0 on ^C and such */
1281 /* Go to the next line */
1287 /* Control-d -- Delete one character, or exit
1288 * if the len=0 and no chars to delete */
1291 clean_up_and_die(0);
1297 /* Control-e -- End of line */
1301 /* Control-f -- Move forward one character */
1306 /* Control-h and DEL */
1310 #ifdef BB_FEATURE_COMMAND_TAB_COMPLETION
1311 input_tab(&lastWasTab);
1315 /* Control-n -- Get next command in history */
1316 if (hp && hp->n && hp->n->s) {
1317 get_next_history(&hp);
1324 /* Control-p -- Get previous command from history */
1326 get_previous_history(&hp, hp->p);
1333 /* Control-U -- Clear line before cursor */
1335 strcpy(command, command + cursor);
1336 redraw(cmdedit_y, len -= cursor);
1341 /* escape sequence follows */
1342 if (read(inputFd, &c, 1) < 1)
1344 /* different vt100 emulations */
1345 if (c == '[' || c == 'O') {
1346 if (read(inputFd, &c, 1) < 1)
1350 #ifdef BB_FEATURE_COMMAND_TAB_COMPLETION
1351 case '\t': /* Alt-Tab */
1353 input_tab(&lastWasTab);
1357 /* Up Arrow -- Get previous command from history */
1359 get_previous_history(&hp, hp->p);
1366 /* Down Arrow -- Get next command in history */
1367 if (hp && hp->n && hp->n->s) {
1368 get_next_history(&hp);
1375 /* Rewrite the line with the selected history item */
1377 /* change command */
1378 len = strlen(strcpy(command, hp->s));
1379 /* redraw and go to end line */
1380 redraw(cmdedit_y, 0);
1383 /* Right Arrow -- Move forward one character */
1387 /* Left Arrow -- Move back one character */
1397 input_backward(cursor);
1405 if (!(c >= '1' && c <= '9'))
1409 if (c >= '1' && c <= '9')
1411 if (read(inputFd, &c, 1) < 1)
1417 default: /* If it's regular input, do the normal thing */
1418 #ifdef BB_FEATURE_NONPRINTABLE_INVERSE_PUT
1419 /* Control-V -- Add non-printable symbol */
1421 if (read(inputFd, &c, 1) < 1)
1429 if (!isprint(c)) /* Skip non-printable characters */
1432 if (len >= (BUFSIZ - 2)) /* Need to leave space for enter */
1437 if (cursor == (len - 1)) { /* Append if at the end of the line */
1438 *(command + cursor) = c;
1439 *(command + cursor + 1) = 0;
1440 cmdedit_set_out_char(0);
1441 } else { /* Insert otherwise */
1444 memmove(command + sc + 1, command + sc, len - sc);
1445 *(command + sc) = c;
1447 /* rewrite from cursor */
1449 /* to prev x pos + 1 */
1450 input_backward(cursor - sc);
1455 if (break_out) /* Enter is the command terminator, no more input. */
1462 setTermSettings(inputFd, (void *) &initial_settings);
1463 handlers_sets &= ~SET_RESET_TERM;
1465 /* Handle command history log */
1466 if (len) { /* no put empty line */
1468 struct history *h = his_end;
1471 ss = xstrdup(command); /* duplicate */
1474 /* No previous history -- this memory is never freed */
1475 h = his_front = xmalloc(sizeof(struct history));
1476 h->n = xmalloc(sizeof(struct history));
1486 /* Add a new history command -- this memory is never freed */
1487 h->n = xmalloc(sizeof(struct history));
1495 /* After max history, remove the oldest command */
1496 if (history_counter >= MAX_HISTORY) {
1498 struct history *p = his_front->n;
1508 #if !defined(BB_FEATURE_SH_SIMPLE_PROMPT)
1512 command[len++] = '\n'; /* set '\n' */
1514 #if defined(BB_FEATURE_CLEAN_UP) && defined(BB_FEATURE_COMMAND_TAB_COMPLETION)
1515 input_tab(0); /* strong free */
1517 #if !defined(BB_FEATURE_SH_SIMPLE_PROMPT)
1518 free(cmdedit_prompt);
1524 /* Undo the effects of cmdedit_init(). */
1525 extern void cmdedit_terminate(void)
1527 cmdedit_reset_term();
1528 if ((handlers_sets & SET_TERM_HANDLERS) != 0) {
1529 signal(SIGKILL, SIG_DFL);
1530 signal(SIGINT, SIG_DFL);
1531 signal(SIGQUIT, SIG_DFL);
1532 signal(SIGTERM, SIG_DFL);
1533 signal(SIGWINCH, SIG_DFL);
1534 handlers_sets &= ~SET_TERM_HANDLERS;
1538 #endif /* BB_FEATURE_COMMAND_EDITING */
1543 #ifdef BB_FEATURE_NONPRINTABLE_INVERSE_PUT
1547 unsigned int shell_context;
1549 int main(int argc, char **argv)
1553 #if !defined(BB_FEATURE_SH_SIMPLE_PROMPT)
1554 "\\[\\033[32;1m\\]\\u@\\[\\x1b[33;1m\\]\\h:\
1555 \\[\\033[34;1m\\]\\w\\[\\033[35;1m\\] \
1556 \\!\\[\\e[36;1m\\]\\$ \\[\\E[0m\\]";
1561 #ifdef BB_FEATURE_NONPRINTABLE_INVERSE_PUT
1562 setlocale(LC_ALL, "");
1567 cmdedit_read_input(prompt, buff);
1569 if(l > 0 && buff[l-1] == '\n')
1571 printf("*** cmdedit_read_input() returned line =%s=\n", buff);
1572 } while (shell_context);
1573 printf("*** cmdedit_read_input() detect ^C\n");