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