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