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"
39 /* These are the escape sequences corresponding to special keys */
47 REAL_KEY_HOME = '7', // vt100? linux vt? or what?
49 REAL_KEY_HOME_ALT = '1', // ESC [1~ (vt100? linux vt? or what?)
50 REAL_KEY_END_ALT = '4', // ESC [4~
51 REAL_KEY_HOME_XTERM = 'H',
52 REAL_KEY_END_XTERM = 'F',
54 /* These are the special codes assigned by this program to the special keys */
64 /* Absolute max of lines eaten */
65 MAXLINES = CONFIG_FEATURE_LESS_MAXLINES,
67 /* This many "after the end" lines we will show (at max) */
71 /* Command line options */
79 FLAG_S = (1 << 6) * ENABLE_FEATURE_LESS_DASHCMD,
80 /* hijack command line options variable for internal state vars */
81 LESS_STATE_MATCH_BACKWARDS = 1 << 15,
84 #if !ENABLE_FEATURE_LESS_REGEXP
85 enum { pattern_valid = 0 };
89 int cur_fline; /* signed */
90 int kbd_fd; /* fd to get input from */
92 /* last position in last line, taking into account tabs */
95 unsigned max_lineno; /* this one tracks linewrap */
96 unsigned max_displayed_line;
98 #if ENABLE_FEATURE_LESS_WINCH
99 unsigned winch_counter;
101 ssize_t eof_error; /* eof if 0, error if < 0 */
103 ssize_t readeof; /* must be signed */
106 const char *empty_line_marker;
108 unsigned current_file;
111 #if ENABLE_FEATURE_LESS_MARKS
113 unsigned mark_lines[15][2];
115 #if ENABLE_FEATURE_LESS_REGEXP
116 unsigned *match_lines;
117 int match_pos; /* signed! */
118 int wanted_match; /* signed! */
121 smallint pattern_valid;
124 struct termios term_orig, term_less;
126 #define G (*ptr_to_globals)
127 #define cur_fline (G.cur_fline )
128 #define kbd_fd (G.kbd_fd )
129 #define less_gets_pos (G.less_gets_pos )
130 #define linepos (G.linepos )
131 #define max_fline (G.max_fline )
132 #define max_lineno (G.max_lineno )
133 #define max_displayed_line (G.max_displayed_line)
134 #define width (G.width )
135 #define winch_counter (G.winch_counter )
136 #define eof_error (G.eof_error )
137 #define readpos (G.readpos )
138 #define readeof (G.readeof )
139 #define buffer (G.buffer )
140 #define flines (G.flines )
141 #define empty_line_marker (G.empty_line_marker )
142 #define num_files (G.num_files )
143 #define current_file (G.current_file )
144 #define filename (G.filename )
145 #define files (G.files )
146 #define num_marks (G.num_marks )
147 #define mark_lines (G.mark_lines )
148 #if ENABLE_FEATURE_LESS_REGEXP
149 #define match_lines (G.match_lines )
150 #define match_pos (G.match_pos )
151 #define num_matches (G.num_matches )
152 #define wanted_match (G.wanted_match )
153 #define pattern (G.pattern )
154 #define pattern_valid (G.pattern_valid )
156 #define terminated (G.terminated )
157 #define term_orig (G.term_orig )
158 #define term_less (G.term_less )
159 #define INIT_G() do { \
160 SET_PTR_TO_GLOBALS(xzalloc(sizeof(G))); \
161 less_gets_pos = -1; \
162 empty_line_marker = "~"; \
167 USE_FEATURE_LESS_REGEXP(wanted_match = -1;) \
170 /* flines[] are lines read from stdin, each in malloc'ed buffer.
171 * Line numbers are stored as uint32_t prepended to each line.
172 * Pointer is adjusted so that flines[i] points directly past
173 * line number. Accesor: */
174 #define MEMPTR(p) ((char*)(p) - 4)
175 #define LINENO(p) (*(uint32_t*)((p) - 4))
178 /* Reset terminal input to normal */
179 static void set_tty_cooked(void)
182 tcsetattr(kbd_fd, TCSANOW, &term_orig);
185 /* Move the cursor to a position (x,y), where (0,0) is the
186 top-left corner of the console */
187 static void move_cursor(int line, int row)
189 printf("\033[%u;%uH", line, row);
192 static void clear_line(void)
194 printf("\033[%u;0H" CLEAR_2_EOL, max_displayed_line + 2);
197 static void print_hilite(const char *str)
199 printf(HIGHLIGHT"%s"NORMAL, str);
202 static void print_statusline(const char *str)
205 printf(HIGHLIGHT"%.*s"NORMAL, width - 1, str);
208 /* Exit the program gracefully */
209 static void less_exit(int code)
214 kill_myself_with_sig(- code); /* does not return */
218 #if ENABLE_FEATURE_LESS_LINENUMS || ENABLE_FEATURE_LESS_WINCH
219 static void re_wrap(void)
225 int new_cur_fline = 0;
228 const char **old_flines = flines;
230 char **new_flines = NULL;
233 if (option_mask32 & FLAG_N)
250 /* new line is full, create next one */
253 sz = (d - linebuf) + 1; /* + 1: NUL */
254 d = ((char*)xmalloc(sz + 4)) + 4;
256 memcpy(d, linebuf, sz);
257 new_flines = xrealloc_vector(new_flines, 8, dst_idx);
258 new_flines[dst_idx] = d;
261 /* did we come here thru "goto next_new"? */
262 if (src_idx > max_fline)
271 /* *d == NUL: old line ended, go to next old one */
272 free(MEMPTR(old_flines[src_idx]));
273 /* btw, convert cur_fline... */
274 if (cur_fline == src_idx) {
275 new_cur_fline = dst_idx;
278 /* no more lines? finish last new line (and exit the loop) */
279 if (src_idx > max_fline) {
282 s = old_flines[src_idx];
283 if (lineno != LINENO(s)) {
284 /* this is not a continuation line!
285 * create next _new_ line too */
291 flines = (const char **)new_flines;
293 max_fline = dst_idx - 1;
295 cur_fline = new_cur_fline;
296 /* max_lineno is screen-size independent */
301 #if ENABLE_FEATURE_LESS_REGEXP
302 static void fill_match_lines(unsigned pos);
304 #define fill_match_lines(pos) ((void)0)
307 /* Devilishly complex routine.
309 * Has to deal with EOF and EPIPE on input,
310 * with line wrapping, with last line not ending in '\n'
311 * (possibly not ending YET!), with backspace and tabs.
312 * It reads input again if last time we got an EOF (thus supporting
313 * growing files) or EPIPE (watching output of slow process like make).
316 * flines[] - array of lines already read. Linewrap may cause
317 * one source file line to occupy several flines[n].
318 * flines[max_fline] - last line, possibly incomplete.
319 * terminated - 1 if flines[max_fline] is 'terminated'
320 * (if there was '\n' [which isn't stored itself, we just remember
322 * max_lineno - last line's number, this one doesn't increment
323 * on line wrap, only on "real" new lines.
324 * readbuf[0..readeof-1] - small preliminary buffer.
325 * readbuf[readpos] - next character to add to current line.
326 * linepos - screen line position of next char to be read
327 * (takes into account tabs and backspaces)
328 * eof_error - < 0 error, == 0 EOF, > 0 not EOF/error
330 static void read_lines(void)
332 #define readbuf bb_common_bufsiz1
333 char *current_line, *p;
335 char last_terminated = terminated;
336 #if ENABLE_FEATURE_LESS_REGEXP
337 unsigned old_max_fline = max_fline;
338 time_t last_time = 0;
339 unsigned seconds_p1 = 3; /* seconds_to_loop + 1 */
342 if (option_mask32 & FLAG_N)
345 USE_FEATURE_LESS_REGEXP(again0:)
347 p = current_line = ((char*)xmalloc(w + 4)) + 4;
348 max_fline += last_terminated;
349 if (!last_terminated) {
350 const char *cp = flines[max_fline];
352 p += strlen(current_line);
353 free(MEMPTR(flines[max_fline]));
354 /* linepos is still valid from previous read_lines() */
359 while (1) { /* read lines until we reach cur_fline or wanted_match */
362 while (1) { /* read chars until we have a line */
364 /* if no unprocessed chars left, eat more */
365 if (readpos >= readeof) {
367 eof_error = safe_read(STDIN_FILENO, readbuf, sizeof(readbuf));
374 c = readbuf[readpos];
375 /* backspace? [needed for manpages] */
376 /* <tab><bs> is (a) insane and */
377 /* (b) harder to do correctly, so we refuse to do it */
378 if (c == '\x8' && linepos && p[-1] != '\t') {
379 readpos++; /* eat it */
381 /* was buggy (p could end up <= current_line)... */
386 size_t new_linepos = linepos + 1;
391 if ((int)new_linepos >= w)
393 linepos = new_linepos;
395 /* ok, we will eat this char */
402 /* NUL is substituted by '\n'! */
403 if (c == '\0') c = '\n';
406 } /* end of "read chars until we have a line" loop */
407 /* Corner case: linewrap with only "" wrapping to next line */
408 /* Looks ugly on screen, so we do not store this empty line */
409 if (!last_terminated && !current_line[0]) {
415 last_terminated = terminated;
416 flines = xrealloc_vector(flines, 8, max_fline);
418 flines[max_fline] = (char*)xrealloc(MEMPTR(current_line), strlen(current_line) + 1 + 4) + 4;
419 LINENO(flines[max_fline]) = max_lineno;
423 if (max_fline >= MAXLINES) {
424 eof_error = 0; /* Pretend we saw EOF */
427 if (!(option_mask32 & FLAG_S)
428 ? (max_fline > cur_fline + max_displayed_line)
429 : (max_fline >= cur_fline
430 && max_lineno > LINENO(flines[cur_fline]) + max_displayed_line)
432 #if !ENABLE_FEATURE_LESS_REGEXP
435 if (wanted_match >= num_matches) { /* goto_match called us */
436 fill_match_lines(old_max_fline);
437 old_max_fline = max_fline;
439 if (wanted_match < num_matches)
443 if (eof_error <= 0) {
445 if (errno == EAGAIN) {
446 /* not yet eof or error, reset flag (or else
447 * we will hog CPU - select() will return
451 print_statusline("read error");
454 #if !ENABLE_FEATURE_LESS_REGEXP
457 if (wanted_match < num_matches) {
459 } else { /* goto_match called us */
460 time_t t = time(NULL);
461 if (t != last_time) {
463 if (--seconds_p1 == 0)
467 goto again0; /* go loop again (max 2 seconds) */
472 current_line = ((char*)xmalloc(w + 4)) + 4;
475 } /* end of "read lines until we reach cur_fline" loop */
476 fill_match_lines(old_max_fline);
477 #if ENABLE_FEATURE_LESS_REGEXP
478 /* prevent us from being stuck in search for a match */
484 #if ENABLE_FEATURE_LESS_FLAGS
485 /* Interestingly, writing calc_percent as a function saves around 32 bytes
487 static int calc_percent(void)
489 unsigned p = (100 * (cur_fline+max_displayed_line+1) + max_fline/2) / (max_fline+1);
490 return p <= 100 ? p : 100;
493 /* Print a status line if -M was specified */
494 static void m_status_print(void)
498 if (less_gets_pos >= 0) /* don't touch statusline while input is done! */
502 printf(HIGHLIGHT"%s", filename);
504 printf(" (file %i of %i)", current_file, num_files);
505 printf(" lines %i-%i/%i ",
506 cur_fline + 1, cur_fline + max_displayed_line + 1,
508 if (cur_fline >= (int)(max_fline - max_displayed_line)) {
509 printf("(END)"NORMAL);
510 if (num_files > 1 && current_file != num_files)
511 printf(HIGHLIGHT" - next: %s"NORMAL, files[current_file]);
514 percentage = calc_percent();
515 printf("%i%%"NORMAL, percentage);
519 /* Print the status line */
520 static void status_print(void)
524 if (less_gets_pos >= 0) /* don't touch statusline while input is done! */
527 /* Change the status if flags have been set */
528 #if ENABLE_FEATURE_LESS_FLAGS
529 if (option_mask32 & (FLAG_M|FLAG_m)) {
537 if (cur_fline && cur_fline < (int)(max_fline - max_displayed_line)) {
545 printf(HIGHLIGHT"%s (file %i of %i)"NORMAL,
546 p, current_file, num_files);
552 static void cap_cur_fline(int nlines)
557 if (cur_fline + max_displayed_line > max_fline + TILDES) {
561 diff = max_fline - (cur_fline + max_displayed_line) + TILDES;
562 /* As the number of lines requested was too large, we just move
563 to the end of the file */
569 static const char controls[] ALIGN1 =
570 /* NUL: never encountered; TAB: not converted */
571 /**/"\x01\x02\x03\x04\x05\x06\x07\x08" "\x0a\x0b\x0c\x0d\x0e\x0f"
572 "\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1a\x1b\x1c\x1d\x1e\x1f"
573 "\x7f\x9b"; /* DEL and infamous Meta-ESC :( */
574 static const char ctrlconv[] ALIGN1 =
575 /* '\n': it's a former NUL - subst with '@', not 'J' */
576 "\x40\x41\x42\x43\x44\x45\x46\x47\x48\x49\x40\x4b\x4c\x4d\x4e\x4f"
577 "\x50\x51\x52\x53\x54\x55\x56\x57\x58\x59\x5a\x5b\x5c\x5d\x5e\x5f";
579 static void lineno_str(char *nbuf9, const char *line)
582 if (option_mask32 & FLAG_N) {
586 if (line == empty_line_marker) {
587 memset(nbuf9, ' ', 8);
591 /* Width of 7 preserves tab spacing in the text */
593 n = LINENO(line) + 1;
598 sprintf(nbuf9, fmt, n);
603 #if ENABLE_FEATURE_LESS_REGEXP
604 static void print_found(const char *line)
609 regmatch_t match_structs;
613 const char *str = line;
618 n = strcspn(str, controls);
625 n = strspn(str, controls);
632 /* buf[] holds quarantined version of str */
634 /* Each part of the line that matches has the HIGHLIGHT
635 and NORMAL escape sequences placed around it.
636 NB: we regex against line, but insert text
637 from quarantined copy (buf[]) */
643 while (match_status == 0) {
644 char *new = xasprintf("%s%.*s"HIGHLIGHT"%.*s"NORMAL,
646 match_structs.rm_so, str,
647 match_structs.rm_eo - match_structs.rm_so,
648 str + match_structs.rm_so);
651 str += match_structs.rm_eo;
652 line += match_structs.rm_eo;
655 /* Most of the time doesn't find the regex, optimize for that */
656 match_status = regexec(&pattern, line, 1, &match_structs, eflags);
657 /* if even "" matches, treat it as "not a match" */
658 if (match_structs.rm_so >= match_structs.rm_eo)
662 lineno_str(nbuf9, line);
664 printf(CLEAR_2_EOL"%s%s\n", nbuf9, str);
667 printf(CLEAR_2_EOL"%s%s%s\n", nbuf9, growline, str);
671 void print_found(const char *line);
674 static void print_ascii(const char *str)
681 lineno_str(nbuf9, str);
682 printf(CLEAR_2_EOL"%s", nbuf9);
685 n = strcspn(str, controls);
688 printf("%.*s", (int) n, str);
691 n = strspn(str, controls);
696 else if (*str == (char)0x9b)
697 /* VT100's CSI, aka Meta-ESC. Who's inventor? */
698 /* I want to know who committed this sin */
701 *p++ = ctrlconv[(unsigned char)*str];
710 /* Print the buffer */
711 static void buffer_print(void)
716 for (i = 0; i <= max_displayed_line; i++)
718 print_found(buffer[i]);
720 print_ascii(buffer[i]);
724 static void buffer_fill_and_print(void)
727 #if ENABLE_FEATURE_LESS_DASHCMD
728 int fpos = cur_fline;
730 if (option_mask32 & FLAG_S) {
731 /* Go back to the beginning of this line */
732 while (fpos && LINENO(flines[fpos]) == LINENO(flines[fpos-1]))
737 while (i <= max_displayed_line && fpos <= max_fline) {
738 int lineno = LINENO(flines[fpos]);
739 buffer[i] = flines[fpos];
743 } while ((fpos <= max_fline)
744 && (option_mask32 & FLAG_S)
745 && lineno == LINENO(flines[fpos])
749 for (i = 0; i <= max_displayed_line && cur_fline + i <= max_fline; i++) {
750 buffer[i] = flines[cur_fline + i];
753 for (; i <= max_displayed_line; i++) {
754 buffer[i] = empty_line_marker;
759 /* Move the buffer up and down in the file in order to scroll */
760 static void buffer_down(int nlines)
764 cap_cur_fline(nlines);
765 buffer_fill_and_print();
768 static void buffer_up(int nlines)
771 if (cur_fline < 0) cur_fline = 0;
773 buffer_fill_and_print();
776 static void buffer_line(int linenum)
782 if (linenum + max_displayed_line > max_fline)
783 linenum = max_fline - max_displayed_line + TILDES;
787 buffer_fill_and_print();
790 static void open_file_and_read_lines(void)
793 int fd = xopen(filename, O_RDONLY);
797 /* "less" with no arguments in argv[] */
798 /* For status line only */
799 filename = xstrdup(bb_msg_standard_input);
808 /* Reinitialize everything for a new file - free the memory and start over */
809 static void reinitialize(void)
814 for (i = 0; i <= max_fline; i++)
815 free(MEMPTR(flines[i]));
823 open_file_and_read_lines();
824 buffer_fill_and_print();
827 static ssize_t getch_nowait(char* input, int sz)
830 struct pollfd pfd[2];
832 pfd[0].fd = STDIN_FILENO;
833 pfd[0].events = POLLIN;
835 pfd[1].events = POLLIN;
837 tcsetattr(kbd_fd, TCSANOW, &term_less);
838 /* NB: select/poll returns whenever read will not block. Therefore:
839 * if eof is reached, select/poll will return immediately
840 * because read will immediately return 0 bytes.
841 * Even if select/poll says that input is available, read CAN block
842 * (switch fd into O_NONBLOCK'ed mode to avoid it)
845 if (max_fline <= cur_fline + max_displayed_line
846 && eof_error > 0 /* did NOT reach eof yet */
848 /* We are interested in stdin */
851 /* position cursor if line input is done */
852 if (less_gets_pos >= 0)
853 move_cursor(max_displayed_line + 2, less_gets_pos + 1);
855 #if ENABLE_FEATURE_LESS_WINCH
858 r = poll(pfd + rd, 2 - rd, -1);
859 if (/*r < 0 && errno == EINTR &&*/ winch_counter) {
860 input[0] = '\\'; /* anything which has no defined function */
866 safe_poll(pfd + rd, 2 - rd, -1);
870 rd = safe_read(kbd_fd, input, sz); /* NB: kbd_fd is in O_NONBLOCK mode */
871 if (rd < 0 && errno == EAGAIN) {
872 /* No keyboard input -> we have input on stdin! */
874 buffer_fill_and_print();
881 /* Grab a character from input without requiring the return key. If the
882 * character is ASCII \033, get more characters and assign certain sequences
883 * special return codes. Note that this function works best with raw input. */
884 static int less_getch(int pos)
886 unsigned char input[16];
891 memset(input, 0, sizeof(input));
892 getch_nowait((char *)input, sizeof(input));
895 /* Detect escape sequences (i.e. arrow keys) and handle
896 * them accordingly */
897 if (input[0] == '\033' && input[1] == '[') {
898 i = input[2] - REAL_KEY_UP;
901 i = input[2] - REAL_PAGE_UP;
904 if (input[2] == REAL_KEY_HOME_XTERM)
906 if (input[2] == REAL_KEY_HOME_ALT)
908 if (input[2] == REAL_KEY_END_XTERM)
910 if (input[2] == REAL_KEY_END_ALT)
914 /* Reject almost all control chars */
916 if (i < ' ' && i != 0x0d && i != 8)
921 static char* less_gets(int sz)
925 char *result = xzalloc(1);
929 less_gets_pos = sz + i;
944 if (i >= width - sz - 1)
945 continue; /* len limit */
948 result = xrealloc(result, i+1);
952 static void examine_file(void)
956 print_statusline("Examine: ");
957 new_fname = less_gets(sizeof("Examine: ") - 1);
964 if (access(new_fname, R_OK) != 0) {
965 print_statusline("Cannot read this file");
969 filename = new_fname;
970 /* files start by = argv. why we assume that argv is infinitely long??
971 files[num_files] = filename;
972 current_file = num_files + 1;
975 num_files = current_file = 1;
979 /* This function changes the file currently being paged. direction can be one of the following:
980 * -1: go back one file
981 * 0: go to the first file
982 * 1: go forward one file */
983 static void change_file(int direction)
985 if (current_file != ((direction > 0) ? num_files : 1)) {
986 current_file = direction ? current_file + direction : 1;
988 filename = xstrdup(files[current_file - 1]);
991 print_statusline(direction > 0 ? "No next file" : "No previous file");
995 static void remove_current_file(void)
1002 if (current_file != 1) {
1004 for (i = 3; i <= num_files; i++)
1005 files[i - 2] = files[i - 1];
1009 for (i = 2; i <= num_files; i++)
1010 files[i - 2] = files[i - 1];
1016 static void colon_process(void)
1020 /* Clear the current line and print a prompt */
1021 print_statusline(" :");
1023 keypress = less_getch(2);
1026 remove_current_file();
1031 #if ENABLE_FEATURE_LESS_FLAGS
1043 less_exit(EXIT_SUCCESS);
1051 #if ENABLE_FEATURE_LESS_REGEXP
1052 static void normalize_match_pos(int match)
1054 if (match >= num_matches)
1055 match = num_matches - 1;
1061 static void goto_match(int match)
1067 /* Try to find next match if eof isn't reached yet */
1068 if (match >= num_matches && eof_error > 0) {
1069 wanted_match = match; /* "I want to read until I see N'th match" */
1073 normalize_match_pos(match);
1074 buffer_line(match_lines[match_pos]);
1076 print_statusline("No matches found");
1080 static void fill_match_lines(unsigned pos)
1084 /* Run the regex on each line of the current file */
1085 while (pos <= max_fline) {
1086 /* If this line matches */
1087 if (regexec(&pattern, flines[pos], 0, NULL, 0) == 0
1088 /* and we didn't match it last time */
1089 && !(num_matches && match_lines[num_matches-1] == pos)
1091 match_lines = xrealloc_vector(match_lines, 4, num_matches);
1092 match_lines[num_matches++] = pos;
1098 static void regex_process(void)
1100 char *uncomp_regex, *err;
1102 /* Reset variables */
1107 if (pattern_valid) {
1112 /* Get the uncompiled regular expression from the user */
1114 bb_putchar((option_mask32 & LESS_STATE_MATCH_BACKWARDS) ? '?' : '/');
1115 uncomp_regex = less_gets(1);
1116 if (!uncomp_regex[0]) {
1122 /* Compile the regex and check for errors */
1123 err = regcomp_or_errmsg(&pattern, uncomp_regex,
1124 (option_mask32 & FLAG_I) ? REG_ICASE : 0);
1127 print_statusline(err);
1134 fill_match_lines(0);
1135 while (match_pos < num_matches) {
1136 if ((int)match_lines[match_pos] > cur_fline)
1140 if (option_mask32 & LESS_STATE_MATCH_BACKWARDS)
1143 /* It's possible that no matches are found yet.
1144 * goto_match() will read input looking for match,
1146 goto_match(match_pos);
1150 static void number_process(int first_digit)
1154 char num_input[sizeof(int)*4]; /* more than enough */
1157 num_input[0] = first_digit;
1159 /* Clear the current line, print a prompt, and then print the digit */
1161 printf(":%c", first_digit);
1163 /* Receive input until a letter is given */
1165 while (i < sizeof(num_input)-1) {
1166 num_input[i] = less_getch(i + 1);
1167 if (!num_input[i] || !isdigit(num_input[i]))
1169 bb_putchar(num_input[i]);
1173 /* Take the final letter out of the digits string */
1174 keypress = num_input[i];
1175 num_input[i] = '\0';
1176 num = bb_strtou(num_input, NULL, 10);
1177 /* on format error, num == -1 */
1178 if (num < 1 || num > MAXLINES) {
1183 /* We now know the number and the letter entered, so we process them */
1185 case KEY_DOWN: case 'z': case 'd': case 'e': case ' ': case '\015':
1188 case KEY_UP: case 'b': case 'w': case 'y': case 'u':
1191 case 'g': case '<': case 'G': case '>':
1192 cur_fline = num + max_displayed_line;
1194 buffer_line(num - 1);
1197 num = num * (max_fline / 100); /* + max_fline / 2; */
1198 cur_fline = num + max_displayed_line;
1202 #if ENABLE_FEATURE_LESS_REGEXP
1204 goto_match(match_pos + num);
1207 option_mask32 &= ~LESS_STATE_MATCH_BACKWARDS;
1211 option_mask32 |= LESS_STATE_MATCH_BACKWARDS;
1218 #if ENABLE_FEATURE_LESS_DASHCMD
1219 static void flag_change(void)
1225 keypress = less_getch(1);
1229 option_mask32 ^= FLAG_M;
1232 option_mask32 ^= FLAG_m;
1235 option_mask32 ^= FLAG_E;
1238 option_mask32 ^= FLAG_TILDE;
1241 option_mask32 ^= FLAG_S;
1242 buffer_fill_and_print();
1244 #if ENABLE_FEATURE_LESS_LINENUMS
1246 option_mask32 ^= FLAG_N;
1248 buffer_fill_and_print();
1254 static void show_flag_status(void)
1261 keypress = less_getch(1);
1265 flag_val = option_mask32 & FLAG_M;
1268 flag_val = option_mask32 & FLAG_m;
1271 flag_val = option_mask32 & FLAG_TILDE;
1274 flag_val = option_mask32 & FLAG_N;
1277 flag_val = option_mask32 & FLAG_E;
1285 printf(HIGHLIGHT"The status of the flag is: %u"NORMAL, flag_val != 0);
1289 static void save_input_to_file(void)
1291 const char *msg = "";
1296 print_statusline("Log file: ");
1297 current_line = less_gets(sizeof("Log file: ")-1);
1298 if (current_line[0]) {
1299 fp = fopen_for_write(current_line);
1301 msg = "Error opening log file";
1304 for (i = 0; i <= max_fline; i++)
1305 fprintf(fp, "%s\n", flines[i]);
1310 print_statusline(msg);
1314 #if ENABLE_FEATURE_LESS_MARKS
1315 static void add_mark(void)
1319 print_statusline("Mark: ");
1320 letter = less_getch(sizeof("Mark: ") - 1);
1322 if (isalpha(letter)) {
1323 /* If we exceed 15 marks, start overwriting previous ones */
1324 if (num_marks == 14)
1327 mark_lines[num_marks][0] = letter;
1328 mark_lines[num_marks][1] = cur_fline;
1331 print_statusline("Invalid mark letter");
1335 static void goto_mark(void)
1340 print_statusline("Go to mark: ");
1341 letter = less_getch(sizeof("Go to mark: ") - 1);
1344 if (isalpha(letter)) {
1345 for (i = 0; i <= num_marks; i++)
1346 if (letter == mark_lines[i][0]) {
1347 buffer_line(mark_lines[i][1]);
1350 if (num_marks == 14 && letter != mark_lines[14][0])
1351 print_statusline("Mark not set");
1353 print_statusline("Invalid mark letter");
1357 #if ENABLE_FEATURE_LESS_BRACKETS
1358 static char opp_bracket(char bracket)
1361 case '{': case '[': /* '}' == '{' + 2. Same for '[' */
1363 case '(': /* ')' == '(' + 1 */
1375 static void match_right_bracket(char bracket)
1379 if (strchr(flines[cur_fline], bracket) == NULL) {
1380 print_statusline("No bracket in top line");
1383 bracket = opp_bracket(bracket);
1384 for (i = cur_fline + 1; i < max_fline; i++) {
1385 if (strchr(flines[i], bracket) != NULL) {
1390 print_statusline("No matching bracket found");
1393 static void match_left_bracket(char bracket)
1397 if (strchr(flines[cur_fline + max_displayed_line], bracket) == NULL) {
1398 print_statusline("No bracket in bottom line");
1402 bracket = opp_bracket(bracket);
1403 for (i = cur_fline + max_displayed_line; i >= 0; i--) {
1404 if (strchr(flines[i], bracket) != NULL) {
1409 print_statusline("No matching bracket found");
1411 #endif /* FEATURE_LESS_BRACKETS */
1413 static void keypress_process(int keypress)
1416 case KEY_DOWN: case 'e': case 'j': case 0x0d:
1419 case KEY_UP: case 'y': case 'k':
1422 case PAGE_DOWN: case ' ': case 'z': case 'f':
1423 buffer_down(max_displayed_line + 1);
1425 case PAGE_UP: case 'w': case 'b':
1426 buffer_up(max_displayed_line + 1);
1429 buffer_down((max_displayed_line + 1) / 2);
1432 buffer_up((max_displayed_line + 1) / 2);
1434 case KEY_HOME: case 'g': case 'p': case '<': case '%':
1437 case KEY_END: case 'G': case '>':
1438 cur_fline = MAXLINES;
1440 buffer_line(cur_fline);
1443 less_exit(EXIT_SUCCESS);
1445 #if ENABLE_FEATURE_LESS_MARKS
1462 save_input_to_file();
1467 #if ENABLE_FEATURE_LESS_FLAGS
1472 #if ENABLE_FEATURE_LESS_REGEXP
1474 option_mask32 &= ~LESS_STATE_MATCH_BACKWARDS;
1478 goto_match(match_pos + 1);
1481 goto_match(match_pos - 1);
1484 option_mask32 |= LESS_STATE_MATCH_BACKWARDS;
1488 #if ENABLE_FEATURE_LESS_DASHCMD
1497 #if ENABLE_FEATURE_LESS_BRACKETS
1498 case '{': case '(': case '[':
1499 match_right_bracket(keypress);
1501 case '}': case ')': case ']':
1502 match_left_bracket(keypress);
1510 if (isdigit(keypress))
1511 number_process(keypress);
1514 static void sig_catcher(int sig)
1519 #if ENABLE_FEATURE_LESS_WINCH
1520 static void sigwinch_handler(int sig UNUSED_PARAM)
1526 int less_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
1527 int less_main(int argc, char **argv)
1533 /* TODO: -x: do not interpret backspace, -xx: tab also */
1534 /* -xxx: newline also */
1535 /* -w N: assume width N (-xxx -w 32: hex viewer of sorts) */
1536 getopt32(argv, "EMmN~I" USE_FEATURE_LESS_DASHCMD("S"));
1542 /* Another popular pager, most, detects when stdout
1543 * is not a tty and turns into cat. This makes sense. */
1544 if (!isatty(STDOUT_FILENO))
1545 return bb_cat(argv);
1548 if (isatty(STDIN_FILENO)) {
1549 /* Just "less"? No args and no redirection? */
1550 bb_error_msg("missing filename");
1554 filename = xstrdup(files[0]);
1557 if (option_mask32 & FLAG_TILDE)
1558 empty_line_marker = "";
1560 kbd_fd = open(CURRENT_TTY, O_RDONLY);
1562 return bb_cat(argv);
1565 tcgetattr(kbd_fd, &term_orig);
1566 term_less = term_orig;
1567 term_less.c_lflag &= ~(ICANON | ECHO);
1568 term_less.c_iflag &= ~(IXON | ICRNL);
1569 /*term_less.c_oflag &= ~ONLCR;*/
1570 term_less.c_cc[VMIN] = 1;
1571 term_less.c_cc[VTIME] = 0;
1573 get_terminal_width_height(kbd_fd, &width, &max_displayed_line);
1574 /* 20: two tabstops + 4 */
1575 if (width < 20 || max_displayed_line < 3)
1576 return bb_cat(argv);
1577 max_displayed_line -= 2;
1579 /* We want to restore term_orig on exit */
1580 bb_signals(BB_FATAL_SIGS, sig_catcher);
1581 #if ENABLE_FEATURE_LESS_WINCH
1582 signal(SIGWINCH, sigwinch_handler);
1585 buffer = xmalloc((max_displayed_line+1) * sizeof(char *));
1588 #if ENABLE_FEATURE_LESS_WINCH
1589 if (winch_counter) {
1591 get_terminal_width_height(kbd_fd, &width, &max_displayed_line);
1592 /* 20: two tabstops + 4 */
1595 if (max_displayed_line < 3)
1596 max_displayed_line = 3;
1597 max_displayed_line -= 2;
1599 buffer = xmalloc((max_displayed_line+1) * sizeof(char *));
1601 buffer_fill_and_print();
1604 keypress = less_getch(-1); /* -1: do not position cursor */
1605 keypress_process(keypress);
1610 Help text of less version 418 is below.
1611 If you are implementing something, keeping
1612 key and/or command line switch compatibility is a good idea:
1615 SUMMARY OF LESS COMMANDS
1617 Commands marked with * may be preceded by a number, N.
1618 Notes in parentheses indicate the behavior if N is given.
1619 h H Display this help.
1621 ---------------------------------------------------------------------------
1623 e ^E j ^N CR * Forward one line (or N lines).
1624 y ^Y k ^K ^P * Backward one line (or N lines).
1625 f ^F ^V SPACE * Forward one window (or N lines).
1626 b ^B ESC-v * Backward one window (or N lines).
1627 z * Forward one window (and set window to N).
1628 w * Backward one window (and set window to N).
1629 ESC-SPACE * Forward one window, but don't stop at end-of-file.
1630 d ^D * Forward one half-window (and set half-window to N).
1631 u ^U * Backward one half-window (and set half-window to N).
1632 ESC-) RightArrow * Left one half screen width (or N positions).
1633 ESC-( LeftArrow * Right one half screen width (or N positions).
1634 F Forward forever; like "tail -f".
1635 r ^R ^L Repaint screen.
1636 R Repaint screen, discarding buffered input.
1637 ---------------------------------------------------
1638 Default "window" is the screen height.
1639 Default "half-window" is half of the screen height.
1640 ---------------------------------------------------------------------------
1642 /pattern * Search forward for (N-th) matching line.
1643 ?pattern * Search backward for (N-th) matching line.
1644 n * Repeat previous search (for N-th occurrence).
1645 N * Repeat previous search in reverse direction.
1646 ESC-n * Repeat previous search, spanning files.
1647 ESC-N * Repeat previous search, reverse dir. & spanning files.
1648 ESC-u Undo (toggle) search highlighting.
1649 ---------------------------------------------------
1650 Search patterns may be modified by one or more of:
1651 ^N or ! Search for NON-matching lines.
1652 ^E or * Search multiple files (pass thru END OF FILE).
1653 ^F or @ Start search at FIRST file (for /) or last file (for ?).
1654 ^K Highlight matches, but don't move (KEEP position).
1655 ^R Don't use REGULAR EXPRESSIONS.
1656 ---------------------------------------------------------------------------
1658 g < ESC-< * Go to first line in file (or line N).
1659 G > ESC-> * Go to last line in file (or line N).
1660 p % * Go to beginning of file (or N percent into file).
1661 t * Go to the (N-th) next tag.
1662 T * Go to the (N-th) previous tag.
1663 { ( [ * Find close bracket } ) ].
1664 } ) ] * Find open bracket { ( [.
1665 ESC-^F <c1> <c2> * Find close bracket <c2>.
1666 ESC-^B <c1> <c2> * Find open bracket <c1>
1667 ---------------------------------------------------
1668 Each "find close bracket" command goes forward to the close bracket
1669 matching the (N-th) open bracket in the top line.
1670 Each "find open bracket" command goes backward to the open bracket
1671 matching the (N-th) close bracket in the bottom line.
1672 m<letter> Mark the current position with <letter>.
1673 '<letter> Go to a previously marked position.
1674 '' Go to the previous position.
1676 ---------------------------------------------------
1677 A mark is any upper-case or lower-case letter.
1678 Certain marks are predefined:
1679 ^ means beginning of the file
1680 $ means end of the file
1681 ---------------------------------------------------------------------------
1683 :e [file] Examine a new file.
1685 :n * Examine the (N-th) next file from the command line.
1686 :p * Examine the (N-th) previous file from the command line.
1687 :x * Examine the first (or N-th) file from the command line.
1688 :d Delete the current file from the command line list.
1689 = ^G :f Print current file name.
1690 ---------------------------------------------------------------------------
1691 MISCELLANEOUS COMMANDS
1692 -<flag> Toggle a command line option [see OPTIONS below].
1693 --<name> Toggle a command line option, by name.
1694 _<flag> Display the setting of a command line option.
1695 __<name> Display the setting of an option, by name.
1696 +cmd Execute the less cmd each time a new file is examined.
1697 !command Execute the shell command with $SHELL.
1698 |Xcommand Pipe file between current pos & mark X to shell command.
1699 v Edit the current file with $VISUAL or $EDITOR.
1700 V Print version number of "less".
1701 ---------------------------------------------------------------------------
1703 Most options may be changed either on the command line,
1704 or from within less by using the - or -- command.
1705 Options may be given in one of two forms: either a single
1706 character preceded by a -, or a name preceeded by --.
1708 Display help (from command line).
1709 -a ........ --search-skip-screen
1710 Forward search skips current screen.
1711 -b [N] .... --buffers=[N]
1713 -B ........ --auto-buffers
1714 Don't automatically allocate buffers for pipes.
1715 -c ........ --clear-screen
1716 Repaint by clearing rather than scrolling.
1719 -D [xn.n] . --color=xn.n
1720 Set screen colors. (MS-DOS only)
1721 -e -E .... --quit-at-eof --QUIT-AT-EOF
1722 Quit at end of file.
1724 Force open non-regular files.
1725 -F ........ --quit-if-one-screen
1726 Quit if entire file fits on first screen.
1727 -g ........ --hilite-search
1728 Highlight only last match for searches.
1729 -G ........ --HILITE-SEARCH
1730 Don't highlight any matches for searches.
1731 -h [N] .... --max-back-scroll=[N]
1732 Backward scroll limit.
1733 -i ........ --ignore-case
1734 Ignore case in searches that do not contain uppercase.
1735 -I ........ --IGNORE-CASE
1736 Ignore case in all searches.
1737 -j [N] .... --jump-target=[N]
1738 Screen position of target lines.
1739 -J ........ --status-column
1740 Display a status column at left edge of screen.
1741 -k [file] . --lesskey-file=[file]
1743 -L ........ --no-lessopen
1744 Ignore the LESSOPEN environment variable.
1745 -m -M .... --long-prompt --LONG-PROMPT
1747 -n -N .... --line-numbers --LINE-NUMBERS
1748 Don't use line numbers.
1749 -o [file] . --log-file=[file]
1750 Copy to log file (standard input only).
1751 -O [file] . --LOG-FILE=[file]
1752 Copy to log file (unconditionally overwrite).
1753 -p [pattern] --pattern=[pattern]
1754 Start at pattern (from command line).
1755 -P [prompt] --prompt=[prompt]
1757 -q -Q .... --quiet --QUIET --silent --SILENT
1758 Quiet the terminal bell.
1759 -r -R .... --raw-control-chars --RAW-CONTROL-CHARS
1760 Output "raw" control characters.
1761 -s ........ --squeeze-blank-lines
1762 Squeeze multiple blank lines.
1763 -S ........ --chop-long-lines
1765 -t [tag] .. --tag=[tag]
1767 -T [tagsfile] --tag-file=[tagsfile]
1768 Use an alternate tags file.
1769 -u -U .... --underline-special --UNDERLINE-SPECIAL
1770 Change handling of backspaces.
1771 -V ........ --version
1772 Display the version number of "less".
1773 -w ........ --hilite-unread
1774 Highlight first new line after forward-screen.
1775 -W ........ --HILITE-UNREAD
1776 Highlight first new line after any forward movement.
1777 -x [N[,...]] --tabs=[N[,...]]
1779 -X ........ --no-init
1780 Don't use termcap init/deinit strings.
1782 Don't use termcap keypad init/deinit strings.
1783 -y [N] .... --max-forw-scroll=[N]
1784 Forward scroll limit.
1785 -z [N] .... --window=[N]
1787 -" [c[c]] . --quotes=[c[c]]
1788 Set shell quote characters.
1790 Don't display tildes after end of file.
1791 -# [N] .... --shift=[N]
1792 Horizontal scroll amount (0 = one half screen width)
1794 ---------------------------------------------------------------------------
1796 These keys can be used to edit text being entered
1797 on the "command line" at the bottom of the screen.
1798 RightArrow ESC-l Move cursor right one character.
1799 LeftArrow ESC-h Move cursor left one character.
1800 CNTL-RightArrow ESC-RightArrow ESC-w Move cursor right one word.
1801 CNTL-LeftArrow ESC-LeftArrow ESC-b Move cursor left one word.
1802 HOME ESC-0 Move cursor to start of line.
1803 END ESC-$ Move cursor to end of line.
1804 BACKSPACE Delete char to left of cursor.
1805 DELETE ESC-x Delete char under cursor.
1806 CNTL-BACKSPACE ESC-BACKSPACE Delete word to left of cursor.
1807 CNTL-DELETE ESC-DELETE ESC-X Delete word under cursor.
1808 CNTL-U ESC (MS-DOS only) Delete entire line.
1809 UpArrow ESC-k Retrieve previous command line.
1810 DownArrow ESC-j Retrieve next command line.
1811 TAB Complete filename & cycle.
1812 SHIFT-TAB ESC-TAB Complete filename & reverse cycle.
1813 CNTL-L Complete filename, list all.