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 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)
175 /* TODO: We really should save the terminal state when we start,
176 * and restore it when we exit. Less does this with the
177 * "ti" and "te" termcap commands; can this be done with
180 fflush_stdout_and_exit(code);
183 /* Move the cursor to a position (x,y), where (0,0) is the
184 top-left corner of the console */
185 static void move_cursor(int line, int row)
187 printf("\033[%u;%uH", line, row);
190 static void clear_line(void)
192 printf("\033[%u;0H" CLEAR_2_EOL, max_displayed_line + 2);
195 static void print_hilite(const char *str)
197 printf(HIGHLIGHT"%s"NORMAL, str);
200 static void print_statusline(const char *str)
203 printf(HIGHLIGHT"%.*s"NORMAL, width - 1, str);
206 #if ENABLE_FEATURE_LESS_REGEXP
207 static void fill_match_lines(unsigned pos);
209 #define fill_match_lines(pos) ((void)0)
212 /* Devilishly complex routine.
214 * Has to deal with EOF and EPIPE on input,
215 * with line wrapping, with last line not ending in '\n'
216 * (possibly not ending YET!), with backspace and tabs.
217 * It reads input again if last time we got an EOF (thus supporting
218 * growing files) or EPIPE (watching output of slow process like make).
221 * flines[] - array of lines already read. Linewrap may cause
222 * one source file line to occupy several flines[n].
223 * flines[max_fline] - last line, possibly incomplete.
224 * terminated - 1 if flines[max_fline] is 'terminated'
225 * (if there was '\n' [which isn't stored itself, we just remember
227 * max_lineno - last line's number, this one doesn't increment
228 * on line wrap, only on "real" new lines.
229 * readbuf[0..readeof-1] - small preliminary buffer.
230 * readbuf[readpos] - next character to add to current line.
231 * linepos - screen line position of next char to be read
232 * (takes into account tabs and backspaces)
233 * eof_error - < 0 error, == 0 EOF, > 0 not EOF/error
235 static void read_lines(void)
237 #define readbuf bb_common_bufsiz1
238 char *current_line, *p;
239 USE_FEATURE_LESS_REGEXP(unsigned old_max_fline = max_fline;)
241 char last_terminated = terminated;
243 if (option_mask32 & FLAG_N)
246 current_line = xmalloc(w);
248 max_fline += last_terminated;
249 if (!last_terminated) {
250 const char *cp = flines[max_fline];
251 if (option_mask32 & FLAG_N)
253 strcpy(current_line, cp);
254 p += strlen(current_line);
255 /* linepos is still valid from previous read_lines() */
266 /* if no unprocessed chars left, eat more */
267 if (readpos >= readeof) {
268 smallint yielded = 0;
272 eof_error = safe_read(0, readbuf, sizeof(readbuf));
276 if (errno == EAGAIN && !yielded) {
277 /* We can hit EAGAIN while searching for regexp match.
278 * Yield is not 100% reliable solution in general,
279 * but for less it should be good enough -
280 * we give stdin supplier some CPU time to produce
281 * more input. We do it just once.
282 * Currently, we do not stop when we found the Nth
283 * occurrence we were looking for. We read till end
284 * (or double EAGAIN). TODO? */
291 print_statusline("read error");
295 if (eof_error <= 0) {
299 c = readbuf[readpos];
300 /* backspace? [needed for manpages] */
301 /* <tab><bs> is (a) insane and */
302 /* (b) harder to do correctly, so we refuse to do it */
303 if (c == '\x8' && linepos && p[-1] != '\t') {
304 readpos++; /* eat it */
306 /* was buggy (p could end up <= current_line)... */
311 size_t new_linepos = linepos + 1;
316 if (new_linepos >= w)
318 linepos = new_linepos;
320 /* ok, we will eat this char */
327 /* NUL is substituted by '\n'! */
328 if (c == '\0') c = '\n';
332 /* Corner case: linewrap with only "" wrapping to next line */
333 /* Looks ugly on screen, so we do not store this empty line */
334 if (!last_terminated && !current_line[0]) {
340 last_terminated = terminated;
341 flines = xrealloc(flines, (max_fline+1) * sizeof(char *));
342 if (option_mask32 & FLAG_N) {
343 /* Width of 7 preserves tab spacing in the text */
344 flines[max_fline] = xasprintf(
345 (max_lineno <= 9999999) ? "%7u %s" : "%07u %s",
346 max_lineno % 10000000, current_line);
351 flines[max_fline] = xrealloc(current_line, strlen(current_line)+1);
353 if (max_fline >= MAXLINES) {
354 eof_error = 0; /* Pretend we saw EOF */
357 if (max_fline > cur_fline + max_displayed_line)
359 if (eof_error <= 0) {
360 if (eof_error < 0 && errno == EAGAIN) {
361 /* not yet eof or error, reset flag (or else
362 * we will hog CPU - select() will return
369 current_line = xmalloc(w);
373 fill_match_lines(old_max_fline);
377 #if ENABLE_FEATURE_LESS_FLAGS
378 /* Interestingly, writing calc_percent as a function saves around 32 bytes
380 static int calc_percent(void)
382 unsigned p = (100 * (cur_fline+max_displayed_line+1) + max_fline/2) / (max_fline+1);
383 return p <= 100 ? p : 100;
386 /* Print a status line if -M was specified */
387 static void m_status_print(void)
391 if (less_gets_pos >= 0) /* don't touch statusline while input is done! */
395 printf(HIGHLIGHT"%s", filename);
397 printf(" (file %i of %i)", current_file, num_files);
398 printf(" lines %i-%i/%i ",
399 cur_fline + 1, cur_fline + max_displayed_line + 1,
401 if (cur_fline >= max_fline - max_displayed_line) {
402 printf("(END)"NORMAL);
403 if (num_files > 1 && current_file != num_files)
404 printf(HIGHLIGHT" - next: %s"NORMAL, files[current_file]);
407 percentage = calc_percent();
408 printf("%i%%"NORMAL, percentage);
412 /* Print the status line */
413 static void status_print(void)
417 if (less_gets_pos >= 0) /* don't touch statusline while input is done! */
420 /* Change the status if flags have been set */
421 #if ENABLE_FEATURE_LESS_FLAGS
422 if (option_mask32 & (FLAG_M|FLAG_m)) {
430 if (cur_fline && cur_fline < max_fline - max_displayed_line) {
438 printf(HIGHLIGHT"%s (file %i of %i)"NORMAL,
439 p, current_file, num_files);
445 static void cap_cur_fline(int nlines)
450 if (cur_fline + max_displayed_line > max_fline + TILDES) {
454 diff = max_fline - (cur_fline + max_displayed_line) + TILDES;
455 /* As the number of lines requested was too large, we just move
456 to the end of the file */
462 static const char controls[] ALIGN1 =
463 /* NUL: never encountered; TAB: not converted */
464 /**/"\x01\x02\x03\x04\x05\x06\x07\x08" "\x0a\x0b\x0c\x0d\x0e\x0f"
465 "\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1a\x1b\x1c\x1d\x1e\x1f"
466 "\x7f\x9b"; /* DEL and infamous Meta-ESC :( */
467 static const char ctrlconv[] ALIGN1 =
468 /* '\n': it's a former NUL - subst with '@', not 'J' */
469 "\x40\x41\x42\x43\x44\x45\x46\x47\x48\x49\x40\x4b\x4c\x4d\x4e\x4f"
470 "\x50\x51\x52\x53\x54\x55\x56\x57\x58\x59\x5a\x5b\x5c\x5d\x5e\x5f";
472 #if ENABLE_FEATURE_LESS_REGEXP
473 static void print_found(const char *line)
478 regmatch_t match_structs;
481 const char *str = line;
486 n = strcspn(str, controls);
493 n = strspn(str, controls);
500 /* buf[] holds quarantined version of str */
502 /* Each part of the line that matches has the HIGHLIGHT
503 and NORMAL escape sequences placed around it.
504 NB: we regex against line, but insert text
505 from quarantined copy (buf[]) */
511 while (match_status == 0) {
512 char *new = xasprintf("%s%.*s"HIGHLIGHT"%.*s"NORMAL,
514 match_structs.rm_so, str,
515 match_structs.rm_eo - match_structs.rm_so,
516 str + match_structs.rm_so);
517 free(growline); growline = new;
518 str += match_structs.rm_eo;
519 line += match_structs.rm_eo;
522 /* Most of the time doesn't find the regex, optimize for that */
523 match_status = regexec(&pattern, line, 1, &match_structs, eflags);
527 printf(CLEAR_2_EOL"%s\n", str);
530 printf(CLEAR_2_EOL"%s%s\n", growline, str);
534 void print_found(const char *line);
537 static void print_ascii(const char *str)
545 n = strcspn(str, controls);
548 printf("%.*s", (int) n, str);
551 n = strspn(str, controls);
556 else if (*str == (char)0x9b)
557 /* VT100's CSI, aka Meta-ESC. Who's inventor? */
558 /* I want to know who committed this sin */
561 *p++ = ctrlconv[(unsigned char)*str];
570 /* Print the buffer */
571 static void buffer_print(void)
576 for (i = 0; i <= max_displayed_line; i++)
578 print_found(buffer[i]);
580 print_ascii(buffer[i]);
584 static void buffer_fill_and_print(void)
587 for (i = 0; i <= max_displayed_line && cur_fline + i <= max_fline; i++) {
588 buffer[i] = flines[cur_fline + i];
590 for (; i <= max_displayed_line; i++) {
591 buffer[i] = empty_line_marker;
596 /* Move the buffer up and down in the file in order to scroll */
597 static void buffer_down(int nlines)
601 cap_cur_fline(nlines);
602 buffer_fill_and_print();
605 static void buffer_up(int nlines)
608 if (cur_fline < 0) cur_fline = 0;
610 buffer_fill_and_print();
613 static void buffer_line(int linenum)
619 if (linenum + max_displayed_line > max_fline)
620 linenum = max_fline - max_displayed_line + TILDES;
624 buffer_fill_and_print();
627 static void open_file_and_read_lines(void)
630 int fd = xopen(filename, O_RDONLY);
634 /* "less" with no arguments in argv[] */
635 /* For status line only */
636 filename = xstrdup(bb_msg_standard_input);
645 /* Reinitialize everything for a new file - free the memory and start over */
646 static void reinitialize(void)
651 for (i = 0; i <= max_fline; i++)
652 free((void*)(flines[i]));
660 open_file_and_read_lines();
661 buffer_fill_and_print();
664 static ssize_t getch_nowait(char* input, int sz)
667 struct pollfd pfd[2];
669 pfd[0].fd = STDIN_FILENO;
670 pfd[0].events = POLLIN;
672 pfd[1].events = POLLIN;
674 tcsetattr(kbd_fd, TCSANOW, &term_less);
675 /* NB: select/poll returns whenever read will not block. Therefore:
676 * if eof is reached, select/poll will return immediately
677 * because read will immediately return 0 bytes.
678 * Even if select/poll says that input is available, read CAN block
679 * (switch fd into O_NONBLOCK'ed mode to avoid it)
682 if (max_fline <= cur_fline + max_displayed_line
683 && eof_error > 0 /* did NOT reach eof yet */
685 /* We are interested in stdin */
688 /* position cursor if line input is done */
689 if (less_gets_pos >= 0)
690 move_cursor(max_displayed_line + 2, less_gets_pos + 1);
692 safe_poll(pfd + rd, 2 - rd, -1);
695 rd = safe_read(kbd_fd, input, sz); /* NB: kbd_fd is in O_NONBLOCK mode */
696 if (rd < 0 && errno == EAGAIN) {
697 /* No keyboard input -> we have input on stdin! */
699 buffer_fill_and_print();
706 /* Grab a character from input without requiring the return key. If the
707 * character is ASCII \033, get more characters and assign certain sequences
708 * special return codes. Note that this function works best with raw input. */
709 static int less_getch(int pos)
711 unsigned char input[16];
716 memset(input, 0, sizeof(input));
717 getch_nowait(input, sizeof(input));
720 /* Detect escape sequences (i.e. arrow keys) and handle
721 * them accordingly */
722 if (input[0] == '\033' && input[1] == '[') {
723 i = input[2] - REAL_KEY_UP;
726 i = input[2] - REAL_PAGE_UP;
729 if (input[2] == REAL_KEY_HOME_XTERM)
731 if (input[2] == REAL_KEY_HOME_ALT)
733 if (input[2] == REAL_KEY_END_XTERM)
735 if (input[2] == REAL_KEY_END_ALT)
739 /* Reject almost all control chars */
741 if (i < ' ' && i != 0x0d && i != 8)
746 static char* less_gets(int sz)
750 char *result = xzalloc(1);
754 less_gets_pos = sz + i;
769 if (i >= width - sz - 1)
770 continue; /* len limit */
773 result = xrealloc(result, i+1);
778 static void examine_file(void)
782 print_statusline("Examine: ");
783 new_fname = less_gets(sizeof("Examine: ") - 1);
790 if (access(new_fname, R_OK) != 0) {
791 print_statusline("Cannot read this file");
795 filename = new_fname;
796 /* files start by = argv. why we assume that argv is infinitely long??
797 files[num_files] = filename;
798 current_file = num_files + 1;
801 num_files = current_file = 1;
805 /* This function changes the file currently being paged. direction can be one of the following:
806 * -1: go back one file
807 * 0: go to the first file
808 * 1: go forward one file */
809 static void change_file(int direction)
811 if (current_file != ((direction > 0) ? num_files : 1)) {
812 current_file = direction ? current_file + direction : 1;
814 filename = xstrdup(files[current_file - 1]);
817 print_statusline(direction > 0 ? "No next file" : "No previous file");
821 static void remove_current_file(void)
828 if (current_file != 1) {
830 for (i = 3; i <= num_files; i++)
831 files[i - 2] = files[i - 1];
835 for (i = 2; i <= num_files; i++)
836 files[i - 2] = files[i - 1];
842 static void colon_process(void)
846 /* Clear the current line and print a prompt */
847 print_statusline(" :");
849 keypress = less_getch(2);
852 remove_current_file();
857 #if ENABLE_FEATURE_LESS_FLAGS
877 #if ENABLE_FEATURE_LESS_REGEXP
878 static void normalize_match_pos(int match)
880 if (match >= num_matches)
881 match = num_matches - 1;
887 static void goto_match(int match)
896 /* Try to find next match if eof isn't reached yet */
897 if (match >= num_matches && eof_error > 0) {
898 cur_fline = MAXLINES; /* look as far as needed */
902 cap_cur_fline(cur_fline);
903 normalize_match_pos(match);
904 buffer_line(match_lines[match_pos]);
907 print_statusline("No matches found");
911 static void fill_match_lines(unsigned pos)
915 /* Run the regex on each line of the current file */
916 while (pos <= max_fline) {
917 /* If this line matches */
918 if (regexec(&pattern, flines[pos], 0, NULL, 0) == 0
919 /* and we didn't match it last time */
920 && !(num_matches && match_lines[num_matches-1] == pos)
922 match_lines = xrealloc(match_lines, (num_matches+1) * sizeof(int));
923 match_lines[num_matches++] = pos;
929 static void regex_process(void)
931 char *uncomp_regex, *err;
933 /* Reset variables */
943 /* Get the uncompiled regular expression from the user */
945 bb_putchar((option_mask32 & LESS_STATE_MATCH_BACKWARDS) ? '?' : '/');
946 uncomp_regex = less_gets(1);
947 if (!uncomp_regex[0]) {
953 /* Compile the regex and check for errors */
954 err = regcomp_or_errmsg(&pattern, uncomp_regex, 0);
957 print_statusline(err);
965 while (match_pos < num_matches) {
966 if (match_lines[match_pos] > cur_fline)
970 if (option_mask32 & LESS_STATE_MATCH_BACKWARDS)
973 /* It's possible that no matches are found yet.
974 * goto_match() will read input looking for match,
976 goto_match(match_pos);
980 static void number_process(int first_digit)
984 char num_input[sizeof(int)*4]; /* more than enough */
987 num_input[0] = first_digit;
989 /* Clear the current line, print a prompt, and then print the digit */
991 printf(":%c", first_digit);
993 /* Receive input until a letter is given */
995 while (i < sizeof(num_input)-1) {
996 num_input[i] = less_getch(i + 1);
997 if (!num_input[i] || !isdigit(num_input[i]))
999 bb_putchar(num_input[i]);
1003 /* Take the final letter out of the digits string */
1004 keypress = num_input[i];
1005 num_input[i] = '\0';
1006 num = bb_strtou(num_input, NULL, 10);
1007 /* on format error, num == -1 */
1008 if (num < 1 || num > MAXLINES) {
1013 /* We now know the number and the letter entered, so we process them */
1015 case KEY_DOWN: case 'z': case 'd': case 'e': case ' ': case '\015':
1018 case KEY_UP: case 'b': case 'w': case 'y': case 'u':
1021 case 'g': case '<': case 'G': case '>':
1022 cur_fline = num + max_displayed_line;
1024 buffer_line(num - 1);
1027 num = num * (max_fline / 100); /* + max_fline / 2; */
1028 cur_fline = num + max_displayed_line;
1032 #if ENABLE_FEATURE_LESS_REGEXP
1034 goto_match(match_pos + num);
1037 option_mask32 &= ~LESS_STATE_MATCH_BACKWARDS;
1041 option_mask32 |= LESS_STATE_MATCH_BACKWARDS;
1048 #if ENABLE_FEATURE_LESS_FLAGCS
1049 static void flag_change(void)
1055 keypress = less_getch(1);
1059 option_mask32 ^= FLAG_M;
1062 option_mask32 ^= FLAG_m;
1065 option_mask32 ^= FLAG_E;
1068 option_mask32 ^= FLAG_TILDE;
1073 static void show_flag_status(void)
1080 keypress = less_getch(1);
1084 flag_val = option_mask32 & FLAG_M;
1087 flag_val = option_mask32 & FLAG_m;
1090 flag_val = option_mask32 & FLAG_TILDE;
1093 flag_val = option_mask32 & FLAG_N;
1096 flag_val = option_mask32 & FLAG_E;
1104 printf(HIGHLIGHT"The status of the flag is: %u"NORMAL, flag_val != 0);
1108 static void save_input_to_file(void)
1110 const char *msg = "";
1115 print_statusline("Log file: ");
1116 current_line = less_gets(sizeof("Log file: ")-1);
1117 if (current_line[0]) {
1118 fp = fopen(current_line, "w");
1120 msg = "Error opening log file";
1123 for (i = 0; i <= max_fline; i++)
1124 fprintf(fp, "%s\n", flines[i]);
1129 print_statusline(msg);
1133 #if ENABLE_FEATURE_LESS_MARKS
1134 static void add_mark(void)
1138 print_statusline("Mark: ");
1139 letter = less_getch(sizeof("Mark: ") - 1);
1141 if (isalpha(letter)) {
1142 /* If we exceed 15 marks, start overwriting previous ones */
1143 if (num_marks == 14)
1146 mark_lines[num_marks][0] = letter;
1147 mark_lines[num_marks][1] = cur_fline;
1150 print_statusline("Invalid mark letter");
1154 static void goto_mark(void)
1159 print_statusline("Go to mark: ");
1160 letter = less_getch(sizeof("Go to mark: ") - 1);
1163 if (isalpha(letter)) {
1164 for (i = 0; i <= num_marks; i++)
1165 if (letter == mark_lines[i][0]) {
1166 buffer_line(mark_lines[i][1]);
1169 if (num_marks == 14 && letter != mark_lines[14][0])
1170 print_statusline("Mark not set");
1172 print_statusline("Invalid mark letter");
1176 #if ENABLE_FEATURE_LESS_BRACKETS
1177 static char opp_bracket(char bracket)
1192 static void match_right_bracket(char bracket)
1194 int bracket_line = -1;
1197 if (strchr(flines[cur_fline], bracket) == NULL) {
1198 print_statusline("No bracket in top line");
1201 for (i = cur_fline + 1; i < max_fline; i++) {
1202 if (strchr(flines[i], opp_bracket(bracket)) != NULL) {
1207 if (bracket_line == -1)
1208 print_statusline("No matching bracket found");
1209 buffer_line(bracket_line - max_displayed_line);
1212 static void match_left_bracket(char bracket)
1214 int bracket_line = -1;
1217 if (strchr(flines[cur_fline + max_displayed_line], bracket) == NULL) {
1218 print_statusline("No bracket in bottom line");
1222 for (i = cur_fline + max_displayed_line; i >= 0; i--) {
1223 if (strchr(flines[i], opp_bracket(bracket)) != NULL) {
1228 if (bracket_line == -1)
1229 print_statusline("No matching bracket found");
1230 buffer_line(bracket_line);
1232 #endif /* FEATURE_LESS_BRACKETS */
1234 static void keypress_process(int keypress)
1237 case KEY_DOWN: case 'e': case 'j': case 0x0d:
1240 case KEY_UP: case 'y': case 'k':
1243 case PAGE_DOWN: case ' ': case 'z': case 'f':
1244 buffer_down(max_displayed_line + 1);
1246 case PAGE_UP: case 'w': case 'b':
1247 buffer_up(max_displayed_line + 1);
1250 buffer_down((max_displayed_line + 1) / 2);
1253 buffer_up((max_displayed_line + 1) / 2);
1255 case KEY_HOME: case 'g': case 'p': case '<': case '%':
1258 case KEY_END: case 'G': case '>':
1259 cur_fline = MAXLINES;
1261 buffer_line(cur_fline);
1266 #if ENABLE_FEATURE_LESS_MARKS
1283 save_input_to_file();
1288 #if ENABLE_FEATURE_LESS_FLAGS
1293 #if ENABLE_FEATURE_LESS_REGEXP
1295 option_mask32 &= ~LESS_STATE_MATCH_BACKWARDS;
1299 goto_match(match_pos + 1);
1302 goto_match(match_pos - 1);
1305 option_mask32 |= LESS_STATE_MATCH_BACKWARDS;
1309 #if ENABLE_FEATURE_LESS_FLAGCS
1318 #if ENABLE_FEATURE_LESS_BRACKETS
1319 case '{': case '(': case '[':
1320 match_right_bracket(keypress);
1322 case '}': case ')': case ']':
1323 match_left_bracket(keypress);
1331 if (isdigit(keypress))
1332 number_process(keypress);
1335 static void sig_catcher(int sig ATTRIBUTE_UNUSED)
1341 int less_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
1342 int less_main(int argc, char **argv)
1348 /* TODO: -x: do not interpret backspace, -xx: tab also */
1349 /* -xxx: newline also */
1350 /* -w N: assume width N (-xxx -w 32: hex viewer of sorts) */
1351 getopt32(argv, "EMmN~");
1357 /* Another popular pager, most, detects when stdout
1358 * is not a tty and turns into cat. This makes sense. */
1359 if (!isatty(STDOUT_FILENO))
1360 return bb_cat(argv);
1361 kbd_fd = open(CURRENT_TTY, O_RDONLY);
1363 return bb_cat(argv);
1367 if (isatty(STDIN_FILENO)) {
1368 /* Just "less"? No args and no redirection? */
1369 bb_error_msg("missing filename");
1373 filename = xstrdup(files[0]);
1375 get_terminal_width_height(kbd_fd, &width, &max_displayed_line);
1376 /* 20: two tabstops + 4 */
1377 if (width < 20 || max_displayed_line < 3)
1378 bb_error_msg_and_die("too narrow here");
1379 max_displayed_line -= 2;
1381 buffer = xmalloc((max_displayed_line+1) * sizeof(char *));
1382 if (option_mask32 & FLAG_TILDE)
1383 empty_line_marker = "";
1385 bb_signals(BB_SIGS_FATAL, sig_catcher);
1387 tcgetattr(kbd_fd, &term_orig);
1388 term_less = term_orig;
1389 term_less.c_lflag &= ~(ICANON | ECHO);
1390 term_less.c_iflag &= ~(IXON | ICRNL);
1391 /*term_less.c_oflag &= ~ONLCR;*/
1392 term_less.c_cc[VMIN] = 1;
1393 term_less.c_cc[VTIME] = 0;
1397 keypress = less_getch(-1); /* -1: do not position cursor */
1398 keypress_process(keypress);