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