Update a bunch of docs. Run a script to update my email addr.
[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-2001 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 /* It seems that libc5 doesn't know what a sighandler_t is... */
167 #if (__GLIBC__ <= 2) && (__GLIBC_MINOR__ < 1)
168 typedef void (*sighandler_t) (int);
169 #endif
170
171 static void cmdedit_setwidth(int w, int redraw_flg);
172
173 static void win_changed(int nsig)
174 {
175         struct winsize win = { 0, 0, 0, 0 };
176         static sighandler_t previous_SIGWINCH_handler;  /* for reset */
177
178         /*   emulate      || signal call */
179         if (nsig == -SIGWINCH || nsig == SIGWINCH) {
180                 ioctl(0, TIOCGWINSZ, &win);
181                 if (win.ws_col > 0) {
182                         cmdedit_setwidth(win.ws_col, nsig == SIGWINCH);
183                 } 
184         }
185         /* Unix not all standart in recall signal */
186
187         if (nsig == -SIGWINCH)          /* save previous handler   */
188                 previous_SIGWINCH_handler = signal(SIGWINCH, win_changed);
189         else if (nsig == SIGWINCH)      /* signaled called handler */
190                 signal(SIGWINCH, win_changed);  /* set for next call       */
191         else                                            /* nsig == 0 */
192                 /* set previous handler    */
193                 signal(SIGWINCH, previous_SIGWINCH_handler);    /* reset    */
194 }
195
196 static void cmdedit_reset_term(void)
197 {
198         if ((handlers_sets & SET_RESET_TERM) != 0) {
199 /* sparc and other have broken termios support: use old termio handling. */
200                 setTermSettings(fileno(stdin), (void *) &initial_settings);
201                 handlers_sets &= ~SET_RESET_TERM;
202         }
203         if ((handlers_sets & SET_WCHG_HANDLERS) != 0) {
204                 /* reset SIGWINCH handler to previous (default) */
205                 win_changed(0);
206                 handlers_sets &= ~SET_WCHG_HANDLERS;
207         }
208         fflush(stdout);
209 }
210
211
212 /* special for recount position for scroll and remove terminal margin effect */
213 static void cmdedit_set_out_char(int next_char)
214 {
215
216         int c = (int)((unsigned char) command_ps[cursor]);
217
218         if (c == 0)
219                 c = ' ';        /* destroy end char? */
220 #ifdef CONFIG_FEATURE_NONPRINTABLE_INVERSE_PUT
221         if (!Isprint(c)) {      /* Inverse put non-printable characters */
222                 if (c >= 128)
223                         c -= 128;
224                 if (c < ' ')
225                         c += '@';
226                 if (c == 127)
227                         c = '?';
228                 printf("\033[7m%c\033[0m", c);
229         } else
230 #endif
231                 putchar(c);
232         if (++cmdedit_x >= cmdedit_termw) {
233                 /* terminal is scrolled down */
234                 cmdedit_y++;
235                 cmdedit_x = 0;
236
237                 if (!next_char)
238                         next_char = ' ';
239                 /* destroy "(auto)margin" */
240                 putchar(next_char);
241                 putchar('\b');
242         }
243         cursor++;
244 }
245
246 /* Move to end line. Bonus: rewrite line from cursor */
247 static void input_end(void)
248 {
249         while (cursor < len)
250                 cmdedit_set_out_char(0);
251 }
252
253 /* Go to the next line */
254 static void goto_new_line(void)
255 {
256         input_end();
257         if (cmdedit_x)
258                 putchar('\n');
259 }
260
261
262 static inline void out1str(const char *s)
263 {
264         if ( s )
265                 fputs(s, stdout);
266 }
267 static inline void beep(void)
268 {
269         putchar('\007');
270 }
271
272 /* Move back one charactor */
273 /* special for slow terminal */
274 static void input_backward(int num)
275 {
276         if (num > cursor)
277                 num = cursor;
278         cursor -= num;          /* new cursor (in command, not terminal) */
279
280         if (cmdedit_x >= num) {         /* no to up line */
281                 cmdedit_x -= num;
282                 if (num < 4)
283                         while (num-- > 0)
284                                 putchar('\b');
285
286                 else
287                         printf("\033[%dD", num);
288         } else {
289                 int count_y;
290
291                 if (cmdedit_x) {
292                         putchar('\r');          /* back to first terminal pos.  */
293                         num -= cmdedit_x;       /* set previous backward        */
294                 }
295                 count_y = 1 + num / cmdedit_termw;
296                 printf("\033[%dA", count_y);
297                 cmdedit_y -= count_y;
298                 /*  require  forward  after  uping   */
299                 cmdedit_x = cmdedit_termw * count_y - num;
300                 printf("\033[%dC", cmdedit_x);  /* set term cursor   */
301         }
302 }
303
304 static void put_prompt(void)
305 {
306         out1str(cmdedit_prompt);
307         cmdedit_x = cmdedit_prmt_len;   /* count real x terminal position */
308         cursor = 0;
309         cmdedit_y = 0;                  /* new quasireal y */
310 }
311
312 #ifndef CONFIG_FEATURE_SH_FANCY_PROMPT
313 static void parse_prompt(const char *prmt_ptr)
314 {
315         cmdedit_prompt = prmt_ptr;
316         cmdedit_prmt_len = strlen(prmt_ptr);
317         put_prompt();
318 }
319 #else
320 static void parse_prompt(const char *prmt_ptr)
321 {
322         int prmt_len = 0;
323         int sub_len = 0;
324         char  flg_not_length = '[';
325         char *prmt_mem_ptr = xcalloc(1, 1);
326         char *pwd_buf = xgetcwd(0);
327         char  buf2[PATH_MAX + 1];
328         char  buf[2];
329         char  c;
330         char *pbuf;
331
332         if (!pwd_buf) {
333                 pwd_buf=(char *)bb_msg_unknown;
334         }
335
336         while (*prmt_ptr) {
337                 pbuf    = buf;
338                 pbuf[1] = 0;
339                 c = *prmt_ptr++;
340                 if (c == '\\') {
341                         const char *cp = prmt_ptr;
342                         int l;
343                         
344                         c = bb_process_escape_sequence(&prmt_ptr);
345                         if(prmt_ptr==cp) {
346                           if (*cp == 0)
347                                 break;
348                           c = *prmt_ptr++;
349                           switch (c) {
350 #ifdef CONFIG_FEATURE_GETUSERNAME_AND_HOMEDIR
351                           case 'u':
352                                 pbuf = user_buf;
353                                 break;
354 #endif  
355                           case 'h':
356                                 pbuf = hostname_buf;
357                                 if (pbuf == 0) {
358                                         pbuf = xcalloc(256, 1);
359                                         if (gethostname(pbuf, 255) < 0) {
360                                                 strcpy(pbuf, "?");
361                                         } else {
362                                                 char *s = strchr(pbuf, '.');
363
364                                                 if (s)
365                                                         *s = 0;
366                                         }
367                                         hostname_buf = pbuf;
368                                 }
369                                 break;
370                           case '$':
371                                 c = my_euid == 0 ? '#' : '$';
372                                 break;
373 #ifdef CONFIG_FEATURE_GETUSERNAME_AND_HOMEDIR
374                           case 'w':
375                                 pbuf = pwd_buf;
376                                 l = strlen(home_pwd_buf);
377                                 if (home_pwd_buf[0] != 0 &&
378                                     strncmp(home_pwd_buf, pbuf, l) == 0 &&
379                                     (pbuf[l]=='/' || pbuf[l]=='\0') &&
380                                     strlen(pwd_buf+l)<PATH_MAX) {
381                                         pbuf = buf2;
382                                         *pbuf = '~';
383                                         strcpy(pbuf+1, pwd_buf+l);
384                                         }
385                                 break;
386 #endif  
387                           case 'W':
388                                 pbuf = pwd_buf;
389                                 cp = strrchr(pbuf,'/');
390                                 if ( (cp != NULL) && (cp != pbuf) )
391                                         pbuf += (cp-pbuf)+1;
392                                 break;
393                           case '!':
394                                 snprintf(pbuf = buf2, sizeof(buf2), "%d", num_ok_lines);
395                                 break;
396                           case 'e': case 'E':     /* \e \E = \033 */
397                                 c = '\033';
398                                 break;
399                           case 'x': case 'X': 
400                                 for (l = 0; l < 3;) {
401                                         int h;
402                                         buf2[l++] = *prmt_ptr;
403                                         buf2[l] = 0;
404                                         h = strtol(buf2, &pbuf, 16);
405                                         if (h > UCHAR_MAX || (pbuf - buf2) < l) {
406                                                 l--;
407                                                 break;
408                                         }
409                                         prmt_ptr++;
410                                 }
411                                 buf2[l] = 0;
412                                 c = (char)strtol(buf2, 0, 16);
413                                 if(c==0)
414                                         c = '?';
415                                 pbuf = buf;
416                                 break;
417                           case '[': case ']':
418                                 if (c == flg_not_length) {
419                                         flg_not_length = flg_not_length == '[' ? ']' : '[';
420                                         continue;
421                                 }
422                                 break;
423                           }
424                         } 
425                 }
426                 if(pbuf == buf)
427                         *pbuf = c;
428                 prmt_len += strlen(pbuf);
429                 prmt_mem_ptr = strcat(xrealloc(prmt_mem_ptr, prmt_len+1), pbuf);
430                 if (flg_not_length == ']')
431                         sub_len++;
432         }
433         if(pwd_buf!=(char *)bb_msg_unknown)
434                 free(pwd_buf);
435         cmdedit_prompt = prmt_mem_ptr;
436         cmdedit_prmt_len = prmt_len - sub_len;
437         put_prompt();
438 }
439 #endif
440
441
442 /* draw promt, editor line, and clear tail */
443 static void redraw(int y, int back_cursor)
444 {
445         if (y > 0)                              /* up to start y */
446                 printf("\033[%dA", y);
447         putchar('\r');
448         put_prompt();
449         input_end();                            /* rewrite */
450         printf("\033[J");                       /* destroy tail after cursor */
451         input_backward(back_cursor);
452 }
453
454 /* Delete the char in front of the cursor */
455 static void input_delete(void)
456 {
457         int j = cursor;
458
459         if (j == len)
460                 return;
461
462         strcpy(command_ps + j, command_ps + j + 1);
463         len--;
464         input_end();                    /* rewtite new line */
465         cmdedit_set_out_char(0);        /* destroy end char */
466         input_backward(cursor - j);     /* back to old pos cursor */
467 }
468
469 /* Delete the char in back of the cursor */
470 static void input_backspace(void)
471 {
472         if (cursor > 0) {
473                 input_backward(1);
474                 input_delete();
475         }
476 }
477
478
479 /* Move forward one charactor */
480 static void input_forward(void)
481 {
482         if (cursor < len)
483                 cmdedit_set_out_char(command_ps[cursor + 1]);
484 }
485
486
487 static void cmdedit_setwidth(int w, int redraw_flg)
488 {
489         cmdedit_termw = cmdedit_prmt_len + 2;
490         if (w <= cmdedit_termw) {
491                 cmdedit_termw = cmdedit_termw % w;
492         }
493         if (w > cmdedit_termw) {
494                 cmdedit_termw = w;
495
496                 if (redraw_flg) {
497                         /* new y for current cursor */
498                         int new_y = (cursor + cmdedit_prmt_len) / w;
499
500                         /* redraw */
501                         redraw((new_y >= cmdedit_y ? new_y : cmdedit_y), len - cursor);
502                         fflush(stdout);
503                 }
504         } 
505 }
506
507 static void cmdedit_init(void)
508 {
509         cmdedit_prmt_len = 0;
510         if ((handlers_sets & SET_WCHG_HANDLERS) == 0) {
511                 /* emulate usage handler to set handler and call yours work */
512                 win_changed(-SIGWINCH);
513                 handlers_sets |= SET_WCHG_HANDLERS;
514         }
515
516         if ((handlers_sets & SET_ATEXIT) == 0) {
517 #ifdef CONFIG_FEATURE_GETUSERNAME_AND_HOMEDIR
518                 struct passwd *entry;
519
520                 my_euid = geteuid();
521                 entry = getpwuid(my_euid);
522                 if (entry) {
523                         user_buf = bb_xstrdup(entry->pw_name);
524                         home_pwd_buf = bb_xstrdup(entry->pw_dir);
525                 }
526 #endif
527
528 #ifdef  CONFIG_FEATURE_COMMAND_TAB_COMPLETION
529
530 #ifndef CONFIG_FEATURE_GETUSERNAME_AND_HOMEDIR
531                 my_euid = geteuid();
532 #endif
533                 my_uid = getuid();
534                 my_gid = getgid();
535 #endif  /* CONFIG_FEATURE_COMMAND_TAB_COMPLETION */
536                 handlers_sets |= SET_ATEXIT;
537                 atexit(cmdedit_reset_term);     /* be sure to do this only once */
538         }
539 }
540
541 #ifdef CONFIG_FEATURE_COMMAND_TAB_COMPLETION
542
543 static int is_execute(const struct stat *st)
544 {
545         if ((!my_euid && (st->st_mode & (S_IXUSR | S_IXGRP | S_IXOTH))) ||
546                 (my_uid == st->st_uid && (st->st_mode & S_IXUSR)) ||
547                 (my_gid == st->st_gid && (st->st_mode & S_IXGRP)) ||
548                 (st->st_mode & S_IXOTH)) return TRUE;
549         return FALSE;
550 }
551
552 #ifdef CONFIG_FEATURE_COMMAND_USERNAME_COMPLETION
553
554 static char **username_tab_completion(char *ud, int *num_matches)
555 {
556         struct passwd *entry;
557         int userlen;
558         char *temp;
559
560
561         ud++;                           /* ~user/... to user/... */
562         userlen = strlen(ud);
563
564         if (num_matches == 0) {         /* "~/..." or "~user/..." */
565                 char *sav_ud = ud - 1;
566                 char *home = 0;
567
568                 if (*ud == '/') {       /* "~/..."     */
569                         home = home_pwd_buf;
570                 } else {
571                         /* "~user/..." */
572                         temp = strchr(ud, '/');
573                         *temp = 0;              /* ~user\0 */
574                         entry = getpwnam(ud);
575                         *temp = '/';            /* restore ~user/... */
576                         ud = temp;
577                         if (entry)
578                                 home = entry->pw_dir;
579                 }
580                 if (home) {
581                         if ((userlen + strlen(home) + 1) < BUFSIZ) {
582                                 char temp2[BUFSIZ];     /* argument size */
583
584                                 /* /home/user/... */
585                                 sprintf(temp2, "%s%s", home, ud);
586                                 strcpy(sav_ud, temp2);
587                         }
588                 }
589                 return 0;       /* void, result save to argument :-) */
590         } else {
591                 /* "~[^/]*" */
592                 char **matches = (char **) NULL;
593                 int nm = 0;
594
595                 setpwent();
596
597                 while ((entry = getpwent()) != NULL) {
598                         /* Null usernames should result in all users as possible completions. */
599                         if ( /*!userlen || */ !strncmp(ud, entry->pw_name, userlen)) {
600
601                                bb_xasprintf(&temp, "~%s/", entry->pw_name);
602                                 matches = xrealloc(matches, (nm + 1) * sizeof(char *));
603
604                                 matches[nm++] = temp;
605                         }
606                 }
607
608                 endpwent();
609                 (*num_matches) = nm;
610                 return (matches);
611         }
612 }
613 #endif  /* CONFIG_FEATURE_COMMAND_USERNAME_COMPLETION */
614
615 enum {
616         FIND_EXE_ONLY = 0,
617         FIND_DIR_ONLY = 1,
618         FIND_FILE_ONLY = 2,
619 };
620
621 static int path_parse(char ***p, int flags)
622 {
623         int npth;
624         char *tmp;
625         char *pth;
626
627         /* if not setenv PATH variable, to search cur dir "." */
628         if (flags != FIND_EXE_ONLY || (pth = getenv("PATH")) == 0 ||
629                 /* PATH=<empty> or PATH=:<empty> */
630                 *pth == 0 || (*pth == ':' && *(pth + 1) == 0)) {
631                 return 1;
632         }
633
634         tmp = pth;
635         npth = 0;
636
637         for (;;) {
638                 npth++;                 /* count words is + 1 count ':' */
639                 tmp = strchr(tmp, ':');
640                 if (tmp) {
641                         if (*++tmp == 0)
642                                 break;  /* :<empty> */
643                 } else
644                         break;
645         }
646
647         *p = xmalloc(npth * sizeof(char *));
648
649         tmp = pth;
650         (*p)[0] = bb_xstrdup(tmp);
651         npth = 1;                       /* count words is + 1 count ':' */
652
653         for (;;) {
654                 tmp = strchr(tmp, ':');
655                 if (tmp) {
656                         (*p)[0][(tmp - pth)] = 0;       /* ':' -> '\0' */
657                         if (*++tmp == 0)
658                                 break;                  /* :<empty> */
659                 } else
660                         break;
661                 (*p)[npth++] = &(*p)[0][(tmp - pth)];   /* p[next]=p[0][&'\0'+1] */
662         }
663
664         return npth;
665 }
666
667 static char *add_quote_for_spec_chars(char *found)
668 {
669         int l = 0;
670         char *s = xmalloc((strlen(found) + 1) * 2);
671
672         while (*found) {
673                 if (strchr(" `\"#$%^&*()=+{}[]:;\'|\\<>", *found))
674                         s[l++] = '\\';
675                 s[l++] = *found++;
676         }
677         s[l] = 0;
678         return s;
679 }
680
681 static char **exe_n_cwd_tab_completion(char *command, int *num_matches,
682                                         int type)
683 {
684
685         char **matches = 0;
686         DIR *dir;
687         struct dirent *next;
688         char dirbuf[BUFSIZ];
689         int nm = *num_matches;
690         struct stat st;
691         char *path1[1];
692         char **paths = path1;
693         int npaths;
694         int i;
695         char *found;
696         char *pfind = strrchr(command, '/');
697
698         path1[0] = ".";
699
700         if (pfind == NULL) {
701                 /* no dir, if flags==EXE_ONLY - get paths, else "." */
702                 npaths = path_parse(&paths, type);
703                 pfind = command;
704         } else {
705                 /* with dir */
706                 /* save for change */
707                 strcpy(dirbuf, command);
708                 /* set dir only */
709                 dirbuf[(pfind - command) + 1] = 0;
710 #ifdef CONFIG_FEATURE_COMMAND_USERNAME_COMPLETION
711                 if (dirbuf[0] == '~')   /* ~/... or ~user/... */
712                         username_tab_completion(dirbuf, 0);
713 #endif
714                 /* "strip" dirname in command */
715                 pfind++;
716
717                 paths[0] = dirbuf;
718                 npaths = 1;                             /* only 1 dir */
719         }
720
721         for (i = 0; i < npaths; i++) {
722
723                 dir = opendir(paths[i]);
724                 if (!dir)                       /* Don't print an error */
725                         continue;
726
727                 while ((next = readdir(dir)) != NULL) {
728                         char *str_found = next->d_name;
729
730                         /* matched ? */
731                         if (strncmp(str_found, pfind, strlen(pfind)))
732                                 continue;
733                         /* not see .name without .match */
734                         if (*str_found == '.' && *pfind == 0) {
735                                 if (*paths[i] == '/' && paths[i][1] == 0
736                                         && str_found[1] == 0) str_found = "";   /* only "/" */
737                                 else
738                                         continue;
739                         }
740                         found = concat_path_file(paths[i], str_found);
741                         /* hmm, remover in progress? */
742                         if (stat(found, &st) < 0) 
743                                 goto cont;
744                         /* find with dirs ? */
745                         if (paths[i] != dirbuf)
746                                 strcpy(found, next->d_name);    /* only name */
747                         if (S_ISDIR(st.st_mode)) {
748                                 /* name is directory      */
749                                 str_found = found;
750                                 found = concat_path_file(found, "");
751                                 free(str_found);
752                                 str_found = add_quote_for_spec_chars(found);
753                         } else {
754                                 /* not put found file if search only dirs for cd */
755                                 if (type == FIND_DIR_ONLY) 
756                                         goto cont;
757                                 str_found = add_quote_for_spec_chars(found);
758                                 if (type == FIND_FILE_ONLY ||
759                                         (type == FIND_EXE_ONLY && is_execute(&st)))
760                                         strcat(str_found, " ");
761                         }
762                         /* Add it to the list */
763                         matches = xrealloc(matches, (nm + 1) * sizeof(char *));
764
765                         matches[nm++] = str_found;
766 cont:
767                         free(found);
768                 }
769                 closedir(dir);
770         }
771         if (paths != path1) {
772                 free(paths[0]);                 /* allocated memory only in first member */
773                 free(paths);
774         }
775         *num_matches = nm;
776         return (matches);
777 }
778
779 static int match_compare(const void *a, const void *b)
780 {
781         return strcmp(*(char **) a, *(char **) b);
782 }
783
784
785
786 #define QUOT    (UCHAR_MAX+1)
787
788 #define collapse_pos(is, in) { \
789         memcpy(int_buf+(is), int_buf+(in), (BUFSIZ+1-(is)-(in))*sizeof(int)); \
790         memcpy(pos_buf+(is), pos_buf+(in), (BUFSIZ+1-(is)-(in))*sizeof(int)); }
791
792 static int find_match(char *matchBuf, int *len_with_quotes)
793 {
794         int i, j;
795         int command_mode;
796         int c, c2;
797         int int_buf[BUFSIZ + 1];
798         int pos_buf[BUFSIZ + 1];
799
800         /* set to integer dimension characters and own positions */
801         for (i = 0;; i++) {
802                 int_buf[i] = (int) ((unsigned char) matchBuf[i]);
803                 if (int_buf[i] == 0) {
804                         pos_buf[i] = -1;        /* indicator end line */
805                         break;
806                 } else
807                         pos_buf[i] = i;
808         }
809
810         /* mask \+symbol and convert '\t' to ' ' */
811         for (i = j = 0; matchBuf[i]; i++, j++)
812                 if (matchBuf[i] == '\\') {
813                         collapse_pos(j, j + 1);
814                         int_buf[j] |= QUOT;
815                         i++;
816 #ifdef CONFIG_FEATURE_NONPRINTABLE_INVERSE_PUT
817                         if (matchBuf[i] == '\t')        /* algorithm equivalent */
818                                 int_buf[j] = ' ' | QUOT;
819 #endif
820                 }
821 #ifdef CONFIG_FEATURE_NONPRINTABLE_INVERSE_PUT
822                 else if (matchBuf[i] == '\t')
823                         int_buf[j] = ' ';
824 #endif
825
826         /* mask "symbols" or 'symbols' */
827         c2 = 0;
828         for (i = 0; int_buf[i]; i++) {
829                 c = int_buf[i];
830                 if (c == '\'' || c == '"') {
831                         if (c2 == 0)
832                                 c2 = c;
833                         else {
834                                 if (c == c2)
835                                         c2 = 0;
836                                 else
837                                         int_buf[i] |= QUOT;
838                         }
839                 } else if (c2 != 0 && c != '$')
840                         int_buf[i] |= QUOT;
841         }
842
843         /* skip commands with arguments if line have commands delimiters */
844         /* ';' ';;' '&' '|' '&&' '||' but `>&' `<&' `>|' */
845         for (i = 0; int_buf[i]; i++) {
846                 c = int_buf[i];
847                 c2 = int_buf[i + 1];
848                 j = i ? int_buf[i - 1] : -1;
849                 command_mode = 0;
850                 if (c == ';' || c == '&' || c == '|') {
851                         command_mode = 1 + (c == c2);
852                         if (c == '&') {
853                                 if (j == '>' || j == '<')
854                                         command_mode = 0;
855                         } else if (c == '|' && j == '>')
856                                 command_mode = 0;
857                 }
858                 if (command_mode) {
859                         collapse_pos(0, i + command_mode);
860                         i = -1;                         /* hack incremet */
861                 }
862         }
863         /* collapse `command...` */
864         for (i = 0; int_buf[i]; i++)
865                 if (int_buf[i] == '`') {
866                         for (j = i + 1; int_buf[j]; j++)
867                                 if (int_buf[j] == '`') {
868                                         collapse_pos(i, j + 1);
869                                         j = 0;
870                                         break;
871                                 }
872                         if (j) {
873                                 /* not found close ` - command mode, collapse all previous */
874                                 collapse_pos(0, i + 1);
875                                 break;
876                         } else
877                                 i--;                    /* hack incremet */
878                 }
879
880         /* collapse (command...(command...)...) or {command...{command...}...} */
881         c = 0;                                          /* "recursive" level */
882         c2 = 0;
883         for (i = 0; int_buf[i]; i++)
884                 if (int_buf[i] == '(' || int_buf[i] == '{') {
885                         if (int_buf[i] == '(')
886                                 c++;
887                         else
888                                 c2++;
889                         collapse_pos(0, i + 1);
890                         i = -1;                         /* hack incremet */
891                 }
892         for (i = 0; pos_buf[i] >= 0 && (c > 0 || c2 > 0); i++)
893                 if ((int_buf[i] == ')' && c > 0) || (int_buf[i] == '}' && c2 > 0)) {
894                         if (int_buf[i] == ')')
895                                 c--;
896                         else
897                                 c2--;
898                         collapse_pos(0, i + 1);
899                         i = -1;                         /* hack incremet */
900                 }
901
902         /* skip first not quote space */
903         for (i = 0; int_buf[i]; i++)
904                 if (int_buf[i] != ' ')
905                         break;
906         if (i)
907                 collapse_pos(0, i);
908
909         /* set find mode for completion */
910         command_mode = FIND_EXE_ONLY;
911         for (i = 0; int_buf[i]; i++)
912                 if (int_buf[i] == ' ' || int_buf[i] == '<' || int_buf[i] == '>') {
913                         if (int_buf[i] == ' ' && command_mode == FIND_EXE_ONLY
914                                 && matchBuf[pos_buf[0]]=='c'
915                                 && matchBuf[pos_buf[1]]=='d' )
916                                 command_mode = FIND_DIR_ONLY;
917                         else {
918                                 command_mode = FIND_FILE_ONLY;
919                                 break;
920                         }
921                 }
922         /* "strlen" */
923         for (i = 0; int_buf[i]; i++);
924         /* find last word */
925         for (--i; i >= 0; i--) {
926                 c = int_buf[i];
927                 if (c == ' ' || c == '<' || c == '>' || c == '|' || c == '&') {
928                         collapse_pos(0, i + 1);
929                         break;
930                 }
931         }
932         /* skip first not quoted '\'' or '"' */
933         for (i = 0; int_buf[i] == '\'' || int_buf[i] == '"'; i++);
934         /* collapse quote or unquote // or /~ */
935         while ((int_buf[i] & ~QUOT) == '/' && 
936                         ((int_buf[i + 1] & ~QUOT) == '/'
937                          || (int_buf[i + 1] & ~QUOT) == '~')) {
938                 i++;
939         }
940
941         /* set only match and destroy quotes */
942         j = 0;
943         for (c = 0; pos_buf[i] >= 0; i++) {
944                 matchBuf[c++] = matchBuf[pos_buf[i]];
945                 j = pos_buf[i] + 1;
946         }
947         matchBuf[c] = 0;
948         /* old lenght matchBuf with quotes symbols */
949         *len_with_quotes = j ? j - pos_buf[0] : 0;
950
951         return command_mode;
952 }
953
954 /*
955    display by column original ideas from ls applet,
956    very optimize by my :)
957 */
958 static void showfiles(char **matches, int nfiles)
959 {
960         int ncols, row;
961         int column_width = 0;
962         int nrows = nfiles;
963
964         /* find the longest file name-  use that as the column width */
965         for (row = 0; row < nrows; row++) {
966                 int l = strlen(matches[row]);
967
968                 if (column_width < l)
969                         column_width = l;
970         }
971         column_width += 2;              /* min space for columns */
972         ncols = cmdedit_termw / column_width;
973
974         if (ncols > 1) {
975                 nrows /= ncols;
976                 if(nfiles % ncols)
977                         nrows++;        /* round up fractionals */
978                 column_width = -column_width;   /* for printf("%-Ns", ...); */
979         } else {
980                 ncols = 1;
981         }
982         for (row = 0; row < nrows; row++) {
983                 int n = row;
984                 int nc;
985
986                 for(nc = 1; nc < ncols && n+nrows < nfiles; n += nrows, nc++)
987                         printf("%*s", column_width, matches[n]);
988                 printf("%s\n", matches[n]);
989         }
990 }
991
992
993 static void input_tab(int *lastWasTab)
994 {
995         /* Do TAB completion */
996         static int num_matches;
997         static char **matches;
998
999         if (lastWasTab == 0) {          /* free all memory */
1000                 if (matches) {
1001                         while (num_matches > 0)
1002                                 free(matches[--num_matches]);
1003                         free(matches);
1004                         matches = (char **) NULL;
1005                 }
1006                 return;
1007         }
1008         if (! *lastWasTab) {
1009
1010                 char *tmp;
1011                 int len_found;
1012                 char matchBuf[BUFSIZ];
1013                 int find_type;
1014                 int recalc_pos;
1015
1016                 *lastWasTab = TRUE;             /* flop trigger */
1017
1018                 /* Make a local copy of the string -- up
1019                  * to the position of the cursor */
1020                 tmp = strncpy(matchBuf, command_ps, cursor);
1021                 tmp[cursor] = 0;
1022
1023                 find_type = find_match(matchBuf, &recalc_pos);
1024
1025                 /* Free up any memory already allocated */
1026                 input_tab(0);
1027
1028 #ifdef CONFIG_FEATURE_COMMAND_USERNAME_COMPLETION
1029                 /* If the word starts with `~' and there is no slash in the word,
1030                  * then try completing this word as a username. */
1031
1032                 if (matchBuf[0] == '~' && strchr(matchBuf, '/') == 0)
1033                         matches = username_tab_completion(matchBuf, &num_matches);
1034 #endif
1035                 /* Try to match any executable in our path and everything
1036                  * in the current working directory that matches.  */
1037                 if (!matches)
1038                         matches =
1039                                 exe_n_cwd_tab_completion(matchBuf,
1040                                         &num_matches, find_type);
1041                 /* Remove duplicate found */
1042                 if(matches) {
1043                         int i, j;
1044                         /* bubble */
1045                         for(i=0; i<(num_matches-1); i++)
1046                                 for(j=i+1; j<num_matches; j++)
1047                                         if(matches[i]!=0 && matches[j]!=0 &&
1048                                                 strcmp(matches[i], matches[j])==0) {
1049                                                         free(matches[j]);
1050                                                         matches[j]=0;
1051                                         }
1052                         j=num_matches;
1053                         num_matches = 0;
1054                         for(i=0; i<j; i++)
1055                                 if(matches[i]) {
1056                                         if(!strcmp(matches[i], "./"))
1057                                                 matches[i][1]=0;
1058                                         else if(!strcmp(matches[i], "../"))
1059                                                 matches[i][2]=0;
1060                                         matches[num_matches++]=matches[i];
1061                                 }
1062                 }
1063                 /* Did we find exactly one match? */
1064                 if (!matches || num_matches > 1) {
1065                         char *tmp1;
1066
1067                         beep();
1068                         if (!matches)
1069                                 return;         /* not found */
1070                         /* sort */
1071                         qsort(matches, num_matches, sizeof(char *), match_compare);
1072
1073                         /* find minimal match */
1074                         tmp = bb_xstrdup(matches[0]);
1075                         for (tmp1 = tmp; *tmp1; tmp1++)
1076                                 for (len_found = 1; len_found < num_matches; len_found++)
1077                                         if (matches[len_found][(tmp1 - tmp)] != *tmp1) {
1078                                                 *tmp1 = 0;
1079                                                 break;
1080                                         }
1081                         if (*tmp == 0) {        /* have unique */
1082                                 free(tmp);
1083                                 return;
1084                         }
1085                 } else {                        /* one match */
1086                         tmp = matches[0];
1087                         /* for next completion current found */
1088                         *lastWasTab = FALSE;
1089                 }
1090
1091                 len_found = strlen(tmp);
1092                 /* have space to placed match? */
1093                 if ((len_found - strlen(matchBuf) + len) < BUFSIZ) {
1094
1095                         /* before word for match   */
1096                         command_ps[cursor - recalc_pos] = 0;
1097                         /* save   tail line        */
1098                         strcpy(matchBuf, command_ps + cursor);
1099                         /* add    match            */
1100                         strcat(command_ps, tmp);
1101                         /* add    tail             */
1102                         strcat(command_ps, matchBuf);
1103                         /* back to begin word for match    */
1104                         input_backward(recalc_pos);
1105                         /* new pos                         */
1106                         recalc_pos = cursor + len_found;
1107                         /* new len                         */
1108                         len = strlen(command_ps);
1109                         /* write out the matched command   */
1110                         redraw(cmdedit_y, len - recalc_pos);
1111                 }
1112                 if (tmp != matches[0])
1113                         free(tmp);
1114         } else {
1115                 /* Ok -- the last char was a TAB.  Since they
1116                  * just hit TAB again, print a list of all the
1117                  * available choices... */
1118                 if (matches && num_matches > 0) {
1119                         int sav_cursor = cursor;        /* change goto_new_line() */
1120
1121                         /* Go to the next line */
1122                         goto_new_line();
1123                         showfiles(matches, num_matches);
1124                         redraw(0, len - sav_cursor);
1125                 }
1126         }
1127 }
1128 #endif  /* CONFIG_FEATURE_COMMAND_TAB_COMPLETION */
1129
1130 #if MAX_HISTORY >= 1
1131 static void get_previous_history(void)
1132 {
1133         if(command_ps[0] != 0 || history[cur_history] == 0) {
1134                 free(history[cur_history]);
1135                 history[cur_history] = bb_xstrdup(command_ps);
1136         }
1137         cur_history--;
1138 }
1139
1140 static int get_next_history(void)
1141 {
1142         int ch = cur_history;
1143
1144         if (ch < n_history) {
1145                 get_previous_history(); /* save the current history line */
1146                 return (cur_history = ch+1);
1147         } else {
1148                 beep();
1149                 return 0;
1150         }
1151 }
1152
1153 #ifdef CONFIG_FEATURE_COMMAND_SAVEHISTORY
1154 extern void load_history ( const char *fromfile )
1155 {
1156         FILE *fp;
1157         int hi;
1158
1159         /* cleanup old */
1160
1161         for(hi = n_history; hi > 0; ) {
1162                 hi--;
1163                 free ( history [hi] );
1164         }
1165
1166         if (( fp = fopen ( fromfile, "r" ))) {
1167         
1168                 for ( hi = 0; hi < MAX_HISTORY; ) {
1169                         char * hl = bb_get_chomped_line_from_file(fp);
1170                         int l;
1171
1172                         if(!hl)
1173                                 break;
1174                         l = strlen(hl);
1175                         if(l >= BUFSIZ)
1176                                 hl[BUFSIZ-1] = 0;
1177                         if(l == 0 || hl[0] == ' ') {
1178                                 free(hl);
1179                                 continue;
1180                         }
1181                         history [hi++] = hl;
1182                 }
1183                 fclose ( fp );
1184         }
1185         cur_history = n_history = hi;
1186 }
1187
1188 extern void save_history ( const char *tofile )
1189 {
1190         FILE *fp = fopen ( tofile, "w" );
1191         
1192         if ( fp ) {
1193                 int i;
1194                 
1195                 for ( i = 0; i < n_history; i++ ) {
1196                         fputs ( history [i], fp );
1197                         fputc ( '\n', fp );
1198                 }
1199                 fclose ( fp );
1200         }
1201 }
1202 #endif
1203
1204 #endif
1205
1206 enum {
1207         ESC = 27,
1208         DEL = 127,
1209 };
1210
1211
1212 /*
1213  * This function is used to grab a character buffer
1214  * from the input file descriptor and allows you to
1215  * a string with full command editing (sortof like
1216  * a mini readline).
1217  *
1218  * The following standard commands are not implemented:
1219  * ESC-b -- Move back one word
1220  * ESC-f -- Move forward one word
1221  * ESC-d -- Delete back one word
1222  * ESC-h -- Delete forward one word
1223  * CTL-t -- Transpose two characters
1224  *
1225  * Furthermore, the "vi" command editing keys are not implemented.
1226  *
1227  */
1228  
1229
1230 int cmdedit_read_input(char *prompt, char command[BUFSIZ])
1231 {
1232
1233         int break_out = 0;
1234         int lastWasTab = FALSE;
1235         unsigned char c = 0;
1236
1237         /* prepare before init handlers */
1238         cmdedit_y = 0;  /* quasireal y, not true work if line > xt*yt */
1239         len = 0;
1240         command_ps = command;
1241
1242         getTermSettings(0, (void *) &initial_settings);
1243         memcpy(&new_settings, &initial_settings, sizeof(struct termios));
1244         new_settings.c_lflag &= ~ICANON;        /* unbuffered input */
1245         /* Turn off echoing and CTRL-C, so we can trap it */
1246         new_settings.c_lflag &= ~(ECHO | ECHONL | ISIG);
1247 #ifndef linux
1248         /* Hmm, in linux c_cc[] not parsed if set ~ICANON */
1249         new_settings.c_cc[VMIN] = 1;
1250         new_settings.c_cc[VTIME] = 0;
1251         /* Turn off CTRL-C, so we can trap it */
1252 #       ifndef _POSIX_VDISABLE
1253 #               define _POSIX_VDISABLE '\0'
1254 #       endif
1255         new_settings.c_cc[VINTR] = _POSIX_VDISABLE;     
1256 #endif
1257         command[0] = 0;
1258
1259         setTermSettings(0, (void *) &new_settings);
1260         handlers_sets |= SET_RESET_TERM;
1261
1262         /* Now initialize things */
1263         cmdedit_init();
1264         /* Print out the command prompt */
1265         parse_prompt(prompt);
1266
1267         while (1) {
1268
1269                 fflush(stdout);                 /* buffered out to fast */
1270
1271                 if (safe_read(0, &c, 1) < 1)
1272                         /* if we can't read input then exit */
1273                         goto prepare_to_die;
1274
1275                 switch (c) {
1276                 case '\n':
1277                 case '\r':
1278                         /* Enter */
1279                         goto_new_line();
1280                         break_out = 1;
1281                         break;
1282                 case 1:
1283                         /* Control-a -- Beginning of line */
1284                         input_backward(cursor);
1285                         break;
1286                 case 2:
1287                         /* Control-b -- Move back one character */
1288                         input_backward(1);
1289                         break;
1290                 case 3:
1291                         /* Control-c -- stop gathering input */
1292                         goto_new_line();
1293                         command[0] = 0;
1294                         len = 0;
1295                         lastWasTab = FALSE;
1296                         put_prompt();
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>0) {
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         return len;
1528 }
1529
1530
1531
1532 #endif  /* CONFIG_FEATURE_COMMAND_EDITING */
1533
1534
1535 #ifdef TEST
1536
1537 const char *bb_applet_name = "debug stuff usage";
1538 const char *memory_exhausted = "Memory exhausted";
1539
1540 #ifdef CONFIG_FEATURE_NONPRINTABLE_INVERSE_PUT
1541 #include <locale.h>
1542 #endif
1543
1544 int main(int argc, char **argv)
1545 {
1546         char buff[BUFSIZ];
1547         char *prompt =
1548 #if defined(CONFIG_FEATURE_SH_FANCY_PROMPT)
1549                 "\\[\\033[32;1m\\]\\u@\\[\\x1b[33;1m\\]\\h:\
1550 \\[\\033[34;1m\\]\\w\\[\\033[35;1m\\] \
1551 \\!\\[\\e[36;1m\\]\\$ \\[\\E[0m\\]";
1552 #else
1553                 "% ";
1554 #endif
1555
1556 #ifdef CONFIG_FEATURE_NONPRINTABLE_INVERSE_PUT
1557         setlocale(LC_ALL, "");
1558 #endif
1559         while(1) {
1560                 int l;
1561                 cmdedit_read_input(prompt, buff);
1562                 l = strlen(buff);
1563                 if(l==0)
1564                         break;
1565                 if(l > 0 && buff[l-1] == '\n')
1566                         buff[l-1] = 0;
1567                 printf("*** cmdedit_read_input() returned line =%s=\n", buff);
1568         }
1569         printf("*** cmdedit_read_input() detect ^C\n");
1570         return 0;
1571 }
1572
1573 #endif  /* TEST */