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 */
102 ssize_t readeof; /* must be signed */
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 int wanted_match; /* signed! */
120 smallint pattern_valid;
123 struct termios term_orig, term_less;
125 #define G (*ptr_to_globals)
126 #define cur_fline (G.cur_fline )
127 #define kbd_fd (G.kbd_fd )
128 #define less_gets_pos (G.less_gets_pos )
129 #define linepos (G.linepos )
130 #define max_displayed_line (G.max_displayed_line)
131 #define max_fline (G.max_fline )
132 #define max_lineno (G.max_lineno )
133 #define width (G.width )
134 #define eof_error (G.eof_error )
135 #define readpos (G.readpos )
136 #define readeof (G.readeof )
137 #define buffer (G.buffer )
138 #define flines (G.flines )
139 #define empty_line_marker (G.empty_line_marker )
140 #define num_files (G.num_files )
141 #define current_file (G.current_file )
142 #define filename (G.filename )
143 #define files (G.files )
144 #define num_marks (G.num_marks )
145 #define mark_lines (G.mark_lines )
146 #if ENABLE_FEATURE_LESS_REGEXP
147 #define match_lines (G.match_lines )
148 #define match_pos (G.match_pos )
149 #define num_matches (G.num_matches )
150 #define wanted_match (G.wanted_match )
151 #define pattern (G.pattern )
152 #define pattern_valid (G.pattern_valid )
154 #define terminated (G.terminated )
155 #define term_orig (G.term_orig )
156 #define term_less (G.term_less )
157 #define INIT_G() do { \
158 SET_PTR_TO_GLOBALS(xzalloc(sizeof(G))); \
159 less_gets_pos = -1; \
160 empty_line_marker = "~"; \
165 USE_FEATURE_LESS_REGEXP(wanted_match = -1;) \
168 /* Reset terminal input to normal */
169 static void set_tty_cooked(void)
172 tcsetattr(kbd_fd, TCSANOW, &term_orig);
175 /* Move the cursor to a position (x,y), where (0,0) is the
176 top-left corner of the console */
177 static void move_cursor(int line, int row)
179 printf("\033[%u;%uH", line, row);
182 static void clear_line(void)
184 printf("\033[%u;0H" CLEAR_2_EOL, max_displayed_line + 2);
187 static void print_hilite(const char *str)
189 printf(HIGHLIGHT"%s"NORMAL, str);
192 static void print_statusline(const char *str)
195 printf(HIGHLIGHT"%.*s"NORMAL, width - 1, str);
198 /* Exit the program gracefully */
199 static void less_exit(int code)
204 kill_myself_with_sig(- code); /* does not return */
208 #if ENABLE_FEATURE_LESS_REGEXP
209 static void fill_match_lines(unsigned pos);
211 #define fill_match_lines(pos) ((void)0)
214 /* Devilishly complex routine.
216 * Has to deal with EOF and EPIPE on input,
217 * with line wrapping, with last line not ending in '\n'
218 * (possibly not ending YET!), with backspace and tabs.
219 * It reads input again if last time we got an EOF (thus supporting
220 * growing files) or EPIPE (watching output of slow process like make).
223 * flines[] - array of lines already read. Linewrap may cause
224 * one source file line to occupy several flines[n].
225 * flines[max_fline] - last line, possibly incomplete.
226 * terminated - 1 if flines[max_fline] is 'terminated'
227 * (if there was '\n' [which isn't stored itself, we just remember
229 * max_lineno - last line's number, this one doesn't increment
230 * on line wrap, only on "real" new lines.
231 * readbuf[0..readeof-1] - small preliminary buffer.
232 * readbuf[readpos] - next character to add to current line.
233 * linepos - screen line position of next char to be read
234 * (takes into account tabs and backspaces)
235 * eof_error - < 0 error, == 0 EOF, > 0 not EOF/error
237 static void read_lines(void)
239 #define readbuf bb_common_bufsiz1
240 char *current_line, *p;
242 char last_terminated = terminated;
243 #if ENABLE_FEATURE_LESS_REGEXP
244 unsigned old_max_fline = max_fline;
245 time_t last_time = 0;
246 unsigned seconds_p1 = 3; /* seconds_to_loop + 1 */
249 if (option_mask32 & FLAG_N)
252 USE_FEATURE_LESS_REGEXP(again0:)
254 p = current_line = xmalloc(w);
255 max_fline += last_terminated;
256 if (!last_terminated) {
257 const char *cp = flines[max_fline];
258 if (option_mask32 & FLAG_N)
260 strcpy(current_line, cp);
261 p += strlen(current_line);
262 free((char*)flines[max_fline]);
263 /* linepos is still valid from previous read_lines() */
268 while (1) { /* read lines until we reach cur_fline or wanted_match */
271 while (1) { /* read chars until we have a line */
273 /* if no unprocessed chars left, eat more */
274 if (readpos >= readeof) {
276 eof_error = safe_read(STDIN_FILENO, readbuf, sizeof(readbuf));
283 c = readbuf[readpos];
284 /* backspace? [needed for manpages] */
285 /* <tab><bs> is (a) insane and */
286 /* (b) harder to do correctly, so we refuse to do it */
287 if (c == '\x8' && linepos && p[-1] != '\t') {
288 readpos++; /* eat it */
290 /* was buggy (p could end up <= current_line)... */
295 size_t new_linepos = linepos + 1;
300 if ((int)new_linepos >= w)
302 linepos = new_linepos;
304 /* ok, we will eat this char */
311 /* NUL is substituted by '\n'! */
312 if (c == '\0') c = '\n';
315 } /* end of "read chars until we have a line" loop */
316 /* Corner case: linewrap with only "" wrapping to next line */
317 /* Looks ugly on screen, so we do not store this empty line */
318 if (!last_terminated && !current_line[0]) {
324 last_terminated = terminated;
325 flines = xrealloc_vector(flines, 8, max_fline);
326 if (option_mask32 & FLAG_N) {
327 /* Width of 7 preserves tab spacing in the text */
328 flines[max_fline] = xasprintf(
329 (max_lineno <= 9999999) ? "%7u %s" : "%07u %s",
330 max_lineno % 10000000, current_line);
335 flines[max_fline] = xrealloc(current_line, strlen(current_line) + 1);
337 if (max_fline >= MAXLINES) {
338 eof_error = 0; /* Pretend we saw EOF */
341 if (max_fline > cur_fline + max_displayed_line) {
342 #if !ENABLE_FEATURE_LESS_REGEXP
345 if (wanted_match >= num_matches) { /* goto_match called us */
346 fill_match_lines(old_max_fline);
347 old_max_fline = max_fline;
349 if (wanted_match < num_matches)
353 if (eof_error <= 0) {
355 if (errno == EAGAIN) {
356 /* not yet eof or error, reset flag (or else
357 * we will hog CPU - select() will return
361 print_statusline("read error");
364 #if !ENABLE_FEATURE_LESS_REGEXP
367 if (wanted_match < num_matches) {
369 } else { /* goto_match called us */
370 time_t t = time(NULL);
371 if (t != last_time) {
373 if (--seconds_p1 == 0)
377 goto again0; /* go loop again (max 2 seconds) */
382 current_line = xmalloc(w);
385 } /* end of "read lines until we reach cur_fline" loop */
386 fill_match_lines(old_max_fline);
387 #if ENABLE_FEATURE_LESS_REGEXP
388 /* prevent us from being stuck in search for a match */
394 #if ENABLE_FEATURE_LESS_FLAGS
395 /* Interestingly, writing calc_percent as a function saves around 32 bytes
397 static int calc_percent(void)
399 unsigned p = (100 * (cur_fline+max_displayed_line+1) + max_fline/2) / (max_fline+1);
400 return p <= 100 ? p : 100;
403 /* Print a status line if -M was specified */
404 static void m_status_print(void)
408 if (less_gets_pos >= 0) /* don't touch statusline while input is done! */
412 printf(HIGHLIGHT"%s", filename);
414 printf(" (file %i of %i)", current_file, num_files);
415 printf(" lines %i-%i/%i ",
416 cur_fline + 1, cur_fline + max_displayed_line + 1,
418 if (cur_fline >= (int)(max_fline - max_displayed_line)) {
419 printf("(END)"NORMAL);
420 if (num_files > 1 && current_file != num_files)
421 printf(HIGHLIGHT" - next: %s"NORMAL, files[current_file]);
424 percentage = calc_percent();
425 printf("%i%%"NORMAL, percentage);
429 /* Print the status line */
430 static void status_print(void)
434 if (less_gets_pos >= 0) /* don't touch statusline while input is done! */
437 /* Change the status if flags have been set */
438 #if ENABLE_FEATURE_LESS_FLAGS
439 if (option_mask32 & (FLAG_M|FLAG_m)) {
447 if (cur_fline && cur_fline < (int)(max_fline - max_displayed_line)) {
455 printf(HIGHLIGHT"%s (file %i of %i)"NORMAL,
456 p, current_file, num_files);
462 static void cap_cur_fline(int nlines)
467 if (cur_fline + max_displayed_line > max_fline + TILDES) {
471 diff = max_fline - (cur_fline + max_displayed_line) + TILDES;
472 /* As the number of lines requested was too large, we just move
473 to the end of the file */
479 static const char controls[] ALIGN1 =
480 /* NUL: never encountered; TAB: not converted */
481 /**/"\x01\x02\x03\x04\x05\x06\x07\x08" "\x0a\x0b\x0c\x0d\x0e\x0f"
482 "\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1a\x1b\x1c\x1d\x1e\x1f"
483 "\x7f\x9b"; /* DEL and infamous Meta-ESC :( */
484 static const char ctrlconv[] ALIGN1 =
485 /* '\n': it's a former NUL - subst with '@', not 'J' */
486 "\x40\x41\x42\x43\x44\x45\x46\x47\x48\x49\x40\x4b\x4c\x4d\x4e\x4f"
487 "\x50\x51\x52\x53\x54\x55\x56\x57\x58\x59\x5a\x5b\x5c\x5d\x5e\x5f";
489 #if ENABLE_FEATURE_LESS_REGEXP
490 static void print_found(const char *line)
495 regmatch_t match_structs;
498 const char *str = line;
503 n = strcspn(str, controls);
510 n = strspn(str, controls);
517 /* buf[] holds quarantined version of str */
519 /* Each part of the line that matches has the HIGHLIGHT
520 and NORMAL escape sequences placed around it.
521 NB: we regex against line, but insert text
522 from quarantined copy (buf[]) */
528 while (match_status == 0) {
529 char *new = xasprintf("%s%.*s"HIGHLIGHT"%.*s"NORMAL,
531 match_structs.rm_so, str,
532 match_structs.rm_eo - match_structs.rm_so,
533 str + match_structs.rm_so);
534 free(growline); growline = new;
535 str += match_structs.rm_eo;
536 line += match_structs.rm_eo;
539 /* Most of the time doesn't find the regex, optimize for that */
540 match_status = regexec(&pattern, line, 1, &match_structs, eflags);
541 /* if even "" matches, treat it as "not a match" */
542 if (match_structs.rm_so >= match_structs.rm_eo)
547 printf(CLEAR_2_EOL"%s\n", str);
550 printf(CLEAR_2_EOL"%s%s\n", growline, str);
554 void print_found(const char *line);
557 static void print_ascii(const char *str)
565 n = strcspn(str, controls);
568 printf("%.*s", (int) n, str);
571 n = strspn(str, controls);
576 else if (*str == (char)0x9b)
577 /* VT100's CSI, aka Meta-ESC. Who's inventor? */
578 /* I want to know who committed this sin */
581 *p++ = ctrlconv[(unsigned char)*str];
590 /* Print the buffer */
591 static void buffer_print(void)
596 for (i = 0; i <= max_displayed_line; i++)
598 print_found(buffer[i]);
600 print_ascii(buffer[i]);
604 static void buffer_fill_and_print(void)
607 for (i = 0; i <= max_displayed_line && cur_fline + i <= max_fline; i++) {
608 buffer[i] = flines[cur_fline + i];
610 for (; i <= max_displayed_line; i++) {
611 buffer[i] = empty_line_marker;
616 /* Move the buffer up and down in the file in order to scroll */
617 static void buffer_down(int nlines)
621 cap_cur_fline(nlines);
622 buffer_fill_and_print();
625 static void buffer_up(int nlines)
628 if (cur_fline < 0) cur_fline = 0;
630 buffer_fill_and_print();
633 static void buffer_line(int linenum)
639 if (linenum + max_displayed_line > max_fline)
640 linenum = max_fline - max_displayed_line + TILDES;
644 buffer_fill_and_print();
647 static void open_file_and_read_lines(void)
650 int fd = xopen(filename, O_RDONLY);
654 /* "less" with no arguments in argv[] */
655 /* For status line only */
656 filename = xstrdup(bb_msg_standard_input);
665 /* Reinitialize everything for a new file - free the memory and start over */
666 static void reinitialize(void)
671 for (i = 0; i <= max_fline; i++)
672 free((void*)(flines[i]));
680 open_file_and_read_lines();
681 buffer_fill_and_print();
684 static ssize_t getch_nowait(char* input, int sz)
687 struct pollfd pfd[2];
689 pfd[0].fd = STDIN_FILENO;
690 pfd[0].events = POLLIN;
692 pfd[1].events = POLLIN;
694 tcsetattr(kbd_fd, TCSANOW, &term_less);
695 /* NB: select/poll returns whenever read will not block. Therefore:
696 * if eof is reached, select/poll will return immediately
697 * because read will immediately return 0 bytes.
698 * Even if select/poll says that input is available, read CAN block
699 * (switch fd into O_NONBLOCK'ed mode to avoid it)
702 if (max_fline <= cur_fline + max_displayed_line
703 && eof_error > 0 /* did NOT reach eof yet */
705 /* We are interested in stdin */
708 /* position cursor if line input is done */
709 if (less_gets_pos >= 0)
710 move_cursor(max_displayed_line + 2, less_gets_pos + 1);
712 safe_poll(pfd + rd, 2 - rd, -1);
715 rd = safe_read(kbd_fd, input, sz); /* NB: kbd_fd is in O_NONBLOCK mode */
716 if (rd < 0 && errno == EAGAIN) {
717 /* No keyboard input -> we have input on stdin! */
719 buffer_fill_and_print();
726 /* Grab a character from input without requiring the return key. If the
727 * character is ASCII \033, get more characters and assign certain sequences
728 * special return codes. Note that this function works best with raw input. */
729 static int less_getch(int pos)
731 unsigned char input[16];
736 memset(input, 0, sizeof(input));
737 getch_nowait((char *)input, sizeof(input));
740 /* Detect escape sequences (i.e. arrow keys) and handle
741 * them accordingly */
742 if (input[0] == '\033' && input[1] == '[') {
743 i = input[2] - REAL_KEY_UP;
746 i = input[2] - REAL_PAGE_UP;
749 if (input[2] == REAL_KEY_HOME_XTERM)
751 if (input[2] == REAL_KEY_HOME_ALT)
753 if (input[2] == REAL_KEY_END_XTERM)
755 if (input[2] == REAL_KEY_END_ALT)
759 /* Reject almost all control chars */
761 if (i < ' ' && i != 0x0d && i != 8)
766 static char* less_gets(int sz)
770 char *result = xzalloc(1);
774 less_gets_pos = sz + i;
789 if (i >= width - sz - 1)
790 continue; /* len limit */
793 result = xrealloc(result, i+1);
797 static void examine_file(void)
801 print_statusline("Examine: ");
802 new_fname = less_gets(sizeof("Examine: ") - 1);
809 if (access(new_fname, R_OK) != 0) {
810 print_statusline("Cannot read this file");
814 filename = new_fname;
815 /* files start by = argv. why we assume that argv is infinitely long??
816 files[num_files] = filename;
817 current_file = num_files + 1;
820 num_files = current_file = 1;
824 /* This function changes the file currently being paged. direction can be one of the following:
825 * -1: go back one file
826 * 0: go to the first file
827 * 1: go forward one file */
828 static void change_file(int direction)
830 if (current_file != ((direction > 0) ? num_files : 1)) {
831 current_file = direction ? current_file + direction : 1;
833 filename = xstrdup(files[current_file - 1]);
836 print_statusline(direction > 0 ? "No next file" : "No previous file");
840 static void remove_current_file(void)
847 if (current_file != 1) {
849 for (i = 3; i <= num_files; i++)
850 files[i - 2] = files[i - 1];
854 for (i = 2; i <= num_files; i++)
855 files[i - 2] = files[i - 1];
861 static void colon_process(void)
865 /* Clear the current line and print a prompt */
866 print_statusline(" :");
868 keypress = less_getch(2);
871 remove_current_file();
876 #if ENABLE_FEATURE_LESS_FLAGS
888 less_exit(EXIT_SUCCESS);
896 #if ENABLE_FEATURE_LESS_REGEXP
897 static void normalize_match_pos(int match)
899 if (match >= num_matches)
900 match = num_matches - 1;
906 static void goto_match(int match)
912 /* Try to find next match if eof isn't reached yet */
913 if (match >= num_matches && eof_error > 0) {
914 wanted_match = match; /* "I want to read until I see N'th match" */
918 normalize_match_pos(match);
919 buffer_line(match_lines[match_pos]);
921 print_statusline("No matches found");
925 static void fill_match_lines(unsigned pos)
929 /* Run the regex on each line of the current file */
930 while (pos <= max_fline) {
931 /* If this line matches */
932 if (regexec(&pattern, flines[pos], 0, NULL, 0) == 0
933 /* and we didn't match it last time */
934 && !(num_matches && match_lines[num_matches-1] == pos)
936 match_lines = xrealloc_vector(match_lines, 4, num_matches);
937 match_lines[num_matches++] = pos;
943 static void regex_process(void)
945 char *uncomp_regex, *err;
947 /* Reset variables */
957 /* Get the uncompiled regular expression from the user */
959 bb_putchar((option_mask32 & LESS_STATE_MATCH_BACKWARDS) ? '?' : '/');
960 uncomp_regex = less_gets(1);
961 if (!uncomp_regex[0]) {
967 /* Compile the regex and check for errors */
968 err = regcomp_or_errmsg(&pattern, uncomp_regex, 0);
971 print_statusline(err);
979 while (match_pos < num_matches) {
980 if ((int)match_lines[match_pos] > cur_fline)
984 if (option_mask32 & LESS_STATE_MATCH_BACKWARDS)
987 /* It's possible that no matches are found yet.
988 * goto_match() will read input looking for match,
990 goto_match(match_pos);
994 static void number_process(int first_digit)
998 char num_input[sizeof(int)*4]; /* more than enough */
1001 num_input[0] = first_digit;
1003 /* Clear the current line, print a prompt, and then print the digit */
1005 printf(":%c", first_digit);
1007 /* Receive input until a letter is given */
1009 while (i < sizeof(num_input)-1) {
1010 num_input[i] = less_getch(i + 1);
1011 if (!num_input[i] || !isdigit(num_input[i]))
1013 bb_putchar(num_input[i]);
1017 /* Take the final letter out of the digits string */
1018 keypress = num_input[i];
1019 num_input[i] = '\0';
1020 num = bb_strtou(num_input, NULL, 10);
1021 /* on format error, num == -1 */
1022 if (num < 1 || num > MAXLINES) {
1027 /* We now know the number and the letter entered, so we process them */
1029 case KEY_DOWN: case 'z': case 'd': case 'e': case ' ': case '\015':
1032 case KEY_UP: case 'b': case 'w': case 'y': case 'u':
1035 case 'g': case '<': case 'G': case '>':
1036 cur_fline = num + max_displayed_line;
1038 buffer_line(num - 1);
1041 num = num * (max_fline / 100); /* + max_fline / 2; */
1042 cur_fline = num + max_displayed_line;
1046 #if ENABLE_FEATURE_LESS_REGEXP
1048 goto_match(match_pos + num);
1051 option_mask32 &= ~LESS_STATE_MATCH_BACKWARDS;
1055 option_mask32 |= LESS_STATE_MATCH_BACKWARDS;
1062 #if ENABLE_FEATURE_LESS_FLAGCS
1063 static void flag_change(void)
1069 keypress = less_getch(1);
1073 option_mask32 ^= FLAG_M;
1076 option_mask32 ^= FLAG_m;
1079 option_mask32 ^= FLAG_E;
1082 option_mask32 ^= FLAG_TILDE;
1087 static void show_flag_status(void)
1094 keypress = less_getch(1);
1098 flag_val = option_mask32 & FLAG_M;
1101 flag_val = option_mask32 & FLAG_m;
1104 flag_val = option_mask32 & FLAG_TILDE;
1107 flag_val = option_mask32 & FLAG_N;
1110 flag_val = option_mask32 & FLAG_E;
1118 printf(HIGHLIGHT"The status of the flag is: %u"NORMAL, flag_val != 0);
1122 static void save_input_to_file(void)
1124 const char *msg = "";
1129 print_statusline("Log file: ");
1130 current_line = less_gets(sizeof("Log file: ")-1);
1131 if (current_line[0]) {
1132 fp = fopen_for_write(current_line);
1134 msg = "Error opening log file";
1137 for (i = 0; i <= max_fline; i++)
1138 fprintf(fp, "%s\n", flines[i]);
1143 print_statusline(msg);
1147 #if ENABLE_FEATURE_LESS_MARKS
1148 static void add_mark(void)
1152 print_statusline("Mark: ");
1153 letter = less_getch(sizeof("Mark: ") - 1);
1155 if (isalpha(letter)) {
1156 /* If we exceed 15 marks, start overwriting previous ones */
1157 if (num_marks == 14)
1160 mark_lines[num_marks][0] = letter;
1161 mark_lines[num_marks][1] = cur_fline;
1164 print_statusline("Invalid mark letter");
1168 static void goto_mark(void)
1173 print_statusline("Go to mark: ");
1174 letter = less_getch(sizeof("Go to mark: ") - 1);
1177 if (isalpha(letter)) {
1178 for (i = 0; i <= num_marks; i++)
1179 if (letter == mark_lines[i][0]) {
1180 buffer_line(mark_lines[i][1]);
1183 if (num_marks == 14 && letter != mark_lines[14][0])
1184 print_statusline("Mark not set");
1186 print_statusline("Invalid mark letter");
1190 #if ENABLE_FEATURE_LESS_BRACKETS
1191 static char opp_bracket(char bracket)
1194 case '{': case '[': /* '}' == '{' + 2. Same for '[' */
1196 case '(': /* ')' == '(' + 1 */
1208 static void match_right_bracket(char bracket)
1212 if (strchr(flines[cur_fline], bracket) == NULL) {
1213 print_statusline("No bracket in top line");
1216 bracket = opp_bracket(bracket);
1217 for (i = cur_fline + 1; i < max_fline; i++) {
1218 if (strchr(flines[i], bracket) != NULL) {
1223 print_statusline("No matching bracket found");
1226 static void match_left_bracket(char bracket)
1230 if (strchr(flines[cur_fline + max_displayed_line], bracket) == NULL) {
1231 print_statusline("No bracket in bottom line");
1235 bracket = opp_bracket(bracket);
1236 for (i = cur_fline + max_displayed_line; i >= 0; i--) {
1237 if (strchr(flines[i], bracket) != NULL) {
1242 print_statusline("No matching bracket found");
1244 #endif /* FEATURE_LESS_BRACKETS */
1246 static void keypress_process(int keypress)
1249 case KEY_DOWN: case 'e': case 'j': case 0x0d:
1252 case KEY_UP: case 'y': case 'k':
1255 case PAGE_DOWN: case ' ': case 'z': case 'f':
1256 buffer_down(max_displayed_line + 1);
1258 case PAGE_UP: case 'w': case 'b':
1259 buffer_up(max_displayed_line + 1);
1262 buffer_down((max_displayed_line + 1) / 2);
1265 buffer_up((max_displayed_line + 1) / 2);
1267 case KEY_HOME: case 'g': case 'p': case '<': case '%':
1270 case KEY_END: case 'G': case '>':
1271 cur_fline = MAXLINES;
1273 buffer_line(cur_fline);
1276 less_exit(EXIT_SUCCESS);
1278 #if ENABLE_FEATURE_LESS_MARKS
1295 save_input_to_file();
1300 #if ENABLE_FEATURE_LESS_FLAGS
1305 #if ENABLE_FEATURE_LESS_REGEXP
1307 option_mask32 &= ~LESS_STATE_MATCH_BACKWARDS;
1311 goto_match(match_pos + 1);
1314 goto_match(match_pos - 1);
1317 option_mask32 |= LESS_STATE_MATCH_BACKWARDS;
1321 #if ENABLE_FEATURE_LESS_FLAGCS
1330 #if ENABLE_FEATURE_LESS_BRACKETS
1331 case '{': case '(': case '[':
1332 match_right_bracket(keypress);
1334 case '}': case ')': case ']':
1335 match_left_bracket(keypress);
1343 if (isdigit(keypress))
1344 number_process(keypress);
1347 static void sig_catcher(int sig)
1352 int less_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
1353 int less_main(int argc, char **argv)
1359 /* TODO: -x: do not interpret backspace, -xx: tab also */
1360 /* -xxx: newline also */
1361 /* -w N: assume width N (-xxx -w 32: hex viewer of sorts) */
1362 getopt32(argv, "EMmN~");
1368 /* Another popular pager, most, detects when stdout
1369 * is not a tty and turns into cat. This makes sense. */
1370 if (!isatty(STDOUT_FILENO))
1371 return bb_cat(argv);
1372 kbd_fd = open(CURRENT_TTY, O_RDONLY);
1374 return bb_cat(argv);
1378 if (isatty(STDIN_FILENO)) {
1379 /* Just "less"? No args and no redirection? */
1380 bb_error_msg("missing filename");
1384 filename = xstrdup(files[0]);
1386 get_terminal_width_height(kbd_fd, &width, &max_displayed_line);
1387 /* 20: two tabstops + 4 */
1388 if (width < 20 || max_displayed_line < 3)
1389 return bb_cat(argv);
1390 max_displayed_line -= 2;
1392 buffer = xmalloc((max_displayed_line+1) * sizeof(char *));
1393 if (option_mask32 & FLAG_TILDE)
1394 empty_line_marker = "";
1396 tcgetattr(kbd_fd, &term_orig);
1397 term_less = term_orig;
1398 term_less.c_lflag &= ~(ICANON | ECHO);
1399 term_less.c_iflag &= ~(IXON | ICRNL);
1400 /*term_less.c_oflag &= ~ONLCR;*/
1401 term_less.c_cc[VMIN] = 1;
1402 term_less.c_cc[VTIME] = 0;
1404 /* We want to restore term_orig on exit */
1405 bb_signals(BB_FATAL_SIGS, sig_catcher);
1409 keypress = less_getch(-1); /* -1: do not position cursor */
1410 keypress_process(keypress);