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 the GPL v2 or later, see the file LICENSE in this tarball.
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 #include <sched.h> /* sched_yield() */
27 #if ENABLE_FEATURE_LESS_REGEXP
31 /* The escape codes for highlighted and normal text */
32 #define HIGHLIGHT "\033[7m"
33 #define NORMAL "\033[0m"
34 /* The escape code to clear the screen */
35 #define CLEAR "\033[H\033[J"
36 /* The escape code to clear to end of line */
37 #define CLEAR_2_EOL "\033[K"
40 /* Absolute max of lines eaten */
41 MAXLINES = CONFIG_FEATURE_LESS_MAXLINES,
42 /* This many "after the end" lines we will show (at max) */
46 /* Command line options */
54 FLAG_S = (1 << 6) * ENABLE_FEATURE_LESS_DASHCMD,
55 /* hijack command line options variable for internal state vars */
56 LESS_STATE_MATCH_BACKWARDS = 1 << 15,
59 #if !ENABLE_FEATURE_LESS_REGEXP
60 enum { pattern_valid = 0 };
64 int cur_fline; /* signed */
65 int kbd_fd; /* fd to get input from */
67 /* last position in last line, taking into account tabs */
70 unsigned max_lineno; /* this one tracks linewrap */
71 unsigned max_displayed_line;
73 #if ENABLE_FEATURE_LESS_WINCH
74 unsigned winch_counter;
76 ssize_t eof_error; /* eof if 0, error if < 0 */
78 ssize_t readeof; /* must be signed */
81 const char *empty_line_marker;
83 unsigned current_file;
86 #if ENABLE_FEATURE_LESS_MARKS
88 unsigned mark_lines[15][2];
90 #if ENABLE_FEATURE_LESS_REGEXP
91 unsigned *match_lines;
92 int match_pos; /* signed! */
93 int wanted_match; /* signed! */
96 smallint pattern_valid;
99 struct termios term_orig, term_less;
101 #define G (*ptr_to_globals)
102 #define cur_fline (G.cur_fline )
103 #define kbd_fd (G.kbd_fd )
104 #define less_gets_pos (G.less_gets_pos )
105 #define last_line_pos (G.last_line_pos )
106 #define max_fline (G.max_fline )
107 #define max_lineno (G.max_lineno )
108 #define max_displayed_line (G.max_displayed_line)
109 #define width (G.width )
110 #define winch_counter (G.winch_counter )
111 /* This one is 100% not cached by compiler on read access */
112 #define WINCH_COUNTER (*(volatile unsigned *)&winch_counter)
113 #define eof_error (G.eof_error )
114 #define readpos (G.readpos )
115 #define readeof (G.readeof )
116 #define buffer (G.buffer )
117 #define flines (G.flines )
118 #define empty_line_marker (G.empty_line_marker )
119 #define num_files (G.num_files )
120 #define current_file (G.current_file )
121 #define filename (G.filename )
122 #define files (G.files )
123 #define num_marks (G.num_marks )
124 #define mark_lines (G.mark_lines )
125 #if ENABLE_FEATURE_LESS_REGEXP
126 #define match_lines (G.match_lines )
127 #define match_pos (G.match_pos )
128 #define num_matches (G.num_matches )
129 #define wanted_match (G.wanted_match )
130 #define pattern (G.pattern )
131 #define pattern_valid (G.pattern_valid )
133 #define terminated (G.terminated )
134 #define term_orig (G.term_orig )
135 #define term_less (G.term_less )
136 #define INIT_G() do { \
137 SET_PTR_TO_GLOBALS(xzalloc(sizeof(G))); \
138 less_gets_pos = -1; \
139 empty_line_marker = "~"; \
144 USE_FEATURE_LESS_REGEXP(wanted_match = -1;) \
147 /* flines[] are lines read from stdin, each in malloc'ed buffer.
148 * Line numbers are stored as uint32_t prepended to each line.
149 * Pointer is adjusted so that flines[i] points directly past
150 * line number. Accesor: */
151 #define MEMPTR(p) ((char*)(p) - 4)
152 #define LINENO(p) (*(uint32_t*)((p) - 4))
155 /* Reset terminal input to normal */
156 static void set_tty_cooked(void)
159 tcsetattr(kbd_fd, TCSANOW, &term_orig);
162 /* Move the cursor to a position (x,y), where (0,0) is the
163 top-left corner of the console */
164 static void move_cursor(int line, int row)
166 printf("\033[%u;%uH", line, row);
169 static void clear_line(void)
171 printf("\033[%u;0H" CLEAR_2_EOL, max_displayed_line + 2);
174 static void print_hilite(const char *str)
176 printf(HIGHLIGHT"%s"NORMAL, str);
179 static void print_statusline(const char *str)
182 printf(HIGHLIGHT"%.*s"NORMAL, width - 1, str);
185 /* Exit the program gracefully */
186 static void less_exit(int code)
191 kill_myself_with_sig(- code); /* does not return */
195 #if (ENABLE_FEATURE_LESS_DASHCMD && ENABLE_FEATURE_LESS_LINENUMS) \
196 || ENABLE_FEATURE_LESS_WINCH
197 static void re_wrap(void)
203 int new_cur_fline = 0;
206 const char **old_flines = flines;
208 char **new_flines = NULL;
211 if (option_mask32 & FLAG_N)
224 if (*d == '\t') /* tab */
228 if (new_line_pos >= w) {
230 /* new line is full, create next one */
233 sz = (d - linebuf) + 1; /* + 1: NUL */
234 d = ((char*)xmalloc(sz + 4)) + 4;
236 memcpy(d, linebuf, sz);
237 new_flines = xrealloc_vector(new_flines, 8, dst_idx);
238 new_flines[dst_idx] = d;
240 if (new_line_pos < w) {
241 /* if we came here thru "goto next_new" */
242 if (src_idx > max_fline)
251 /* *d == NUL: old line ended, go to next old one */
252 free(MEMPTR(old_flines[src_idx]));
253 /* btw, convert cur_fline... */
254 if (cur_fline == src_idx)
255 new_cur_fline = dst_idx;
257 /* no more lines? finish last new line (and exit the loop) */
258 if (src_idx > max_fline)
260 s = old_flines[src_idx];
261 if (lineno != LINENO(s)) {
262 /* this is not a continuation line!
263 * create next _new_ line too */
269 flines = (const char **)new_flines;
271 max_fline = dst_idx - 1;
272 last_line_pos = new_line_pos;
273 cur_fline = new_cur_fline;
274 /* max_lineno is screen-size independent */
275 #if ENABLE_FEATURE_LESS_REGEXP
281 #if ENABLE_FEATURE_LESS_REGEXP
282 static void fill_match_lines(unsigned pos);
284 #define fill_match_lines(pos) ((void)0)
287 /* Devilishly complex routine.
289 * Has to deal with EOF and EPIPE on input,
290 * with line wrapping, with last line not ending in '\n'
291 * (possibly not ending YET!), with backspace and tabs.
292 * It reads input again if last time we got an EOF (thus supporting
293 * growing files) or EPIPE (watching output of slow process like make).
296 * flines[] - array of lines already read. Linewrap may cause
297 * one source file line to occupy several flines[n].
298 * flines[max_fline] - last line, possibly incomplete.
299 * terminated - 1 if flines[max_fline] is 'terminated'
300 * (if there was '\n' [which isn't stored itself, we just remember
302 * max_lineno - last line's number, this one doesn't increment
303 * on line wrap, only on "real" new lines.
304 * readbuf[0..readeof-1] - small preliminary buffer.
305 * readbuf[readpos] - next character to add to current line.
306 * last_line_pos - screen line position of next char to be read
307 * (takes into account tabs and backspaces)
308 * eof_error - < 0 error, == 0 EOF, > 0 not EOF/error
310 static void read_lines(void)
312 #define readbuf bb_common_bufsiz1
313 char *current_line, *p;
315 char last_terminated = terminated;
316 #if ENABLE_FEATURE_LESS_REGEXP
317 unsigned old_max_fline = max_fline;
318 time_t last_time = 0;
319 unsigned seconds_p1 = 3; /* seconds_to_loop + 1 */
322 if (option_mask32 & FLAG_N)
325 USE_FEATURE_LESS_REGEXP(again0:)
327 p = current_line = ((char*)xmalloc(w + 4)) + 4;
328 max_fline += last_terminated;
329 if (!last_terminated) {
330 const char *cp = flines[max_fline];
332 p += strlen(current_line);
333 free(MEMPTR(flines[max_fline]));
334 /* last_line_pos is still valid from previous read_lines() */
339 while (1) { /* read lines until we reach cur_fline or wanted_match */
342 while (1) { /* read chars until we have a line */
344 /* if no unprocessed chars left, eat more */
345 if (readpos >= readeof) {
347 eof_error = safe_read(STDIN_FILENO, readbuf, sizeof(readbuf));
354 c = readbuf[readpos];
355 /* backspace? [needed for manpages] */
356 /* <tab><bs> is (a) insane and */
357 /* (b) harder to do correctly, so we refuse to do it */
358 if (c == '\x8' && last_line_pos && p[-1] != '\t') {
359 readpos++; /* eat it */
361 /* was buggy (p could end up <= current_line)... */
366 size_t new_last_line_pos = last_line_pos + 1;
368 new_last_line_pos += 7;
369 new_last_line_pos &= (~7);
371 if ((int)new_last_line_pos >= w)
373 last_line_pos = new_last_line_pos;
375 /* ok, we will eat this char */
382 /* NUL is substituted by '\n'! */
383 if (c == '\0') c = '\n';
386 } /* end of "read chars until we have a line" loop */
387 /* Corner case: linewrap with only "" wrapping to next line */
388 /* Looks ugly on screen, so we do not store this empty line */
389 if (!last_terminated && !current_line[0]) {
395 last_terminated = terminated;
396 flines = xrealloc_vector(flines, 8, max_fline);
398 flines[max_fline] = (char*)xrealloc(MEMPTR(current_line), strlen(current_line) + 1 + 4) + 4;
399 LINENO(flines[max_fline]) = max_lineno;
403 if (max_fline >= MAXLINES) {
404 eof_error = 0; /* Pretend we saw EOF */
407 if (!(option_mask32 & FLAG_S)
408 ? (max_fline > cur_fline + max_displayed_line)
409 : (max_fline >= cur_fline
410 && max_lineno > LINENO(flines[cur_fline]) + max_displayed_line)
412 #if !ENABLE_FEATURE_LESS_REGEXP
415 if (wanted_match >= num_matches) { /* goto_match called us */
416 fill_match_lines(old_max_fline);
417 old_max_fline = max_fline;
419 if (wanted_match < num_matches)
423 if (eof_error <= 0) {
425 if (errno == EAGAIN) {
426 /* not yet eof or error, reset flag (or else
427 * we will hog CPU - select() will return
431 print_statusline("read error");
434 #if !ENABLE_FEATURE_LESS_REGEXP
437 if (wanted_match < num_matches) {
439 } else { /* goto_match called us */
440 time_t t = time(NULL);
441 if (t != last_time) {
443 if (--seconds_p1 == 0)
447 goto again0; /* go loop again (max 2 seconds) */
452 current_line = ((char*)xmalloc(w + 4)) + 4;
455 } /* end of "read lines until we reach cur_fline" loop */
456 fill_match_lines(old_max_fline);
457 #if ENABLE_FEATURE_LESS_REGEXP
458 /* prevent us from being stuck in search for a match */
464 #if ENABLE_FEATURE_LESS_FLAGS
465 /* Interestingly, writing calc_percent as a function saves around 32 bytes
467 static int calc_percent(void)
469 unsigned p = (100 * (cur_fline+max_displayed_line+1) + max_fline/2) / (max_fline+1);
470 return p <= 100 ? p : 100;
473 /* Print a status line if -M was specified */
474 static void m_status_print(void)
478 if (less_gets_pos >= 0) /* don't touch statusline while input is done! */
482 printf(HIGHLIGHT"%s", filename);
484 printf(" (file %i of %i)", current_file, num_files);
485 printf(" lines %i-%i/%i ",
486 cur_fline + 1, cur_fline + max_displayed_line + 1,
488 if (cur_fline >= (int)(max_fline - max_displayed_line)) {
489 printf("(END)"NORMAL);
490 if (num_files > 1 && current_file != num_files)
491 printf(HIGHLIGHT" - next: %s"NORMAL, files[current_file]);
494 percentage = calc_percent();
495 printf("%i%%"NORMAL, percentage);
499 /* Print the status line */
500 static void status_print(void)
504 if (less_gets_pos >= 0) /* don't touch statusline while input is done! */
507 /* Change the status if flags have been set */
508 #if ENABLE_FEATURE_LESS_FLAGS
509 if (option_mask32 & (FLAG_M|FLAG_m)) {
517 if (cur_fline && cur_fline < (int)(max_fline - max_displayed_line)) {
525 printf(HIGHLIGHT"%s (file %i of %i)"NORMAL,
526 p, current_file, num_files);
532 static void cap_cur_fline(int nlines)
537 if (cur_fline + max_displayed_line > max_fline + TILDES) {
541 diff = max_fline - (cur_fline + max_displayed_line) + TILDES;
542 /* As the number of lines requested was too large, we just move
543 to the end of the file */
549 static const char controls[] ALIGN1 =
550 /* NUL: never encountered; TAB: not converted */
551 /**/"\x01\x02\x03\x04\x05\x06\x07\x08" "\x0a\x0b\x0c\x0d\x0e\x0f"
552 "\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1a\x1b\x1c\x1d\x1e\x1f"
553 "\x7f\x9b"; /* DEL and infamous Meta-ESC :( */
554 static const char ctrlconv[] ALIGN1 =
555 /* '\n': it's a former NUL - subst with '@', not 'J' */
556 "\x40\x41\x42\x43\x44\x45\x46\x47\x48\x49\x40\x4b\x4c\x4d\x4e\x4f"
557 "\x50\x51\x52\x53\x54\x55\x56\x57\x58\x59\x5a\x5b\x5c\x5d\x5e\x5f";
559 static void lineno_str(char *nbuf9, const char *line)
562 if (option_mask32 & FLAG_N) {
566 if (line == empty_line_marker) {
567 memset(nbuf9, ' ', 8);
571 /* Width of 7 preserves tab spacing in the text */
573 n = LINENO(line) + 1;
578 sprintf(nbuf9, fmt, n);
583 #if ENABLE_FEATURE_LESS_REGEXP
584 static void print_found(const char *line)
589 regmatch_t match_structs;
593 const char *str = line;
598 n = strcspn(str, controls);
605 n = strspn(str, controls);
612 /* buf[] holds quarantined version of str */
614 /* Each part of the line that matches has the HIGHLIGHT
615 and NORMAL escape sequences placed around it.
616 NB: we regex against line, but insert text
617 from quarantined copy (buf[]) */
623 while (match_status == 0) {
624 char *new = xasprintf("%s%.*s"HIGHLIGHT"%.*s"NORMAL,
626 match_structs.rm_so, str,
627 match_structs.rm_eo - match_structs.rm_so,
628 str + match_structs.rm_so);
631 str += match_structs.rm_eo;
632 line += match_structs.rm_eo;
635 /* Most of the time doesn't find the regex, optimize for that */
636 match_status = regexec(&pattern, line, 1, &match_structs, eflags);
637 /* if even "" matches, treat it as "not a match" */
638 if (match_structs.rm_so >= match_structs.rm_eo)
642 lineno_str(nbuf9, line);
644 printf(CLEAR_2_EOL"%s%s\n", nbuf9, str);
647 printf(CLEAR_2_EOL"%s%s%s\n", nbuf9, growline, str);
651 void print_found(const char *line);
654 static void print_ascii(const char *str)
661 lineno_str(nbuf9, str);
662 printf(CLEAR_2_EOL"%s", nbuf9);
665 n = strcspn(str, controls);
668 printf("%.*s", (int) n, str);
671 n = strspn(str, controls);
676 else if (*str == (char)0x9b)
677 /* VT100's CSI, aka Meta-ESC. Who's inventor? */
678 /* I want to know who committed this sin */
681 *p++ = ctrlconv[(unsigned char)*str];
690 /* Print the buffer */
691 static void buffer_print(void)
696 for (i = 0; i <= max_displayed_line; i++)
698 print_found(buffer[i]);
700 print_ascii(buffer[i]);
704 static void buffer_fill_and_print(void)
707 #if ENABLE_FEATURE_LESS_DASHCMD
708 int fpos = cur_fline;
710 if (option_mask32 & FLAG_S) {
711 /* Go back to the beginning of this line */
712 while (fpos && LINENO(flines[fpos]) == LINENO(flines[fpos-1]))
717 while (i <= max_displayed_line && fpos <= max_fline) {
718 int lineno = LINENO(flines[fpos]);
719 buffer[i] = flines[fpos];
723 } while ((fpos <= max_fline)
724 && (option_mask32 & FLAG_S)
725 && lineno == LINENO(flines[fpos])
729 for (i = 0; i <= max_displayed_line && cur_fline + i <= max_fline; i++) {
730 buffer[i] = flines[cur_fline + i];
733 for (; i <= max_displayed_line; i++) {
734 buffer[i] = empty_line_marker;
739 /* Move the buffer up and down in the file in order to scroll */
740 static void buffer_down(int nlines)
744 cap_cur_fline(nlines);
745 buffer_fill_and_print();
748 static void buffer_up(int nlines)
751 if (cur_fline < 0) cur_fline = 0;
753 buffer_fill_and_print();
756 static void buffer_line(int linenum)
762 if (linenum + max_displayed_line > max_fline)
763 linenum = max_fline - max_displayed_line + TILDES;
767 buffer_fill_and_print();
770 static void open_file_and_read_lines(void)
773 int fd = xopen(filename, O_RDONLY);
777 /* "less" with no arguments in argv[] */
778 /* For status line only */
779 filename = xstrdup(bb_msg_standard_input);
788 /* Reinitialize everything for a new file - free the memory and start over */
789 static void reinitialize(void)
794 for (i = 0; i <= max_fline; i++)
795 free(MEMPTR(flines[i]));
803 open_file_and_read_lines();
804 buffer_fill_and_print();
807 static ssize_t getch_nowait(void)
809 char input[KEYCODE_BUFFER_SIZE];
811 struct pollfd pfd[2];
813 pfd[0].fd = STDIN_FILENO;
814 pfd[0].events = POLLIN;
816 pfd[1].events = POLLIN;
818 tcsetattr(kbd_fd, TCSANOW, &term_less);
819 /* NB: select/poll returns whenever read will not block. Therefore:
820 * if eof is reached, select/poll will return immediately
821 * because read will immediately return 0 bytes.
822 * Even if select/poll says that input is available, read CAN block
823 * (switch fd into O_NONBLOCK'ed mode to avoid it)
826 /* Are we interested in stdin? */
827 //TODO: reuse code for determining this
828 if (!(option_mask32 & FLAG_S)
829 ? !(max_fline > cur_fline + max_displayed_line)
830 : !(max_fline >= cur_fline
831 && max_lineno > LINENO(flines[cur_fline]) + max_displayed_line)
833 if (eof_error > 0) /* did NOT reach eof yet */
834 rd = 0; /* yes, we are interested in stdin */
836 /* Position cursor if line input is done */
837 if (less_gets_pos >= 0)
838 move_cursor(max_displayed_line + 2, less_gets_pos + 1);
840 #if ENABLE_FEATURE_LESS_WINCH
843 /* NB: SIGWINCH interrupts poll() */
844 r = poll(pfd + rd, 2 - rd, -1);
845 if (/*r < 0 && errno == EINTR &&*/ winch_counter)
846 return '\\'; /* anything which has no defined function */
850 safe_poll(pfd + rd, 2 - rd, -1);
853 /* We have kbd_fd in O_NONBLOCK mode, read inside read_key()
854 * would not block even if there is no input available */
855 rd = read_key(kbd_fd, NULL, input);
857 if (errno == EAGAIN) {
858 /* No keyboard input available. Since poll() did return,
859 * we should have input on stdin */
861 buffer_fill_and_print();
864 /* EOF/error (ssh session got killed etc) */
871 /* Grab a character from input without requiring the return key. If the
872 * character is ASCII \033, get more characters and assign certain sequences
873 * special return codes. Note that this function works best with raw input. */
874 static int less_getch(int pos)
883 /* Discard Ctrl-something chars */
884 if (i >= 0 && i < ' ' && i != 0x0d && i != 8)
889 static char* less_gets(int sz)
893 char *result = xzalloc(1);
897 less_gets_pos = sz + i;
910 if (c < ' ') /* filters out KEYCODE_xxx too (<0) */
912 if (i >= width - sz - 1)
913 continue; /* len limit */
916 result = xrealloc(result, i+1);
920 static void examine_file(void)
924 print_statusline("Examine: ");
925 new_fname = less_gets(sizeof("Examine: ") - 1);
932 if (access(new_fname, R_OK) != 0) {
933 print_statusline("Cannot read this file");
937 filename = new_fname;
938 /* files start by = argv. why we assume that argv is infinitely long??
939 files[num_files] = filename;
940 current_file = num_files + 1;
943 num_files = current_file = 1;
947 /* This function changes the file currently being paged. direction can be one of the following:
948 * -1: go back one file
949 * 0: go to the first file
950 * 1: go forward one file */
951 static void change_file(int direction)
953 if (current_file != ((direction > 0) ? num_files : 1)) {
954 current_file = direction ? current_file + direction : 1;
956 filename = xstrdup(files[current_file - 1]);
959 print_statusline(direction > 0 ? "No next file" : "No previous file");
963 static void remove_current_file(void)
970 if (current_file != 1) {
972 for (i = 3; i <= num_files; i++)
973 files[i - 2] = files[i - 1];
977 for (i = 2; i <= num_files; i++)
978 files[i - 2] = files[i - 1];
984 static void colon_process(void)
988 /* Clear the current line and print a prompt */
989 print_statusline(" :");
991 keypress = less_getch(2);
994 remove_current_file();
999 #if ENABLE_FEATURE_LESS_FLAGS
1011 less_exit(EXIT_SUCCESS);
1019 #if ENABLE_FEATURE_LESS_REGEXP
1020 static void normalize_match_pos(int match)
1022 if (match >= num_matches)
1023 match = num_matches - 1;
1029 static void goto_match(int match)
1035 /* Try to find next match if eof isn't reached yet */
1036 if (match >= num_matches && eof_error > 0) {
1037 wanted_match = match; /* "I want to read until I see N'th match" */
1041 normalize_match_pos(match);
1042 buffer_line(match_lines[match_pos]);
1044 print_statusline("No matches found");
1048 static void fill_match_lines(unsigned pos)
1052 /* Run the regex on each line of the current file */
1053 while (pos <= max_fline) {
1054 /* If this line matches */
1055 if (regexec(&pattern, flines[pos], 0, NULL, 0) == 0
1056 /* and we didn't match it last time */
1057 && !(num_matches && match_lines[num_matches-1] == pos)
1059 match_lines = xrealloc_vector(match_lines, 4, num_matches);
1060 match_lines[num_matches++] = pos;
1066 static void regex_process(void)
1068 char *uncomp_regex, *err;
1070 /* Reset variables */
1075 if (pattern_valid) {
1080 /* Get the uncompiled regular expression from the user */
1082 bb_putchar((option_mask32 & LESS_STATE_MATCH_BACKWARDS) ? '?' : '/');
1083 uncomp_regex = less_gets(1);
1084 if (!uncomp_regex[0]) {
1090 /* Compile the regex and check for errors */
1091 err = regcomp_or_errmsg(&pattern, uncomp_regex,
1092 (option_mask32 & FLAG_I) ? REG_ICASE : 0);
1095 print_statusline(err);
1102 fill_match_lines(0);
1103 while (match_pos < num_matches) {
1104 if ((int)match_lines[match_pos] > cur_fline)
1108 if (option_mask32 & LESS_STATE_MATCH_BACKWARDS)
1111 /* It's possible that no matches are found yet.
1112 * goto_match() will read input looking for match,
1114 goto_match(match_pos);
1118 static void number_process(int first_digit)
1123 char num_input[sizeof(int)*4]; /* more than enough */
1125 num_input[0] = first_digit;
1127 /* Clear the current line, print a prompt, and then print the digit */
1129 printf(":%c", first_digit);
1131 /* Receive input until a letter is given */
1133 while (i < sizeof(num_input)-1) {
1134 keypress = less_getch(i + 1);
1135 if ((unsigned)keypress > 255 || !isdigit(num_input[i]))
1137 num_input[i] = keypress;
1138 bb_putchar(keypress);
1142 num_input[i] = '\0';
1143 num = bb_strtou(num_input, NULL, 10);
1144 /* on format error, num == -1 */
1145 if (num < 1 || num > MAXLINES) {
1150 /* We now know the number and the letter entered, so we process them */
1152 case KEYCODE_DOWN: case 'z': case 'd': case 'e': case ' ': case '\015':
1155 case KEYCODE_UP: case 'b': case 'w': case 'y': case 'u':
1158 case 'g': case '<': case 'G': case '>':
1159 cur_fline = num + max_displayed_line;
1161 buffer_line(num - 1);
1164 num = num * (max_fline / 100); /* + max_fline / 2; */
1165 cur_fline = num + max_displayed_line;
1169 #if ENABLE_FEATURE_LESS_REGEXP
1171 goto_match(match_pos + num);
1174 option_mask32 &= ~LESS_STATE_MATCH_BACKWARDS;
1178 option_mask32 |= LESS_STATE_MATCH_BACKWARDS;
1185 #if ENABLE_FEATURE_LESS_DASHCMD
1186 static void flag_change(void)
1192 keypress = less_getch(1);
1196 option_mask32 ^= FLAG_M;
1199 option_mask32 ^= FLAG_m;
1202 option_mask32 ^= FLAG_E;
1205 option_mask32 ^= FLAG_TILDE;
1208 option_mask32 ^= FLAG_S;
1209 buffer_fill_and_print();
1211 #if ENABLE_FEATURE_LESS_LINENUMS
1213 option_mask32 ^= FLAG_N;
1215 buffer_fill_and_print();
1222 static void show_flag_status(void)
1229 keypress = less_getch(1);
1233 flag_val = option_mask32 & FLAG_M;
1236 flag_val = option_mask32 & FLAG_m;
1239 flag_val = option_mask32 & FLAG_TILDE;
1242 flag_val = option_mask32 & FLAG_N;
1245 flag_val = option_mask32 & FLAG_E;
1253 printf(HIGHLIGHT"The status of the flag is: %u"NORMAL, flag_val != 0);
1257 #endif /* ENABLE_FEATURE_LESS_DASHCMD */
1259 static void save_input_to_file(void)
1261 const char *msg = "";
1266 print_statusline("Log file: ");
1267 current_line = less_gets(sizeof("Log file: ")-1);
1268 if (current_line[0]) {
1269 fp = fopen_for_write(current_line);
1271 msg = "Error opening log file";
1274 for (i = 0; i <= max_fline; i++)
1275 fprintf(fp, "%s\n", flines[i]);
1280 print_statusline(msg);
1284 #if ENABLE_FEATURE_LESS_MARKS
1285 static void add_mark(void)
1289 print_statusline("Mark: ");
1290 letter = less_getch(sizeof("Mark: ") - 1);
1292 if (isalpha(letter)) {
1293 /* If we exceed 15 marks, start overwriting previous ones */
1294 if (num_marks == 14)
1297 mark_lines[num_marks][0] = letter;
1298 mark_lines[num_marks][1] = cur_fline;
1301 print_statusline("Invalid mark letter");
1305 static void goto_mark(void)
1310 print_statusline("Go to mark: ");
1311 letter = less_getch(sizeof("Go to mark: ") - 1);
1314 if (isalpha(letter)) {
1315 for (i = 0; i <= num_marks; i++)
1316 if (letter == mark_lines[i][0]) {
1317 buffer_line(mark_lines[i][1]);
1320 if (num_marks == 14 && letter != mark_lines[14][0])
1321 print_statusline("Mark not set");
1323 print_statusline("Invalid mark letter");
1327 #if ENABLE_FEATURE_LESS_BRACKETS
1328 static char opp_bracket(char bracket)
1331 case '{': case '[': /* '}' == '{' + 2. Same for '[' */
1333 case '(': /* ')' == '(' + 1 */
1345 static void match_right_bracket(char bracket)
1349 if (strchr(flines[cur_fline], bracket) == NULL) {
1350 print_statusline("No bracket in top line");
1353 bracket = opp_bracket(bracket);
1354 for (i = cur_fline + 1; i < max_fline; i++) {
1355 if (strchr(flines[i], bracket) != NULL) {
1360 print_statusline("No matching bracket found");
1363 static void match_left_bracket(char bracket)
1367 if (strchr(flines[cur_fline + max_displayed_line], bracket) == NULL) {
1368 print_statusline("No bracket in bottom line");
1372 bracket = opp_bracket(bracket);
1373 for (i = cur_fline + max_displayed_line; i >= 0; i--) {
1374 if (strchr(flines[i], bracket) != NULL) {
1379 print_statusline("No matching bracket found");
1381 #endif /* FEATURE_LESS_BRACKETS */
1383 static void keypress_process(int keypress)
1386 case KEYCODE_DOWN: case 'e': case 'j': case 0x0d:
1389 case KEYCODE_UP: case 'y': case 'k':
1392 case KEYCODE_PAGEDOWN: case ' ': case 'z': case 'f':
1393 buffer_down(max_displayed_line + 1);
1395 case KEYCODE_PAGEUP: case 'w': case 'b':
1396 buffer_up(max_displayed_line + 1);
1399 buffer_down((max_displayed_line + 1) / 2);
1402 buffer_up((max_displayed_line + 1) / 2);
1404 case KEYCODE_HOME: case 'g': case 'p': case '<': case '%':
1407 case KEYCODE_END: case 'G': case '>':
1408 cur_fline = MAXLINES;
1410 buffer_line(cur_fline);
1413 less_exit(EXIT_SUCCESS);
1415 #if ENABLE_FEATURE_LESS_MARKS
1432 save_input_to_file();
1437 #if ENABLE_FEATURE_LESS_FLAGS
1442 #if ENABLE_FEATURE_LESS_REGEXP
1444 option_mask32 &= ~LESS_STATE_MATCH_BACKWARDS;
1448 goto_match(match_pos + 1);
1451 goto_match(match_pos - 1);
1454 option_mask32 |= LESS_STATE_MATCH_BACKWARDS;
1458 #if ENABLE_FEATURE_LESS_DASHCMD
1469 #if ENABLE_FEATURE_LESS_BRACKETS
1470 case '{': case '(': case '[':
1471 match_right_bracket(keypress);
1473 case '}': case ')': case ']':
1474 match_left_bracket(keypress);
1482 if (isdigit(keypress))
1483 number_process(keypress);
1486 static void sig_catcher(int sig)
1491 #if ENABLE_FEATURE_LESS_WINCH
1492 static void sigwinch_handler(int sig UNUSED_PARAM)
1498 int less_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
1499 int less_main(int argc, char **argv)
1505 /* TODO: -x: do not interpret backspace, -xx: tab also */
1506 /* -xxx: newline also */
1507 /* -w N: assume width N (-xxx -w 32: hex viewer of sorts) */
1508 getopt32(argv, "EMmN~I" USE_FEATURE_LESS_DASHCMD("S"));
1514 /* Another popular pager, most, detects when stdout
1515 * is not a tty and turns into cat. This makes sense. */
1516 if (!isatty(STDOUT_FILENO))
1517 return bb_cat(argv);
1520 if (isatty(STDIN_FILENO)) {
1521 /* Just "less"? No args and no redirection? */
1522 bb_error_msg("missing filename");
1526 filename = xstrdup(files[0]);
1529 if (option_mask32 & FLAG_TILDE)
1530 empty_line_marker = "";
1532 kbd_fd = open(CURRENT_TTY, O_RDONLY);
1534 return bb_cat(argv);
1537 tcgetattr(kbd_fd, &term_orig);
1538 term_less = term_orig;
1539 term_less.c_lflag &= ~(ICANON | ECHO);
1540 term_less.c_iflag &= ~(IXON | ICRNL);
1541 /*term_less.c_oflag &= ~ONLCR;*/
1542 term_less.c_cc[VMIN] = 1;
1543 term_less.c_cc[VTIME] = 0;
1545 get_terminal_width_height(kbd_fd, &width, &max_displayed_line);
1546 /* 20: two tabstops + 4 */
1547 if (width < 20 || max_displayed_line < 3)
1548 return bb_cat(argv);
1549 max_displayed_line -= 2;
1551 /* We want to restore term_orig on exit */
1552 bb_signals(BB_FATAL_SIGS, sig_catcher);
1553 #if ENABLE_FEATURE_LESS_WINCH
1554 signal(SIGWINCH, sigwinch_handler);
1557 buffer = xmalloc((max_displayed_line+1) * sizeof(char *));
1560 #if ENABLE_FEATURE_LESS_WINCH
1561 while (WINCH_COUNTER) {
1564 get_terminal_width_height(kbd_fd, &width, &max_displayed_line);
1565 /* 20: two tabstops + 4 */
1568 if (max_displayed_line < 3)
1569 max_displayed_line = 3;
1570 max_displayed_line -= 2;
1572 buffer = xmalloc((max_displayed_line+1) * sizeof(char *));
1573 /* Avoid re-wrap and/or redraw if we already know
1574 * we need to do it again. These ops are expensive */
1580 buffer_fill_and_print();
1581 /* This took some time. Loop back and check,
1582 * were there another SIGWINCH? */
1585 keypress = less_getch(-1); /* -1: do not position cursor */
1586 keypress_process(keypress);
1591 Help text of less version 418 is below.
1592 If you are implementing something, keeping
1593 key and/or command line switch compatibility is a good idea:
1596 SUMMARY OF LESS COMMANDS
1598 Commands marked with * may be preceded by a number, N.
1599 Notes in parentheses indicate the behavior if N is given.
1600 h H Display this help.
1602 ---------------------------------------------------------------------------
1604 e ^E j ^N CR * Forward one line (or N lines).
1605 y ^Y k ^K ^P * Backward one line (or N lines).
1606 f ^F ^V SPACE * Forward one window (or N lines).
1607 b ^B ESC-v * Backward one window (or N lines).
1608 z * Forward one window (and set window to N).
1609 w * Backward one window (and set window to N).
1610 ESC-SPACE * Forward one window, but don't stop at end-of-file.
1611 d ^D * Forward one half-window (and set half-window to N).
1612 u ^U * Backward one half-window (and set half-window to N).
1613 ESC-) RightArrow * Left one half screen width (or N positions).
1614 ESC-( LeftArrow * Right one half screen width (or N positions).
1615 F Forward forever; like "tail -f".
1616 r ^R ^L Repaint screen.
1617 R Repaint screen, discarding buffered input.
1618 ---------------------------------------------------
1619 Default "window" is the screen height.
1620 Default "half-window" is half of the screen height.
1621 ---------------------------------------------------------------------------
1623 /pattern * Search forward for (N-th) matching line.
1624 ?pattern * Search backward for (N-th) matching line.
1625 n * Repeat previous search (for N-th occurrence).
1626 N * Repeat previous search in reverse direction.
1627 ESC-n * Repeat previous search, spanning files.
1628 ESC-N * Repeat previous search, reverse dir. & spanning files.
1629 ESC-u Undo (toggle) search highlighting.
1630 ---------------------------------------------------
1631 Search patterns may be modified by one or more of:
1632 ^N or ! Search for NON-matching lines.
1633 ^E or * Search multiple files (pass thru END OF FILE).
1634 ^F or @ Start search at FIRST file (for /) or last file (for ?).
1635 ^K Highlight matches, but don't move (KEEP position).
1636 ^R Don't use REGULAR EXPRESSIONS.
1637 ---------------------------------------------------------------------------
1639 g < ESC-< * Go to first line in file (or line N).
1640 G > ESC-> * Go to last line in file (or line N).
1641 p % * Go to beginning of file (or N percent into file).
1642 t * Go to the (N-th) next tag.
1643 T * Go to the (N-th) previous tag.
1644 { ( [ * Find close bracket } ) ].
1645 } ) ] * Find open bracket { ( [.
1646 ESC-^F <c1> <c2> * Find close bracket <c2>.
1647 ESC-^B <c1> <c2> * Find open bracket <c1>
1648 ---------------------------------------------------
1649 Each "find close bracket" command goes forward to the close bracket
1650 matching the (N-th) open bracket in the top line.
1651 Each "find open bracket" command goes backward to the open bracket
1652 matching the (N-th) close bracket in the bottom line.
1653 m<letter> Mark the current position with <letter>.
1654 '<letter> Go to a previously marked position.
1655 '' Go to the previous position.
1657 ---------------------------------------------------
1658 A mark is any upper-case or lower-case letter.
1659 Certain marks are predefined:
1660 ^ means beginning of the file
1661 $ means end of the file
1662 ---------------------------------------------------------------------------
1664 :e [file] Examine a new file.
1666 :n * Examine the (N-th) next file from the command line.
1667 :p * Examine the (N-th) previous file from the command line.
1668 :x * Examine the first (or N-th) file from the command line.
1669 :d Delete the current file from the command line list.
1670 = ^G :f Print current file name.
1671 ---------------------------------------------------------------------------
1672 MISCELLANEOUS COMMANDS
1673 -<flag> Toggle a command line option [see OPTIONS below].
1674 --<name> Toggle a command line option, by name.
1675 _<flag> Display the setting of a command line option.
1676 __<name> Display the setting of an option, by name.
1677 +cmd Execute the less cmd each time a new file is examined.
1678 !command Execute the shell command with $SHELL.
1679 |Xcommand Pipe file between current pos & mark X to shell command.
1680 v Edit the current file with $VISUAL or $EDITOR.
1681 V Print version number of "less".
1682 ---------------------------------------------------------------------------
1684 Most options may be changed either on the command line,
1685 or from within less by using the - or -- command.
1686 Options may be given in one of two forms: either a single
1687 character preceded by a -, or a name preceeded by --.
1689 Display help (from command line).
1690 -a ........ --search-skip-screen
1691 Forward search skips current screen.
1692 -b [N] .... --buffers=[N]
1694 -B ........ --auto-buffers
1695 Don't automatically allocate buffers for pipes.
1696 -c ........ --clear-screen
1697 Repaint by clearing rather than scrolling.
1700 -D [xn.n] . --color=xn.n
1701 Set screen colors. (MS-DOS only)
1702 -e -E .... --quit-at-eof --QUIT-AT-EOF
1703 Quit at end of file.
1705 Force open non-regular files.
1706 -F ........ --quit-if-one-screen
1707 Quit if entire file fits on first screen.
1708 -g ........ --hilite-search
1709 Highlight only last match for searches.
1710 -G ........ --HILITE-SEARCH
1711 Don't highlight any matches for searches.
1712 -h [N] .... --max-back-scroll=[N]
1713 Backward scroll limit.
1714 -i ........ --ignore-case
1715 Ignore case in searches that do not contain uppercase.
1716 -I ........ --IGNORE-CASE
1717 Ignore case in all searches.
1718 -j [N] .... --jump-target=[N]
1719 Screen position of target lines.
1720 -J ........ --status-column
1721 Display a status column at left edge of screen.
1722 -k [file] . --lesskey-file=[file]
1724 -L ........ --no-lessopen
1725 Ignore the LESSOPEN environment variable.
1726 -m -M .... --long-prompt --LONG-PROMPT
1728 -n -N .... --line-numbers --LINE-NUMBERS
1729 Don't use line numbers.
1730 -o [file] . --log-file=[file]
1731 Copy to log file (standard input only).
1732 -O [file] . --LOG-FILE=[file]
1733 Copy to log file (unconditionally overwrite).
1734 -p [pattern] --pattern=[pattern]
1735 Start at pattern (from command line).
1736 -P [prompt] --prompt=[prompt]
1738 -q -Q .... --quiet --QUIET --silent --SILENT
1739 Quiet the terminal bell.
1740 -r -R .... --raw-control-chars --RAW-CONTROL-CHARS
1741 Output "raw" control characters.
1742 -s ........ --squeeze-blank-lines
1743 Squeeze multiple blank lines.
1744 -S ........ --chop-long-lines
1746 -t [tag] .. --tag=[tag]
1748 -T [tagsfile] --tag-file=[tagsfile]
1749 Use an alternate tags file.
1750 -u -U .... --underline-special --UNDERLINE-SPECIAL
1751 Change handling of backspaces.
1752 -V ........ --version
1753 Display the version number of "less".
1754 -w ........ --hilite-unread
1755 Highlight first new line after forward-screen.
1756 -W ........ --HILITE-UNREAD
1757 Highlight first new line after any forward movement.
1758 -x [N[,...]] --tabs=[N[,...]]
1760 -X ........ --no-init
1761 Don't use termcap init/deinit strings.
1763 Don't use termcap keypad init/deinit strings.
1764 -y [N] .... --max-forw-scroll=[N]
1765 Forward scroll limit.
1766 -z [N] .... --window=[N]
1768 -" [c[c]] . --quotes=[c[c]]
1769 Set shell quote characters.
1771 Don't display tildes after end of file.
1772 -# [N] .... --shift=[N]
1773 Horizontal scroll amount (0 = one half screen width)
1775 ---------------------------------------------------------------------------
1777 These keys can be used to edit text being entered
1778 on the "command line" at the bottom of the screen.
1779 RightArrow ESC-l Move cursor right one character.
1780 LeftArrow ESC-h Move cursor left one character.
1781 CNTL-RightArrow ESC-RightArrow ESC-w Move cursor right one word.
1782 CNTL-LeftArrow ESC-LeftArrow ESC-b Move cursor left one word.
1783 HOME ESC-0 Move cursor to start of line.
1784 END ESC-$ Move cursor to end of line.
1785 BACKSPACE Delete char to left of cursor.
1786 DELETE ESC-x Delete char under cursor.
1787 CNTL-BACKSPACE ESC-BACKSPACE Delete word to left of cursor.
1788 CNTL-DELETE ESC-DELETE ESC-X Delete word under cursor.
1789 CNTL-U ESC (MS-DOS only) Delete entire line.
1790 UpArrow ESC-k Retrieve previous command line.
1791 DownArrow ESC-j Retrieve next command line.
1792 TAB Complete filename & cycle.
1793 SHIFT-TAB ESC-TAB Complete filename & reverse cycle.
1794 CNTL-L Complete filename, list all.