Declare dependencies of command line editing in the build system
[oweals/busybox.git] / shell / cmdedit.c
1 /* vi: set sw=4 ts=4: */
2 /*
3  * Termios command line History and Editting.
4  *
5  * Copyright (c) 1986-2003 may safely be consumed by a BSD or GPL license.
6  * Written by:   Vladimir Oleynik <dzo@simtreas.ru>
7  *
8  * Used ideas:
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)
13  *
14  * This code is 'as is' with no warranty.
15  *
16  *
17  */
18
19 /*
20    Usage and Known bugs:
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.
26
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
31  */
32
33
34 #include <stdio.h>
35 #include <errno.h>
36 #include <unistd.h>
37 #include <stdlib.h>
38 #include <string.h>
39 #include <sys/ioctl.h>
40 #include <ctype.h>
41 #include <signal.h>
42 #include <limits.h>
43
44 #include "busybox.h"
45
46 #ifdef CONFIG_LOCALE_SUPPORT
47 #define Isprint(c) isprint((c))
48 #else
49 #define Isprint(c) ( (c) >= ' ' && (c) != ((unsigned char)'\233') )
50 #endif
51
52 #ifdef TEST
53
54 /* pretect redefined for test */
55 #undef CONFIG_FEATURE_COMMAND_EDITING
56 #undef CONFIG_FEATURE_COMMAND_TAB_COMPLETION
57 #undef CONFIG_FEATURE_COMMAND_USERNAME_COMPLETION
58 #undef CONFIG_FEATURE_NONPRINTABLE_INVERSE_PUT
59 #undef CONFIG_FEATURE_CLEAN_UP
60
61 #define CONFIG_FEATURE_COMMAND_EDITING
62 #define CONFIG_FEATURE_COMMAND_TAB_COMPLETION
63 #define CONFIG_FEATURE_COMMAND_USERNAME_COMPLETION
64 #define CONFIG_FEATURE_NONPRINTABLE_INVERSE_PUT
65 #define CONFIG_FEATURE_CLEAN_UP
66
67 #endif                                                  /* TEST */
68
69 #ifdef CONFIG_FEATURE_COMMAND_TAB_COMPLETION
70 #include <dirent.h>
71 #include <sys/stat.h>
72 #endif
73
74 #ifdef CONFIG_FEATURE_COMMAND_EDITING
75
76 #if defined(CONFIG_FEATURE_COMMAND_USERNAME_COMPLETION) || defined(CONFIG_FEATURE_SH_FANCY_PROMPT)
77 #define CONFIG_FEATURE_GETUSERNAME_AND_HOMEDIR
78 #endif
79
80 #ifdef CONFIG_FEATURE_GETUSERNAME_AND_HOMEDIR
81 #       ifndef TEST
82 #               include "pwd_.h"
83 #       else
84 #               include <pwd.h>
85 #       endif  /* TEST */
86 #endif                                                  /* advanced FEATURES */
87
88
89 /* Maximum length of the linked list for the command line history */
90 #ifndef CONFIG_FEATURE_COMMAND_HISTORY
91 #define MAX_HISTORY   15
92 #else
93 #define MAX_HISTORY   CONFIG_FEATURE_COMMAND_HISTORY
94 #endif
95
96 #if MAX_HISTORY < 1
97 #warning cmdedit: You set MAX_HISTORY < 1. The history algorithm switched off.
98 #else
99 static char *history[MAX_HISTORY+1]; /* history + current */
100 /* saved history lines */
101 static int n_history;
102 /* current pointer to history line */
103 static int cur_history;
104 #endif
105
106 #include <termios.h>
107 #define setTermSettings(fd,argp) tcsetattr(fd,TCSANOW,argp)
108 #define getTermSettings(fd,argp) tcgetattr(fd, argp);
109
110 /* Current termio and the previous termio before starting sh */
111 static struct termios initial_settings, new_settings;
112
113
114 static
115 volatile int cmdedit_termw = 80;        /* actual terminal width */
116 static
117 volatile int handlers_sets = 0; /* Set next bites: */
118
119 enum {
120         SET_ATEXIT = 1,         /* when atexit() has been called
121                                    and get euid,uid,gid to fast compare */
122         SET_WCHG_HANDLERS = 2,  /* winchg signal handler */
123         SET_RESET_TERM = 4,     /* if the terminal needs to be reset upon exit */
124 };
125
126
127 static int cmdedit_x;           /* real x terminal position */
128 static int cmdedit_y;           /* pseudoreal y terminal position */
129 static int cmdedit_prmt_len;    /* lenght prompt without colores string */
130
131 static int cursor;              /* required global for signal handler */
132 static int len;                 /* --- "" - - "" - -"- --""-- --""--- */
133 static char *command_ps;        /* --- "" - - "" - -"- --""-- --""--- */
134 static
135 #ifndef CONFIG_FEATURE_SH_FANCY_PROMPT
136         const
137 #endif
138 char *cmdedit_prompt;           /* --- "" - - "" - -"- --""-- --""--- */
139
140 #ifdef CONFIG_FEATURE_GETUSERNAME_AND_HOMEDIR
141 static char *user_buf = "";
142 static char *home_pwd_buf = "";
143 static int my_euid;
144 #endif
145
146 #ifdef CONFIG_FEATURE_SH_FANCY_PROMPT
147 static char *hostname_buf;
148 static int num_ok_lines = 1;
149 #endif
150
151
152 #ifdef  CONFIG_FEATURE_COMMAND_TAB_COMPLETION
153
154 #ifndef CONFIG_FEATURE_GETUSERNAME_AND_HOMEDIR
155 static int my_euid;
156 #endif
157
158 static int my_uid;
159 static int my_gid;
160
161 #endif  /* CONFIG_FEATURE_COMMAND_TAB_COMPLETION */
162
163 static void cmdedit_setwidth(int w, int redraw_flg);
164
165 static void win_changed(int nsig)
166 {
167         static sighandler_t previous_SIGWINCH_handler;  /* for reset */
168
169         /*   emulate      || signal call */
170         if (nsig == -SIGWINCH || nsig == SIGWINCH) {
171                 int width = 0;
172                 get_terminal_width_height(0, &width, NULL);
173                 cmdedit_setwidth(width, nsig == SIGWINCH);
174         }
175         /* Unix not all standart in recall signal */
176
177         if (nsig == -SIGWINCH)          /* save previous handler   */
178                 previous_SIGWINCH_handler = signal(SIGWINCH, win_changed);
179         else if (nsig == SIGWINCH)      /* signaled called handler */
180                 signal(SIGWINCH, win_changed);  /* set for next call       */
181         else                                            /* nsig == 0 */
182                 /* set previous handler    */
183                 signal(SIGWINCH, previous_SIGWINCH_handler);    /* reset    */
184 }
185
186 static void cmdedit_reset_term(void)
187 {
188         if ((handlers_sets & SET_RESET_TERM) != 0) {
189 /* sparc and other have broken termios support: use old termio handling. */
190                 setTermSettings(fileno(stdin), (void *) &initial_settings);
191                 handlers_sets &= ~SET_RESET_TERM;
192         }
193         if ((handlers_sets & SET_WCHG_HANDLERS) != 0) {
194                 /* reset SIGWINCH handler to previous (default) */
195                 win_changed(0);
196                 handlers_sets &= ~SET_WCHG_HANDLERS;
197         }
198         fflush(stdout);
199 }
200
201
202 /* special for recount position for scroll and remove terminal margin effect */
203 static void cmdedit_set_out_char(int next_char)
204 {
205
206         int c = (int)((unsigned char) command_ps[cursor]);
207
208         if (c == 0)
209                 c = ' ';        /* destroy end char? */
210 #ifdef CONFIG_FEATURE_NONPRINTABLE_INVERSE_PUT
211         if (!Isprint(c)) {      /* Inverse put non-printable characters */
212                 if (c >= 128)
213                         c -= 128;
214                 if (c < ' ')
215                         c += '@';
216                 if (c == 127)
217                         c = '?';
218                 printf("\033[7m%c\033[0m", c);
219         } else
220 #endif
221                 putchar(c);
222         if (++cmdedit_x >= cmdedit_termw) {
223                 /* terminal is scrolled down */
224                 cmdedit_y++;
225                 cmdedit_x = 0;
226
227                 if (!next_char)
228                         next_char = ' ';
229                 /* destroy "(auto)margin" */
230                 putchar(next_char);
231                 putchar('\b');
232         }
233         cursor++;
234 }
235
236 /* Move to end line. Bonus: rewrite line from cursor */
237 static void input_end(void)
238 {
239         while (cursor < len)
240                 cmdedit_set_out_char(0);
241 }
242
243 /* Go to the next line */
244 static void goto_new_line(void)
245 {
246         input_end();
247         if (cmdedit_x)
248                 putchar('\n');
249 }
250
251
252 static inline void out1str(const char *s)
253 {
254         if ( s )
255                 fputs(s, stdout);
256 }
257
258 static inline void beep(void)
259 {
260         putchar('\007');
261 }
262
263 /* Move back one charactor */
264 /* special for slow terminal */
265 static void input_backward(int num)
266 {
267         if (num > cursor)
268                 num = cursor;
269         cursor -= num;          /* new cursor (in command, not terminal) */
270
271         if (cmdedit_x >= num) {         /* no to up line */
272                 cmdedit_x -= num;
273                 if (num < 4)
274                         while (num-- > 0)
275                                 putchar('\b');
276
277                 else
278                         printf("\033[%dD", num);
279         } else {
280                 int count_y;
281
282                 if (cmdedit_x) {
283                         putchar('\r');          /* back to first terminal pos.  */
284                         num -= cmdedit_x;       /* set previous backward        */
285                 }
286                 count_y = 1 + num / cmdedit_termw;
287                 printf("\033[%dA", count_y);
288                 cmdedit_y -= count_y;
289                 /*  require  forward  after  uping   */
290                 cmdedit_x = cmdedit_termw * count_y - num;
291                 printf("\033[%dC", cmdedit_x);  /* set term cursor   */
292         }
293 }
294
295 static void put_prompt(void)
296 {
297         out1str(cmdedit_prompt);
298         cmdedit_x = cmdedit_prmt_len;   /* count real x terminal position */
299         cursor = 0;
300         cmdedit_y = 0;                  /* new quasireal y */
301 }
302
303 #ifndef CONFIG_FEATURE_SH_FANCY_PROMPT
304 static void parse_prompt(const char *prmt_ptr)
305 {
306         cmdedit_prompt = prmt_ptr;
307         cmdedit_prmt_len = strlen(prmt_ptr);
308         put_prompt();
309 }
310 #else
311 static void parse_prompt(const char *prmt_ptr)
312 {
313         int prmt_len = 0;
314         int sub_len = 0;
315         char  flg_not_length = '[';
316         char *prmt_mem_ptr = xcalloc(1, 1);
317         char *pwd_buf = xgetcwd(0);
318         char  buf2[PATH_MAX + 1];
319         char  buf[2];
320         char  c;
321         char *pbuf;
322
323         if (!pwd_buf) {
324                 pwd_buf=(char *)bb_msg_unknown;
325         }
326
327         while (*prmt_ptr) {
328                 pbuf    = buf;
329                 pbuf[1] = 0;
330                 c = *prmt_ptr++;
331                 if (c == '\\') {
332                         const char *cp = prmt_ptr;
333                         int l;
334
335                         c = bb_process_escape_sequence(&prmt_ptr);
336                         if(prmt_ptr==cp) {
337                           if (*cp == 0)
338                                 break;
339                           c = *prmt_ptr++;
340                           switch (c) {
341 #ifdef CONFIG_FEATURE_GETUSERNAME_AND_HOMEDIR
342                           case 'u':
343                                 pbuf = user_buf;
344                                 break;
345 #endif
346                           case 'h':
347                                 pbuf = hostname_buf;
348                                 if (pbuf == 0) {
349                                         pbuf = xcalloc(256, 1);
350                                         if (gethostname(pbuf, 255) < 0) {
351                                                 strcpy(pbuf, "?");
352                                         } else {
353                                                 char *s = strchr(pbuf, '.');
354
355                                                 if (s)
356                                                         *s = 0;
357                                         }
358                                         hostname_buf = pbuf;
359                                 }
360                                 break;
361                           case '$':
362                                 c = my_euid == 0 ? '#' : '$';
363                                 break;
364 #ifdef CONFIG_FEATURE_GETUSERNAME_AND_HOMEDIR
365                           case 'w':
366                                 pbuf = pwd_buf;
367                                 l = strlen(home_pwd_buf);
368                                 if (home_pwd_buf[0] != 0 &&
369                                     strncmp(home_pwd_buf, pbuf, l) == 0 &&
370                                     (pbuf[l]=='/' || pbuf[l]=='\0') &&
371                                     strlen(pwd_buf+l)<PATH_MAX) {
372                                         pbuf = buf2;
373                                         *pbuf = '~';
374                                         strcpy(pbuf+1, pwd_buf+l);
375                                         }
376                                 break;
377 #endif
378                           case 'W':
379                                 pbuf = pwd_buf;
380                                 cp = strrchr(pbuf,'/');
381                                 if ( (cp != NULL) && (cp != pbuf) )
382                                         pbuf += (cp-pbuf)+1;
383                                 break;
384                           case '!':
385                                 snprintf(pbuf = buf2, sizeof(buf2), "%d", num_ok_lines);
386                                 break;
387                           case 'e': case 'E':     /* \e \E = \033 */
388                                 c = '\033';
389                                 break;
390                           case 'x': case 'X':
391                                 for (l = 0; l < 3;) {
392                                         int h;
393                                         buf2[l++] = *prmt_ptr;
394                                         buf2[l] = 0;
395                                         h = strtol(buf2, &pbuf, 16);
396                                         if (h > UCHAR_MAX || (pbuf - buf2) < l) {
397                                                 l--;
398                                                 break;
399                                         }
400                                         prmt_ptr++;
401                                 }
402                                 buf2[l] = 0;
403                                 c = (char)strtol(buf2, 0, 16);
404                                 if(c==0)
405                                         c = '?';
406                                 pbuf = buf;
407                                 break;
408                           case '[': case ']':
409                                 if (c == flg_not_length) {
410                                         flg_not_length = flg_not_length == '[' ? ']' : '[';
411                                         continue;
412                                 }
413                                 break;
414                           }
415                         }
416                 }
417                 if(pbuf == buf)
418                         *pbuf = c;
419                 prmt_len += strlen(pbuf);
420                 prmt_mem_ptr = strcat(xrealloc(prmt_mem_ptr, prmt_len+1), pbuf);
421                 if (flg_not_length == ']')
422                         sub_len++;
423         }
424         if(pwd_buf!=(char *)bb_msg_unknown)
425                 free(pwd_buf);
426         cmdedit_prompt = prmt_mem_ptr;
427         cmdedit_prmt_len = prmt_len - sub_len;
428         put_prompt();
429 }
430 #endif
431
432
433 /* draw promt, editor line, and clear tail */
434 static void redraw(int y, int back_cursor)
435 {
436         if (y > 0)                              /* up to start y */
437                 printf("\033[%dA", y);
438         putchar('\r');
439         put_prompt();
440         input_end();                            /* rewrite */
441         printf("\033[J");                       /* destroy tail after cursor */
442         input_backward(back_cursor);
443 }
444
445 /* Delete the char in front of the cursor */
446 static void input_delete(void)
447 {
448         int j = cursor;
449
450         if (j == len)
451                 return;
452
453         strcpy(command_ps + j, command_ps + j + 1);
454         len--;
455         input_end();                    /* rewtite new line */
456         cmdedit_set_out_char(0);        /* destroy end char */
457         input_backward(cursor - j);     /* back to old pos cursor */
458 }
459
460 /* Delete the char in back of the cursor */
461 static void input_backspace(void)
462 {
463         if (cursor > 0) {
464                 input_backward(1);
465                 input_delete();
466         }
467 }
468
469
470 /* Move forward one charactor */
471 static void input_forward(void)
472 {
473         if (cursor < len)
474                 cmdedit_set_out_char(command_ps[cursor + 1]);
475 }
476
477
478 static void cmdedit_setwidth(int w, int redraw_flg)
479 {
480         cmdedit_termw = cmdedit_prmt_len + 2;
481         if (w <= cmdedit_termw) {
482                 cmdedit_termw = cmdedit_termw % w;
483         }
484         if (w > cmdedit_termw) {
485                 cmdedit_termw = w;
486
487                 if (redraw_flg) {
488                         /* new y for current cursor */
489                         int new_y = (cursor + cmdedit_prmt_len) / w;
490
491                         /* redraw */
492                         redraw((new_y >= cmdedit_y ? new_y : cmdedit_y), len - cursor);
493                         fflush(stdout);
494                 }
495         }
496 }
497
498 static void cmdedit_init(void)
499 {
500         cmdedit_prmt_len = 0;
501         if ((handlers_sets & SET_WCHG_HANDLERS) == 0) {
502                 /* emulate usage handler to set handler and call yours work */
503                 win_changed(-SIGWINCH);
504                 handlers_sets |= SET_WCHG_HANDLERS;
505         }
506
507         if ((handlers_sets & SET_ATEXIT) == 0) {
508 #ifdef CONFIG_FEATURE_GETUSERNAME_AND_HOMEDIR
509                 struct passwd *entry;
510
511                 my_euid = geteuid();
512                 entry = getpwuid(my_euid);
513                 if (entry) {
514                         user_buf = bb_xstrdup(entry->pw_name);
515                         home_pwd_buf = bb_xstrdup(entry->pw_dir);
516                 }
517 #endif
518
519 #ifdef  CONFIG_FEATURE_COMMAND_TAB_COMPLETION
520
521 #ifndef CONFIG_FEATURE_GETUSERNAME_AND_HOMEDIR
522                 my_euid = geteuid();
523 #endif
524                 my_uid = getuid();
525                 my_gid = getgid();
526 #endif  /* CONFIG_FEATURE_COMMAND_TAB_COMPLETION */
527                 handlers_sets |= SET_ATEXIT;
528                 atexit(cmdedit_reset_term);     /* be sure to do this only once */
529         }
530 }
531
532 #ifdef CONFIG_FEATURE_COMMAND_TAB_COMPLETION
533
534 static int is_execute(const struct stat *st)
535 {
536         if ((!my_euid && (st->st_mode & (S_IXUSR | S_IXGRP | S_IXOTH))) ||
537                 (my_uid == st->st_uid && (st->st_mode & S_IXUSR)) ||
538                 (my_gid == st->st_gid && (st->st_mode & S_IXGRP)) ||
539                 (st->st_mode & S_IXOTH)) return TRUE;
540         return FALSE;
541 }
542
543 #ifdef CONFIG_FEATURE_COMMAND_USERNAME_COMPLETION
544
545 static char **username_tab_completion(char *ud, int *num_matches)
546 {
547         struct passwd *entry;
548         int userlen;
549         char *temp;
550
551
552         ud++;                           /* ~user/... to user/... */
553         userlen = strlen(ud);
554
555         if (num_matches == 0) {         /* "~/..." or "~user/..." */
556                 char *sav_ud = ud - 1;
557                 char *home = 0;
558
559                 if (*ud == '/') {       /* "~/..."     */
560                         home = home_pwd_buf;
561                 } else {
562                         /* "~user/..." */
563                         temp = strchr(ud, '/');
564                         *temp = 0;              /* ~user\0 */
565                         entry = getpwnam(ud);
566                         *temp = '/';            /* restore ~user/... */
567                         ud = temp;
568                         if (entry)
569                                 home = entry->pw_dir;
570                 }
571                 if (home) {
572                         if ((userlen + strlen(home) + 1) < BUFSIZ) {
573                                 char temp2[BUFSIZ];     /* argument size */
574
575                                 /* /home/user/... */
576                                 sprintf(temp2, "%s%s", home, ud);
577                                 strcpy(sav_ud, temp2);
578                         }
579                 }
580                 return 0;       /* void, result save to argument :-) */
581         } else {
582                 /* "~[^/]*" */
583                 char **matches = (char **) NULL;
584                 int nm = 0;
585
586                 setpwent();
587
588                 while ((entry = getpwent()) != NULL) {
589                         /* Null usernames should result in all users as possible completions. */
590                         if ( /*!userlen || */ !strncmp(ud, entry->pw_name, userlen)) {
591
592                                bb_xasprintf(&temp, "~%s/", entry->pw_name);
593                                 matches = xrealloc(matches, (nm + 1) * sizeof(char *));
594
595                                 matches[nm++] = temp;
596                         }
597                 }
598
599                 endpwent();
600                 (*num_matches) = nm;
601                 return (matches);
602         }
603 }
604 #endif  /* CONFIG_FEATURE_COMMAND_USERNAME_COMPLETION */
605
606 enum {
607         FIND_EXE_ONLY = 0,
608         FIND_DIR_ONLY = 1,
609         FIND_FILE_ONLY = 2,
610 };
611
612 static int path_parse(char ***p, int flags)
613 {
614         int npth;
615         char *tmp;
616         char *pth;
617
618         /* if not setenv PATH variable, to search cur dir "." */
619         if (flags != FIND_EXE_ONLY || (pth = getenv("PATH")) == 0 ||
620                 /* PATH=<empty> or PATH=:<empty> */
621                 *pth == 0 || (*pth == ':' && *(pth + 1) == 0)) {
622                 return 1;
623         }
624
625         tmp = pth;
626         npth = 0;
627
628         for (;;) {
629                 npth++;                 /* count words is + 1 count ':' */
630                 tmp = strchr(tmp, ':');
631                 if (tmp) {
632                         if (*++tmp == 0)
633                                 break;  /* :<empty> */
634                 } else
635                         break;
636         }
637
638         *p = xmalloc(npth * sizeof(char *));
639
640         tmp = pth;
641         (*p)[0] = bb_xstrdup(tmp);
642         npth = 1;                       /* count words is + 1 count ':' */
643
644         for (;;) {
645                 tmp = strchr(tmp, ':');
646                 if (tmp) {
647                         (*p)[0][(tmp - pth)] = 0;       /* ':' -> '\0' */
648                         if (*++tmp == 0)
649                                 break;                  /* :<empty> */
650                 } else
651                         break;
652                 (*p)[npth++] = &(*p)[0][(tmp - pth)];   /* p[next]=p[0][&'\0'+1] */
653         }
654
655         return npth;
656 }
657
658 static char *add_quote_for_spec_chars(char *found)
659 {
660         int l = 0;
661         char *s = xmalloc((strlen(found) + 1) * 2);
662
663         while (*found) {
664                 if (strchr(" `\"#$%^&*()=+{}[]:;\'|\\<>", *found))
665                         s[l++] = '\\';
666                 s[l++] = *found++;
667         }
668         s[l] = 0;
669         return s;
670 }
671
672 static char **exe_n_cwd_tab_completion(char *command, int *num_matches,
673                                         int type)
674 {
675
676         char **matches = 0;
677         DIR *dir;
678         struct dirent *next;
679         char dirbuf[BUFSIZ];
680         int nm = *num_matches;
681         struct stat st;
682         char *path1[1];
683         char **paths = path1;
684         int npaths;
685         int i;
686         char *found;
687         char *pfind = strrchr(command, '/');
688
689         path1[0] = ".";
690
691         if (pfind == NULL) {
692                 /* no dir, if flags==EXE_ONLY - get paths, else "." */
693                 npaths = path_parse(&paths, type);
694                 pfind = command;
695         } else {
696                 /* with dir */
697                 /* save for change */
698                 strcpy(dirbuf, command);
699                 /* set dir only */
700                 dirbuf[(pfind - command) + 1] = 0;
701 #ifdef CONFIG_FEATURE_COMMAND_USERNAME_COMPLETION
702                 if (dirbuf[0] == '~')   /* ~/... or ~user/... */
703                         username_tab_completion(dirbuf, 0);
704 #endif
705                 /* "strip" dirname in command */
706                 pfind++;
707
708                 paths[0] = dirbuf;
709                 npaths = 1;                             /* only 1 dir */
710         }
711
712         for (i = 0; i < npaths; i++) {
713
714                 dir = opendir(paths[i]);
715                 if (!dir)                       /* Don't print an error */
716                         continue;
717
718                 while ((next = readdir(dir)) != NULL) {
719                         char *str_found = next->d_name;
720
721                         /* matched ? */
722                         if (strncmp(str_found, pfind, strlen(pfind)))
723                                 continue;
724                         /* not see .name without .match */
725                         if (*str_found == '.' && *pfind == 0) {
726                                 if (*paths[i] == '/' && paths[i][1] == 0
727                                         && str_found[1] == 0) str_found = "";   /* only "/" */
728                                 else
729                                         continue;
730                         }
731                         found = concat_path_file(paths[i], str_found);
732                         /* hmm, remover in progress? */
733                         if (stat(found, &st) < 0)
734                                 goto cont;
735                         /* find with dirs ? */
736                         if (paths[i] != dirbuf)
737                                 strcpy(found, next->d_name);    /* only name */
738                         if (S_ISDIR(st.st_mode)) {
739                                 /* name is directory      */
740                                 str_found = found;
741                                 found = concat_path_file(found, "");
742                                 free(str_found);
743                                 str_found = add_quote_for_spec_chars(found);
744                         } else {
745                                 /* not put found file if search only dirs for cd */
746                                 if (type == FIND_DIR_ONLY)
747                                         goto cont;
748                                 str_found = add_quote_for_spec_chars(found);
749                                 if (type == FIND_FILE_ONLY ||
750                                         (type == FIND_EXE_ONLY && is_execute(&st)))
751                                         strcat(str_found, " ");
752                         }
753                         /* Add it to the list */
754                         matches = xrealloc(matches, (nm + 1) * sizeof(char *));
755
756                         matches[nm++] = str_found;
757 cont:
758                         free(found);
759                 }
760                 closedir(dir);
761         }
762         if (paths != path1) {
763                 free(paths[0]);                 /* allocated memory only in first member */
764                 free(paths);
765         }
766         *num_matches = nm;
767         return (matches);
768 }
769
770 static int match_compare(const void *a, const void *b)
771 {
772         return strcmp(*(char **) a, *(char **) b);
773 }
774
775
776
777 #define QUOT    (UCHAR_MAX+1)
778
779 #define collapse_pos(is, in) { \
780         memcpy(int_buf+(is), int_buf+(in), (BUFSIZ+1-(is)-(in))*sizeof(int)); \
781         memcpy(pos_buf+(is), pos_buf+(in), (BUFSIZ+1-(is)-(in))*sizeof(int)); }
782
783 static int find_match(char *matchBuf, int *len_with_quotes)
784 {
785         int i, j;
786         int command_mode;
787         int c, c2;
788         int int_buf[BUFSIZ + 1];
789         int pos_buf[BUFSIZ + 1];
790
791         /* set to integer dimension characters and own positions */
792         for (i = 0;; i++) {
793                 int_buf[i] = (int) ((unsigned char) matchBuf[i]);
794                 if (int_buf[i] == 0) {
795                         pos_buf[i] = -1;        /* indicator end line */
796                         break;
797                 } else
798                         pos_buf[i] = i;
799         }
800
801         /* mask \+symbol and convert '\t' to ' ' */
802         for (i = j = 0; matchBuf[i]; i++, j++)
803                 if (matchBuf[i] == '\\') {
804                         collapse_pos(j, j + 1);
805                         int_buf[j] |= QUOT;
806                         i++;
807 #ifdef CONFIG_FEATURE_NONPRINTABLE_INVERSE_PUT
808                         if (matchBuf[i] == '\t')        /* algorithm equivalent */
809                                 int_buf[j] = ' ' | QUOT;
810 #endif
811                 }
812 #ifdef CONFIG_FEATURE_NONPRINTABLE_INVERSE_PUT
813                 else if (matchBuf[i] == '\t')
814                         int_buf[j] = ' ';
815 #endif
816
817         /* mask "symbols" or 'symbols' */
818         c2 = 0;
819         for (i = 0; int_buf[i]; i++) {
820                 c = int_buf[i];
821                 if (c == '\'' || c == '"') {
822                         if (c2 == 0)
823                                 c2 = c;
824                         else {
825                                 if (c == c2)
826                                         c2 = 0;
827                                 else
828                                         int_buf[i] |= QUOT;
829                         }
830                 } else if (c2 != 0 && c != '$')
831                         int_buf[i] |= QUOT;
832         }
833
834         /* skip commands with arguments if line have commands delimiters */
835         /* ';' ';;' '&' '|' '&&' '||' but `>&' `<&' `>|' */
836         for (i = 0; int_buf[i]; i++) {
837                 c = int_buf[i];
838                 c2 = int_buf[i + 1];
839                 j = i ? int_buf[i - 1] : -1;
840                 command_mode = 0;
841                 if (c == ';' || c == '&' || c == '|') {
842                         command_mode = 1 + (c == c2);
843                         if (c == '&') {
844                                 if (j == '>' || j == '<')
845                                         command_mode = 0;
846                         } else if (c == '|' && j == '>')
847                                 command_mode = 0;
848                 }
849                 if (command_mode) {
850                         collapse_pos(0, i + command_mode);
851                         i = -1;                         /* hack incremet */
852                 }
853         }
854         /* collapse `command...` */
855         for (i = 0; int_buf[i]; i++)
856                 if (int_buf[i] == '`') {
857                         for (j = i + 1; int_buf[j]; j++)
858                                 if (int_buf[j] == '`') {
859                                         collapse_pos(i, j + 1);
860                                         j = 0;
861                                         break;
862                                 }
863                         if (j) {
864                                 /* not found close ` - command mode, collapse all previous */
865                                 collapse_pos(0, i + 1);
866                                 break;
867                         } else
868                                 i--;                    /* hack incremet */
869                 }
870
871         /* collapse (command...(command...)...) or {command...{command...}...} */
872         c = 0;                                          /* "recursive" level */
873         c2 = 0;
874         for (i = 0; int_buf[i]; i++)
875                 if (int_buf[i] == '(' || int_buf[i] == '{') {
876                         if (int_buf[i] == '(')
877                                 c++;
878                         else
879                                 c2++;
880                         collapse_pos(0, i + 1);
881                         i = -1;                         /* hack incremet */
882                 }
883         for (i = 0; pos_buf[i] >= 0 && (c > 0 || c2 > 0); i++)
884                 if ((int_buf[i] == ')' && c > 0) || (int_buf[i] == '}' && c2 > 0)) {
885                         if (int_buf[i] == ')')
886                                 c--;
887                         else
888                                 c2--;
889                         collapse_pos(0, i + 1);
890                         i = -1;                         /* hack incremet */
891                 }
892
893         /* skip first not quote space */
894         for (i = 0; int_buf[i]; i++)
895                 if (int_buf[i] != ' ')
896                         break;
897         if (i)
898                 collapse_pos(0, i);
899
900         /* set find mode for completion */
901         command_mode = FIND_EXE_ONLY;
902         for (i = 0; int_buf[i]; i++)
903                 if (int_buf[i] == ' ' || int_buf[i] == '<' || int_buf[i] == '>') {
904                         if (int_buf[i] == ' ' && command_mode == FIND_EXE_ONLY
905                                 && matchBuf[pos_buf[0]]=='c'
906                                 && matchBuf[pos_buf[1]]=='d' )
907                                 command_mode = FIND_DIR_ONLY;
908                         else {
909                                 command_mode = FIND_FILE_ONLY;
910                                 break;
911                         }
912                 }
913         /* "strlen" */
914         for (i = 0; int_buf[i]; i++);
915         /* find last word */
916         for (--i; i >= 0; i--) {
917                 c = int_buf[i];
918                 if (c == ' ' || c == '<' || c == '>' || c == '|' || c == '&') {
919                         collapse_pos(0, i + 1);
920                         break;
921                 }
922         }
923         /* skip first not quoted '\'' or '"' */
924         for (i = 0; int_buf[i] == '\'' || int_buf[i] == '"'; i++);
925         /* collapse quote or unquote // or /~ */
926         while ((int_buf[i] & ~QUOT) == '/' &&
927                         ((int_buf[i + 1] & ~QUOT) == '/'
928                          || (int_buf[i + 1] & ~QUOT) == '~')) {
929                 i++;
930         }
931
932         /* set only match and destroy quotes */
933         j = 0;
934         for (c = 0; pos_buf[i] >= 0; i++) {
935                 matchBuf[c++] = matchBuf[pos_buf[i]];
936                 j = pos_buf[i] + 1;
937         }
938         matchBuf[c] = 0;
939         /* old lenght matchBuf with quotes symbols */
940         *len_with_quotes = j ? j - pos_buf[0] : 0;
941
942         return command_mode;
943 }
944
945 /*
946    display by column original ideas from ls applet,
947    very optimize by my :)
948 */
949 static void showfiles(char **matches, int nfiles)
950 {
951         int ncols, row;
952         int column_width = 0;
953         int nrows = nfiles;
954
955         /* find the longest file name-  use that as the column width */
956         for (row = 0; row < nrows; row++) {
957                 int l = strlen(matches[row]);
958
959                 if (column_width < l)
960                         column_width = l;
961         }
962         column_width += 2;              /* min space for columns */
963         ncols = cmdedit_termw / column_width;
964
965         if (ncols > 1) {
966                 nrows /= ncols;
967                 if(nfiles % ncols)
968                         nrows++;        /* round up fractionals */
969                 column_width = -column_width;   /* for printf("%-Ns", ...); */
970         } else {
971                 ncols = 1;
972         }
973         for (row = 0; row < nrows; row++) {
974                 int n = row;
975                 int nc;
976
977                 for(nc = 1; nc < ncols && n+nrows < nfiles; n += nrows, nc++)
978                         printf("%*s", column_width, matches[n]);
979                 printf("%s\n", matches[n]);
980         }
981 }
982
983
984 static void input_tab(int *lastWasTab)
985 {
986         /* Do TAB completion */
987         static int num_matches;
988         static char **matches;
989
990         if (lastWasTab == 0) {          /* free all memory */
991                 if (matches) {
992                         while (num_matches > 0)
993                                 free(matches[--num_matches]);
994                         free(matches);
995                         matches = (char **) NULL;
996                 }
997                 return;
998         }
999         if (! *lastWasTab) {
1000
1001                 char *tmp;
1002                 int len_found;
1003                 char matchBuf[BUFSIZ];
1004                 int find_type;
1005                 int recalc_pos;
1006
1007                 *lastWasTab = TRUE;             /* flop trigger */
1008
1009                 /* Make a local copy of the string -- up
1010                  * to the position of the cursor */
1011                 tmp = strncpy(matchBuf, command_ps, cursor);
1012                 tmp[cursor] = 0;
1013
1014                 find_type = find_match(matchBuf, &recalc_pos);
1015
1016                 /* Free up any memory already allocated */
1017                 input_tab(0);
1018
1019 #ifdef CONFIG_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. */
1022
1023                 if (matchBuf[0] == '~' && strchr(matchBuf, '/') == 0)
1024                         matches = username_tab_completion(matchBuf, &num_matches);
1025 #endif
1026                 /* Try to match any executable in our path and everything
1027                  * in the current working directory that matches.  */
1028                 if (!matches)
1029                         matches =
1030                                 exe_n_cwd_tab_completion(matchBuf,
1031                                         &num_matches, find_type);
1032                 /* Remove duplicate found */
1033                 if(matches) {
1034                         int i, j;
1035                         /* bubble */
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) {
1040                                                         free(matches[j]);
1041                                                         matches[j]=0;
1042                                         }
1043                         j=num_matches;
1044                         num_matches = 0;
1045                         for(i=0; i<j; i++)
1046                                 if(matches[i]) {
1047                                         if(!strcmp(matches[i], "./"))
1048                                                 matches[i][1]=0;
1049                                         else if(!strcmp(matches[i], "../"))
1050                                                 matches[i][2]=0;
1051                                         matches[num_matches++]=matches[i];
1052                                 }
1053                 }
1054                 /* Did we find exactly one match? */
1055                 if (!matches || num_matches > 1) {
1056                         char *tmp1;
1057
1058                         beep();
1059                         if (!matches)
1060                                 return;         /* not found */
1061                         /* sort */
1062                         qsort(matches, num_matches, sizeof(char *), match_compare);
1063
1064                         /* find minimal match */
1065                         tmp = bb_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) {
1069                                                 *tmp1 = 0;
1070                                                 break;
1071                                         }
1072                         if (*tmp == 0) {        /* have unique */
1073                                 free(tmp);
1074                                 return;
1075                         }
1076                 } else {                        /* one match */
1077                         tmp = matches[0];
1078                         /* for next completion current found */
1079                         *lastWasTab = FALSE;
1080                 }
1081
1082                 len_found = strlen(tmp);
1083                 /* have space to placed match? */
1084                 if ((len_found - strlen(matchBuf) + len) < BUFSIZ) {
1085
1086                         /* before word for match   */
1087                         command_ps[cursor - recalc_pos] = 0;
1088                         /* save   tail line        */
1089                         strcpy(matchBuf, command_ps + cursor);
1090                         /* add    match            */
1091                         strcat(command_ps, tmp);
1092                         /* add    tail             */
1093                         strcat(command_ps, matchBuf);
1094                         /* back to begin word for match    */
1095                         input_backward(recalc_pos);
1096                         /* new pos                         */
1097                         recalc_pos = cursor + len_found;
1098                         /* new len                         */
1099                         len = strlen(command_ps);
1100                         /* write out the matched command   */
1101                         redraw(cmdedit_y, len - recalc_pos);
1102                 }
1103                 if (tmp != matches[0])
1104                         free(tmp);
1105         } else {
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) {
1110                         int sav_cursor = cursor;        /* change goto_new_line() */
1111
1112                         /* Go to the next line */
1113                         goto_new_line();
1114                         showfiles(matches, num_matches);
1115                         redraw(0, len - sav_cursor);
1116                 }
1117         }
1118 }
1119 #endif  /* CONFIG_FEATURE_COMMAND_TAB_COMPLETION */
1120
1121 #if MAX_HISTORY >= 1
1122 static void get_previous_history(void)
1123 {
1124         if(command_ps[0] != 0 || history[cur_history] == 0) {
1125                 free(history[cur_history]);
1126                 history[cur_history] = bb_xstrdup(command_ps);
1127         }
1128         cur_history--;
1129 }
1130
1131 static int get_next_history(void)
1132 {
1133         int ch = cur_history;
1134
1135         if (ch < n_history) {
1136                 get_previous_history(); /* save the current history line */
1137                 return (cur_history = ch+1);
1138         } else {
1139                 beep();
1140                 return 0;
1141         }
1142 }
1143
1144 #ifdef CONFIG_FEATURE_COMMAND_SAVEHISTORY
1145 extern void load_history ( const char *fromfile )
1146 {
1147         FILE *fp;
1148         int hi;
1149
1150         /* cleanup old */
1151
1152         for(hi = n_history; hi > 0; ) {
1153                 hi--;
1154                 free ( history [hi] );
1155         }
1156
1157         if (( fp = fopen ( fromfile, "r" ))) {
1158
1159                 for ( hi = 0; hi < MAX_HISTORY; ) {
1160                         char * hl = bb_get_chomped_line_from_file(fp);
1161                         int l;
1162
1163                         if(!hl)
1164                                 break;
1165                         l = strlen(hl);
1166                         if(l >= BUFSIZ)
1167                                 hl[BUFSIZ-1] = 0;
1168                         if(l == 0 || hl[0] == ' ') {
1169                                 free(hl);
1170                                 continue;
1171                         }
1172                         history [hi++] = hl;
1173                 }
1174                 fclose ( fp );
1175         }
1176         cur_history = n_history = hi;
1177 }
1178
1179 extern void save_history ( const char *tofile )
1180 {
1181         FILE *fp = fopen ( tofile, "w" );
1182
1183         if ( fp ) {
1184                 int i;
1185
1186                 for ( i = 0; i < n_history; i++ ) {
1187                         fprintf(fp, "%s\n", history [i]);
1188                 }
1189                 fclose ( fp );
1190         }
1191 }
1192 #endif
1193
1194 #endif
1195
1196 enum {
1197         ESC = 27,
1198         DEL = 127,
1199 };
1200
1201
1202 /*
1203  * This function is used to grab a character buffer
1204  * from the input file descriptor and allows you to
1205  * a string with full command editing (sortof like
1206  * a mini readline).
1207  *
1208  * The following standard commands are not implemented:
1209  * ESC-b -- Move back one word
1210  * ESC-f -- Move forward one word
1211  * ESC-d -- Delete back one word
1212  * ESC-h -- Delete forward one word
1213  * CTL-t -- Transpose two characters
1214  *
1215  * Furthermore, the "vi" command editing keys are not implemented.
1216  *
1217  */
1218
1219
1220 int cmdedit_read_input(char *prompt, char command[BUFSIZ])
1221 {
1222
1223         int break_out = 0;
1224         int lastWasTab = FALSE;
1225         unsigned char c = 0;
1226
1227         /* prepare before init handlers */
1228         cmdedit_y = 0;  /* quasireal y, not true work if line > xt*yt */
1229         len = 0;
1230         command_ps = command;
1231
1232         getTermSettings(0, (void *) &initial_settings);
1233         memcpy(&new_settings, &initial_settings, sizeof(struct termios));
1234         new_settings.c_lflag &= ~ICANON;        /* unbuffered input */
1235         /* Turn off echoing and CTRL-C, so we can trap it */
1236         new_settings.c_lflag &= ~(ECHO | ECHONL | ISIG);
1237         /* Hmm, in linux c_cc[] not parsed if set ~ICANON */
1238         new_settings.c_cc[VMIN] = 1;
1239         new_settings.c_cc[VTIME] = 0;
1240         /* Turn off CTRL-C, so we can trap it */
1241 #       ifndef _POSIX_VDISABLE
1242 #               define _POSIX_VDISABLE '\0'
1243 #       endif
1244         new_settings.c_cc[VINTR] = _POSIX_VDISABLE;
1245         command[0] = 0;
1246
1247         setTermSettings(0, (void *) &new_settings);
1248         handlers_sets |= SET_RESET_TERM;
1249
1250         /* Now initialize things */
1251         cmdedit_init();
1252         /* Print out the command prompt */
1253         parse_prompt(prompt);
1254
1255         while (1) {
1256
1257                 fflush(stdout);                 /* buffered out to fast */
1258
1259                 if (safe_read(0, &c, 1) < 1)
1260                         /* if we can't read input then exit */
1261                         goto prepare_to_die;
1262
1263                 switch (c) {
1264                 case '\n':
1265                 case '\r':
1266                         /* Enter */
1267                         goto_new_line();
1268                         break_out = 1;
1269                         break;
1270                 case 1:
1271                         /* Control-a -- Beginning of line */
1272                         input_backward(cursor);
1273                         break;
1274                 case 2:
1275                         /* Control-b -- Move back one character */
1276                         input_backward(1);
1277                         break;
1278                 case 3:
1279                         /* Control-c -- stop gathering input */
1280                         goto_new_line();
1281                         command[0] = 0;
1282                         len = 0;
1283                         lastWasTab = FALSE;
1284                         put_prompt();
1285                         break;
1286                 case 4:
1287                         /* Control-d -- Delete one character, or exit
1288                          * if the len=0 and no chars to delete */
1289                         if (len == 0) {
1290 prepare_to_die:
1291 #if !defined(CONFIG_ASH)
1292                                 printf("exit");
1293                                 goto_new_line();
1294                                 /* cmdedit_reset_term() called in atexit */
1295                                 exit(EXIT_SUCCESS);
1296 #else
1297                                 break_out = -1; /* for control stoped jobs */
1298                                 break;
1299 #endif
1300                         } else {
1301                                 input_delete();
1302                         }
1303                         break;
1304                 case 5:
1305                         /* Control-e -- End of line */
1306                         input_end();
1307                         break;
1308                 case 6:
1309                         /* Control-f -- Move forward one character */
1310                         input_forward();
1311                         break;
1312                 case '\b':
1313                 case DEL:
1314                         /* Control-h and DEL */
1315                         input_backspace();
1316                         break;
1317                 case '\t':
1318 #ifdef CONFIG_FEATURE_COMMAND_TAB_COMPLETION
1319                         input_tab(&lastWasTab);
1320 #endif
1321                         break;
1322                 case 11:
1323                         /* Control-k -- clear to end of line */
1324                         *(command + cursor) = 0;
1325                         len = cursor;
1326                         printf("\033[J");
1327                         break;
1328                 case 12:
1329                         /* Control-l -- clear screen */
1330                         printf("\033[H");
1331                         redraw(0, len-cursor);
1332                         break;
1333 #if MAX_HISTORY >= 1
1334                 case 14:
1335                         /* Control-n -- Get next command in history */
1336                         if (get_next_history())
1337                                 goto rewrite_line;
1338                         break;
1339                 case 16:
1340                         /* Control-p -- Get previous command from history */
1341                         if (cur_history > 0) {
1342                                 get_previous_history();
1343                                 goto rewrite_line;
1344                         } else {
1345                                 beep();
1346                         }
1347                         break;
1348 #endif
1349                 case 21:
1350                         /* Control-U -- Clear line before cursor */
1351                         if (cursor) {
1352                                 strcpy(command, command + cursor);
1353                                 redraw(cmdedit_y, len -= cursor);
1354                         }
1355                         break;
1356                 case 23:
1357                         /* Control-W -- Remove the last word */
1358                         while (cursor > 0 && isspace(command[cursor-1]))
1359                                 input_backspace();
1360                         while (cursor > 0 &&!isspace(command[cursor-1]))
1361                                 input_backspace();
1362                         break;
1363                 case ESC:{
1364                         /* escape sequence follows */
1365                         if (safe_read(0, &c, 1) < 1)
1366                                 goto prepare_to_die;
1367                         /* different vt100 emulations */
1368                         if (c == '[' || c == 'O') {
1369                                 if (safe_read(0, &c, 1) < 1)
1370                                         goto prepare_to_die;
1371                         }
1372                         switch (c) {
1373 #ifdef CONFIG_FEATURE_COMMAND_TAB_COMPLETION
1374                         case '\t':                      /* Alt-Tab */
1375
1376                                 input_tab(&lastWasTab);
1377                                 break;
1378 #endif
1379 #if MAX_HISTORY >= 1
1380                         case 'A':
1381                                 /* Up Arrow -- Get previous command from history */
1382                                 if (cur_history > 0) {
1383                                         get_previous_history();
1384                                         goto rewrite_line;
1385                                 } else {
1386                                         beep();
1387                                 }
1388                                 break;
1389                         case 'B':
1390                                 /* Down Arrow -- Get next command in history */
1391                                 if (!get_next_history())
1392                                 break;
1393                                 /* Rewrite the line with the selected history item */
1394 rewrite_line:
1395                                 /* change command */
1396                                 len = strlen(strcpy(command, history[cur_history]));
1397                                 /* redraw and go to end line */
1398                                 redraw(cmdedit_y, 0);
1399                                 break;
1400 #endif
1401                         case 'C':
1402                                 /* Right Arrow -- Move forward one character */
1403                                 input_forward();
1404                                 break;
1405                         case 'D':
1406                                 /* Left Arrow -- Move back one character */
1407                                 input_backward(1);
1408                                 break;
1409                         case '3':
1410                                 /* Delete */
1411                                 input_delete();
1412                                 break;
1413                         case '1':
1414                         case 'H':
1415                                 /* Home (Ctrl-A) */
1416                                 input_backward(cursor);
1417                                 break;
1418                         case '4':
1419                         case 'F':
1420                                 /* End (Ctrl-E) */
1421                                 input_end();
1422                                 break;
1423                         default:
1424                                 if (!(c >= '1' && c <= '9'))
1425                                         c = 0;
1426                                 beep();
1427                         }
1428                         if (c >= '1' && c <= '9')
1429                                 do
1430                                         if (safe_read(0, &c, 1) < 1)
1431                                                 goto prepare_to_die;
1432                                 while (c != '~');
1433                         break;
1434                 }
1435
1436                 default:        /* If it's regular input, do the normal thing */
1437 #ifdef CONFIG_FEATURE_NONPRINTABLE_INVERSE_PUT
1438                         /* Control-V -- Add non-printable symbol */
1439                         if (c == 22) {
1440                                 if (safe_read(0, &c, 1) < 1)
1441                                         goto prepare_to_die;
1442                                 if (c == 0) {
1443                                         beep();
1444                                         break;
1445                                 }
1446                         } else
1447 #endif
1448                         if (!Isprint(c))        /* Skip non-printable characters */
1449                                 break;
1450
1451                         if (len >= (BUFSIZ - 2))        /* Need to leave space for enter */
1452                                 break;
1453
1454                         len++;
1455
1456                         if (cursor == (len - 1)) {      /* Append if at the end of the line */
1457                                 *(command + cursor) = c;
1458                                 *(command + cursor + 1) = 0;
1459                                 cmdedit_set_out_char(0);
1460                         } else {                        /* Insert otherwise */
1461                                 int sc = cursor;
1462
1463                                 memmove(command + sc + 1, command + sc, len - sc);
1464                                 *(command + sc) = c;
1465                                 sc++;
1466                                 /* rewrite from cursor */
1467                                 input_end();
1468                                 /* to prev x pos + 1 */
1469                                 input_backward(cursor - sc);
1470                         }
1471
1472                         break;
1473                 }
1474                 if (break_out)                  /* Enter is the command terminator, no more input. */
1475                         break;
1476
1477                 if (c != '\t')
1478                         lastWasTab = FALSE;
1479         }
1480
1481         setTermSettings(0, (void *) &initial_settings);
1482         handlers_sets &= ~SET_RESET_TERM;
1483
1484 #if MAX_HISTORY >= 1
1485         /* Handle command history log */
1486         /* cleanup may be saved current command line */
1487         free(history[MAX_HISTORY]);
1488         history[MAX_HISTORY] = 0;
1489         if (len) {                                      /* no put empty line */
1490                 int i = n_history;
1491                         /* After max history, remove the oldest command */
1492                 if (i >= MAX_HISTORY) {
1493                         free(history[0]);
1494                         for(i = 0; i < (MAX_HISTORY-1); i++)
1495                                 history[i] = history[i+1];
1496                 }
1497                 history[i++] = bb_xstrdup(command);
1498                 cur_history = i;
1499                 n_history = i;
1500 #if defined(CONFIG_FEATURE_SH_FANCY_PROMPT)
1501                 num_ok_lines++;
1502 #endif
1503         }
1504 #else  /* MAX_HISTORY < 1 */
1505 #if defined(CONFIG_FEATURE_SH_FANCY_PROMPT)
1506         if (len) {              /* no put empty line */
1507                 num_ok_lines++;
1508         }
1509 #endif
1510 #endif  /* MAX_HISTORY >= 1 */
1511         if (break_out > 0) {
1512                 command[len++] = '\n';          /* set '\n' */
1513                 command[len] = 0;
1514         }
1515 #if defined(CONFIG_FEATURE_CLEAN_UP) && defined(CONFIG_FEATURE_COMMAND_TAB_COMPLETION)
1516         input_tab(0);                           /* strong free */
1517 #endif
1518 #if defined(CONFIG_FEATURE_SH_FANCY_PROMPT)
1519         free(cmdedit_prompt);
1520 #endif
1521         cmdedit_reset_term();
1522         return len;
1523 }
1524
1525
1526
1527 #endif  /* CONFIG_FEATURE_COMMAND_EDITING */
1528
1529
1530 #ifdef TEST
1531
1532 const char *bb_applet_name = "debug stuff usage";
1533
1534 #ifdef CONFIG_FEATURE_NONPRINTABLE_INVERSE_PUT
1535 #include <locale.h>
1536 #endif
1537
1538 int main(int argc, char **argv)
1539 {
1540         char buff[BUFSIZ];
1541         char *prompt =
1542 #if defined(CONFIG_FEATURE_SH_FANCY_PROMPT)
1543                 "\\[\\033[32;1m\\]\\u@\\[\\x1b[33;1m\\]\\h:\
1544 \\[\\033[34;1m\\]\\w\\[\\033[35;1m\\] \
1545 \\!\\[\\e[36;1m\\]\\$ \\[\\E[0m\\]";
1546 #else
1547                 "% ";
1548 #endif
1549
1550 #ifdef CONFIG_FEATURE_NONPRINTABLE_INVERSE_PUT
1551         setlocale(LC_ALL, "");
1552 #endif
1553         while(1) {
1554                 int l;
1555                 l = cmdedit_read_input(prompt, buff);
1556                 if(l > 0 && buff[l-1] == '\n') {
1557                         buff[l-1] = 0;
1558                         printf("*** cmdedit_read_input() returned line =%s=\n", buff);
1559                 } else {
1560                         break;
1561                 }
1562         }
1563         printf("*** cmdedit_read_input() detect ^D\n");
1564         return 0;
1565 }
1566
1567 #endif  /* TEST */