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