cmdedit: fix my bug, improve code a bit
[oweals/busybox.git] / shell / cmdedit.c
1 /* vi: set sw=4 ts=4: */
2 /*
3  * Termios command line History and Editing.
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    Usage and known bugs:
19    Terminal key codes are not extensive, and more will probably
20    need to be added. This version was created on Debian GNU/Linux 2.x.
21    Delete, Backspace, Home, End, and the arrow keys were tested
22    to work in an Xterm and console. Ctrl-A also works as Home.
23    Ctrl-E also works as End.
24
25    Small bugs (simple effect):
26    - not true viewing if terminal size (x*y symbols) less
27      size (prompt + editor`s line + 2 symbols)
28    - not true viewing if length prompt less terminal width
29  */
30
31 #include "busybox.h"
32 #include <sys/ioctl.h>
33
34 #include "cmdedit.h"
35
36
37 #if ENABLE_LOCALE_SUPPORT
38 #define Isprint(c) isprint(c)
39 #else
40 #define Isprint(c) ((c) >= ' ' && (c) != ((unsigned char)'\233'))
41 #endif
42
43
44 /* FIXME: obsolete CONFIG item? */
45 #define ENABLE_FEATURE_NONPRINTABLE_INVERSE_PUT 0
46
47
48 #ifdef TEST
49
50 #define ENABLE_FEATURE_COMMAND_EDITING 0
51 #define ENABLE_FEATURE_COMMAND_TAB_COMPLETION 0
52 #define ENABLE_FEATURE_COMMAND_USERNAME_COMPLETION 0
53 #define ENABLE_FEATURE_NONPRINTABLE_INVERSE_PUT 0
54 #define ENABLE_FEATURE_CLEAN_UP 0
55
56 #endif  /* TEST */
57
58
59 #if ENABLE_FEATURE_COMMAND_EDITING
60
61 #if ENABLE_FEATURE_COMMAND_USERNAME_COMPLETION || ENABLE_FEATURE_SH_FANCY_PROMPT
62 #define ENABLE_FEATURE_GETUSERNAME_AND_HOMEDIR 1
63 #endif
64
65 /* Maximum length of the linked list for the command line history */
66 #if !ENABLE_FEATURE_COMMAND_HISTORY
67 #define MAX_HISTORY   15
68 #else
69 #define MAX_HISTORY   (CONFIG_FEATURE_COMMAND_HISTORY + 0)
70 #endif
71
72 #if MAX_HISTORY > 0
73 static char *history[MAX_HISTORY+1]; /* history + current */
74 /* saved history lines */
75 static int n_history;
76 /* current pointer to history line */
77 static int cur_history;
78 #endif
79
80 //#include <termios.h>
81 #define setTermSettings(fd,argp) tcsetattr(fd,TCSANOW,argp)
82 #define getTermSettings(fd,argp) tcgetattr(fd, argp);
83
84 /* Current termio and the previous termio before starting sh */
85 static struct termios initial_settings, new_settings;
86
87
88 static
89 volatile int cmdedit_termw = 80;        /* actual terminal width */
90 static
91 volatile int handlers_sets = 0; /* Set next bites: */
92
93 enum {
94         SET_ATEXIT = 1,         /* when atexit() has been called
95                                    and get euid,uid,gid to fast compare */
96         SET_WCHG_HANDLERS = 2,  /* winchg signal handler */
97         SET_RESET_TERM = 4,     /* if the terminal needs to be reset upon exit */
98 };
99
100
101 static int cmdedit_x;           /* real x terminal position */
102 static int cmdedit_y;           /* pseudoreal y terminal position */
103 static int cmdedit_prmt_len;    /* lenght prompt without colores string */
104
105 static int cursor;              /* required globals for signal handler */
106 static int len;                 /* --- "" - - "" -- -"- --""-- --""--- */
107 static char *command_ps;        /* --- "" - - "" -- -"- --""-- --""--- */
108 static SKIP_FEATURE_SH_FANCY_PROMPT(const) char *cmdedit_prompt; /* -- */
109
110 #if ENABLE_FEATURE_GETUSERNAME_AND_HOMEDIR
111 static char *user_buf = "";
112 static char *home_pwd_buf = "";
113 static int my_euid;
114 #endif
115
116 #if ENABLE_FEATURE_SH_FANCY_PROMPT
117 static char *hostname_buf;
118 static int num_ok_lines = 1;
119 #endif
120
121
122 #if ENABLE_FEATURE_COMMAND_TAB_COMPLETION
123
124 #if !ENABLE_FEATURE_GETUSERNAME_AND_HOMEDIR
125 static int my_euid;
126 #endif
127
128 static int my_uid;
129 static int my_gid;
130
131 #endif  /* FEATURE_COMMAND_TAB_COMPLETION */
132
133 static void cmdedit_setwidth(int w, int redraw_flg);
134
135 static void win_changed(int nsig)
136 {
137         static sighandler_t previous_SIGWINCH_handler;  /* for reset */
138
139         /*   emulate      || signal call */
140         if (nsig == -SIGWINCH || nsig == SIGWINCH) {
141                 int width = 0;
142                 get_terminal_width_height(0, &width, NULL);
143                 cmdedit_setwidth(width, nsig == SIGWINCH);
144         }
145         /* Unix not all standard in recall signal */
146
147         if (nsig == -SIGWINCH)          /* save previous handler   */
148                 previous_SIGWINCH_handler = signal(SIGWINCH, win_changed);
149         else if (nsig == SIGWINCH)      /* signaled called handler */
150                 signal(SIGWINCH, win_changed);  /* set for next call       */
151         else                                            /* nsig == 0 */
152                 /* set previous handler    */
153                 signal(SIGWINCH, previous_SIGWINCH_handler);    /* reset    */
154 }
155
156 static void cmdedit_reset_term(void)
157 {
158         if ((handlers_sets & SET_RESET_TERM) != 0) {
159 /* sparc and other have broken termios support: use old termio handling. */
160                 setTermSettings(STDIN_FILENO, (void *) &initial_settings);
161                 handlers_sets &= ~SET_RESET_TERM;
162         }
163         if ((handlers_sets & SET_WCHG_HANDLERS) != 0) {
164                 /* reset SIGWINCH handler to previous (default) */
165                 win_changed(0);
166                 handlers_sets &= ~SET_WCHG_HANDLERS;
167         }
168         fflush(stdout);
169 }
170
171
172 /* special for recount position for scroll and remove terminal margin effect */
173 static void cmdedit_set_out_char(int next_char)
174 {
175
176         int c = (int)((unsigned char) command_ps[cursor]);
177
178         if (c == 0)
179                 c = ' ';        /* destroy end char? */
180 #if ENABLE_FEATURE_NONPRINTABLE_INVERSE_PUT
181         if (!Isprint(c)) {      /* Inverse put non-printable characters */
182                 if (c >= 128)
183                         c -= 128;
184                 if (c < ' ')
185                         c += '@';
186                 if (c == 127)
187                         c = '?';
188                 printf("\033[7m%c\033[0m", c);
189         } else
190 #endif
191                 if (initial_settings.c_lflag & ECHO) putchar(c);
192         if (++cmdedit_x >= cmdedit_termw) {
193                 /* terminal is scrolled down */
194                 cmdedit_y++;
195                 cmdedit_x = 0;
196
197                 if (!next_char)
198                         next_char = ' ';
199                 /* destroy "(auto)margin" */
200                 putchar(next_char);
201                 putchar('\b');
202         }
203         cursor++;
204 }
205
206 /* Move to end line. Bonus: rewrite line from cursor */
207 static void input_end(void)
208 {
209         while (cursor < len)
210                 cmdedit_set_out_char(0);
211 }
212
213 /* Go to the next line */
214 static void goto_new_line(void)
215 {
216         input_end();
217         if (cmdedit_x)
218                 putchar('\n');
219 }
220
221
222 static void out1str(const char *s)
223 {
224         if ( s )
225                 fputs(s, stdout);
226 }
227
228 static void beep(void)
229 {
230         putchar('\007');
231 }
232
233 /* Move back one character */
234 /* special for slow terminal */
235 static void input_backward(int num)
236 {
237         if (num > cursor)
238                 num = cursor;
239         cursor -= num;          /* new cursor (in command, not terminal) */
240
241         if (cmdedit_x >= num) {         /* no to up line */
242                 cmdedit_x -= num;
243                 if (num < 4)
244                         while (num-- > 0)
245                                 putchar('\b');
246                 else
247                         printf("\033[%dD", num);
248         } else {
249                 int count_y;
250
251                 if (cmdedit_x) {
252                         putchar('\r');          /* back to first terminal pos.  */
253                         num -= cmdedit_x;       /* set previous backward        */
254                 }
255                 count_y = 1 + num / cmdedit_termw;
256                 printf("\033[%dA", count_y);
257                 cmdedit_y -= count_y;
258                 /*  require  forward  after  uping   */
259                 cmdedit_x = cmdedit_termw * count_y - num;
260                 printf("\033[%dC", cmdedit_x);  /* set term cursor   */
261         }
262 }
263
264 static void put_prompt(void)
265 {
266         out1str(cmdedit_prompt);
267         cmdedit_x = cmdedit_prmt_len;   /* count real x terminal position */
268         cursor = 0;
269         cmdedit_y = 0;                  /* new quasireal y */
270 }
271
272 #if !ENABLE_FEATURE_SH_FANCY_PROMPT
273 static void parse_prompt(const char *prmt_ptr)
274 {
275         cmdedit_prompt = prmt_ptr;
276         cmdedit_prmt_len = strlen(prmt_ptr);
277         put_prompt();
278 }
279 #else
280 static void parse_prompt(const char *prmt_ptr)
281 {
282         int prmt_len = 0;
283         size_t cur_prmt_len = 0;
284         char  flg_not_length = '[';
285         char *prmt_mem_ptr = xzalloc(1);
286         char *pwd_buf = xgetcwd(0);
287         char  buf2[PATH_MAX + 1];
288         char  buf[2];
289         char  c;
290         char *pbuf;
291
292         if (!pwd_buf) {
293                 pwd_buf=(char *)bb_msg_unknown;
294         }
295
296         while (*prmt_ptr) {
297                 pbuf    = buf;
298                 pbuf[1] = 0;
299                 c = *prmt_ptr++;
300                 if (c == '\\') {
301                         const char *cp = prmt_ptr;
302                         int l;
303
304                         c = bb_process_escape_sequence(&prmt_ptr);
305                         if (prmt_ptr==cp) {
306                           if (*cp == 0)
307                                 break;
308                           c = *prmt_ptr++;
309                           switch (c) {
310 #if ENABLE_FEATURE_GETUSERNAME_AND_HOMEDIR
311                           case 'u':
312                                 pbuf = user_buf;
313                                 break;
314 #endif
315                           case 'h':
316                                 pbuf = hostname_buf;
317                                 if (pbuf == 0) {
318                                         pbuf = xzalloc(256);
319                                         if (gethostname(pbuf, 255) < 0) {
320                                                 strcpy(pbuf, "?");
321                                         } else {
322                                                 char *s = strchr(pbuf, '.');
323
324                                                 if (s)
325                                                         *s = 0;
326                                         }
327                                         hostname_buf = pbuf;
328                                 }
329                                 break;
330                           case '$':
331                                 c = my_euid == 0 ? '#' : '$';
332                                 break;
333 #if ENABLE_FEATURE_GETUSERNAME_AND_HOMEDIR
334                           case 'w':
335                                 pbuf = pwd_buf;
336                                 l = strlen(home_pwd_buf);
337                                 if (home_pwd_buf[0] != 0 &&
338                                     strncmp(home_pwd_buf, pbuf, l) == 0 &&
339                                     (pbuf[l]=='/' || pbuf[l]=='\0') &&
340                                     strlen(pwd_buf+l)<PATH_MAX) {
341                                         pbuf = buf2;
342                                         *pbuf = '~';
343                                         strcpy(pbuf+1, pwd_buf+l);
344                                 }
345                                 break;
346 #endif
347                           case 'W':
348                                 pbuf = pwd_buf;
349                                 cp = strrchr(pbuf,'/');
350                                 if ( (cp != NULL) && (cp != pbuf) )
351                                         pbuf += (cp-pbuf)+1;
352                                 break;
353                           case '!':
354                                 snprintf(pbuf = buf2, sizeof(buf2), "%d", num_ok_lines);
355                                 break;
356                           case 'e': case 'E':     /* \e \E = \033 */
357                                 c = '\033';
358                                 break;
359                           case 'x': case 'X':
360                                 for (l = 0; l < 3;) {
361                                         int h;
362                                         buf2[l++] = *prmt_ptr;
363                                         buf2[l] = 0;
364                                         h = strtol(buf2, &pbuf, 16);
365                                         if (h > UCHAR_MAX || (pbuf - buf2) < l) {
366                                                 l--;
367                                                 break;
368                                         }
369                                         prmt_ptr++;
370                                 }
371                                 buf2[l] = 0;
372                                 c = (char)strtol(buf2, 0, 16);
373                                 if (c==0)
374                                         c = '?';
375                                 pbuf = buf;
376                                 break;
377                           case '[': case ']':
378                                 if (c == flg_not_length) {
379                                         flg_not_length = flg_not_length == '[' ? ']' : '[';
380                                         continue;
381                                 }
382                                 break;
383                           }
384                         }
385                 }
386                 if (pbuf == buf)
387                         *pbuf = c;
388                 cur_prmt_len = strlen(pbuf);
389                 prmt_len += cur_prmt_len;
390                 if (flg_not_length != ']')
391                         cmdedit_prmt_len += cur_prmt_len;
392                 prmt_mem_ptr = strcat(xrealloc(prmt_mem_ptr, prmt_len+1), pbuf);
393         }
394         if (pwd_buf!=(char *)bb_msg_unknown)
395                 free(pwd_buf);
396         cmdedit_prompt = prmt_mem_ptr;
397         put_prompt();
398 }
399 #endif
400
401
402 /* draw prompt, editor line, and clear tail */
403 static void redraw(int y, int back_cursor)
404 {
405         if (y > 0)                              /* up to start y */
406                 printf("\033[%dA", y);
407         putchar('\r');
408         put_prompt();
409         input_end();                            /* rewrite */
410         printf("\033[J");                       /* destroy tail after cursor */
411         input_backward(back_cursor);
412 }
413
414 #if ENABLE_FEATURE_COMMAND_EDITING_VI
415 #define DELBUFSIZ 128
416 static char *delbuf;  /* a (malloced) place to store deleted characters */
417 static char *delp;
418 static char newdelflag;      /* whether delbuf should be reused yet */
419 #endif
420
421 /* Delete the char in front of the cursor, optionally saving it
422  * for later putback */
423 static void input_delete(int save)
424 {
425         int j = cursor;
426
427         if (j == len)
428                 return;
429
430 #if ENABLE_FEATURE_COMMAND_EDITING_VI
431         if (save) {
432                 if (newdelflag) {
433                         if (!delbuf)
434                                 delbuf = malloc(DELBUFSIZ);
435                         /* safe if malloc fails */
436                         delp = delbuf;
437                         newdelflag = 0;
438                 }
439                 if (delbuf && (delp - delbuf < DELBUFSIZ))
440                         *delp++ = command_ps[j];
441         }
442 #endif
443
444         strcpy(command_ps + j, command_ps + j + 1);
445         len--;
446         input_end();                    /* rewrite new line */
447         cmdedit_set_out_char(0);        /* destroy end char */
448         input_backward(cursor - j);     /* back to old pos cursor */
449 }
450
451 #if ENABLE_FEATURE_COMMAND_EDITING_VI
452 static void put(void)
453 {
454         int ocursor, j = delp - delbuf;
455         if (j == 0)
456                 return;
457         ocursor = cursor;
458         /* open hole and then fill it */
459         memmove(command_ps + cursor + j, command_ps + cursor, len - cursor + 1);
460         strncpy(command_ps + cursor, delbuf, j);
461         len += j;
462         input_end();                    /* rewrite new line */
463         input_backward(cursor-ocursor-j+1); /* at end of new text */
464 }
465 #endif
466
467 /* Delete the char in back of the cursor */
468 static void input_backspace(void)
469 {
470         if (cursor > 0) {
471                 input_backward(1);
472                 input_delete(0);
473         }
474 }
475
476
477 /* Move forward one character */
478 static void input_forward(void)
479 {
480         if (cursor < len)
481                 cmdedit_set_out_char(command_ps[cursor + 1]);
482 }
483
484 static void cmdedit_setwidth(int w, int redraw_flg)
485 {
486         cmdedit_termw = cmdedit_prmt_len + 2;
487         if (w <= cmdedit_termw) {
488                 cmdedit_termw = cmdedit_termw % w;
489         }
490         if (w > cmdedit_termw) {
491                 cmdedit_termw = w;
492
493                 if (redraw_flg) {
494                         /* new y for current cursor */
495                         int new_y = (cursor + cmdedit_prmt_len) / w;
496
497                         /* redraw */
498                         redraw((new_y >= cmdedit_y ? new_y : cmdedit_y), len - cursor);
499                         fflush(stdout);
500                 }
501         }
502 }
503
504 static void cmdedit_init(void)
505 {
506         cmdedit_prmt_len = 0;
507         if ((handlers_sets & SET_WCHG_HANDLERS) == 0) {
508                 /* emulate usage handler to set handler and call yours work */
509                 win_changed(-SIGWINCH);
510                 handlers_sets |= SET_WCHG_HANDLERS;
511         }
512
513         if ((handlers_sets & SET_ATEXIT) == 0) {
514 #if ENABLE_FEATURE_GETUSERNAME_AND_HOMEDIR
515                 struct passwd *entry;
516
517                 my_euid = geteuid();
518                 entry = getpwuid(my_euid);
519                 if (entry) {
520                         user_buf = xstrdup(entry->pw_name);
521                         home_pwd_buf = xstrdup(entry->pw_dir);
522                 }
523 #endif
524
525 #if ENABLE_FEATURE_COMMAND_TAB_COMPLETION
526
527 #if !ENABLE_FEATURE_GETUSERNAME_AND_HOMEDIR
528                 my_euid = geteuid();
529 #endif
530                 my_uid = getuid();
531                 my_gid = getgid();
532 #endif  /* FEATURE_COMMAND_TAB_COMPLETION */
533                 handlers_sets |= SET_ATEXIT;
534                 atexit(cmdedit_reset_term);     /* be sure to do this only once */
535         }
536 }
537
538 #if ENABLE_FEATURE_COMMAND_TAB_COMPLETION
539
540 static char **matches;
541 static int num_matches;
542 static char *add_char_to_match;
543
544 static void add_match(char *matched, int add_char)
545 {
546         int nm = num_matches;
547         int nm1 = nm + 1;
548
549         matches = xrealloc(matches, nm1 * sizeof(char *));
550         add_char_to_match = xrealloc(add_char_to_match, nm1);
551         matches[nm] = matched;
552         add_char_to_match[nm] = (char)add_char;
553         num_matches++;
554 }
555
556 static int is_execute(const struct stat *st)
557 {
558         if ((!my_euid && (st->st_mode & (S_IXUSR | S_IXGRP | S_IXOTH))) ||
559                 (my_uid == st->st_uid && (st->st_mode & S_IXUSR)) ||
560                 (my_gid == st->st_gid && (st->st_mode & S_IXGRP)) ||
561                 (st->st_mode & S_IXOTH)) return TRUE;
562         return FALSE;
563 }
564
565 #if ENABLE_FEATURE_COMMAND_USERNAME_COMPLETION
566
567 static void username_tab_completion(char *ud, char *with_shash_flg)
568 {
569         struct passwd *entry;
570         int userlen;
571
572         ud++;                           /* ~user/... to user/... */
573         userlen = strlen(ud);
574
575         if (with_shash_flg) {           /* "~/..." or "~user/..." */
576                 char *sav_ud = ud - 1;
577                 char *home = 0;
578                 char *temp;
579
580                 if (*ud == '/') {       /* "~/..."     */
581                         home = home_pwd_buf;
582                 } else {
583                         /* "~user/..." */
584                         temp = strchr(ud, '/');
585                         *temp = 0;              /* ~user\0 */
586                         entry = getpwnam(ud);
587                         *temp = '/';            /* restore ~user/... */
588                         ud = temp;
589                         if (entry)
590                                 home = entry->pw_dir;
591                 }
592                 if (home) {
593                         if ((userlen + strlen(home) + 1) < BUFSIZ) {
594                                 char temp2[BUFSIZ];     /* argument size */
595
596                                 /* /home/user/... */
597                                 sprintf(temp2, "%s%s", home, ud);
598                                 strcpy(sav_ud, temp2);
599                         }
600                 }
601         } else {
602                 /* "~[^/]*" */
603                 setpwent();
604
605                 while ((entry = getpwent()) != NULL) {
606                         /* Null usernames should result in all users as possible completions. */
607                         if ( /*!userlen || */ !strncmp(ud, entry->pw_name, userlen)) {
608                                 add_match(xasprintf("~%s", entry->pw_name), '/');
609                         }
610                 }
611
612                 endpwent();
613         }
614 }
615 #endif  /* FEATURE_COMMAND_USERNAME_COMPLETION */
616
617 enum {
618         FIND_EXE_ONLY = 0,
619         FIND_DIR_ONLY = 1,
620         FIND_FILE_ONLY = 2,
621 };
622
623 #if ENABLE_ASH
624 const char *cmdedit_path_lookup;
625 #else
626 #define cmdedit_path_lookup getenv("PATH")
627 #endif
628
629 static int path_parse(char ***p, int flags)
630 {
631         int npth;
632         const char *tmp;
633         const char *pth;
634
635         /* if not setenv PATH variable, to search cur dir "." */
636         if (flags != FIND_EXE_ONLY || (pth = cmdedit_path_lookup) == 0 ||
637                 /* PATH=<empty> or PATH=:<empty> */
638                 *pth == 0 || (*pth == ':' && *(pth + 1) == 0)) {
639                 return 1;
640         }
641
642         tmp = pth;
643         npth = 0;
644
645         for (;;) {
646                 npth++;                 /* count words is + 1 count ':' */
647                 tmp = strchr(tmp, ':');
648                 if (tmp) {
649                         if (*++tmp == 0)
650                                 break;  /* :<empty> */
651                 } else
652                         break;
653         }
654
655         *p = xmalloc(npth * sizeof(char *));
656
657         tmp = pth;
658         (*p)[0] = xstrdup(tmp);
659         npth = 1;                       /* count words is + 1 count ':' */
660
661         for (;;) {
662                 tmp = strchr(tmp, ':');
663                 if (tmp) {
664                         (*p)[0][(tmp - pth)] = 0;       /* ':' -> '\0' */
665                         if (*++tmp == 0)
666                                 break;                  /* :<empty> */
667                 } else
668                         break;
669                 (*p)[npth++] = &(*p)[0][(tmp - pth)];   /* p[next]=p[0][&'\0'+1] */
670         }
671
672         return npth;
673 }
674
675 static char *add_quote_for_spec_chars(char *found, int add)
676 {
677         int l = 0;
678         char *s = xmalloc((strlen(found) + 1) * 2);
679
680         while (*found) {
681                 if (strchr(" `\"#$%^&*()=+{}[]:;\'|\\<>", *found))
682                         s[l++] = '\\';
683                 s[l++] = *found++;
684         }
685         if (add)
686                 s[l++] = (char)add;
687         s[l] = 0;
688         return s;
689 }
690
691 static void exe_n_cwd_tab_completion(char *command, int type)
692 {
693         DIR *dir;
694         struct dirent *next;
695         char dirbuf[BUFSIZ];
696         struct stat st;
697         char *path1[1];
698         char **paths = path1;
699         int npaths;
700         int i;
701         char *found;
702         char *pfind = strrchr(command, '/');
703
704         path1[0] = ".";
705
706         if (pfind == NULL) {
707                 /* no dir, if flags==EXE_ONLY - get paths, else "." */
708                 npaths = path_parse(&paths, type);
709                 pfind = command;
710         } else {
711                 /* with dir */
712                 /* save for change */
713                 strcpy(dirbuf, command);
714                 /* set dir only */
715                 dirbuf[(pfind - command) + 1] = 0;
716 #if ENABLE_FEATURE_COMMAND_USERNAME_COMPLETION
717                 if (dirbuf[0] == '~')   /* ~/... or ~user/... */
718                         username_tab_completion(dirbuf, dirbuf);
719 #endif
720                 /* "strip" dirname in command */
721                 pfind++;
722
723                 paths[0] = dirbuf;
724                 npaths = 1;                             /* only 1 dir */
725         }
726
727         for (i = 0; i < npaths; i++) {
728
729                 dir = opendir(paths[i]);
730                 if (!dir)                       /* Don't print an error */
731                         continue;
732
733                 while ((next = readdir(dir)) != NULL) {
734                         char *str_found = next->d_name;
735                         int add_chr = 0;
736
737                         /* matched ? */
738                         if (strncmp(str_found, pfind, strlen(pfind)))
739                                 continue;
740                         /* not see .name without .match */
741                         if (*str_found == '.' && *pfind == 0) {
742                                 if (*paths[i] == '/' && paths[i][1] == 0
743                                         && str_found[1] == 0) str_found = "";   /* only "/" */
744                                 else
745                                         continue;
746                         }
747                         found = concat_path_file(paths[i], str_found);
748                         /* hmm, remover in progress? */
749                         if (stat(found, &st) < 0)
750                                 goto cont;
751                         /* find with dirs ? */
752                         if (paths[i] != dirbuf)
753                                 strcpy(found, next->d_name);    /* only name */
754                         if (S_ISDIR(st.st_mode)) {
755                                 /* name is directory      */
756                                 char *e = found + strlen(found) - 1;
757
758                                 add_chr = '/';
759                                 if (*e == '/')
760                                         *e = '\0';
761                         } else {
762                                 /* not put found file if search only dirs for cd */
763                                 if (type == FIND_DIR_ONLY)
764                                         goto cont;
765                                 if (type == FIND_FILE_ONLY ||
766                                         (type == FIND_EXE_ONLY && is_execute(&st)))
767                                         add_chr = ' ';
768                         }
769                         /* Add it to the list */
770                         add_match(found, add_chr);
771                         continue;
772 cont:
773                         free(found);
774                 }
775                 closedir(dir);
776         }
777         if (paths != path1) {
778                 free(paths[0]);                 /* allocated memory only in first member */
779                 free(paths);
780         }
781 }
782
783
784 #define QUOT    (UCHAR_MAX+1)
785
786 #define collapse_pos(is, in) { \
787         memmove(int_buf+(is), int_buf+(in), (BUFSIZ+1-(is)-(in))*sizeof(int)); \
788         memmove(pos_buf+(is), pos_buf+(in), (BUFSIZ+1-(is)-(in))*sizeof(int)); }
789
790 static int find_match(char *matchBuf, int *len_with_quotes)
791 {
792         int i, j;
793         int command_mode;
794         int c, c2;
795         int int_buf[BUFSIZ + 1];
796         int pos_buf[BUFSIZ + 1];
797
798         /* set to integer dimension characters and own positions */
799         for (i = 0;; i++) {
800                 int_buf[i] = (int) ((unsigned char) matchBuf[i]);
801                 if (int_buf[i] == 0) {
802                         pos_buf[i] = -1;        /* indicator end line */
803                         break;
804                 } else
805                         pos_buf[i] = i;
806         }
807
808         /* mask \+symbol and convert '\t' to ' ' */
809         for (i = j = 0; matchBuf[i]; i++, j++)
810                 if (matchBuf[i] == '\\') {
811                         collapse_pos(j, j + 1);
812                         int_buf[j] |= QUOT;
813                         i++;
814 #if ENABLE_FEATURE_NONPRINTABLE_INVERSE_PUT
815                         if (matchBuf[i] == '\t')        /* algorithm equivalent */
816                                 int_buf[j] = ' ' | QUOT;
817 #endif
818                 }
819 #if ENABLE_FEATURE_NONPRINTABLE_INVERSE_PUT
820                 else if (matchBuf[i] == '\t')
821                         int_buf[j] = ' ';
822 #endif
823
824         /* mask "symbols" or 'symbols' */
825         c2 = 0;
826         for (i = 0; int_buf[i]; i++) {
827                 c = int_buf[i];
828                 if (c == '\'' || c == '"') {
829                         if (c2 == 0)
830                                 c2 = c;
831                         else {
832                                 if (c == c2)
833                                         c2 = 0;
834                                 else
835                                         int_buf[i] |= QUOT;
836                         }
837                 } else if (c2 != 0 && c != '$')
838                         int_buf[i] |= QUOT;
839         }
840
841         /* skip commands with arguments if line have commands delimiters */
842         /* ';' ';;' '&' '|' '&&' '||' but `>&' `<&' `>|' */
843         for (i = 0; int_buf[i]; i++) {
844                 c = int_buf[i];
845                 c2 = int_buf[i + 1];
846                 j = i ? int_buf[i - 1] : -1;
847                 command_mode = 0;
848                 if (c == ';' || c == '&' || c == '|') {
849                         command_mode = 1 + (c == c2);
850                         if (c == '&') {
851                                 if (j == '>' || j == '<')
852                                         command_mode = 0;
853                         } else if (c == '|' && j == '>')
854                                 command_mode = 0;
855                 }
856                 if (command_mode) {
857                         collapse_pos(0, i + command_mode);
858                         i = -1;                         /* hack incremet */
859                 }
860         }
861         /* collapse `command...` */
862         for (i = 0; int_buf[i]; i++)
863                 if (int_buf[i] == '`') {
864                         for (j = i + 1; int_buf[j]; j++)
865                                 if (int_buf[j] == '`') {
866                                         collapse_pos(i, j + 1);
867                                         j = 0;
868                                         break;
869                                 }
870                         if (j) {
871                                 /* not found close ` - command mode, collapse all previous */
872                                 collapse_pos(0, i + 1);
873                                 break;
874                         } else
875                                 i--;                    /* hack incremet */
876                 }
877
878         /* collapse (command...(command...)...) or {command...{command...}...} */
879         c = 0;                                          /* "recursive" level */
880         c2 = 0;
881         for (i = 0; int_buf[i]; i++)
882                 if (int_buf[i] == '(' || int_buf[i] == '{') {
883                         if (int_buf[i] == '(')
884                                 c++;
885                         else
886                                 c2++;
887                         collapse_pos(0, i + 1);
888                         i = -1;                         /* hack incremet */
889                 }
890         for (i = 0; pos_buf[i] >= 0 && (c > 0 || c2 > 0); i++)
891                 if ((int_buf[i] == ')' && c > 0) || (int_buf[i] == '}' && c2 > 0)) {
892                         if (int_buf[i] == ')')
893                                 c--;
894                         else
895                                 c2--;
896                         collapse_pos(0, i + 1);
897                         i = -1;                         /* hack incremet */
898                 }
899
900         /* skip first not quote space */
901         for (i = 0; int_buf[i]; i++)
902                 if (int_buf[i] != ' ')
903                         break;
904         if (i)
905                 collapse_pos(0, i);
906
907         /* set find mode for completion */
908         command_mode = FIND_EXE_ONLY;
909         for (i = 0; int_buf[i]; i++)
910                 if (int_buf[i] == ' ' || int_buf[i] == '<' || int_buf[i] == '>') {
911                         if (int_buf[i] == ' ' && command_mode == FIND_EXE_ONLY
912                                 && matchBuf[pos_buf[0]]=='c'
913                                 && matchBuf[pos_buf[1]]=='d' )
914                                 command_mode = FIND_DIR_ONLY;
915                         else {
916                                 command_mode = FIND_FILE_ONLY;
917                                 break;
918                         }
919                 }
920         /* "strlen" */
921         for (i = 0; int_buf[i]; i++);
922         /* find last word */
923         for (--i; i >= 0; i--) {
924                 c = int_buf[i];
925                 if (c == ' ' || c == '<' || c == '>' || c == '|' || c == '&') {
926                         collapse_pos(0, i + 1);
927                         break;
928                 }
929         }
930         /* skip first not quoted '\'' or '"' */
931         for (i = 0; int_buf[i] == '\'' || int_buf[i] == '"'; i++);
932         /* collapse quote or unquote // or /~ */
933         while ((int_buf[i] & ~QUOT) == '/' &&
934                         ((int_buf[i + 1] & ~QUOT) == '/'
935                          || (int_buf[i + 1] & ~QUOT) == '~')) {
936                 i++;
937         }
938
939         /* set only match and destroy quotes */
940         j = 0;
941         for (c = 0; pos_buf[i] >= 0; i++) {
942                 matchBuf[c++] = matchBuf[pos_buf[i]];
943                 j = pos_buf[i] + 1;
944         }
945         matchBuf[c] = 0;
946         /* old lenght matchBuf with quotes symbols */
947         *len_with_quotes = j ? j - pos_buf[0] : 0;
948
949         return command_mode;
950 }
951
952 /*
953    display by column original ideas from ls applet,
954    very optimize by my :)
955 */
956 static void showfiles(void)
957 {
958         int ncols, row;
959         int column_width = 0;
960         int nfiles = num_matches;
961         int nrows = nfiles;
962         char str_add_chr[2];
963         int l;
964
965         /* find the longest file name-  use that as the column width */
966         for (row = 0; row < nrows; row++) {
967                 l = strlen(matches[row]);
968                 if (add_char_to_match[row])
969                         l++;
970                 if (column_width < l)
971                         column_width = l;
972         }
973         column_width += 2;              /* min space for columns */
974         ncols = cmdedit_termw / column_width;
975
976         if (ncols > 1) {
977                 nrows /= ncols;
978                 if (nfiles % ncols)
979                         nrows++;        /* round up fractionals */
980         } else {
981                 ncols = 1;
982         }
983         str_add_chr[1] = 0;
984         for (row = 0; row < nrows; row++) {
985                 int n = row;
986                 int nc;
987                 int acol;
988
989                 for(nc = 1; nc < ncols && n+nrows < nfiles; n += nrows, nc++) {
990                         str_add_chr[0] = add_char_to_match[n];
991                         acol = str_add_chr[0] ? column_width - 1 : column_width;
992                         printf("%s%s%-*s", matches[n], str_add_chr,
993                                         acol - strlen(matches[n]), "");
994                 }
995                 str_add_chr[0] = add_char_to_match[n];
996                 printf("%s%s\n", matches[n], str_add_chr);
997         }
998 }
999
1000 static int match_compare(const void *a, const void *b)
1001 {
1002         return strcmp(*(char**)a, *(char**)b);
1003 }
1004
1005 static void input_tab(int *lastWasTab)
1006 {
1007         /* Do TAB completion */
1008         if (lastWasTab == 0) {          /* free all memory */
1009                 if (matches) {
1010                         while (num_matches > 0)
1011                                 free(matches[--num_matches]);
1012                         free(matches);
1013                         matches = (char **) NULL;
1014                         free(add_char_to_match);
1015                         add_char_to_match = NULL;
1016                 }
1017                 return;
1018         }
1019         if (! *lastWasTab) {
1020                 char *tmp, *tmp1;
1021                 int len_found;
1022                 char matchBuf[BUFSIZ];
1023                 int find_type;
1024                 int recalc_pos;
1025
1026                 *lastWasTab = TRUE;             /* flop trigger */
1027
1028                 /* Make a local copy of the string -- up
1029                  * to the position of the cursor */
1030                 tmp = strncpy(matchBuf, command_ps, cursor);
1031                 tmp[cursor] = 0;
1032
1033                 find_type = find_match(matchBuf, &recalc_pos);
1034
1035                 /* Free up any memory already allocated */
1036                 input_tab(0);
1037
1038 #if ENABLE_FEATURE_COMMAND_USERNAME_COMPLETION
1039                 /* If the word starts with `~' and there is no slash in the word,
1040                  * then try completing this word as a username. */
1041
1042                 if (matchBuf[0] == '~' && strchr(matchBuf, '/') == 0)
1043                         username_tab_completion(matchBuf, NULL);
1044                 if (!matches)
1045 #endif
1046                 /* Try to match any executable in our path and everything
1047                  * in the current working directory that matches.  */
1048                         exe_n_cwd_tab_completion(matchBuf, find_type);
1049                 /* Sort, then remove any duplicates found */
1050                 if (matches) {
1051                         int i, n = 0;
1052                         qsort(matches, num_matches, sizeof(char*), match_compare);
1053                         for (i = 0; i < num_matches - 1; ++i) {
1054                                 if (matches[i] && matches[i+1]) {
1055                                         if (strcmp(matches[i], matches[i+1]) == 0) {
1056                                                 free(matches[i]);
1057                                                 matches[i] = 0;
1058                                         } else {
1059                                                 add_char_to_match[n] = add_char_to_match[i];
1060                                                 matches[n++] = matches[i];
1061                                         }
1062                                 }
1063                         }
1064                         add_char_to_match[n] = add_char_to_match[num_matches-1];
1065                         matches[n++] = matches[num_matches-1];
1066                         num_matches = n;
1067                 }
1068                 /* Did we find exactly one match? */
1069                 if (!matches || num_matches > 1) {
1070                         beep();
1071                         if (!matches)
1072                                 return;         /* not found */
1073                         /* find minimal match */
1074                         tmp1 = xstrdup(matches[0]);
1075                         for (tmp = tmp1; *tmp; tmp++)
1076                                 for (len_found = 1; len_found < num_matches; len_found++)
1077                                         if (matches[len_found][(tmp - tmp1)] != *tmp) {
1078                                                 *tmp = 0;
1079                                                 break;
1080                                         }
1081                         if (*tmp1 == 0) {        /* have unique */
1082                                 free(tmp1);
1083                                 return;
1084                         }
1085                         tmp = add_quote_for_spec_chars(tmp1, 0);
1086                         free(tmp1);
1087                 } else {                        /* one match */
1088                         tmp = add_quote_for_spec_chars(matches[0], add_char_to_match[0]);
1089                         /* for next completion current found */
1090                         *lastWasTab = FALSE;
1091                 }
1092                 len_found = strlen(tmp);
1093                 /* have space to placed match? */
1094                 if ((len_found - strlen(matchBuf) + len) < BUFSIZ) {
1095
1096                         /* before word for match   */
1097                         command_ps[cursor - recalc_pos] = 0;
1098                         /* save   tail line        */
1099                         strcpy(matchBuf, command_ps + cursor);
1100                         /* add    match            */
1101                         strcat(command_ps, tmp);
1102                         /* add    tail             */
1103                         strcat(command_ps, matchBuf);
1104                         /* back to begin word for match    */
1105                         input_backward(recalc_pos);
1106                         /* new pos                         */
1107                         recalc_pos = cursor + len_found;
1108                         /* new len                         */
1109                         len = strlen(command_ps);
1110                         /* write out the matched command   */
1111                         redraw(cmdedit_y, len - recalc_pos);
1112                 }
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();
1124                         redraw(0, len - sav_cursor);
1125                 }
1126         }
1127 }
1128 #endif  /* FEATURE_COMMAND_TAB_COMPLETION */
1129
1130 #if MAX_HISTORY > 0
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] = 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                 cur_history = ch + 1;
1147                 return cur_history;
1148         } else {
1149                 beep();
1150                 return 0;
1151         }
1152 }
1153
1154 #if ENABLE_FEATURE_COMMAND_SAVEHISTORY
1155 void load_history ( const char *fromfile )
1156 {
1157         FILE *fp;
1158         int hi;
1159
1160         /* cleanup old */
1161
1162         for(hi = n_history; hi > 0; ) {
1163                 hi--;
1164                 free ( history [hi] );
1165         }
1166
1167         if (( fp = fopen ( fromfile, "r" ))) {
1168
1169                 for ( hi = 0; hi < MAX_HISTORY; ) {
1170                         char * hl = xmalloc_getline(fp);
1171                         int l;
1172
1173                         if (!hl)
1174                                 break;
1175                         l = strlen(hl);
1176                         if (l >= BUFSIZ)
1177                                 hl[BUFSIZ-1] = 0;
1178                         if (l == 0 || hl[0] == ' ') {
1179                                 free(hl);
1180                                 continue;
1181                         }
1182                         history [hi++] = hl;
1183                 }
1184                 fclose ( fp );
1185         }
1186         cur_history = n_history = hi;
1187 }
1188
1189 void save_history ( const char *tofile )
1190 {
1191         FILE *fp = fopen ( tofile, "w" );
1192
1193         if ( fp ) {
1194                 int i;
1195
1196                 for ( i = 0; i < n_history; i++ ) {
1197                         fprintf(fp, "%s\n", history [i]);
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 (sort of 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  * Minimalist vi-style command line editing available if configured.
1226  *  vi mode implemented 2005 by Paul Fox <pgf@foxharp.boston.ma.us>
1227  *
1228  */
1229
1230 #if ENABLE_FEATURE_COMMAND_EDITING_VI
1231 static int vi_mode;
1232
1233 void setvimode ( int viflag )
1234 {
1235         vi_mode = viflag;
1236 }
1237
1238 static void
1239 vi_Word_motion(char *command, int eat)
1240 {
1241         while (cursor < len && !isspace(command[cursor]))
1242                 input_forward();
1243         if (eat) while (cursor < len && isspace(command[cursor]))
1244                 input_forward();
1245 }
1246
1247 static void
1248 vi_word_motion(char *command, int eat)
1249 {
1250         if (isalnum(command[cursor]) || command[cursor] == '_') {
1251                 while (cursor < len &&
1252                     (isalnum(command[cursor+1]) ||
1253                                 command[cursor+1] == '_'))
1254                         input_forward();
1255         } else if (ispunct(command[cursor])) {
1256                 while (cursor < len &&
1257                     (ispunct(command[cursor+1])))
1258                         input_forward();
1259         }
1260
1261         if (cursor < len)
1262                 input_forward();
1263
1264         if (eat && cursor < len && isspace(command[cursor]))
1265                 while (cursor < len && isspace(command[cursor]))
1266                         input_forward();
1267 }
1268
1269 static void
1270 vi_End_motion(char *command)
1271 {
1272         input_forward();
1273         while (cursor < len && isspace(command[cursor]))
1274                 input_forward();
1275         while (cursor < len-1 && !isspace(command[cursor+1]))
1276                 input_forward();
1277 }
1278
1279 static void
1280 vi_end_motion(char *command)
1281 {
1282         if (cursor >= len-1)
1283                 return;
1284         input_forward();
1285         while (cursor < len-1 && isspace(command[cursor]))
1286                 input_forward();
1287         if (cursor >= len-1)
1288                 return;
1289         if (isalnum(command[cursor]) || command[cursor] == '_') {
1290                 while (cursor < len-1 &&
1291                     (isalnum(command[cursor+1]) ||
1292                                 command[cursor+1] == '_'))
1293                         input_forward();
1294         } else if (ispunct(command[cursor])) {
1295                 while (cursor < len-1 &&
1296                     (ispunct(command[cursor+1])))
1297                         input_forward();
1298         }
1299 }
1300
1301 static void
1302 vi_Back_motion(char *command)
1303 {
1304         while (cursor > 0 && isspace(command[cursor-1]))
1305                 input_backward(1);
1306         while (cursor > 0 && !isspace(command[cursor-1]))
1307                 input_backward(1);
1308 }
1309
1310 static void
1311 vi_back_motion(char *command)
1312 {
1313         if (cursor <= 0)
1314                 return;
1315         input_backward(1);
1316         while (cursor > 0 && isspace(command[cursor]))
1317                 input_backward(1);
1318         if (cursor <= 0)
1319                 return;
1320         if (isalnum(command[cursor]) || command[cursor] == '_') {
1321                 while (cursor > 0 &&
1322                     (isalnum(command[cursor-1]) ||
1323                                 command[cursor-1] == '_'))
1324                         input_backward(1);
1325         } else if (ispunct(command[cursor])) {
1326                 while (cursor > 0 &&
1327                     (ispunct(command[cursor-1])))
1328                         input_backward(1);
1329         }
1330 }
1331 #endif
1332
1333 /*
1334  * the emacs and vi modes share much of the code in the big
1335  * command loop.  commands entered when in vi's command mode (aka
1336  * "escape mode") get an extra bit added to distinguish them --
1337  * this keeps them from being self-inserted.  this clutters the
1338  * big switch a bit, but keeps all the code in one place.
1339  */
1340
1341 #define vbit 0x100
1342
1343 /* leave out the "vi-mode"-only case labels if vi editing isn't
1344  * configured. */
1345 #define vi_case(caselabel) USE_FEATURE_COMMAND_EDITING(caselabel)
1346
1347 /* convert uppercase ascii to equivalent control char, for readability */
1348 #define CNTRL(uc_char) ((uc_char) - 0x40)
1349
1350
1351 int cmdedit_read_input(char *prompt, char command[BUFSIZ])
1352 {
1353
1354         int break_out = 0;
1355         int lastWasTab = FALSE;
1356         unsigned char c;
1357         unsigned int ic;
1358 #if ENABLE_FEATURE_COMMAND_EDITING_VI
1359         unsigned int prevc;
1360         int vi_cmdmode = 0;
1361 #endif
1362         /* prepare before init handlers */
1363         cmdedit_y = 0;  /* quasireal y, not true work if line > xt*yt */
1364         len = 0;
1365         command_ps = command;
1366
1367         getTermSettings(0, (void *) &initial_settings);
1368         memcpy(&new_settings, &initial_settings, sizeof(struct termios));
1369         new_settings.c_lflag &= ~ICANON;        /* unbuffered input */
1370         /* Turn off echoing and CTRL-C, so we can trap it */
1371         new_settings.c_lflag &= ~(ECHO | ECHONL | ISIG);
1372         /* Hmm, in linux c_cc[] not parsed if set ~ICANON */
1373         new_settings.c_cc[VMIN] = 1;
1374         new_settings.c_cc[VTIME] = 0;
1375         /* Turn off CTRL-C, so we can trap it */
1376 #       ifndef _POSIX_VDISABLE
1377 #               define _POSIX_VDISABLE '\0'
1378 #       endif
1379         new_settings.c_cc[VINTR] = _POSIX_VDISABLE;
1380         command[0] = 0;
1381
1382         setTermSettings(0, (void *) &new_settings);
1383         handlers_sets |= SET_RESET_TERM;
1384
1385         /* Now initialize things */
1386         cmdedit_init();
1387         /* Print out the command prompt */
1388         parse_prompt(prompt);
1389
1390         while (1) {
1391
1392                 fflush(stdout);                 /* buffered out to fast */
1393
1394                 if (safe_read(0, &c, 1) < 1)
1395                         /* if we can't read input then exit */
1396                         goto prepare_to_die;
1397
1398                 ic = c;
1399
1400 #if ENABLE_FEATURE_COMMAND_EDITING_VI
1401                 newdelflag = 1;
1402                 if (vi_cmdmode)
1403                         ic |= vbit;
1404 #endif
1405                 switch (ic)
1406                 {
1407                 case '\n':
1408                 case '\r':
1409                 vi_case( case '\n'|vbit: )
1410                 vi_case( case '\r'|vbit: )
1411                         /* Enter */
1412                         goto_new_line();
1413                         break_out = 1;
1414                         break;
1415                 case CNTRL('A'):
1416                 vi_case( case '0'|vbit: )
1417                         /* Control-a -- Beginning of line */
1418                         input_backward(cursor);
1419                         break;
1420                 case CNTRL('B'):
1421                 vi_case( case 'h'|vbit: )
1422                 vi_case( case '\b'|vbit: )
1423                 vi_case( case DEL|vbit: )
1424                         /* Control-b -- Move back one character */
1425                         input_backward(1);
1426                         break;
1427                 case CNTRL('C'):
1428                 vi_case( case CNTRL('C')|vbit: )
1429                         /* Control-c -- stop gathering input */
1430                         goto_new_line();
1431 #if !ENABLE_ASH
1432                         command[0] = 0;
1433                         len = 0;
1434                         lastWasTab = FALSE;
1435                         put_prompt();
1436 #else
1437                         len = 0;
1438                         break_out = -1; /* to control traps */
1439 #endif
1440                         break;
1441                 case CNTRL('D'):
1442                         /* Control-d -- Delete one character, or exit
1443                          * if the len=0 and no chars to delete */
1444                         if (len == 0) {
1445                                         errno = 0;
1446 prepare_to_die:
1447 #if !ENABLE_ASH
1448                                 printf("exit");
1449                                 goto_new_line();
1450                                 /* cmdedit_reset_term() called in atexit */
1451                                 exit(EXIT_SUCCESS);
1452 #else
1453                                 /* to control stopped jobs */
1454                                 len = break_out = -1;
1455                                 break;
1456 #endif
1457                         } else {
1458                                 input_delete(0);
1459                         }
1460                         break;
1461                 case CNTRL('E'):
1462                 vi_case( case '$'|vbit: )
1463                         /* Control-e -- End of line */
1464                         input_end();
1465                         break;
1466                 case CNTRL('F'):
1467                 vi_case( case 'l'|vbit: )
1468                 vi_case( case ' '|vbit: )
1469                         /* Control-f -- Move forward one character */
1470                         input_forward();
1471                         break;
1472                 case '\b':
1473                 case DEL:
1474                         /* Control-h and DEL */
1475                         input_backspace();
1476                         break;
1477                 case '\t':
1478 #if ENABLE_FEATURE_COMMAND_TAB_COMPLETION
1479                         input_tab(&lastWasTab);
1480 #endif
1481                         break;
1482                 case CNTRL('K'):
1483                         /* Control-k -- clear to end of line */
1484                         *(command + cursor) = 0;
1485                         len = cursor;
1486                         printf("\033[J");
1487                         break;
1488                 case CNTRL('L'):
1489                 vi_case( case CNTRL('L')|vbit: )
1490                         /* Control-l -- clear screen */
1491                         printf("\033[H");
1492                         redraw(0, len-cursor);
1493                         break;
1494 #if MAX_HISTORY > 0
1495                 case CNTRL('N'):
1496                 vi_case( case CNTRL('N')|vbit: )
1497                 vi_case( case 'j'|vbit: )
1498                         /* Control-n -- Get next command in history */
1499                         if (get_next_history())
1500                                 goto rewrite_line;
1501                         break;
1502                 case CNTRL('P'):
1503                 vi_case( case CNTRL('P')|vbit: )
1504                 vi_case( case 'k'|vbit: )
1505                         /* Control-p -- Get previous command from history */
1506                         if (cur_history > 0) {
1507                                 get_previous_history();
1508                                 goto rewrite_line;
1509                         } else {
1510                                 beep();
1511                         }
1512                         break;
1513 #endif
1514                 case CNTRL('U'):
1515                 vi_case( case CNTRL('U')|vbit: )
1516                         /* Control-U -- Clear line before cursor */
1517                         if (cursor) {
1518                                 strcpy(command, command + cursor);
1519                                 redraw(cmdedit_y, len -= cursor);
1520                         }
1521                         break;
1522                 case CNTRL('W'):
1523                 vi_case( case CNTRL('W')|vbit: )
1524                         /* Control-W -- Remove the last word */
1525                         while (cursor > 0 && isspace(command[cursor-1]))
1526                                 input_backspace();
1527                         while (cursor > 0 &&!isspace(command[cursor-1]))
1528                                 input_backspace();
1529                         break;
1530 #if ENABLE_FEATURE_COMMAND_EDITING_VI
1531                 case 'i'|vbit:
1532                         vi_cmdmode = 0;
1533                         break;
1534                 case 'I'|vbit:
1535                         input_backward(cursor);
1536                         vi_cmdmode = 0;
1537                         break;
1538                 case 'a'|vbit:
1539                         input_forward();
1540                         vi_cmdmode = 0;
1541                         break;
1542                 case 'A'|vbit:
1543                         input_end();
1544                         vi_cmdmode = 0;
1545                         break;
1546                 case 'x'|vbit:
1547                         input_delete(1);
1548                         break;
1549                 case 'X'|vbit:
1550                         if (cursor > 0) {
1551                                 input_backward(1);
1552                                 input_delete(1);
1553                         }
1554                         break;
1555                 case 'W'|vbit:
1556                         vi_Word_motion(command, 1);
1557                         break;
1558                 case 'w'|vbit:
1559                         vi_word_motion(command, 1);
1560                         break;
1561                 case 'E'|vbit:
1562                         vi_End_motion(command);
1563                         break;
1564                 case 'e'|vbit:
1565                         vi_end_motion(command);
1566                         break;
1567                 case 'B'|vbit:
1568                         vi_Back_motion(command);
1569                         break;
1570                 case 'b'|vbit:
1571                         vi_back_motion(command);
1572                         break;
1573                 case 'C'|vbit:
1574                         vi_cmdmode = 0;
1575                         /* fall through */
1576                 case 'D'|vbit:
1577                         goto clear_to_eol;
1578
1579                 case 'c'|vbit:
1580                         vi_cmdmode = 0;
1581                         /* fall through */
1582                 case 'd'|vbit:
1583                         {
1584                                 int nc, sc;
1585                                 sc = cursor;
1586                                 prevc = ic;
1587                                 if (safe_read(0, &c, 1) < 1)
1588                                         goto prepare_to_die;
1589                                 if (c == (prevc & 0xff)) {
1590                                         /* "cc", "dd" */
1591                                         input_backward(cursor);
1592                                         goto clear_to_eol;
1593                                         break;
1594                                 }
1595                                 switch (c) {
1596                                 case 'w':
1597                                 case 'W':
1598                                 case 'e':
1599                                 case 'E':
1600                                         switch (c) {
1601                                         case 'w':   /* "dw", "cw" */
1602                                                 vi_word_motion(command, vi_cmdmode);
1603                                                 break;
1604                                         case 'W':   /* 'dW', 'cW' */
1605                                                 vi_Word_motion(command, vi_cmdmode);
1606                                                 break;
1607                                         case 'e':   /* 'de', 'ce' */
1608                                                 vi_end_motion(command);
1609                                                 input_forward();
1610                                                 break;
1611                                         case 'E':   /* 'dE', 'cE' */
1612                                                 vi_End_motion(command);
1613                                                 input_forward();
1614                                                 break;
1615                                         }
1616                                         nc = cursor;
1617                                         input_backward(cursor - sc);
1618                                         while (nc-- > cursor)
1619                                                 input_delete(1);
1620                                         break;
1621                                 case 'b':  /* "db", "cb" */
1622                                 case 'B':  /* implemented as B */
1623                                         if (c == 'b')
1624                                                 vi_back_motion(command);
1625                                         else
1626                                                 vi_Back_motion(command);
1627                                         while (sc-- > cursor)
1628                                                 input_delete(1);
1629                                         break;
1630                                 case ' ':  /* "d ", "c " */
1631                                         input_delete(1);
1632                                         break;
1633                                 case '$':  /* "d$", "c$" */
1634                                 clear_to_eol:
1635                                         while (cursor < len)
1636                                                 input_delete(1);
1637                                         break;
1638                                 }
1639                         }
1640                         break;
1641                 case 'p'|vbit:
1642                         input_forward();
1643                         /* fallthrough */
1644                 case 'P'|vbit:
1645                         put();
1646                         break;
1647                 case 'r'|vbit:
1648                         if (safe_read(0, &c, 1) < 1)
1649                                 goto prepare_to_die;
1650                         if (c == 0)
1651                                 beep();
1652                         else {
1653                                 *(command + cursor) = c;
1654                                 putchar(c);
1655                                 putchar('\b');
1656                         }
1657                         break;
1658 #endif /* FEATURE_COMMAND_EDITING_VI */
1659
1660                 case ESC:
1661
1662 #if ENABLE_FEATURE_COMMAND_EDITING_VI
1663                         if (vi_mode) {
1664                                 /* ESC: insert mode --> command mode */
1665                                 vi_cmdmode = 1;
1666                                 input_backward(1);
1667                                 break;
1668                         }
1669 #endif
1670                         /* escape sequence follows */
1671                         if (safe_read(0, &c, 1) < 1)
1672                                 goto prepare_to_die;
1673                         /* different vt100 emulations */
1674                         if (c == '[' || c == 'O') {
1675                 vi_case( case '['|vbit: )
1676                 vi_case( case 'O'|vbit: )
1677                                 if (safe_read(0, &c, 1) < 1)
1678                                         goto prepare_to_die;
1679                         }
1680                         if (c >= '1' && c <= '9') {
1681                                 unsigned char dummy;
1682
1683                                 if (safe_read(0, &dummy, 1) < 1)
1684                                         goto prepare_to_die;
1685                                 if (dummy != '~')
1686                                         c = 0;
1687                         }
1688                         switch (c) {
1689 #if ENABLE_FEATURE_COMMAND_TAB_COMPLETION
1690                         case '\t':                      /* Alt-Tab */
1691
1692                                 input_tab(&lastWasTab);
1693                                 break;
1694 #endif
1695 #if MAX_HISTORY > 0
1696                         case 'A':
1697                                 /* Up Arrow -- Get previous command from history */
1698                                 if (cur_history > 0) {
1699                                         get_previous_history();
1700                                         goto rewrite_line;
1701                                 } else {
1702                                         beep();
1703                                 }
1704                                 break;
1705                         case 'B':
1706                                 /* Down Arrow -- Get next command in history */
1707                                 if (!get_next_history())
1708                                         break;
1709                                 /* Rewrite the line with the selected history item */
1710 rewrite_line:
1711                                 /* change command */
1712                                 len = strlen(strcpy(command, history[cur_history]));
1713                                 /* redraw and go to eol (bol, in vi */
1714 #if ENABLE_FEATURE_COMMAND_EDITING_VI
1715                                 redraw(cmdedit_y, vi_mode ? 9999:0);
1716 #else
1717                                 redraw(cmdedit_y, 0);
1718 #endif
1719                                 break;
1720 #endif
1721                         case 'C':
1722                                 /* Right Arrow -- Move forward one character */
1723                                 input_forward();
1724                                 break;
1725                         case 'D':
1726                                 /* Left Arrow -- Move back one character */
1727                                 input_backward(1);
1728                                 break;
1729                         case '3':
1730                                 /* Delete */
1731                                 input_delete(0);
1732                                 break;
1733                         case '1':
1734                         case 'H':
1735                                 /* <Home> */
1736                                 input_backward(cursor);
1737                                 break;
1738                         case '4':
1739                         case 'F':
1740                                 /* <End> */
1741                                 input_end();
1742                                 break;
1743                         default:
1744                                 c = 0;
1745                                 beep();
1746                         }
1747                         break;
1748
1749                 default:        /* If it's regular input, do the normal thing */
1750 #if ENABLE_FEATURE_NONPRINTABLE_INVERSE_PUT
1751                         /* Control-V -- Add non-printable symbol */
1752                         if (c == CNTRL('V')) {
1753                                 if (safe_read(0, &c, 1) < 1)
1754                                         goto prepare_to_die;
1755                                 if (c == 0) {
1756                                         beep();
1757                                         break;
1758                                 }
1759                         } else
1760 #endif
1761                         {
1762 #if ENABLE_FEATURE_COMMAND_EDITING_VI
1763                                 if (vi_cmdmode)  /* don't self-insert */
1764                                         break;
1765 #endif
1766                                 if (!Isprint(c)) /* Skip non-printable characters */
1767                                         break;
1768                         }
1769
1770                         if (len >= (BUFSIZ - 2))        /* Need to leave space for enter */
1771                                 break;
1772
1773                         len++;
1774
1775                         if (cursor == (len - 1)) {      /* Append if at the end of the line */
1776                                 *(command + cursor) = c;
1777                                 *(command + cursor + 1) = 0;
1778                                 cmdedit_set_out_char(0);
1779                         } else {                        /* Insert otherwise */
1780                                 int sc = cursor;
1781
1782                                 memmove(command + sc + 1, command + sc, len - sc);
1783                                 *(command + sc) = c;
1784                                 sc++;
1785                                 /* rewrite from cursor */
1786                                 input_end();
1787                                 /* to prev x pos + 1 */
1788                                 input_backward(cursor - sc);
1789                         }
1790
1791                         break;
1792                 }
1793                 if (break_out)                  /* Enter is the command terminator, no more input. */
1794                         break;
1795
1796                 if (c != '\t')
1797                         lastWasTab = FALSE;
1798         }
1799
1800         setTermSettings(0, (void *) &initial_settings);
1801         handlers_sets &= ~SET_RESET_TERM;
1802
1803 #if MAX_HISTORY > 0
1804         /* Handle command history log */
1805         /* cleanup may be saved current command line */
1806         if (len> 0) {                                      /* no put empty line */
1807                 int i = n_history;
1808
1809                 free(history[MAX_HISTORY]);
1810                 history[MAX_HISTORY] = 0;
1811                         /* After max history, remove the oldest command */
1812                 if (i >= MAX_HISTORY) {
1813                         free(history[0]);
1814                         for(i = 0; i < (MAX_HISTORY-1); i++)
1815                                 history[i] = history[i+1];
1816                 }
1817                 history[i++] = xstrdup(command);
1818                 cur_history = i;
1819                 n_history = i;
1820 #if ENABLE_FEATURE_SH_FANCY_PROMPT
1821                 num_ok_lines++;
1822 #endif
1823         }
1824 #else  /* MAX_HISTORY == 0 */
1825 #if ENABLE_FEATURE_SH_FANCY_PROMPT
1826         if (len > 0) {              /* no put empty line */
1827                 num_ok_lines++;
1828         }
1829 #endif
1830 #endif  /* MAX_HISTORY > 0 */
1831         if (break_out > 0) {
1832                 command[len++] = '\n';          /* set '\n' */
1833                 command[len] = 0;
1834         }
1835 #if ENABLE_FEATURE_CLEAN_UP && ENABLE_FEATURE_COMMAND_TAB_COMPLETION
1836         input_tab(0);                           /* strong free */
1837 #endif
1838 #if ENABLE_FEATURE_SH_FANCY_PROMPT
1839         free(cmdedit_prompt);
1840 #endif
1841         cmdedit_reset_term();
1842         return len;
1843 }
1844
1845 #endif  /* FEATURE_COMMAND_EDITING */
1846
1847
1848 #ifdef TEST
1849
1850 const char *applet_name = "debug stuff usage";
1851
1852 #if ENABLE_FEATURE_NONPRINTABLE_INVERSE_PUT
1853 #include <locale.h>
1854 #endif
1855
1856 int main(int argc, char **argv)
1857 {
1858         char buff[BUFSIZ];
1859         char *prompt =
1860 #if ENABLE_FEATURE_SH_FANCY_PROMPT
1861                 "\\[\\033[32;1m\\]\\u@\\[\\x1b[33;1m\\]\\h:\
1862 \\[\\033[34;1m\\]\\w\\[\\033[35;1m\\] \
1863 \\!\\[\\e[36;1m\\]\\$ \\[\\E[0m\\]";
1864 #else
1865                 "% ";
1866 #endif
1867
1868 #if ENABLE_FEATURE_NONPRINTABLE_INVERSE_PUT
1869         setlocale(LC_ALL, "");
1870 #endif
1871         while (1) {
1872                 int l;
1873                 l = cmdedit_read_input(prompt, buff);
1874                 if (l > 0 && buff[l-1] == '\n') {
1875                         buff[l-1] = 0;
1876                         printf("*** cmdedit_read_input() returned line =%s=\n", buff);
1877                 } else {
1878                         break;
1879                 }
1880         }
1881         printf("*** cmdedit_read_input() detect ^D\n");
1882         return 0;
1883 }
1884
1885 #endif  /* TEST */