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 /* FIXME: currently doesn't work right */
32 #undef ENABLE_FEATURE_LESS_FLAGCS
33 #define ENABLE_FEATURE_LESS_FLAGCS 0
35 /* The escape codes for highlighted and normal text */
36 #define HIGHLIGHT "\033[7m"
37 #define NORMAL "\033[0m"
38 /* The escape code to clear the screen */
39 #define CLEAR "\033[H\033[J"
40 /* The escape code to clear to end of line */
41 #define CLEAR_2_EOL "\033[K"
43 /* These are the escape sequences corresponding to special keys */
51 REAL_KEY_HOME = '7', // vt100? linux vt? or what?
53 REAL_KEY_HOME_ALT = '1', // ESC [1~ (vt100? linux vt? or what?)
54 REAL_KEY_END_ALT = '4', // ESC [4~
55 REAL_KEY_HOME_XTERM = 'H',
56 REAL_KEY_END_XTERM = 'F',
58 /* These are the special codes assigned by this program to the special keys */
68 /* Absolute max of lines eaten */
69 MAXLINES = CONFIG_FEATURE_LESS_MAXLINES,
71 /* This many "after the end" lines we will show (at max) */
75 /* Command line options */
82 /* hijack command line options variable for internal state vars */
83 LESS_STATE_MATCH_BACKWARDS = 1 << 15,
86 #if !ENABLE_FEATURE_LESS_REGEXP
87 enum { pattern_valid = 0 };
91 int cur_fline; /* signed */
92 int kbd_fd; /* fd to get input from */
94 /* last position in last line, taking into account tabs */
96 unsigned max_displayed_line;
98 unsigned max_lineno; /* this one tracks linewrap */
100 ssize_t eof_error; /* eof if 0, error if < 0 */
105 const char *empty_line_marker;
107 unsigned current_file;
110 #if ENABLE_FEATURE_LESS_MARKS
112 unsigned mark_lines[15][2];
114 #if ENABLE_FEATURE_LESS_REGEXP
115 unsigned *match_lines;
116 int match_pos; /* signed! */
117 unsigned num_matches;
119 smallint pattern_valid;
122 struct termios term_orig, term_less;
124 #define G (*ptr_to_globals)
125 #define cur_fline (G.cur_fline )
126 #define kbd_fd (G.kbd_fd )
127 #define less_gets_pos (G.less_gets_pos )
128 #define linepos (G.linepos )
129 #define max_displayed_line (G.max_displayed_line)
130 #define max_fline (G.max_fline )
131 #define max_lineno (G.max_lineno )
132 #define width (G.width )
133 #define eof_error (G.eof_error )
134 #define readpos (G.readpos )
135 #define readeof (G.readeof )
136 #define buffer (G.buffer )
137 #define flines (G.flines )
138 #define empty_line_marker (G.empty_line_marker )
139 #define num_files (G.num_files )
140 #define current_file (G.current_file )
141 #define filename (G.filename )
142 #define files (G.files )
143 #define num_marks (G.num_marks )
144 #define mark_lines (G.mark_lines )
145 #if ENABLE_FEATURE_LESS_REGEXP
146 #define match_lines (G.match_lines )
147 #define match_pos (G.match_pos )
148 #define num_matches (G.num_matches )
149 #define pattern (G.pattern )
150 #define pattern_valid (G.pattern_valid )
152 #define terminated (G.terminated )
153 #define term_orig (G.term_orig )
154 #define term_less (G.term_less )
155 #define INIT_G() do { \
156 SET_PTR_TO_GLOBALS(xzalloc(sizeof(G))); \
157 less_gets_pos = -1; \
158 empty_line_marker = "~"; \
165 /* Reset terminal input to normal */
166 static void set_tty_cooked(void)
169 tcsetattr(kbd_fd, TCSANOW, &term_orig);
172 /* Exit the program gracefully */
173 static void less_exit(int code)
178 kill_myself_with_sig(- code); /* does not return */
182 /* Move the cursor to a position (x,y), where (0,0) is the
183 top-left corner of the console */
184 static void move_cursor(int line, int row)
186 printf("\033[%u;%uH", line, row);
189 static void clear_line(void)
191 printf("\033[%u;0H" CLEAR_2_EOL, max_displayed_line + 2);
194 static void print_hilite(const char *str)
196 printf(HIGHLIGHT"%s"NORMAL, str);
199 static void print_statusline(const char *str)
202 printf(HIGHLIGHT"%.*s"NORMAL, width - 1, str);
205 #if ENABLE_FEATURE_LESS_REGEXP
206 static void fill_match_lines(unsigned pos);
208 #define fill_match_lines(pos) ((void)0)
211 /* Devilishly complex routine.
213 * Has to deal with EOF and EPIPE on input,
214 * with line wrapping, with last line not ending in '\n'
215 * (possibly not ending YET!), with backspace and tabs.
216 * It reads input again if last time we got an EOF (thus supporting
217 * growing files) or EPIPE (watching output of slow process like make).
220 * flines[] - array of lines already read. Linewrap may cause
221 * one source file line to occupy several flines[n].
222 * flines[max_fline] - last line, possibly incomplete.
223 * terminated - 1 if flines[max_fline] is 'terminated'
224 * (if there was '\n' [which isn't stored itself, we just remember
226 * max_lineno - last line's number, this one doesn't increment
227 * on line wrap, only on "real" new lines.
228 * readbuf[0..readeof-1] - small preliminary buffer.
229 * readbuf[readpos] - next character to add to current line.
230 * linepos - screen line position of next char to be read
231 * (takes into account tabs and backspaces)
232 * eof_error - < 0 error, == 0 EOF, > 0 not EOF/error
234 static void read_lines(void)
236 #define readbuf bb_common_bufsiz1
237 char *current_line, *p;
238 USE_FEATURE_LESS_REGEXP(unsigned old_max_fline = max_fline;)
240 char last_terminated = terminated;
242 if (option_mask32 & FLAG_N)
245 current_line = xmalloc(w);
247 max_fline += last_terminated;
248 if (!last_terminated) {
249 const char *cp = flines[max_fline];
250 if (option_mask32 & FLAG_N)
252 strcpy(current_line, cp);
253 p += strlen(current_line);
254 /* linepos is still valid from previous read_lines() */
265 /* if no unprocessed chars left, eat more */
266 if (readpos >= readeof) {
267 smallint yielded = 0;
271 eof_error = safe_read(0, readbuf, sizeof(readbuf));
275 if (errno == EAGAIN && !yielded) {
276 /* We can hit EAGAIN while searching for regexp match.
277 * Yield is not 100% reliable solution in general,
278 * but for less it should be good enough -
279 * we give stdin supplier some CPU time to produce
280 * more input. We do it just once.
281 * Currently, we do not stop when we found the Nth
282 * occurrence we were looking for. We read till end
283 * (or double EAGAIN). TODO? */
290 print_statusline("read error");
294 if (eof_error <= 0) {
298 c = readbuf[readpos];
299 /* backspace? [needed for manpages] */
300 /* <tab><bs> is (a) insane and */
301 /* (b) harder to do correctly, so we refuse to do it */
302 if (c == '\x8' && linepos && p[-1] != '\t') {
303 readpos++; /* eat it */
305 /* was buggy (p could end up <= current_line)... */
310 size_t new_linepos = linepos + 1;
315 if (new_linepos >= w)
317 linepos = new_linepos;
319 /* ok, we will eat this char */
326 /* NUL is substituted by '\n'! */
327 if (c == '\0') c = '\n';
331 /* Corner case: linewrap with only "" wrapping to next line */
332 /* Looks ugly on screen, so we do not store this empty line */
333 if (!last_terminated && !current_line[0]) {
339 last_terminated = terminated;
340 flines = xrealloc(flines, (max_fline+1) * sizeof(char *));
341 if (option_mask32 & FLAG_N) {
342 /* Width of 7 preserves tab spacing in the text */
343 flines[max_fline] = xasprintf(
344 (max_lineno <= 9999999) ? "%7u %s" : "%07u %s",
345 max_lineno % 10000000, current_line);
350 flines[max_fline] = xrealloc(current_line, strlen(current_line)+1);
352 if (max_fline >= MAXLINES) {
353 eof_error = 0; /* Pretend we saw EOF */
356 if (max_fline > cur_fline + max_displayed_line)
358 if (eof_error <= 0) {
359 if (eof_error < 0 && errno == EAGAIN) {
360 /* not yet eof or error, reset flag (or else
361 * we will hog CPU - select() will return
368 current_line = xmalloc(w);
372 fill_match_lines(old_max_fline);
376 #if ENABLE_FEATURE_LESS_FLAGS
377 /* Interestingly, writing calc_percent as a function saves around 32 bytes
379 static int calc_percent(void)
381 unsigned p = (100 * (cur_fline+max_displayed_line+1) + max_fline/2) / (max_fline+1);
382 return p <= 100 ? p : 100;
385 /* Print a status line if -M was specified */
386 static void m_status_print(void)
390 if (less_gets_pos >= 0) /* don't touch statusline while input is done! */
394 printf(HIGHLIGHT"%s", filename);
396 printf(" (file %i of %i)", current_file, num_files);
397 printf(" lines %i-%i/%i ",
398 cur_fline + 1, cur_fline + max_displayed_line + 1,
400 if (cur_fline >= max_fline - max_displayed_line) {
401 printf("(END)"NORMAL);
402 if (num_files > 1 && current_file != num_files)
403 printf(HIGHLIGHT" - next: %s"NORMAL, files[current_file]);
406 percentage = calc_percent();
407 printf("%i%%"NORMAL, percentage);
411 /* Print the status line */
412 static void status_print(void)
416 if (less_gets_pos >= 0) /* don't touch statusline while input is done! */
419 /* Change the status if flags have been set */
420 #if ENABLE_FEATURE_LESS_FLAGS
421 if (option_mask32 & (FLAG_M|FLAG_m)) {
429 if (cur_fline && cur_fline < max_fline - max_displayed_line) {
437 printf(HIGHLIGHT"%s (file %i of %i)"NORMAL,
438 p, current_file, num_files);
444 static void cap_cur_fline(int nlines)
449 if (cur_fline + max_displayed_line > max_fline + TILDES) {
453 diff = max_fline - (cur_fline + max_displayed_line) + TILDES;
454 /* As the number of lines requested was too large, we just move
455 to the end of the file */
461 static const char controls[] ALIGN1 =
462 /* NUL: never encountered; TAB: not converted */
463 /**/"\x01\x02\x03\x04\x05\x06\x07\x08" "\x0a\x0b\x0c\x0d\x0e\x0f"
464 "\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1a\x1b\x1c\x1d\x1e\x1f"
465 "\x7f\x9b"; /* DEL and infamous Meta-ESC :( */
466 static const char ctrlconv[] ALIGN1 =
467 /* '\n': it's a former NUL - subst with '@', not 'J' */
468 "\x40\x41\x42\x43\x44\x45\x46\x47\x48\x49\x40\x4b\x4c\x4d\x4e\x4f"
469 "\x50\x51\x52\x53\x54\x55\x56\x57\x58\x59\x5a\x5b\x5c\x5d\x5e\x5f";
471 #if ENABLE_FEATURE_LESS_REGEXP
472 static void print_found(const char *line)
477 regmatch_t match_structs;
480 const char *str = line;
485 n = strcspn(str, controls);
492 n = strspn(str, controls);
499 /* buf[] holds quarantined version of str */
501 /* Each part of the line that matches has the HIGHLIGHT
502 and NORMAL escape sequences placed around it.
503 NB: we regex against line, but insert text
504 from quarantined copy (buf[]) */
510 while (match_status == 0) {
511 char *new = xasprintf("%s%.*s"HIGHLIGHT"%.*s"NORMAL,
513 match_structs.rm_so, str,
514 match_structs.rm_eo - match_structs.rm_so,
515 str + match_structs.rm_so);
516 free(growline); growline = new;
517 str += match_structs.rm_eo;
518 line += match_structs.rm_eo;
521 /* Most of the time doesn't find the regex, optimize for that */
522 match_status = regexec(&pattern, line, 1, &match_structs, eflags);
526 printf(CLEAR_2_EOL"%s\n", str);
529 printf(CLEAR_2_EOL"%s%s\n", growline, str);
533 void print_found(const char *line);
536 static void print_ascii(const char *str)
544 n = strcspn(str, controls);
547 printf("%.*s", (int) n, str);
550 n = strspn(str, controls);
555 else if (*str == (char)0x9b)
556 /* VT100's CSI, aka Meta-ESC. Who's inventor? */
557 /* I want to know who committed this sin */
560 *p++ = ctrlconv[(unsigned char)*str];
569 /* Print the buffer */
570 static void buffer_print(void)
575 for (i = 0; i <= max_displayed_line; i++)
577 print_found(buffer[i]);
579 print_ascii(buffer[i]);
583 static void buffer_fill_and_print(void)
586 for (i = 0; i <= max_displayed_line && cur_fline + i <= max_fline; i++) {
587 buffer[i] = flines[cur_fline + i];
589 for (; i <= max_displayed_line; i++) {
590 buffer[i] = empty_line_marker;
595 /* Move the buffer up and down in the file in order to scroll */
596 static void buffer_down(int nlines)
600 cap_cur_fline(nlines);
601 buffer_fill_and_print();
604 static void buffer_up(int nlines)
607 if (cur_fline < 0) cur_fline = 0;
609 buffer_fill_and_print();
612 static void buffer_line(int linenum)
618 if (linenum + max_displayed_line > max_fline)
619 linenum = max_fline - max_displayed_line + TILDES;
623 buffer_fill_and_print();
626 static void open_file_and_read_lines(void)
629 int fd = xopen(filename, O_RDONLY);
633 /* "less" with no arguments in argv[] */
634 /* For status line only */
635 filename = xstrdup(bb_msg_standard_input);
644 /* Reinitialize everything for a new file - free the memory and start over */
645 static void reinitialize(void)
650 for (i = 0; i <= max_fline; i++)
651 free((void*)(flines[i]));
659 open_file_and_read_lines();
660 buffer_fill_and_print();
663 static ssize_t getch_nowait(char* input, int sz)
666 struct pollfd pfd[2];
668 pfd[0].fd = STDIN_FILENO;
669 pfd[0].events = POLLIN;
671 pfd[1].events = POLLIN;
673 tcsetattr(kbd_fd, TCSANOW, &term_less);
674 /* NB: select/poll returns whenever read will not block. Therefore:
675 * if eof is reached, select/poll will return immediately
676 * because read will immediately return 0 bytes.
677 * Even if select/poll says that input is available, read CAN block
678 * (switch fd into O_NONBLOCK'ed mode to avoid it)
681 if (max_fline <= cur_fline + max_displayed_line
682 && eof_error > 0 /* did NOT reach eof yet */
684 /* We are interested in stdin */
687 /* position cursor if line input is done */
688 if (less_gets_pos >= 0)
689 move_cursor(max_displayed_line + 2, less_gets_pos + 1);
691 safe_poll(pfd + rd, 2 - rd, -1);
694 rd = safe_read(kbd_fd, input, sz); /* NB: kbd_fd is in O_NONBLOCK mode */
695 if (rd < 0 && errno == EAGAIN) {
696 /* No keyboard input -> we have input on stdin! */
698 buffer_fill_and_print();
705 /* Grab a character from input without requiring the return key. If the
706 * character is ASCII \033, get more characters and assign certain sequences
707 * special return codes. Note that this function works best with raw input. */
708 static int less_getch(int pos)
710 unsigned char input[16];
715 memset(input, 0, sizeof(input));
716 getch_nowait(input, sizeof(input));
719 /* Detect escape sequences (i.e. arrow keys) and handle
720 * them accordingly */
721 if (input[0] == '\033' && input[1] == '[') {
722 i = input[2] - REAL_KEY_UP;
725 i = input[2] - REAL_PAGE_UP;
728 if (input[2] == REAL_KEY_HOME_XTERM)
730 if (input[2] == REAL_KEY_HOME_ALT)
732 if (input[2] == REAL_KEY_END_XTERM)
734 if (input[2] == REAL_KEY_END_ALT)
738 /* Reject almost all control chars */
740 if (i < ' ' && i != 0x0d && i != 8)
745 static char* less_gets(int sz)
749 char *result = xzalloc(1);
753 less_gets_pos = sz + i;
768 if (i >= width - sz - 1)
769 continue; /* len limit */
772 result = xrealloc(result, i+1);
776 static void examine_file(void)
780 print_statusline("Examine: ");
781 new_fname = less_gets(sizeof("Examine: ") - 1);
788 if (access(new_fname, R_OK) != 0) {
789 print_statusline("Cannot read this file");
793 filename = new_fname;
794 /* files start by = argv. why we assume that argv is infinitely long??
795 files[num_files] = filename;
796 current_file = num_files + 1;
799 num_files = current_file = 1;
803 /* This function changes the file currently being paged. direction can be one of the following:
804 * -1: go back one file
805 * 0: go to the first file
806 * 1: go forward one file */
807 static void change_file(int direction)
809 if (current_file != ((direction > 0) ? num_files : 1)) {
810 current_file = direction ? current_file + direction : 1;
812 filename = xstrdup(files[current_file - 1]);
815 print_statusline(direction > 0 ? "No next file" : "No previous file");
819 static void remove_current_file(void)
826 if (current_file != 1) {
828 for (i = 3; i <= num_files; i++)
829 files[i - 2] = files[i - 1];
833 for (i = 2; i <= num_files; i++)
834 files[i - 2] = files[i - 1];
840 static void colon_process(void)
844 /* Clear the current line and print a prompt */
845 print_statusline(" :");
847 keypress = less_getch(2);
850 remove_current_file();
855 #if ENABLE_FEATURE_LESS_FLAGS
875 #if ENABLE_FEATURE_LESS_REGEXP
876 static void normalize_match_pos(int match)
878 if (match >= num_matches)
879 match = num_matches - 1;
885 static void goto_match(int match)
894 /* Try to find next match if eof isn't reached yet */
895 if (match >= num_matches && eof_error > 0) {
896 cur_fline = MAXLINES; /* look as far as needed */
900 cap_cur_fline(cur_fline);
901 normalize_match_pos(match);
902 buffer_line(match_lines[match_pos]);
905 print_statusline("No matches found");
909 static void fill_match_lines(unsigned pos)
913 /* Run the regex on each line of the current file */
914 while (pos <= max_fline) {
915 /* If this line matches */
916 if (regexec(&pattern, flines[pos], 0, NULL, 0) == 0
917 /* and we didn't match it last time */
918 && !(num_matches && match_lines[num_matches-1] == pos)
920 match_lines = xrealloc(match_lines, (num_matches+1) * sizeof(int));
921 match_lines[num_matches++] = pos;
927 static void regex_process(void)
929 char *uncomp_regex, *err;
931 /* Reset variables */
941 /* Get the uncompiled regular expression from the user */
943 bb_putchar((option_mask32 & LESS_STATE_MATCH_BACKWARDS) ? '?' : '/');
944 uncomp_regex = less_gets(1);
945 if (!uncomp_regex[0]) {
951 /* Compile the regex and check for errors */
952 err = regcomp_or_errmsg(&pattern, uncomp_regex, 0);
955 print_statusline(err);
963 while (match_pos < num_matches) {
964 if (match_lines[match_pos] > cur_fline)
968 if (option_mask32 & LESS_STATE_MATCH_BACKWARDS)
971 /* It's possible that no matches are found yet.
972 * goto_match() will read input looking for match,
974 goto_match(match_pos);
978 static void number_process(int first_digit)
982 char num_input[sizeof(int)*4]; /* more than enough */
985 num_input[0] = first_digit;
987 /* Clear the current line, print a prompt, and then print the digit */
989 printf(":%c", first_digit);
991 /* Receive input until a letter is given */
993 while (i < sizeof(num_input)-1) {
994 num_input[i] = less_getch(i + 1);
995 if (!num_input[i] || !isdigit(num_input[i]))
997 bb_putchar(num_input[i]);
1001 /* Take the final letter out of the digits string */
1002 keypress = num_input[i];
1003 num_input[i] = '\0';
1004 num = bb_strtou(num_input, NULL, 10);
1005 /* on format error, num == -1 */
1006 if (num < 1 || num > MAXLINES) {
1011 /* We now know the number and the letter entered, so we process them */
1013 case KEY_DOWN: case 'z': case 'd': case 'e': case ' ': case '\015':
1016 case KEY_UP: case 'b': case 'w': case 'y': case 'u':
1019 case 'g': case '<': case 'G': case '>':
1020 cur_fline = num + max_displayed_line;
1022 buffer_line(num - 1);
1025 num = num * (max_fline / 100); /* + max_fline / 2; */
1026 cur_fline = num + max_displayed_line;
1030 #if ENABLE_FEATURE_LESS_REGEXP
1032 goto_match(match_pos + num);
1035 option_mask32 &= ~LESS_STATE_MATCH_BACKWARDS;
1039 option_mask32 |= LESS_STATE_MATCH_BACKWARDS;
1046 #if ENABLE_FEATURE_LESS_FLAGCS
1047 static void flag_change(void)
1053 keypress = less_getch(1);
1057 option_mask32 ^= FLAG_M;
1060 option_mask32 ^= FLAG_m;
1063 option_mask32 ^= FLAG_E;
1066 option_mask32 ^= FLAG_TILDE;
1071 static void show_flag_status(void)
1078 keypress = less_getch(1);
1082 flag_val = option_mask32 & FLAG_M;
1085 flag_val = option_mask32 & FLAG_m;
1088 flag_val = option_mask32 & FLAG_TILDE;
1091 flag_val = option_mask32 & FLAG_N;
1094 flag_val = option_mask32 & FLAG_E;
1102 printf(HIGHLIGHT"The status of the flag is: %u"NORMAL, flag_val != 0);
1106 static void save_input_to_file(void)
1108 const char *msg = "";
1113 print_statusline("Log file: ");
1114 current_line = less_gets(sizeof("Log file: ")-1);
1115 if (current_line[0]) {
1116 fp = fopen(current_line, "w");
1118 msg = "Error opening log file";
1121 for (i = 0; i <= max_fline; i++)
1122 fprintf(fp, "%s\n", flines[i]);
1127 print_statusline(msg);
1131 #if ENABLE_FEATURE_LESS_MARKS
1132 static void add_mark(void)
1136 print_statusline("Mark: ");
1137 letter = less_getch(sizeof("Mark: ") - 1);
1139 if (isalpha(letter)) {
1140 /* If we exceed 15 marks, start overwriting previous ones */
1141 if (num_marks == 14)
1144 mark_lines[num_marks][0] = letter;
1145 mark_lines[num_marks][1] = cur_fline;
1148 print_statusline("Invalid mark letter");
1152 static void goto_mark(void)
1157 print_statusline("Go to mark: ");
1158 letter = less_getch(sizeof("Go to mark: ") - 1);
1161 if (isalpha(letter)) {
1162 for (i = 0; i <= num_marks; i++)
1163 if (letter == mark_lines[i][0]) {
1164 buffer_line(mark_lines[i][1]);
1167 if (num_marks == 14 && letter != mark_lines[14][0])
1168 print_statusline("Mark not set");
1170 print_statusline("Invalid mark letter");
1174 #if ENABLE_FEATURE_LESS_BRACKETS
1175 static char opp_bracket(char bracket)
1178 case '{': case '[': /* '}' == '{' + 2. Same for '[' */
1180 case '(': /* ')' == '(' + 1 */
1192 static void match_right_bracket(char bracket)
1196 if (strchr(flines[cur_fline], bracket) == NULL) {
1197 print_statusline("No bracket in top line");
1200 bracket = opp_bracket(bracket);
1201 for (i = cur_fline + 1; i < max_fline; i++) {
1202 if (strchr(flines[i], bracket) != NULL) {
1207 print_statusline("No matching bracket found");
1210 static void match_left_bracket(char bracket)
1214 if (strchr(flines[cur_fline + max_displayed_line], bracket) == NULL) {
1215 print_statusline("No bracket in bottom line");
1219 bracket = opp_bracket(bracket);
1220 for (i = cur_fline + max_displayed_line; i >= 0; i--) {
1221 if (strchr(flines[i], bracket) != NULL) {
1226 print_statusline("No matching bracket found");
1228 #endif /* FEATURE_LESS_BRACKETS */
1230 static void keypress_process(int keypress)
1233 case KEY_DOWN: case 'e': case 'j': case 0x0d:
1236 case KEY_UP: case 'y': case 'k':
1239 case PAGE_DOWN: case ' ': case 'z': case 'f':
1240 buffer_down(max_displayed_line + 1);
1242 case PAGE_UP: case 'w': case 'b':
1243 buffer_up(max_displayed_line + 1);
1246 buffer_down((max_displayed_line + 1) / 2);
1249 buffer_up((max_displayed_line + 1) / 2);
1251 case KEY_HOME: case 'g': case 'p': case '<': case '%':
1254 case KEY_END: case 'G': case '>':
1255 cur_fline = MAXLINES;
1257 buffer_line(cur_fline);
1262 #if ENABLE_FEATURE_LESS_MARKS
1279 save_input_to_file();
1284 #if ENABLE_FEATURE_LESS_FLAGS
1289 #if ENABLE_FEATURE_LESS_REGEXP
1291 option_mask32 &= ~LESS_STATE_MATCH_BACKWARDS;
1295 goto_match(match_pos + 1);
1298 goto_match(match_pos - 1);
1301 option_mask32 |= LESS_STATE_MATCH_BACKWARDS;
1305 #if ENABLE_FEATURE_LESS_FLAGCS
1314 #if ENABLE_FEATURE_LESS_BRACKETS
1315 case '{': case '(': case '[':
1316 match_right_bracket(keypress);
1318 case '}': case ')': case ']':
1319 match_left_bracket(keypress);
1327 if (isdigit(keypress))
1328 number_process(keypress);
1331 static void sig_catcher(int sig)
1336 int less_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
1337 int less_main(int argc, char **argv)
1343 /* TODO: -x: do not interpret backspace, -xx: tab also */
1344 /* -xxx: newline also */
1345 /* -w N: assume width N (-xxx -w 32: hex viewer of sorts) */
1346 getopt32(argv, "EMmN~");
1352 /* Another popular pager, most, detects when stdout
1353 * is not a tty and turns into cat. This makes sense. */
1354 if (!isatty(STDOUT_FILENO))
1355 return bb_cat(argv);
1356 kbd_fd = open(CURRENT_TTY, O_RDONLY);
1358 return bb_cat(argv);
1362 if (isatty(STDIN_FILENO)) {
1363 /* Just "less"? No args and no redirection? */
1364 bb_error_msg("missing filename");
1368 filename = xstrdup(files[0]);
1370 get_terminal_width_height(kbd_fd, &width, &max_displayed_line);
1371 /* 20: two tabstops + 4 */
1372 if (width < 20 || max_displayed_line < 3)
1373 bb_error_msg_and_die("too narrow here");
1374 max_displayed_line -= 2;
1376 buffer = xmalloc((max_displayed_line+1) * sizeof(char *));
1377 if (option_mask32 & FLAG_TILDE)
1378 empty_line_marker = "";
1380 tcgetattr(kbd_fd, &term_orig);
1381 term_less = term_orig;
1382 term_less.c_lflag &= ~(ICANON | ECHO);
1383 term_less.c_iflag &= ~(IXON | ICRNL);
1384 /*term_less.c_oflag &= ~ONLCR;*/
1385 term_less.c_cc[VMIN] = 1;
1386 term_less.c_cc[VTIME] = 0;
1388 /* We want to restore term_orig on exit */
1389 bb_signals(BB_SIGS_FATAL, sig_catcher);
1393 keypress = less_getch(-1); /* -1: do not position cursor */
1394 keypress_process(keypress);