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