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 extra flags"
47 //config: depends on LESS
49 //config: The extra flags provided do the following:
51 //config: The -M flag enables a more sophisticated status line.
52 //config: The -m flag enables a simpler status line with a percentage.
54 //config:config FEATURE_LESS_MARKS
55 //config: bool "Enable marks"
57 //config: depends on LESS
59 //config: Marks enable positions in a file to be stored for easy reference.
61 //config:config FEATURE_LESS_REGEXP
62 //config: bool "Enable regular expressions"
64 //config: depends on LESS
66 //config: Enable regular expressions, allowing complex file searches.
68 //config:config FEATURE_LESS_WINCH
69 //config: bool "Enable automatic resizing on window size changes"
71 //config: depends on LESS
73 //config: Makes less track window size changes.
75 //config:config FEATURE_LESS_ASK_TERMINAL
76 //config: bool "Use 'tell me cursor position' ESC sequence to measure window"
78 //config: depends on FEATURE_LESS_WINCH
80 //config: Makes less track window size changes.
81 //config: If terminal size can't be retrieved and $LINES/$COLUMNS are not set,
82 //config: this option makes less perform a last-ditch effort to find it:
83 //config: position cursor to 999,999 and ask terminal to report real
84 //config: cursor position using "ESC [ 6 n" escape sequence, then read stdin.
86 //config: This is not clean but helps a lot on serial lines and such.
88 //config:config FEATURE_LESS_DASHCMD
89 //config: bool "Enable flag changes ('-' command)"
91 //config: depends on LESS
93 //config: This enables the ability to change command-line flags within
94 //config: less itself ('-' keyboard command).
96 //config:config FEATURE_LESS_LINENUMS
97 //config: bool "Enable dynamic switching of line numbers"
99 //config: depends on FEATURE_LESS_DASHCMD
101 //config: Enables "-N" command.
103 //usage:#define less_trivial_usage
104 //usage: "[-EMNmh~I?] [FILE]..."
105 //usage:#define less_full_usage "\n\n"
106 //usage: "View FILE (or stdin) one screenful at a time\n"
107 //usage: "\n -E Quit once the end of a file is reached"
108 //usage: "\n -M,-m Display status line with line numbers"
109 //usage: "\n and percentage through the file"
110 //usage: "\n -N Prefix line number to each line"
111 //usage: "\n -I Ignore case in all searches"
112 //usage: "\n -~ Suppress ~s displayed past the end of the file"
114 #include <sched.h> /* sched_yield() */
117 #if ENABLE_FEATURE_LESS_REGEXP
123 /* The escape codes for highlighted and normal text */
124 #define HIGHLIGHT ESC"[7m"
125 #define NORMAL ESC"[0m"
126 /* The escape code to home and clear to the end of screen */
127 #define CLEAR ESC"[H\033[J"
128 /* The escape code to clear to the end of line */
129 #define CLEAR_2_EOL ESC"[K"
132 /* Absolute max of lines eaten */
133 MAXLINES = CONFIG_FEATURE_LESS_MAXLINES,
134 /* This many "after the end" lines we will show (at max) */
138 /* Command line options */
146 FLAG_S = (1 << 6) * ENABLE_FEATURE_LESS_DASHCMD,
147 /* hijack command line options variable for internal state vars */
148 LESS_STATE_MATCH_BACKWARDS = 1 << 15,
151 #if !ENABLE_FEATURE_LESS_REGEXP
152 enum { pattern_valid = 0 };
156 int cur_fline; /* signed */
157 int kbd_fd; /* fd to get input from */
159 /* last position in last line, taking into account tabs */
160 size_t last_line_pos;
162 unsigned max_lineno; /* this one tracks linewrap */
163 unsigned max_displayed_line;
165 #if ENABLE_FEATURE_LESS_WINCH
166 unsigned winch_counter;
168 ssize_t eof_error; /* eof if 0, error if < 0 */
170 ssize_t readeof; /* must be signed */
173 const char *empty_line_marker;
175 unsigned current_file;
178 #if ENABLE_FEATURE_LESS_MARKS
180 unsigned mark_lines[15][2];
182 #if ENABLE_FEATURE_LESS_REGEXP
183 unsigned *match_lines;
184 int match_pos; /* signed! */
185 int wanted_match; /* signed! */
188 smallint pattern_valid;
190 #if ENABLE_FEATURE_LESS_ASK_TERMINAL
191 smallint winsize_err;
194 struct termios term_orig, term_less;
195 char kbd_input[KEYCODE_BUFFER_SIZE];
197 #define G (*ptr_to_globals)
198 #define cur_fline (G.cur_fline )
199 #define kbd_fd (G.kbd_fd )
200 #define less_gets_pos (G.less_gets_pos )
201 #define last_line_pos (G.last_line_pos )
202 #define max_fline (G.max_fline )
203 #define max_lineno (G.max_lineno )
204 #define max_displayed_line (G.max_displayed_line)
205 #define width (G.width )
206 #define winch_counter (G.winch_counter )
207 /* This one is 100% not cached by compiler on read access */
208 #define WINCH_COUNTER (*(volatile unsigned *)&winch_counter)
209 #define eof_error (G.eof_error )
210 #define readpos (G.readpos )
211 #define readeof (G.readeof )
212 #define buffer (G.buffer )
213 #define flines (G.flines )
214 #define empty_line_marker (G.empty_line_marker )
215 #define num_files (G.num_files )
216 #define current_file (G.current_file )
217 #define filename (G.filename )
218 #define files (G.files )
219 #define num_marks (G.num_marks )
220 #define mark_lines (G.mark_lines )
221 #if ENABLE_FEATURE_LESS_REGEXP
222 #define match_lines (G.match_lines )
223 #define match_pos (G.match_pos )
224 #define num_matches (G.num_matches )
225 #define wanted_match (G.wanted_match )
226 #define pattern (G.pattern )
227 #define pattern_valid (G.pattern_valid )
229 #define terminated (G.terminated )
230 #define term_orig (G.term_orig )
231 #define term_less (G.term_less )
232 #define kbd_input (G.kbd_input )
233 #define INIT_G() do { \
234 SET_PTR_TO_GLOBALS(xzalloc(sizeof(G))); \
235 less_gets_pos = -1; \
236 empty_line_marker = "~"; \
241 IF_FEATURE_LESS_REGEXP(wanted_match = -1;) \
244 /* flines[] are lines read from stdin, each in malloc'ed buffer.
245 * Line numbers are stored as uint32_t prepended to each line.
246 * Pointer is adjusted so that flines[i] points directly past
247 * line number. Accesor: */
248 #define MEMPTR(p) ((char*)(p) - 4)
249 #define LINENO(p) (*(uint32_t*)((p) - 4))
252 /* Reset terminal input to normal */
253 static void set_tty_cooked(void)
256 tcsetattr(kbd_fd, TCSANOW, &term_orig);
259 /* Move the cursor to a position (x,y), where (0,0) is the
260 top-left corner of the console */
261 static void move_cursor(int line, int row)
263 printf(ESC"[%u;%uH", line, row);
266 static void clear_line(void)
268 printf(ESC"[%u;0H" CLEAR_2_EOL, max_displayed_line + 2);
271 static void print_hilite(const char *str)
273 printf(HIGHLIGHT"%s"NORMAL, str);
276 static void print_statusline(const char *str)
279 printf(HIGHLIGHT"%.*s"NORMAL, width - 1, str);
282 /* Exit the program gracefully */
283 static void less_exit(int code)
288 kill_myself_with_sig(- code); /* does not return */
292 #if (ENABLE_FEATURE_LESS_DASHCMD && ENABLE_FEATURE_LESS_LINENUMS) \
293 || ENABLE_FEATURE_LESS_WINCH
294 static void re_wrap(void)
300 int new_cur_fline = 0;
303 const char **old_flines = flines;
305 char **new_flines = NULL;
308 if (option_mask32 & FLAG_N)
321 if (*d == '\t') /* tab */
325 if (new_line_pos >= w) {
327 /* new line is full, create next one */
330 sz = (d - linebuf) + 1; /* + 1: NUL */
331 d = ((char*)xmalloc(sz + 4)) + 4;
333 memcpy(d, linebuf, sz);
334 new_flines = xrealloc_vector(new_flines, 8, dst_idx);
335 new_flines[dst_idx] = d;
337 if (new_line_pos < w) {
338 /* if we came here thru "goto next_new" */
339 if (src_idx > max_fline)
348 /* *d == NUL: old line ended, go to next old one */
349 free(MEMPTR(old_flines[src_idx]));
350 /* btw, convert cur_fline... */
351 if (cur_fline == src_idx)
352 new_cur_fline = dst_idx;
354 /* no more lines? finish last new line (and exit the loop) */
355 if (src_idx > max_fline)
357 s = old_flines[src_idx];
358 if (lineno != LINENO(s)) {
359 /* this is not a continuation line!
360 * create next _new_ line too */
366 flines = (const char **)new_flines;
368 max_fline = dst_idx - 1;
369 last_line_pos = new_line_pos;
370 cur_fline = new_cur_fline;
371 /* max_lineno is screen-size independent */
372 #if ENABLE_FEATURE_LESS_REGEXP
378 #if ENABLE_FEATURE_LESS_REGEXP
379 static void fill_match_lines(unsigned pos);
381 #define fill_match_lines(pos) ((void)0)
384 /* Devilishly complex routine.
386 * Has to deal with EOF and EPIPE on input,
387 * with line wrapping, with last line not ending in '\n'
388 * (possibly not ending YET!), with backspace and tabs.
389 * It reads input again if last time we got an EOF (thus supporting
390 * growing files) or EPIPE (watching output of slow process like make).
393 * flines[] - array of lines already read. Linewrap may cause
394 * one source file line to occupy several flines[n].
395 * flines[max_fline] - last line, possibly incomplete.
396 * terminated - 1 if flines[max_fline] is 'terminated'
397 * (if there was '\n' [which isn't stored itself, we just remember
399 * max_lineno - last line's number, this one doesn't increment
400 * on line wrap, only on "real" new lines.
401 * readbuf[0..readeof-1] - small preliminary buffer.
402 * readbuf[readpos] - next character to add to current line.
403 * last_line_pos - screen line position of next char to be read
404 * (takes into account tabs and backspaces)
405 * eof_error - < 0 error, == 0 EOF, > 0 not EOF/error
407 static void read_lines(void)
409 #define readbuf bb_common_bufsiz1
410 char *current_line, *p;
412 char last_terminated = terminated;
413 #if ENABLE_FEATURE_LESS_REGEXP
414 unsigned old_max_fline = max_fline;
415 time_t last_time = 0;
416 unsigned seconds_p1 = 3; /* seconds_to_loop + 1 */
419 if (option_mask32 & FLAG_N)
422 IF_FEATURE_LESS_REGEXP(again0:)
424 p = current_line = ((char*)xmalloc(w + 4)) + 4;
425 max_fline += last_terminated;
426 if (!last_terminated) {
427 const char *cp = flines[max_fline];
429 p += strlen(current_line);
430 free(MEMPTR(flines[max_fline]));
431 /* last_line_pos is still valid from previous read_lines() */
436 while (1) { /* read lines until we reach cur_fline or wanted_match */
439 while (1) { /* read chars until we have a line */
441 /* if no unprocessed chars left, eat more */
442 if (readpos >= readeof) {
444 eof_error = safe_read(STDIN_FILENO, readbuf, sizeof(readbuf));
451 c = readbuf[readpos];
452 /* backspace? [needed for manpages] */
453 /* <tab><bs> is (a) insane and */
454 /* (b) harder to do correctly, so we refuse to do it */
455 if (c == '\x8' && last_line_pos && p[-1] != '\t') {
456 readpos++; /* eat it */
458 /* was buggy (p could end up <= current_line)... */
463 size_t new_last_line_pos = last_line_pos + 1;
465 new_last_line_pos += 7;
466 new_last_line_pos &= (~7);
468 if ((int)new_last_line_pos >= w)
470 last_line_pos = new_last_line_pos;
472 /* ok, we will eat this char */
479 /* NUL is substituted by '\n'! */
480 if (c == '\0') c = '\n';
483 } /* end of "read chars until we have a line" loop */
484 /* Corner case: linewrap with only "" wrapping to next line */
485 /* Looks ugly on screen, so we do not store this empty line */
486 if (!last_terminated && !current_line[0]) {
492 last_terminated = terminated;
493 flines = xrealloc_vector(flines, 8, max_fline);
495 flines[max_fline] = (char*)xrealloc(MEMPTR(current_line), strlen(current_line) + 1 + 4) + 4;
496 LINENO(flines[max_fline]) = max_lineno;
500 if (max_fline >= MAXLINES) {
501 eof_error = 0; /* Pretend we saw EOF */
504 if (!(option_mask32 & FLAG_S)
505 ? (max_fline > cur_fline + max_displayed_line)
506 : (max_fline >= cur_fline
507 && max_lineno > LINENO(flines[cur_fline]) + max_displayed_line)
509 #if !ENABLE_FEATURE_LESS_REGEXP
512 if (wanted_match >= num_matches) { /* goto_match called us */
513 fill_match_lines(old_max_fline);
514 old_max_fline = max_fline;
516 if (wanted_match < num_matches)
520 if (eof_error <= 0) {
522 if (errno == EAGAIN) {
523 /* not yet eof or error, reset flag (or else
524 * we will hog CPU - select() will return
528 print_statusline(bb_msg_read_error);
531 #if !ENABLE_FEATURE_LESS_REGEXP
534 if (wanted_match < num_matches) {
536 } else { /* goto_match called us */
537 time_t t = time(NULL);
538 if (t != last_time) {
540 if (--seconds_p1 == 0)
544 goto again0; /* go loop again (max 2 seconds) */
549 current_line = ((char*)xmalloc(w + 4)) + 4;
552 } /* end of "read lines until we reach cur_fline" loop */
553 fill_match_lines(old_max_fline);
554 #if ENABLE_FEATURE_LESS_REGEXP
555 /* prevent us from being stuck in search for a match */
561 #if ENABLE_FEATURE_LESS_FLAGS
562 /* Interestingly, writing calc_percent as a function saves around 32 bytes
564 static int calc_percent(void)
566 unsigned p = (100 * (cur_fline+max_displayed_line+1) + max_fline/2) / (max_fline+1);
567 return p <= 100 ? p : 100;
570 /* Print a status line if -M was specified */
571 static void m_status_print(void)
575 if (less_gets_pos >= 0) /* don't touch statusline while input is done! */
579 printf(HIGHLIGHT"%s", filename);
581 printf(" (file %i of %i)", current_file, num_files);
582 printf(" lines %i-%i/%i ",
583 cur_fline + 1, cur_fline + max_displayed_line + 1,
585 if (cur_fline >= (int)(max_fline - max_displayed_line)) {
586 printf("(END)"NORMAL);
587 if (num_files > 1 && current_file != num_files)
588 printf(HIGHLIGHT" - next: %s"NORMAL, files[current_file]);
591 percentage = calc_percent();
592 printf("%i%%"NORMAL, percentage);
596 /* Print the status line */
597 static void status_print(void)
601 if (less_gets_pos >= 0) /* don't touch statusline while input is done! */
604 /* Change the status if flags have been set */
605 #if ENABLE_FEATURE_LESS_FLAGS
606 if (option_mask32 & (FLAG_M|FLAG_m)) {
614 if (cur_fline && cur_fline < (int)(max_fline - max_displayed_line)) {
622 printf(HIGHLIGHT"%s (file %i of %i)"NORMAL,
623 p, current_file, num_files);
629 static void cap_cur_fline(int nlines)
634 if (cur_fline + max_displayed_line > max_fline + TILDES) {
638 diff = max_fline - (cur_fline + max_displayed_line) + TILDES;
639 /* As the number of lines requested was too large, we just move
640 * to the end of the file */
646 static const char controls[] ALIGN1 =
647 /* NUL: never encountered; TAB: not converted */
648 /**/"\x01\x02\x03\x04\x05\x06\x07\x08" "\x0a\x0b\x0c\x0d\x0e\x0f"
649 "\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1a\x1b\x1c\x1d\x1e\x1f"
650 "\x7f\x9b"; /* DEL and infamous Meta-ESC :( */
651 static const char ctrlconv[] ALIGN1 =
652 /* why 40 instead of 4a below? - it is a replacement for '\n'.
653 * '\n' is a former NUL - we subst it with @, not J */
654 "\x40\x41\x42\x43\x44\x45\x46\x47\x48\x49\x40\x4b\x4c\x4d\x4e\x4f"
655 "\x50\x51\x52\x53\x54\x55\x56\x57\x58\x59\x5a\x5b\x5c\x5d\x5e\x5f";
657 static void lineno_str(char *nbuf9, const char *line)
660 if (option_mask32 & FLAG_N) {
664 if (line == empty_line_marker) {
665 memset(nbuf9, ' ', 8);
669 /* Width of 7 preserves tab spacing in the text */
671 n = LINENO(line) + 1;
676 sprintf(nbuf9, fmt, n);
681 #if ENABLE_FEATURE_LESS_REGEXP
682 static void print_found(const char *line)
687 regmatch_t match_structs;
691 const char *str = line;
696 n = strcspn(str, controls);
703 n = strspn(str, controls);
710 /* buf[] holds quarantined version of str */
712 /* Each part of the line that matches has the HIGHLIGHT
713 and NORMAL escape sequences placed around it.
714 NB: we regex against line, but insert text
715 from quarantined copy (buf[]) */
721 while (match_status == 0) {
722 char *new = xasprintf("%s%.*s"HIGHLIGHT"%.*s"NORMAL,
723 growline ? growline : "",
724 match_structs.rm_so, str,
725 match_structs.rm_eo - match_structs.rm_so,
726 str + match_structs.rm_so);
729 str += match_structs.rm_eo;
730 line += match_structs.rm_eo;
733 /* Most of the time doesn't find the regex, optimize for that */
734 match_status = regexec(&pattern, line, 1, &match_structs, eflags);
735 /* if even "" matches, treat it as "not a match" */
736 if (match_structs.rm_so >= match_structs.rm_eo)
740 lineno_str(nbuf9, line);
742 printf(CLEAR_2_EOL"%s%s\n", nbuf9, str);
745 printf(CLEAR_2_EOL"%s%s%s\n", nbuf9, growline, str);
749 void print_found(const char *line);
752 static void print_ascii(const char *str)
759 lineno_str(nbuf9, str);
760 printf(CLEAR_2_EOL"%s", nbuf9);
763 n = strcspn(str, controls);
766 printf("%.*s", (int) n, str);
769 n = strspn(str, controls);
774 else if (*str == (char)0x9b)
775 /* VT100's CSI, aka Meta-ESC. Who's inventor? */
776 /* I want to know who committed this sin */
779 *p++ = ctrlconv[(unsigned char)*str];
788 /* Print the buffer */
789 static void buffer_print(void)
794 for (i = 0; i <= max_displayed_line; i++)
796 print_found(buffer[i]);
798 print_ascii(buffer[i]);
802 static void buffer_fill_and_print(void)
805 #if ENABLE_FEATURE_LESS_DASHCMD
806 int fpos = cur_fline;
808 if (option_mask32 & FLAG_S) {
809 /* Go back to the beginning of this line */
810 while (fpos && LINENO(flines[fpos]) == LINENO(flines[fpos-1]))
815 while (i <= max_displayed_line && fpos <= max_fline) {
816 int lineno = LINENO(flines[fpos]);
817 buffer[i] = flines[fpos];
821 } while ((fpos <= max_fline)
822 && (option_mask32 & FLAG_S)
823 && lineno == LINENO(flines[fpos])
827 for (i = 0; i <= max_displayed_line && cur_fline + i <= max_fline; i++) {
828 buffer[i] = flines[cur_fline + i];
831 for (; i <= max_displayed_line; i++) {
832 buffer[i] = empty_line_marker;
837 /* Move the buffer up and down in the file in order to scroll */
838 static void buffer_down(int nlines)
842 cap_cur_fline(nlines);
843 buffer_fill_and_print();
846 static void buffer_up(int nlines)
849 if (cur_fline < 0) cur_fline = 0;
851 buffer_fill_and_print();
854 static void buffer_line(int linenum)
860 if (linenum + max_displayed_line > max_fline)
861 linenum = max_fline - max_displayed_line + TILDES;
865 buffer_fill_and_print();
868 static void open_file_and_read_lines(void)
871 xmove_fd(xopen(filename, O_RDONLY), STDIN_FILENO);
873 /* "less" with no arguments in argv[] */
874 /* For status line only */
875 filename = xstrdup(bb_msg_standard_input);
884 /* Reinitialize everything for a new file - free the memory and start over */
885 static void reinitialize(void)
890 for (i = 0; i <= max_fline; i++)
891 free(MEMPTR(flines[i]));
899 open_file_and_read_lines();
900 #if ENABLE_FEATURE_LESS_ASK_TERMINAL
902 printf("\033[999;999H" "\033[6n");
904 buffer_fill_and_print();
907 static int64_t getch_nowait(void)
911 struct pollfd pfd[2];
913 pfd[0].fd = STDIN_FILENO;
914 pfd[0].events = POLLIN;
916 pfd[1].events = POLLIN;
918 tcsetattr(kbd_fd, TCSANOW, &term_less);
919 /* NB: select/poll returns whenever read will not block. Therefore:
920 * if eof is reached, select/poll will return immediately
921 * because read will immediately return 0 bytes.
922 * Even if select/poll says that input is available, read CAN block
923 * (switch fd into O_NONBLOCK'ed mode to avoid it)
926 /* Are we interested in stdin? */
927 //TODO: reuse code for determining this
928 if (!(option_mask32 & FLAG_S)
929 ? !(max_fline > cur_fline + max_displayed_line)
930 : !(max_fline >= cur_fline
931 && max_lineno > LINENO(flines[cur_fline]) + max_displayed_line)
933 if (eof_error > 0) /* did NOT reach eof yet */
934 rd = 0; /* yes, we are interested in stdin */
936 /* Position cursor if line input is done */
937 if (less_gets_pos >= 0)
938 move_cursor(max_displayed_line + 2, less_gets_pos + 1);
941 if (kbd_input[0] == 0) { /* if nothing is buffered */
942 #if ENABLE_FEATURE_LESS_WINCH
945 /* NB: SIGWINCH interrupts poll() */
946 r = poll(pfd + rd, 2 - rd, -1);
947 if (/*r < 0 && errno == EINTR &&*/ winch_counter)
948 return '\\'; /* anything which has no defined function */
952 safe_poll(pfd + rd, 2 - rd, -1);
956 /* We have kbd_fd in O_NONBLOCK mode, read inside read_key()
957 * would not block even if there is no input available */
958 key64 = read_key(kbd_fd, kbd_input, /*timeout off:*/ -2);
959 if ((int)key64 == -1) {
960 if (errno == EAGAIN) {
961 /* No keyboard input available. Since poll() did return,
962 * we should have input on stdin */
964 buffer_fill_and_print();
967 /* EOF/error (ssh session got killed etc) */
974 /* Grab a character from input without requiring the return key.
975 * May return KEYCODE_xxx values.
976 * Note that this function works best with raw input. */
977 static int64_t less_getch(int pos)
984 key = key64 = getch_nowait();
987 /* Discard Ctrl-something chars.
988 * (checking only lower 32 bits is a size optimization:
989 * upper 32 bits are used only by KEYCODE_CURSOR_POS)
991 if (key >= 0 && key < ' ' && key != 0x0d && key != 8)
996 static char* less_gets(int sz)
1000 char *result = xzalloc(1);
1004 less_gets_pos = sz + i;
1017 if (c < ' ') /* filters out KEYCODE_xxx too (<0) */
1019 if (i >= width - sz - 1)
1020 continue; /* len limit */
1023 result = xrealloc(result, i+1);
1027 static void examine_file(void)
1031 print_statusline("Examine: ");
1032 new_fname = less_gets(sizeof("Examine: ") - 1);
1033 if (!new_fname[0]) {
1039 if (access(new_fname, R_OK) != 0) {
1040 print_statusline("Cannot read this file");
1044 filename = new_fname;
1045 /* files start by = argv. why we assume that argv is infinitely long??
1046 files[num_files] = filename;
1047 current_file = num_files + 1;
1049 files[0] = filename;
1050 num_files = current_file = 1;
1054 /* This function changes the file currently being paged. direction can be one of the following:
1055 * -1: go back one file
1056 * 0: go to the first file
1057 * 1: go forward one file */
1058 static void change_file(int direction)
1060 if (current_file != ((direction > 0) ? num_files : 1)) {
1061 current_file = direction ? current_file + direction : 1;
1063 filename = xstrdup(files[current_file - 1]);
1066 print_statusline(direction > 0 ? "No next file" : "No previous file");
1070 static void remove_current_file(void)
1077 if (current_file != 1) {
1079 for (i = 3; i <= num_files; i++)
1080 files[i - 2] = files[i - 1];
1084 for (i = 2; i <= num_files; i++)
1085 files[i - 2] = files[i - 1];
1091 static void colon_process(void)
1095 /* Clear the current line and print a prompt */
1096 print_statusline(" :");
1098 keypress = less_getch(2);
1101 remove_current_file();
1106 #if ENABLE_FEATURE_LESS_FLAGS
1118 less_exit(EXIT_SUCCESS);
1126 #if ENABLE_FEATURE_LESS_REGEXP
1127 static void normalize_match_pos(int match)
1129 if (match >= num_matches)
1130 match = num_matches - 1;
1136 static void goto_match(int match)
1142 /* Try to find next match if eof isn't reached yet */
1143 if (match >= num_matches && eof_error > 0) {
1144 wanted_match = match; /* "I want to read until I see N'th match" */
1148 normalize_match_pos(match);
1149 buffer_line(match_lines[match_pos]);
1151 print_statusline("No matches found");
1155 static void fill_match_lines(unsigned pos)
1159 /* Run the regex on each line of the current file */
1160 while (pos <= max_fline) {
1161 /* If this line matches */
1162 if (regexec(&pattern, flines[pos], 0, NULL, 0) == 0
1163 /* and we didn't match it last time */
1164 && !(num_matches && match_lines[num_matches-1] == pos)
1166 match_lines = xrealloc_vector(match_lines, 4, num_matches);
1167 match_lines[num_matches++] = pos;
1173 static void regex_process(void)
1175 char *uncomp_regex, *err;
1177 /* Reset variables */
1182 if (pattern_valid) {
1187 /* Get the uncompiled regular expression from the user */
1189 bb_putchar((option_mask32 & LESS_STATE_MATCH_BACKWARDS) ? '?' : '/');
1190 uncomp_regex = less_gets(1);
1191 if (!uncomp_regex[0]) {
1197 /* Compile the regex and check for errors */
1198 err = regcomp_or_errmsg(&pattern, uncomp_regex,
1199 (option_mask32 & FLAG_I) ? REG_ICASE : 0);
1202 print_statusline(err);
1209 fill_match_lines(0);
1210 while (match_pos < num_matches) {
1211 if ((int)match_lines[match_pos] > cur_fline)
1215 if (option_mask32 & LESS_STATE_MATCH_BACKWARDS)
1218 /* It's possible that no matches are found yet.
1219 * goto_match() will read input looking for match,
1221 goto_match(match_pos);
1225 static void number_process(int first_digit)
1230 char num_input[sizeof(int)*4]; /* more than enough */
1232 num_input[0] = first_digit;
1234 /* Clear the current line, print a prompt, and then print the digit */
1236 printf(":%c", first_digit);
1238 /* Receive input until a letter is given */
1240 while (i < sizeof(num_input)-1) {
1241 keypress = less_getch(i + 1);
1242 if ((unsigned)keypress > 255 || !isdigit(num_input[i]))
1244 num_input[i] = keypress;
1245 bb_putchar(keypress);
1249 num_input[i] = '\0';
1250 num = bb_strtou(num_input, NULL, 10);
1251 /* on format error, num == -1 */
1252 if (num < 1 || num > MAXLINES) {
1257 /* We now know the number and the letter entered, so we process them */
1259 case KEYCODE_DOWN: case 'z': case 'd': case 'e': case ' ': case '\015':
1262 case KEYCODE_UP: case 'b': case 'w': case 'y': case 'u':
1265 case 'g': case '<': case 'G': case '>':
1266 cur_fline = num + max_displayed_line;
1268 buffer_line(num - 1);
1271 num = num * (max_fline / 100); /* + max_fline / 2; */
1272 cur_fline = num + max_displayed_line;
1276 #if ENABLE_FEATURE_LESS_REGEXP
1278 goto_match(match_pos + num);
1281 option_mask32 &= ~LESS_STATE_MATCH_BACKWARDS;
1285 option_mask32 |= LESS_STATE_MATCH_BACKWARDS;
1292 #if ENABLE_FEATURE_LESS_DASHCMD
1293 static void flag_change(void)
1299 keypress = less_getch(1);
1303 option_mask32 ^= FLAG_M;
1306 option_mask32 ^= FLAG_m;
1309 option_mask32 ^= FLAG_E;
1312 option_mask32 ^= FLAG_TILDE;
1315 option_mask32 ^= FLAG_S;
1316 buffer_fill_and_print();
1318 #if ENABLE_FEATURE_LESS_LINENUMS
1320 option_mask32 ^= FLAG_N;
1322 buffer_fill_and_print();
1329 static void show_flag_status(void)
1336 keypress = less_getch(1);
1340 flag_val = option_mask32 & FLAG_M;
1343 flag_val = option_mask32 & FLAG_m;
1346 flag_val = option_mask32 & FLAG_TILDE;
1349 flag_val = option_mask32 & FLAG_N;
1352 flag_val = option_mask32 & FLAG_E;
1360 printf(HIGHLIGHT"The status of the flag is: %u"NORMAL, flag_val != 0);
1364 #endif /* ENABLE_FEATURE_LESS_DASHCMD */
1366 static void save_input_to_file(void)
1368 const char *msg = "";
1373 print_statusline("Log file: ");
1374 current_line = less_gets(sizeof("Log file: ")-1);
1375 if (current_line[0]) {
1376 fp = fopen_for_write(current_line);
1378 msg = "Error opening log file";
1381 for (i = 0; i <= max_fline; i++)
1382 fprintf(fp, "%s\n", flines[i]);
1387 print_statusline(msg);
1391 #if ENABLE_FEATURE_LESS_MARKS
1392 static void add_mark(void)
1396 print_statusline("Mark: ");
1397 letter = less_getch(sizeof("Mark: ") - 1);
1399 if (isalpha(letter)) {
1400 /* If we exceed 15 marks, start overwriting previous ones */
1401 if (num_marks == 14)
1404 mark_lines[num_marks][0] = letter;
1405 mark_lines[num_marks][1] = cur_fline;
1408 print_statusline("Invalid mark letter");
1412 static void goto_mark(void)
1417 print_statusline("Go to mark: ");
1418 letter = less_getch(sizeof("Go to mark: ") - 1);
1421 if (isalpha(letter)) {
1422 for (i = 0; i <= num_marks; i++)
1423 if (letter == mark_lines[i][0]) {
1424 buffer_line(mark_lines[i][1]);
1427 if (num_marks == 14 && letter != mark_lines[14][0])
1428 print_statusline("Mark not set");
1430 print_statusline("Invalid mark letter");
1434 #if ENABLE_FEATURE_LESS_BRACKETS
1435 static char opp_bracket(char bracket)
1438 case '{': case '[': /* '}' == '{' + 2. Same for '[' */
1440 case '(': /* ')' == '(' + 1 */
1452 static void match_right_bracket(char bracket)
1456 if (strchr(flines[cur_fline], bracket) == NULL) {
1457 print_statusline("No bracket in top line");
1460 bracket = opp_bracket(bracket);
1461 for (i = cur_fline + 1; i < max_fline; i++) {
1462 if (strchr(flines[i], bracket) != NULL) {
1467 print_statusline("No matching bracket found");
1470 static void match_left_bracket(char bracket)
1474 if (strchr(flines[cur_fline + max_displayed_line], bracket) == NULL) {
1475 print_statusline("No bracket in bottom line");
1479 bracket = opp_bracket(bracket);
1480 for (i = cur_fline + max_displayed_line; i >= 0; i--) {
1481 if (strchr(flines[i], bracket) != NULL) {
1486 print_statusline("No matching bracket found");
1488 #endif /* FEATURE_LESS_BRACKETS */
1490 static void keypress_process(int keypress)
1493 case KEYCODE_DOWN: case 'e': case 'j': case 0x0d:
1496 case KEYCODE_UP: case 'y': case 'k':
1499 case KEYCODE_PAGEDOWN: case ' ': case 'z': case 'f':
1500 buffer_down(max_displayed_line + 1);
1502 case KEYCODE_PAGEUP: case 'w': case 'b':
1503 buffer_up(max_displayed_line + 1);
1506 buffer_down((max_displayed_line + 1) / 2);
1509 buffer_up((max_displayed_line + 1) / 2);
1511 case KEYCODE_HOME: case 'g': case 'p': case '<': case '%':
1514 case KEYCODE_END: case 'G': case '>':
1515 cur_fline = MAXLINES;
1517 buffer_line(cur_fline);
1520 less_exit(EXIT_SUCCESS);
1522 #if ENABLE_FEATURE_LESS_MARKS
1533 /* TODO: (1) also bind ^R, ^L to this?
1534 * (2) re-measure window size?
1542 save_input_to_file();
1547 #if ENABLE_FEATURE_LESS_FLAGS
1552 #if ENABLE_FEATURE_LESS_REGEXP
1554 option_mask32 &= ~LESS_STATE_MATCH_BACKWARDS;
1558 goto_match(match_pos + 1);
1561 goto_match(match_pos - 1);
1564 option_mask32 |= LESS_STATE_MATCH_BACKWARDS;
1568 #if ENABLE_FEATURE_LESS_DASHCMD
1579 #if ENABLE_FEATURE_LESS_BRACKETS
1580 case '{': case '(': case '[':
1581 match_right_bracket(keypress);
1583 case '}': case ')': case ']':
1584 match_left_bracket(keypress);
1592 if (isdigit(keypress))
1593 number_process(keypress);
1596 static void sig_catcher(int sig)
1601 #if ENABLE_FEATURE_LESS_WINCH
1602 static void sigwinch_handler(int sig UNUSED_PARAM)
1608 int less_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
1609 int less_main(int argc, char **argv)
1613 /* TODO: -x: do not interpret backspace, -xx: tab also */
1614 /* -xxx: newline also */
1615 /* -w N: assume width N (-xxx -w 32: hex viewer of sorts) */
1616 getopt32(argv, "EMmN~I" IF_FEATURE_LESS_DASHCMD("S"));
1622 /* Another popular pager, most, detects when stdout
1623 * is not a tty and turns into cat. This makes sense. */
1624 if (!isatty(STDOUT_FILENO))
1625 return bb_cat(argv);
1628 if (isatty(STDIN_FILENO)) {
1629 /* Just "less"? No args and no redirection? */
1630 bb_error_msg("missing filename");
1634 filename = xstrdup(files[0]);
1637 if (option_mask32 & FLAG_TILDE)
1638 empty_line_marker = "";
1640 kbd_fd = open(CURRENT_TTY, O_RDONLY);
1642 return bb_cat(argv);
1645 tcgetattr(kbd_fd, &term_orig);
1646 term_less = term_orig;
1647 term_less.c_lflag &= ~(ICANON | ECHO);
1648 term_less.c_iflag &= ~(IXON | ICRNL);
1649 /*term_less.c_oflag &= ~ONLCR;*/
1650 term_less.c_cc[VMIN] = 1;
1651 term_less.c_cc[VTIME] = 0;
1653 IF_FEATURE_LESS_ASK_TERMINAL(G.winsize_err =) get_terminal_width_height(kbd_fd, &width, &max_displayed_line);
1654 /* 20: two tabstops + 4 */
1655 if (width < 20 || max_displayed_line < 3)
1656 return bb_cat(argv);
1657 max_displayed_line -= 2;
1659 /* We want to restore term_orig on exit */
1660 bb_signals(BB_FATAL_SIGS, sig_catcher);
1661 #if ENABLE_FEATURE_LESS_WINCH
1662 signal(SIGWINCH, sigwinch_handler);
1665 buffer = xmalloc((max_displayed_line+1) * sizeof(char *));
1670 #if ENABLE_FEATURE_LESS_WINCH
1671 while (WINCH_COUNTER) {
1674 IF_FEATURE_LESS_ASK_TERMINAL(G.winsize_err =) get_terminal_width_height(kbd_fd, &width, &max_displayed_line);
1675 IF_FEATURE_LESS_ASK_TERMINAL(got_size:)
1676 /* 20: two tabstops + 4 */
1679 if (max_displayed_line < 3)
1680 max_displayed_line = 3;
1681 max_displayed_line -= 2;
1683 buffer = xmalloc((max_displayed_line+1) * sizeof(char *));
1684 /* Avoid re-wrap and/or redraw if we already know
1685 * we need to do it again. These ops are expensive */
1691 buffer_fill_and_print();
1692 /* This took some time. Loop back and check,
1693 * were there another SIGWINCH? */
1695 keypress = less_getch(-1); /* -1: do not position cursor */
1696 # if ENABLE_FEATURE_LESS_ASK_TERMINAL
1697 if ((int32_t)keypress == KEYCODE_CURSOR_POS) {
1698 uint32_t rc = (keypress >> 32);
1699 width = (rc & 0x7fff);
1700 max_displayed_line = ((rc >> 16) & 0x7fff);
1705 keypress = less_getch(-1); /* -1: do not position cursor */
1707 keypress_process(keypress);
1712 Help text of less version 418 is below.
1713 If you are implementing something, keeping
1714 key and/or command line switch compatibility is a good idea:
1717 SUMMARY OF LESS COMMANDS
1719 Commands marked with * may be preceded by a number, N.
1720 Notes in parentheses indicate the behavior if N is given.
1721 h H Display this help.
1723 ---------------------------------------------------------------------------
1725 e ^E j ^N CR * Forward one line (or N lines).
1726 y ^Y k ^K ^P * Backward one line (or N lines).
1727 f ^F ^V SPACE * Forward one window (or N lines).
1728 b ^B ESC-v * Backward one window (or N lines).
1729 z * Forward one window (and set window to N).
1730 w * Backward one window (and set window to N).
1731 ESC-SPACE * Forward one window, but don't stop at end-of-file.
1732 d ^D * Forward one half-window (and set half-window to N).
1733 u ^U * Backward one half-window (and set half-window to N).
1734 ESC-) RightArrow * Left one half screen width (or N positions).
1735 ESC-( LeftArrow * Right one half screen width (or N positions).
1736 F Forward forever; like "tail -f".
1737 r ^R ^L Repaint screen.
1738 R Repaint screen, discarding buffered input.
1739 ---------------------------------------------------
1740 Default "window" is the screen height.
1741 Default "half-window" is half of the screen height.
1742 ---------------------------------------------------------------------------
1744 /pattern * Search forward for (N-th) matching line.
1745 ?pattern * Search backward for (N-th) matching line.
1746 n * Repeat previous search (for N-th occurrence).
1747 N * Repeat previous search in reverse direction.
1748 ESC-n * Repeat previous search, spanning files.
1749 ESC-N * Repeat previous search, reverse dir. & spanning files.
1750 ESC-u Undo (toggle) search highlighting.
1751 ---------------------------------------------------
1752 Search patterns may be modified by one or more of:
1753 ^N or ! Search for NON-matching lines.
1754 ^E or * Search multiple files (pass thru END OF FILE).
1755 ^F or @ Start search at FIRST file (for /) or last file (for ?).
1756 ^K Highlight matches, but don't move (KEEP position).
1757 ^R Don't use REGULAR EXPRESSIONS.
1758 ---------------------------------------------------------------------------
1760 g < ESC-< * Go to first line in file (or line N).
1761 G > ESC-> * Go to last line in file (or line N).
1762 p % * Go to beginning of file (or N percent into file).
1763 t * Go to the (N-th) next tag.
1764 T * Go to the (N-th) previous tag.
1765 { ( [ * Find close bracket } ) ].
1766 } ) ] * Find open bracket { ( [.
1767 ESC-^F <c1> <c2> * Find close bracket <c2>.
1768 ESC-^B <c1> <c2> * Find open bracket <c1>
1769 ---------------------------------------------------
1770 Each "find close bracket" command goes forward to the close bracket
1771 matching the (N-th) open bracket in the top line.
1772 Each "find open bracket" command goes backward to the open bracket
1773 matching the (N-th) close bracket in the bottom line.
1774 m<letter> Mark the current position with <letter>.
1775 '<letter> Go to a previously marked position.
1776 '' Go to the previous position.
1778 ---------------------------------------------------
1779 A mark is any upper-case or lower-case letter.
1780 Certain marks are predefined:
1781 ^ means beginning of the file
1782 $ means end of the file
1783 ---------------------------------------------------------------------------
1785 :e [file] Examine a new file.
1787 :n * Examine the (N-th) next file from the command line.
1788 :p * Examine the (N-th) previous file from the command line.
1789 :x * Examine the first (or N-th) file from the command line.
1790 :d Delete the current file from the command line list.
1791 = ^G :f Print current file name.
1792 ---------------------------------------------------------------------------
1793 MISCELLANEOUS COMMANDS
1794 -<flag> Toggle a command line option [see OPTIONS below].
1795 --<name> Toggle a command line option, by name.
1796 _<flag> Display the setting of a command line option.
1797 __<name> Display the setting of an option, by name.
1798 +cmd Execute the less cmd each time a new file is examined.
1799 !command Execute the shell command with $SHELL.
1800 |Xcommand Pipe file between current pos & mark X to shell command.
1801 v Edit the current file with $VISUAL or $EDITOR.
1802 V Print version number of "less".
1803 ---------------------------------------------------------------------------
1805 Most options may be changed either on the command line,
1806 or from within less by using the - or -- command.
1807 Options may be given in one of two forms: either a single
1808 character preceded by a -, or a name preceeded by --.
1810 Display help (from command line).
1811 -a ........ --search-skip-screen
1812 Forward search skips current screen.
1813 -b [N] .... --buffers=[N]
1815 -B ........ --auto-buffers
1816 Don't automatically allocate buffers for pipes.
1817 -c ........ --clear-screen
1818 Repaint by clearing rather than scrolling.
1821 -D [xn.n] . --color=xn.n
1822 Set screen colors. (MS-DOS only)
1823 -e -E .... --quit-at-eof --QUIT-AT-EOF
1824 Quit at end of file.
1826 Force open non-regular files.
1827 -F ........ --quit-if-one-screen
1828 Quit if entire file fits on first screen.
1829 -g ........ --hilite-search
1830 Highlight only last match for searches.
1831 -G ........ --HILITE-SEARCH
1832 Don't highlight any matches for searches.
1833 -h [N] .... --max-back-scroll=[N]
1834 Backward scroll limit.
1835 -i ........ --ignore-case
1836 Ignore case in searches that do not contain uppercase.
1837 -I ........ --IGNORE-CASE
1838 Ignore case in all searches.
1839 -j [N] .... --jump-target=[N]
1840 Screen position of target lines.
1841 -J ........ --status-column
1842 Display a status column at left edge of screen.
1843 -k [file] . --lesskey-file=[file]
1845 -L ........ --no-lessopen
1846 Ignore the LESSOPEN environment variable.
1847 -m -M .... --long-prompt --LONG-PROMPT
1849 -n -N .... --line-numbers --LINE-NUMBERS
1850 Don't use line numbers.
1851 -o [file] . --log-file=[file]
1852 Copy to log file (standard input only).
1853 -O [file] . --LOG-FILE=[file]
1854 Copy to log file (unconditionally overwrite).
1855 -p [pattern] --pattern=[pattern]
1856 Start at pattern (from command line).
1857 -P [prompt] --prompt=[prompt]
1859 -q -Q .... --quiet --QUIET --silent --SILENT
1860 Quiet the terminal bell.
1861 -r -R .... --raw-control-chars --RAW-CONTROL-CHARS
1862 Output "raw" control characters.
1863 -s ........ --squeeze-blank-lines
1864 Squeeze multiple blank lines.
1865 -S ........ --chop-long-lines
1867 -t [tag] .. --tag=[tag]
1869 -T [tagsfile] --tag-file=[tagsfile]
1870 Use an alternate tags file.
1871 -u -U .... --underline-special --UNDERLINE-SPECIAL
1872 Change handling of backspaces.
1873 -V ........ --version
1874 Display the version number of "less".
1875 -w ........ --hilite-unread
1876 Highlight first new line after forward-screen.
1877 -W ........ --HILITE-UNREAD
1878 Highlight first new line after any forward movement.
1879 -x [N[,...]] --tabs=[N[,...]]
1881 -X ........ --no-init
1882 Don't use termcap init/deinit strings.
1884 Don't use termcap keypad init/deinit strings.
1885 -y [N] .... --max-forw-scroll=[N]
1886 Forward scroll limit.
1887 -z [N] .... --window=[N]
1889 -" [c[c]] . --quotes=[c[c]]
1890 Set shell quote characters.
1892 Don't display tildes after end of file.
1893 -# [N] .... --shift=[N]
1894 Horizontal scroll amount (0 = one half screen width)
1896 ---------------------------------------------------------------------------
1898 These keys can be used to edit text being entered
1899 on the "command line" at the bottom of the screen.
1900 RightArrow ESC-l Move cursor right one character.
1901 LeftArrow ESC-h Move cursor left one character.
1902 CNTL-RightArrow ESC-RightArrow ESC-w Move cursor right one word.
1903 CNTL-LeftArrow ESC-LeftArrow ESC-b Move cursor left one word.
1904 HOME ESC-0 Move cursor to start of line.
1905 END ESC-$ Move cursor to end of line.
1906 BACKSPACE Delete char to left of cursor.
1907 DELETE ESC-x Delete char under cursor.
1908 CNTL-BACKSPACE ESC-BACKSPACE Delete word to left of cursor.
1909 CNTL-DELETE ESC-DELETE ESC-X Delete word under cursor.
1910 CNTL-U ESC (MS-DOS only) Delete entire line.
1911 UpArrow ESC-k Retrieve previous command line.
1912 DownArrow ESC-j Retrieve next command line.
1913 TAB Complete filename & cycle.
1914 SHIFT-TAB ESC-TAB Complete filename & reverse cycle.
1915 CNTL-L Complete filename, list all.