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