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
25 #if ENABLE_FEATURE_LESS_REGEXP
29 /* FIXME: currently doesn't work right */
30 #undef ENABLE_FEATURE_LESS_FLAGCS
31 #define ENABLE_FEATURE_LESS_FLAGCS 0
33 /* The escape codes for highlighted and normal text */
34 #define HIGHLIGHT "\033[7m"
35 #define NORMAL "\033[0m"
36 /* The escape code to clear the screen */
37 #define CLEAR "\033[H\033[J"
38 /* The escape code to clear to end of line */
39 #define CLEAR_2_EOL "\033[K"
41 /* These are the escape sequences corresponding to special keys */
52 /* These are the special codes assigned by this program to the special keys */
62 /* Absolute max of lines eaten */
63 MAXLINES = CONFIG_FEATURE_LESS_MAXLINES,
65 /* This many "after the end" lines we will show (at max) */
69 static unsigned max_displayed_line;
70 static unsigned width;
71 static const char *empty_line_marker = "~";
73 static char *filename;
75 static unsigned num_files = 1;
76 static unsigned current_file = 1;
77 static const char **buffer;
78 static const char **flines;
79 static int cur_fline; /* signed */
80 static unsigned max_fline;
81 static unsigned max_lineno; /* this one tracks linewrap */
83 static ssize_t eof_error = 1; /* eof if 0, error if < 0 */
84 static char terminated = 1;
85 static size_t readpos;
86 static size_t readeof;
87 /* last position in last line, taking into account tabs */
88 static size_t linepos;
90 /* Command line options */
97 /* hijack command line options variable for internal state vars */
98 LESS_STATE_MATCH_BACKWARDS = 1 << 15,
101 #if ENABLE_FEATURE_LESS_MARKS
102 static unsigned mark_lines[15][2];
103 static unsigned num_marks;
106 #if ENABLE_FEATURE_LESS_REGEXP
107 static unsigned *match_lines;
108 static int match_pos; /* signed! */
109 static unsigned num_matches;
110 static regex_t pattern;
111 static unsigned pattern_valid;
114 static struct termios term_orig, term_vi;
116 /* File pointer to get input from */
119 /* Reset terminal input to normal */
120 static void set_tty_cooked(void)
123 tcsetattr(kbd_fd, TCSANOW, &term_orig);
126 /* Exit the program gracefully */
127 static void less_exit(int code)
129 /* TODO: We really should save the terminal state when we start,
130 * and restore it when we exit. Less does this with the
131 * "ti" and "te" termcap commands; can this be done with
134 fflush_stdout_and_exit(code);
137 /* Move the cursor to a position (x,y), where (0,0) is the
138 top-left corner of the console */
139 static void move_cursor(int line, int row)
141 printf("\033[%u;%uH", line, row);
144 static void clear_line(void)
146 printf("\033[%u;0H" CLEAR_2_EOL, max_displayed_line + 2);
149 static void print_hilite(const char *str)
151 printf(HIGHLIGHT"%s"NORMAL, str);
154 static void print_statusline(const char *str)
157 printf(HIGHLIGHT"%.*s"NORMAL, width - 1, str);
160 #if ENABLE_FEATURE_LESS_REGEXP
161 static void fill_match_lines(unsigned pos);
163 #define fill_match_lines(pos) ((void)0)
167 static void read_lines(void)
169 #define readbuf bb_common_bufsiz1
170 char *current_line, *p;
171 unsigned old_max_fline = max_fline;
173 char last_terminated = terminated;
175 if (option_mask32 & FLAG_N)
178 current_line = xmalloc(w);
180 max_fline += last_terminated;
181 if (!last_terminated) {
182 const char *cp = flines[max_fline];
183 if (option_mask32 & FLAG_N)
185 strcpy(current_line, cp);
186 p += strlen(current_line);
197 if (readpos >= readeof) {
199 eof_error = safe_read(0, readbuf, sizeof(readbuf));
206 print_statusline("read error");
208 if (eof_error <= 0) {
212 c = readbuf[readpos];
214 linepos += (linepos^7) & 7;
219 if (c == '\n') { terminated = 1; break; }
220 /* NUL is substituted by '\n'! */
221 if (c == '\0') c = '\n';
225 /* Corner case: linewrap with only "" wrapping to next line */
226 /* Looks ugly on screen, so we do not store this empty line */
227 if (!last_terminated && !current_line[0]) {
233 last_terminated = terminated;
234 flines = xrealloc(flines, (max_fline+1) * sizeof(char *));
235 if (option_mask32 & FLAG_N) {
236 /* Width of 7 preserves tab spacing in the text */
237 flines[max_fline] = xasprintf(
238 (max_lineno <= 9999999) ? "%7u %s" : "%07u %s",
239 max_lineno % 10000000, current_line);
244 flines[max_fline] = xrealloc(current_line, strlen(current_line)+1);
246 if (max_fline >= MAXLINES)
248 if (max_fline > cur_fline + max_displayed_line)
250 if (eof_error <= 0) {
251 if (eof_error < 0 && errno == EAGAIN) {
252 /* not yet eof or error, reset flag (or else
253 * we will hog CPU - select() will return
260 current_line = xmalloc(w);
264 fill_match_lines(old_max_fline);
268 #if ENABLE_FEATURE_LESS_FLAGS
269 /* Interestingly, writing calc_percent as a function saves around 32 bytes
271 static int calc_percent(void)
273 unsigned p = (100 * (cur_fline+max_displayed_line+1) + max_fline/2) / (max_fline+1);
274 return p <= 100 ? p : 100;
277 /* Print a status line if -M was specified */
278 static void m_status_print(void)
283 printf(HIGHLIGHT"%s", filename);
285 printf(" (file %i of %i)", current_file, num_files);
286 printf(" lines %i-%i/%i ",
287 cur_fline + 1, cur_fline + max_displayed_line + 1,
289 if (cur_fline >= max_fline - max_displayed_line) {
290 printf("(END)"NORMAL);
291 if (num_files > 1 && current_file != num_files)
292 printf(HIGHLIGHT" - next: %s"NORMAL, files[current_file]);
295 percentage = calc_percent();
296 printf("%i%%"NORMAL, percentage);
300 /* Print the status line */
301 static void status_print(void)
305 /* Change the status if flags have been set */
306 #if ENABLE_FEATURE_LESS_FLAGS
307 if (option_mask32 & (FLAG_M|FLAG_m)) {
315 if (cur_fline && cur_fline < max_fline - max_displayed_line) {
323 printf(HIGHLIGHT"%s (file %i of %i)"NORMAL,
324 p, current_file, num_files);
330 static char controls[] =
331 /* NUL: never encountered; TAB: not converted */
332 /**/"\x01\x02\x03\x04\x05\x06\x07\x08" "\x0a\x0b\x0c\x0d\x0e\x0f"
333 "\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1a\x1b\x1c\x1d\x1e\x1f"
334 "\x7f\x9b"; /* DEL and infamous Meta-ESC :( */
335 static char ctrlconv[] =
336 /* '\n': it's a former NUL - subst with '@', not 'J' */
337 "\x40\x41\x42\x43\x44\x45\x46\x47\x48\x49\x40\x4b\x4c\x4d\x4e\x4f"
338 "\x50\x51\x52\x53\x54\x55\x56\x57\x58\x59\x5a\x5b\x5c\x5d\x5e\x5f";
340 static void print_found(const char *line)
345 regmatch_t match_structs;
348 const char *str = line;
353 n = strcspn(str, controls);
360 n = strspn(str, controls);
367 /* buf[] holds quarantined version of str */
369 /* Each part of the line that matches has the HIGHLIGHT
370 and NORMAL escape sequences placed around it.
371 NB: we regex against line, but insert text
372 from quarantined copy (buf[]) */
378 while (match_status == 0) {
379 char *new = xasprintf("%s%.*s"HIGHLIGHT"%.*s"NORMAL,
381 match_structs.rm_so, str,
382 match_structs.rm_eo - match_structs.rm_so,
383 str + match_structs.rm_so);
384 free(growline); growline = new;
385 str += match_structs.rm_eo;
386 line += match_structs.rm_eo;
389 /* Most of the time doesn't find the regex, optimize for that */
390 match_status = regexec(&pattern, line, 1, &match_structs, eflags);
394 printf(CLEAR_2_EOL"%s\n", str);
397 printf(CLEAR_2_EOL"%s%s\n", growline, str);
401 static void print_ascii(const char *str)
409 n = strcspn(str, controls);
412 printf("%.*s", n, str);
415 n = strspn(str, controls);
420 else if (*str == (char)0x9b)
421 /* VT100's CSI, aka Meta-ESC. Who's inventor? */
422 /* I want to know who committed this sin */
425 *p++ = ctrlconv[(unsigned char)*str];
434 /* Print the buffer */
435 static void buffer_print(void)
440 for (i = 0; i <= max_displayed_line; i++)
442 print_found(buffer[i]);
444 print_ascii(buffer[i]);
448 static void buffer_fill_and_print(void)
451 for (i = 0; i <= max_displayed_line && cur_fline + i <= max_fline; i++) {
452 buffer[i] = flines[cur_fline + i];
454 for (; i <= max_displayed_line; i++) {
455 buffer[i] = empty_line_marker;
460 /* Move the buffer up and down in the file in order to scroll */
461 static void buffer_down(int nlines)
467 if (cur_fline + max_displayed_line > max_fline + TILDES) {
469 diff = max_fline - (cur_fline + max_displayed_line) + TILDES;
470 /* As the number of lines requested was too large, we just move
471 to the end of the file */
475 buffer_fill_and_print();
478 static void buffer_up(int nlines)
481 if (cur_fline < 0) cur_fline = 0;
483 buffer_fill_and_print();
486 static void buffer_line(int linenum)
492 if (linenum + max_displayed_line > max_fline)
493 linenum = max_fline - max_displayed_line + TILDES;
495 buffer_fill_and_print();
498 static void open_file_and_read_lines(void)
501 int fd = xopen(filename, O_RDONLY);
505 /* "less" with no arguments in argv[] */
506 /* For status line only */
507 filename = xstrdup(bb_msg_standard_input);
516 /* Reinitialize everything for a new file - free the memory and start over */
517 static void reinitialize(void)
522 for (i = 0; i <= max_fline; i++)
523 free((void*)(flines[i]));
531 open_file_and_read_lines();
532 buffer_fill_and_print();
535 static void getch_nowait(char* input, int sz)
542 /* NB: select returns whenever read will not block. Therefore:
543 * (a) with O_NONBLOCK'ed fds select will return immediately
544 * (b) if eof is reached, select will also return
545 * because read will immediately return 0 bytes.
546 * Even if select says that input is available, read CAN block
547 * (switch fd into O_NONBLOCK'ed mode to avoid it)
550 if (max_fline <= cur_fline + max_displayed_line
551 && eof_error > 0 /* did NOT reach eof yet */
553 /* We are interested in stdin */
556 FD_SET(kbd_fd, &readfds);
557 tcsetattr(kbd_fd, TCSANOW, &term_vi);
558 select(kbd_fd + 1, &readfds, NULL, NULL, NULL);
562 rd = read(kbd_fd, input, sz);
565 /* No keyboard input, but we have input on stdin! */
566 if (errno != EAGAIN) /* Huh?? */
569 buffer_fill_and_print();
574 /* Grab a character from input without requiring the return key. If the
575 * character is ASCII \033, get more characters and assign certain sequences
576 * special return codes. Note that this function works best with raw input. */
577 static int less_getch(void)
582 getch_nowait(input, sizeof(input));
583 /* Detect escape sequences (i.e. arrow keys) and handle
584 * them accordingly */
586 if (input[0] == '\033' && input[1] == '[') {
588 i = input[2] - REAL_KEY_UP;
591 i = input[2] - REAL_PAGE_UP;
596 /* Reject almost all control chars */
598 if (i < ' ' && i != 0x0d && i != 8) goto again;
603 static char* less_gets(int sz)
607 char *result = xzalloc(1);
611 /* I be damned if I know why is it needed *repeatedly*,
612 * but it is needed. Is it because of stdio? */
613 tcsetattr(kbd_fd, TCSANOW, &term_vi);
626 if (i >= width - sz - 1)
627 continue; /* len limit */
630 result = xrealloc(result, i+1);
635 static void examine_file(void)
637 print_statusline("Examine: ");
639 filename = less_gets(sizeof("Examine: ")-1);
640 /* files start by = argv. why we assume that argv is infinitely long??
641 files[num_files] = filename;
642 current_file = num_files + 1;
645 num_files = current_file = 1;
649 /* This function changes the file currently being paged. direction can be one of the following:
650 * -1: go back one file
651 * 0: go to the first file
652 * 1: go forward one file */
653 static void change_file(int direction)
655 if (current_file != ((direction > 0) ? num_files : 1)) {
656 current_file = direction ? current_file + direction : 1;
658 filename = xstrdup(files[current_file - 1]);
661 print_statusline(direction > 0 ? "No next file" : "No previous file");
665 static void remove_current_file(void)
672 if (current_file != 1) {
674 for (i = 3; i <= num_files; i++)
675 files[i - 2] = files[i - 1];
679 for (i = 2; i <= num_files; i++)
680 files[i - 2] = files[i - 1];
686 static void colon_process(void)
690 /* Clear the current line and print a prompt */
691 print_statusline(" :");
693 keypress = less_getch();
696 remove_current_file();
701 #if ENABLE_FEATURE_LESS_FLAGS
721 static int normalize_match_pos(int match)
724 if (match >= num_matches)
725 match_pos = num_matches - 1;
731 #if ENABLE_FEATURE_LESS_REGEXP
732 static void goto_match(int match)
735 buffer_line(match_lines[normalize_match_pos(match)]);
738 static void fill_match_lines(unsigned pos)
742 /* Run the regex on each line of the current file */
743 while (pos <= max_fline) {
744 /* If this line matches */
745 if (regexec(&pattern, flines[pos], 0, NULL, 0) == 0
746 /* and we didn't match it last time */
747 && !(num_matches && match_lines[num_matches-1] == pos)
749 match_lines = xrealloc(match_lines, (num_matches+1) * sizeof(int));
750 match_lines[num_matches++] = pos;
756 static void regex_process(void)
758 char *uncomp_regex, *err;
760 /* Reset variables */
770 /* Get the uncompiled regular expression from the user */
772 putchar((option_mask32 & LESS_STATE_MATCH_BACKWARDS) ? '?' : '/');
773 uncomp_regex = less_gets(1);
774 if (!uncomp_regex[0]) {
780 /* Compile the regex and check for errors */
781 err = regcomp_or_errmsg(&pattern, uncomp_regex, 0);
784 print_statusline(err);
793 if (num_matches == 0 || max_fline <= max_displayed_line) {
797 while (match_pos < num_matches) {
798 if (match_lines[match_pos] > cur_fline)
802 if (option_mask32 & LESS_STATE_MATCH_BACKWARDS)
804 buffer_line(match_lines[normalize_match_pos(match_pos)]);
808 static void number_process(int first_digit)
812 char num_input[sizeof(int)*4]; /* more than enough */
815 num_input[0] = first_digit;
817 /* Clear the current line, print a prompt, and then print the digit */
819 printf(":%c", first_digit);
821 /* Receive input until a letter is given */
822 while (i < sizeof(num_input)-1) {
823 num_input[i] = less_getch();
824 if (!num_input[i] || !isdigit(num_input[i]))
826 putchar(num_input[i]);
830 /* Take the final letter out of the digits string */
831 keypress = num_input[i];
833 num = bb_strtou(num_input, NULL, 10);
834 /* on format error, num == -1 */
835 if (num < 1 || num > MAXLINES) {
840 /* We now know the number and the letter entered, so we process them */
842 case KEY_DOWN: case 'z': case 'd': case 'e': case ' ': case '\015':
845 case KEY_UP: case 'b': case 'w': case 'y': case 'u':
848 case 'g': case '<': case 'G': case '>':
849 cur_fline = num + max_displayed_line;
851 buffer_line(num - 1);
854 num = num * (max_fline / 100); /* + max_fline / 2; */
855 cur_fline = num + max_displayed_line;
859 #if ENABLE_FEATURE_LESS_REGEXP
861 goto_match(match_pos + num);
864 option_mask32 &= ~LESS_STATE_MATCH_BACKWARDS;
868 option_mask32 |= LESS_STATE_MATCH_BACKWARDS;
875 #if ENABLE_FEATURE_LESS_FLAGCS
876 static void flag_change(void)
882 keypress = less_getch();
886 option_mask32 ^= FLAG_M;
889 option_mask32 ^= FLAG_m;
892 option_mask32 ^= FLAG_E;
895 option_mask32 ^= FLAG_TILDE;
900 static void show_flag_status(void)
907 keypress = less_getch();
911 flag_val = option_mask32 & FLAG_M;
914 flag_val = option_mask32 & FLAG_m;
917 flag_val = option_mask32 & FLAG_TILDE;
920 flag_val = option_mask32 & FLAG_N;
923 flag_val = option_mask32 & FLAG_E;
931 printf(HIGHLIGHT"The status of the flag is: %u"NORMAL, flag_val != 0);
935 static void save_input_to_file(void)
937 const char *msg = "";
942 print_statusline("Log file: ");
943 current_line = less_gets(sizeof("Log file: ")-1);
944 if (strlen(current_line) > 0) {
945 fp = fopen(current_line, "w");
947 msg = "Error opening log file";
950 for (i = 0; i <= max_fline; i++)
951 fprintf(fp, "%s\n", flines[i]);
956 print_statusline(msg);
960 #if ENABLE_FEATURE_LESS_MARKS
961 static void add_mark(void)
965 print_statusline("Mark: ");
966 letter = less_getch();
968 if (isalpha(letter)) {
969 /* If we exceed 15 marks, start overwriting previous ones */
973 mark_lines[num_marks][0] = letter;
974 mark_lines[num_marks][1] = cur_fline;
977 print_statusline("Invalid mark letter");
981 static void goto_mark(void)
986 print_statusline("Go to mark: ");
987 letter = less_getch();
990 if (isalpha(letter)) {
991 for (i = 0; i <= num_marks; i++)
992 if (letter == mark_lines[i][0]) {
993 buffer_line(mark_lines[i][1]);
996 if (num_marks == 14 && letter != mark_lines[14][0])
997 print_statusline("Mark not set");
999 print_statusline("Invalid mark letter");
1003 #if ENABLE_FEATURE_LESS_BRACKETS
1004 static char opp_bracket(char bracket)
1019 static void match_right_bracket(char bracket)
1021 int bracket_line = -1;
1024 if (strchr(flines[cur_fline], bracket) == NULL) {
1025 print_statusline("No bracket in top line");
1028 for (i = cur_fline + 1; i < max_fline; i++) {
1029 if (strchr(flines[i], opp_bracket(bracket)) != NULL) {
1034 if (bracket_line == -1)
1035 print_statusline("No matching bracket found");
1036 buffer_line(bracket_line - max_displayed_line);
1039 static void match_left_bracket(char bracket)
1041 int bracket_line = -1;
1044 if (strchr(flines[cur_fline + max_displayed_line], bracket) == NULL) {
1045 print_statusline("No bracket in bottom line");
1049 for (i = cur_fline + max_displayed_line; i >= 0; i--) {
1050 if (strchr(flines[i], opp_bracket(bracket)) != NULL) {
1055 if (bracket_line == -1)
1056 print_statusline("No matching bracket found");
1057 buffer_line(bracket_line);
1059 #endif /* FEATURE_LESS_BRACKETS */
1061 static void keypress_process(int keypress)
1064 case KEY_DOWN: case 'e': case 'j': case 0x0d:
1067 case KEY_UP: case 'y': case 'k':
1070 case PAGE_DOWN: case ' ': case 'z':
1071 buffer_down(max_displayed_line + 1);
1073 case PAGE_UP: case 'w': case 'b':
1074 buffer_up(max_displayed_line + 1);
1077 buffer_down((max_displayed_line + 1) / 2);
1080 buffer_up((max_displayed_line + 1) / 2);
1082 case KEY_HOME: case 'g': case 'p': case '<': case '%':
1085 case KEY_END: case 'G': case '>':
1086 cur_fline = MAXLINES;
1088 buffer_line(cur_fline);
1093 #if ENABLE_FEATURE_LESS_MARKS
1110 save_input_to_file();
1115 #if ENABLE_FEATURE_LESS_FLAGS
1120 #if ENABLE_FEATURE_LESS_REGEXP
1122 option_mask32 &= ~LESS_STATE_MATCH_BACKWARDS;
1126 goto_match(match_pos + 1);
1129 goto_match(match_pos - 1);
1132 option_mask32 |= LESS_STATE_MATCH_BACKWARDS;
1136 #if ENABLE_FEATURE_LESS_FLAGCS
1145 #if ENABLE_FEATURE_LESS_BRACKETS
1146 case '{': case '(': case '[':
1147 match_right_bracket(keypress);
1149 case '}': case ')': case ']':
1150 match_left_bracket(keypress);
1158 if (isdigit(keypress))
1159 number_process(keypress);
1162 static void sig_catcher(int sig ATTRIBUTE_UNUSED)
1168 int less_main(int argc, char **argv)
1172 getopt32(argc, argv, "EMmN~");
1178 /* Another popular pager, most, detects when stdout
1179 * is not a tty and turns into cat. This makes sense. */
1180 if (!isatty(STDOUT_FILENO))
1181 return bb_cat(argv);
1184 if (isatty(STDIN_FILENO)) {
1185 /* Just "less"? No args and no redirection? */
1186 bb_error_msg("missing filename");
1190 filename = xstrdup(files[0]);
1192 kbd_fd = xopen(CURRENT_TTY, O_RDONLY);
1194 get_terminal_width_height(kbd_fd, &width, &max_displayed_line);
1195 /* 20: two tabstops + 4 */
1196 if (width < 20 || max_displayed_line < 3)
1197 bb_error_msg_and_die("too narrow here");
1198 max_displayed_line -= 2;
1200 buffer = xmalloc((max_displayed_line+1) * sizeof(char *));
1201 if (option_mask32 & FLAG_TILDE)
1202 empty_line_marker = "";
1204 tcgetattr(kbd_fd, &term_orig);
1205 signal(SIGTERM, sig_catcher);
1206 signal(SIGINT, sig_catcher);
1207 term_vi = term_orig;
1208 term_vi.c_lflag &= ~(ICANON | ECHO);
1209 term_vi.c_iflag &= ~(IXON | ICRNL);
1210 /*term_vi.c_oflag &= ~ONLCR;*/
1211 term_vi.c_cc[VMIN] = 1;
1212 term_vi.c_cc[VTIME] = 0;
1214 /* Want to do it just once, but it doesn't work, */
1215 /* so we are redoing it (see code above). Mystery... */
1216 /*tcsetattr(kbd_fd, TCSANOW, &term_vi);*/
1220 keypress = less_getch();
1221 keypress_process(keypress);