Changed bb_regcomp to xregcomp and #if 0'ed out destroy_cmd_strs in sed.c
[oweals/busybox.git] / shell / cmdedit.c
1 /* vi: set sw=4 ts=4: */
2 /*
3  * Termios command line History and Editting, originally 
4  * intended for NetBSD sh (ash)
5  * Copyright (c) 1999
6  *      Main code:            Adam Rogoyski <rogoyski@cs.utexas.edu> 
7  *      Etc:                  Dave Cinege <dcinege@psychosis.com>
8  *  Majorly adjusted/re-written for busybox:
9  *                            Erik Andersen <andersee@debian.org>
10  *
11  * You may use this code as you wish, so long as the original author(s)
12  * are attributed in any redistributions of the source code.
13  * This code is 'as is' with no warranty.
14  * This code may safely be consumed by a BSD or GPL license.
15  *
16  * v 0.5  19990328      Initial release 
17  *
18  * Future plans: Simple file and path name completion. (like BASH)
19  *
20  */
21
22 /*
23    Usage and Known bugs:
24    Terminal key codes are not extensive, and more will probably
25    need to be added. This version was created on Debian GNU/Linux 2.x.
26    Delete, Backspace, Home, End, and the arrow keys were tested
27    to work in an Xterm and console. Ctrl-A also works as Home.
28    Ctrl-E also works as End. The binary size increase is <3K.
29
30    Editting will not display correctly for lines greater then the 
31    terminal width. (more then one line.) However, history will.
32  */
33
34 #include "internal.h"
35 #ifdef BB_FEATURE_SH_COMMAND_EDITING
36
37 #include <stdio.h>
38 #include <errno.h>
39 #include <unistd.h>
40 #include <stdlib.h>
41 #include <string.h>
42 #include <sys/ioctl.h>
43 #include <ctype.h>
44 #include <signal.h>
45
46
47 #define  MAX_HISTORY   15               /* Maximum length of the linked list for the command line history */
48
49 #define ESC     27
50 #define DEL     127
51 #define member(c, s) ((c) ? ((char *)strchr ((s), (c)) != (char *)NULL) : 0)
52 #define whitespace(c) (((c) == ' ') || ((c) == '\t'))
53
54 static struct history *his_front = NULL;        /* First element in command line list */
55 static struct history *his_end = NULL;  /* Last element in command line list */
56
57 /* ED: sparc termios is broken: revert back to old termio handling. */
58 #ifdef BB_FEATURE_USE_TERMIOS
59
60 #if #cpu(sparc)
61 #      include <termio.h>
62 #      define termios termio
63 #      define setTermSettings(fd,argp) ioctl(fd,TCSETAF,argp)
64 #      define getTermSettings(fd,argp) ioctl(fd,TCGETA,argp)
65 #else
66 #      include <termios.h>
67 #      define setTermSettings(fd,argp) tcsetattr(fd,TCSANOW,argp)
68 #      define getTermSettings(fd,argp) tcgetattr(fd, argp);
69 #endif
70
71 /* Current termio and the previous termio before starting sh */
72 struct termios initial_settings, new_settings;
73
74
75 #ifndef _POSIX_VDISABLE
76 #define _POSIX_VDISABLE '\0'
77 #endif
78
79 #endif
80
81
82
83 static int cmdedit_termw = 80;  /* actual terminal width */
84 static int cmdedit_scroll = 27; /* width of EOL scrolling region */
85 static int history_counter = 0; /* Number of commands in history list */
86 static int reset_term = 0;              /* Set to true if the terminal needs to be reset upon exit */
87
88 struct history {
89         char *s;
90         struct history *p;
91         struct history *n;
92 };
93
94 #define xwrite write
95
96 void
97 cmdedit_setwidth(int w)
98 {
99         if (w > 20) {
100                 cmdedit_termw = w;
101                 cmdedit_scroll = w / 3;
102         } else {
103                 errorMsg("\n*** Error: minimum screen width is 21\n");
104         }
105 }
106
107
108 void cmdedit_reset_term(void)
109 {
110         if (reset_term)
111                 /* sparc and other have broken termios support: use old termio handling. */
112                 setTermSettings(fileno(stdin), (void*) &initial_settings);
113 }
114
115 void clean_up_and_die(int sig)
116 {
117         cmdedit_reset_term();
118         fprintf(stdout, "\n");
119         if (sig!=SIGINT)
120                 exit(TRUE);
121 }
122
123 /* Go to HOME position */
124 void input_home(int outputFd, int *cursor)
125 {
126         while (*cursor > 0) {
127                 xwrite(outputFd, "\b", 1);
128                 --*cursor;
129         }
130 }
131
132 /* Go to END position */
133 void input_end(int outputFd, int *cursor, int len)
134 {
135         while (*cursor < len) {
136                 xwrite(outputFd, "\033[C", 3);
137                 ++*cursor;
138         }
139 }
140
141 /* Delete the char in back of the cursor */
142 void input_backspace(char* command, int outputFd, int *cursor, int *len)
143 {
144         int j = 0;
145
146 /* Debug crap */
147 //fprintf(stderr, "\nerik: len=%d, cursor=%d, strlen(command)='%d'\n", *len, *cursor, strlen(command));
148 //xwrite(outputFd, command, *len);
149 //*cursor = *len;
150
151
152         if (*cursor > 0) {
153                 xwrite(outputFd, "\b \b", 3);
154                 --*cursor;
155                 memmove(command + *cursor, command + *cursor + 1,
156                                 BUFSIZ - *cursor + 1);
157
158                 for (j = *cursor; j < (BUFSIZ - 1); j++) {
159                         if (!*(command + j))
160                                 break;
161                         else
162                                 xwrite(outputFd, (command + j), 1);
163                 }
164
165                 xwrite(outputFd, " \b", 2);
166
167                 while (j-- > *cursor)
168                         xwrite(outputFd, "\b", 1);
169
170                 --*len;
171         }
172 }
173
174 /* Delete the char in front of the cursor */
175 void input_delete(char* command, int outputFd, int cursor, int *len)
176 {
177         int j = 0;
178
179         if (cursor == *len)
180                 return;
181         
182         memmove(command + cursor, command + cursor + 1,
183                         BUFSIZ - cursor - 1);
184         for (j = cursor; j < (BUFSIZ - 1); j++) {
185                 if (!*(command + j))
186                         break;
187                 else
188                         xwrite(outputFd, (command + j), 1);
189         }
190
191         xwrite(outputFd, " \b", 2);
192
193         while (j-- > cursor)
194                 xwrite(outputFd, "\b", 1);
195         --*len;
196 }
197
198 /* Move forward one charactor */
199 void input_forward(int outputFd, int *cursor, int len)
200 {
201         if (*cursor < len) {
202                 xwrite(outputFd, "\033[C", 3);
203                 ++*cursor;
204         }
205 }
206
207 /* Move back one charactor */
208 void input_backward(int outputFd, int *cursor)
209 {
210         if (*cursor > 0) {
211                 xwrite(outputFd, "\033[D", 3);
212                 --*cursor;
213         }
214 }
215
216
217
218 #ifdef BB_FEATURE_SH_TAB_COMPLETION
219 char** username_tab_completion(char* command, int *num_matches)
220 {
221         char **matches = (char **) NULL;
222         *num_matches=0;
223         fprintf(stderr, "\nin username_tab_completion\n");
224         return (matches);
225 }
226
227 #include <dirent.h>
228 char** exe_n_cwd_tab_completion(char* command, int *num_matches)
229 {
230         char *dirName;
231         char **matches = (char **) NULL;
232         DIR *dir;
233         struct dirent *next;
234                         
235         matches = malloc( sizeof(char*)*50);
236
237         /* Stick a wildcard onto the command, for later use */
238         strcat( command, "*");
239
240         /* Now wall the current directory */
241         dirName = get_current_dir_name();
242         dir = opendir(dirName);
243         if (!dir) {
244                 /* Don't print an error, just shut up and return */
245                 *num_matches=0;
246                 return (matches);
247         }
248         while ((next = readdir(dir)) != NULL) {
249
250                 /* Some quick sanity checks */
251                 if ((strcmp(next->d_name, "..") == 0)
252                         || (strcmp(next->d_name, ".") == 0)) {
253                         continue;
254                 } 
255                 /* See if this matches */
256                 if (check_wildcard_match(next->d_name, command) == TRUE) {
257                         /* Cool, found a match.  Add it to the list */
258                         matches[*num_matches] = malloc(strlen(next->d_name)+1);
259                         strcpy( matches[*num_matches], next->d_name);
260                         ++*num_matches;
261                         //matches = realloc( matches, sizeof(char*)*(*num_matches));
262                 }
263         }
264
265         return (matches);
266 }
267
268 void input_tab(char* command, char* prompt, int outputFd, int *cursor, int *len)
269 {
270         /* Do TAB completion */
271         static int num_matches=0;
272         static char **matches = (char **) NULL;
273         int pos = cursor;
274
275
276         if (lastWasTab == FALSE) {
277                 char *tmp, *tmp1, *matchBuf;
278
279                 /* For now, we will not bother with trying to distinguish
280                  * whether the cursor is in/at a command extression -- we
281                  * will always try all possible matches.  If you don't like
282                  * that then feel free to fix it.
283                  */
284
285                 /* Make a local copy of the string -- up 
286                  * to the position of the cursor */
287                 matchBuf = (char *) calloc(BUFSIZ, sizeof(char));
288                 strncpy(matchBuf, command, cursor);
289                 tmp=matchBuf;
290
291                 /* skip past any command seperator tokens */
292                 while (*tmp && (tmp1=strpbrk(tmp, ";|&{(`")) != NULL) {
293                         tmp=++tmp1;
294                         /* skip any leading white space */
295                         while (*tmp && isspace(*tmp)) 
296                                 ++tmp;
297                 }
298
299                 /* skip any leading white space */
300                 while (*tmp && isspace(*tmp)) 
301                         ++tmp;
302
303                 /* Free up any memory already allocated */
304                 if (matches) {
305                         free(matches);
306                         matches = (char **) NULL;
307                 }
308
309                 /* If the word starts with `~' and there is no slash in the word, 
310                  * then try completing this word as a username. */
311
312                 /* FIXME -- this check is broken! */
313                 if (*tmp == '~' && !strchr(tmp, '/'))
314                         matches = username_tab_completion(tmp, &num_matches);
315
316                 /* Try to match any executable in our path and everything 
317                  * in the current working directory that matches.  */
318                 if (!matches)
319                         matches = exe_n_cwd_tab_completion(tmp, &num_matches);
320
321                 /* Don't leak memory */
322                 free( matchBuf);
323
324                 /* Did we find exactly one match? */
325                 if (matches && num_matches==1) {
326                         /* write out the matched command */
327                         strncpy(command+pos, matches[0]+pos, strlen(matches[0])-pos);
328                         len=strlen(command);
329                         cursor=len;
330                         xwrite(outputFd, matches[0]+pos, strlen(matches[0])-pos);
331                         break;
332                 }
333         } else {
334                 /* Ok -- the last char was a TAB.  Since they
335                  * just hit TAB again, print a list of all the
336                  * available choices... */
337                 if ( matches && num_matches>0 ) {
338                         int i, col;
339
340                         /* Go to the next line */
341                         xwrite(outputFd, "\n", 1);
342                         /* Print the list of matches */
343                         for (i=0,col=0; i<num_matches; i++) {
344                                 char foo[17];
345                                 sprintf(foo, "%-14s  ", matches[i]);
346                                 col += xwrite(outputFd, foo, strlen(foo));
347                                 if (col > 60 && matches[i+1] != NULL) {
348                                         xwrite(outputFd, "\n", 1);
349                                         col = 0;
350                                 }
351                         }
352                         /* Go to the next line */
353                         xwrite(outputFd, "\n", 1);
354                         /* Rewrite the prompt */
355                         xwrite(outputFd, prompt, strlen(prompt));
356                         /* Rewrite the command */
357                         xwrite(outputFd, command, len);
358                         /* Put the cursor back to where it used to be */
359                         for (cursor=len; cursor > pos; cursor--)
360                                 xwrite(outputFd, "\b", 1);
361                 }
362         }
363 }
364 #endif
365
366 void get_previous_history(struct history **hp, char* command)
367 {
368         free((*hp)->s);
369         (*hp)->s = strdup(command);
370         *hp = (*hp)->p;
371 }
372
373 void get_next_history(struct history **hp, char* command)
374 {
375         free((*hp)->s);
376         (*hp)->s = strdup(command);
377         *hp = (*hp)->n;
378 }
379
380 /*
381  * This function is used to grab a character buffer
382  * from the input file descriptor and allows you to
383  * a string with full command editing (sortof like
384  * a mini readline).
385  *
386  * The following standard commands are not implemented:
387  * ESC-b -- Move back one word
388  * ESC-f -- Move forward one word
389  * ESC-d -- Delete back one word
390  * ESC-h -- Delete forward one word
391  * CTL-t -- Transpose two characters
392  *
393  * Furthermore, the "vi" command editing keys are not implemented.
394  *
395  * TODO: implement TAB command completion. :)
396  */
397 extern void cmdedit_read_input(char* prompt, char command[BUFSIZ])
398 {
399
400         int inputFd=fileno(stdin);
401         int outputFd=fileno(stdout);
402         int nr = 0;
403         int len = 0;
404         int j = 0;
405         int cursor = 0;
406         int break_out = 0;
407         int ret = 0;
408         int lastWasTab = FALSE;
409         char c = 0;
410         struct history *hp = his_end;
411
412         memset(command, 0, sizeof(command));
413         if (!reset_term) {
414                 
415                 getTermSettings(inputFd, (void*) &initial_settings);
416                 memcpy(&new_settings, &initial_settings, sizeof(struct termios));
417                 new_settings.c_cc[VMIN] = 1;
418                 new_settings.c_cc[VTIME] = 0;
419                 new_settings.c_cc[VINTR] = _POSIX_VDISABLE; /* Turn off CTRL-C, so we can trap it */
420                 new_settings.c_lflag &= ~ICANON;        /* unbuffered input */
421                 new_settings.c_lflag &= ~(ECHO|ECHOCTL|ECHONL); /* Turn off echoing */
422                 reset_term = 1;
423         }
424         setTermSettings(inputFd, (void*) &new_settings);
425
426         memset(command, 0, BUFSIZ);
427
428         while (1) {
429
430                 if ((ret = read(inputFd, &c, 1)) < 1)
431                         return;
432                 //fprintf(stderr, "got a '%c' (%d)\n", c, c);
433
434                 switch (c) {
435                 case '\n':
436                 case '\r':
437                         /* Enter */
438                         *(command + len++ + 1) = c;
439                         xwrite(outputFd, &c, 1);
440                         break_out = 1;
441                         break;
442                 case 1:
443                         /* Control-a -- Beginning of line */
444                         input_home(outputFd, &cursor);
445                 case 2:
446                         /* Control-b -- Move back one character */
447                         input_backward(outputFd, &cursor);
448                         break;
449                 case 3:
450                         /* Control-c -- leave the current line, 
451                          * and start over on the next line */ 
452
453                         /* Go to the next line */
454                         xwrite(outputFd, "\n", 1);
455
456                         /* Rewrite the prompt */
457                         xwrite(outputFd, prompt, strlen(prompt));
458
459                         /* Reset the command string */
460                         memset(command, 0, sizeof(command));
461                         len = cursor = 0;
462
463                         break;
464                 case 4:
465                         /* Control-d -- Delete one character, or exit 
466                          * if the len=0 and no chars to delete */
467                         if (len == 0) {
468                                 xwrite(outputFd, "exit", 4);
469                                 clean_up_and_die(0);
470                         } else {
471                                 input_delete(command, outputFd, cursor, &len);
472                         }
473                         break;
474                 case 5:
475                         /* Control-e -- End of line */
476                         input_end(outputFd, &cursor, len);
477                         break;
478                 case 6:
479                         /* Control-f -- Move forward one character */
480                         input_forward(outputFd, &cursor, len);
481                         break;
482                 case '\b':
483                 case DEL:
484                         /* Control-h and DEL */
485                         input_backspace(command, outputFd, &cursor, &len);
486                         break;
487                 case '\t':
488 #ifdef BB_FEATURE_SH_TAB_COMPLETION
489                         input_tab(command, prompt, outputFd, &cursor, &len);
490 #endif
491                         break;
492                 case 14:
493                         /* Control-n -- Get next command in history */
494                         if (hp && hp->n && hp->n->s) {
495                                 get_next_history(&hp, command);
496                                 goto rewrite_line;
497                         } else {
498                                 xwrite(outputFd, "\007", 1);
499                         }
500                         break;
501                 case 16:
502                         /* Control-p -- Get previous command from history */
503                         if (hp && hp->p) {
504                                 get_previous_history(&hp, command);
505                                 goto rewrite_line;
506                         } else {
507                                 xwrite(outputFd, "\007", 1);
508                         }
509                         break;
510                 case ESC:{
511                                 /* escape sequence follows */
512                                 if ((ret = read(inputFd, &c, 1)) < 1)
513                                         return;
514
515                                 if (c == '[') { /* 91 */
516                                         if ((ret = read(inputFd, &c, 1)) < 1)
517                                                 return;
518
519                                         switch (c) {
520                                         case 'A':
521                                                 /* Up Arrow -- Get previous command from history */
522                                                 if (hp && hp->p) {
523                                                         get_previous_history(&hp, command);
524                                                         goto rewrite_line;
525                                                 } else {
526                                                         xwrite(outputFd, "\007", 1);
527                                                 }
528                                                 break;
529                                         case 'B':
530                                                 /* Down Arrow -- Get next command in history */
531                                                 if (hp && hp->n && hp->n->s) {
532                                                         get_next_history(&hp, command);
533                                                         goto rewrite_line;
534                                                 } else {
535                                                         xwrite(outputFd, "\007", 1);
536                                                 }
537                                                 break;
538
539                                                 /* Rewrite the line with the selected history item */
540                                           rewrite_line:
541                                                 /* erase old command from command line */
542                                                 len = strlen(command)-strlen(hp->s);
543
544                                                 while (len>cursor)
545                                                         input_delete(command, outputFd, cursor, &len);
546                                                 while (cursor>0)
547                                                         input_backspace(command, outputFd, &cursor, &len);
548                                                 input_home(outputFd, &cursor);
549                                                 
550                                                 /* write new command */
551                                                 strcpy(command, hp->s);
552                                                 len = strlen(hp->s);
553                                                 xwrite(outputFd, command, len);
554                                                 cursor = len;
555                                                 break;
556                                         case 'C':
557                                                 /* Right Arrow -- Move forward one character */
558                                                 input_forward(outputFd, &cursor, len);
559                                                 break;
560                                         case 'D':
561                                                 /* Left Arrow -- Move back one character */
562                                                 input_backward(outputFd, &cursor);
563                                                 break;
564                                         case '3':
565                                                 /* Delete */
566                                                 input_delete(command, outputFd, cursor, &len);
567                                                 break;
568                                         case '1':
569                                                 /* Home (Ctrl-A) */
570                                                 input_home(outputFd, &cursor);
571                                                 break;
572                                         case '4':
573                                                 /* End (Ctrl-E) */
574                                                 input_end(outputFd, &cursor, len);
575                                                 break;
576                                         default:
577                                                 xwrite(outputFd, "\007", 1);
578                                         }
579                                         if (c == '1' || c == '3' || c == '4')
580                                                 if ((ret = read(inputFd, &c, 1)) < 1)
581                                                         return; /* read 126 (~) */
582                                 }
583                                 if (c == 'O') {
584                                         /* 79 */
585                                         if ((ret = read(inputFd, &c, 1)) < 1)
586                                                 return;
587                                         switch (c) {
588                                         case 'H':
589                                                 /* Home (xterm) */
590                                                 input_home(outputFd, &cursor);
591                                                 break;
592                                         case 'F':
593                                                 /* End (xterm) */
594                                                 input_end(outputFd, &cursor, len);
595                                                 break;
596                                         default:
597                                                 xwrite(outputFd, "\007", 1);
598                                         }
599                                 }
600                                 c = 0;
601                                 break;
602                         }
603
604                 default:                                /* If it's regular input, do the normal thing */
605
606                         if (!isprint(c)) {      /* Skip non-printable characters */
607                                 break;
608                         }
609
610                         if (len >= (BUFSIZ - 2))        /* Need to leave space for enter */
611                                 break;
612
613                         len++;
614
615                         if (cursor == (len - 1)) {      /* Append if at the end of the line */
616                                 *(command + cursor) = c;
617                         } else {                        /* Insert otherwise */
618                                 memmove(command + cursor + 1, command + cursor,
619                                                 len - cursor - 1);
620
621                                 *(command + cursor) = c;
622
623                                 for (j = cursor; j < len; j++)
624                                         xwrite(outputFd, command + j, 1);
625                                 for (; j > cursor; j--)
626                                         xwrite(outputFd, "\033[D", 3);
627                         }
628
629                         cursor++;
630                         xwrite(outputFd, &c, 1);
631                         break;
632                 }
633                 if (c == '\t')
634                         lastWasTab = TRUE;
635                 else
636                         lastWasTab = FALSE;
637
638                 if (break_out)                  /* Enter is the command terminator, no more input. */
639                         break;
640         }
641
642         nr = len + 1;
643         setTermSettings(inputFd, (void *) &initial_settings);
644         reset_term = 0;
645
646
647         /* Handle command history log */
648         if (*(command)) {
649
650                 struct history *h = his_end;
651
652                 if (!h) {
653                         /* No previous history */
654                         h = his_front = malloc(sizeof(struct history));
655                         h->n = malloc(sizeof(struct history));
656
657                         h->p = NULL;
658                         h->s = strdup(command);
659                         h->n->p = h;
660                         h->n->n = NULL;
661                         h->n->s = NULL;
662                         his_end = h->n;
663                         history_counter++;
664                 } else {
665                         /* Add a new history command */
666                         h->n = malloc(sizeof(struct history));
667
668                         h->n->p = h;
669                         h->n->n = NULL;
670                         h->n->s = NULL;
671                         h->s = strdup(command);
672                         his_end = h->n;
673
674                         /* After max history, remove the oldest command */
675                         if (history_counter >= MAX_HISTORY) {
676
677                                 struct history *p = his_front->n;
678
679                                 p->p = NULL;
680                                 free(his_front->s);
681                                 free(his_front);
682                                 his_front = p;
683                         } else {
684                                 history_counter++;
685                         }
686                 }
687         }
688
689         return;
690 }
691
692 extern void cmdedit_init(void)
693 {
694         atexit(cmdedit_reset_term);
695         signal(SIGKILL, clean_up_and_die);
696         signal(SIGINT, clean_up_and_die);
697         signal(SIGQUIT, clean_up_and_die);
698         signal(SIGTERM, clean_up_and_die);
699 }
700 #endif                                                  /* BB_FEATURE_SH_COMMAND_EDITING */