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