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