0ce64beebf130c00943866cda8edab6cefb2c910
[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 /*
97  * TODO: Someday we want to implement 'horizontal scrolling' of the
98  * command-line when the user has typed more than the current width. This
99  * would allow the user to see a 'window' of what he has typed.
100  */
101 void
102 cmdedit_setwidth(int w)
103 {
104         if (w > 20) {
105                 cmdedit_termw = w;
106                 cmdedit_scroll = w / 3;
107         } else {
108                 errorMsg("\n*** Error: minimum screen width is 21\n");
109         }
110 }
111
112
113 void cmdedit_reset_term(void)
114 {
115         if (reset_term)
116                 /* sparc and other have broken termios support: use old termio handling. */
117                 setTermSettings(fileno(stdin), (void*) &initial_settings);
118 #ifdef BB_FEATURE_CLEAN_UP
119         if (his_front) {
120                 struct history *n;
121                 //while(his_front!=his_end) {
122                 while(his_front!=his_end) {
123                         n = his_front->n;
124                         free(his_front->s);
125                         free(his_front);
126                         his_front=n;
127                 }
128         }
129 #endif
130 }
131
132 void clean_up_and_die(int sig)
133 {
134         cmdedit_reset_term();
135         fprintf(stdout, "\n");
136         if (sig!=SIGINT)
137                 exit(TRUE);
138 }
139
140 /* Go to HOME position */
141 void input_home(int outputFd, int *cursor)
142 {
143         while (*cursor > 0) {
144                 xwrite(outputFd, "\b", 1);
145                 --*cursor;
146         }
147 }
148
149 /* Go to END position */
150 void input_end(int outputFd, int *cursor, int len)
151 {
152         while (*cursor < len) {
153                 xwrite(outputFd, "\033[C", 3);
154                 ++*cursor;
155         }
156 }
157
158 /* Delete the char in back of the cursor */
159 void input_backspace(char* command, int outputFd, int *cursor, int *len)
160 {
161         int j = 0;
162
163 /* Debug crap */
164 //fprintf(stderr, "\nerik: len=%d, cursor=%d, strlen(command)='%d'\n", *len, *cursor, strlen(command));
165 //xwrite(outputFd, command, *len);
166 //*cursor = *len;
167
168
169         if (*cursor > 0) {
170                 xwrite(outputFd, "\b \b", 3);
171                 --*cursor;
172                 memmove(command + *cursor, command + *cursor + 1,
173                                 BUFSIZ - *cursor + 1);
174
175                 for (j = *cursor; j < (BUFSIZ - 1); j++) {
176                         if (!*(command + j))
177                                 break;
178                         else
179                                 xwrite(outputFd, (command + j), 1);
180                 }
181
182                 xwrite(outputFd, " \b", 2);
183
184                 while (j-- > *cursor)
185                         xwrite(outputFd, "\b", 1);
186
187                 --*len;
188         }
189 }
190
191 /* Delete the char in front of the cursor */
192 void input_delete(char* command, int outputFd, int cursor, int *len)
193 {
194         int j = 0;
195
196         if (cursor == *len)
197                 return;
198         
199         memmove(command + cursor, command + cursor + 1,
200                         BUFSIZ - cursor - 1);
201         for (j = cursor; j < (BUFSIZ - 1); j++) {
202                 if (!*(command + j))
203                         break;
204                 else
205                         xwrite(outputFd, (command + j), 1);
206         }
207
208         xwrite(outputFd, " \b", 2);
209
210         while (j-- > cursor)
211                 xwrite(outputFd, "\b", 1);
212         --*len;
213 }
214
215 /* Move forward one charactor */
216 void input_forward(int outputFd, int *cursor, int len)
217 {
218         if (*cursor < len) {
219                 xwrite(outputFd, "\033[C", 3);
220                 ++*cursor;
221         }
222 }
223
224 /* Move back one charactor */
225 void input_backward(int outputFd, int *cursor)
226 {
227         if (*cursor > 0) {
228                 xwrite(outputFd, "\033[D", 3);
229                 --*cursor;
230         }
231 }
232
233
234
235 #ifdef BB_FEATURE_SH_TAB_COMPLETION
236 char** username_tab_completion(char* command, int *num_matches)
237 {
238         char **matches = (char **) NULL;
239         *num_matches=0;
240         fprintf(stderr, "\nin username_tab_completion\n");
241         return (matches);
242 }
243
244 #include <dirent.h>
245 char** exe_n_cwd_tab_completion(char* command, int *num_matches)
246 {
247         char *dirName;
248         char **matches = (char **) NULL;
249         DIR *dir;
250         struct dirent *next;
251                         
252         matches = malloc( sizeof(char*)*50);
253
254         /* Stick a wildcard onto the command, for later use */
255         strcat( command, "*");
256
257         /* Now wall the current directory */
258         dirName = get_current_dir_name();
259         dir = opendir(dirName);
260         if (!dir) {
261                 /* Don't print an error, just shut up and return */
262                 *num_matches=0;
263                 return (matches);
264         }
265         while ((next = readdir(dir)) != NULL) {
266
267                 /* Some quick sanity checks */
268                 if ((strcmp(next->d_name, "..") == 0)
269                         || (strcmp(next->d_name, ".") == 0)) {
270                         continue;
271                 } 
272                 /* See if this matches */
273                 if (check_wildcard_match(next->d_name, command) == TRUE) {
274                         /* Cool, found a match.  Add it to the list */
275                         matches[*num_matches] = malloc(strlen(next->d_name)+1);
276                         strcpy( matches[*num_matches], next->d_name);
277                         ++*num_matches;
278                         //matches = realloc( matches, sizeof(char*)*(*num_matches));
279                 }
280         }
281
282         return (matches);
283 }
284
285 void input_tab(char* command, char* prompt, int outputFd, int *cursor, int *len)
286 {
287         /* Do TAB completion */
288         static int num_matches=0;
289         static char **matches = (char **) NULL;
290         int pos = cursor;
291
292
293         if (lastWasTab == FALSE) {
294                 char *tmp, *tmp1, *matchBuf;
295
296                 /* For now, we will not bother with trying to distinguish
297                  * whether the cursor is in/at a command extression -- we
298                  * will always try all possible matches.  If you don't like
299                  * that then feel free to fix it.
300                  */
301
302                 /* Make a local copy of the string -- up 
303                  * to the position of the cursor */
304                 matchBuf = (char *) calloc(BUFSIZ, sizeof(char));
305                 strncpy(matchBuf, command, cursor);
306                 tmp=matchBuf;
307
308                 /* skip past any command seperator tokens */
309                 while (*tmp && (tmp1=strpbrk(tmp, ";|&{(`")) != NULL) {
310                         tmp=++tmp1;
311                         /* skip any leading white space */
312                         while (*tmp && isspace(*tmp)) 
313                                 ++tmp;
314                 }
315
316                 /* skip any leading white space */
317                 while (*tmp && isspace(*tmp)) 
318                         ++tmp;
319
320                 /* Free up any memory already allocated */
321                 if (matches) {
322                         free(matches);
323                         matches = (char **) NULL;
324                 }
325
326                 /* If the word starts with `~' and there is no slash in the word, 
327                  * then try completing this word as a username. */
328
329                 /* FIXME -- this check is broken! */
330                 if (*tmp == '~' && !strchr(tmp, '/'))
331                         matches = username_tab_completion(tmp, &num_matches);
332
333                 /* Try to match any executable in our path and everything 
334                  * in the current working directory that matches.  */
335                 if (!matches)
336                         matches = exe_n_cwd_tab_completion(tmp, &num_matches);
337
338                 /* Don't leak memory */
339                 free( matchBuf);
340
341                 /* Did we find exactly one match? */
342                 if (matches && num_matches==1) {
343                         /* write out the matched command */
344                         strncpy(command+pos, matches[0]+pos, strlen(matches[0])-pos);
345                         len=strlen(command);
346                         cursor=len;
347                         xwrite(outputFd, matches[0]+pos, strlen(matches[0])-pos);
348                         break;
349                 }
350         } else {
351                 /* Ok -- the last char was a TAB.  Since they
352                  * just hit TAB again, print a list of all the
353                  * available choices... */
354                 if ( matches && num_matches>0 ) {
355                         int i, col;
356
357                         /* Go to the next line */
358                         xwrite(outputFd, "\n", 1);
359                         /* Print the list of matches */
360                         for (i=0,col=0; i<num_matches; i++) {
361                                 char foo[17];
362                                 sprintf(foo, "%-14s  ", matches[i]);
363                                 col += xwrite(outputFd, foo, strlen(foo));
364                                 if (col > 60 && matches[i+1] != NULL) {
365                                         xwrite(outputFd, "\n", 1);
366                                         col = 0;
367                                 }
368                         }
369                         /* Go to the next line */
370                         xwrite(outputFd, "\n", 1);
371                         /* Rewrite the prompt */
372                         xwrite(outputFd, prompt, strlen(prompt));
373                         /* Rewrite the command */
374                         xwrite(outputFd, command, len);
375                         /* Put the cursor back to where it used to be */
376                         for (cursor=len; cursor > pos; cursor--)
377                                 xwrite(outputFd, "\b", 1);
378                 }
379         }
380 }
381 #endif
382
383 void get_previous_history(struct history **hp, char* command)
384 {
385         if ((*hp)->s)
386                 free((*hp)->s);
387         (*hp)->s = strdup(command);
388         *hp = (*hp)->p;
389 }
390
391 void get_next_history(struct history **hp, char* command)
392 {
393         if ((*hp)->s)
394                 free((*hp)->s);
395         (*hp)->s = strdup(command);
396         *hp = (*hp)->n;
397 }
398
399 /*
400  * This function is used to grab a character buffer
401  * from the input file descriptor and allows you to
402  * a string with full command editing (sortof like
403  * a mini readline).
404  *
405  * The following standard commands are not implemented:
406  * ESC-b -- Move back one word
407  * ESC-f -- Move forward one word
408  * ESC-d -- Delete back one word
409  * ESC-h -- Delete forward one word
410  * CTL-t -- Transpose two characters
411  *
412  * Furthermore, the "vi" command editing keys are not implemented.
413  *
414  * TODO: implement TAB command completion. :)
415  */
416 extern void cmdedit_read_input(char* prompt, char command[BUFSIZ])
417 {
418
419         int inputFd=fileno(stdin);
420         int outputFd=fileno(stdout);
421         int nr = 0;
422         int len = 0;
423         int j = 0;
424         int cursor = 0;
425         int break_out = 0;
426         int ret = 0;
427         int lastWasTab = FALSE;
428         char c = 0;
429         struct history *hp = his_end;
430
431         if (!reset_term) {
432                 
433                 getTermSettings(inputFd, (void*) &initial_settings);
434                 memcpy(&new_settings, &initial_settings, sizeof(struct termios));
435                 new_settings.c_cc[VMIN] = 1;
436                 new_settings.c_cc[VTIME] = 0;
437                 new_settings.c_cc[VINTR] = _POSIX_VDISABLE; /* Turn off CTRL-C, so we can trap it */
438                 new_settings.c_lflag &= ~ICANON;        /* unbuffered input */
439                 new_settings.c_lflag &= ~(ECHO|ECHOCTL|ECHONL); /* Turn off echoing */
440                 reset_term = 1;
441         }
442         setTermSettings(inputFd, (void*) &new_settings);
443
444         memset(command, 0, BUFSIZ);
445
446         while (1) {
447
448                 if ((ret = read(inputFd, &c, 1)) < 1)
449                         return;
450                 //fprintf(stderr, "got a '%c' (%d)\n", c, c);
451
452                 switch (c) {
453                 case '\n':
454                 case '\r':
455                         /* Enter */
456                         *(command + len++ + 1) = c;
457                         xwrite(outputFd, &c, 1);
458                         break_out = 1;
459                         break;
460                 case 1:
461                         /* Control-a -- Beginning of line */
462                         input_home(outputFd, &cursor);
463                 case 2:
464                         /* Control-b -- Move back one character */
465                         input_backward(outputFd, &cursor);
466                         break;
467                 case 3:
468                         /* Control-c -- leave the current line, 
469                          * and start over on the next line */ 
470
471                         /* Go to the next line */
472                         xwrite(outputFd, "\n", 1);
473
474                         /* Rewrite the prompt */
475                         xwrite(outputFd, prompt, strlen(prompt));
476
477                         /* Reset the command string */
478                         memset(command, 0, BUFSIZ);
479                         len = cursor = 0;
480
481                         break;
482                 case 4:
483                         /* Control-d -- Delete one character, or exit 
484                          * if the len=0 and no chars to delete */
485                         if (len == 0) {
486                                 xwrite(outputFd, "exit", 4);
487                                 clean_up_and_die(0);
488                         } else {
489                                 input_delete(command, outputFd, cursor, &len);
490                         }
491                         break;
492                 case 5:
493                         /* Control-e -- End of line */
494                         input_end(outputFd, &cursor, len);
495                         break;
496                 case 6:
497                         /* Control-f -- Move forward one character */
498                         input_forward(outputFd, &cursor, len);
499                         break;
500                 case '\b':
501                 case DEL:
502                         /* Control-h and DEL */
503                         input_backspace(command, outputFd, &cursor, &len);
504                         break;
505                 case '\t':
506 #ifdef BB_FEATURE_SH_TAB_COMPLETION
507                         input_tab(command, prompt, outputFd, &cursor, &len);
508 #endif
509                         break;
510                 case 14:
511                         /* Control-n -- Get next command in history */
512                         if (hp && hp->n && hp->n->s) {
513                                 get_next_history(&hp, command);
514                                 goto rewrite_line;
515                         } else {
516                                 xwrite(outputFd, "\007", 1);
517                         }
518                         break;
519                 case 16:
520                         /* Control-p -- Get previous command from history */
521                         if (hp && hp->p) {
522                                 get_previous_history(&hp, command);
523                                 goto rewrite_line;
524                         } else {
525                                 xwrite(outputFd, "\007", 1);
526                         }
527                         break;
528                 case ESC:{
529                                 /* escape sequence follows */
530                                 if ((ret = read(inputFd, &c, 1)) < 1)
531                                         return;
532
533                                 if (c == '[') { /* 91 */
534                                         if ((ret = read(inputFd, &c, 1)) < 1)
535                                                 return;
536
537                                         switch (c) {
538                                         case 'A':
539                                                 /* Up Arrow -- Get previous command from history */
540                                                 if (hp && hp->p) {
541                                                         get_previous_history(&hp, command);
542                                                         goto rewrite_line;
543                                                 } else {
544                                                         xwrite(outputFd, "\007", 1);
545                                                 }
546                                                 break;
547                                         case 'B':
548                                                 /* Down Arrow -- Get next command in history */
549                                                 if (hp && hp->n && hp->n->s) {
550                                                         get_next_history(&hp, command);
551                                                         goto rewrite_line;
552                                                 } else {
553                                                         xwrite(outputFd, "\007", 1);
554                                                 }
555                                                 break;
556
557                                                 /* Rewrite the line with the selected history item */
558                                           rewrite_line:
559                                                 /* erase old command from command line */
560                                                 len = strlen(command)-strlen(hp->s);
561
562                                                 while (len>cursor)
563                                                         input_delete(command, outputFd, cursor, &len);
564                                                 while (cursor>0)
565                                                         input_backspace(command, outputFd, &cursor, &len);
566                                                 input_home(outputFd, &cursor);
567                                                 
568                                                 /* write new command */
569                                                 strcpy(command, hp->s);
570                                                 len = strlen(hp->s);
571                                                 xwrite(outputFd, command, len);
572                                                 cursor = len;
573                                                 break;
574                                         case 'C':
575                                                 /* Right Arrow -- Move forward one character */
576                                                 input_forward(outputFd, &cursor, len);
577                                                 break;
578                                         case 'D':
579                                                 /* Left Arrow -- Move back one character */
580                                                 input_backward(outputFd, &cursor);
581                                                 break;
582                                         case '3':
583                                                 /* Delete */
584                                                 input_delete(command, outputFd, cursor, &len);
585                                                 break;
586                                         case '1':
587                                                 /* Home (Ctrl-A) */
588                                                 input_home(outputFd, &cursor);
589                                                 break;
590                                         case '4':
591                                                 /* End (Ctrl-E) */
592                                                 input_end(outputFd, &cursor, len);
593                                                 break;
594                                         default:
595                                                 xwrite(outputFd, "\007", 1);
596                                         }
597                                         if (c == '1' || c == '3' || c == '4')
598                                                 if ((ret = read(inputFd, &c, 1)) < 1)
599                                                         return; /* read 126 (~) */
600                                 }
601                                 if (c == 'O') {
602                                         /* 79 */
603                                         if ((ret = read(inputFd, &c, 1)) < 1)
604                                                 return;
605                                         switch (c) {
606                                         case 'H':
607                                                 /* Home (xterm) */
608                                                 input_home(outputFd, &cursor);
609                                                 break;
610                                         case 'F':
611                                                 /* End (xterm) */
612                                                 input_end(outputFd, &cursor, len);
613                                                 break;
614                                         default:
615                                                 xwrite(outputFd, "\007", 1);
616                                         }
617                                 }
618                                 c = 0;
619                                 break;
620                         }
621
622                 default:                                /* If it's regular input, do the normal thing */
623
624                         if (!isprint(c)) {      /* Skip non-printable characters */
625                                 break;
626                         }
627
628                         if (len >= (BUFSIZ - 2))        /* Need to leave space for enter */
629                                 break;
630
631                         len++;
632
633                         if (cursor == (len - 1)) {      /* Append if at the end of the line */
634                                 *(command + cursor) = c;
635                         } else {                        /* Insert otherwise */
636                                 memmove(command + cursor + 1, command + cursor,
637                                                 len - cursor - 1);
638
639                                 *(command + cursor) = c;
640
641                                 for (j = cursor; j < len; j++)
642                                         xwrite(outputFd, command + j, 1);
643                                 for (; j > cursor; j--)
644                                         xwrite(outputFd, "\033[D", 3);
645                         }
646
647                         cursor++;
648                         xwrite(outputFd, &c, 1);
649                         break;
650                 }
651                 if (c == '\t')
652                         lastWasTab = TRUE;
653                 else
654                         lastWasTab = FALSE;
655
656                 if (break_out)                  /* Enter is the command terminator, no more input. */
657                         break;
658         }
659
660         nr = len + 1;
661         setTermSettings(inputFd, (void *) &initial_settings);
662         reset_term = 0;
663
664
665         /* Handle command history log */
666         if (*(command)) {
667
668                 struct history *h = his_end;
669
670                 if (!h) {
671                         /* No previous history -- this memory is never freed */
672                         h = his_front = malloc(sizeof(struct history));
673                         h->n = malloc(sizeof(struct history));
674
675                         h->p = NULL;
676                         h->s = strdup(command);
677                         h->n->p = h;
678                         h->n->n = NULL;
679                         h->n->s = NULL;
680                         his_end = h->n;
681                         history_counter++;
682                 } else {
683                         /* Add a new history command -- this memory is never freed */
684                         h->n = malloc(sizeof(struct history));
685
686                         h->n->p = h;
687                         h->n->n = NULL;
688                         h->n->s = NULL;
689                         h->s = strdup(command);
690                         his_end = h->n;
691
692                         /* After max history, remove the oldest command */
693                         if (history_counter >= MAX_HISTORY) {
694
695                                 struct history *p = his_front->n;
696
697                                 p->p = NULL;
698                                 free(his_front->s);
699                                 free(his_front);
700                                 his_front = p;
701                         } else {
702                                 history_counter++;
703                         }
704                 }
705         }
706
707         return;
708 }
709
710 extern void cmdedit_init(void)
711 {
712         atexit(cmdedit_reset_term);
713         signal(SIGKILL, clean_up_and_die);
714         signal(SIGINT, clean_up_and_die);
715         signal(SIGQUIT, clean_up_and_die);
716         signal(SIGTERM, clean_up_and_die);
717 }
718 #endif                                                  /* BB_FEATURE_SH_COMMAND_EDITING */