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