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