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