807a5bf4760bb826499d050cd7232f29f0d5ad16
[oweals/busybox.git] / miscutils / less.c
1 /* vi: set sw=4 ts=4: */
2 /*
3  * Mini less implementation for busybox
4  *
5  * Copyright (C) 2005 by Rob Sullivan <cogito.ergo.cogito@gmail.com>
6  *
7  * Licensed under the GPL v2 or later, see the file LICENSE in this tarball.
8  */
9
10 /*
11  * TODO:
12  * - Add more regular expression support - search modifiers, certain matches, etc.
13  * - Add more complex bracket searching - currently, nested brackets are
14  *   not considered.
15  * - Add support for "F" as an input. This causes less to act in
16  *   a similar way to tail -f.
17  * - Allow horizontal scrolling.
18  *
19  * Notes:
20  * - the inp file pointer is used so that keyboard input works after
21  *   redirected input has been read from stdin
22  */
23
24 #include "busybox.h"
25 #if ENABLE_FEATURE_LESS_REGEXP
26 #include "xregex.h"
27 #endif
28
29 /* FIXME: currently doesn't work right */
30 #undef ENABLE_FEATURE_LESS_FLAGCS
31 #define ENABLE_FEATURE_LESS_FLAGCS 0
32
33 /* The escape codes for highlighted and normal text */
34 #define HIGHLIGHT "\033[7m"
35 #define NORMAL "\033[0m"
36 /* The escape code to clear the screen */
37 #define CLEAR "\033[H\033[J"
38 /* The escape code to clear to end of line */
39 #define CLEAR_2_EOL "\033[K"
40
41 /* These are the escape sequences corresponding to special keys */
42 enum {
43         REAL_KEY_UP = 'A',
44         REAL_KEY_DOWN = 'B',
45         REAL_KEY_RIGHT = 'C',
46         REAL_KEY_LEFT = 'D',
47         REAL_PAGE_UP = '5',
48         REAL_PAGE_DOWN = '6',
49         REAL_KEY_HOME = '7',
50         REAL_KEY_END = '8',
51
52 /* These are the special codes assigned by this program to the special keys */
53         KEY_UP = 20,
54         KEY_DOWN = 21,
55         KEY_RIGHT = 22,
56         KEY_LEFT = 23,
57         PAGE_UP = 24,
58         PAGE_DOWN = 25,
59         KEY_HOME = 26,
60         KEY_END = 27,
61
62 /* Absolute max of lines eaten */
63         MAXLINES = CONFIG_FEATURE_LESS_MAXLINES,
64
65 /* This many "after the end" lines we will show (at max) */
66         TILDES = 1,
67 };
68
69 static unsigned max_displayed_line;
70 static unsigned width;
71 static const char *empty_line_marker = "~";
72
73 static char *filename;
74 static char **files;
75 static unsigned num_files = 1;
76 static unsigned current_file = 1;
77 static const char **buffer;
78 static const char **flines;
79 static int cur_fline; /* signed */
80 static unsigned max_fline;
81 static unsigned max_lineno; /* this one tracks linewrap */
82
83 static ssize_t eof_error = 1; /* eof if 0, error if < 0 */
84 static char terminated = 1;
85 static size_t readpos;
86 static size_t readeof;
87 /* last position in last line, taking into account tabs */
88 static size_t linepos;
89
90 /* Command line options */
91 enum {
92         FLAG_E = 1,
93         FLAG_M = 1 << 1,
94         FLAG_m = 1 << 2,
95         FLAG_N = 1 << 3,
96         FLAG_TILDE = 1 << 4,
97 /* hijack command line options variable for internal state vars */
98         LESS_STATE_MATCH_BACKWARDS = 1 << 15,
99 };
100
101 #if ENABLE_FEATURE_LESS_MARKS
102 static unsigned mark_lines[15][2];
103 static unsigned num_marks;
104 #endif
105
106 #if ENABLE_FEATURE_LESS_REGEXP
107 static unsigned *match_lines;
108 static int match_pos; /* signed! */
109 static unsigned num_matches;
110 static regex_t pattern;
111 static unsigned pattern_valid;
112 #else
113 enum { pattern_valid = 0 };
114 #endif
115
116 static struct termios term_orig, term_vi;
117
118 /* File pointer to get input from */
119 static int kbd_fd;
120
121 /* Reset terminal input to normal */
122 static void set_tty_cooked(void)
123 {
124         fflush(stdout);
125         tcsetattr(kbd_fd, TCSANOW, &term_orig);
126 }
127
128 /* Exit the program gracefully */
129 static void less_exit(int code)
130 {
131         /* TODO: We really should save the terminal state when we start,
132          * and restore it when we exit. Less does this with the
133          * "ti" and "te" termcap commands; can this be done with
134          * only termios.h? */
135         putchar('\n');
136         fflush_stdout_and_exit(code);
137 }
138
139 /* Move the cursor to a position (x,y), where (0,0) is the
140    top-left corner of the console */
141 static void move_cursor(int line, int row)
142 {
143         printf("\033[%u;%uH", line, row);
144 }
145
146 static void clear_line(void)
147 {
148         printf("\033[%u;0H" CLEAR_2_EOL, max_displayed_line + 2);
149 }
150
151 static void print_hilite(const char *str)
152 {
153         printf(HIGHLIGHT"%s"NORMAL, str);
154 }
155
156 static void print_statusline(const char *str)
157 {
158         clear_line();
159         printf(HIGHLIGHT"%.*s"NORMAL, width - 1, str);
160 }
161
162 #if ENABLE_FEATURE_LESS_REGEXP
163 static void fill_match_lines(unsigned pos);
164 #else
165 #define fill_match_lines(pos) ((void)0)
166 #endif
167
168
169 static void read_lines(void)
170 {
171 #define readbuf bb_common_bufsiz1
172         char *current_line, *p;
173         USE_FEATURE_LESS_REGEXP(unsigned old_max_fline = max_fline;)
174         int w = width;
175         char last_terminated = terminated;
176
177         if (option_mask32 & FLAG_N)
178                 w -= 8;
179
180         current_line = xmalloc(w);
181         p = current_line;
182         max_fline += last_terminated;
183         if (!last_terminated) {
184                 const char *cp = flines[max_fline];
185                 if (option_mask32 & FLAG_N)
186                         cp += 8;
187                 strcpy(current_line, cp);
188                 p += strlen(current_line);
189         } else {
190                 linepos = 0;
191         }
192
193         while (1) {
194  again:
195                 *p = '\0';
196                 terminated = 0;
197                 while (1) {
198                         char c;
199                         if (readpos >= readeof) {
200                                 ndelay_on(0);
201                                 eof_error = safe_read(0, readbuf, sizeof(readbuf));
202                                 ndelay_off(0);
203                                 readpos = 0;
204                                 readeof = eof_error;
205                                 if (eof_error < 0) {
206                                         readeof = 0;
207                                         if (errno != EAGAIN)
208                                                 print_statusline("read error");
209                                 }
210                                 if (eof_error <= 0) {
211                                         goto reached_eof;
212                                 }
213                         }
214                         c = readbuf[readpos];
215                         if (c == '\t')
216                                 linepos += (linepos^7) & 7;
217                         linepos++;
218                         if (linepos >= w)
219                                 break;
220                         readpos++;
221                         if (c == '\n') { terminated = 1; break; }
222                         /* NUL is substituted by '\n'! */
223                         if (c == '\0') c = '\n';
224                         *p++ = c;
225                         *p = '\0';
226                 }
227                 /* Corner case: linewrap with only "" wrapping to next line */
228                 /* Looks ugly on screen, so we do not store this empty line */
229                 if (!last_terminated && !current_line[0]) {
230                         last_terminated = 1;
231                         max_lineno++;
232                         goto again;
233                 }
234  reached_eof:
235                 last_terminated = terminated;
236                 flines = xrealloc(flines, (max_fline+1) * sizeof(char *));
237                 if (option_mask32 & FLAG_N) {
238                         /* Width of 7 preserves tab spacing in the text */
239                         flines[max_fline] = xasprintf(
240                                 (max_lineno <= 9999999) ? "%7u %s" : "%07u %s",
241                                 max_lineno % 10000000, current_line);
242                         free(current_line);
243                         if (terminated)
244                                 max_lineno++;
245                 } else {
246                         flines[max_fline] = xrealloc(current_line, strlen(current_line)+1);
247                 }
248                 if (max_fline >= MAXLINES)
249                         break;
250                 if (max_fline > cur_fline + max_displayed_line)
251                         break;
252                 if (eof_error <= 0) {
253                         if (eof_error < 0 && errno == EAGAIN) {
254                                 /* not yet eof or error, reset flag (or else
255                                  * we will hog CPU - select() will return
256                                  * immediately */
257                                 eof_error = 1;
258                         }
259                         break;
260                 }
261                 max_fline++;
262                 current_line = xmalloc(w);
263                 p = current_line;
264                 linepos = 0;
265         }
266         fill_match_lines(old_max_fline);
267 #undef readbuf
268 }
269
270 #if ENABLE_FEATURE_LESS_FLAGS
271 /* Interestingly, writing calc_percent as a function saves around 32 bytes
272  * on my build. */
273 static int calc_percent(void)
274 {
275         unsigned p = (100 * (cur_fline+max_displayed_line+1) + max_fline/2) / (max_fline+1);
276         return p <= 100 ? p : 100;
277 }
278
279 /* Print a status line if -M was specified */
280 static void m_status_print(void)
281 {
282         int percentage;
283
284         clear_line();
285         printf(HIGHLIGHT"%s", filename);
286         if (num_files > 1)
287                 printf(" (file %i of %i)", current_file, num_files);
288         printf(" lines %i-%i/%i ",
289                         cur_fline + 1, cur_fline + max_displayed_line + 1,
290                         max_fline + 1);
291         if (cur_fline >= max_fline - max_displayed_line) {
292                 printf("(END)"NORMAL);
293                 if (num_files > 1 && current_file != num_files)
294                         printf(HIGHLIGHT" - next: %s"NORMAL, files[current_file]);
295                 return;
296         }
297         percentage = calc_percent();
298         printf("%i%%"NORMAL, percentage);
299 }
300 #endif
301
302 /* Print the status line */
303 static void status_print(void)
304 {
305         const char *p;
306
307         /* Change the status if flags have been set */
308 #if ENABLE_FEATURE_LESS_FLAGS
309         if (option_mask32 & (FLAG_M|FLAG_m)) {
310                 m_status_print();
311                 return;
312         }
313         /* No flags set */
314 #endif
315
316         clear_line();
317         if (cur_fline && cur_fline < max_fline - max_displayed_line) {
318                 putchar(':');
319                 return;
320         }
321         p = "(END)";
322         if (!cur_fline)
323                 p = filename;
324         if (num_files > 1) {
325                 printf(HIGHLIGHT"%s (file %i of %i)"NORMAL,
326                                 p, current_file, num_files);
327                 return;
328         }
329         print_hilite(p);
330 }
331
332 static char controls[] =
333         /* NUL: never encountered; TAB: not converted */
334         /**/"\x01\x02\x03\x04\x05\x06\x07\x08"  "\x0a\x0b\x0c\x0d\x0e\x0f"
335         "\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1a\x1b\x1c\x1d\x1e\x1f"
336         "\x7f\x9b"; /* DEL and infamous Meta-ESC :( */
337 static char ctrlconv[] =
338         /* '\n': it's a former NUL - subst with '@', not 'J' */
339         "\x40\x41\x42\x43\x44\x45\x46\x47\x48\x49\x40\x4b\x4c\x4d\x4e\x4f"
340         "\x50\x51\x52\x53\x54\x55\x56\x57\x58\x59\x5a\x5b\x5c\x5d\x5e\x5f";
341
342 #if ENABLE_FEATURE_LESS_REGEXP
343 static void print_found(const char *line)
344 {
345         int match_status;
346         int eflags;
347         char *growline;
348         regmatch_t match_structs;
349
350         char buf[width];
351         const char *str = line;
352         char *p = buf;
353         size_t n;
354
355         while (*str) {
356                 n = strcspn(str, controls);
357                 if (n) {
358                         if (!str[n]) break;
359                         memcpy(p, str, n);
360                         p += n;
361                         str += n;
362                 }
363                 n = strspn(str, controls);
364                 memset(p, '.', n);
365                 p += n;
366                 str += n;
367         }
368         strcpy(p, str);
369
370         /* buf[] holds quarantined version of str */
371
372         /* Each part of the line that matches has the HIGHLIGHT
373            and NORMAL escape sequences placed around it.
374            NB: we regex against line, but insert text
375            from quarantined copy (buf[]) */
376         str = buf;
377         growline = NULL;
378         eflags = 0;
379         goto start;
380
381         while (match_status == 0) {
382                 char *new = xasprintf("%s%.*s"HIGHLIGHT"%.*s"NORMAL,
383                                 growline ? : "",
384                                 match_structs.rm_so, str,
385                                 match_structs.rm_eo - match_structs.rm_so,
386                                                 str + match_structs.rm_so);
387                 free(growline); growline = new;
388                 str += match_structs.rm_eo;
389                 line += match_structs.rm_eo;
390                 eflags = REG_NOTBOL;
391  start:
392                 /* Most of the time doesn't find the regex, optimize for that */
393                 match_status = regexec(&pattern, line, 1, &match_structs, eflags);
394         }
395
396         if (!growline) {
397                 printf(CLEAR_2_EOL"%s\n", str);
398                 return;
399         }
400         printf(CLEAR_2_EOL"%s%s\n", growline, str);
401         free(growline);
402 }
403 #else
404 void print_found(const char *line);
405 #endif
406
407 static void print_ascii(const char *str)
408 {
409         char buf[width];
410         char *p;
411         size_t n;
412
413         printf(CLEAR_2_EOL);
414         while (*str) {
415                 n = strcspn(str, controls);
416                 if (n) {
417                         if (!str[n]) break;
418                         printf("%.*s", n, str);
419                         str += n;
420                 }
421                 n = strspn(str, controls);
422                 p = buf;
423                 do {
424                         if (*str == 0x7f)
425                                 *p++ = '?';
426                         else if (*str == (char)0x9b)
427                         /* VT100's CSI, aka Meta-ESC. Who's inventor? */
428                         /* I want to know who committed this sin */
429                                 *p++ = '{';
430                         else
431                                 *p++ = ctrlconv[(unsigned char)*str];
432                         str++;
433                 } while (--n);
434                 *p = '\0';
435                 print_hilite(buf);
436         }
437         puts(str);
438 }
439
440 /* Print the buffer */
441 static void buffer_print(void)
442 {
443         int i;
444
445         move_cursor(0, 0);
446         for (i = 0; i <= max_displayed_line; i++)
447                 if (pattern_valid)
448                         print_found(buffer[i]);
449                 else
450                         print_ascii(buffer[i]);
451         status_print();
452 }
453
454 static void buffer_fill_and_print(void)
455 {
456         int i;
457         for (i = 0; i <= max_displayed_line && cur_fline + i <= max_fline; i++) {
458                 buffer[i] = flines[cur_fline + i];
459         }
460         for (; i <= max_displayed_line; i++) {
461                 buffer[i] = empty_line_marker;
462         }
463         buffer_print();
464 }
465
466 /* Move the buffer up and down in the file in order to scroll */
467 static void buffer_down(int nlines)
468 {
469         int diff;
470         cur_fline += nlines;
471         read_lines();
472
473         if (cur_fline + max_displayed_line > max_fline + TILDES) {
474                 cur_fline -= nlines;
475                 diff = max_fline - (cur_fline + max_displayed_line) + TILDES;
476                 /* As the number of lines requested was too large, we just move
477                 to the end of the file */
478                 if (diff > 0)
479                         cur_fline += diff;
480         }
481         buffer_fill_and_print();
482 }
483
484 static void buffer_up(int nlines)
485 {
486         cur_fline -= nlines;
487         if (cur_fline < 0) cur_fline = 0;
488         read_lines();
489         buffer_fill_and_print();
490 }
491
492 static void buffer_line(int linenum)
493 {
494         if (linenum < 0)
495                 linenum = 0;
496         cur_fline = linenum;
497         read_lines();
498         if (linenum + max_displayed_line > max_fline)
499                 linenum = max_fline - max_displayed_line + TILDES;
500         cur_fline = linenum;
501         buffer_fill_and_print();
502 }
503
504 static void open_file_and_read_lines(void)
505 {
506         if (filename) {
507                 int fd = xopen(filename, O_RDONLY);
508                 dup2(fd, 0);
509                 if (fd) close(fd);
510         } else {
511                 /* "less" with no arguments in argv[] */
512                 /* For status line only */
513                 filename = xstrdup(bb_msg_standard_input);
514         }
515         readpos = 0;
516         readeof = 0;
517         linepos = 0;
518         terminated = 1;
519         read_lines();
520 }
521
522 /* Reinitialize everything for a new file - free the memory and start over */
523 static void reinitialize(void)
524 {
525         int i;
526
527         if (flines) {
528                 for (i = 0; i <= max_fline; i++)
529                         free((void*)(flines[i]));
530                 free(flines);
531                 flines = NULL;
532         }
533
534         max_fline = -1;
535         cur_fline = 0;
536         max_lineno = 0;
537         open_file_and_read_lines();
538         buffer_fill_and_print();
539 }
540
541 static void getch_nowait(char* input, int sz)
542 {
543         ssize_t rd;
544         fd_set readfds;
545  again:
546         fflush(stdout);
547
548         /* NB: select returns whenever read will not block. Therefore:
549          * (a) with O_NONBLOCK'ed fds select will return immediately
550          * (b) if eof is reached, select will also return
551          *     because read will immediately return 0 bytes.
552          * Even if select says that input is available, read CAN block
553          * (switch fd into O_NONBLOCK'ed mode to avoid it)
554          */
555         FD_ZERO(&readfds);
556         if (max_fline <= cur_fline + max_displayed_line
557          && eof_error > 0 /* did NOT reach eof yet */
558         ) {
559                 /* We are interested in stdin */
560                 FD_SET(0, &readfds);
561         }
562         FD_SET(kbd_fd, &readfds);
563         tcsetattr(kbd_fd, TCSANOW, &term_vi);
564         select(kbd_fd + 1, &readfds, NULL, NULL, NULL);
565
566         input[0] = '\0';
567         ndelay_on(kbd_fd);
568         rd = read(kbd_fd, input, sz);
569         ndelay_off(kbd_fd);
570         if (rd < 0) {
571                 /* No keyboard input, but we have input on stdin! */
572                 if (errno != EAGAIN) /* Huh?? */
573                         return;
574                 read_lines();
575                 buffer_fill_and_print();
576                 goto again;
577         }
578 }
579
580 /* Grab a character from input without requiring the return key. If the
581  * character is ASCII \033, get more characters and assign certain sequences
582  * special return codes. Note that this function works best with raw input. */
583 static int less_getch(void)
584 {
585         char input[16];
586         unsigned i;
587  again:
588         getch_nowait(input, sizeof(input));
589         /* Detect escape sequences (i.e. arrow keys) and handle
590          * them accordingly */
591
592         if (input[0] == '\033' && input[1] == '[') {
593                 set_tty_cooked();
594                 i = input[2] - REAL_KEY_UP;
595                 if (i < 4)
596                         return 20 + i;
597                 i = input[2] - REAL_PAGE_UP;
598                 if (i < 4)
599                         return 24 + i;
600                 return 0;
601         }
602         /* Reject almost all control chars */
603         i = input[0];
604         if (i < ' ' && i != 0x0d && i != 8) goto again;
605         set_tty_cooked();
606         return i;
607 }
608
609 static char* less_gets(int sz)
610 {
611         char c;
612         int i = 0;
613         char *result = xzalloc(1);
614         while (1) {
615                 fflush(stdout);
616
617                 /* I be damned if I know why is it needed *repeatedly*,
618                  * but it is needed. Is it because of stdio? */
619                 tcsetattr(kbd_fd, TCSANOW, &term_vi);
620
621                 read(kbd_fd, &c, 1);
622                 if (c == 0x0d)
623                         return result;
624                 if (c == 0x7f)
625                         c = 8;
626                 if (c == 8 && i) {
627                         printf("\x8 \x8");
628                         i--;
629                 }
630                 if (c < ' ')
631                         continue;
632                 if (i >= width - sz - 1)
633                         continue; /* len limit */
634                 putchar(c);
635                 result[i++] = c;
636                 result = xrealloc(result, i+1);
637                 result[i] = '\0';
638         }
639 }
640
641 static void examine_file(void)
642 {
643         print_statusline("Examine: ");
644         free(filename);
645         filename = less_gets(sizeof("Examine: ")-1);
646         /* files start by = argv. why we assume that argv is infinitely long??
647         files[num_files] = filename;
648         current_file = num_files + 1;
649         num_files++; */
650         files[0] = filename;
651         num_files = current_file = 1;
652         reinitialize();
653 }
654
655 /* This function changes the file currently being paged. direction can be one of the following:
656  * -1: go back one file
657  *  0: go to the first file
658  *  1: go forward one file */
659 static void change_file(int direction)
660 {
661         if (current_file != ((direction > 0) ? num_files : 1)) {
662                 current_file = direction ? current_file + direction : 1;
663                 free(filename);
664                 filename = xstrdup(files[current_file - 1]);
665                 reinitialize();
666         } else {
667                 print_statusline(direction > 0 ? "No next file" : "No previous file");
668         }
669 }
670
671 static void remove_current_file(void)
672 {
673         int i;
674
675         if (num_files < 2)
676                 return;
677
678         if (current_file != 1) {
679                 change_file(-1);
680                 for (i = 3; i <= num_files; i++)
681                         files[i - 2] = files[i - 1];
682                 num_files--;
683         } else {
684                 change_file(1);
685                 for (i = 2; i <= num_files; i++)
686                         files[i - 2] = files[i - 1];
687                 num_files--;
688                 current_file--;
689         }
690 }
691
692 static void colon_process(void)
693 {
694         int keypress;
695
696         /* Clear the current line and print a prompt */
697         print_statusline(" :");
698
699         keypress = less_getch();
700         switch (keypress) {
701         case 'd':
702                 remove_current_file();
703                 break;
704         case 'e':
705                 examine_file();
706                 break;
707 #if ENABLE_FEATURE_LESS_FLAGS
708         case 'f':
709                 m_status_print();
710                 break;
711 #endif
712         case 'n':
713                 change_file(1);
714                 break;
715         case 'p':
716                 change_file(-1);
717                 break;
718         case 'q':
719                 less_exit(0);
720                 break;
721         case 'x':
722                 change_file(0);
723                 break;
724         }
725 }
726
727 #if ENABLE_FEATURE_LESS_REGEXP
728 static int normalize_match_pos(int match)
729 {
730         match_pos = match;
731         if (match >= num_matches)
732                 match_pos = num_matches - 1;
733         if (match < 0)
734                 match_pos = 0;
735         return match_pos;
736 }
737
738 static void goto_match(int match)
739 {
740         if (num_matches)
741                 buffer_line(match_lines[normalize_match_pos(match)]);
742 }
743
744 static void fill_match_lines(unsigned pos)
745 {
746         if (!pattern_valid)
747                 return;
748         /* Run the regex on each line of the current file */
749         while (pos <= max_fline) {
750                 /* If this line matches */
751                 if (regexec(&pattern, flines[pos], 0, NULL, 0) == 0
752                 /* and we didn't match it last time */
753                  && !(num_matches && match_lines[num_matches-1] == pos)
754                 ) {
755                         match_lines = xrealloc(match_lines, (num_matches+1) * sizeof(int));
756                         match_lines[num_matches++] = pos;
757                 }
758                 pos++;
759         }
760 }
761
762 static void regex_process(void)
763 {
764         char *uncomp_regex, *err;
765
766         /* Reset variables */
767         free(match_lines);
768         match_lines = NULL;
769         match_pos = 0;
770         num_matches = 0;
771         if (pattern_valid) {
772                 regfree(&pattern);
773                 pattern_valid = 0;
774         }
775
776         /* Get the uncompiled regular expression from the user */
777         clear_line();
778         putchar((option_mask32 & LESS_STATE_MATCH_BACKWARDS) ? '?' : '/');
779         uncomp_regex = less_gets(1);
780         if (!uncomp_regex[0]) {
781                 free(uncomp_regex);
782                 buffer_print();
783                 return;
784         }
785
786         /* Compile the regex and check for errors */
787         err = regcomp_or_errmsg(&pattern, uncomp_regex, 0);
788         free(uncomp_regex);
789         if (err) {
790                 print_statusline(err);
791                 free(err);
792                 return;
793         }
794         pattern_valid = 1;
795         match_pos = 0;
796
797         fill_match_lines(0);
798
799         if (num_matches == 0 || max_fline <= max_displayed_line) {
800                 buffer_print();
801                 return;
802         }
803         while (match_pos < num_matches) {
804                 if (match_lines[match_pos] > cur_fline)
805                         break;
806                 match_pos++;
807         }
808         if (option_mask32 & LESS_STATE_MATCH_BACKWARDS)
809                 match_pos--;
810         buffer_line(match_lines[normalize_match_pos(match_pos)]);
811 }
812 #endif
813
814 static void number_process(int first_digit)
815 {
816         int i = 1;
817         int num;
818         char num_input[sizeof(int)*4]; /* more than enough */
819         char keypress;
820
821         num_input[0] = first_digit;
822
823         /* Clear the current line, print a prompt, and then print the digit */
824         clear_line();
825         printf(":%c", first_digit);
826
827         /* Receive input until a letter is given */
828         while (i < sizeof(num_input)-1) {
829                 num_input[i] = less_getch();
830                 if (!num_input[i] || !isdigit(num_input[i]))
831                         break;
832                 putchar(num_input[i]);
833                 i++;
834         }
835
836         /* Take the final letter out of the digits string */
837         keypress = num_input[i];
838         num_input[i] = '\0';
839         num = bb_strtou(num_input, NULL, 10);
840         /* on format error, num == -1 */
841         if (num < 1 || num > MAXLINES) {
842                 buffer_print();
843                 return;
844         }
845
846         /* We now know the number and the letter entered, so we process them */
847         switch (keypress) {
848         case KEY_DOWN: case 'z': case 'd': case 'e': case ' ': case '\015':
849                 buffer_down(num);
850                 break;
851         case KEY_UP: case 'b': case 'w': case 'y': case 'u':
852                 buffer_up(num);
853                 break;
854         case 'g': case '<': case 'G': case '>':
855                 cur_fline = num + max_displayed_line;
856                 read_lines();
857                 buffer_line(num - 1);
858                 break;
859         case 'p': case '%':
860                 num = num * (max_fline / 100); /* + max_fline / 2; */
861                 cur_fline = num + max_displayed_line;
862                 read_lines();
863                 buffer_line(num);
864                 break;
865 #if ENABLE_FEATURE_LESS_REGEXP
866         case 'n':
867                 goto_match(match_pos + num);
868                 break;
869         case '/':
870                 option_mask32 &= ~LESS_STATE_MATCH_BACKWARDS;
871                 regex_process();
872                 break;
873         case '?':
874                 option_mask32 |= LESS_STATE_MATCH_BACKWARDS;
875                 regex_process();
876                 break;
877 #endif
878         }
879 }
880
881 #if ENABLE_FEATURE_LESS_FLAGCS
882 static void flag_change(void)
883 {
884         int keypress;
885
886         clear_line();
887         putchar('-');
888         keypress = less_getch();
889
890         switch (keypress) {
891         case 'M':
892                 option_mask32 ^= FLAG_M;
893                 break;
894         case 'm':
895                 option_mask32 ^= FLAG_m;
896                 break;
897         case 'E':
898                 option_mask32 ^= FLAG_E;
899                 break;
900         case '~':
901                 option_mask32 ^= FLAG_TILDE;
902                 break;
903         }
904 }
905
906 static void show_flag_status(void)
907 {
908         int keypress;
909         int flag_val;
910
911         clear_line();
912         putchar('_');
913         keypress = less_getch();
914
915         switch (keypress) {
916         case 'M':
917                 flag_val = option_mask32 & FLAG_M;
918                 break;
919         case 'm':
920                 flag_val = option_mask32 & FLAG_m;
921                 break;
922         case '~':
923                 flag_val = option_mask32 & FLAG_TILDE;
924                 break;
925         case 'N':
926                 flag_val = option_mask32 & FLAG_N;
927                 break;
928         case 'E':
929                 flag_val = option_mask32 & FLAG_E;
930                 break;
931         default:
932                 flag_val = 0;
933                 break;
934         }
935
936         clear_line();
937         printf(HIGHLIGHT"The status of the flag is: %u"NORMAL, flag_val != 0);
938 }
939 #endif
940
941 static void save_input_to_file(void)
942 {
943         const char *msg = "";
944         char *current_line;
945         int i;
946         FILE *fp;
947
948         print_statusline("Log file: ");
949         current_line = less_gets(sizeof("Log file: ")-1);
950         if (strlen(current_line) > 0) {
951                 fp = fopen(current_line, "w");
952                 if (!fp) {
953                         msg = "Error opening log file";
954                         goto ret;
955                 }
956                 for (i = 0; i <= max_fline; i++)
957                         fprintf(fp, "%s\n", flines[i]);
958                 fclose(fp);
959                 msg = "Done";
960         }
961  ret:
962         print_statusline(msg);
963         free(current_line);
964 }
965
966 #if ENABLE_FEATURE_LESS_MARKS
967 static void add_mark(void)
968 {
969         int letter;
970
971         print_statusline("Mark: ");
972         letter = less_getch();
973
974         if (isalpha(letter)) {
975                 /* If we exceed 15 marks, start overwriting previous ones */
976                 if (num_marks == 14)
977                         num_marks = 0;
978
979                 mark_lines[num_marks][0] = letter;
980                 mark_lines[num_marks][1] = cur_fline;
981                 num_marks++;
982         } else {
983                 print_statusline("Invalid mark letter");
984         }
985 }
986
987 static void goto_mark(void)
988 {
989         int letter;
990         int i;
991
992         print_statusline("Go to mark: ");
993         letter = less_getch();
994         clear_line();
995
996         if (isalpha(letter)) {
997                 for (i = 0; i <= num_marks; i++)
998                         if (letter == mark_lines[i][0]) {
999                                 buffer_line(mark_lines[i][1]);
1000                                 break;
1001                         }
1002                 if (num_marks == 14 && letter != mark_lines[14][0])
1003                         print_statusline("Mark not set");
1004         } else
1005                 print_statusline("Invalid mark letter");
1006 }
1007 #endif
1008
1009 #if ENABLE_FEATURE_LESS_BRACKETS
1010 static char opp_bracket(char bracket)
1011 {
1012         switch (bracket) {
1013         case '{': case '[':
1014                 return bracket + 2;
1015         case '(':
1016                 return ')';
1017         case '}': case ']':
1018                 return bracket - 2;
1019         case ')':
1020                 return '(';
1021         }
1022         return 0;
1023 }
1024
1025 static void match_right_bracket(char bracket)
1026 {
1027         int bracket_line = -1;
1028         int i;
1029
1030         if (strchr(flines[cur_fline], bracket) == NULL) {
1031                 print_statusline("No bracket in top line");
1032                 return;
1033         }
1034         for (i = cur_fline + 1; i < max_fline; i++) {
1035                 if (strchr(flines[i], opp_bracket(bracket)) != NULL) {
1036                         bracket_line = i;
1037                         break;
1038                 }
1039         }
1040         if (bracket_line == -1)
1041                 print_statusline("No matching bracket found");
1042         buffer_line(bracket_line - max_displayed_line);
1043 }
1044
1045 static void match_left_bracket(char bracket)
1046 {
1047         int bracket_line = -1;
1048         int i;
1049
1050         if (strchr(flines[cur_fline + max_displayed_line], bracket) == NULL) {
1051                 print_statusline("No bracket in bottom line");
1052                 return;
1053         }
1054
1055         for (i = cur_fline + max_displayed_line; i >= 0; i--) {
1056                 if (strchr(flines[i], opp_bracket(bracket)) != NULL) {
1057                         bracket_line = i;
1058                         break;
1059                 }
1060         }
1061         if (bracket_line == -1)
1062                 print_statusline("No matching bracket found");
1063         buffer_line(bracket_line);
1064 }
1065 #endif  /* FEATURE_LESS_BRACKETS */
1066
1067 static void keypress_process(int keypress)
1068 {
1069         switch (keypress) {
1070         case KEY_DOWN: case 'e': case 'j': case 0x0d:
1071                 buffer_down(1);
1072                 break;
1073         case KEY_UP: case 'y': case 'k':
1074                 buffer_up(1);
1075                 break;
1076         case PAGE_DOWN: case ' ': case 'z':
1077                 buffer_down(max_displayed_line + 1);
1078                 break;
1079         case PAGE_UP: case 'w': case 'b':
1080                 buffer_up(max_displayed_line + 1);
1081                 break;
1082         case 'd':
1083                 buffer_down((max_displayed_line + 1) / 2);
1084                 break;
1085         case 'u':
1086                 buffer_up((max_displayed_line + 1) / 2);
1087                 break;
1088         case KEY_HOME: case 'g': case 'p': case '<': case '%':
1089                 buffer_line(0);
1090                 break;
1091         case KEY_END: case 'G': case '>':
1092                 cur_fline = MAXLINES;
1093                 read_lines();
1094                 buffer_line(cur_fline);
1095                 break;
1096         case 'q': case 'Q':
1097                 less_exit(0);
1098                 break;
1099 #if ENABLE_FEATURE_LESS_MARKS
1100         case 'm':
1101                 add_mark();
1102                 buffer_print();
1103                 break;
1104         case '\'':
1105                 goto_mark();
1106                 buffer_print();
1107                 break;
1108 #endif
1109         case 'r': case 'R':
1110                 buffer_print();
1111                 break;
1112         /*case 'R':
1113                 full_repaint();
1114                 break;*/
1115         case 's':
1116                 save_input_to_file();
1117                 break;
1118         case 'E':
1119                 examine_file();
1120                 break;
1121 #if ENABLE_FEATURE_LESS_FLAGS
1122         case '=':
1123                 m_status_print();
1124                 break;
1125 #endif
1126 #if ENABLE_FEATURE_LESS_REGEXP
1127         case '/':
1128                 option_mask32 &= ~LESS_STATE_MATCH_BACKWARDS;
1129                 regex_process();
1130                 break;
1131         case 'n':
1132                 goto_match(match_pos + 1);
1133                 break;
1134         case 'N':
1135                 goto_match(match_pos - 1);
1136                 break;
1137         case '?':
1138                 option_mask32 |= LESS_STATE_MATCH_BACKWARDS;
1139                 regex_process();
1140                 break;
1141 #endif
1142 #if ENABLE_FEATURE_LESS_FLAGCS
1143         case '-':
1144                 flag_change();
1145                 buffer_print();
1146                 break;
1147         case '_':
1148                 show_flag_status();
1149                 break;
1150 #endif
1151 #if ENABLE_FEATURE_LESS_BRACKETS
1152         case '{': case '(': case '[':
1153                 match_right_bracket(keypress);
1154                 break;
1155         case '}': case ')': case ']':
1156                 match_left_bracket(keypress);
1157                 break;
1158 #endif
1159         case ':':
1160                 colon_process();
1161                 break;
1162         }
1163
1164         if (isdigit(keypress))
1165                 number_process(keypress);
1166 }
1167
1168 static void sig_catcher(int sig ATTRIBUTE_UNUSED)
1169 {
1170         set_tty_cooked();
1171         exit(1);
1172 }
1173
1174 int less_main(int argc, char **argv)
1175 {
1176         int keypress;
1177
1178         getopt32(argc, argv, "EMmN~");
1179         argc -= optind;
1180         argv += optind;
1181         num_files = argc;
1182         files = argv;
1183
1184         /* Another popular pager, most, detects when stdout
1185          * is not a tty and turns into cat. This makes sense. */
1186         if (!isatty(STDOUT_FILENO))
1187                 return bb_cat(argv);
1188
1189         if (!num_files) {
1190                 if (isatty(STDIN_FILENO)) {
1191                         /* Just "less"? No args and no redirection? */
1192                         bb_error_msg("missing filename");
1193                         bb_show_usage();
1194                 }
1195         } else
1196                 filename = xstrdup(files[0]);
1197
1198         kbd_fd = xopen(CURRENT_TTY, O_RDONLY);
1199
1200         get_terminal_width_height(kbd_fd, &width, &max_displayed_line);
1201         /* 20: two tabstops + 4 */
1202         if (width < 20 || max_displayed_line < 3)
1203                 bb_error_msg_and_die("too narrow here");
1204         max_displayed_line -= 2;
1205
1206         buffer = xmalloc((max_displayed_line+1) * sizeof(char *));
1207         if (option_mask32 & FLAG_TILDE)
1208                 empty_line_marker = "";
1209
1210         tcgetattr(kbd_fd, &term_orig);
1211         signal(SIGTERM, sig_catcher);
1212         signal(SIGINT, sig_catcher);
1213         term_vi = term_orig;
1214         term_vi.c_lflag &= ~(ICANON | ECHO);
1215         term_vi.c_iflag &= ~(IXON | ICRNL);
1216         /*term_vi.c_oflag &= ~ONLCR;*/
1217         term_vi.c_cc[VMIN] = 1;
1218         term_vi.c_cc[VTIME] = 0;
1219
1220         /* Want to do it just once, but it doesn't work, */
1221         /* so we are redoing it (see code above). Mystery... */
1222         /*tcsetattr(kbd_fd, TCSANOW, &term_vi);*/
1223
1224         reinitialize();
1225         while (1) {
1226                 keypress = less_getch();
1227                 keypress_process(keypress);
1228         }
1229 }