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