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 */
93 /* last position in last line, taking into account tabs */
95 unsigned max_displayed_line;
97 unsigned max_lineno; /* this one tracks linewrap */
99 ssize_t eof_error; /* eof if 0, error if < 0 */
104 const char *empty_line_marker;
106 unsigned current_file;
109 #if ENABLE_FEATURE_LESS_MARKS
111 unsigned mark_lines[15][2];
113 #if ENABLE_FEATURE_LESS_REGEXP
114 unsigned *match_lines;
115 int match_pos; /* signed! */
116 unsigned num_matches;
118 smallint pattern_valid;
121 struct termios term_orig, term_less;
123 #define G (*ptr_to_globals)
124 #define cur_fline (G.cur_fline )
125 #define kbd_fd (G.kbd_fd )
126 #define linepos (G.linepos )
127 #define max_displayed_line (G.max_displayed_line)
128 #define max_fline (G.max_fline )
129 #define max_lineno (G.max_lineno )
130 #define width (G.width )
131 #define eof_error (G.eof_error )
132 #define readpos (G.readpos )
133 #define readeof (G.readeof )
134 #define buffer (G.buffer )
135 #define flines (G.flines )
136 #define empty_line_marker (G.empty_line_marker )
137 #define num_files (G.num_files )
138 #define current_file (G.current_file )
139 #define filename (G.filename )
140 #define files (G.files )
141 #define num_marks (G.num_marks )
142 #define mark_lines (G.mark_lines )
143 #if ENABLE_FEATURE_LESS_REGEXP
144 #define match_lines (G.match_lines )
145 #define match_pos (G.match_pos )
146 #define num_matches (G.num_matches )
147 #define pattern (G.pattern )
148 #define pattern_valid (G.pattern_valid )
150 #define terminated (G.terminated )
151 #define term_orig (G.term_orig )
152 #define term_less (G.term_less )
153 #define INIT_G() do { \
154 PTR_TO_GLOBALS = xzalloc(sizeof(G)); \
155 empty_line_marker = "~"; \
162 /* Reset terminal input to normal */
163 static void set_tty_cooked(void)
166 tcsetattr(kbd_fd, TCSANOW, &term_orig);
169 /* Exit the program gracefully */
170 static void less_exit(int code)
172 /* TODO: We really should save the terminal state when we start,
173 * and restore it when we exit. Less does this with the
174 * "ti" and "te" termcap commands; can this be done with
177 fflush_stdout_and_exit(code);
180 /* Move the cursor to a position (x,y), where (0,0) is the
181 top-left corner of the console */
182 static void move_cursor(int line, int row)
184 printf("\033[%u;%uH", line, row);
187 static void clear_line(void)
189 printf("\033[%u;0H" CLEAR_2_EOL, max_displayed_line + 2);
192 static void print_hilite(const char *str)
194 printf(HIGHLIGHT"%s"NORMAL, str);
197 static void print_statusline(const char *str)
200 printf(HIGHLIGHT"%.*s"NORMAL, width - 1, str);
203 #if ENABLE_FEATURE_LESS_REGEXP
204 static void fill_match_lines(unsigned pos);
206 #define fill_match_lines(pos) ((void)0)
209 /* Devilishly complex routine.
211 * Has to deal with EOF and EPIPE on input,
212 * with line wrapping, with last line not ending in '\n'
213 * (possibly not ending YET!), with backspace and tabs.
214 * It reads input again if last time we got an EOF (thus supporting
215 * growing files) or EPIPE (watching output of slow process like make).
218 * flines[] - array of lines already read. Linewrap may cause
219 * one source file line to occupy several flines[n].
220 * flines[max_fline] - last line, possibly incomplete.
221 * terminated - 1 if flines[max_fline] is 'terminated'
222 * (if there was '\n' [which isn't stored itself, we just remember
224 * max_lineno - last line's number, this one doesn't increment
225 * on line wrap, only on "real" new lines.
226 * readbuf[0..readeof-1] - small preliminary buffer.
227 * readbuf[readpos] - next character to add to current line.
228 * linepos - screen line position of next char to be read
229 * (takes into account tabs and backspaces)
230 * eof_error - < 0 error, == 0 EOF, > 0 not EOF/error
232 static void read_lines(void)
234 #define readbuf bb_common_bufsiz1
235 char *current_line, *p;
236 USE_FEATURE_LESS_REGEXP(unsigned old_max_fline = max_fline;)
238 char last_terminated = terminated;
240 if (option_mask32 & FLAG_N)
243 current_line = xmalloc(w);
245 max_fline += last_terminated;
246 if (!last_terminated) {
247 const char *cp = flines[max_fline];
248 if (option_mask32 & FLAG_N)
250 strcpy(current_line, cp);
251 p += strlen(current_line);
252 /* linepos is still valid from previous read_lines() */
263 /* if no unprocessed chars left, eat more */
264 if (readpos >= readeof) {
265 smallint yielded = 0;
269 eof_error = safe_read(0, readbuf, sizeof(readbuf));
273 if (errno == EAGAIN && !yielded) {
274 /* We can hit EAGAIN while searching for regexp match.
275 * Yield is not 100% reliable solution in general,
276 * but for less it should be good enough -
277 * we give stdin supplier some CPU time to produce
278 * more input. We do it just once.
279 * Currently, we do not stop when we found the Nth
280 * occurrence we were looking for. We read till end
281 * (or double EAGAIN). TODO? */
288 print_statusline("read error");
292 if (eof_error <= 0) {
296 c = readbuf[readpos];
297 /* backspace? [needed for manpages] */
298 /* <tab><bs> is (a) insane and */
299 /* (b) harder to do correctly, so we refuse to do it */
300 if (c == '\x8' && linepos && p[-1] != '\t') {
301 readpos++; /* eat it */
303 /* was buggy (p could end up <= current_line)... */
308 size_t new_linepos = linepos + 1;
313 if (new_linepos >= w)
315 linepos = new_linepos;
317 /* ok, we will eat this char */
324 /* NUL is substituted by '\n'! */
325 if (c == '\0') c = '\n';
329 /* Corner case: linewrap with only "" wrapping to next line */
330 /* Looks ugly on screen, so we do not store this empty line */
331 if (!last_terminated && !current_line[0]) {
337 last_terminated = terminated;
338 flines = xrealloc(flines, (max_fline+1) * sizeof(char *));
339 if (option_mask32 & FLAG_N) {
340 /* Width of 7 preserves tab spacing in the text */
341 flines[max_fline] = xasprintf(
342 (max_lineno <= 9999999) ? "%7u %s" : "%07u %s",
343 max_lineno % 10000000, current_line);
348 flines[max_fline] = xrealloc(current_line, strlen(current_line)+1);
350 if (max_fline >= MAXLINES) {
351 eof_error = 0; /* Pretend we saw EOF */
354 if (max_fline > cur_fline + max_displayed_line)
356 if (eof_error <= 0) {
357 if (eof_error < 0 && errno == EAGAIN) {
358 /* not yet eof or error, reset flag (or else
359 * we will hog CPU - select() will return
366 current_line = xmalloc(w);
370 fill_match_lines(old_max_fline);
374 #if ENABLE_FEATURE_LESS_FLAGS
375 /* Interestingly, writing calc_percent as a function saves around 32 bytes
377 static int calc_percent(void)
379 unsigned p = (100 * (cur_fline+max_displayed_line+1) + max_fline/2) / (max_fline+1);
380 return p <= 100 ? p : 100;
383 /* Print a status line if -M was specified */
384 static void m_status_print(void)
389 printf(HIGHLIGHT"%s", filename);
391 printf(" (file %i of %i)", current_file, num_files);
392 printf(" lines %i-%i/%i ",
393 cur_fline + 1, cur_fline + max_displayed_line + 1,
395 if (cur_fline >= max_fline - max_displayed_line) {
396 printf("(END)"NORMAL);
397 if (num_files > 1 && current_file != num_files)
398 printf(HIGHLIGHT" - next: %s"NORMAL, files[current_file]);
401 percentage = calc_percent();
402 printf("%i%%"NORMAL, percentage);
406 /* Print the status line */
407 static void status_print(void)
411 /* Change the status if flags have been set */
412 #if ENABLE_FEATURE_LESS_FLAGS
413 if (option_mask32 & (FLAG_M|FLAG_m)) {
421 if (cur_fline && cur_fline < max_fline - max_displayed_line) {
429 printf(HIGHLIGHT"%s (file %i of %i)"NORMAL,
430 p, current_file, num_files);
436 static void cap_cur_fline(int nlines)
441 if (cur_fline + max_displayed_line > max_fline + TILDES) {
445 diff = max_fline - (cur_fline + max_displayed_line) + TILDES;
446 /* As the number of lines requested was too large, we just move
447 to the end of the file */
453 static const char controls[] ALIGN1 =
454 /* NUL: never encountered; TAB: not converted */
455 /**/"\x01\x02\x03\x04\x05\x06\x07\x08" "\x0a\x0b\x0c\x0d\x0e\x0f"
456 "\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1a\x1b\x1c\x1d\x1e\x1f"
457 "\x7f\x9b"; /* DEL and infamous Meta-ESC :( */
458 static const char ctrlconv[] ALIGN1 =
459 /* '\n': it's a former NUL - subst with '@', not 'J' */
460 "\x40\x41\x42\x43\x44\x45\x46\x47\x48\x49\x40\x4b\x4c\x4d\x4e\x4f"
461 "\x50\x51\x52\x53\x54\x55\x56\x57\x58\x59\x5a\x5b\x5c\x5d\x5e\x5f";
463 #if ENABLE_FEATURE_LESS_REGEXP
464 static void print_found(const char *line)
469 regmatch_t match_structs;
472 const char *str = line;
477 n = strcspn(str, controls);
484 n = strspn(str, controls);
491 /* buf[] holds quarantined version of str */
493 /* Each part of the line that matches has the HIGHLIGHT
494 and NORMAL escape sequences placed around it.
495 NB: we regex against line, but insert text
496 from quarantined copy (buf[]) */
502 while (match_status == 0) {
503 char *new = xasprintf("%s%.*s"HIGHLIGHT"%.*s"NORMAL,
505 match_structs.rm_so, str,
506 match_structs.rm_eo - match_structs.rm_so,
507 str + match_structs.rm_so);
508 free(growline); growline = new;
509 str += match_structs.rm_eo;
510 line += match_structs.rm_eo;
513 /* Most of the time doesn't find the regex, optimize for that */
514 match_status = regexec(&pattern, line, 1, &match_structs, eflags);
518 printf(CLEAR_2_EOL"%s\n", str);
521 printf(CLEAR_2_EOL"%s%s\n", growline, str);
525 void print_found(const char *line);
528 static void print_ascii(const char *str)
536 n = strcspn(str, controls);
539 printf("%.*s", (int) n, str);
542 n = strspn(str, controls);
547 else if (*str == (char)0x9b)
548 /* VT100's CSI, aka Meta-ESC. Who's inventor? */
549 /* I want to know who committed this sin */
552 *p++ = ctrlconv[(unsigned char)*str];
561 /* Print the buffer */
562 static void buffer_print(void)
567 for (i = 0; i <= max_displayed_line; i++)
569 print_found(buffer[i]);
571 print_ascii(buffer[i]);
575 static void buffer_fill_and_print(void)
578 for (i = 0; i <= max_displayed_line && cur_fline + i <= max_fline; i++) {
579 buffer[i] = flines[cur_fline + i];
581 for (; i <= max_displayed_line; i++) {
582 buffer[i] = empty_line_marker;
587 /* Move the buffer up and down in the file in order to scroll */
588 static void buffer_down(int nlines)
592 cap_cur_fline(nlines);
593 buffer_fill_and_print();
596 static void buffer_up(int nlines)
599 if (cur_fline < 0) cur_fline = 0;
601 buffer_fill_and_print();
604 static void buffer_line(int linenum)
610 if (linenum + max_displayed_line > max_fline)
611 linenum = max_fline - max_displayed_line + TILDES;
615 buffer_fill_and_print();
618 static void open_file_and_read_lines(void)
621 int fd = xopen(filename, O_RDONLY);
625 /* "less" with no arguments in argv[] */
626 /* For status line only */
627 filename = xstrdup(bb_msg_standard_input);
636 /* Reinitialize everything for a new file - free the memory and start over */
637 static void reinitialize(void)
642 for (i = 0; i <= max_fline; i++)
643 free((void*)(flines[i]));
651 open_file_and_read_lines();
652 buffer_fill_and_print();
655 static void getch_nowait(char* input, int sz)
662 /* NB: select returns whenever read will not block. Therefore:
663 * (a) with O_NONBLOCK'ed fds select will return immediately
664 * (b) if eof is reached, select will also return
665 * because read will immediately return 0 bytes.
666 * Even if select says that input is available, read CAN block
667 * (switch fd into O_NONBLOCK'ed mode to avoid it)
670 if (max_fline <= cur_fline + max_displayed_line
671 && eof_error > 0 /* did NOT reach eof yet */
673 /* We are interested in stdin */
676 FD_SET(kbd_fd, &readfds);
677 tcsetattr(kbd_fd, TCSANOW, &term_less);
678 select(kbd_fd + 1, &readfds, NULL, NULL, NULL);
682 rd = read(kbd_fd, input, sz);
685 /* No keyboard input, but we have input on stdin! */
686 if (errno != EAGAIN) /* Huh?? */
689 buffer_fill_and_print();
694 /* Grab a character from input without requiring the return key. If the
695 * character is ASCII \033, get more characters and assign certain sequences
696 * special return codes. Note that this function works best with raw input. */
697 static int less_getch(void)
702 memset(input, 0, sizeof(input));
703 getch_nowait(input, sizeof(input));
705 /* Detect escape sequences (i.e. arrow keys) and handle
706 * them accordingly */
707 if (input[0] == '\033' && input[1] == '[') {
709 i = input[2] - REAL_KEY_UP;
712 i = input[2] - REAL_PAGE_UP;
715 if (input[2] == REAL_KEY_HOME_XTERM)
717 if (input[2] == REAL_KEY_HOME_ALT)
719 if (input[2] == REAL_KEY_END_XTERM)
721 if (input[2] == REAL_KEY_END_ALT)
725 /* Reject almost all control chars */
727 if (i < ' ' && i != 0x0d && i != 8) goto again;
732 static char* less_gets(int sz)
736 char *result = xzalloc(1);
740 /* I be damned if I know why is it needed *repeatedly*,
741 * but it is needed. Is it because of stdio? */
742 tcsetattr(kbd_fd, TCSANOW, &term_less);
756 if (i >= width - sz - 1)
757 continue; /* len limit */
760 result = xrealloc(result, i+1);
765 static void examine_file(void)
767 print_statusline("Examine: ");
769 filename = less_gets(sizeof("Examine: ")-1);
770 /* files start by = argv. why we assume that argv is infinitely long??
771 files[num_files] = filename;
772 current_file = num_files + 1;
775 num_files = current_file = 1;
779 /* This function changes the file currently being paged. direction can be one of the following:
780 * -1: go back one file
781 * 0: go to the first file
782 * 1: go forward one file */
783 static void change_file(int direction)
785 if (current_file != ((direction > 0) ? num_files : 1)) {
786 current_file = direction ? current_file + direction : 1;
788 filename = xstrdup(files[current_file - 1]);
791 print_statusline(direction > 0 ? "No next file" : "No previous file");
795 static void remove_current_file(void)
802 if (current_file != 1) {
804 for (i = 3; i <= num_files; i++)
805 files[i - 2] = files[i - 1];
809 for (i = 2; i <= num_files; i++)
810 files[i - 2] = files[i - 1];
816 static void colon_process(void)
820 /* Clear the current line and print a prompt */
821 print_statusline(" :");
823 keypress = less_getch();
826 remove_current_file();
831 #if ENABLE_FEATURE_LESS_FLAGS
851 #if ENABLE_FEATURE_LESS_REGEXP
852 static void normalize_match_pos(int match)
854 if (match >= num_matches)
855 match = num_matches - 1;
861 static void goto_match(int match)
870 /* Try to find next match if eof isn't reached yet */
871 if (match >= num_matches && eof_error > 0) {
872 cur_fline = MAXLINES; /* look as far as needed */
876 cap_cur_fline(cur_fline);
877 normalize_match_pos(match);
878 buffer_line(match_lines[match_pos]);
881 print_statusline("No matches found");
885 static void fill_match_lines(unsigned pos)
889 /* Run the regex on each line of the current file */
890 while (pos <= max_fline) {
891 /* If this line matches */
892 if (regexec(&pattern, flines[pos], 0, NULL, 0) == 0
893 /* and we didn't match it last time */
894 && !(num_matches && match_lines[num_matches-1] == pos)
896 match_lines = xrealloc(match_lines, (num_matches+1) * sizeof(int));
897 match_lines[num_matches++] = pos;
903 static void regex_process(void)
905 char *uncomp_regex, *err;
907 /* Reset variables */
917 /* Get the uncompiled regular expression from the user */
919 putchar((option_mask32 & LESS_STATE_MATCH_BACKWARDS) ? '?' : '/');
920 uncomp_regex = less_gets(1);
921 if (!uncomp_regex[0]) {
927 /* Compile the regex and check for errors */
928 err = regcomp_or_errmsg(&pattern, uncomp_regex, 0);
931 print_statusline(err);
939 while (match_pos < num_matches) {
940 if (match_lines[match_pos] > cur_fline)
944 if (option_mask32 & LESS_STATE_MATCH_BACKWARDS)
947 /* It's possible that no matches are found yet.
948 * goto_match() will read input looking for match,
950 goto_match(match_pos);
954 static void number_process(int first_digit)
958 char num_input[sizeof(int)*4]; /* more than enough */
961 num_input[0] = first_digit;
963 /* Clear the current line, print a prompt, and then print the digit */
965 printf(":%c", first_digit);
967 /* Receive input until a letter is given */
968 while (i < sizeof(num_input)-1) {
969 num_input[i] = less_getch();
970 if (!num_input[i] || !isdigit(num_input[i]))
972 putchar(num_input[i]);
976 /* Take the final letter out of the digits string */
977 keypress = num_input[i];
979 num = bb_strtou(num_input, NULL, 10);
980 /* on format error, num == -1 */
981 if (num < 1 || num > MAXLINES) {
986 /* We now know the number and the letter entered, so we process them */
988 case KEY_DOWN: case 'z': case 'd': case 'e': case ' ': case '\015':
991 case KEY_UP: case 'b': case 'w': case 'y': case 'u':
994 case 'g': case '<': case 'G': case '>':
995 cur_fline = num + max_displayed_line;
997 buffer_line(num - 1);
1000 num = num * (max_fline / 100); /* + max_fline / 2; */
1001 cur_fline = num + max_displayed_line;
1005 #if ENABLE_FEATURE_LESS_REGEXP
1007 goto_match(match_pos + num);
1010 option_mask32 &= ~LESS_STATE_MATCH_BACKWARDS;
1014 option_mask32 |= LESS_STATE_MATCH_BACKWARDS;
1021 #if ENABLE_FEATURE_LESS_FLAGCS
1022 static void flag_change(void)
1028 keypress = less_getch();
1032 option_mask32 ^= FLAG_M;
1035 option_mask32 ^= FLAG_m;
1038 option_mask32 ^= FLAG_E;
1041 option_mask32 ^= FLAG_TILDE;
1046 static void show_flag_status(void)
1053 keypress = less_getch();
1057 flag_val = option_mask32 & FLAG_M;
1060 flag_val = option_mask32 & FLAG_m;
1063 flag_val = option_mask32 & FLAG_TILDE;
1066 flag_val = option_mask32 & FLAG_N;
1069 flag_val = option_mask32 & FLAG_E;
1077 printf(HIGHLIGHT"The status of the flag is: %u"NORMAL, flag_val != 0);
1081 static void save_input_to_file(void)
1083 const char *msg = "";
1088 print_statusline("Log file: ");
1089 current_line = less_gets(sizeof("Log file: ")-1);
1090 if (strlen(current_line) > 0) {
1091 fp = fopen(current_line, "w");
1093 msg = "Error opening log file";
1096 for (i = 0; i <= max_fline; i++)
1097 fprintf(fp, "%s\n", flines[i]);
1102 print_statusline(msg);
1106 #if ENABLE_FEATURE_LESS_MARKS
1107 static void add_mark(void)
1111 print_statusline("Mark: ");
1112 letter = less_getch();
1114 if (isalpha(letter)) {
1115 /* If we exceed 15 marks, start overwriting previous ones */
1116 if (num_marks == 14)
1119 mark_lines[num_marks][0] = letter;
1120 mark_lines[num_marks][1] = cur_fline;
1123 print_statusline("Invalid mark letter");
1127 static void goto_mark(void)
1132 print_statusline("Go to mark: ");
1133 letter = less_getch();
1136 if (isalpha(letter)) {
1137 for (i = 0; i <= num_marks; i++)
1138 if (letter == mark_lines[i][0]) {
1139 buffer_line(mark_lines[i][1]);
1142 if (num_marks == 14 && letter != mark_lines[14][0])
1143 print_statusline("Mark not set");
1145 print_statusline("Invalid mark letter");
1149 #if ENABLE_FEATURE_LESS_BRACKETS
1150 static char opp_bracket(char bracket)
1165 static void match_right_bracket(char bracket)
1167 int bracket_line = -1;
1170 if (strchr(flines[cur_fline], bracket) == NULL) {
1171 print_statusline("No bracket in top line");
1174 for (i = cur_fline + 1; i < max_fline; i++) {
1175 if (strchr(flines[i], opp_bracket(bracket)) != NULL) {
1180 if (bracket_line == -1)
1181 print_statusline("No matching bracket found");
1182 buffer_line(bracket_line - max_displayed_line);
1185 static void match_left_bracket(char bracket)
1187 int bracket_line = -1;
1190 if (strchr(flines[cur_fline + max_displayed_line], bracket) == NULL) {
1191 print_statusline("No bracket in bottom line");
1195 for (i = cur_fline + max_displayed_line; i >= 0; i--) {
1196 if (strchr(flines[i], opp_bracket(bracket)) != NULL) {
1201 if (bracket_line == -1)
1202 print_statusline("No matching bracket found");
1203 buffer_line(bracket_line);
1205 #endif /* FEATURE_LESS_BRACKETS */
1207 static void keypress_process(int keypress)
1210 case KEY_DOWN: case 'e': case 'j': case 0x0d:
1213 case KEY_UP: case 'y': case 'k':
1216 case PAGE_DOWN: case ' ': case 'z':
1217 buffer_down(max_displayed_line + 1);
1219 case PAGE_UP: case 'w': case 'b':
1220 buffer_up(max_displayed_line + 1);
1223 buffer_down((max_displayed_line + 1) / 2);
1226 buffer_up((max_displayed_line + 1) / 2);
1228 case KEY_HOME: case 'g': case 'p': case '<': case '%':
1231 case KEY_END: case 'G': case '>':
1232 cur_fline = MAXLINES;
1234 buffer_line(cur_fline);
1239 #if ENABLE_FEATURE_LESS_MARKS
1256 save_input_to_file();
1261 #if ENABLE_FEATURE_LESS_FLAGS
1266 #if ENABLE_FEATURE_LESS_REGEXP
1268 option_mask32 &= ~LESS_STATE_MATCH_BACKWARDS;
1272 goto_match(match_pos + 1);
1275 goto_match(match_pos - 1);
1278 option_mask32 |= LESS_STATE_MATCH_BACKWARDS;
1282 #if ENABLE_FEATURE_LESS_FLAGCS
1291 #if ENABLE_FEATURE_LESS_BRACKETS
1292 case '{': case '(': case '[':
1293 match_right_bracket(keypress);
1295 case '}': case ')': case ']':
1296 match_left_bracket(keypress);
1304 if (isdigit(keypress))
1305 number_process(keypress);
1308 static void sig_catcher(int sig ATTRIBUTE_UNUSED)
1314 int less_main(int argc, char **argv);
1315 int less_main(int argc, char **argv)
1321 /* TODO: -x: do not interpret backspace, -xx: tab also */
1322 /* -xxx: newline also */
1323 /* -w N: assume width N (-xxx -w 32: hex viewer of sorts) */
1324 getopt32(argv, "EMmN~");
1330 /* Another popular pager, most, detects when stdout
1331 * is not a tty and turns into cat. This makes sense. */
1332 if (!isatty(STDOUT_FILENO))
1333 return bb_cat(argv);
1334 kbd_fd = open(CURRENT_TTY, O_RDONLY);
1336 return bb_cat(argv);
1339 if (isatty(STDIN_FILENO)) {
1340 /* Just "less"? No args and no redirection? */
1341 bb_error_msg("missing filename");
1345 filename = xstrdup(files[0]);
1347 get_terminal_width_height(kbd_fd, &width, &max_displayed_line);
1348 /* 20: two tabstops + 4 */
1349 if (width < 20 || max_displayed_line < 3)
1350 bb_error_msg_and_die("too narrow here");
1351 max_displayed_line -= 2;
1353 buffer = xmalloc((max_displayed_line+1) * sizeof(char *));
1354 if (option_mask32 & FLAG_TILDE)
1355 empty_line_marker = "";
1357 tcgetattr(kbd_fd, &term_orig);
1358 signal(SIGTERM, sig_catcher);
1359 signal(SIGINT, sig_catcher);
1360 term_less = term_orig;
1361 term_less.c_lflag &= ~(ICANON | ECHO);
1362 term_less.c_iflag &= ~(IXON | ICRNL);
1363 /*term_less.c_oflag &= ~ONLCR;*/
1364 term_less.c_cc[VMIN] = 1;
1365 term_less.c_cc[VTIME] = 0;
1367 /* Want to do it just once, but it doesn't work, */
1368 /* so we are redoing it (see code above). Mystery... */
1369 /*tcsetattr(kbd_fd, TCSANOW, &term_less);*/
1373 keypress = less_getch();
1374 keypress_process(keypress);