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
24 //usage:#define less_trivial_usage
25 //usage: "[-EMNmh~I?] [FILE]..."
26 //usage:#define less_full_usage "\n\n"
27 //usage: "View FILE (or stdin) one screenful at a time\n"
28 //usage: "\n -E Quit once the end of a file is reached"
29 //usage: "\n -M,-m Display status line with line numbers"
30 //usage: "\n and percentage through the file"
31 //usage: "\n -N Prefix line number to each line"
32 //usage: "\n -I Ignore case in all searches"
33 //usage: "\n -~ Suppress ~s displayed past the end of the file"
35 #include <sched.h> /* sched_yield() */
38 #if ENABLE_FEATURE_LESS_REGEXP
44 /* The escape codes for highlighted and normal text */
45 #define HIGHLIGHT ESC"[7m"
46 #define NORMAL ESC"[0m"
47 /* The escape code to home and clear to the end of screen */
48 #define CLEAR ESC"[H\033[J"
49 /* The escape code to clear to the end of line */
50 #define CLEAR_2_EOL ESC"[K"
53 /* Absolute max of lines eaten */
54 MAXLINES = CONFIG_FEATURE_LESS_MAXLINES,
55 /* This many "after the end" lines we will show (at max) */
59 /* Command line options */
67 FLAG_S = (1 << 6) * ENABLE_FEATURE_LESS_DASHCMD,
68 /* hijack command line options variable for internal state vars */
69 LESS_STATE_MATCH_BACKWARDS = 1 << 15,
72 #if !ENABLE_FEATURE_LESS_REGEXP
73 enum { pattern_valid = 0 };
77 int cur_fline; /* signed */
78 int kbd_fd; /* fd to get input from */
80 /* last position in last line, taking into account tabs */
83 unsigned max_lineno; /* this one tracks linewrap */
84 unsigned max_displayed_line;
86 #if ENABLE_FEATURE_LESS_WINCH
87 unsigned winch_counter;
89 ssize_t eof_error; /* eof if 0, error if < 0 */
91 ssize_t readeof; /* must be signed */
94 const char *empty_line_marker;
96 unsigned current_file;
99 #if ENABLE_FEATURE_LESS_MARKS
101 unsigned mark_lines[15][2];
103 #if ENABLE_FEATURE_LESS_REGEXP
104 unsigned *match_lines;
105 int match_pos; /* signed! */
106 int wanted_match; /* signed! */
109 smallint pattern_valid;
112 struct termios term_orig, term_less;
113 char kbd_input[KEYCODE_BUFFER_SIZE];
115 #define G (*ptr_to_globals)
116 #define cur_fline (G.cur_fline )
117 #define kbd_fd (G.kbd_fd )
118 #define less_gets_pos (G.less_gets_pos )
119 #define last_line_pos (G.last_line_pos )
120 #define max_fline (G.max_fline )
121 #define max_lineno (G.max_lineno )
122 #define max_displayed_line (G.max_displayed_line)
123 #define width (G.width )
124 #define winch_counter (G.winch_counter )
125 /* This one is 100% not cached by compiler on read access */
126 #define WINCH_COUNTER (*(volatile unsigned *)&winch_counter)
127 #define eof_error (G.eof_error )
128 #define readpos (G.readpos )
129 #define readeof (G.readeof )
130 #define buffer (G.buffer )
131 #define flines (G.flines )
132 #define empty_line_marker (G.empty_line_marker )
133 #define num_files (G.num_files )
134 #define current_file (G.current_file )
135 #define filename (G.filename )
136 #define files (G.files )
137 #define num_marks (G.num_marks )
138 #define mark_lines (G.mark_lines )
139 #if ENABLE_FEATURE_LESS_REGEXP
140 #define match_lines (G.match_lines )
141 #define match_pos (G.match_pos )
142 #define num_matches (G.num_matches )
143 #define wanted_match (G.wanted_match )
144 #define pattern (G.pattern )
145 #define pattern_valid (G.pattern_valid )
147 #define terminated (G.terminated )
148 #define term_orig (G.term_orig )
149 #define term_less (G.term_less )
150 #define kbd_input (G.kbd_input )
151 #define INIT_G() do { \
152 SET_PTR_TO_GLOBALS(xzalloc(sizeof(G))); \
153 less_gets_pos = -1; \
154 empty_line_marker = "~"; \
159 IF_FEATURE_LESS_REGEXP(wanted_match = -1;) \
162 /* flines[] are lines read from stdin, each in malloc'ed buffer.
163 * Line numbers are stored as uint32_t prepended to each line.
164 * Pointer is adjusted so that flines[i] points directly past
165 * line number. Accesor: */
166 #define MEMPTR(p) ((char*)(p) - 4)
167 #define LINENO(p) (*(uint32_t*)((p) - 4))
170 /* Reset terminal input to normal */
171 static void set_tty_cooked(void)
174 tcsetattr(kbd_fd, TCSANOW, &term_orig);
177 /* Move the cursor to a position (x,y), where (0,0) is the
178 top-left corner of the console */
179 static void move_cursor(int line, int row)
181 printf(ESC"[%u;%uH", line, row);
184 static void clear_line(void)
186 printf(ESC"[%u;0H" CLEAR_2_EOL, max_displayed_line + 2);
189 static void print_hilite(const char *str)
191 printf(HIGHLIGHT"%s"NORMAL, str);
194 static void print_statusline(const char *str)
197 printf(HIGHLIGHT"%.*s"NORMAL, width - 1, str);
200 /* Exit the program gracefully */
201 static void less_exit(int code)
206 kill_myself_with_sig(- code); /* does not return */
210 #if (ENABLE_FEATURE_LESS_DASHCMD && ENABLE_FEATURE_LESS_LINENUMS) \
211 || ENABLE_FEATURE_LESS_WINCH
212 static void re_wrap(void)
218 int new_cur_fline = 0;
221 const char **old_flines = flines;
223 char **new_flines = NULL;
226 if (option_mask32 & FLAG_N)
239 if (*d == '\t') /* tab */
243 if (new_line_pos >= w) {
245 /* new line is full, create next one */
248 sz = (d - linebuf) + 1; /* + 1: NUL */
249 d = ((char*)xmalloc(sz + 4)) + 4;
251 memcpy(d, linebuf, sz);
252 new_flines = xrealloc_vector(new_flines, 8, dst_idx);
253 new_flines[dst_idx] = d;
255 if (new_line_pos < w) {
256 /* if we came here thru "goto next_new" */
257 if (src_idx > max_fline)
266 /* *d == NUL: old line ended, go to next old one */
267 free(MEMPTR(old_flines[src_idx]));
268 /* btw, convert cur_fline... */
269 if (cur_fline == src_idx)
270 new_cur_fline = dst_idx;
272 /* no more lines? finish last new line (and exit the loop) */
273 if (src_idx > max_fline)
275 s = old_flines[src_idx];
276 if (lineno != LINENO(s)) {
277 /* this is not a continuation line!
278 * create next _new_ line too */
284 flines = (const char **)new_flines;
286 max_fline = dst_idx - 1;
287 last_line_pos = new_line_pos;
288 cur_fline = new_cur_fline;
289 /* max_lineno is screen-size independent */
290 #if ENABLE_FEATURE_LESS_REGEXP
296 #if ENABLE_FEATURE_LESS_REGEXP
297 static void fill_match_lines(unsigned pos);
299 #define fill_match_lines(pos) ((void)0)
302 /* Devilishly complex routine.
304 * Has to deal with EOF and EPIPE on input,
305 * with line wrapping, with last line not ending in '\n'
306 * (possibly not ending YET!), with backspace and tabs.
307 * It reads input again if last time we got an EOF (thus supporting
308 * growing files) or EPIPE (watching output of slow process like make).
311 * flines[] - array of lines already read. Linewrap may cause
312 * one source file line to occupy several flines[n].
313 * flines[max_fline] - last line, possibly incomplete.
314 * terminated - 1 if flines[max_fline] is 'terminated'
315 * (if there was '\n' [which isn't stored itself, we just remember
317 * max_lineno - last line's number, this one doesn't increment
318 * on line wrap, only on "real" new lines.
319 * readbuf[0..readeof-1] - small preliminary buffer.
320 * readbuf[readpos] - next character to add to current line.
321 * last_line_pos - screen line position of next char to be read
322 * (takes into account tabs and backspaces)
323 * eof_error - < 0 error, == 0 EOF, > 0 not EOF/error
325 static void read_lines(void)
327 #define readbuf bb_common_bufsiz1
328 char *current_line, *p;
330 char last_terminated = terminated;
331 #if ENABLE_FEATURE_LESS_REGEXP
332 unsigned old_max_fline = max_fline;
333 time_t last_time = 0;
334 unsigned seconds_p1 = 3; /* seconds_to_loop + 1 */
337 if (option_mask32 & FLAG_N)
340 IF_FEATURE_LESS_REGEXP(again0:)
342 p = current_line = ((char*)xmalloc(w + 4)) + 4;
343 max_fline += last_terminated;
344 if (!last_terminated) {
345 const char *cp = flines[max_fline];
347 p += strlen(current_line);
348 free(MEMPTR(flines[max_fline]));
349 /* last_line_pos is still valid from previous read_lines() */
354 while (1) { /* read lines until we reach cur_fline or wanted_match */
357 while (1) { /* read chars until we have a line */
359 /* if no unprocessed chars left, eat more */
360 if (readpos >= readeof) {
362 eof_error = safe_read(STDIN_FILENO, readbuf, sizeof(readbuf));
369 c = readbuf[readpos];
370 /* backspace? [needed for manpages] */
371 /* <tab><bs> is (a) insane and */
372 /* (b) harder to do correctly, so we refuse to do it */
373 if (c == '\x8' && last_line_pos && p[-1] != '\t') {
374 readpos++; /* eat it */
376 /* was buggy (p could end up <= current_line)... */
381 size_t new_last_line_pos = last_line_pos + 1;
383 new_last_line_pos += 7;
384 new_last_line_pos &= (~7);
386 if ((int)new_last_line_pos >= w)
388 last_line_pos = new_last_line_pos;
390 /* ok, we will eat this char */
397 /* NUL is substituted by '\n'! */
398 if (c == '\0') c = '\n';
401 } /* end of "read chars until we have a line" loop */
402 /* Corner case: linewrap with only "" wrapping to next line */
403 /* Looks ugly on screen, so we do not store this empty line */
404 if (!last_terminated && !current_line[0]) {
410 last_terminated = terminated;
411 flines = xrealloc_vector(flines, 8, max_fline);
413 flines[max_fline] = (char*)xrealloc(MEMPTR(current_line), strlen(current_line) + 1 + 4) + 4;
414 LINENO(flines[max_fline]) = max_lineno;
418 if (max_fline >= MAXLINES) {
419 eof_error = 0; /* Pretend we saw EOF */
422 if (!(option_mask32 & FLAG_S)
423 ? (max_fline > cur_fline + max_displayed_line)
424 : (max_fline >= cur_fline
425 && max_lineno > LINENO(flines[cur_fline]) + max_displayed_line)
427 #if !ENABLE_FEATURE_LESS_REGEXP
430 if (wanted_match >= num_matches) { /* goto_match called us */
431 fill_match_lines(old_max_fline);
432 old_max_fline = max_fline;
434 if (wanted_match < num_matches)
438 if (eof_error <= 0) {
440 if (errno == EAGAIN) {
441 /* not yet eof or error, reset flag (or else
442 * we will hog CPU - select() will return
446 print_statusline(bb_msg_read_error);
449 #if !ENABLE_FEATURE_LESS_REGEXP
452 if (wanted_match < num_matches) {
454 } else { /* goto_match called us */
455 time_t t = time(NULL);
456 if (t != last_time) {
458 if (--seconds_p1 == 0)
462 goto again0; /* go loop again (max 2 seconds) */
467 current_line = ((char*)xmalloc(w + 4)) + 4;
470 } /* end of "read lines until we reach cur_fline" loop */
471 fill_match_lines(old_max_fline);
472 #if ENABLE_FEATURE_LESS_REGEXP
473 /* prevent us from being stuck in search for a match */
479 #if ENABLE_FEATURE_LESS_FLAGS
480 /* Interestingly, writing calc_percent as a function saves around 32 bytes
482 static int calc_percent(void)
484 unsigned p = (100 * (cur_fline+max_displayed_line+1) + max_fline/2) / (max_fline+1);
485 return p <= 100 ? p : 100;
488 /* Print a status line if -M was specified */
489 static void m_status_print(void)
493 if (less_gets_pos >= 0) /* don't touch statusline while input is done! */
497 printf(HIGHLIGHT"%s", filename);
499 printf(" (file %i of %i)", current_file, num_files);
500 printf(" lines %i-%i/%i ",
501 cur_fline + 1, cur_fline + max_displayed_line + 1,
503 if (cur_fline >= (int)(max_fline - max_displayed_line)) {
504 printf("(END)"NORMAL);
505 if (num_files > 1 && current_file != num_files)
506 printf(HIGHLIGHT" - next: %s"NORMAL, files[current_file]);
509 percentage = calc_percent();
510 printf("%i%%"NORMAL, percentage);
514 /* Print the status line */
515 static void status_print(void)
519 if (less_gets_pos >= 0) /* don't touch statusline while input is done! */
522 /* Change the status if flags have been set */
523 #if ENABLE_FEATURE_LESS_FLAGS
524 if (option_mask32 & (FLAG_M|FLAG_m)) {
532 if (cur_fline && cur_fline < (int)(max_fline - max_displayed_line)) {
540 printf(HIGHLIGHT"%s (file %i of %i)"NORMAL,
541 p, current_file, num_files);
547 static void cap_cur_fline(int nlines)
552 if (cur_fline + max_displayed_line > max_fline + TILDES) {
556 diff = max_fline - (cur_fline + max_displayed_line) + TILDES;
557 /* As the number of lines requested was too large, we just move
558 * to the end of the file */
564 static const char controls[] ALIGN1 =
565 /* NUL: never encountered; TAB: not converted */
566 /**/"\x01\x02\x03\x04\x05\x06\x07\x08" "\x0a\x0b\x0c\x0d\x0e\x0f"
567 "\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1a\x1b\x1c\x1d\x1e\x1f"
568 "\x7f\x9b"; /* DEL and infamous Meta-ESC :( */
569 static const char ctrlconv[] ALIGN1 =
570 /* why 40 instead of 4a below? - it is a replacement for '\n'.
571 * '\n' is a former NUL - we subst it with @, not J */
572 "\x40\x41\x42\x43\x44\x45\x46\x47\x48\x49\x40\x4b\x4c\x4d\x4e\x4f"
573 "\x50\x51\x52\x53\x54\x55\x56\x57\x58\x59\x5a\x5b\x5c\x5d\x5e\x5f";
575 static void lineno_str(char *nbuf9, const char *line)
578 if (option_mask32 & FLAG_N) {
582 if (line == empty_line_marker) {
583 memset(nbuf9, ' ', 8);
587 /* Width of 7 preserves tab spacing in the text */
589 n = LINENO(line) + 1;
594 sprintf(nbuf9, fmt, n);
599 #if ENABLE_FEATURE_LESS_REGEXP
600 static void print_found(const char *line)
605 regmatch_t match_structs;
609 const char *str = line;
614 n = strcspn(str, controls);
621 n = strspn(str, controls);
628 /* buf[] holds quarantined version of str */
630 /* Each part of the line that matches has the HIGHLIGHT
631 and NORMAL escape sequences placed around it.
632 NB: we regex against line, but insert text
633 from quarantined copy (buf[]) */
639 while (match_status == 0) {
640 char *new = xasprintf("%s%.*s"HIGHLIGHT"%.*s"NORMAL,
641 growline ? growline : "",
642 match_structs.rm_so, str,
643 match_structs.rm_eo - match_structs.rm_so,
644 str + match_structs.rm_so);
647 str += match_structs.rm_eo;
648 line += match_structs.rm_eo;
651 /* Most of the time doesn't find the regex, optimize for that */
652 match_status = regexec(&pattern, line, 1, &match_structs, eflags);
653 /* if even "" matches, treat it as "not a match" */
654 if (match_structs.rm_so >= match_structs.rm_eo)
658 lineno_str(nbuf9, line);
660 printf(CLEAR_2_EOL"%s%s\n", nbuf9, str);
663 printf(CLEAR_2_EOL"%s%s%s\n", nbuf9, growline, str);
667 void print_found(const char *line);
670 static void print_ascii(const char *str)
677 lineno_str(nbuf9, str);
678 printf(CLEAR_2_EOL"%s", nbuf9);
681 n = strcspn(str, controls);
684 printf("%.*s", (int) n, str);
687 n = strspn(str, controls);
692 else if (*str == (char)0x9b)
693 /* VT100's CSI, aka Meta-ESC. Who's inventor? */
694 /* I want to know who committed this sin */
697 *p++ = ctrlconv[(unsigned char)*str];
706 /* Print the buffer */
707 static void buffer_print(void)
712 for (i = 0; i <= max_displayed_line; i++)
714 print_found(buffer[i]);
716 print_ascii(buffer[i]);
720 static void buffer_fill_and_print(void)
723 #if ENABLE_FEATURE_LESS_DASHCMD
724 int fpos = cur_fline;
726 if (option_mask32 & FLAG_S) {
727 /* Go back to the beginning of this line */
728 while (fpos && LINENO(flines[fpos]) == LINENO(flines[fpos-1]))
733 while (i <= max_displayed_line && fpos <= max_fline) {
734 int lineno = LINENO(flines[fpos]);
735 buffer[i] = flines[fpos];
739 } while ((fpos <= max_fline)
740 && (option_mask32 & FLAG_S)
741 && lineno == LINENO(flines[fpos])
745 for (i = 0; i <= max_displayed_line && cur_fline + i <= max_fline; i++) {
746 buffer[i] = flines[cur_fline + i];
749 for (; i <= max_displayed_line; i++) {
750 buffer[i] = empty_line_marker;
755 /* Move the buffer up and down in the file in order to scroll */
756 static void buffer_down(int nlines)
760 cap_cur_fline(nlines);
761 buffer_fill_and_print();
764 static void buffer_up(int nlines)
767 if (cur_fline < 0) cur_fline = 0;
769 buffer_fill_and_print();
772 static void buffer_line(int linenum)
778 if (linenum + max_displayed_line > max_fline)
779 linenum = max_fline - max_displayed_line + TILDES;
783 buffer_fill_and_print();
786 static void open_file_and_read_lines(void)
789 xmove_fd(xopen(filename, O_RDONLY), STDIN_FILENO);
791 /* "less" with no arguments in argv[] */
792 /* For status line only */
793 filename = xstrdup(bb_msg_standard_input);
802 /* Reinitialize everything for a new file - free the memory and start over */
803 static void reinitialize(void)
808 for (i = 0; i <= max_fline; i++)
809 free(MEMPTR(flines[i]));
817 open_file_and_read_lines();
818 buffer_fill_and_print();
821 static int getch_nowait(void)
824 struct pollfd pfd[2];
826 pfd[0].fd = STDIN_FILENO;
827 pfd[0].events = POLLIN;
829 pfd[1].events = POLLIN;
831 tcsetattr(kbd_fd, TCSANOW, &term_less);
832 /* NB: select/poll returns whenever read will not block. Therefore:
833 * if eof is reached, select/poll will return immediately
834 * because read will immediately return 0 bytes.
835 * Even if select/poll says that input is available, read CAN block
836 * (switch fd into O_NONBLOCK'ed mode to avoid it)
839 /* Are we interested in stdin? */
840 //TODO: reuse code for determining this
841 if (!(option_mask32 & FLAG_S)
842 ? !(max_fline > cur_fline + max_displayed_line)
843 : !(max_fline >= cur_fline
844 && max_lineno > LINENO(flines[cur_fline]) + max_displayed_line)
846 if (eof_error > 0) /* did NOT reach eof yet */
847 rd = 0; /* yes, we are interested in stdin */
849 /* Position cursor if line input is done */
850 if (less_gets_pos >= 0)
851 move_cursor(max_displayed_line + 2, less_gets_pos + 1);
854 if (kbd_input[0] == 0) { /* if nothing is buffered */
855 #if ENABLE_FEATURE_LESS_WINCH
858 /* NB: SIGWINCH interrupts poll() */
859 r = poll(pfd + rd, 2 - rd, -1);
860 if (/*r < 0 && errno == EINTR &&*/ winch_counter)
861 return '\\'; /* anything which has no defined function */
865 safe_poll(pfd + rd, 2 - rd, -1);
869 /* We have kbd_fd in O_NONBLOCK mode, read inside read_key()
870 * would not block even if there is no input available */
871 rd = read_key(kbd_fd, kbd_input, /*timeout off:*/ -2);
873 if (errno == EAGAIN) {
874 /* No keyboard input available. Since poll() did return,
875 * we should have input on stdin */
877 buffer_fill_and_print();
880 /* EOF/error (ssh session got killed etc) */
887 /* Grab a character from input without requiring the return key.
888 * May return KEYCODE_xxx values.
889 * Note that this function works best with raw input. */
890 static int less_getch(int pos)
899 /* Discard Ctrl-something chars */
900 if (i >= 0 && i < ' ' && i != 0x0d && i != 8)
905 static char* less_gets(int sz)
909 char *result = xzalloc(1);
913 less_gets_pos = sz + i;
926 if (c < ' ') /* filters out KEYCODE_xxx too (<0) */
928 if (i >= width - sz - 1)
929 continue; /* len limit */
932 result = xrealloc(result, i+1);
936 static void examine_file(void)
940 print_statusline("Examine: ");
941 new_fname = less_gets(sizeof("Examine: ") - 1);
948 if (access(new_fname, R_OK) != 0) {
949 print_statusline("Cannot read this file");
953 filename = new_fname;
954 /* files start by = argv. why we assume that argv is infinitely long??
955 files[num_files] = filename;
956 current_file = num_files + 1;
959 num_files = current_file = 1;
963 /* This function changes the file currently being paged. direction can be one of the following:
964 * -1: go back one file
965 * 0: go to the first file
966 * 1: go forward one file */
967 static void change_file(int direction)
969 if (current_file != ((direction > 0) ? num_files : 1)) {
970 current_file = direction ? current_file + direction : 1;
972 filename = xstrdup(files[current_file - 1]);
975 print_statusline(direction > 0 ? "No next file" : "No previous file");
979 static void remove_current_file(void)
986 if (current_file != 1) {
988 for (i = 3; i <= num_files; i++)
989 files[i - 2] = files[i - 1];
993 for (i = 2; i <= num_files; i++)
994 files[i - 2] = files[i - 1];
1000 static void colon_process(void)
1004 /* Clear the current line and print a prompt */
1005 print_statusline(" :");
1007 keypress = less_getch(2);
1010 remove_current_file();
1015 #if ENABLE_FEATURE_LESS_FLAGS
1027 less_exit(EXIT_SUCCESS);
1035 #if ENABLE_FEATURE_LESS_REGEXP
1036 static void normalize_match_pos(int match)
1038 if (match >= num_matches)
1039 match = num_matches - 1;
1045 static void goto_match(int match)
1051 /* Try to find next match if eof isn't reached yet */
1052 if (match >= num_matches && eof_error > 0) {
1053 wanted_match = match; /* "I want to read until I see N'th match" */
1057 normalize_match_pos(match);
1058 buffer_line(match_lines[match_pos]);
1060 print_statusline("No matches found");
1064 static void fill_match_lines(unsigned pos)
1068 /* Run the regex on each line of the current file */
1069 while (pos <= max_fline) {
1070 /* If this line matches */
1071 if (regexec(&pattern, flines[pos], 0, NULL, 0) == 0
1072 /* and we didn't match it last time */
1073 && !(num_matches && match_lines[num_matches-1] == pos)
1075 match_lines = xrealloc_vector(match_lines, 4, num_matches);
1076 match_lines[num_matches++] = pos;
1082 static void regex_process(void)
1084 char *uncomp_regex, *err;
1086 /* Reset variables */
1091 if (pattern_valid) {
1096 /* Get the uncompiled regular expression from the user */
1098 bb_putchar((option_mask32 & LESS_STATE_MATCH_BACKWARDS) ? '?' : '/');
1099 uncomp_regex = less_gets(1);
1100 if (!uncomp_regex[0]) {
1106 /* Compile the regex and check for errors */
1107 err = regcomp_or_errmsg(&pattern, uncomp_regex,
1108 (option_mask32 & FLAG_I) ? REG_ICASE : 0);
1111 print_statusline(err);
1118 fill_match_lines(0);
1119 while (match_pos < num_matches) {
1120 if ((int)match_lines[match_pos] > cur_fline)
1124 if (option_mask32 & LESS_STATE_MATCH_BACKWARDS)
1127 /* It's possible that no matches are found yet.
1128 * goto_match() will read input looking for match,
1130 goto_match(match_pos);
1134 static void number_process(int first_digit)
1139 char num_input[sizeof(int)*4]; /* more than enough */
1141 num_input[0] = first_digit;
1143 /* Clear the current line, print a prompt, and then print the digit */
1145 printf(":%c", first_digit);
1147 /* Receive input until a letter is given */
1149 while (i < sizeof(num_input)-1) {
1150 keypress = less_getch(i + 1);
1151 if ((unsigned)keypress > 255 || !isdigit(num_input[i]))
1153 num_input[i] = keypress;
1154 bb_putchar(keypress);
1158 num_input[i] = '\0';
1159 num = bb_strtou(num_input, NULL, 10);
1160 /* on format error, num == -1 */
1161 if (num < 1 || num > MAXLINES) {
1166 /* We now know the number and the letter entered, so we process them */
1168 case KEYCODE_DOWN: case 'z': case 'd': case 'e': case ' ': case '\015':
1171 case KEYCODE_UP: case 'b': case 'w': case 'y': case 'u':
1174 case 'g': case '<': case 'G': case '>':
1175 cur_fline = num + max_displayed_line;
1177 buffer_line(num - 1);
1180 num = num * (max_fline / 100); /* + max_fline / 2; */
1181 cur_fline = num + max_displayed_line;
1185 #if ENABLE_FEATURE_LESS_REGEXP
1187 goto_match(match_pos + num);
1190 option_mask32 &= ~LESS_STATE_MATCH_BACKWARDS;
1194 option_mask32 |= LESS_STATE_MATCH_BACKWARDS;
1201 #if ENABLE_FEATURE_LESS_DASHCMD
1202 static void flag_change(void)
1208 keypress = less_getch(1);
1212 option_mask32 ^= FLAG_M;
1215 option_mask32 ^= FLAG_m;
1218 option_mask32 ^= FLAG_E;
1221 option_mask32 ^= FLAG_TILDE;
1224 option_mask32 ^= FLAG_S;
1225 buffer_fill_and_print();
1227 #if ENABLE_FEATURE_LESS_LINENUMS
1229 option_mask32 ^= FLAG_N;
1231 buffer_fill_and_print();
1238 static void show_flag_status(void)
1245 keypress = less_getch(1);
1249 flag_val = option_mask32 & FLAG_M;
1252 flag_val = option_mask32 & FLAG_m;
1255 flag_val = option_mask32 & FLAG_TILDE;
1258 flag_val = option_mask32 & FLAG_N;
1261 flag_val = option_mask32 & FLAG_E;
1269 printf(HIGHLIGHT"The status of the flag is: %u"NORMAL, flag_val != 0);
1273 #endif /* ENABLE_FEATURE_LESS_DASHCMD */
1275 static void save_input_to_file(void)
1277 const char *msg = "";
1282 print_statusline("Log file: ");
1283 current_line = less_gets(sizeof("Log file: ")-1);
1284 if (current_line[0]) {
1285 fp = fopen_for_write(current_line);
1287 msg = "Error opening log file";
1290 for (i = 0; i <= max_fline; i++)
1291 fprintf(fp, "%s\n", flines[i]);
1296 print_statusline(msg);
1300 #if ENABLE_FEATURE_LESS_MARKS
1301 static void add_mark(void)
1305 print_statusline("Mark: ");
1306 letter = less_getch(sizeof("Mark: ") - 1);
1308 if (isalpha(letter)) {
1309 /* If we exceed 15 marks, start overwriting previous ones */
1310 if (num_marks == 14)
1313 mark_lines[num_marks][0] = letter;
1314 mark_lines[num_marks][1] = cur_fline;
1317 print_statusline("Invalid mark letter");
1321 static void goto_mark(void)
1326 print_statusline("Go to mark: ");
1327 letter = less_getch(sizeof("Go to mark: ") - 1);
1330 if (isalpha(letter)) {
1331 for (i = 0; i <= num_marks; i++)
1332 if (letter == mark_lines[i][0]) {
1333 buffer_line(mark_lines[i][1]);
1336 if (num_marks == 14 && letter != mark_lines[14][0])
1337 print_statusline("Mark not set");
1339 print_statusline("Invalid mark letter");
1343 #if ENABLE_FEATURE_LESS_BRACKETS
1344 static char opp_bracket(char bracket)
1347 case '{': case '[': /* '}' == '{' + 2. Same for '[' */
1349 case '(': /* ')' == '(' + 1 */
1361 static void match_right_bracket(char bracket)
1365 if (strchr(flines[cur_fline], bracket) == NULL) {
1366 print_statusline("No bracket in top line");
1369 bracket = opp_bracket(bracket);
1370 for (i = cur_fline + 1; i < max_fline; i++) {
1371 if (strchr(flines[i], bracket) != NULL) {
1376 print_statusline("No matching bracket found");
1379 static void match_left_bracket(char bracket)
1383 if (strchr(flines[cur_fline + max_displayed_line], bracket) == NULL) {
1384 print_statusline("No bracket in bottom line");
1388 bracket = opp_bracket(bracket);
1389 for (i = cur_fline + max_displayed_line; i >= 0; i--) {
1390 if (strchr(flines[i], bracket) != NULL) {
1395 print_statusline("No matching bracket found");
1397 #endif /* FEATURE_LESS_BRACKETS */
1399 static void keypress_process(int keypress)
1402 case KEYCODE_DOWN: case 'e': case 'j': case 0x0d:
1405 case KEYCODE_UP: case 'y': case 'k':
1408 case KEYCODE_PAGEDOWN: case ' ': case 'z': case 'f':
1409 buffer_down(max_displayed_line + 1);
1411 case KEYCODE_PAGEUP: case 'w': case 'b':
1412 buffer_up(max_displayed_line + 1);
1415 buffer_down((max_displayed_line + 1) / 2);
1418 buffer_up((max_displayed_line + 1) / 2);
1420 case KEYCODE_HOME: case 'g': case 'p': case '<': case '%':
1423 case KEYCODE_END: case 'G': case '>':
1424 cur_fline = MAXLINES;
1426 buffer_line(cur_fline);
1429 less_exit(EXIT_SUCCESS);
1431 #if ENABLE_FEATURE_LESS_MARKS
1448 save_input_to_file();
1453 #if ENABLE_FEATURE_LESS_FLAGS
1458 #if ENABLE_FEATURE_LESS_REGEXP
1460 option_mask32 &= ~LESS_STATE_MATCH_BACKWARDS;
1464 goto_match(match_pos + 1);
1467 goto_match(match_pos - 1);
1470 option_mask32 |= LESS_STATE_MATCH_BACKWARDS;
1474 #if ENABLE_FEATURE_LESS_DASHCMD
1485 #if ENABLE_FEATURE_LESS_BRACKETS
1486 case '{': case '(': case '[':
1487 match_right_bracket(keypress);
1489 case '}': case ')': case ']':
1490 match_left_bracket(keypress);
1498 if (isdigit(keypress))
1499 number_process(keypress);
1502 static void sig_catcher(int sig)
1507 #if ENABLE_FEATURE_LESS_WINCH
1508 static void sigwinch_handler(int sig UNUSED_PARAM)
1514 int less_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
1515 int less_main(int argc, char **argv)
1521 /* TODO: -x: do not interpret backspace, -xx: tab also */
1522 /* -xxx: newline also */
1523 /* -w N: assume width N (-xxx -w 32: hex viewer of sorts) */
1524 getopt32(argv, "EMmN~I" IF_FEATURE_LESS_DASHCMD("S"));
1530 /* Another popular pager, most, detects when stdout
1531 * is not a tty and turns into cat. This makes sense. */
1532 if (!isatty(STDOUT_FILENO))
1533 return bb_cat(argv);
1536 if (isatty(STDIN_FILENO)) {
1537 /* Just "less"? No args and no redirection? */
1538 bb_error_msg("missing filename");
1542 filename = xstrdup(files[0]);
1545 if (option_mask32 & FLAG_TILDE)
1546 empty_line_marker = "";
1548 kbd_fd = open(CURRENT_TTY, O_RDONLY);
1550 return bb_cat(argv);
1553 tcgetattr(kbd_fd, &term_orig);
1554 term_less = term_orig;
1555 term_less.c_lflag &= ~(ICANON | ECHO);
1556 term_less.c_iflag &= ~(IXON | ICRNL);
1557 /*term_less.c_oflag &= ~ONLCR;*/
1558 term_less.c_cc[VMIN] = 1;
1559 term_less.c_cc[VTIME] = 0;
1561 get_terminal_width_height(kbd_fd, &width, &max_displayed_line);
1562 /* 20: two tabstops + 4 */
1563 if (width < 20 || max_displayed_line < 3)
1564 return bb_cat(argv);
1565 max_displayed_line -= 2;
1567 /* We want to restore term_orig on exit */
1568 bb_signals(BB_FATAL_SIGS, sig_catcher);
1569 #if ENABLE_FEATURE_LESS_WINCH
1570 signal(SIGWINCH, sigwinch_handler);
1573 buffer = xmalloc((max_displayed_line+1) * sizeof(char *));
1576 #if ENABLE_FEATURE_LESS_WINCH
1577 while (WINCH_COUNTER) {
1580 get_terminal_width_height(kbd_fd, &width, &max_displayed_line);
1581 /* 20: two tabstops + 4 */
1584 if (max_displayed_line < 3)
1585 max_displayed_line = 3;
1586 max_displayed_line -= 2;
1588 buffer = xmalloc((max_displayed_line+1) * sizeof(char *));
1589 /* Avoid re-wrap and/or redraw if we already know
1590 * we need to do it again. These ops are expensive */
1596 buffer_fill_and_print();
1597 /* This took some time. Loop back and check,
1598 * were there another SIGWINCH? */
1601 keypress = less_getch(-1); /* -1: do not position cursor */
1602 keypress_process(keypress);
1607 Help text of less version 418 is below.
1608 If you are implementing something, keeping
1609 key and/or command line switch compatibility is a good idea:
1612 SUMMARY OF LESS COMMANDS
1614 Commands marked with * may be preceded by a number, N.
1615 Notes in parentheses indicate the behavior if N is given.
1616 h H Display this help.
1618 ---------------------------------------------------------------------------
1620 e ^E j ^N CR * Forward one line (or N lines).
1621 y ^Y k ^K ^P * Backward one line (or N lines).
1622 f ^F ^V SPACE * Forward one window (or N lines).
1623 b ^B ESC-v * Backward one window (or N lines).
1624 z * Forward one window (and set window to N).
1625 w * Backward one window (and set window to N).
1626 ESC-SPACE * Forward one window, but don't stop at end-of-file.
1627 d ^D * Forward one half-window (and set half-window to N).
1628 u ^U * Backward one half-window (and set half-window to N).
1629 ESC-) RightArrow * Left one half screen width (or N positions).
1630 ESC-( LeftArrow * Right one half screen width (or N positions).
1631 F Forward forever; like "tail -f".
1632 r ^R ^L Repaint screen.
1633 R Repaint screen, discarding buffered input.
1634 ---------------------------------------------------
1635 Default "window" is the screen height.
1636 Default "half-window" is half of the screen height.
1637 ---------------------------------------------------------------------------
1639 /pattern * Search forward for (N-th) matching line.
1640 ?pattern * Search backward for (N-th) matching line.
1641 n * Repeat previous search (for N-th occurrence).
1642 N * Repeat previous search in reverse direction.
1643 ESC-n * Repeat previous search, spanning files.
1644 ESC-N * Repeat previous search, reverse dir. & spanning files.
1645 ESC-u Undo (toggle) search highlighting.
1646 ---------------------------------------------------
1647 Search patterns may be modified by one or more of:
1648 ^N or ! Search for NON-matching lines.
1649 ^E or * Search multiple files (pass thru END OF FILE).
1650 ^F or @ Start search at FIRST file (for /) or last file (for ?).
1651 ^K Highlight matches, but don't move (KEEP position).
1652 ^R Don't use REGULAR EXPRESSIONS.
1653 ---------------------------------------------------------------------------
1655 g < ESC-< * Go to first line in file (or line N).
1656 G > ESC-> * Go to last line in file (or line N).
1657 p % * Go to beginning of file (or N percent into file).
1658 t * Go to the (N-th) next tag.
1659 T * Go to the (N-th) previous tag.
1660 { ( [ * Find close bracket } ) ].
1661 } ) ] * Find open bracket { ( [.
1662 ESC-^F <c1> <c2> * Find close bracket <c2>.
1663 ESC-^B <c1> <c2> * Find open bracket <c1>
1664 ---------------------------------------------------
1665 Each "find close bracket" command goes forward to the close bracket
1666 matching the (N-th) open bracket in the top line.
1667 Each "find open bracket" command goes backward to the open bracket
1668 matching the (N-th) close bracket in the bottom line.
1669 m<letter> Mark the current position with <letter>.
1670 '<letter> Go to a previously marked position.
1671 '' Go to the previous position.
1673 ---------------------------------------------------
1674 A mark is any upper-case or lower-case letter.
1675 Certain marks are predefined:
1676 ^ means beginning of the file
1677 $ means end of the file
1678 ---------------------------------------------------------------------------
1680 :e [file] Examine a new file.
1682 :n * Examine the (N-th) next file from the command line.
1683 :p * Examine the (N-th) previous file from the command line.
1684 :x * Examine the first (or N-th) file from the command line.
1685 :d Delete the current file from the command line list.
1686 = ^G :f Print current file name.
1687 ---------------------------------------------------------------------------
1688 MISCELLANEOUS COMMANDS
1689 -<flag> Toggle a command line option [see OPTIONS below].
1690 --<name> Toggle a command line option, by name.
1691 _<flag> Display the setting of a command line option.
1692 __<name> Display the setting of an option, by name.
1693 +cmd Execute the less cmd each time a new file is examined.
1694 !command Execute the shell command with $SHELL.
1695 |Xcommand Pipe file between current pos & mark X to shell command.
1696 v Edit the current file with $VISUAL or $EDITOR.
1697 V Print version number of "less".
1698 ---------------------------------------------------------------------------
1700 Most options may be changed either on the command line,
1701 or from within less by using the - or -- command.
1702 Options may be given in one of two forms: either a single
1703 character preceded by a -, or a name preceeded by --.
1705 Display help (from command line).
1706 -a ........ --search-skip-screen
1707 Forward search skips current screen.
1708 -b [N] .... --buffers=[N]
1710 -B ........ --auto-buffers
1711 Don't automatically allocate buffers for pipes.
1712 -c ........ --clear-screen
1713 Repaint by clearing rather than scrolling.
1716 -D [xn.n] . --color=xn.n
1717 Set screen colors. (MS-DOS only)
1718 -e -E .... --quit-at-eof --QUIT-AT-EOF
1719 Quit at end of file.
1721 Force open non-regular files.
1722 -F ........ --quit-if-one-screen
1723 Quit if entire file fits on first screen.
1724 -g ........ --hilite-search
1725 Highlight only last match for searches.
1726 -G ........ --HILITE-SEARCH
1727 Don't highlight any matches for searches.
1728 -h [N] .... --max-back-scroll=[N]
1729 Backward scroll limit.
1730 -i ........ --ignore-case
1731 Ignore case in searches that do not contain uppercase.
1732 -I ........ --IGNORE-CASE
1733 Ignore case in all searches.
1734 -j [N] .... --jump-target=[N]
1735 Screen position of target lines.
1736 -J ........ --status-column
1737 Display a status column at left edge of screen.
1738 -k [file] . --lesskey-file=[file]
1740 -L ........ --no-lessopen
1741 Ignore the LESSOPEN environment variable.
1742 -m -M .... --long-prompt --LONG-PROMPT
1744 -n -N .... --line-numbers --LINE-NUMBERS
1745 Don't use line numbers.
1746 -o [file] . --log-file=[file]
1747 Copy to log file (standard input only).
1748 -O [file] . --LOG-FILE=[file]
1749 Copy to log file (unconditionally overwrite).
1750 -p [pattern] --pattern=[pattern]
1751 Start at pattern (from command line).
1752 -P [prompt] --prompt=[prompt]
1754 -q -Q .... --quiet --QUIET --silent --SILENT
1755 Quiet the terminal bell.
1756 -r -R .... --raw-control-chars --RAW-CONTROL-CHARS
1757 Output "raw" control characters.
1758 -s ........ --squeeze-blank-lines
1759 Squeeze multiple blank lines.
1760 -S ........ --chop-long-lines
1762 -t [tag] .. --tag=[tag]
1764 -T [tagsfile] --tag-file=[tagsfile]
1765 Use an alternate tags file.
1766 -u -U .... --underline-special --UNDERLINE-SPECIAL
1767 Change handling of backspaces.
1768 -V ........ --version
1769 Display the version number of "less".
1770 -w ........ --hilite-unread
1771 Highlight first new line after forward-screen.
1772 -W ........ --HILITE-UNREAD
1773 Highlight first new line after any forward movement.
1774 -x [N[,...]] --tabs=[N[,...]]
1776 -X ........ --no-init
1777 Don't use termcap init/deinit strings.
1779 Don't use termcap keypad init/deinit strings.
1780 -y [N] .... --max-forw-scroll=[N]
1781 Forward scroll limit.
1782 -z [N] .... --window=[N]
1784 -" [c[c]] . --quotes=[c[c]]
1785 Set shell quote characters.
1787 Don't display tildes after end of file.
1788 -# [N] .... --shift=[N]
1789 Horizontal scroll amount (0 = one half screen width)
1791 ---------------------------------------------------------------------------
1793 These keys can be used to edit text being entered
1794 on the "command line" at the bottom of the screen.
1795 RightArrow ESC-l Move cursor right one character.
1796 LeftArrow ESC-h Move cursor left one character.
1797 CNTL-RightArrow ESC-RightArrow ESC-w Move cursor right one word.
1798 CNTL-LeftArrow ESC-LeftArrow ESC-b Move cursor left one word.
1799 HOME ESC-0 Move cursor to start of line.
1800 END ESC-$ Move cursor to end of line.
1801 BACKSPACE Delete char to left of cursor.
1802 DELETE ESC-x Delete char under cursor.
1803 CNTL-BACKSPACE ESC-BACKSPACE Delete word to left of cursor.
1804 CNTL-DELETE ESC-DELETE ESC-X Delete word under cursor.
1805 CNTL-U ESC (MS-DOS only) Delete entire line.
1806 UpArrow ESC-k Retrieve previous command line.
1807 DownArrow ESC-j Retrieve next command line.
1808 TAB Complete filename & cycle.
1809 SHIFT-TAB ESC-TAB Complete filename & reverse cycle.
1810 CNTL-L Complete filename, list all.