pointless whitespace/comment fixes, no code changes
[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 /* The escape codes for highlighted and normal text */
32 #define HIGHLIGHT "\033[7m"
33 #define NORMAL "\033[0m"
34 /* The escape code to clear the screen */
35 #define CLEAR "\033[H\033[J"
36 /* The escape code to clear to end of line */
37 #define CLEAR_2_EOL "\033[K"
38
39 enum {
40 /* Absolute max of lines eaten */
41         MAXLINES = CONFIG_FEATURE_LESS_MAXLINES,
42 /* This many "after the end" lines we will show (at max) */
43         TILDES = 1,
44 };
45
46 /* Command line options */
47 enum {
48         FLAG_E = 1 << 0,
49         FLAG_M = 1 << 1,
50         FLAG_m = 1 << 2,
51         FLAG_N = 1 << 3,
52         FLAG_TILDE = 1 << 4,
53         FLAG_I = 1 << 5,
54         FLAG_S = (1 << 6) * ENABLE_FEATURE_LESS_DASHCMD,
55 /* hijack command line options variable for internal state vars */
56         LESS_STATE_MATCH_BACKWARDS = 1 << 15,
57 };
58
59 #if !ENABLE_FEATURE_LESS_REGEXP
60 enum { pattern_valid = 0 };
61 #endif
62
63 struct globals {
64         int cur_fline; /* signed */
65         int kbd_fd;  /* fd to get input from */
66         int less_gets_pos;
67 /* last position in last line, taking into account tabs */
68         size_t last_line_pos;
69         unsigned max_fline;
70         unsigned max_lineno; /* this one tracks linewrap */
71         unsigned max_displayed_line;
72         unsigned width;
73 #if ENABLE_FEATURE_LESS_WINCH
74         unsigned winch_counter;
75 #endif
76         ssize_t eof_error; /* eof if 0, error if < 0 */
77         ssize_t readpos;
78         ssize_t readeof; /* must be signed */
79         const char **buffer;
80         const char **flines;
81         const char *empty_line_marker;
82         unsigned num_files;
83         unsigned current_file;
84         char *filename;
85         char **files;
86 #if ENABLE_FEATURE_LESS_MARKS
87         unsigned num_marks;
88         unsigned mark_lines[15][2];
89 #endif
90 #if ENABLE_FEATURE_LESS_REGEXP
91         unsigned *match_lines;
92         int match_pos; /* signed! */
93         int wanted_match; /* signed! */
94         int num_matches;
95         regex_t pattern;
96         smallint pattern_valid;
97 #endif
98         smallint terminated;
99         smalluint kbd_input_size;
100         struct termios term_orig, term_less;
101         char kbd_input[KEYCODE_BUFFER_SIZE];
102 };
103 #define G (*ptr_to_globals)
104 #define cur_fline           (G.cur_fline         )
105 #define kbd_fd              (G.kbd_fd            )
106 #define less_gets_pos       (G.less_gets_pos     )
107 #define last_line_pos       (G.last_line_pos     )
108 #define max_fline           (G.max_fline         )
109 #define max_lineno          (G.max_lineno        )
110 #define max_displayed_line  (G.max_displayed_line)
111 #define width               (G.width             )
112 #define winch_counter       (G.winch_counter     )
113 /* This one is 100% not cached by compiler on read access */
114 #define WINCH_COUNTER (*(volatile unsigned *)&winch_counter)
115 #define eof_error           (G.eof_error         )
116 #define readpos             (G.readpos           )
117 #define readeof             (G.readeof           )
118 #define buffer              (G.buffer            )
119 #define flines              (G.flines            )
120 #define empty_line_marker   (G.empty_line_marker )
121 #define num_files           (G.num_files         )
122 #define current_file        (G.current_file      )
123 #define filename            (G.filename          )
124 #define files               (G.files             )
125 #define num_marks           (G.num_marks         )
126 #define mark_lines          (G.mark_lines        )
127 #if ENABLE_FEATURE_LESS_REGEXP
128 #define match_lines         (G.match_lines       )
129 #define match_pos           (G.match_pos         )
130 #define num_matches         (G.num_matches       )
131 #define wanted_match        (G.wanted_match      )
132 #define pattern             (G.pattern           )
133 #define pattern_valid       (G.pattern_valid     )
134 #endif
135 #define terminated          (G.terminated        )
136 #define term_orig           (G.term_orig         )
137 #define term_less           (G.term_less         )
138 #define kbd_input_size      (G.kbd_input_size    )
139 #define kbd_input           (G.kbd_input         )
140 #define INIT_G() do { \
141         SET_PTR_TO_GLOBALS(xzalloc(sizeof(G))); \
142         less_gets_pos = -1; \
143         empty_line_marker = "~"; \
144         num_files = 1; \
145         current_file = 1; \
146         eof_error = 1; \
147         terminated = 1; \
148         USE_FEATURE_LESS_REGEXP(wanted_match = -1;) \
149 } while (0)
150
151 /* flines[] are lines read from stdin, each in malloc'ed buffer.
152  * Line numbers are stored as uint32_t prepended to each line.
153  * Pointer is adjusted so that flines[i] points directly past
154  * line number. Accesor: */
155 #define MEMPTR(p) ((char*)(p) - 4)
156 #define LINENO(p) (*(uint32_t*)((p) - 4))
157
158
159 /* Reset terminal input to normal */
160 static void set_tty_cooked(void)
161 {
162         fflush(stdout);
163         tcsetattr(kbd_fd, TCSANOW, &term_orig);
164 }
165
166 /* Move the cursor to a position (x,y), where (0,0) is the
167    top-left corner of the console */
168 static void move_cursor(int line, int row)
169 {
170         printf("\033[%u;%uH", line, row);
171 }
172
173 static void clear_line(void)
174 {
175         printf("\033[%u;0H" CLEAR_2_EOL, max_displayed_line + 2);
176 }
177
178 static void print_hilite(const char *str)
179 {
180         printf(HIGHLIGHT"%s"NORMAL, str);
181 }
182
183 static void print_statusline(const char *str)
184 {
185         clear_line();
186         printf(HIGHLIGHT"%.*s"NORMAL, width - 1, str);
187 }
188
189 /* Exit the program gracefully */
190 static void less_exit(int code)
191 {
192         set_tty_cooked();
193         clear_line();
194         if (code < 0)
195                 kill_myself_with_sig(- code); /* does not return */
196         exit(code);
197 }
198
199 #if (ENABLE_FEATURE_LESS_DASHCMD && ENABLE_FEATURE_LESS_LINENUMS) \
200  || ENABLE_FEATURE_LESS_WINCH
201 static void re_wrap(void)
202 {
203         int w = width;
204         int new_line_pos;
205         int src_idx;
206         int dst_idx;
207         int new_cur_fline = 0;
208         uint32_t lineno;
209         char linebuf[w + 1];
210         const char **old_flines = flines;
211         const char *s;
212         char **new_flines = NULL;
213         char *d;
214
215         if (option_mask32 & FLAG_N)
216                 w -= 8;
217
218         src_idx = 0;
219         dst_idx = 0;
220         s = old_flines[0];
221         lineno = LINENO(s);
222         d = linebuf;
223         new_line_pos = 0;
224         while (1) {
225                 *d = *s;
226                 if (*d != '\0') {
227                         new_line_pos++;
228                         if (*d == '\t') /* tab */
229                                 new_line_pos += 7;
230                         s++;
231                         d++;
232                         if (new_line_pos >= w) {
233                                 int sz;
234                                 /* new line is full, create next one */
235                                 *d = '\0';
236  next_new:
237                                 sz = (d - linebuf) + 1; /* + 1: NUL */
238                                 d = ((char*)xmalloc(sz + 4)) + 4;
239                                 LINENO(d) = lineno;
240                                 memcpy(d, linebuf, sz);
241                                 new_flines = xrealloc_vector(new_flines, 8, dst_idx);
242                                 new_flines[dst_idx] = d;
243                                 dst_idx++;
244                                 if (new_line_pos < w) {
245                                         /* if we came here thru "goto next_new" */
246                                         if (src_idx > max_fline)
247                                                 break;
248                                         lineno = LINENO(s);
249                                 }
250                                 d = linebuf;
251                                 new_line_pos = 0;
252                         }
253                         continue;
254                 }
255                 /* *d == NUL: old line ended, go to next old one */
256                 free(MEMPTR(old_flines[src_idx]));
257                 /* btw, convert cur_fline... */
258                 if (cur_fline == src_idx)
259                         new_cur_fline = dst_idx;
260                 src_idx++;
261                 /* no more lines? finish last new line (and exit the loop) */
262                 if (src_idx > max_fline)
263                         goto next_new;
264                 s = old_flines[src_idx];
265                 if (lineno != LINENO(s)) {
266                         /* this is not a continuation line!
267                          * create next _new_ line too */
268                         goto next_new;
269                 }
270         }
271
272         free(old_flines);
273         flines = (const char **)new_flines;
274
275         max_fline = dst_idx - 1;
276         last_line_pos = new_line_pos;
277         cur_fline = new_cur_fline;
278         /* max_lineno is screen-size independent */
279 #if ENABLE_FEATURE_LESS_REGEXP
280         pattern_valid = 0;
281 #endif
282 }
283 #endif
284
285 #if ENABLE_FEATURE_LESS_REGEXP
286 static void fill_match_lines(unsigned pos);
287 #else
288 #define fill_match_lines(pos) ((void)0)
289 #endif
290
291 /* Devilishly complex routine.
292  *
293  * Has to deal with EOF and EPIPE on input,
294  * with line wrapping, with last line not ending in '\n'
295  * (possibly not ending YET!), with backspace and tabs.
296  * It reads input again if last time we got an EOF (thus supporting
297  * growing files) or EPIPE (watching output of slow process like make).
298  *
299  * Variables used:
300  * flines[] - array of lines already read. Linewrap may cause
301  *      one source file line to occupy several flines[n].
302  * flines[max_fline] - last line, possibly incomplete.
303  * terminated - 1 if flines[max_fline] is 'terminated'
304  *      (if there was '\n' [which isn't stored itself, we just remember
305  *      that it was seen])
306  * max_lineno - last line's number, this one doesn't increment
307  *      on line wrap, only on "real" new lines.
308  * readbuf[0..readeof-1] - small preliminary buffer.
309  * readbuf[readpos] - next character to add to current line.
310  * last_line_pos - screen line position of next char to be read
311  *      (takes into account tabs and backspaces)
312  * eof_error - < 0 error, == 0 EOF, > 0 not EOF/error
313  */
314 static void read_lines(void)
315 {
316 #define readbuf bb_common_bufsiz1
317         char *current_line, *p;
318         int w = width;
319         char last_terminated = terminated;
320 #if ENABLE_FEATURE_LESS_REGEXP
321         unsigned old_max_fline = max_fline;
322         time_t last_time = 0;
323         unsigned seconds_p1 = 3; /* seconds_to_loop + 1 */
324 #endif
325
326         if (option_mask32 & FLAG_N)
327                 w -= 8;
328
329  USE_FEATURE_LESS_REGEXP(again0:)
330
331         p = current_line = ((char*)xmalloc(w + 4)) + 4;
332         max_fline += last_terminated;
333         if (!last_terminated) {
334                 const char *cp = flines[max_fline];
335                 strcpy(p, cp);
336                 p += strlen(current_line);
337                 free(MEMPTR(flines[max_fline]));
338                 /* last_line_pos is still valid from previous read_lines() */
339         } else {
340                 last_line_pos = 0;
341         }
342
343         while (1) { /* read lines until we reach cur_fline or wanted_match */
344                 *p = '\0';
345                 terminated = 0;
346                 while (1) { /* read chars until we have a line */
347                         char c;
348                         /* if no unprocessed chars left, eat more */
349                         if (readpos >= readeof) {
350                                 ndelay_on(0);
351                                 eof_error = safe_read(STDIN_FILENO, readbuf, sizeof(readbuf));
352                                 ndelay_off(0);
353                                 readpos = 0;
354                                 readeof = eof_error;
355                                 if (eof_error <= 0)
356                                         goto reached_eof;
357                         }
358                         c = readbuf[readpos];
359                         /* backspace? [needed for manpages] */
360                         /* <tab><bs> is (a) insane and */
361                         /* (b) harder to do correctly, so we refuse to do it */
362                         if (c == '\x8' && last_line_pos && p[-1] != '\t') {
363                                 readpos++; /* eat it */
364                                 last_line_pos--;
365                         /* was buggy (p could end up <= current_line)... */
366                                 *--p = '\0';
367                                 continue;
368                         }
369                         {
370                                 size_t new_last_line_pos = last_line_pos + 1;
371                                 if (c == '\t') {
372                                         new_last_line_pos += 7;
373                                         new_last_line_pos &= (~7);
374                                 }
375                                 if ((int)new_last_line_pos >= w)
376                                         break;
377                                 last_line_pos = new_last_line_pos;
378                         }
379                         /* ok, we will eat this char */
380                         readpos++;
381                         if (c == '\n') {
382                                 terminated = 1;
383                                 last_line_pos = 0;
384                                 break;
385                         }
386                         /* NUL is substituted by '\n'! */
387                         if (c == '\0') c = '\n';
388                         *p++ = c;
389                         *p = '\0';
390                 } /* end of "read chars until we have a line" loop */
391                 /* Corner case: linewrap with only "" wrapping to next line */
392                 /* Looks ugly on screen, so we do not store this empty line */
393                 if (!last_terminated && !current_line[0]) {
394                         last_terminated = 1;
395                         max_lineno++;
396                         continue;
397                 }
398  reached_eof:
399                 last_terminated = terminated;
400                 flines = xrealloc_vector(flines, 8, max_fline);
401
402                 flines[max_fline] = (char*)xrealloc(MEMPTR(current_line), strlen(current_line) + 1 + 4) + 4;
403                 LINENO(flines[max_fline]) = max_lineno;
404                 if (terminated)
405                         max_lineno++;
406
407                 if (max_fline >= MAXLINES) {
408                         eof_error = 0; /* Pretend we saw EOF */
409                         break;
410                 }
411                 if (!(option_mask32 & FLAG_S)
412                   ? (max_fline > cur_fline + max_displayed_line)
413                   : (max_fline >= cur_fline
414                      && max_lineno > LINENO(flines[cur_fline]) + max_displayed_line)
415                 ) {
416 #if !ENABLE_FEATURE_LESS_REGEXP
417                         break;
418 #else
419                         if (wanted_match >= num_matches) { /* goto_match called us */
420                                 fill_match_lines(old_max_fline);
421                                 old_max_fline = max_fline;
422                         }
423                         if (wanted_match < num_matches)
424                                 break;
425 #endif
426                 }
427                 if (eof_error <= 0) {
428                         if (eof_error < 0) {
429                                 if (errno == EAGAIN) {
430                                         /* not yet eof or error, reset flag (or else
431                                          * we will hog CPU - select() will return
432                                          * immediately */
433                                         eof_error = 1;
434                                 } else {
435                                         print_statusline("read error");
436                                 }
437                         }
438 #if !ENABLE_FEATURE_LESS_REGEXP
439                         break;
440 #else
441                         if (wanted_match < num_matches) {
442                                 break;
443                         } else { /* goto_match called us */
444                                 time_t t = time(NULL);
445                                 if (t != last_time) {
446                                         last_time = t;
447                                         if (--seconds_p1 == 0)
448                                                 break;
449                                 }
450                                 sched_yield();
451                                 goto again0; /* go loop again (max 2 seconds) */
452                         }
453 #endif
454                 }
455                 max_fline++;
456                 current_line = ((char*)xmalloc(w + 4)) + 4;
457                 p = current_line;
458                 last_line_pos = 0;
459         } /* end of "read lines until we reach cur_fline" loop */
460         fill_match_lines(old_max_fline);
461 #if ENABLE_FEATURE_LESS_REGEXP
462         /* prevent us from being stuck in search for a match */
463         wanted_match = -1;
464 #endif
465 #undef readbuf
466 }
467
468 #if ENABLE_FEATURE_LESS_FLAGS
469 /* Interestingly, writing calc_percent as a function saves around 32 bytes
470  * on my build. */
471 static int calc_percent(void)
472 {
473         unsigned p = (100 * (cur_fline+max_displayed_line+1) + max_fline/2) / (max_fline+1);
474         return p <= 100 ? p : 100;
475 }
476
477 /* Print a status line if -M was specified */
478 static void m_status_print(void)
479 {
480         int percentage;
481
482         if (less_gets_pos >= 0) /* don't touch statusline while input is done! */
483                 return;
484
485         clear_line();
486         printf(HIGHLIGHT"%s", filename);
487         if (num_files > 1)
488                 printf(" (file %i of %i)", current_file, num_files);
489         printf(" lines %i-%i/%i ",
490                         cur_fline + 1, cur_fline + max_displayed_line + 1,
491                         max_fline + 1);
492         if (cur_fline >= (int)(max_fline - max_displayed_line)) {
493                 printf("(END)"NORMAL);
494                 if (num_files > 1 && current_file != num_files)
495                         printf(HIGHLIGHT" - next: %s"NORMAL, files[current_file]);
496                 return;
497         }
498         percentage = calc_percent();
499         printf("%i%%"NORMAL, percentage);
500 }
501 #endif
502
503 /* Print the status line */
504 static void status_print(void)
505 {
506         const char *p;
507
508         if (less_gets_pos >= 0) /* don't touch statusline while input is done! */
509                 return;
510
511         /* Change the status if flags have been set */
512 #if ENABLE_FEATURE_LESS_FLAGS
513         if (option_mask32 & (FLAG_M|FLAG_m)) {
514                 m_status_print();
515                 return;
516         }
517         /* No flags set */
518 #endif
519
520         clear_line();
521         if (cur_fline && cur_fline < (int)(max_fline - max_displayed_line)) {
522                 bb_putchar(':');
523                 return;
524         }
525         p = "(END)";
526         if (!cur_fline)
527                 p = filename;
528         if (num_files > 1) {
529                 printf(HIGHLIGHT"%s (file %i of %i)"NORMAL,
530                                 p, current_file, num_files);
531                 return;
532         }
533         print_hilite(p);
534 }
535
536 static void cap_cur_fline(int nlines)
537 {
538         int diff;
539         if (cur_fline < 0)
540                 cur_fline = 0;
541         if (cur_fline + max_displayed_line > max_fline + TILDES) {
542                 cur_fline -= nlines;
543                 if (cur_fline < 0)
544                         cur_fline = 0;
545                 diff = max_fline - (cur_fline + max_displayed_line) + TILDES;
546                 /* As the number of lines requested was too large, we just move
547                 to the end of the file */
548                 if (diff > 0)
549                         cur_fline += diff;
550         }
551 }
552
553 static const char controls[] ALIGN1 =
554         /* NUL: never encountered; TAB: not converted */
555         /**/"\x01\x02\x03\x04\x05\x06\x07\x08"  "\x0a\x0b\x0c\x0d\x0e\x0f"
556         "\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1a\x1b\x1c\x1d\x1e\x1f"
557         "\x7f\x9b"; /* DEL and infamous Meta-ESC :( */
558 static const char ctrlconv[] ALIGN1 =
559         /* '\n': it's a former NUL - subst with '@', not 'J' */
560         "\x40\x41\x42\x43\x44\x45\x46\x47\x48\x49\x40\x4b\x4c\x4d\x4e\x4f"
561         "\x50\x51\x52\x53\x54\x55\x56\x57\x58\x59\x5a\x5b\x5c\x5d\x5e\x5f";
562
563 static void lineno_str(char *nbuf9, const char *line)
564 {
565         nbuf9[0] = '\0';
566         if (option_mask32 & FLAG_N) {
567                 const char *fmt;
568                 unsigned n;
569
570                 if (line == empty_line_marker) {
571                         memset(nbuf9, ' ', 8);
572                         nbuf9[8] = '\0';
573                         return;
574                 }
575                 /* Width of 7 preserves tab spacing in the text */
576                 fmt = "%7u ";
577                 n = LINENO(line) + 1;
578                 if (n > 9999999) {
579                         n %= 10000000;
580                         fmt = "%07u ";
581                 }
582                 sprintf(nbuf9, fmt, n);
583         }
584 }
585
586
587 #if ENABLE_FEATURE_LESS_REGEXP
588 static void print_found(const char *line)
589 {
590         int match_status;
591         int eflags;
592         char *growline;
593         regmatch_t match_structs;
594
595         char buf[width];
596         char nbuf9[9];
597         const char *str = line;
598         char *p = buf;
599         size_t n;
600
601         while (*str) {
602                 n = strcspn(str, controls);
603                 if (n) {
604                         if (!str[n]) break;
605                         memcpy(p, str, n);
606                         p += n;
607                         str += n;
608                 }
609                 n = strspn(str, controls);
610                 memset(p, '.', n);
611                 p += n;
612                 str += n;
613         }
614         strcpy(p, str);
615
616         /* buf[] holds quarantined version of str */
617
618         /* Each part of the line that matches has the HIGHLIGHT
619            and NORMAL escape sequences placed around it.
620            NB: we regex against line, but insert text
621            from quarantined copy (buf[]) */
622         str = buf;
623         growline = NULL;
624         eflags = 0;
625         goto start;
626
627         while (match_status == 0) {
628                 char *new = xasprintf("%s%.*s"HIGHLIGHT"%.*s"NORMAL,
629                                 growline ? : "",
630                                 match_structs.rm_so, str,
631                                 match_structs.rm_eo - match_structs.rm_so,
632                                                 str + match_structs.rm_so);
633                 free(growline);
634                 growline = new;
635                 str += match_structs.rm_eo;
636                 line += match_structs.rm_eo;
637                 eflags = REG_NOTBOL;
638  start:
639                 /* Most of the time doesn't find the regex, optimize for that */
640                 match_status = regexec(&pattern, line, 1, &match_structs, eflags);
641                 /* if even "" matches, treat it as "not a match" */
642                 if (match_structs.rm_so >= match_structs.rm_eo)
643                         match_status = 1;
644         }
645
646         lineno_str(nbuf9, line);
647         if (!growline) {
648                 printf(CLEAR_2_EOL"%s%s\n", nbuf9, str);
649                 return;
650         }
651         printf(CLEAR_2_EOL"%s%s%s\n", nbuf9, growline, str);
652         free(growline);
653 }
654 #else
655 void print_found(const char *line);
656 #endif
657
658 static void print_ascii(const char *str)
659 {
660         char buf[width];
661         char nbuf9[9];
662         char *p;
663         size_t n;
664
665         lineno_str(nbuf9, str);
666         printf(CLEAR_2_EOL"%s", nbuf9);
667
668         while (*str) {
669                 n = strcspn(str, controls);
670                 if (n) {
671                         if (!str[n]) break;
672                         printf("%.*s", (int) n, str);
673                         str += n;
674                 }
675                 n = strspn(str, controls);
676                 p = buf;
677                 do {
678                         if (*str == 0x7f)
679                                 *p++ = '?';
680                         else if (*str == (char)0x9b)
681                         /* VT100's CSI, aka Meta-ESC. Who's inventor? */
682                         /* I want to know who committed this sin */
683                                 *p++ = '{';
684                         else
685                                 *p++ = ctrlconv[(unsigned char)*str];
686                         str++;
687                 } while (--n);
688                 *p = '\0';
689                 print_hilite(buf);
690         }
691         puts(str);
692 }
693
694 /* Print the buffer */
695 static void buffer_print(void)
696 {
697         unsigned i;
698
699         move_cursor(0, 0);
700         for (i = 0; i <= max_displayed_line; i++)
701                 if (pattern_valid)
702                         print_found(buffer[i]);
703                 else
704                         print_ascii(buffer[i]);
705         status_print();
706 }
707
708 static void buffer_fill_and_print(void)
709 {
710         unsigned i;
711 #if ENABLE_FEATURE_LESS_DASHCMD
712         int fpos = cur_fline;
713
714         if (option_mask32 & FLAG_S) {
715                 /* Go back to the beginning of this line */
716                 while (fpos && LINENO(flines[fpos]) == LINENO(flines[fpos-1]))
717                         fpos--;
718         }
719
720         i = 0;
721         while (i <= max_displayed_line && fpos <= max_fline) {
722                 int lineno = LINENO(flines[fpos]);
723                 buffer[i] = flines[fpos];
724                 i++;
725                 do {
726                         fpos++;
727                 } while ((fpos <= max_fline)
728                       && (option_mask32 & FLAG_S)
729                       && lineno == LINENO(flines[fpos])
730                 );
731         }
732 #else
733         for (i = 0; i <= max_displayed_line && cur_fline + i <= max_fline; i++) {
734                 buffer[i] = flines[cur_fline + i];
735         }
736 #endif
737         for (; i <= max_displayed_line; i++) {
738                 buffer[i] = empty_line_marker;
739         }
740         buffer_print();
741 }
742
743 /* Move the buffer up and down in the file in order to scroll */
744 static void buffer_down(int nlines)
745 {
746         cur_fline += nlines;
747         read_lines();
748         cap_cur_fline(nlines);
749         buffer_fill_and_print();
750 }
751
752 static void buffer_up(int nlines)
753 {
754         cur_fline -= nlines;
755         if (cur_fline < 0) cur_fline = 0;
756         read_lines();
757         buffer_fill_and_print();
758 }
759
760 static void buffer_line(int linenum)
761 {
762         if (linenum < 0)
763                 linenum = 0;
764         cur_fline = linenum;
765         read_lines();
766         if (linenum + max_displayed_line > max_fline)
767                 linenum = max_fline - max_displayed_line + TILDES;
768         if (linenum < 0)
769                 linenum = 0;
770         cur_fline = linenum;
771         buffer_fill_and_print();
772 }
773
774 static void open_file_and_read_lines(void)
775 {
776         if (filename) {
777                 xmove_fd(xopen(filename, O_RDONLY), STDIN_FILENO);
778         } else {
779                 /* "less" with no arguments in argv[] */
780                 /* For status line only */
781                 filename = xstrdup(bb_msg_standard_input);
782         }
783         readpos = 0;
784         readeof = 0;
785         last_line_pos = 0;
786         terminated = 1;
787         read_lines();
788 }
789
790 /* Reinitialize everything for a new file - free the memory and start over */
791 static void reinitialize(void)
792 {
793         unsigned i;
794
795         if (flines) {
796                 for (i = 0; i <= max_fline; i++)
797                         free(MEMPTR(flines[i]));
798                 free(flines);
799                 flines = NULL;
800         }
801
802         max_fline = -1;
803         cur_fline = 0;
804         max_lineno = 0;
805         open_file_and_read_lines();
806         buffer_fill_and_print();
807 }
808
809 static ssize_t getch_nowait(void)
810 {
811         int rd;
812         struct pollfd pfd[2];
813
814         pfd[0].fd = STDIN_FILENO;
815         pfd[0].events = POLLIN;
816         pfd[1].fd = kbd_fd;
817         pfd[1].events = POLLIN;
818  again:
819         tcsetattr(kbd_fd, TCSANOW, &term_less);
820         /* NB: select/poll returns whenever read will not block. Therefore:
821          * if eof is reached, select/poll will return immediately
822          * because read will immediately return 0 bytes.
823          * Even if select/poll says that input is available, read CAN block
824          * (switch fd into O_NONBLOCK'ed mode to avoid it)
825          */
826         rd = 1;
827         /* Are we interested in stdin? */
828 //TODO: reuse code for determining this
829         if (!(option_mask32 & FLAG_S)
830            ? !(max_fline > cur_fline + max_displayed_line)
831            : !(max_fline >= cur_fline
832                && max_lineno > LINENO(flines[cur_fline]) + max_displayed_line)
833         ) {
834                 if (eof_error > 0) /* did NOT reach eof yet */
835                         rd = 0; /* yes, we are interested in stdin */
836         }
837         /* Position cursor if line input is done */
838         if (less_gets_pos >= 0)
839                 move_cursor(max_displayed_line + 2, less_gets_pos + 1);
840         fflush(stdout);
841
842         if (kbd_input_size == 0) {
843 #if ENABLE_FEATURE_LESS_WINCH
844                 while (1) {
845                         int r;
846                         /* NB: SIGWINCH interrupts poll() */
847                         r = poll(pfd + rd, 2 - rd, -1);
848                         if (/*r < 0 && errno == EINTR &&*/ winch_counter)
849                                 return '\\'; /* anything which has no defined function */
850                         if (r) break;
851                 }
852 #else
853                 safe_poll(pfd + rd, 2 - rd, -1);
854 #endif
855         }
856
857         /* We have kbd_fd in O_NONBLOCK mode, read inside read_key()
858          * would not block even if there is no input available */
859         rd = read_key(kbd_fd, &kbd_input_size, kbd_input);
860         if (rd == -1) {
861                 if (errno == EAGAIN) {
862                         /* No keyboard input available. Since poll() did return,
863                          * we should have input on stdin */
864                         read_lines();
865                         buffer_fill_and_print();
866                         goto again;
867                 }
868                 /* EOF/error (ssh session got killed etc) */
869                 less_exit(0);
870         }
871         set_tty_cooked();
872         return rd;
873 }
874
875 /* Grab a character from input without requiring the return key. If the
876  * character is ASCII \033, get more characters and assign certain sequences
877  * special return codes. Note that this function works best with raw input. */
878 static int less_getch(int pos)
879 {
880         int i;
881
882  again:
883         less_gets_pos = pos;
884         i = getch_nowait();
885         less_gets_pos = -1;
886
887         /* Discard Ctrl-something chars */
888         if (i >= 0 && i < ' ' && i != 0x0d && i != 8)
889                 goto again;
890         return i;
891 }
892
893 static char* less_gets(int sz)
894 {
895         int c;
896         unsigned i = 0;
897         char *result = xzalloc(1);
898
899         while (1) {
900                 c = '\0';
901                 less_gets_pos = sz + i;
902                 c = getch_nowait();
903                 if (c == 0x0d) {
904                         result[i] = '\0';
905                         less_gets_pos = -1;
906                         return result;
907                 }
908                 if (c == 0x7f)
909                         c = 8;
910                 if (c == 8 && i) {
911                         printf("\x8 \x8");
912                         i--;
913                 }
914                 if (c < ' ') /* filters out KEYCODE_xxx too (<0) */
915                         continue;
916                 if (i >= width - sz - 1)
917                         continue; /* len limit */
918                 bb_putchar(c);
919                 result[i++] = c;
920                 result = xrealloc(result, i+1);
921         }
922 }
923
924 static void examine_file(void)
925 {
926         char *new_fname;
927
928         print_statusline("Examine: ");
929         new_fname = less_gets(sizeof("Examine: ") - 1);
930         if (!new_fname[0]) {
931                 status_print();
932  err:
933                 free(new_fname);
934                 return;
935         }
936         if (access(new_fname, R_OK) != 0) {
937                 print_statusline("Cannot read this file");
938                 goto err;
939         }
940         free(filename);
941         filename = new_fname;
942         /* files start by = argv. why we assume that argv is infinitely long??
943         files[num_files] = filename;
944         current_file = num_files + 1;
945         num_files++; */
946         files[0] = filename;
947         num_files = current_file = 1;
948         reinitialize();
949 }
950
951 /* This function changes the file currently being paged. direction can be one of the following:
952  * -1: go back one file
953  *  0: go to the first file
954  *  1: go forward one file */
955 static void change_file(int direction)
956 {
957         if (current_file != ((direction > 0) ? num_files : 1)) {
958                 current_file = direction ? current_file + direction : 1;
959                 free(filename);
960                 filename = xstrdup(files[current_file - 1]);
961                 reinitialize();
962         } else {
963                 print_statusline(direction > 0 ? "No next file" : "No previous file");
964         }
965 }
966
967 static void remove_current_file(void)
968 {
969         unsigned i;
970
971         if (num_files < 2)
972                 return;
973
974         if (current_file != 1) {
975                 change_file(-1);
976                 for (i = 3; i <= num_files; i++)
977                         files[i - 2] = files[i - 1];
978                 num_files--;
979         } else {
980                 change_file(1);
981                 for (i = 2; i <= num_files; i++)
982                         files[i - 2] = files[i - 1];
983                 num_files--;
984                 current_file--;
985         }
986 }
987
988 static void colon_process(void)
989 {
990         int keypress;
991
992         /* Clear the current line and print a prompt */
993         print_statusline(" :");
994
995         keypress = less_getch(2);
996         switch (keypress) {
997         case 'd':
998                 remove_current_file();
999                 break;
1000         case 'e':
1001                 examine_file();
1002                 break;
1003 #if ENABLE_FEATURE_LESS_FLAGS
1004         case 'f':
1005                 m_status_print();
1006                 break;
1007 #endif
1008         case 'n':
1009                 change_file(1);
1010                 break;
1011         case 'p':
1012                 change_file(-1);
1013                 break;
1014         case 'q':
1015                 less_exit(EXIT_SUCCESS);
1016                 break;
1017         case 'x':
1018                 change_file(0);
1019                 break;
1020         }
1021 }
1022
1023 #if ENABLE_FEATURE_LESS_REGEXP
1024 static void normalize_match_pos(int match)
1025 {
1026         if (match >= num_matches)
1027                 match = num_matches - 1;
1028         if (match < 0)
1029                 match = 0;
1030         match_pos = match;
1031 }
1032
1033 static void goto_match(int match)
1034 {
1035         if (!pattern_valid)
1036                 return;
1037         if (match < 0)
1038                 match = 0;
1039         /* Try to find next match if eof isn't reached yet */
1040         if (match >= num_matches && eof_error > 0) {
1041                 wanted_match = match; /* "I want to read until I see N'th match" */
1042                 read_lines();
1043         }
1044         if (num_matches) {
1045                 normalize_match_pos(match);
1046                 buffer_line(match_lines[match_pos]);
1047         } else {
1048                 print_statusline("No matches found");
1049         }
1050 }
1051
1052 static void fill_match_lines(unsigned pos)
1053 {
1054         if (!pattern_valid)
1055                 return;
1056         /* Run the regex on each line of the current file */
1057         while (pos <= max_fline) {
1058                 /* If this line matches */
1059                 if (regexec(&pattern, flines[pos], 0, NULL, 0) == 0
1060                 /* and we didn't match it last time */
1061                  && !(num_matches && match_lines[num_matches-1] == pos)
1062                 ) {
1063                         match_lines = xrealloc_vector(match_lines, 4, num_matches);
1064                         match_lines[num_matches++] = pos;
1065                 }
1066                 pos++;
1067         }
1068 }
1069
1070 static void regex_process(void)
1071 {
1072         char *uncomp_regex, *err;
1073
1074         /* Reset variables */
1075         free(match_lines);
1076         match_lines = NULL;
1077         match_pos = 0;
1078         num_matches = 0;
1079         if (pattern_valid) {
1080                 regfree(&pattern);
1081                 pattern_valid = 0;
1082         }
1083
1084         /* Get the uncompiled regular expression from the user */
1085         clear_line();
1086         bb_putchar((option_mask32 & LESS_STATE_MATCH_BACKWARDS) ? '?' : '/');
1087         uncomp_regex = less_gets(1);
1088         if (!uncomp_regex[0]) {
1089                 free(uncomp_regex);
1090                 buffer_print();
1091                 return;
1092         }
1093
1094         /* Compile the regex and check for errors */
1095         err = regcomp_or_errmsg(&pattern, uncomp_regex,
1096                                 (option_mask32 & FLAG_I) ? REG_ICASE : 0);
1097         free(uncomp_regex);
1098         if (err) {
1099                 print_statusline(err);
1100                 free(err);
1101                 return;
1102         }
1103
1104         pattern_valid = 1;
1105         match_pos = 0;
1106         fill_match_lines(0);
1107         while (match_pos < num_matches) {
1108                 if ((int)match_lines[match_pos] > cur_fline)
1109                         break;
1110                 match_pos++;
1111         }
1112         if (option_mask32 & LESS_STATE_MATCH_BACKWARDS)
1113                 match_pos--;
1114
1115         /* It's possible that no matches are found yet.
1116          * goto_match() will read input looking for match,
1117          * if needed */
1118         goto_match(match_pos);
1119 }
1120 #endif
1121
1122 static void number_process(int first_digit)
1123 {
1124         unsigned i;
1125         int num;
1126         int keypress;
1127         char num_input[sizeof(int)*4]; /* more than enough */
1128
1129         num_input[0] = first_digit;
1130
1131         /* Clear the current line, print a prompt, and then print the digit */
1132         clear_line();
1133         printf(":%c", first_digit);
1134
1135         /* Receive input until a letter is given */
1136         i = 1;
1137         while (i < sizeof(num_input)-1) {
1138                 keypress = less_getch(i + 1);
1139                 if ((unsigned)keypress > 255 || !isdigit(num_input[i]))
1140                         break;
1141                 num_input[i] = keypress;
1142                 bb_putchar(keypress);
1143                 i++;
1144         }
1145
1146         num_input[i] = '\0';
1147         num = bb_strtou(num_input, NULL, 10);
1148         /* on format error, num == -1 */
1149         if (num < 1 || num > MAXLINES) {
1150                 buffer_print();
1151                 return;
1152         }
1153
1154         /* We now know the number and the letter entered, so we process them */
1155         switch (keypress) {
1156         case KEYCODE_DOWN: case 'z': case 'd': case 'e': case ' ': case '\015':
1157                 buffer_down(num);
1158                 break;
1159         case KEYCODE_UP: case 'b': case 'w': case 'y': case 'u':
1160                 buffer_up(num);
1161                 break;
1162         case 'g': case '<': case 'G': case '>':
1163                 cur_fline = num + max_displayed_line;
1164                 read_lines();
1165                 buffer_line(num - 1);
1166                 break;
1167         case 'p': case '%':
1168                 num = num * (max_fline / 100); /* + max_fline / 2; */
1169                 cur_fline = num + max_displayed_line;
1170                 read_lines();
1171                 buffer_line(num);
1172                 break;
1173 #if ENABLE_FEATURE_LESS_REGEXP
1174         case 'n':
1175                 goto_match(match_pos + num);
1176                 break;
1177         case '/':
1178                 option_mask32 &= ~LESS_STATE_MATCH_BACKWARDS;
1179                 regex_process();
1180                 break;
1181         case '?':
1182                 option_mask32 |= LESS_STATE_MATCH_BACKWARDS;
1183                 regex_process();
1184                 break;
1185 #endif
1186         }
1187 }
1188
1189 #if ENABLE_FEATURE_LESS_DASHCMD
1190 static void flag_change(void)
1191 {
1192         int keypress;
1193
1194         clear_line();
1195         bb_putchar('-');
1196         keypress = less_getch(1);
1197
1198         switch (keypress) {
1199         case 'M':
1200                 option_mask32 ^= FLAG_M;
1201                 break;
1202         case 'm':
1203                 option_mask32 ^= FLAG_m;
1204                 break;
1205         case 'E':
1206                 option_mask32 ^= FLAG_E;
1207                 break;
1208         case '~':
1209                 option_mask32 ^= FLAG_TILDE;
1210                 break;
1211         case 'S':
1212                 option_mask32 ^= FLAG_S;
1213                 buffer_fill_and_print();
1214                 break;
1215 #if ENABLE_FEATURE_LESS_LINENUMS
1216         case 'N':
1217                 option_mask32 ^= FLAG_N;
1218                 re_wrap();
1219                 buffer_fill_and_print();
1220                 break;
1221 #endif
1222         }
1223 }
1224
1225 #ifdef BLOAT
1226 static void show_flag_status(void)
1227 {
1228         int keypress;
1229         int flag_val;
1230
1231         clear_line();
1232         bb_putchar('_');
1233         keypress = less_getch(1);
1234
1235         switch (keypress) {
1236         case 'M':
1237                 flag_val = option_mask32 & FLAG_M;
1238                 break;
1239         case 'm':
1240                 flag_val = option_mask32 & FLAG_m;
1241                 break;
1242         case '~':
1243                 flag_val = option_mask32 & FLAG_TILDE;
1244                 break;
1245         case 'N':
1246                 flag_val = option_mask32 & FLAG_N;
1247                 break;
1248         case 'E':
1249                 flag_val = option_mask32 & FLAG_E;
1250                 break;
1251         default:
1252                 flag_val = 0;
1253                 break;
1254         }
1255
1256         clear_line();
1257         printf(HIGHLIGHT"The status of the flag is: %u"NORMAL, flag_val != 0);
1258 }
1259 #endif
1260
1261 #endif /* ENABLE_FEATURE_LESS_DASHCMD */
1262
1263 static void save_input_to_file(void)
1264 {
1265         const char *msg = "";
1266         char *current_line;
1267         unsigned i;
1268         FILE *fp;
1269
1270         print_statusline("Log file: ");
1271         current_line = less_gets(sizeof("Log file: ")-1);
1272         if (current_line[0]) {
1273                 fp = fopen_for_write(current_line);
1274                 if (!fp) {
1275                         msg = "Error opening log file";
1276                         goto ret;
1277                 }
1278                 for (i = 0; i <= max_fline; i++)
1279                         fprintf(fp, "%s\n", flines[i]);
1280                 fclose(fp);
1281                 msg = "Done";
1282         }
1283  ret:
1284         print_statusline(msg);
1285         free(current_line);
1286 }
1287
1288 #if ENABLE_FEATURE_LESS_MARKS
1289 static void add_mark(void)
1290 {
1291         int letter;
1292
1293         print_statusline("Mark: ");
1294         letter = less_getch(sizeof("Mark: ") - 1);
1295
1296         if (isalpha(letter)) {
1297                 /* If we exceed 15 marks, start overwriting previous ones */
1298                 if (num_marks == 14)
1299                         num_marks = 0;
1300
1301                 mark_lines[num_marks][0] = letter;
1302                 mark_lines[num_marks][1] = cur_fline;
1303                 num_marks++;
1304         } else {
1305                 print_statusline("Invalid mark letter");
1306         }
1307 }
1308
1309 static void goto_mark(void)
1310 {
1311         int letter;
1312         int i;
1313
1314         print_statusline("Go to mark: ");
1315         letter = less_getch(sizeof("Go to mark: ") - 1);
1316         clear_line();
1317
1318         if (isalpha(letter)) {
1319                 for (i = 0; i <= num_marks; i++)
1320                         if (letter == mark_lines[i][0]) {
1321                                 buffer_line(mark_lines[i][1]);
1322                                 break;
1323                         }
1324                 if (num_marks == 14 && letter != mark_lines[14][0])
1325                         print_statusline("Mark not set");
1326         } else
1327                 print_statusline("Invalid mark letter");
1328 }
1329 #endif
1330
1331 #if ENABLE_FEATURE_LESS_BRACKETS
1332 static char opp_bracket(char bracket)
1333 {
1334         switch (bracket) {
1335                 case '{': case '[': /* '}' == '{' + 2. Same for '[' */
1336                         bracket++;
1337                 case '(':           /* ')' == '(' + 1 */
1338                         bracket++;
1339                         break;
1340                 case '}': case ']':
1341                         bracket--;
1342                 case ')':
1343                         bracket--;
1344                         break;
1345         };
1346         return bracket;
1347 }
1348
1349 static void match_right_bracket(char bracket)
1350 {
1351         unsigned i;
1352
1353         if (strchr(flines[cur_fline], bracket) == NULL) {
1354                 print_statusline("No bracket in top line");
1355                 return;
1356         }
1357         bracket = opp_bracket(bracket);
1358         for (i = cur_fline + 1; i < max_fline; i++) {
1359                 if (strchr(flines[i], bracket) != NULL) {
1360                         buffer_line(i);
1361                         return;
1362                 }
1363         }
1364         print_statusline("No matching bracket found");
1365 }
1366
1367 static void match_left_bracket(char bracket)
1368 {
1369         int i;
1370
1371         if (strchr(flines[cur_fline + max_displayed_line], bracket) == NULL) {
1372                 print_statusline("No bracket in bottom line");
1373                 return;
1374         }
1375
1376         bracket = opp_bracket(bracket);
1377         for (i = cur_fline + max_displayed_line; i >= 0; i--) {
1378                 if (strchr(flines[i], bracket) != NULL) {
1379                         buffer_line(i);
1380                         return;
1381                 }
1382         }
1383         print_statusline("No matching bracket found");
1384 }
1385 #endif  /* FEATURE_LESS_BRACKETS */
1386
1387 static void keypress_process(int keypress)
1388 {
1389         switch (keypress) {
1390         case KEYCODE_DOWN: case 'e': case 'j': case 0x0d:
1391                 buffer_down(1);
1392                 break;
1393         case KEYCODE_UP: case 'y': case 'k':
1394                 buffer_up(1);
1395                 break;
1396         case KEYCODE_PAGEDOWN: case ' ': case 'z': case 'f':
1397                 buffer_down(max_displayed_line + 1);
1398                 break;
1399         case KEYCODE_PAGEUP: case 'w': case 'b':
1400                 buffer_up(max_displayed_line + 1);
1401                 break;
1402         case 'd':
1403                 buffer_down((max_displayed_line + 1) / 2);
1404                 break;
1405         case 'u':
1406                 buffer_up((max_displayed_line + 1) / 2);
1407                 break;
1408         case KEYCODE_HOME: case 'g': case 'p': case '<': case '%':
1409                 buffer_line(0);
1410                 break;
1411         case KEYCODE_END: case 'G': case '>':
1412                 cur_fline = MAXLINES;
1413                 read_lines();
1414                 buffer_line(cur_fline);
1415                 break;
1416         case 'q': case 'Q':
1417                 less_exit(EXIT_SUCCESS);
1418                 break;
1419 #if ENABLE_FEATURE_LESS_MARKS
1420         case 'm':
1421                 add_mark();
1422                 buffer_print();
1423                 break;
1424         case '\'':
1425                 goto_mark();
1426                 buffer_print();
1427                 break;
1428 #endif
1429         case 'r': case 'R':
1430                 buffer_print();
1431                 break;
1432         /*case 'R':
1433                 full_repaint();
1434                 break;*/
1435         case 's':
1436                 save_input_to_file();
1437                 break;
1438         case 'E':
1439                 examine_file();
1440                 break;
1441 #if ENABLE_FEATURE_LESS_FLAGS
1442         case '=':
1443                 m_status_print();
1444                 break;
1445 #endif
1446 #if ENABLE_FEATURE_LESS_REGEXP
1447         case '/':
1448                 option_mask32 &= ~LESS_STATE_MATCH_BACKWARDS;
1449                 regex_process();
1450                 break;
1451         case 'n':
1452                 goto_match(match_pos + 1);
1453                 break;
1454         case 'N':
1455                 goto_match(match_pos - 1);
1456                 break;
1457         case '?':
1458                 option_mask32 |= LESS_STATE_MATCH_BACKWARDS;
1459                 regex_process();
1460                 break;
1461 #endif
1462 #if ENABLE_FEATURE_LESS_DASHCMD
1463         case '-':
1464                 flag_change();
1465                 buffer_print();
1466                 break;
1467 #ifdef BLOAT
1468         case '_':
1469                 show_flag_status();
1470                 break;
1471 #endif
1472 #endif
1473 #if ENABLE_FEATURE_LESS_BRACKETS
1474         case '{': case '(': case '[':
1475                 match_right_bracket(keypress);
1476                 break;
1477         case '}': case ')': case ']':
1478                 match_left_bracket(keypress);
1479                 break;
1480 #endif
1481         case ':':
1482                 colon_process();
1483                 break;
1484         }
1485
1486         if (isdigit(keypress))
1487                 number_process(keypress);
1488 }
1489
1490 static void sig_catcher(int sig)
1491 {
1492         less_exit(- sig);
1493 }
1494
1495 #if ENABLE_FEATURE_LESS_WINCH
1496 static void sigwinch_handler(int sig UNUSED_PARAM)
1497 {
1498         winch_counter++;
1499 }
1500 #endif
1501
1502 int less_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
1503 int less_main(int argc, char **argv)
1504 {
1505         int keypress;
1506
1507         INIT_G();
1508
1509         /* TODO: -x: do not interpret backspace, -xx: tab also */
1510         /* -xxx: newline also */
1511         /* -w N: assume width N (-xxx -w 32: hex viewer of sorts) */
1512         getopt32(argv, "EMmN~I" USE_FEATURE_LESS_DASHCMD("S"));
1513         argc -= optind;
1514         argv += optind;
1515         num_files = argc;
1516         files = argv;
1517
1518         /* Another popular pager, most, detects when stdout
1519          * is not a tty and turns into cat. This makes sense. */
1520         if (!isatty(STDOUT_FILENO))
1521                 return bb_cat(argv);
1522
1523         if (!num_files) {
1524                 if (isatty(STDIN_FILENO)) {
1525                         /* Just "less"? No args and no redirection? */
1526                         bb_error_msg("missing filename");
1527                         bb_show_usage();
1528                 }
1529         } else {
1530                 filename = xstrdup(files[0]);
1531         }
1532
1533         if (option_mask32 & FLAG_TILDE)
1534                 empty_line_marker = "";
1535
1536         kbd_fd = open(CURRENT_TTY, O_RDONLY);
1537         if (kbd_fd < 0)
1538                 return bb_cat(argv);
1539         ndelay_on(kbd_fd);
1540
1541         tcgetattr(kbd_fd, &term_orig);
1542         term_less = term_orig;
1543         term_less.c_lflag &= ~(ICANON | ECHO);
1544         term_less.c_iflag &= ~(IXON | ICRNL);
1545         /*term_less.c_oflag &= ~ONLCR;*/
1546         term_less.c_cc[VMIN] = 1;
1547         term_less.c_cc[VTIME] = 0;
1548
1549         get_terminal_width_height(kbd_fd, &width, &max_displayed_line);
1550         /* 20: two tabstops + 4 */
1551         if (width < 20 || max_displayed_line < 3)
1552                 return bb_cat(argv);
1553         max_displayed_line -= 2;
1554
1555         /* We want to restore term_orig on exit */
1556         bb_signals(BB_FATAL_SIGS, sig_catcher);
1557 #if ENABLE_FEATURE_LESS_WINCH
1558         signal(SIGWINCH, sigwinch_handler);
1559 #endif
1560
1561         buffer = xmalloc((max_displayed_line+1) * sizeof(char *));
1562         reinitialize();
1563         while (1) {
1564 #if ENABLE_FEATURE_LESS_WINCH
1565                 while (WINCH_COUNTER) {
1566  again:
1567                         winch_counter--;
1568                         get_terminal_width_height(kbd_fd, &width, &max_displayed_line);
1569                         /* 20: two tabstops + 4 */
1570                         if (width < 20)
1571                                 width = 20;
1572                         if (max_displayed_line < 3)
1573                                 max_displayed_line = 3;
1574                         max_displayed_line -= 2;
1575                         free(buffer);
1576                         buffer = xmalloc((max_displayed_line+1) * sizeof(char *));
1577                         /* Avoid re-wrap and/or redraw if we already know
1578                          * we need to do it again. These ops are expensive */
1579                         if (WINCH_COUNTER)
1580                                 goto again;
1581                         re_wrap();
1582                         if (WINCH_COUNTER)
1583                                 goto again;
1584                         buffer_fill_and_print();
1585                         /* This took some time. Loop back and check,
1586                          * were there another SIGWINCH? */
1587                 }
1588 #endif
1589                 keypress = less_getch(-1); /* -1: do not position cursor */
1590                 keypress_process(keypress);
1591         }
1592 }
1593
1594 /*
1595 Help text of less version 418 is below.
1596 If you are implementing something, keeping
1597 key and/or command line switch compatibility is a good idea:
1598
1599
1600                    SUMMARY OF LESS COMMANDS
1601
1602       Commands marked with * may be preceded by a number, N.
1603       Notes in parentheses indicate the behavior if N is given.
1604   h  H                 Display this help.
1605   q  :q  Q  :Q  ZZ     Exit.
1606  ---------------------------------------------------------------------------
1607                            MOVING
1608   e  ^E  j  ^N  CR  *  Forward  one line   (or N lines).
1609   y  ^Y  k  ^K  ^P  *  Backward one line   (or N lines).
1610   f  ^F  ^V  SPACE  *  Forward  one window (or N lines).
1611   b  ^B  ESC-v      *  Backward one window (or N lines).
1612   z                 *  Forward  one window (and set window to N).
1613   w                 *  Backward one window (and set window to N).
1614   ESC-SPACE         *  Forward  one window, but don't stop at end-of-file.
1615   d  ^D             *  Forward  one half-window (and set half-window to N).
1616   u  ^U             *  Backward one half-window (and set half-window to N).
1617   ESC-)  RightArrow *  Left  one half screen width (or N positions).
1618   ESC-(  LeftArrow  *  Right one half screen width (or N positions).
1619   F                    Forward forever; like "tail -f".
1620   r  ^R  ^L            Repaint screen.
1621   R                    Repaint screen, discarding buffered input.
1622         ---------------------------------------------------
1623         Default "window" is the screen height.
1624         Default "half-window" is half of the screen height.
1625  ---------------------------------------------------------------------------
1626                           SEARCHING
1627   /pattern          *  Search forward for (N-th) matching line.
1628   ?pattern          *  Search backward for (N-th) matching line.
1629   n                 *  Repeat previous search (for N-th occurrence).
1630   N                 *  Repeat previous search in reverse direction.
1631   ESC-n             *  Repeat previous search, spanning files.
1632   ESC-N             *  Repeat previous search, reverse dir. & spanning files.
1633   ESC-u                Undo (toggle) search highlighting.
1634         ---------------------------------------------------
1635         Search patterns may be modified by one or more of:
1636         ^N or !  Search for NON-matching lines.
1637         ^E or *  Search multiple files (pass thru END OF FILE).
1638         ^F or @  Start search at FIRST file (for /) or last file (for ?).
1639         ^K       Highlight matches, but don't move (KEEP position).
1640         ^R       Don't use REGULAR EXPRESSIONS.
1641  ---------------------------------------------------------------------------
1642                            JUMPING
1643   g  <  ESC-<       *  Go to first line in file (or line N).
1644   G  >  ESC->       *  Go to last line in file (or line N).
1645   p  %              *  Go to beginning of file (or N percent into file).
1646   t                 *  Go to the (N-th) next tag.
1647   T                 *  Go to the (N-th) previous tag.
1648   {  (  [           *  Find close bracket } ) ].
1649   }  )  ]           *  Find open bracket { ( [.
1650   ESC-^F <c1> <c2>  *  Find close bracket <c2>.
1651   ESC-^B <c1> <c2>  *  Find open bracket <c1>
1652         ---------------------------------------------------
1653         Each "find close bracket" command goes forward to the close bracket
1654           matching the (N-th) open bracket in the top line.
1655         Each "find open bracket" command goes backward to the open bracket
1656           matching the (N-th) close bracket in the bottom line.
1657   m<letter>            Mark the current position with <letter>.
1658   '<letter>            Go to a previously marked position.
1659   ''                   Go to the previous position.
1660   ^X^X                 Same as '.
1661         ---------------------------------------------------
1662         A mark is any upper-case or lower-case letter.
1663         Certain marks are predefined:
1664              ^  means  beginning of the file
1665              $  means  end of the file
1666  ---------------------------------------------------------------------------
1667                         CHANGING FILES
1668   :e [file]            Examine a new file.
1669   ^X^V                 Same as :e.
1670   :n                *  Examine the (N-th) next file from the command line.
1671   :p                *  Examine the (N-th) previous file from the command line.
1672   :x                *  Examine the first (or N-th) file from the command line.
1673   :d                   Delete the current file from the command line list.
1674   =  ^G  :f            Print current file name.
1675  ---------------------------------------------------------------------------
1676                     MISCELLANEOUS COMMANDS
1677   -<flag>              Toggle a command line option [see OPTIONS below].
1678   --<name>             Toggle a command line option, by name.
1679   _<flag>              Display the setting of a command line option.
1680   __<name>             Display the setting of an option, by name.
1681   +cmd                 Execute the less cmd each time a new file is examined.
1682   !command             Execute the shell command with $SHELL.
1683   |Xcommand            Pipe file between current pos & mark X to shell command.
1684   v                    Edit the current file with $VISUAL or $EDITOR.
1685   V                    Print version number of "less".
1686  ---------------------------------------------------------------------------
1687                            OPTIONS
1688         Most options may be changed either on the command line,
1689         or from within less by using the - or -- command.
1690         Options may be given in one of two forms: either a single
1691         character preceded by a -, or a name preceeded by --.
1692   -?  ........  --help
1693                   Display help (from command line).
1694   -a  ........  --search-skip-screen
1695                   Forward search skips current screen.
1696   -b [N]  ....  --buffers=[N]
1697                   Number of buffers.
1698   -B  ........  --auto-buffers
1699                   Don't automatically allocate buffers for pipes.
1700   -c  ........  --clear-screen
1701                   Repaint by clearing rather than scrolling.
1702   -d  ........  --dumb
1703                   Dumb terminal.
1704   -D [xn.n]  .  --color=xn.n
1705                   Set screen colors. (MS-DOS only)
1706   -e  -E  ....  --quit-at-eof  --QUIT-AT-EOF
1707                   Quit at end of file.
1708   -f  ........  --force
1709                   Force open non-regular files.
1710   -F  ........  --quit-if-one-screen
1711                   Quit if entire file fits on first screen.
1712   -g  ........  --hilite-search
1713                   Highlight only last match for searches.
1714   -G  ........  --HILITE-SEARCH
1715                   Don't highlight any matches for searches.
1716   -h [N]  ....  --max-back-scroll=[N]
1717                   Backward scroll limit.
1718   -i  ........  --ignore-case
1719                   Ignore case in searches that do not contain uppercase.
1720   -I  ........  --IGNORE-CASE
1721                   Ignore case in all searches.
1722   -j [N]  ....  --jump-target=[N]
1723                   Screen position of target lines.
1724   -J  ........  --status-column
1725                   Display a status column at left edge of screen.
1726   -k [file]  .  --lesskey-file=[file]
1727                   Use a lesskey file.
1728   -L  ........  --no-lessopen
1729                   Ignore the LESSOPEN environment variable.
1730   -m  -M  ....  --long-prompt  --LONG-PROMPT
1731                   Set prompt style.
1732   -n  -N  ....  --line-numbers  --LINE-NUMBERS
1733                   Don't use line numbers.
1734   -o [file]  .  --log-file=[file]
1735                   Copy to log file (standard input only).
1736   -O [file]  .  --LOG-FILE=[file]
1737                   Copy to log file (unconditionally overwrite).
1738   -p [pattern]  --pattern=[pattern]
1739                   Start at pattern (from command line).
1740   -P [prompt]   --prompt=[prompt]
1741                   Define new prompt.
1742   -q  -Q  ....  --quiet  --QUIET  --silent --SILENT
1743                   Quiet the terminal bell.
1744   -r  -R  ....  --raw-control-chars  --RAW-CONTROL-CHARS
1745                   Output "raw" control characters.
1746   -s  ........  --squeeze-blank-lines
1747                   Squeeze multiple blank lines.
1748   -S  ........  --chop-long-lines
1749                   Chop long lines.
1750   -t [tag]  ..  --tag=[tag]
1751                   Find a tag.
1752   -T [tagsfile] --tag-file=[tagsfile]
1753                   Use an alternate tags file.
1754   -u  -U  ....  --underline-special  --UNDERLINE-SPECIAL
1755                   Change handling of backspaces.
1756   -V  ........  --version
1757                   Display the version number of "less".
1758   -w  ........  --hilite-unread
1759                   Highlight first new line after forward-screen.
1760   -W  ........  --HILITE-UNREAD
1761                   Highlight first new line after any forward movement.
1762   -x [N[,...]]  --tabs=[N[,...]]
1763                   Set tab stops.
1764   -X  ........  --no-init
1765                   Don't use termcap init/deinit strings.
1766                 --no-keypad
1767                   Don't use termcap keypad init/deinit strings.
1768   -y [N]  ....  --max-forw-scroll=[N]
1769                   Forward scroll limit.
1770   -z [N]  ....  --window=[N]
1771                   Set size of window.
1772   -" [c[c]]  .  --quotes=[c[c]]
1773                   Set shell quote characters.
1774   -~  ........  --tilde
1775                   Don't display tildes after end of file.
1776   -# [N]  ....  --shift=[N]
1777                   Horizontal scroll amount (0 = one half screen width)
1778
1779  ---------------------------------------------------------------------------
1780                           LINE EDITING
1781         These keys can be used to edit text being entered
1782         on the "command line" at the bottom of the screen.
1783  RightArrow                       ESC-l     Move cursor right one character.
1784  LeftArrow                        ESC-h     Move cursor left one character.
1785  CNTL-RightArrow  ESC-RightArrow  ESC-w     Move cursor right one word.
1786  CNTL-LeftArrow   ESC-LeftArrow   ESC-b     Move cursor left one word.
1787  HOME                             ESC-0     Move cursor to start of line.
1788  END                              ESC-$     Move cursor to end of line.
1789  BACKSPACE                                  Delete char to left of cursor.
1790  DELETE                           ESC-x     Delete char under cursor.
1791  CNTL-BACKSPACE   ESC-BACKSPACE             Delete word to left of cursor.
1792  CNTL-DELETE      ESC-DELETE      ESC-X     Delete word under cursor.
1793  CNTL-U           ESC (MS-DOS only)         Delete entire line.
1794  UpArrow                          ESC-k     Retrieve previous command line.
1795  DownArrow                        ESC-j     Retrieve next command line.
1796  TAB                                        Complete filename & cycle.
1797  SHIFT-TAB                        ESC-TAB   Complete filename & reverse cycle.
1798  CNTL-L                                     Complete filename, list all.
1799 */