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