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
39 #include <sys/ioctl.h>
46 #ifdef BB_LOCALE_SUPPORT
47 #define Isprint(c) isprint((c))
49 #define Isprint(c) ( (c) >= ' ' && (c) != ((unsigned char)'\233') )
58 #define BB_FEATURE_COMMAND_EDITING
59 #define BB_FEATURE_COMMAND_TAB_COMPLETION
60 #define BB_FEATURE_COMMAND_USERNAME_COMPLETION
61 #define BB_FEATURE_NONPRINTABLE_INVERSE_PUT
62 #define BB_FEATURE_CLEAN_UP
68 #ifdef BB_FEATURE_COMMAND_TAB_COMPLETION
73 #ifdef BB_FEATURE_COMMAND_EDITING
75 #ifndef BB_FEATURE_COMMAND_TAB_COMPLETION
76 #undef BB_FEATURE_COMMAND_USERNAME_COMPLETION
79 #if defined(BB_FEATURE_COMMAND_USERNAME_COMPLETION) || defined(BB_FEATURE_SH_FANCY_PROMPT)
80 #define BB_FEATURE_GETUSERNAME_AND_HOMEDIR
83 #ifdef BB_FEATURE_GETUSERNAME_AND_HOMEDIR
85 # include "pwd_grp/pwd.h"
89 #endif /* advanced FEATURES */
99 /* Maximum length of the linked list for the command line history */
100 static const int MAX_HISTORY = 15;
102 /* First element in command line list */
103 static struct history *his_front = NULL;
105 /* Last element in command line list */
106 static struct history *his_end = NULL;
110 #define setTermSettings(fd,argp) tcsetattr(fd,TCSANOW,argp)
111 #define getTermSettings(fd,argp) tcgetattr(fd, argp);
113 /* Current termio and the previous termio before starting sh */
114 static struct termios initial_settings, new_settings;
118 volatile int cmdedit_termw = 80; /* actual terminal width */
119 static int history_counter = 0; /* Number of commands in history list */
121 volatile int handlers_sets = 0; /* Set next bites: */
124 SET_ATEXIT = 1, /* when atexit() has been called
125 and get euid,uid,gid to fast compare */
126 SET_TERM_HANDLERS = 2, /* set many terminates signal handlers */
127 SET_WCHG_HANDLERS = 4, /* winchg signal handler */
128 SET_RESET_TERM = 8, /* if the terminal needs to be reset upon exit */
132 static int cmdedit_x; /* real x terminal position */
133 static int cmdedit_y; /* pseudoreal y terminal position */
134 static int cmdedit_prmt_len; /* lenght prompt without colores string */
136 static int cursor; /* required global for signal handler */
137 static int len; /* --- "" - - "" - -"- --""-- --""--- */
138 static char *command_ps; /* --- "" - - "" - -"- --""-- --""--- */
140 #ifndef BB_FEATURE_SH_FANCY_PROMPT
143 char *cmdedit_prompt; /* --- "" - - "" - -"- --""-- --""--- */
145 /* Link into lash to reset context to 0 on ^C and such */
146 extern unsigned int shell_context;
149 #ifdef BB_FEATURE_GETUSERNAME_AND_HOMEDIR
150 static char *user_buf = "";
151 static char *home_pwd_buf = "";
155 #ifdef BB_FEATURE_SH_FANCY_PROMPT
156 static char *hostname_buf = "";
157 static int num_ok_lines = 1;
161 #ifdef BB_FEATURE_COMMAND_TAB_COMPLETION
163 #ifndef BB_FEATURE_GETUSERNAME_AND_HOMEDIR
170 #endif /* BB_FEATURE_COMMAND_TAB_COMPLETION */
173 static void cmdedit_setwidth(int w, int redraw_flg);
175 static void win_changed(int nsig)
177 struct winsize win = { 0, 0, 0, 0 };
178 static __sighandler_t previous_SIGWINCH_handler; /* for reset */
180 /* emulate || signal call */
181 if (nsig == -SIGWINCH || nsig == SIGWINCH) {
182 ioctl(0, TIOCGWINSZ, &win);
183 if (win.ws_col > 0) {
184 cmdedit_setwidth(win.ws_col, nsig == SIGWINCH);
187 /* Unix not all standart in recall signal */
189 if (nsig == -SIGWINCH) /* save previous handler */
190 previous_SIGWINCH_handler = signal(SIGWINCH, win_changed);
191 else if (nsig == SIGWINCH) /* signaled called handler */
192 signal(SIGWINCH, win_changed); /* set for next call */
194 /* set previous handler */
195 signal(SIGWINCH, previous_SIGWINCH_handler); /* reset */
198 static void cmdedit_reset_term(void)
200 if ((handlers_sets & SET_RESET_TERM) != 0) {
201 /* sparc and other have broken termios support: use old termio handling. */
202 setTermSettings(fileno(stdin), (void *) &initial_settings);
203 handlers_sets &= ~SET_RESET_TERM;
205 if ((handlers_sets & SET_WCHG_HANDLERS) != 0) {
206 /* reset SIGWINCH handler to previous (default) */
208 handlers_sets &= ~SET_WCHG_HANDLERS;
211 #ifdef BB_FEATURE_CLEAN_UP
215 while (his_front != his_end) {
226 /* special for recount position for scroll and remove terminal margin effect */
227 static void cmdedit_set_out_char(int next_char)
230 int c = (int)((unsigned char) command_ps[cursor]);
233 c = ' '; /* destroy end char? */
234 #ifdef BB_FEATURE_NONPRINTABLE_INVERSE_PUT
235 if (!Isprint(c)) { /* Inverse put non-printable characters */
242 printf("\033[7m%c\033[0m", c);
246 if (++cmdedit_x >= cmdedit_termw) {
247 /* terminal is scrolled down */
253 /* destroy "(auto)margin" */
260 /* Move to end line. Bonus: rewrite line from cursor */
261 static void input_end(void)
264 cmdedit_set_out_char(0);
267 /* Go to the next line */
268 static void goto_new_line(void)
276 static inline void out1str(const char *s)
280 static inline void beep(void)
285 /* Move back one charactor */
286 /* special for slow terminal */
287 static void input_backward(int num)
291 cursor -= num; /* new cursor (in command, not terminal) */
293 if (cmdedit_x >= num) { /* no to up line */
300 printf("\033[%dD", num);
305 putchar('\r'); /* back to first terminal pos. */
306 num -= cmdedit_x; /* set previous backward */
308 count_y = 1 + num / cmdedit_termw;
309 printf("\033[%dA", count_y);
310 cmdedit_y -= count_y;
311 /* require forward after uping */
312 cmdedit_x = cmdedit_termw * count_y - num;
313 printf("\033[%dC", cmdedit_x); /* set term cursor */
317 static void put_prompt(void)
319 out1str(cmdedit_prompt);
320 cmdedit_x = cmdedit_prmt_len; /* count real x terminal position */
324 #ifndef BB_FEATURE_SH_FANCY_PROMPT
325 static void parse_prompt(const char *prmt_ptr)
327 cmdedit_prompt = prmt_ptr;
328 cmdedit_prmt_len = strlen(prmt_ptr);
332 static void parse_prompt(const char *prmt_ptr)
336 char flg_not_length = '[';
337 char *prmt_mem_ptr = xcalloc(1, 1);
338 char *pwd_buf = xgetcwd(0);
339 char buf2[PATH_MAX + 1];
345 pwd_buf=(char *)unknown;
353 const char *cp = prmt_ptr;
356 c = process_escape_sequence(&prmt_ptr);
362 #ifdef BB_FEATURE_GETUSERNAME_AND_HOMEDIR
370 pbuf = xcalloc(256, 1);
371 if (gethostname(pbuf, 255) < 0) {
374 char *s = strchr(pbuf, '.');
383 c = my_euid == 0 ? '#' : '$';
385 #ifdef BB_FEATURE_GETUSERNAME_AND_HOMEDIR
388 l = strlen(home_pwd_buf);
389 if (home_pwd_buf[0] != 0 &&
390 strncmp(home_pwd_buf, pbuf, l) == 0 &&
391 (pbuf[l]=='/' || pbuf[l]=='\0') &&
392 strlen(pwd_buf+l)<PATH_MAX) {
395 strcpy(pbuf+1, pwd_buf+l);
401 cp = strrchr(pbuf,'/');
402 if ( (cp != NULL) && (cp != pbuf) )
406 snprintf(pbuf = buf2, sizeof(buf2), "%d", num_ok_lines);
408 case 'e': case 'E': /* \e \E = \033 */
412 for (l = 0; l < 3;) {
414 buf2[l++] = *prmt_ptr;
416 h = strtol(buf2, &pbuf, 16);
417 if (h > UCHAR_MAX || (pbuf - buf2) < l) {
424 c = (char)strtol(buf2, 0, 16);
430 if (c == flg_not_length) {
431 flg_not_length = flg_not_length == '[' ? ']' : '[';
440 prmt_len += strlen(pbuf);
441 prmt_mem_ptr = strcat(xrealloc(prmt_mem_ptr, prmt_len+1), pbuf);
442 if (flg_not_length == ']')
446 cmdedit_prompt = prmt_mem_ptr;
447 cmdedit_prmt_len = prmt_len - sub_len;
453 /* draw promt, editor line, and clear tail */
454 static void redraw(int y, int back_cursor)
456 if (y > 0) /* up to start y */
457 printf("\033[%dA", y);
458 cmdedit_y = 0; /* new quasireal y */
461 input_end(); /* rewrite */
462 printf("\033[J"); /* destroy tail after cursor */
463 input_backward(back_cursor);
466 /* Delete the char in front of the cursor */
467 static void input_delete(void)
474 strcpy(command_ps + j, command_ps + j + 1);
476 input_end(); /* rewtite new line */
477 cmdedit_set_out_char(0); /* destroy end char */
478 input_backward(cursor - j); /* back to old pos cursor */
481 /* Delete the char in back of the cursor */
482 static void input_backspace(void)
491 /* Move forward one charactor */
492 static void input_forward(void)
495 cmdedit_set_out_char(command_ps[cursor + 1]);
499 static void clean_up_and_die(int sig)
503 exit(EXIT_SUCCESS); /* cmdedit_reset_term() called in atexit */
504 cmdedit_reset_term();
507 static void cmdedit_setwidth(int w, int redraw_flg)
509 cmdedit_termw = cmdedit_prmt_len + 2;
510 if (w <= cmdedit_termw) {
511 cmdedit_termw = cmdedit_termw % w;
513 if (w > cmdedit_termw) {
517 /* new y for current cursor */
518 int new_y = (cursor + cmdedit_prmt_len) / w;
521 redraw((new_y >= cmdedit_y ? new_y : cmdedit_y), len - cursor);
527 extern void cmdedit_init(void)
529 cmdedit_prmt_len = 0;
530 if ((handlers_sets & SET_WCHG_HANDLERS) == 0) {
531 /* emulate usage handler to set handler and call yours work */
532 win_changed(-SIGWINCH);
533 handlers_sets |= SET_WCHG_HANDLERS;
536 if ((handlers_sets & SET_ATEXIT) == 0) {
537 #ifdef BB_FEATURE_GETUSERNAME_AND_HOMEDIR
538 struct passwd *entry;
541 entry = getpwuid(my_euid);
543 user_buf = xstrdup(entry->pw_name);
544 home_pwd_buf = xstrdup(entry->pw_dir);
548 #ifdef BB_FEATURE_COMMAND_TAB_COMPLETION
550 #ifndef BB_FEATURE_GETUSERNAME_AND_HOMEDIR
555 #endif /* BB_FEATURE_COMMAND_TAB_COMPLETION */
556 handlers_sets |= SET_ATEXIT;
557 atexit(cmdedit_reset_term); /* be sure to do this only once */
560 if ((handlers_sets & SET_TERM_HANDLERS) == 0) {
561 signal(SIGKILL, clean_up_and_die);
562 signal(SIGINT, clean_up_and_die);
563 signal(SIGQUIT, clean_up_and_die);
564 signal(SIGTERM, clean_up_and_die);
565 handlers_sets |= SET_TERM_HANDLERS;
569 #ifdef BB_FEATURE_COMMAND_TAB_COMPLETION
571 static int is_execute(const struct stat *st)
573 if ((!my_euid && (st->st_mode & (S_IXUSR | S_IXGRP | S_IXOTH))) ||
574 (my_uid == st->st_uid && (st->st_mode & S_IXUSR)) ||
575 (my_gid == st->st_gid && (st->st_mode & S_IXGRP)) ||
576 (st->st_mode & S_IXOTH)) return TRUE;
580 #ifdef BB_FEATURE_COMMAND_USERNAME_COMPLETION
582 static char **username_tab_completion(char *ud, int *num_matches)
584 struct passwd *entry;
589 ud++; /* ~user/... to user/... */
590 userlen = strlen(ud);
592 if (num_matches == 0) { /* "~/..." or "~user/..." */
593 char *sav_ud = ud - 1;
596 if (*ud == '/') { /* "~/..." */
600 temp = strchr(ud, '/');
601 *temp = 0; /* ~user\0 */
602 entry = getpwnam(ud);
603 *temp = '/'; /* restore ~user/... */
606 home = entry->pw_dir;
609 if ((userlen + strlen(home) + 1) < BUFSIZ) {
610 char temp2[BUFSIZ]; /* argument size */
613 sprintf(temp2, "%s%s", home, ud);
614 strcpy(sav_ud, temp2);
617 return 0; /* void, result save to argument :-) */
620 char **matches = (char **) NULL;
625 while ((entry = getpwent()) != NULL) {
626 /* Null usernames should result in all users as possible completions. */
627 if ( /*!userlen || */ !strncmp(ud, entry->pw_name, userlen)) {
629 temp = xmalloc(3 + strlen(entry->pw_name));
630 sprintf(temp, "~%s/", entry->pw_name);
631 matches = xrealloc(matches, (nm + 1) * sizeof(char *));
633 matches[nm++] = temp;
642 #endif /* BB_FEATURE_COMMAND_USERNAME_COMPLETION */
650 static int path_parse(char ***p, int flags)
656 /* if not setenv PATH variable, to search cur dir "." */
657 if (flags != FIND_EXE_ONLY || (pth = getenv("PATH")) == 0 ||
658 /* PATH=<empty> or PATH=:<empty> */
659 *pth == 0 || (*pth == ':' && *(pth + 1) == 0)) {
667 npth++; /* count words is + 1 count ':' */
668 tmp = strchr(tmp, ':');
671 break; /* :<empty> */
676 *p = xmalloc(npth * sizeof(char *));
679 (*p)[0] = xstrdup(tmp);
680 npth = 1; /* count words is + 1 count ':' */
683 tmp = strchr(tmp, ':');
685 (*p)[0][(tmp - pth)] = 0; /* ':' -> '\0' */
687 break; /* :<empty> */
690 (*p)[npth++] = &(*p)[0][(tmp - pth)]; /* p[next]=p[0][&'\0'+1] */
696 static char *add_quote_for_spec_chars(char *found)
699 char *s = xmalloc((strlen(found) + 1) * 2);
702 if (strchr(" `\"#$%^&*()=+{}[]:;\'|\\<>", *found))
710 static char **exe_n_cwd_tab_completion(char *command, int *num_matches,
718 int nm = *num_matches;
721 char **paths = path1;
725 char *pfind = strrchr(command, '/');
730 /* no dir, if flags==EXE_ONLY - get paths, else "." */
731 npaths = path_parse(&paths, type);
735 /* save for change */
736 strcpy(dirbuf, command);
738 dirbuf[(pfind - command) + 1] = 0;
739 #ifdef BB_FEATURE_COMMAND_USERNAME_COMPLETION
740 if (dirbuf[0] == '~') /* ~/... or ~user/... */
741 username_tab_completion(dirbuf, 0);
743 /* "strip" dirname in command */
747 npaths = 1; /* only 1 dir */
750 for (i = 0; i < npaths; i++) {
752 dir = opendir(paths[i]);
753 if (!dir) /* Don't print an error */
756 while ((next = readdir(dir)) != NULL) {
757 char *str_found = next->d_name;
760 if (strncmp(str_found, pfind, strlen(pfind)))
762 /* not see .name without .match */
763 if (*str_found == '.' && *pfind == 0) {
764 if (*paths[i] == '/' && paths[i][1] == 0
765 && str_found[1] == 0) str_found = ""; /* only "/" */
769 found = concat_path_file(paths[i], str_found);
770 /* hmm, remover in progress? */
771 if (stat(found, &st) < 0)
773 /* find with dirs ? */
774 if (paths[i] != dirbuf)
775 strcpy(found, next->d_name); /* only name */
776 if (S_ISDIR(st.st_mode)) {
777 /* name is directory */
779 found = concat_path_file(found, "");
781 str_found = add_quote_for_spec_chars(found);
783 /* not put found file if search only dirs for cd */
784 if (type == FIND_DIR_ONLY)
786 str_found = add_quote_for_spec_chars(found);
787 if (type == FIND_FILE_ONLY ||
788 (type == FIND_EXE_ONLY && is_execute(&st) == TRUE))
789 strcat(str_found, " ");
791 /* Add it to the list */
792 matches = xrealloc(matches, (nm + 1) * sizeof(char *));
794 matches[nm++] = str_found;
800 if (paths != path1) {
801 free(paths[0]); /* allocated memory only in first member */
808 static int match_compare(const void *a, const void *b)
810 return strcmp(*(char **) a, *(char **) b);
815 #define QUOT (UCHAR_MAX+1)
817 #define collapse_pos(is, in) { \
818 memcpy(int_buf+is, int_buf+in, (BUFSIZ+1-is-in)*sizeof(int)); \
819 memcpy(pos_buf+is, pos_buf+in, (BUFSIZ+1-is-in)*sizeof(int)); }
821 static int find_match(char *matchBuf, int *len_with_quotes)
826 int int_buf[BUFSIZ + 1];
827 int pos_buf[BUFSIZ + 1];
829 /* set to integer dimension characters and own positions */
831 int_buf[i] = (int) ((unsigned char) matchBuf[i]);
832 if (int_buf[i] == 0) {
833 pos_buf[i] = -1; /* indicator end line */
839 /* mask \+symbol and convert '\t' to ' ' */
840 for (i = j = 0; matchBuf[i]; i++, j++)
841 if (matchBuf[i] == '\\') {
842 collapse_pos(j, j + 1);
845 #ifdef BB_FEATURE_NONPRINTABLE_INVERSE_PUT
846 if (matchBuf[i] == '\t') /* algorithm equivalent */
847 int_buf[j] = ' ' | QUOT;
850 #ifdef BB_FEATURE_NONPRINTABLE_INVERSE_PUT
851 else if (matchBuf[i] == '\t')
855 /* mask "symbols" or 'symbols' */
857 for (i = 0; int_buf[i]; i++) {
859 if (c == '\'' || c == '"') {
868 } else if (c2 != 0 && c != '$')
872 /* skip commands with arguments if line have commands delimiters */
873 /* ';' ';;' '&' '|' '&&' '||' but `>&' `<&' `>|' */
874 for (i = 0; int_buf[i]; i++) {
877 j = i ? int_buf[i - 1] : -1;
879 if (c == ';' || c == '&' || c == '|') {
880 command_mode = 1 + (c == c2);
882 if (j == '>' || j == '<')
884 } else if (c == '|' && j == '>')
888 collapse_pos(0, i + command_mode);
889 i = -1; /* hack incremet */
892 /* collapse `command...` */
893 for (i = 0; int_buf[i]; i++)
894 if (int_buf[i] == '`') {
895 for (j = i + 1; int_buf[j]; j++)
896 if (int_buf[j] == '`') {
897 collapse_pos(i, j + 1);
902 /* not found close ` - command mode, collapse all previous */
903 collapse_pos(0, i + 1);
906 i--; /* hack incremet */
909 /* collapse (command...(command...)...) or {command...{command...}...} */
910 c = 0; /* "recursive" level */
912 for (i = 0; int_buf[i]; i++)
913 if (int_buf[i] == '(' || int_buf[i] == '{') {
914 if (int_buf[i] == '(')
918 collapse_pos(0, i + 1);
919 i = -1; /* hack incremet */
921 for (i = 0; pos_buf[i] >= 0 && (c > 0 || c2 > 0); i++)
922 if ((int_buf[i] == ')' && c > 0) || (int_buf[i] == '}' && c2 > 0)) {
923 if (int_buf[i] == ')')
927 collapse_pos(0, i + 1);
928 i = -1; /* hack incremet */
931 /* skip first not quote space */
932 for (i = 0; int_buf[i]; i++)
933 if (int_buf[i] != ' ')
938 /* set find mode for completion */
939 command_mode = FIND_EXE_ONLY;
940 for (i = 0; int_buf[i]; i++)
941 if (int_buf[i] == ' ' || int_buf[i] == '<' || int_buf[i] == '>') {
942 if (int_buf[i] == ' ' && command_mode == FIND_EXE_ONLY
943 && matchBuf[pos_buf[0]]=='c'
944 && matchBuf[pos_buf[1]]=='d' )
945 command_mode = FIND_DIR_ONLY;
947 command_mode = FIND_FILE_ONLY;
952 for (i = 0; int_buf[i]; i++);
954 for (--i; i >= 0; i--) {
956 if (c == ' ' || c == '<' || c == '>' || c == '|' || c == '&') {
957 collapse_pos(0, i + 1);
961 /* skip first not quoted '\'' or '"' */
962 for (i = 0; int_buf[i] == '\'' || int_buf[i] == '"'; i++);
963 /* collapse quote or unquote // or /~ */
964 while ((int_buf[i] & ~QUOT) == '/' &&
965 ((int_buf[i + 1] & ~QUOT) == '/'
966 || (int_buf[i + 1] & ~QUOT) == '~')) {
970 /* set only match and destroy quotes */
972 for (c = 0; pos_buf[i] >= 0; i++) {
973 matchBuf[c++] = matchBuf[pos_buf[i]];
977 /* old lenght matchBuf with quotes symbols */
978 *len_with_quotes = j ? j - pos_buf[0] : 0;
984 static void input_tab(int *lastWasTab)
986 /* Do TAB completion */
987 static int num_matches;
988 static char **matches;
990 if (lastWasTab == 0) { /* free all memory */
992 while (num_matches > 0)
993 free(matches[--num_matches]);
995 matches = (char **) NULL;
999 if (*lastWasTab == FALSE) {
1003 char matchBuf[BUFSIZ];
1007 *lastWasTab = TRUE; /* flop trigger */
1009 /* Make a local copy of the string -- up
1010 * to the position of the cursor */
1011 tmp = strncpy(matchBuf, command_ps, cursor);
1014 find_type = find_match(matchBuf, &recalc_pos);
1016 /* Free up any memory already allocated */
1019 #ifdef BB_FEATURE_COMMAND_USERNAME_COMPLETION
1020 /* If the word starts with `~' and there is no slash in the word,
1021 * then try completing this word as a username. */
1023 if (matchBuf[0] == '~' && strchr(matchBuf, '/') == 0)
1024 matches = username_tab_completion(matchBuf, &num_matches);
1026 /* Try to match any executable in our path and everything
1027 * in the current working directory that matches. */
1030 exe_n_cwd_tab_completion(matchBuf,
1031 &num_matches, find_type);
1032 /* Remove duplicate found */
1036 for(i=0; i<(num_matches-1); i++)
1037 for(j=i+1; j<num_matches; j++)
1038 if(matches[i]!=0 && matches[j]!=0 &&
1039 strcmp(matches[i], matches[j])==0) {
1047 if(!strcmp(matches[i], "./"))
1049 else if(!strcmp(matches[i], "../"))
1051 matches[num_matches++]=matches[i];
1054 /* Did we find exactly one match? */
1055 if (!matches || num_matches > 1) {
1060 return; /* not found */
1062 qsort(matches, num_matches, sizeof(char *), match_compare);
1064 /* find minimal match */
1065 tmp = xstrdup(matches[0]);
1066 for (tmp1 = tmp; *tmp1; tmp1++)
1067 for (len_found = 1; len_found < num_matches; len_found++)
1068 if (matches[len_found][(tmp1 - tmp)] != *tmp1) {
1072 if (*tmp == 0) { /* have unique */
1076 } else { /* one match */
1078 /* for next completion current found */
1079 *lastWasTab = FALSE;
1082 len_found = strlen(tmp);
1083 /* have space to placed match? */
1084 if ((len_found - strlen(matchBuf) + len) < BUFSIZ) {
1086 /* before word for match */
1087 command_ps[cursor - recalc_pos] = 0;
1088 /* save tail line */
1089 strcpy(matchBuf, command_ps + cursor);
1091 strcat(command_ps, tmp);
1093 strcat(command_ps, matchBuf);
1094 /* back to begin word for match */
1095 input_backward(recalc_pos);
1097 recalc_pos = cursor + len_found;
1099 len = strlen(command_ps);
1100 /* write out the matched command */
1101 redraw(cmdedit_y, len - recalc_pos);
1103 if (tmp != matches[0])
1106 /* Ok -- the last char was a TAB. Since they
1107 * just hit TAB again, print a list of all the
1108 * available choices... */
1109 if (matches && num_matches > 0) {
1111 int sav_cursor = cursor; /* change goto_new_line() */
1113 /* Go to the next line */
1115 for (i = 0, col = 0; i < num_matches; i++) {
1116 l = strlen(matches[i]);
1119 printf("%-14s ", matches[i]);
1126 col -= (col / cmdedit_termw) * cmdedit_termw;
1127 if (col > 60 && matches[i + 1] != NULL) {
1132 /* Go to the next line and rewrite */
1134 redraw(0, len - sav_cursor);
1138 #endif /* BB_FEATURE_COMMAND_TAB_COMPLETION */
1140 static void get_previous_history(struct history **hp, struct history *p)
1144 (*hp)->s = xstrdup(command_ps);
1148 static inline void get_next_history(struct history **hp)
1150 get_previous_history(hp, (*hp)->n);
1160 * This function is used to grab a character buffer
1161 * from the input file descriptor and allows you to
1162 * a string with full command editing (sortof like
1165 * The following standard commands are not implemented:
1166 * ESC-b -- Move back one word
1167 * ESC-f -- Move forward one word
1168 * ESC-d -- Delete back one word
1169 * ESC-h -- Delete forward one word
1170 * CTL-t -- Transpose two characters
1172 * Furthermore, the "vi" command editing keys are not implemented.
1176 extern void cmdedit_read_input(char *prompt, char command[BUFSIZ])
1180 int lastWasTab = FALSE;
1181 unsigned char c = 0;
1182 struct history *hp = his_end;
1184 /* prepare before init handlers */
1185 cmdedit_y = 0; /* quasireal y, not true work if line > xt*yt */
1187 command_ps = command;
1189 if (new_settings.c_cc[VERASE] == 0) { /* first call */
1191 getTermSettings(0, (void *) &initial_settings);
1192 memcpy(&new_settings, &initial_settings, sizeof(struct termios));
1193 new_settings.c_lflag &= ~ICANON; /* unbuffered input */
1194 /* Turn off echoing and CTRL-C, so we can trap it */
1195 new_settings.c_lflag &= ~(ECHO | ECHONL | ISIG);
1197 /* Hmm, in linux c_cc[] not parsed if set ~ICANON */
1198 new_settings.c_cc[VMIN] = 1;
1199 new_settings.c_cc[VTIME] = 0;
1200 /* Turn off CTRL-C, so we can trap it */
1201 # ifndef _POSIX_VDISABLE
1202 # define _POSIX_VDISABLE '\0'
1204 new_settings.c_cc[VINTR] = _POSIX_VDISABLE;
1210 setTermSettings(0, (void *) &new_settings);
1211 handlers_sets |= SET_RESET_TERM;
1213 /* Now initialize things */
1215 /* Print out the command prompt */
1216 parse_prompt(prompt);
1220 fflush(stdout); /* buffered out to fast */
1222 if (read(0, &c, 1) < 1)
1223 /* if we can't read input then exit */
1224 goto prepare_to_die;
1234 /* Control-a -- Beginning of line */
1235 input_backward(cursor);
1238 /* Control-b -- Move back one character */
1242 /* Control-c -- stop gathering input */
1244 /* Link into lash to reset context to 0 on ^C and such */
1247 /* Go to the next line */
1253 /* Control-d -- Delete one character, or exit
1254 * if the len=0 and no chars to delete */
1258 clean_up_and_die(0);
1264 /* Control-e -- End of line */
1268 /* Control-f -- Move forward one character */
1273 /* Control-h and DEL */
1277 #ifdef BB_FEATURE_COMMAND_TAB_COMPLETION
1278 input_tab(&lastWasTab);
1282 /* Control-n -- Get next command in history */
1283 if (hp && hp->n && hp->n->s) {
1284 get_next_history(&hp);
1291 /* Control-p -- Get previous command from history */
1293 get_previous_history(&hp, hp->p);
1300 /* Control-U -- Clear line before cursor */
1302 strcpy(command, command + cursor);
1303 redraw(cmdedit_y, len -= cursor);
1308 /* escape sequence follows */
1309 if (read(0, &c, 1) < 1)
1311 /* different vt100 emulations */
1312 if (c == '[' || c == 'O') {
1313 if (read(0, &c, 1) < 1)
1317 #ifdef BB_FEATURE_COMMAND_TAB_COMPLETION
1318 case '\t': /* Alt-Tab */
1320 input_tab(&lastWasTab);
1324 /* Up Arrow -- Get previous command from history */
1326 get_previous_history(&hp, hp->p);
1333 /* Down Arrow -- Get next command in history */
1334 if (hp && hp->n && hp->n->s) {
1335 get_next_history(&hp);
1342 /* Rewrite the line with the selected history item */
1344 /* change command */
1345 len = strlen(strcpy(command, hp->s));
1346 /* redraw and go to end line */
1347 redraw(cmdedit_y, 0);
1350 /* Right Arrow -- Move forward one character */
1354 /* Left Arrow -- Move back one character */
1364 input_backward(cursor);
1372 if (!(c >= '1' && c <= '9'))
1376 if (c >= '1' && c <= '9')
1378 if (read(0, &c, 1) < 1)
1384 default: /* If it's regular input, do the normal thing */
1385 #ifdef BB_FEATURE_NONPRINTABLE_INVERSE_PUT
1386 /* Control-V -- Add non-printable symbol */
1388 if (read(0, &c, 1) < 1)
1396 if (!Isprint(c)) /* Skip non-printable characters */
1399 if (len >= (BUFSIZ - 2)) /* Need to leave space for enter */
1404 if (cursor == (len - 1)) { /* Append if at the end of the line */
1405 *(command + cursor) = c;
1406 *(command + cursor + 1) = 0;
1407 cmdedit_set_out_char(0);
1408 } else { /* Insert otherwise */
1411 memmove(command + sc + 1, command + sc, len - sc);
1412 *(command + sc) = c;
1414 /* rewrite from cursor */
1416 /* to prev x pos + 1 */
1417 input_backward(cursor - sc);
1422 if (break_out) /* Enter is the command terminator, no more input. */
1429 setTermSettings(0, (void *) &initial_settings);
1430 handlers_sets &= ~SET_RESET_TERM;
1432 /* Handle command history log */
1433 if (len) { /* no put empty line */
1435 struct history *h = his_end;
1438 ss = xstrdup(command); /* duplicate */
1441 /* No previous history -- this memory is never freed */
1442 h = his_front = xmalloc(sizeof(struct history));
1443 h->n = xmalloc(sizeof(struct history));
1453 /* Add a new history command -- this memory is never freed */
1454 h->n = xmalloc(sizeof(struct history));
1462 /* After max history, remove the oldest command */
1463 if (history_counter >= MAX_HISTORY) {
1465 struct history *p = his_front->n;
1475 #if defined(BB_FEATURE_SH_FANCY_PROMPT)
1479 command[len++] = '\n'; /* set '\n' */
1481 #if defined(BB_FEATURE_CLEAN_UP) && defined(BB_FEATURE_COMMAND_TAB_COMPLETION)
1482 input_tab(0); /* strong free */
1484 #if defined(BB_FEATURE_SH_FANCY_PROMPT)
1485 free(cmdedit_prompt);
1491 /* Undo the effects of cmdedit_init(). */
1492 extern void cmdedit_terminate(void)
1494 cmdedit_reset_term();
1495 if ((handlers_sets & SET_TERM_HANDLERS) != 0) {
1496 signal(SIGKILL, SIG_DFL);
1497 signal(SIGINT, SIG_DFL);
1498 signal(SIGQUIT, SIG_DFL);
1499 signal(SIGTERM, SIG_DFL);
1500 signal(SIGWINCH, SIG_DFL);
1501 handlers_sets &= ~SET_TERM_HANDLERS;
1505 #endif /* BB_FEATURE_COMMAND_EDITING */
1510 const char *applet_name = "debug stuff usage";
1511 const char *memory_exhausted = "Memory exhausted";
1513 #ifdef BB_FEATURE_NONPRINTABLE_INVERSE_PUT
1517 unsigned int shell_context;
1519 int main(int argc, char **argv)
1523 #if defined(BB_FEATURE_SH_FANCY_PROMPT)
1524 "\\[\\033[32;1m\\]\\u@\\[\\x1b[33;1m\\]\\h:\
1525 \\[\\033[34;1m\\]\\w\\[\\033[35;1m\\] \
1526 \\!\\[\\e[36;1m\\]\\$ \\[\\E[0m\\]";
1531 #ifdef BB_FEATURE_NONPRINTABLE_INVERSE_PUT
1532 setlocale(LC_ALL, "");
1537 cmdedit_read_input(prompt, buff);
1539 if(l > 0 && buff[l-1] == '\n')
1541 printf("*** cmdedit_read_input() returned line =%s=\n", buff);
1542 } while (shell_context);
1543 printf("*** cmdedit_read_input() detect ^C\n");