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