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