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;
113 enum { pattern_valid = 0 };
116 static struct termios term_orig, term_vi;
118 /* File pointer to get input from */
121 /* Reset terminal input to normal */
122 static void set_tty_cooked(void)
125 tcsetattr(kbd_fd, TCSANOW, &term_orig);
128 /* Exit the program gracefully */
129 static void less_exit(int code)
131 /* TODO: We really should save the terminal state when we start,
132 * and restore it when we exit. Less does this with the
133 * "ti" and "te" termcap commands; can this be done with
136 fflush_stdout_and_exit(code);
139 /* Move the cursor to a position (x,y), where (0,0) is the
140 top-left corner of the console */
141 static void move_cursor(int line, int row)
143 printf("\033[%u;%uH", line, row);
146 static void clear_line(void)
148 printf("\033[%u;0H" CLEAR_2_EOL, max_displayed_line + 2);
151 static void print_hilite(const char *str)
153 printf(HIGHLIGHT"%s"NORMAL, str);
156 static void print_statusline(const char *str)
159 printf(HIGHLIGHT"%.*s"NORMAL, width - 1, str);
162 #if ENABLE_FEATURE_LESS_REGEXP
163 static void fill_match_lines(unsigned pos);
165 #define fill_match_lines(pos) ((void)0)
169 static void read_lines(void)
171 #define readbuf bb_common_bufsiz1
172 char *current_line, *p;
173 USE_FEATURE_LESS_REGEXP(unsigned old_max_fline = max_fline;)
175 char last_terminated = terminated;
177 if (option_mask32 & FLAG_N)
180 current_line = xmalloc(w);
182 max_fline += last_terminated;
183 if (!last_terminated) {
184 const char *cp = flines[max_fline];
185 if (option_mask32 & FLAG_N)
187 strcpy(current_line, cp);
188 p += strlen(current_line);
199 if (readpos >= readeof) {
201 eof_error = safe_read(0, readbuf, sizeof(readbuf));
208 print_statusline("read error");
210 if (eof_error <= 0) {
214 c = readbuf[readpos];
215 /* backspace? [need this for manpage display] */
216 if (c == '\x8' && linepos) {
217 readpos++; /* eat it */
218 /* We do not consider the case of <tab><bs> */
219 /* Anyone who has that is pure evil :) */
225 linepos += (linepos^7) & 7;
229 /* ok, we will eat this char */
231 if (c == '\n') { terminated = 1; break; }
232 /* NUL is substituted by '\n'! */
233 if (c == '\0') c = '\n';
237 /* Corner case: linewrap with only "" wrapping to next line */
238 /* Looks ugly on screen, so we do not store this empty line */
239 if (!last_terminated && !current_line[0]) {
245 last_terminated = terminated;
246 flines = xrealloc(flines, (max_fline+1) * sizeof(char *));
247 if (option_mask32 & FLAG_N) {
248 /* Width of 7 preserves tab spacing in the text */
249 flines[max_fline] = xasprintf(
250 (max_lineno <= 9999999) ? "%7u %s" : "%07u %s",
251 max_lineno % 10000000, current_line);
256 flines[max_fline] = xrealloc(current_line, strlen(current_line)+1);
258 if (max_fline >= MAXLINES)
260 if (max_fline > cur_fline + max_displayed_line)
262 if (eof_error <= 0) {
263 if (eof_error < 0 && errno == EAGAIN) {
264 /* not yet eof or error, reset flag (or else
265 * we will hog CPU - select() will return
272 current_line = xmalloc(w);
276 fill_match_lines(old_max_fline);
280 #if ENABLE_FEATURE_LESS_FLAGS
281 /* Interestingly, writing calc_percent as a function saves around 32 bytes
283 static int calc_percent(void)
285 unsigned p = (100 * (cur_fline+max_displayed_line+1) + max_fline/2) / (max_fline+1);
286 return p <= 100 ? p : 100;
289 /* Print a status line if -M was specified */
290 static void m_status_print(void)
295 printf(HIGHLIGHT"%s", filename);
297 printf(" (file %i of %i)", current_file, num_files);
298 printf(" lines %i-%i/%i ",
299 cur_fline + 1, cur_fline + max_displayed_line + 1,
301 if (cur_fline >= max_fline - max_displayed_line) {
302 printf("(END)"NORMAL);
303 if (num_files > 1 && current_file != num_files)
304 printf(HIGHLIGHT" - next: %s"NORMAL, files[current_file]);
307 percentage = calc_percent();
308 printf("%i%%"NORMAL, percentage);
312 /* Print the status line */
313 static void status_print(void)
317 /* Change the status if flags have been set */
318 #if ENABLE_FEATURE_LESS_FLAGS
319 if (option_mask32 & (FLAG_M|FLAG_m)) {
327 if (cur_fline && cur_fline < max_fline - max_displayed_line) {
335 printf(HIGHLIGHT"%s (file %i of %i)"NORMAL,
336 p, current_file, num_files);
342 static char controls[] =
343 /* NUL: never encountered; TAB: not converted */
344 /**/"\x01\x02\x03\x04\x05\x06\x07\x08" "\x0a\x0b\x0c\x0d\x0e\x0f"
345 "\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1a\x1b\x1c\x1d\x1e\x1f"
346 "\x7f\x9b"; /* DEL and infamous Meta-ESC :( */
347 static char ctrlconv[] =
348 /* '\n': it's a former NUL - subst with '@', not 'J' */
349 "\x40\x41\x42\x43\x44\x45\x46\x47\x48\x49\x40\x4b\x4c\x4d\x4e\x4f"
350 "\x50\x51\x52\x53\x54\x55\x56\x57\x58\x59\x5a\x5b\x5c\x5d\x5e\x5f";
352 #if ENABLE_FEATURE_LESS_REGEXP
353 static void print_found(const char *line)
358 regmatch_t match_structs;
361 const char *str = line;
366 n = strcspn(str, controls);
373 n = strspn(str, controls);
380 /* buf[] holds quarantined version of str */
382 /* Each part of the line that matches has the HIGHLIGHT
383 and NORMAL escape sequences placed around it.
384 NB: we regex against line, but insert text
385 from quarantined copy (buf[]) */
391 while (match_status == 0) {
392 char *new = xasprintf("%s%.*s"HIGHLIGHT"%.*s"NORMAL,
394 match_structs.rm_so, str,
395 match_structs.rm_eo - match_structs.rm_so,
396 str + match_structs.rm_so);
397 free(growline); growline = new;
398 str += match_structs.rm_eo;
399 line += match_structs.rm_eo;
402 /* Most of the time doesn't find the regex, optimize for that */
403 match_status = regexec(&pattern, line, 1, &match_structs, eflags);
407 printf(CLEAR_2_EOL"%s\n", str);
410 printf(CLEAR_2_EOL"%s%s\n", growline, str);
414 void print_found(const char *line);
417 static void print_ascii(const char *str)
425 n = strcspn(str, controls);
428 printf("%.*s", (int) n, str);
431 n = strspn(str, controls);
436 else if (*str == (char)0x9b)
437 /* VT100's CSI, aka Meta-ESC. Who's inventor? */
438 /* I want to know who committed this sin */
441 *p++ = ctrlconv[(unsigned char)*str];
450 /* Print the buffer */
451 static void buffer_print(void)
456 for (i = 0; i <= max_displayed_line; i++)
458 print_found(buffer[i]);
460 print_ascii(buffer[i]);
464 static void buffer_fill_and_print(void)
467 for (i = 0; i <= max_displayed_line && cur_fline + i <= max_fline; i++) {
468 buffer[i] = flines[cur_fline + i];
470 for (; i <= max_displayed_line; i++) {
471 buffer[i] = empty_line_marker;
476 /* Move the buffer up and down in the file in order to scroll */
477 static void buffer_down(int nlines)
483 if (cur_fline + max_displayed_line > max_fline + TILDES) {
485 diff = max_fline - (cur_fline + max_displayed_line) + TILDES;
486 /* As the number of lines requested was too large, we just move
487 to the end of the file */
491 buffer_fill_and_print();
494 static void buffer_up(int nlines)
497 if (cur_fline < 0) cur_fline = 0;
499 buffer_fill_and_print();
502 static void buffer_line(int linenum)
508 if (linenum + max_displayed_line > max_fline)
509 linenum = max_fline - max_displayed_line + TILDES;
511 buffer_fill_and_print();
514 static void open_file_and_read_lines(void)
517 int fd = xopen(filename, O_RDONLY);
521 /* "less" with no arguments in argv[] */
522 /* For status line only */
523 filename = xstrdup(bb_msg_standard_input);
532 /* Reinitialize everything for a new file - free the memory and start over */
533 static void reinitialize(void)
538 for (i = 0; i <= max_fline; i++)
539 free((void*)(flines[i]));
547 open_file_and_read_lines();
548 buffer_fill_and_print();
551 static void getch_nowait(char* input, int sz)
558 /* NB: select returns whenever read will not block. Therefore:
559 * (a) with O_NONBLOCK'ed fds select will return immediately
560 * (b) if eof is reached, select will also return
561 * because read will immediately return 0 bytes.
562 * Even if select says that input is available, read CAN block
563 * (switch fd into O_NONBLOCK'ed mode to avoid it)
566 if (max_fline <= cur_fline + max_displayed_line
567 && eof_error > 0 /* did NOT reach eof yet */
569 /* We are interested in stdin */
572 FD_SET(kbd_fd, &readfds);
573 tcsetattr(kbd_fd, TCSANOW, &term_vi);
574 select(kbd_fd + 1, &readfds, NULL, NULL, NULL);
578 rd = read(kbd_fd, input, sz);
581 /* No keyboard input, but we have input on stdin! */
582 if (errno != EAGAIN) /* Huh?? */
585 buffer_fill_and_print();
590 /* Grab a character from input without requiring the return key. If the
591 * character is ASCII \033, get more characters and assign certain sequences
592 * special return codes. Note that this function works best with raw input. */
593 static int less_getch(void)
598 getch_nowait(input, sizeof(input));
599 /* Detect escape sequences (i.e. arrow keys) and handle
600 * them accordingly */
602 if (input[0] == '\033' && input[1] == '[') {
604 i = input[2] - REAL_KEY_UP;
607 i = input[2] - REAL_PAGE_UP;
612 /* Reject almost all control chars */
614 if (i < ' ' && i != 0x0d && i != 8) goto again;
619 static char* less_gets(int sz)
623 char *result = xzalloc(1);
627 /* I be damned if I know why is it needed *repeatedly*,
628 * but it is needed. Is it because of stdio? */
629 tcsetattr(kbd_fd, TCSANOW, &term_vi);
642 if (i >= width - sz - 1)
643 continue; /* len limit */
646 result = xrealloc(result, i+1);
651 static void examine_file(void)
653 print_statusline("Examine: ");
655 filename = less_gets(sizeof("Examine: ")-1);
656 /* files start by = argv. why we assume that argv is infinitely long??
657 files[num_files] = filename;
658 current_file = num_files + 1;
661 num_files = current_file = 1;
665 /* This function changes the file currently being paged. direction can be one of the following:
666 * -1: go back one file
667 * 0: go to the first file
668 * 1: go forward one file */
669 static void change_file(int direction)
671 if (current_file != ((direction > 0) ? num_files : 1)) {
672 current_file = direction ? current_file + direction : 1;
674 filename = xstrdup(files[current_file - 1]);
677 print_statusline(direction > 0 ? "No next file" : "No previous file");
681 static void remove_current_file(void)
688 if (current_file != 1) {
690 for (i = 3; i <= num_files; i++)
691 files[i - 2] = files[i - 1];
695 for (i = 2; i <= num_files; i++)
696 files[i - 2] = files[i - 1];
702 static void colon_process(void)
706 /* Clear the current line and print a prompt */
707 print_statusline(" :");
709 keypress = less_getch();
712 remove_current_file();
717 #if ENABLE_FEATURE_LESS_FLAGS
737 #if ENABLE_FEATURE_LESS_REGEXP
738 static int normalize_match_pos(int match)
741 if (match >= num_matches)
742 match_pos = num_matches - 1;
748 static void goto_match(int match)
751 buffer_line(match_lines[normalize_match_pos(match)]);
754 static void fill_match_lines(unsigned pos)
758 /* Run the regex on each line of the current file */
759 while (pos <= max_fline) {
760 /* If this line matches */
761 if (regexec(&pattern, flines[pos], 0, NULL, 0) == 0
762 /* and we didn't match it last time */
763 && !(num_matches && match_lines[num_matches-1] == pos)
765 match_lines = xrealloc(match_lines, (num_matches+1) * sizeof(int));
766 match_lines[num_matches++] = pos;
772 static void regex_process(void)
774 char *uncomp_regex, *err;
776 /* Reset variables */
786 /* Get the uncompiled regular expression from the user */
788 putchar((option_mask32 & LESS_STATE_MATCH_BACKWARDS) ? '?' : '/');
789 uncomp_regex = less_gets(1);
790 if (!uncomp_regex[0]) {
796 /* Compile the regex and check for errors */
797 err = regcomp_or_errmsg(&pattern, uncomp_regex, 0);
800 print_statusline(err);
809 if (num_matches == 0 || max_fline <= max_displayed_line) {
813 while (match_pos < num_matches) {
814 if (match_lines[match_pos] > cur_fline)
818 if (option_mask32 & LESS_STATE_MATCH_BACKWARDS)
820 buffer_line(match_lines[normalize_match_pos(match_pos)]);
824 static void number_process(int first_digit)
828 char num_input[sizeof(int)*4]; /* more than enough */
831 num_input[0] = first_digit;
833 /* Clear the current line, print a prompt, and then print the digit */
835 printf(":%c", first_digit);
837 /* Receive input until a letter is given */
838 while (i < sizeof(num_input)-1) {
839 num_input[i] = less_getch();
840 if (!num_input[i] || !isdigit(num_input[i]))
842 putchar(num_input[i]);
846 /* Take the final letter out of the digits string */
847 keypress = num_input[i];
849 num = bb_strtou(num_input, NULL, 10);
850 /* on format error, num == -1 */
851 if (num < 1 || num > MAXLINES) {
856 /* We now know the number and the letter entered, so we process them */
858 case KEY_DOWN: case 'z': case 'd': case 'e': case ' ': case '\015':
861 case KEY_UP: case 'b': case 'w': case 'y': case 'u':
864 case 'g': case '<': case 'G': case '>':
865 cur_fline = num + max_displayed_line;
867 buffer_line(num - 1);
870 num = num * (max_fline / 100); /* + max_fline / 2; */
871 cur_fline = num + max_displayed_line;
875 #if ENABLE_FEATURE_LESS_REGEXP
877 goto_match(match_pos + num);
880 option_mask32 &= ~LESS_STATE_MATCH_BACKWARDS;
884 option_mask32 |= LESS_STATE_MATCH_BACKWARDS;
891 #if ENABLE_FEATURE_LESS_FLAGCS
892 static void flag_change(void)
898 keypress = less_getch();
902 option_mask32 ^= FLAG_M;
905 option_mask32 ^= FLAG_m;
908 option_mask32 ^= FLAG_E;
911 option_mask32 ^= FLAG_TILDE;
916 static void show_flag_status(void)
923 keypress = less_getch();
927 flag_val = option_mask32 & FLAG_M;
930 flag_val = option_mask32 & FLAG_m;
933 flag_val = option_mask32 & FLAG_TILDE;
936 flag_val = option_mask32 & FLAG_N;
939 flag_val = option_mask32 & FLAG_E;
947 printf(HIGHLIGHT"The status of the flag is: %u"NORMAL, flag_val != 0);
951 static void save_input_to_file(void)
953 const char *msg = "";
958 print_statusline("Log file: ");
959 current_line = less_gets(sizeof("Log file: ")-1);
960 if (strlen(current_line) > 0) {
961 fp = fopen(current_line, "w");
963 msg = "Error opening log file";
966 for (i = 0; i <= max_fline; i++)
967 fprintf(fp, "%s\n", flines[i]);
972 print_statusline(msg);
976 #if ENABLE_FEATURE_LESS_MARKS
977 static void add_mark(void)
981 print_statusline("Mark: ");
982 letter = less_getch();
984 if (isalpha(letter)) {
985 /* If we exceed 15 marks, start overwriting previous ones */
989 mark_lines[num_marks][0] = letter;
990 mark_lines[num_marks][1] = cur_fline;
993 print_statusline("Invalid mark letter");
997 static void goto_mark(void)
1002 print_statusline("Go to mark: ");
1003 letter = less_getch();
1006 if (isalpha(letter)) {
1007 for (i = 0; i <= num_marks; i++)
1008 if (letter == mark_lines[i][0]) {
1009 buffer_line(mark_lines[i][1]);
1012 if (num_marks == 14 && letter != mark_lines[14][0])
1013 print_statusline("Mark not set");
1015 print_statusline("Invalid mark letter");
1019 #if ENABLE_FEATURE_LESS_BRACKETS
1020 static char opp_bracket(char bracket)
1035 static void match_right_bracket(char bracket)
1037 int bracket_line = -1;
1040 if (strchr(flines[cur_fline], bracket) == NULL) {
1041 print_statusline("No bracket in top line");
1044 for (i = cur_fline + 1; i < max_fline; i++) {
1045 if (strchr(flines[i], opp_bracket(bracket)) != NULL) {
1050 if (bracket_line == -1)
1051 print_statusline("No matching bracket found");
1052 buffer_line(bracket_line - max_displayed_line);
1055 static void match_left_bracket(char bracket)
1057 int bracket_line = -1;
1060 if (strchr(flines[cur_fline + max_displayed_line], bracket) == NULL) {
1061 print_statusline("No bracket in bottom line");
1065 for (i = cur_fline + max_displayed_line; i >= 0; i--) {
1066 if (strchr(flines[i], opp_bracket(bracket)) != NULL) {
1071 if (bracket_line == -1)
1072 print_statusline("No matching bracket found");
1073 buffer_line(bracket_line);
1075 #endif /* FEATURE_LESS_BRACKETS */
1077 static void keypress_process(int keypress)
1080 case KEY_DOWN: case 'e': case 'j': case 0x0d:
1083 case KEY_UP: case 'y': case 'k':
1086 case PAGE_DOWN: case ' ': case 'z':
1087 buffer_down(max_displayed_line + 1);
1089 case PAGE_UP: case 'w': case 'b':
1090 buffer_up(max_displayed_line + 1);
1093 buffer_down((max_displayed_line + 1) / 2);
1096 buffer_up((max_displayed_line + 1) / 2);
1098 case KEY_HOME: case 'g': case 'p': case '<': case '%':
1101 case KEY_END: case 'G': case '>':
1102 cur_fline = MAXLINES;
1104 buffer_line(cur_fline);
1109 #if ENABLE_FEATURE_LESS_MARKS
1126 save_input_to_file();
1131 #if ENABLE_FEATURE_LESS_FLAGS
1136 #if ENABLE_FEATURE_LESS_REGEXP
1138 option_mask32 &= ~LESS_STATE_MATCH_BACKWARDS;
1142 goto_match(match_pos + 1);
1145 goto_match(match_pos - 1);
1148 option_mask32 |= LESS_STATE_MATCH_BACKWARDS;
1152 #if ENABLE_FEATURE_LESS_FLAGCS
1161 #if ENABLE_FEATURE_LESS_BRACKETS
1162 case '{': case '(': case '[':
1163 match_right_bracket(keypress);
1165 case '}': case ')': case ']':
1166 match_left_bracket(keypress);
1174 if (isdigit(keypress))
1175 number_process(keypress);
1178 static void sig_catcher(int sig ATTRIBUTE_UNUSED)
1184 int less_main(int argc, char **argv)
1188 /* TODO: -x: do not interpret backspace, -xx: tab also */
1189 /* -xxx: newline also */
1190 /* -w N: assume width N (-xxx -w 32: hex viewer of sorts) */
1191 getopt32(argc, argv, "EMmN~");
1197 /* Another popular pager, most, detects when stdout
1198 * is not a tty and turns into cat. This makes sense. */
1199 if (!isatty(STDOUT_FILENO))
1200 return bb_cat(argv);
1203 if (isatty(STDIN_FILENO)) {
1204 /* Just "less"? No args and no redirection? */
1205 bb_error_msg("missing filename");
1209 filename = xstrdup(files[0]);
1211 kbd_fd = xopen(CURRENT_TTY, O_RDONLY);
1213 get_terminal_width_height(kbd_fd, &width, &max_displayed_line);
1214 /* 20: two tabstops + 4 */
1215 if (width < 20 || max_displayed_line < 3)
1216 bb_error_msg_and_die("too narrow here");
1217 max_displayed_line -= 2;
1219 buffer = xmalloc((max_displayed_line+1) * sizeof(char *));
1220 if (option_mask32 & FLAG_TILDE)
1221 empty_line_marker = "";
1223 tcgetattr(kbd_fd, &term_orig);
1224 signal(SIGTERM, sig_catcher);
1225 signal(SIGINT, sig_catcher);
1226 term_vi = term_orig;
1227 term_vi.c_lflag &= ~(ICANON | ECHO);
1228 term_vi.c_iflag &= ~(IXON | ICRNL);
1229 /*term_vi.c_oflag &= ~ONLCR;*/
1230 term_vi.c_cc[VMIN] = 1;
1231 term_vi.c_cc[VTIME] = 0;
1233 /* Want to do it just once, but it doesn't work, */
1234 /* so we are redoing it (see code above). Mystery... */
1235 /*tcsetattr(kbd_fd, TCSANOW, &term_vi);*/
1239 keypress = less_getch();
1240 keypress_process(keypress);