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