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