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 */
83 /* hijack command line options variable for internal state vars */
84 LESS_STATE_MATCH_BACKWARDS = 1 << 15,
87 #if !ENABLE_FEATURE_LESS_REGEXP
88 enum { pattern_valid = 0 };
92 int cur_fline; /* signed */
93 int kbd_fd; /* fd to get input from */
95 /* last position in last line, taking into account tabs */
97 unsigned max_displayed_line;
99 unsigned max_lineno; /* this one tracks linewrap */
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_displayed_line (G.max_displayed_line)
132 #define max_fline (G.max_fline )
133 #define max_lineno (G.max_lineno )
134 #define width (G.width )
135 #define eof_error (G.eof_error )
136 #define readpos (G.readpos )
137 #define readeof (G.readeof )
138 #define buffer (G.buffer )
139 #define flines (G.flines )
140 #define empty_line_marker (G.empty_line_marker )
141 #define num_files (G.num_files )
142 #define current_file (G.current_file )
143 #define filename (G.filename )
144 #define files (G.files )
145 #define num_marks (G.num_marks )
146 #define mark_lines (G.mark_lines )
147 #if ENABLE_FEATURE_LESS_REGEXP
148 #define match_lines (G.match_lines )
149 #define match_pos (G.match_pos )
150 #define num_matches (G.num_matches )
151 #define wanted_match (G.wanted_match )
152 #define pattern (G.pattern )
153 #define pattern_valid (G.pattern_valid )
155 #define terminated (G.terminated )
156 #define term_orig (G.term_orig )
157 #define term_less (G.term_less )
158 #define INIT_G() do { \
159 SET_PTR_TO_GLOBALS(xzalloc(sizeof(G))); \
160 less_gets_pos = -1; \
161 empty_line_marker = "~"; \
166 USE_FEATURE_LESS_REGEXP(wanted_match = -1;) \
169 /* Reset terminal input to normal */
170 static void set_tty_cooked(void)
173 tcsetattr(kbd_fd, TCSANOW, &term_orig);
176 /* Move the cursor to a position (x,y), where (0,0) is the
177 top-left corner of the console */
178 static void move_cursor(int line, int row)
180 printf("\033[%u;%uH", line, row);
183 static void clear_line(void)
185 printf("\033[%u;0H" CLEAR_2_EOL, max_displayed_line + 2);
188 static void print_hilite(const char *str)
190 printf(HIGHLIGHT"%s"NORMAL, str);
193 static void print_statusline(const char *str)
196 printf(HIGHLIGHT"%.*s"NORMAL, width - 1, str);
199 /* Exit the program gracefully */
200 static void less_exit(int code)
205 kill_myself_with_sig(- code); /* does not return */
209 #if ENABLE_FEATURE_LESS_REGEXP
210 static void fill_match_lines(unsigned pos);
212 #define fill_match_lines(pos) ((void)0)
215 /* Devilishly complex routine.
217 * Has to deal with EOF and EPIPE on input,
218 * with line wrapping, with last line not ending in '\n'
219 * (possibly not ending YET!), with backspace and tabs.
220 * It reads input again if last time we got an EOF (thus supporting
221 * growing files) or EPIPE (watching output of slow process like make).
224 * flines[] - array of lines already read. Linewrap may cause
225 * one source file line to occupy several flines[n].
226 * flines[max_fline] - last line, possibly incomplete.
227 * terminated - 1 if flines[max_fline] is 'terminated'
228 * (if there was '\n' [which isn't stored itself, we just remember
230 * max_lineno - last line's number, this one doesn't increment
231 * on line wrap, only on "real" new lines.
232 * readbuf[0..readeof-1] - small preliminary buffer.
233 * readbuf[readpos] - next character to add to current line.
234 * linepos - screen line position of next char to be read
235 * (takes into account tabs and backspaces)
236 * eof_error - < 0 error, == 0 EOF, > 0 not EOF/error
238 static void read_lines(void)
240 #define readbuf bb_common_bufsiz1
241 char *current_line, *p;
243 char last_terminated = terminated;
244 #if ENABLE_FEATURE_LESS_REGEXP
245 unsigned old_max_fline = max_fline;
246 time_t last_time = 0;
247 unsigned seconds_p1 = 3; /* seconds_to_loop + 1 */
250 if (option_mask32 & FLAG_N)
253 USE_FEATURE_LESS_REGEXP(again0:)
255 p = current_line = xmalloc(w);
256 max_fline += last_terminated;
257 if (!last_terminated) {
258 const char *cp = flines[max_fline];
259 if (option_mask32 & FLAG_N)
261 strcpy(current_line, cp);
262 p += strlen(current_line);
263 free((char*)flines[max_fline]);
264 /* linepos is still valid from previous read_lines() */
269 while (1) { /* read lines until we reach cur_fline or wanted_match */
272 while (1) { /* read chars until we have a line */
274 /* if no unprocessed chars left, eat more */
275 if (readpos >= readeof) {
277 eof_error = safe_read(STDIN_FILENO, readbuf, sizeof(readbuf));
284 c = readbuf[readpos];
285 /* backspace? [needed for manpages] */
286 /* <tab><bs> is (a) insane and */
287 /* (b) harder to do correctly, so we refuse to do it */
288 if (c == '\x8' && linepos && p[-1] != '\t') {
289 readpos++; /* eat it */
291 /* was buggy (p could end up <= current_line)... */
296 size_t new_linepos = linepos + 1;
301 if ((int)new_linepos >= w)
303 linepos = new_linepos;
305 /* ok, we will eat this char */
312 /* NUL is substituted by '\n'! */
313 if (c == '\0') c = '\n';
316 } /* end of "read chars until we have a line" loop */
317 /* Corner case: linewrap with only "" wrapping to next line */
318 /* Looks ugly on screen, so we do not store this empty line */
319 if (!last_terminated && !current_line[0]) {
325 last_terminated = terminated;
326 flines = xrealloc_vector(flines, 8, max_fline);
327 if (option_mask32 & FLAG_N) {
328 /* Width of 7 preserves tab spacing in the text */
329 flines[max_fline] = xasprintf(
330 (max_lineno <= 9999999) ? "%7u %s" : "%07u %s",
331 max_lineno % 10000000, current_line);
336 flines[max_fline] = xrealloc(current_line, strlen(current_line) + 1);
338 if (max_fline >= MAXLINES) {
339 eof_error = 0; /* Pretend we saw EOF */
342 if (max_fline > cur_fline + max_displayed_line) {
343 #if !ENABLE_FEATURE_LESS_REGEXP
346 if (wanted_match >= num_matches) { /* goto_match called us */
347 fill_match_lines(old_max_fline);
348 old_max_fline = max_fline;
350 if (wanted_match < num_matches)
354 if (eof_error <= 0) {
356 if (errno == EAGAIN) {
357 /* not yet eof or error, reset flag (or else
358 * we will hog CPU - select() will return
362 print_statusline("read error");
365 #if !ENABLE_FEATURE_LESS_REGEXP
368 if (wanted_match < num_matches) {
370 } else { /* goto_match called us */
371 time_t t = time(NULL);
372 if (t != last_time) {
374 if (--seconds_p1 == 0)
378 goto again0; /* go loop again (max 2 seconds) */
383 current_line = xmalloc(w);
386 } /* end of "read lines until we reach cur_fline" loop */
387 fill_match_lines(old_max_fline);
388 #if ENABLE_FEATURE_LESS_REGEXP
389 /* prevent us from being stuck in search for a match */
395 #if ENABLE_FEATURE_LESS_FLAGS
396 /* Interestingly, writing calc_percent as a function saves around 32 bytes
398 static int calc_percent(void)
400 unsigned p = (100 * (cur_fline+max_displayed_line+1) + max_fline/2) / (max_fline+1);
401 return p <= 100 ? p : 100;
404 /* Print a status line if -M was specified */
405 static void m_status_print(void)
409 if (less_gets_pos >= 0) /* don't touch statusline while input is done! */
413 printf(HIGHLIGHT"%s", filename);
415 printf(" (file %i of %i)", current_file, num_files);
416 printf(" lines %i-%i/%i ",
417 cur_fline + 1, cur_fline + max_displayed_line + 1,
419 if (cur_fline >= (int)(max_fline - max_displayed_line)) {
420 printf("(END)"NORMAL);
421 if (num_files > 1 && current_file != num_files)
422 printf(HIGHLIGHT" - next: %s"NORMAL, files[current_file]);
425 percentage = calc_percent();
426 printf("%i%%"NORMAL, percentage);
430 /* Print the status line */
431 static void status_print(void)
435 if (less_gets_pos >= 0) /* don't touch statusline while input is done! */
438 /* Change the status if flags have been set */
439 #if ENABLE_FEATURE_LESS_FLAGS
440 if (option_mask32 & (FLAG_M|FLAG_m)) {
448 if (cur_fline && cur_fline < (int)(max_fline - max_displayed_line)) {
456 printf(HIGHLIGHT"%s (file %i of %i)"NORMAL,
457 p, current_file, num_files);
463 static void cap_cur_fline(int nlines)
468 if (cur_fline + max_displayed_line > max_fline + TILDES) {
472 diff = max_fline - (cur_fline + max_displayed_line) + TILDES;
473 /* As the number of lines requested was too large, we just move
474 to the end of the file */
480 static const char controls[] ALIGN1 =
481 /* NUL: never encountered; TAB: not converted */
482 /**/"\x01\x02\x03\x04\x05\x06\x07\x08" "\x0a\x0b\x0c\x0d\x0e\x0f"
483 "\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1a\x1b\x1c\x1d\x1e\x1f"
484 "\x7f\x9b"; /* DEL and infamous Meta-ESC :( */
485 static const char ctrlconv[] ALIGN1 =
486 /* '\n': it's a former NUL - subst with '@', not 'J' */
487 "\x40\x41\x42\x43\x44\x45\x46\x47\x48\x49\x40\x4b\x4c\x4d\x4e\x4f"
488 "\x50\x51\x52\x53\x54\x55\x56\x57\x58\x59\x5a\x5b\x5c\x5d\x5e\x5f";
490 #if ENABLE_FEATURE_LESS_REGEXP
491 static void print_found(const char *line)
496 regmatch_t match_structs;
499 const char *str = line;
504 n = strcspn(str, controls);
511 n = strspn(str, controls);
518 /* buf[] holds quarantined version of str */
520 /* Each part of the line that matches has the HIGHLIGHT
521 and NORMAL escape sequences placed around it.
522 NB: we regex against line, but insert text
523 from quarantined copy (buf[]) */
529 while (match_status == 0) {
530 char *new = xasprintf("%s%.*s"HIGHLIGHT"%.*s"NORMAL,
532 match_structs.rm_so, str,
533 match_structs.rm_eo - match_structs.rm_so,
534 str + match_structs.rm_so);
535 free(growline); growline = new;
536 str += match_structs.rm_eo;
537 line += match_structs.rm_eo;
540 /* Most of the time doesn't find the regex, optimize for that */
541 match_status = regexec(&pattern, line, 1, &match_structs, eflags);
542 /* if even "" matches, treat it as "not a match" */
543 if (match_structs.rm_so >= match_structs.rm_eo)
548 printf(CLEAR_2_EOL"%s\n", str);
551 printf(CLEAR_2_EOL"%s%s\n", growline, str);
555 void print_found(const char *line);
558 static void print_ascii(const char *str)
566 n = strcspn(str, controls);
569 printf("%.*s", (int) n, str);
572 n = strspn(str, controls);
577 else if (*str == (char)0x9b)
578 /* VT100's CSI, aka Meta-ESC. Who's inventor? */
579 /* I want to know who committed this sin */
582 *p++ = ctrlconv[(unsigned char)*str];
591 /* Print the buffer */
592 static void buffer_print(void)
597 for (i = 0; i <= max_displayed_line; i++)
599 print_found(buffer[i]);
601 print_ascii(buffer[i]);
605 static void buffer_fill_and_print(void)
608 for (i = 0; i <= max_displayed_line && cur_fline + i <= max_fline; i++) {
609 buffer[i] = flines[cur_fline + i];
611 for (; i <= max_displayed_line; i++) {
612 buffer[i] = empty_line_marker;
617 /* Move the buffer up and down in the file in order to scroll */
618 static void buffer_down(int nlines)
622 cap_cur_fline(nlines);
623 buffer_fill_and_print();
626 static void buffer_up(int nlines)
629 if (cur_fline < 0) cur_fline = 0;
631 buffer_fill_and_print();
634 static void buffer_line(int linenum)
640 if (linenum + max_displayed_line > max_fline)
641 linenum = max_fline - max_displayed_line + TILDES;
645 buffer_fill_and_print();
648 static void open_file_and_read_lines(void)
651 int fd = xopen(filename, O_RDONLY);
655 /* "less" with no arguments in argv[] */
656 /* For status line only */
657 filename = xstrdup(bb_msg_standard_input);
666 /* Reinitialize everything for a new file - free the memory and start over */
667 static void reinitialize(void)
672 for (i = 0; i <= max_fline; i++)
673 free((void*)(flines[i]));
681 open_file_and_read_lines();
682 buffer_fill_and_print();
685 static ssize_t getch_nowait(char* input, int sz)
688 struct pollfd pfd[2];
690 pfd[0].fd = STDIN_FILENO;
691 pfd[0].events = POLLIN;
693 pfd[1].events = POLLIN;
695 tcsetattr(kbd_fd, TCSANOW, &term_less);
696 /* NB: select/poll returns whenever read will not block. Therefore:
697 * if eof is reached, select/poll will return immediately
698 * because read will immediately return 0 bytes.
699 * Even if select/poll says that input is available, read CAN block
700 * (switch fd into O_NONBLOCK'ed mode to avoid it)
703 if (max_fline <= cur_fline + max_displayed_line
704 && eof_error > 0 /* did NOT reach eof yet */
706 /* We are interested in stdin */
709 /* position cursor if line input is done */
710 if (less_gets_pos >= 0)
711 move_cursor(max_displayed_line + 2, less_gets_pos + 1);
713 safe_poll(pfd + rd, 2 - rd, -1);
716 rd = safe_read(kbd_fd, input, sz); /* NB: kbd_fd is in O_NONBLOCK mode */
717 if (rd < 0 && errno == EAGAIN) {
718 /* No keyboard input -> we have input on stdin! */
720 buffer_fill_and_print();
727 /* Grab a character from input without requiring the return key. If the
728 * character is ASCII \033, get more characters and assign certain sequences
729 * special return codes. Note that this function works best with raw input. */
730 static int less_getch(int pos)
732 unsigned char input[16];
737 memset(input, 0, sizeof(input));
738 getch_nowait((char *)input, sizeof(input));
741 /* Detect escape sequences (i.e. arrow keys) and handle
742 * them accordingly */
743 if (input[0] == '\033' && input[1] == '[') {
744 i = input[2] - REAL_KEY_UP;
747 i = input[2] - REAL_PAGE_UP;
750 if (input[2] == REAL_KEY_HOME_XTERM)
752 if (input[2] == REAL_KEY_HOME_ALT)
754 if (input[2] == REAL_KEY_END_XTERM)
756 if (input[2] == REAL_KEY_END_ALT)
760 /* Reject almost all control chars */
762 if (i < ' ' && i != 0x0d && i != 8)
767 static char* less_gets(int sz)
771 char *result = xzalloc(1);
775 less_gets_pos = sz + i;
790 if (i >= width - sz - 1)
791 continue; /* len limit */
794 result = xrealloc(result, i+1);
798 static void examine_file(void)
802 print_statusline("Examine: ");
803 new_fname = less_gets(sizeof("Examine: ") - 1);
810 if (access(new_fname, R_OK) != 0) {
811 print_statusline("Cannot read this file");
815 filename = new_fname;
816 /* files start by = argv. why we assume that argv is infinitely long??
817 files[num_files] = filename;
818 current_file = num_files + 1;
821 num_files = current_file = 1;
825 /* This function changes the file currently being paged. direction can be one of the following:
826 * -1: go back one file
827 * 0: go to the first file
828 * 1: go forward one file */
829 static void change_file(int direction)
831 if (current_file != ((direction > 0) ? num_files : 1)) {
832 current_file = direction ? current_file + direction : 1;
834 filename = xstrdup(files[current_file - 1]);
837 print_statusline(direction > 0 ? "No next file" : "No previous file");
841 static void remove_current_file(void)
848 if (current_file != 1) {
850 for (i = 3; i <= num_files; i++)
851 files[i - 2] = files[i - 1];
855 for (i = 2; i <= num_files; i++)
856 files[i - 2] = files[i - 1];
862 static void colon_process(void)
866 /* Clear the current line and print a prompt */
867 print_statusline(" :");
869 keypress = less_getch(2);
872 remove_current_file();
877 #if ENABLE_FEATURE_LESS_FLAGS
889 less_exit(EXIT_SUCCESS);
897 #if ENABLE_FEATURE_LESS_REGEXP
898 static void normalize_match_pos(int match)
900 if (match >= num_matches)
901 match = num_matches - 1;
907 static void goto_match(int match)
913 /* Try to find next match if eof isn't reached yet */
914 if (match >= num_matches && eof_error > 0) {
915 wanted_match = match; /* "I want to read until I see N'th match" */
919 normalize_match_pos(match);
920 buffer_line(match_lines[match_pos]);
922 print_statusline("No matches found");
926 static void fill_match_lines(unsigned pos)
930 /* Run the regex on each line of the current file */
931 while (pos <= max_fline) {
932 /* If this line matches */
933 if (regexec(&pattern, flines[pos], 0, NULL, 0) == 0
934 /* and we didn't match it last time */
935 && !(num_matches && match_lines[num_matches-1] == pos)
937 match_lines = xrealloc_vector(match_lines, 4, num_matches);
938 match_lines[num_matches++] = pos;
944 static void regex_process(void)
946 char *uncomp_regex, *err;
948 /* Reset variables */
958 /* Get the uncompiled regular expression from the user */
960 bb_putchar((option_mask32 & LESS_STATE_MATCH_BACKWARDS) ? '?' : '/');
961 uncomp_regex = less_gets(1);
962 if (!uncomp_regex[0]) {
968 /* Compile the regex and check for errors */
969 err = regcomp_or_errmsg(&pattern, uncomp_regex,
970 option_mask32 & FLAG_I ? REG_ICASE : 0);
973 print_statusline(err);
981 while (match_pos < num_matches) {
982 if ((int)match_lines[match_pos] > cur_fline)
986 if (option_mask32 & LESS_STATE_MATCH_BACKWARDS)
989 /* It's possible that no matches are found yet.
990 * goto_match() will read input looking for match,
992 goto_match(match_pos);
996 static void number_process(int first_digit)
1000 char num_input[sizeof(int)*4]; /* more than enough */
1003 num_input[0] = first_digit;
1005 /* Clear the current line, print a prompt, and then print the digit */
1007 printf(":%c", first_digit);
1009 /* Receive input until a letter is given */
1011 while (i < sizeof(num_input)-1) {
1012 num_input[i] = less_getch(i + 1);
1013 if (!num_input[i] || !isdigit(num_input[i]))
1015 bb_putchar(num_input[i]);
1019 /* Take the final letter out of the digits string */
1020 keypress = num_input[i];
1021 num_input[i] = '\0';
1022 num = bb_strtou(num_input, NULL, 10);
1023 /* on format error, num == -1 */
1024 if (num < 1 || num > MAXLINES) {
1029 /* We now know the number and the letter entered, so we process them */
1031 case KEY_DOWN: case 'z': case 'd': case 'e': case ' ': case '\015':
1034 case KEY_UP: case 'b': case 'w': case 'y': case 'u':
1037 case 'g': case '<': case 'G': case '>':
1038 cur_fline = num + max_displayed_line;
1040 buffer_line(num - 1);
1043 num = num * (max_fline / 100); /* + max_fline / 2; */
1044 cur_fline = num + max_displayed_line;
1048 #if ENABLE_FEATURE_LESS_REGEXP
1050 goto_match(match_pos + num);
1053 option_mask32 &= ~LESS_STATE_MATCH_BACKWARDS;
1057 option_mask32 |= LESS_STATE_MATCH_BACKWARDS;
1064 #if ENABLE_FEATURE_LESS_FLAGCS
1065 static void flag_change(void)
1071 keypress = less_getch(1);
1075 option_mask32 ^= FLAG_M;
1078 option_mask32 ^= FLAG_m;
1081 option_mask32 ^= FLAG_E;
1084 option_mask32 ^= FLAG_TILDE;
1089 static void show_flag_status(void)
1096 keypress = less_getch(1);
1100 flag_val = option_mask32 & FLAG_M;
1103 flag_val = option_mask32 & FLAG_m;
1106 flag_val = option_mask32 & FLAG_TILDE;
1109 flag_val = option_mask32 & FLAG_N;
1112 flag_val = option_mask32 & FLAG_E;
1120 printf(HIGHLIGHT"The status of the flag is: %u"NORMAL, flag_val != 0);
1124 static void save_input_to_file(void)
1126 const char *msg = "";
1131 print_statusline("Log file: ");
1132 current_line = less_gets(sizeof("Log file: ")-1);
1133 if (current_line[0]) {
1134 fp = fopen_for_write(current_line);
1136 msg = "Error opening log file";
1139 for (i = 0; i <= max_fline; i++)
1140 fprintf(fp, "%s\n", flines[i]);
1145 print_statusline(msg);
1149 #if ENABLE_FEATURE_LESS_MARKS
1150 static void add_mark(void)
1154 print_statusline("Mark: ");
1155 letter = less_getch(sizeof("Mark: ") - 1);
1157 if (isalpha(letter)) {
1158 /* If we exceed 15 marks, start overwriting previous ones */
1159 if (num_marks == 14)
1162 mark_lines[num_marks][0] = letter;
1163 mark_lines[num_marks][1] = cur_fline;
1166 print_statusline("Invalid mark letter");
1170 static void goto_mark(void)
1175 print_statusline("Go to mark: ");
1176 letter = less_getch(sizeof("Go to mark: ") - 1);
1179 if (isalpha(letter)) {
1180 for (i = 0; i <= num_marks; i++)
1181 if (letter == mark_lines[i][0]) {
1182 buffer_line(mark_lines[i][1]);
1185 if (num_marks == 14 && letter != mark_lines[14][0])
1186 print_statusline("Mark not set");
1188 print_statusline("Invalid mark letter");
1192 #if ENABLE_FEATURE_LESS_BRACKETS
1193 static char opp_bracket(char bracket)
1196 case '{': case '[': /* '}' == '{' + 2. Same for '[' */
1198 case '(': /* ')' == '(' + 1 */
1210 static void match_right_bracket(char bracket)
1214 if (strchr(flines[cur_fline], bracket) == NULL) {
1215 print_statusline("No bracket in top line");
1218 bracket = opp_bracket(bracket);
1219 for (i = cur_fline + 1; i < max_fline; i++) {
1220 if (strchr(flines[i], bracket) != NULL) {
1225 print_statusline("No matching bracket found");
1228 static void match_left_bracket(char bracket)
1232 if (strchr(flines[cur_fline + max_displayed_line], bracket) == NULL) {
1233 print_statusline("No bracket in bottom line");
1237 bracket = opp_bracket(bracket);
1238 for (i = cur_fline + max_displayed_line; i >= 0; i--) {
1239 if (strchr(flines[i], bracket) != NULL) {
1244 print_statusline("No matching bracket found");
1246 #endif /* FEATURE_LESS_BRACKETS */
1248 static void keypress_process(int keypress)
1251 case KEY_DOWN: case 'e': case 'j': case 0x0d:
1254 case KEY_UP: case 'y': case 'k':
1257 case PAGE_DOWN: case ' ': case 'z': case 'f':
1258 buffer_down(max_displayed_line + 1);
1260 case PAGE_UP: case 'w': case 'b':
1261 buffer_up(max_displayed_line + 1);
1264 buffer_down((max_displayed_line + 1) / 2);
1267 buffer_up((max_displayed_line + 1) / 2);
1269 case KEY_HOME: case 'g': case 'p': case '<': case '%':
1272 case KEY_END: case 'G': case '>':
1273 cur_fline = MAXLINES;
1275 buffer_line(cur_fline);
1278 less_exit(EXIT_SUCCESS);
1280 #if ENABLE_FEATURE_LESS_MARKS
1297 save_input_to_file();
1302 #if ENABLE_FEATURE_LESS_FLAGS
1307 #if ENABLE_FEATURE_LESS_REGEXP
1309 option_mask32 &= ~LESS_STATE_MATCH_BACKWARDS;
1313 goto_match(match_pos + 1);
1316 goto_match(match_pos - 1);
1319 option_mask32 |= LESS_STATE_MATCH_BACKWARDS;
1323 #if ENABLE_FEATURE_LESS_FLAGCS
1332 #if ENABLE_FEATURE_LESS_BRACKETS
1333 case '{': case '(': case '[':
1334 match_right_bracket(keypress);
1336 case '}': case ')': case ']':
1337 match_left_bracket(keypress);
1345 if (isdigit(keypress))
1346 number_process(keypress);
1349 static void sig_catcher(int sig)
1354 int less_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
1355 int less_main(int argc, char **argv)
1361 /* TODO: -x: do not interpret backspace, -xx: tab also */
1362 /* -xxx: newline also */
1363 /* -w N: assume width N (-xxx -w 32: hex viewer of sorts) */
1364 getopt32(argv, "EMmN~I");
1370 /* Another popular pager, most, detects when stdout
1371 * is not a tty and turns into cat. This makes sense. */
1372 if (!isatty(STDOUT_FILENO))
1373 return bb_cat(argv);
1374 kbd_fd = open(CURRENT_TTY, O_RDONLY);
1376 return bb_cat(argv);
1380 if (isatty(STDIN_FILENO)) {
1381 /* Just "less"? No args and no redirection? */
1382 bb_error_msg("missing filename");
1386 filename = xstrdup(files[0]);
1388 get_terminal_width_height(kbd_fd, &width, &max_displayed_line);
1389 /* 20: two tabstops + 4 */
1390 if (width < 20 || max_displayed_line < 3)
1391 return bb_cat(argv);
1392 max_displayed_line -= 2;
1394 buffer = xmalloc((max_displayed_line+1) * sizeof(char *));
1395 if (option_mask32 & FLAG_TILDE)
1396 empty_line_marker = "";
1398 tcgetattr(kbd_fd, &term_orig);
1399 term_less = term_orig;
1400 term_less.c_lflag &= ~(ICANON | ECHO);
1401 term_less.c_iflag &= ~(IXON | ICRNL);
1402 /*term_less.c_oflag &= ~ONLCR;*/
1403 term_less.c_cc[VMIN] = 1;
1404 term_less.c_cc[VTIME] = 0;
1406 /* We want to restore term_orig on exit */
1407 bb_signals(BB_FATAL_SIGS, sig_catcher);
1411 keypress = less_getch(-1); /* -1: do not position cursor */
1412 keypress_process(keypress);