1 /* vi: set sw=4 ts=4: */
3 * Mini less implementation for busybox
5 * Copyright (C) 2005 by Rob Sullivan <cogito.ergo.cogito@gmail.com>
7 * Licensed under GPLv2 or later, see file LICENSE in this source tree.
12 * - Add more regular expression support - search modifiers, certain matches, etc.
13 * - Add more complex bracket searching - currently, nested brackets are
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.
20 * - the inp file pointer is used so that keyboard input works after
21 * redirected input has been read from stdin
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'.
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
36 //config:config FEATURE_LESS_BRACKETS
37 //config: bool "Enable bracket searching"
39 //config: depends on LESS
41 //config: This option adds the capability to search for matching left and right
42 //config: brackets, facilitating programming.
44 //config:config FEATURE_LESS_FLAGS
45 //config: bool "Enable -m/-M"
47 //config: depends on LESS
49 //config: The -M/-m flag enables a more sophisticated status line.
51 //config:config FEATURE_LESS_MARKS
52 //config: bool "Enable marks"
54 //config: depends on LESS
56 //config: Marks enable positions in a file to be stored for easy reference.
58 //config:config FEATURE_LESS_REGEXP
59 //config: bool "Enable regular expressions"
61 //config: depends on LESS
63 //config: Enable regular expressions, allowing complex file searches.
65 //config:config FEATURE_LESS_WINCH
66 //config: bool "Enable automatic resizing on window size changes"
68 //config: depends on LESS
70 //config: Makes less track window size changes.
72 //config:config FEATURE_LESS_ASK_TERMINAL
73 //config: bool "Use 'tell me cursor position' ESC sequence to measure window"
75 //config: depends on FEATURE_LESS_WINCH
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.
83 //config: This is not clean but helps a lot on serial lines and such.
85 //config:config FEATURE_LESS_DASHCMD
86 //config: bool "Enable flag changes ('-' command)"
88 //config: depends on LESS
90 //config: This enables the ability to change command-line flags within
91 //config: less itself ('-' keyboard command).
93 //config:config FEATURE_LESS_LINENUMS
94 //config: bool "Enable dynamic switching of line numbers"
96 //config: depends on FEATURE_LESS_DASHCMD
98 //config: Enables "-N" command.
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"
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"
112 //usage: "\n -N Prefix line number to each line"
113 //usage: "\n -~ Suppress ~s displayed past EOF"
115 #include <sched.h> /* sched_yield() */
118 #if ENABLE_FEATURE_LESS_REGEXP
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"
133 /* Absolute max of lines eaten */
134 MAXLINES = CONFIG_FEATURE_LESS_MAXLINES,
135 /* This many "after the end" lines we will show (at max) */
139 /* Command line options */
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,
152 #if !ENABLE_FEATURE_LESS_REGEXP
153 enum { pattern_valid = 0 };
157 int cur_fline; /* signed */
158 int kbd_fd; /* fd to get input from */
160 /* last position in last line, taking into account tabs */
161 size_t last_line_pos;
163 unsigned max_lineno; /* this one tracks linewrap */
164 unsigned max_displayed_line;
166 #if ENABLE_FEATURE_LESS_WINCH
167 unsigned winch_counter;
169 ssize_t eof_error; /* eof if 0, error if < 0 */
171 ssize_t readeof; /* must be signed */
174 const char *empty_line_marker;
176 unsigned current_file;
179 #if ENABLE_FEATURE_LESS_MARKS
181 unsigned mark_lines[15][2];
183 #if ENABLE_FEATURE_LESS_REGEXP
184 unsigned *match_lines;
185 int match_pos; /* signed! */
186 int wanted_match; /* signed! */
189 smallint pattern_valid;
191 #if ENABLE_FEATURE_LESS_ASK_TERMINAL
192 smallint winsize_err;
195 struct termios term_orig, term_less;
196 char kbd_input[KEYCODE_BUFFER_SIZE];
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 )
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 = "~"; \
242 IF_FEATURE_LESS_REGEXP(wanted_match = -1;) \
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))
253 /* Reset terminal input to normal */
254 static void set_tty_cooked(void)
257 tcsetattr(kbd_fd, TCSANOW, &term_orig);
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)
264 printf(ESC"[%u;%uH", line, row);
267 static void clear_line(void)
269 printf(ESC"[%u;0H" CLEAR_2_EOL, max_displayed_line + 2);
272 static void print_hilite(const char *str)
274 printf(HIGHLIGHT"%s"NORMAL, str);
277 static void print_statusline(const char *str)
280 printf(HIGHLIGHT"%.*s"NORMAL, width - 1, str);
283 /* Exit the program gracefully */
284 static void less_exit(int code)
289 kill_myself_with_sig(- code); /* does not return */
293 #if (ENABLE_FEATURE_LESS_DASHCMD && ENABLE_FEATURE_LESS_LINENUMS) \
294 || ENABLE_FEATURE_LESS_WINCH
295 static void re_wrap(void)
301 int new_cur_fline = 0;
304 const char **old_flines = flines;
306 char **new_flines = NULL;
309 if (option_mask32 & FLAG_N)
322 if (*d == '\t') /* tab */
326 if (new_line_pos >= w) {
328 /* new line is full, create next one */
331 sz = (d - linebuf) + 1; /* + 1: NUL */
332 d = ((char*)xmalloc(sz + 4)) + 4;
334 memcpy(d, linebuf, sz);
335 new_flines = xrealloc_vector(new_flines, 8, dst_idx);
336 new_flines[dst_idx] = d;
338 if (new_line_pos < w) {
339 /* if we came here thru "goto next_new" */
340 if (src_idx > max_fline)
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;
355 /* no more lines? finish last new line (and exit the loop) */
356 if (src_idx > max_fline)
358 s = old_flines[src_idx];
359 if (lineno != LINENO(s)) {
360 /* this is not a continuation line!
361 * create next _new_ line too */
367 flines = (const char **)new_flines;
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
379 #if ENABLE_FEATURE_LESS_REGEXP
380 static void fill_match_lines(unsigned pos);
382 #define fill_match_lines(pos) ((void)0)
385 /* Devilishly complex routine.
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).
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
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
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.
411 static void read_lines(void)
413 #define readbuf bb_common_bufsiz1
414 char *current_line, *p;
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;
423 /* (careful: max_fline can be -1) */
424 if (max_fline + 1 > MAXLINES)
427 if (option_mask32 & FLAG_N)
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];
435 p += strlen(current_line);
436 free(MEMPTR(flines[max_fline]));
437 /* last_line_pos is still valid from previous read_lines() */
442 while (1) { /* read lines until we reach cur_fline or wanted_match */
445 while (1) { /* read chars until we have a line */
447 /* if no unprocessed chars left, eat more */
448 if (readpos >= readeof) {
449 int flags = ndelay_on(0);
455 eof_error = safe_read(STDIN_FILENO, readbuf, sizeof(readbuf));
459 if (t != last_time) {
461 if (--retry_EAGAIN < 0)
466 fcntl(0, F_SETFL, flags); /* ndelay_off(0) */
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 */
480 /* was buggy (p could end up <= current_line)... */
485 size_t new_last_line_pos = last_line_pos + 1;
487 new_last_line_pos += 7;
488 new_last_line_pos &= (~7);
490 if ((int)new_last_line_pos >= w)
492 last_line_pos = new_last_line_pos;
494 /* ok, we will eat this char */
501 /* NUL is substituted by '\n'! */
502 if (c == '\0') c = '\n';
505 } /* end of "read chars until we have a line" loop */
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]) {
520 last_terminated = terminated;
521 flines = xrealloc_vector(flines, 8, max_fline);
523 flines[max_fline] = (char*)xrealloc(MEMPTR(current_line), strlen(current_line) + 1 + 4) + 4;
524 LINENO(flines[max_fline]) = max_lineno;
528 if (max_fline >= MAXLINES) {
529 eof_error = 0; /* Pretend we saw EOF */
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)
537 #if !ENABLE_FEATURE_LESS_REGEXP
540 if (wanted_match >= num_matches) { /* goto_match called us */
541 fill_match_lines(old_max_fline);
542 old_max_fline = max_fline;
544 if (wanted_match < num_matches)
548 if (eof_error <= 0) {
552 current_line = ((char*)xmalloc(w + 4)) + 4;
555 } /* end of "read lines until we reach cur_fline" loop */
558 if (errno == EAGAIN) {
561 print_statusline(bb_msg_read_error);
565 fill_match_lines(old_max_fline);
566 #if ENABLE_FEATURE_LESS_REGEXP
567 /* prevent us from being stuck in search for a match */
573 #if ENABLE_FEATURE_LESS_FLAGS
574 /* Interestingly, writing calc_percent as a function saves around 32 bytes
576 static int calc_percent(void)
578 unsigned p = (100 * (cur_fline+max_displayed_line+1) + max_fline/2) / (max_fline+1);
579 return p <= 100 ? p : 100;
582 /* Print a status line if -M was specified */
583 static void m_status_print(void)
587 if (less_gets_pos >= 0) /* don't touch statusline while input is done! */
591 printf(HIGHLIGHT"%s", filename);
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,
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]);
603 percentage = calc_percent();
604 printf("%i%%"NORMAL, percentage);
608 /* Print the status line */
609 static void status_print(void)
613 if (less_gets_pos >= 0) /* don't touch statusline while input is done! */
616 /* Change the status if flags have been set */
617 #if ENABLE_FEATURE_LESS_FLAGS
618 if (option_mask32 & (FLAG_M|FLAG_m)) {
626 if (cur_fline && cur_fline < (int)(max_fline - max_displayed_line)) {
634 printf(HIGHLIGHT"%s (file %i of %i)"NORMAL,
635 p, current_file, num_files);
641 static void cap_cur_fline(int nlines)
646 if (cur_fline + max_displayed_line > max_fline + TILDES) {
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 */
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";
669 static void lineno_str(char *nbuf9, const char *line)
672 if (option_mask32 & FLAG_N) {
676 if (line == empty_line_marker) {
677 memset(nbuf9, ' ', 8);
681 /* Width of 7 preserves tab spacing in the text */
683 n = LINENO(line) + 1;
688 sprintf(nbuf9, fmt, n);
693 #if ENABLE_FEATURE_LESS_REGEXP
694 static void print_found(const char *line)
699 regmatch_t match_structs;
703 const char *str = line;
708 n = strcspn(str, controls);
715 n = strspn(str, controls);
722 /* buf[] holds quarantined version of str */
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[]) */
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);
741 str += match_structs.rm_eo;
742 line += match_structs.rm_eo;
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)
752 lineno_str(nbuf9, line);
754 printf(CLEAR_2_EOL"%s%s\n", nbuf9, str);
757 printf(CLEAR_2_EOL"%s%s%s\n", nbuf9, growline, str);
761 void print_found(const char *line);
764 static void print_ascii(const char *str)
771 lineno_str(nbuf9, str);
772 printf(CLEAR_2_EOL"%s", nbuf9);
775 n = strcspn(str, controls);
778 printf("%.*s", (int) n, str);
781 n = strspn(str, controls);
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 */
791 *p++ = ctrlconv[(unsigned char)*str];
800 /* Print the buffer */
801 static void buffer_print(void)
806 for (i = 0; i <= max_displayed_line; i++)
808 print_found(buffer[i]);
810 print_ascii(buffer[i]);
814 static void buffer_fill_and_print(void)
817 #if ENABLE_FEATURE_LESS_DASHCMD
818 int fpos = cur_fline;
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]))
827 while (i <= max_displayed_line && fpos <= max_fline) {
828 int lineno = LINENO(flines[fpos]);
829 buffer[i] = flines[fpos];
833 } while ((fpos <= max_fline)
834 && (option_mask32 & FLAG_S)
835 && lineno == LINENO(flines[fpos])
839 for (i = 0; i <= max_displayed_line && cur_fline + i <= max_fline; i++) {
840 buffer[i] = flines[cur_fline + i];
843 for (; i <= max_displayed_line; i++) {
844 buffer[i] = empty_line_marker;
849 /* Move the buffer up and down in the file in order to scroll */
850 static void buffer_down(int nlines)
854 cap_cur_fline(nlines);
855 buffer_fill_and_print();
858 static void buffer_up(int nlines)
861 if (cur_fline < 0) cur_fline = 0;
863 buffer_fill_and_print();
866 static void buffer_line(int linenum)
872 if (linenum + max_displayed_line > max_fline)
873 linenum = max_fline - max_displayed_line + TILDES;
877 buffer_fill_and_print();
880 static void open_file_and_read_lines(void)
883 xmove_fd(xopen(filename, O_RDONLY), STDIN_FILENO);
885 /* "less" with no arguments in argv[] */
886 /* For status line only */
887 filename = xstrdup(bb_msg_standard_input);
896 /* Reinitialize everything for a new file - free the memory and start over */
897 static void reinitialize(void)
902 for (i = 0; i <= max_fline; i++)
903 free(MEMPTR(flines[i]));
911 open_file_and_read_lines();
912 #if ENABLE_FEATURE_LESS_ASK_TERMINAL
914 printf("\033[999;999H" "\033[6n");
916 buffer_fill_and_print();
919 static int64_t getch_nowait(void)
923 struct pollfd pfd[2];
925 pfd[0].fd = STDIN_FILENO;
926 pfd[0].events = POLLIN;
928 pfd[1].events = POLLIN;
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)
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)
945 if (eof_error > 0) /* did NOT reach eof yet */
946 rd = 0; /* yes, we are interested in stdin */
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);
953 if (kbd_input[0] == 0) { /* if nothing is buffered */
954 #if ENABLE_FEATURE_LESS_WINCH
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 */
964 safe_poll(pfd + rd, 2 - rd, -1);
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 */
976 buffer_fill_and_print();
979 /* EOF/error (ssh session got killed etc) */
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)
996 key = key64 = getch_nowait();
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)
1003 if (key >= 0 && key < ' ' && key != 0x0d && key != 8)
1009 static char* less_gets(int sz)
1013 char *result = xzalloc(1);
1017 less_gets_pos = sz + i;
1030 if (c < ' ') /* filters out KEYCODE_xxx too (<0) */
1032 if (i >= width - sz - 1)
1033 continue; /* len limit */
1036 result = xrealloc(result, i+1);
1040 static void examine_file(void)
1044 print_statusline("Examine: ");
1045 new_fname = less_gets(sizeof("Examine: ") - 1);
1046 if (!new_fname[0]) {
1052 if (access(new_fname, R_OK) != 0) {
1053 print_statusline("Cannot read this file");
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;
1062 files[0] = filename;
1063 num_files = current_file = 1;
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)
1073 if (current_file != ((direction > 0) ? num_files : 1)) {
1074 current_file = direction ? current_file + direction : 1;
1076 filename = xstrdup(files[current_file - 1]);
1079 print_statusline(direction > 0 ? "No next file" : "No previous file");
1083 static void remove_current_file(void)
1090 if (current_file != 1) {
1092 for (i = 3; i <= num_files; i++)
1093 files[i - 2] = files[i - 1];
1097 for (i = 2; i <= num_files; i++)
1098 files[i - 2] = files[i - 1];
1104 static void colon_process(void)
1108 /* Clear the current line and print a prompt */
1109 print_statusline(" :");
1111 keypress = less_getch(2);
1114 remove_current_file();
1119 #if ENABLE_FEATURE_LESS_FLAGS
1131 less_exit(EXIT_SUCCESS);
1139 #if ENABLE_FEATURE_LESS_REGEXP
1140 static void normalize_match_pos(int match)
1142 if (match >= num_matches)
1143 match = num_matches - 1;
1149 static void goto_match(int match)
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" */
1161 normalize_match_pos(match);
1162 buffer_line(match_lines[match_pos]);
1164 print_statusline("No matches found");
1168 static void fill_match_lines(unsigned pos)
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)
1179 match_lines = xrealloc_vector(match_lines, 4, num_matches);
1180 match_lines[num_matches++] = pos;
1186 static void regex_process(void)
1188 char *uncomp_regex, *err;
1190 /* Reset variables */
1195 if (pattern_valid) {
1200 /* Get the uncompiled regular expression from the user */
1202 bb_putchar((option_mask32 & LESS_STATE_MATCH_BACKWARDS) ? '?' : '/');
1203 uncomp_regex = less_gets(1);
1204 if (!uncomp_regex[0]) {
1210 /* Compile the regex and check for errors */
1211 err = regcomp_or_errmsg(&pattern, uncomp_regex,
1212 (option_mask32 & FLAG_I) ? REG_ICASE : 0);
1215 print_statusline(err);
1222 fill_match_lines(0);
1223 while (match_pos < num_matches) {
1224 if ((int)match_lines[match_pos] > cur_fline)
1228 if (option_mask32 & LESS_STATE_MATCH_BACKWARDS)
1231 /* It's possible that no matches are found yet.
1232 * goto_match() will read input looking for match,
1234 goto_match(match_pos);
1238 static void number_process(int first_digit)
1243 char num_input[sizeof(int)*4]; /* more than enough */
1245 num_input[0] = first_digit;
1247 /* Clear the current line, print a prompt, and then print the digit */
1249 printf(":%c", first_digit);
1251 /* Receive input until a letter is given */
1253 while (i < sizeof(num_input)-1) {
1254 keypress = less_getch(i + 1);
1255 if ((unsigned)keypress > 255 || !isdigit(num_input[i]))
1257 num_input[i] = keypress;
1258 bb_putchar(keypress);
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) {
1270 /* We now know the number and the letter entered, so we process them */
1272 case KEYCODE_DOWN: case 'z': case 'd': case 'e': case ' ': case '\015':
1275 case KEYCODE_UP: case 'b': case 'w': case 'y': case 'u':
1278 case 'g': case '<': case 'G': case '>':
1279 cur_fline = num + max_displayed_line;
1281 buffer_line(num - 1);
1284 num = num * (max_fline / 100); /* + max_fline / 2; */
1285 cur_fline = num + max_displayed_line;
1289 #if ENABLE_FEATURE_LESS_REGEXP
1291 goto_match(match_pos + num);
1294 option_mask32 &= ~LESS_STATE_MATCH_BACKWARDS;
1298 option_mask32 |= LESS_STATE_MATCH_BACKWARDS;
1305 #if ENABLE_FEATURE_LESS_DASHCMD
1306 static void flag_change(void)
1312 keypress = less_getch(1);
1316 option_mask32 ^= FLAG_M;
1319 option_mask32 ^= FLAG_m;
1322 option_mask32 ^= FLAG_E;
1325 option_mask32 ^= FLAG_TILDE;
1328 option_mask32 ^= FLAG_S;
1329 buffer_fill_and_print();
1331 #if ENABLE_FEATURE_LESS_LINENUMS
1333 option_mask32 ^= FLAG_N;
1335 buffer_fill_and_print();
1342 static void show_flag_status(void)
1349 keypress = less_getch(1);
1353 flag_val = option_mask32 & FLAG_M;
1356 flag_val = option_mask32 & FLAG_m;
1359 flag_val = option_mask32 & FLAG_TILDE;
1362 flag_val = option_mask32 & FLAG_N;
1365 flag_val = option_mask32 & FLAG_E;
1373 printf(HIGHLIGHT"The status of the flag is: %u"NORMAL, flag_val != 0);
1377 #endif /* ENABLE_FEATURE_LESS_DASHCMD */
1379 static void save_input_to_file(void)
1381 const char *msg = "";
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);
1391 msg = "Error opening log file";
1394 for (i = 0; i <= max_fline; i++)
1395 fprintf(fp, "%s\n", flines[i]);
1400 print_statusline(msg);
1404 #if ENABLE_FEATURE_LESS_MARKS
1405 static void add_mark(void)
1409 print_statusline("Mark: ");
1410 letter = less_getch(sizeof("Mark: ") - 1);
1412 if (isalpha(letter)) {
1413 /* If we exceed 15 marks, start overwriting previous ones */
1414 if (num_marks == 14)
1417 mark_lines[num_marks][0] = letter;
1418 mark_lines[num_marks][1] = cur_fline;
1421 print_statusline("Invalid mark letter");
1425 static void goto_mark(void)
1430 print_statusline("Go to mark: ");
1431 letter = less_getch(sizeof("Go to mark: ") - 1);
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]);
1440 if (num_marks == 14 && letter != mark_lines[14][0])
1441 print_statusline("Mark not set");
1443 print_statusline("Invalid mark letter");
1447 #if ENABLE_FEATURE_LESS_BRACKETS
1448 static char opp_bracket(char bracket)
1451 case '{': case '[': /* '}' == '{' + 2. Same for '[' */
1453 case '(': /* ')' == '(' + 1 */
1465 static void match_right_bracket(char bracket)
1469 if (strchr(flines[cur_fline], bracket) == NULL) {
1470 print_statusline("No bracket in top line");
1473 bracket = opp_bracket(bracket);
1474 for (i = cur_fline + 1; i < max_fline; i++) {
1475 if (strchr(flines[i], bracket) != NULL) {
1480 print_statusline("No matching bracket found");
1483 static void match_left_bracket(char bracket)
1487 if (strchr(flines[cur_fline + max_displayed_line], bracket) == NULL) {
1488 print_statusline("No bracket in bottom line");
1492 bracket = opp_bracket(bracket);
1493 for (i = cur_fline + max_displayed_line; i >= 0; i--) {
1494 if (strchr(flines[i], bracket) != NULL) {
1499 print_statusline("No matching bracket found");
1501 #endif /* FEATURE_LESS_BRACKETS */
1503 static void keypress_process(int keypress)
1506 case KEYCODE_DOWN: case 'e': case 'j': case 0x0d:
1509 case KEYCODE_UP: case 'y': case 'k':
1512 case KEYCODE_PAGEDOWN: case ' ': case 'z': case 'f':
1513 buffer_down(max_displayed_line + 1);
1515 case KEYCODE_PAGEUP: case 'w': case 'b':
1516 buffer_up(max_displayed_line + 1);
1519 buffer_down((max_displayed_line + 1) / 2);
1522 buffer_up((max_displayed_line + 1) / 2);
1524 case KEYCODE_HOME: case 'g': case 'p': case '<': case '%':
1527 case KEYCODE_END: case 'G': case '>':
1528 cur_fline = MAXLINES;
1530 buffer_line(cur_fline);
1533 less_exit(EXIT_SUCCESS);
1535 #if ENABLE_FEATURE_LESS_MARKS
1546 /* TODO: (1) also bind ^R, ^L to this?
1547 * (2) re-measure window size?
1555 save_input_to_file();
1560 #if ENABLE_FEATURE_LESS_FLAGS
1565 #if ENABLE_FEATURE_LESS_REGEXP
1567 option_mask32 &= ~LESS_STATE_MATCH_BACKWARDS;
1571 goto_match(match_pos + 1);
1574 goto_match(match_pos - 1);
1577 option_mask32 |= LESS_STATE_MATCH_BACKWARDS;
1581 #if ENABLE_FEATURE_LESS_DASHCMD
1592 #if ENABLE_FEATURE_LESS_BRACKETS
1593 case '{': case '(': case '[':
1594 match_right_bracket(keypress);
1596 case '}': case ')': case ']':
1597 match_left_bracket(keypress);
1605 if (isdigit(keypress))
1606 number_process(keypress);
1609 static void sig_catcher(int sig)
1614 #if ENABLE_FEATURE_LESS_WINCH
1615 static void sigwinch_handler(int sig UNUSED_PARAM)
1621 int less_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
1622 int less_main(int argc, char **argv)
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)
1635 getopt32(argv, "EMmN~I" IF_FEATURE_LESS_DASHCMD("S") /*ignored:*/"s");
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);
1647 if (isatty(STDIN_FILENO)) {
1648 /* Just "less"? No args and no redirection? */
1649 bb_error_msg("missing filename");
1653 filename = xstrdup(files[0]);
1656 if (option_mask32 & FLAG_TILDE)
1657 empty_line_marker = "";
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.
1666 tty_name = xmalloc_ttyname(STDOUT_FILENO);
1668 tty_fd = open(tty_name, O_RDONLY);
1673 /* Try controlling tty */
1675 tty_fd = open(CURRENT_TTY, O_RDONLY);
1677 return bb_cat(argv);
1680 kbd_fd = tty_fd; /* save in a global */
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;
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;
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);
1702 buffer = xmalloc((max_displayed_line+1) * sizeof(char *));
1707 #if ENABLE_FEATURE_LESS_WINCH
1708 while (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 */
1716 if (max_displayed_line < 3)
1717 max_displayed_line = 3;
1718 max_displayed_line -= 2;
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 */
1728 buffer_fill_and_print();
1729 /* This took some time. Loop back and check,
1730 * were there another SIGWINCH? */
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);
1742 keypress = less_getch(-1); /* -1: do not position cursor */
1744 keypress_process(keypress);
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:
1754 SUMMARY OF LESS COMMANDS
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.
1760 ---------------------------------------------------------------------------
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 ---------------------------------------------------------------------------
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 ---------------------------------------------------------------------------
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.
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 ---------------------------------------------------------------------------
1822 :e [file] Examine a new file.
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 ---------------------------------------------------------------------------
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 --.
1847 Display help (from command line).
1848 -a ........ --search-skip-screen
1849 Forward search skips current screen.
1850 -b [N] .... --buffers=[N]
1852 -B ........ --auto-buffers
1853 Don't automatically allocate buffers for pipes.
1854 -c ........ --clear-screen
1855 Repaint by clearing rather than scrolling.
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.
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]
1882 -L ........ --no-lessopen
1883 Ignore the LESSOPEN environment variable.
1884 -m -M .... --long-prompt --LONG-PROMPT
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]
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
1904 -t [tag] .. --tag=[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[,...]]
1918 -X ........ --no-init
1919 Don't use termcap init/deinit strings.
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]
1926 -" [c[c]] . --quotes=[c[c]]
1927 Set shell quote characters.
1929 Don't display tildes after end of file.
1930 -# [N] .... --shift=[N]
1931 Horizontal scroll amount (0 = one half screen width)
1933 ---------------------------------------------------------------------------
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.