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