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
32 #define ENABLE_FEATURE_LESS_REWRAP 0
34 /* FIXME: currently doesn't work right */
35 #undef ENABLE_FEATURE_LESS_FLAGCS
36 #define ENABLE_FEATURE_LESS_FLAGCS 0
38 /* The escape codes for highlighted and normal text */
39 #define HIGHLIGHT "\033[7m"
40 #define NORMAL "\033[0m"
41 /* The escape code to clear the screen */
42 #define CLEAR "\033[H\033[J"
43 /* The escape code to clear to end of line */
44 #define CLEAR_2_EOL "\033[K"
46 /* These are the escape sequences corresponding to special keys */
54 REAL_KEY_HOME = '7', // vt100? linux vt? or what?
56 REAL_KEY_HOME_ALT = '1', // ESC [1~ (vt100? linux vt? or what?)
57 REAL_KEY_END_ALT = '4', // ESC [4~
58 REAL_KEY_HOME_XTERM = 'H',
59 REAL_KEY_END_XTERM = 'F',
61 /* These are the special codes assigned by this program to the special keys */
71 /* Absolute max of lines eaten */
72 MAXLINES = CONFIG_FEATURE_LESS_MAXLINES,
74 /* This many "after the end" lines we will show (at max) */
78 /* Command line options */
86 /* hijack command line options variable for internal state vars */
87 LESS_STATE_NO_WRAP = 1 << 14,
88 LESS_STATE_MATCH_BACKWARDS = 1 << 15,
91 #if !ENABLE_FEATURE_LESS_REGEXP
92 enum { pattern_valid = 0 };
96 int cur_fline; /* signed */
97 int kbd_fd; /* fd to get input from */
99 /* last position in last line, taking into account tabs */
101 unsigned max_displayed_line;
103 unsigned max_lineno; /* this one tracks linewrap */
105 ssize_t eof_error; /* eof if 0, error if < 0 */
107 ssize_t readeof; /* must be signed */
110 const char *empty_line_marker;
112 unsigned current_file;
115 #if ENABLE_FEATURE_LESS_MARKS
117 unsigned mark_lines[15][2];
119 #if ENABLE_FEATURE_LESS_REGEXP
120 unsigned *match_lines;
121 int match_pos; /* signed! */
122 int wanted_match; /* signed! */
125 smallint pattern_valid;
128 struct termios term_orig, term_less;
130 #define G (*ptr_to_globals)
131 #define cur_fline (G.cur_fline )
132 #define kbd_fd (G.kbd_fd )
133 #define less_gets_pos (G.less_gets_pos )
134 #define linepos (G.linepos )
135 #define max_displayed_line (G.max_displayed_line)
136 #define max_fline (G.max_fline )
137 #define max_lineno (G.max_lineno )
138 #define width (G.width )
139 #define eof_error (G.eof_error )
140 #define readpos (G.readpos )
141 #define readeof (G.readeof )
142 #define buffer (G.buffer )
143 #define flines (G.flines )
144 #define empty_line_marker (G.empty_line_marker )
145 #define num_files (G.num_files )
146 #define current_file (G.current_file )
147 #define filename (G.filename )
148 #define files (G.files )
149 #define num_marks (G.num_marks )
150 #define mark_lines (G.mark_lines )
151 #if ENABLE_FEATURE_LESS_REGEXP
152 #define match_lines (G.match_lines )
153 #define match_pos (G.match_pos )
154 #define num_matches (G.num_matches )
155 #define wanted_match (G.wanted_match )
156 #define pattern (G.pattern )
157 #define pattern_valid (G.pattern_valid )
159 #define terminated (G.terminated )
160 #define term_orig (G.term_orig )
161 #define term_less (G.term_less )
162 #define INIT_G() do { \
163 SET_PTR_TO_GLOBALS(xzalloc(sizeof(G))); \
164 less_gets_pos = -1; \
165 empty_line_marker = "~"; \
170 USE_FEATURE_LESS_REGEXP(wanted_match = -1;) \
173 /* flines[] are lines read from stdin, each in malloc'ed buffer.
174 * Line numbers are stored as uint32_t prepended to each line.
175 * Pointer is adjusted so that flines[i] points directly past
176 * line number. Accesor: */
177 #define MEMPTR(p) ((char*)(p) - 4)
178 #define LINENO(p) (*(uint32_t*)((p) - 4))
181 /* Reset terminal input to normal */
182 static void set_tty_cooked(void)
185 tcsetattr(kbd_fd, TCSANOW, &term_orig);
188 /* Move the cursor to a position (x,y), where (0,0) is the
189 top-left corner of the console */
190 static void move_cursor(int line, int row)
192 printf("\033[%u;%uH", line, row);
195 static void clear_line(void)
197 printf("\033[%u;0H" CLEAR_2_EOL, max_displayed_line + 2);
200 static void print_hilite(const char *str)
202 printf(HIGHLIGHT"%s"NORMAL, str);
205 static void print_statusline(const char *str)
208 printf(HIGHLIGHT"%.*s"NORMAL, width - 1, str);
211 /* Exit the program gracefully */
212 static void less_exit(int code)
217 kill_myself_with_sig(- code); /* does not return */
221 #if ENABLE_FEATURE_LESS_REWRAP
222 static void re_wrap(void)
228 int new_cur_fline = 0;
231 const char **old_flines = flines;
233 char **new_flines = NULL;
236 if (option_mask32 & FLAG_N)
253 /* new line is full, create next one */
256 sz = (d - linebuf) + 1; /* + 1: NUL */
257 d = ((char*)xmalloc(sz + 4)) + 4;
259 memcpy(d, linebuf, sz);
260 new_flines = xrealloc_vector(new_flines, 8, dst_idx);
261 new_flines[dst_idx] = d;
264 /* did we come here thru "goto next_new"? */
265 if (src_idx > max_fline)
274 /* *d == NUL: old line ended, go to next old one */
275 free(MEMPTR(old_flines[src_idx]));
276 /* btw, convert cur_fline... */
277 if (cur_fline == src_idx) {
278 new_cur_fline = dst_idx;
281 /* no more lines? finish last new line (and exit the loop) */
282 if (src_idx > max_fline) {
285 s = old_flines[src_idx];
286 if (lineno != LINENO(s)) {
287 /* this is not a continuation line!
288 * create next _new_ line too */
294 flines = (const char **)new_flines;
296 max_fline = dst_idx - 1;
298 cur_fline = new_cur_fline;
299 /* max_lineno is screen-size independent */
303 #if ENABLE_FEATURE_LESS_REGEXP
304 static void fill_match_lines(unsigned pos);
306 #define fill_match_lines(pos) ((void)0)
309 /* Devilishly complex routine.
311 * Has to deal with EOF and EPIPE on input,
312 * with line wrapping, with last line not ending in '\n'
313 * (possibly not ending YET!), with backspace and tabs.
314 * It reads input again if last time we got an EOF (thus supporting
315 * growing files) or EPIPE (watching output of slow process like make).
318 * flines[] - array of lines already read. Linewrap may cause
319 * one source file line to occupy several flines[n].
320 * flines[max_fline] - last line, possibly incomplete.
321 * terminated - 1 if flines[max_fline] is 'terminated'
322 * (if there was '\n' [which isn't stored itself, we just remember
324 * max_lineno - last line's number, this one doesn't increment
325 * on line wrap, only on "real" new lines.
326 * readbuf[0..readeof-1] - small preliminary buffer.
327 * readbuf[readpos] - next character to add to current line.
328 * linepos - screen line position of next char to be read
329 * (takes into account tabs and backspaces)
330 * eof_error - < 0 error, == 0 EOF, > 0 not EOF/error
332 static void read_lines(void)
334 #define readbuf bb_common_bufsiz1
335 char *current_line, *p;
337 char last_terminated = terminated;
338 #if ENABLE_FEATURE_LESS_REGEXP
339 unsigned old_max_fline = max_fline;
340 time_t last_time = 0;
341 unsigned seconds_p1 = 3; /* seconds_to_loop + 1 */
344 if (option_mask32 & FLAG_N)
347 USE_FEATURE_LESS_REGEXP(again0:)
349 p = current_line = ((char*)xmalloc(w + 4)) + 4;
350 max_fline += last_terminated;
351 if (!last_terminated) {
352 const char *cp = flines[max_fline];
354 p += strlen(current_line);
355 free(MEMPTR(flines[max_fline]));
356 /* linepos is still valid from previous read_lines() */
361 while (1) { /* read lines until we reach cur_fline or wanted_match */
364 while (1) { /* read chars until we have a line */
366 /* if no unprocessed chars left, eat more */
367 if (readpos >= readeof) {
369 eof_error = safe_read(STDIN_FILENO, readbuf, sizeof(readbuf));
376 c = readbuf[readpos];
377 /* backspace? [needed for manpages] */
378 /* <tab><bs> is (a) insane and */
379 /* (b) harder to do correctly, so we refuse to do it */
380 if (c == '\x8' && linepos && p[-1] != '\t') {
381 readpos++; /* eat it */
383 /* was buggy (p could end up <= current_line)... */
388 size_t new_linepos = linepos + 1;
393 if ((int)new_linepos >= w)
395 linepos = new_linepos;
397 /* ok, we will eat this char */
404 /* NUL is substituted by '\n'! */
405 if (c == '\0') c = '\n';
408 } /* end of "read chars until we have a line" loop */
409 /* Corner case: linewrap with only "" wrapping to next line */
410 /* Looks ugly on screen, so we do not store this empty line */
411 if (!last_terminated && !current_line[0]) {
417 last_terminated = terminated;
418 flines = xrealloc_vector(flines, 8, max_fline);
420 flines[max_fline] = (char*)xrealloc(MEMPTR(current_line), strlen(current_line) + 1 + 4) + 4;
421 LINENO(flines[max_fline]) = max_lineno;
425 if (max_fline >= MAXLINES) {
426 eof_error = 0; /* Pretend we saw EOF */
429 if (max_fline > cur_fline + max_displayed_line) {
430 #if !ENABLE_FEATURE_LESS_REGEXP
433 if (wanted_match >= num_matches) { /* goto_match called us */
434 fill_match_lines(old_max_fline);
435 old_max_fline = max_fline;
437 if (wanted_match < num_matches)
441 if (eof_error <= 0) {
443 if (errno == EAGAIN) {
444 /* not yet eof or error, reset flag (or else
445 * we will hog CPU - select() will return
449 print_statusline("read error");
452 #if !ENABLE_FEATURE_LESS_REGEXP
455 if (wanted_match < num_matches) {
457 } else { /* goto_match called us */
458 time_t t = time(NULL);
459 if (t != last_time) {
461 if (--seconds_p1 == 0)
465 goto again0; /* go loop again (max 2 seconds) */
470 current_line = ((char*)xmalloc(w + 4)) + 4;
473 } /* end of "read lines until we reach cur_fline" loop */
474 fill_match_lines(old_max_fline);
475 #if ENABLE_FEATURE_LESS_REGEXP
476 /* prevent us from being stuck in search for a match */
482 #if ENABLE_FEATURE_LESS_FLAGS
483 /* Interestingly, writing calc_percent as a function saves around 32 bytes
485 static int calc_percent(void)
487 unsigned p = (100 * (cur_fline+max_displayed_line+1) + max_fline/2) / (max_fline+1);
488 return p <= 100 ? p : 100;
491 /* Print a status line if -M was specified */
492 static void m_status_print(void)
496 if (less_gets_pos >= 0) /* don't touch statusline while input is done! */
500 printf(HIGHLIGHT"%s", filename);
502 printf(" (file %i of %i)", current_file, num_files);
503 printf(" lines %i-%i/%i ",
504 cur_fline + 1, cur_fline + max_displayed_line + 1,
506 if (cur_fline >= (int)(max_fline - max_displayed_line)) {
507 printf("(END)"NORMAL);
508 if (num_files > 1 && current_file != num_files)
509 printf(HIGHLIGHT" - next: %s"NORMAL, files[current_file]);
512 percentage = calc_percent();
513 printf("%i%%"NORMAL, percentage);
517 /* Print the status line */
518 static void status_print(void)
522 if (less_gets_pos >= 0) /* don't touch statusline while input is done! */
525 /* Change the status if flags have been set */
526 #if ENABLE_FEATURE_LESS_FLAGS
527 if (option_mask32 & (FLAG_M|FLAG_m)) {
535 if (cur_fline && cur_fline < (int)(max_fline - max_displayed_line)) {
543 printf(HIGHLIGHT"%s (file %i of %i)"NORMAL,
544 p, current_file, num_files);
550 static void cap_cur_fline(int nlines)
555 if (cur_fline + max_displayed_line > max_fline + TILDES) {
559 diff = max_fline - (cur_fline + max_displayed_line) + TILDES;
560 /* As the number of lines requested was too large, we just move
561 to the end of the file */
567 static const char controls[] ALIGN1 =
568 /* NUL: never encountered; TAB: not converted */
569 /**/"\x01\x02\x03\x04\x05\x06\x07\x08" "\x0a\x0b\x0c\x0d\x0e\x0f"
570 "\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1a\x1b\x1c\x1d\x1e\x1f"
571 "\x7f\x9b"; /* DEL and infamous Meta-ESC :( */
572 static const char ctrlconv[] ALIGN1 =
573 /* '\n': it's a former NUL - subst with '@', not 'J' */
574 "\x40\x41\x42\x43\x44\x45\x46\x47\x48\x49\x40\x4b\x4c\x4d\x4e\x4f"
575 "\x50\x51\x52\x53\x54\x55\x56\x57\x58\x59\x5a\x5b\x5c\x5d\x5e\x5f";
577 static void lineno_str(char *nbuf9, const char *line)
580 if (option_mask32 & FLAG_N) {
584 if (line == empty_line_marker) {
585 memset(nbuf9, ' ', 8);
589 /* Width of 7 preserves tab spacing in the text */
591 n = LINENO(line) + 1;
596 sprintf(nbuf9, fmt, n);
601 #if ENABLE_FEATURE_LESS_REGEXP
602 static void print_found(const char *line)
607 regmatch_t match_structs;
611 const char *str = line;
616 n = strcspn(str, controls);
623 n = strspn(str, controls);
630 /* buf[] holds quarantined version of str */
632 /* Each part of the line that matches has the HIGHLIGHT
633 and NORMAL escape sequences placed around it.
634 NB: we regex against line, but insert text
635 from quarantined copy (buf[]) */
641 while (match_status == 0) {
642 char *new = xasprintf("%s%.*s"HIGHLIGHT"%.*s"NORMAL,
644 match_structs.rm_so, str,
645 match_structs.rm_eo - match_structs.rm_so,
646 str + match_structs.rm_so);
649 str += match_structs.rm_eo;
650 line += match_structs.rm_eo;
653 /* Most of the time doesn't find the regex, optimize for that */
654 match_status = regexec(&pattern, line, 1, &match_structs, eflags);
655 /* if even "" matches, treat it as "not a match" */
656 if (match_structs.rm_so >= match_structs.rm_eo)
660 lineno_str(nbuf9, line);
662 printf(CLEAR_2_EOL"%s%s\n", nbuf9, str);
665 printf(CLEAR_2_EOL"%s%s%s\n", nbuf9, growline, str);
669 void print_found(const char *line);
672 static void print_ascii(const char *str)
679 lineno_str(nbuf9, str);
680 printf(CLEAR_2_EOL"%s", nbuf9);
683 n = strcspn(str, controls);
686 printf("%.*s", (int) n, str);
689 n = strspn(str, controls);
694 else if (*str == (char)0x9b)
695 /* VT100's CSI, aka Meta-ESC. Who's inventor? */
696 /* I want to know who committed this sin */
699 *p++ = ctrlconv[(unsigned char)*str];
708 /* Print the buffer */
709 static void buffer_print(void)
714 for (i = 0; i <= max_displayed_line; i++)
716 print_found(buffer[i]);
718 print_ascii(buffer[i]);
722 #if ENABLE_FEATURE_LESS_REWRAP
723 static void buffer_fill_and_print(void)
726 int fpos = cur_fline + i;
728 if (option_mask32 & LESS_STATE_NO_WRAP) {
729 /* Go back to the beginning of this line */
730 while (fpos && LINENO(flines[fpos]) == LINENO(flines[fpos-1]))
734 while (i <= max_displayed_line && fpos <= max_fline) {
735 int lineno = LINENO(flines[fpos]);
736 buffer[i] = flines[fpos];
740 } while ((fpos <= max_fline)
741 && (option_mask32 & LESS_STATE_NO_WRAP)
742 && lineno == LINENO(flines[fpos])
745 for (; i <= max_displayed_line; i++) {
746 buffer[i] = empty_line_marker;
751 static void buffer_fill_and_print(void)
754 for (i = 0; i <= max_displayed_line && cur_fline + i <= max_fline; i++) {
755 buffer[i] = flines[cur_fline + i];
757 for (; i <= max_displayed_line; i++) {
758 buffer[i] = empty_line_marker;
764 /* Move the buffer up and down in the file in order to scroll */
765 static void buffer_down(int nlines)
769 cap_cur_fline(nlines);
770 buffer_fill_and_print();
773 static void buffer_up(int nlines)
776 if (cur_fline < 0) cur_fline = 0;
778 buffer_fill_and_print();
781 static void buffer_line(int linenum)
787 if (linenum + max_displayed_line > max_fline)
788 linenum = max_fline - max_displayed_line + TILDES;
792 buffer_fill_and_print();
795 static void open_file_and_read_lines(void)
798 int fd = xopen(filename, O_RDONLY);
802 /* "less" with no arguments in argv[] */
803 /* For status line only */
804 filename = xstrdup(bb_msg_standard_input);
813 /* Reinitialize everything for a new file - free the memory and start over */
814 static void reinitialize(void)
819 for (i = 0; i <= max_fline; i++)
820 free(MEMPTR(flines[i]));
828 open_file_and_read_lines();
829 buffer_fill_and_print();
832 static ssize_t getch_nowait(char* input, int sz)
835 struct pollfd pfd[2];
837 pfd[0].fd = STDIN_FILENO;
838 pfd[0].events = POLLIN;
840 pfd[1].events = POLLIN;
842 tcsetattr(kbd_fd, TCSANOW, &term_less);
843 /* NB: select/poll returns whenever read will not block. Therefore:
844 * if eof is reached, select/poll will return immediately
845 * because read will immediately return 0 bytes.
846 * Even if select/poll says that input is available, read CAN block
847 * (switch fd into O_NONBLOCK'ed mode to avoid it)
850 if (max_fline <= cur_fline + max_displayed_line
851 && eof_error > 0 /* did NOT reach eof yet */
853 /* We are interested in stdin */
856 /* position cursor if line input is done */
857 if (less_gets_pos >= 0)
858 move_cursor(max_displayed_line + 2, less_gets_pos + 1);
860 safe_poll(pfd + rd, 2 - rd, -1);
863 rd = safe_read(kbd_fd, input, sz); /* NB: kbd_fd is in O_NONBLOCK mode */
864 if (rd < 0 && errno == EAGAIN) {
865 /* No keyboard input -> we have input on stdin! */
867 buffer_fill_and_print();
874 /* Grab a character from input without requiring the return key. If the
875 * character is ASCII \033, get more characters and assign certain sequences
876 * special return codes. Note that this function works best with raw input. */
877 static int less_getch(int pos)
879 unsigned char input[16];
884 memset(input, 0, sizeof(input));
885 getch_nowait((char *)input, sizeof(input));
888 /* Detect escape sequences (i.e. arrow keys) and handle
889 * them accordingly */
890 if (input[0] == '\033' && input[1] == '[') {
891 i = input[2] - REAL_KEY_UP;
894 i = input[2] - REAL_PAGE_UP;
897 if (input[2] == REAL_KEY_HOME_XTERM)
899 if (input[2] == REAL_KEY_HOME_ALT)
901 if (input[2] == REAL_KEY_END_XTERM)
903 if (input[2] == REAL_KEY_END_ALT)
907 /* Reject almost all control chars */
909 if (i < ' ' && i != 0x0d && i != 8)
914 static char* less_gets(int sz)
918 char *result = xzalloc(1);
922 less_gets_pos = sz + i;
937 if (i >= width - sz - 1)
938 continue; /* len limit */
941 result = xrealloc(result, i+1);
945 static void examine_file(void)
949 print_statusline("Examine: ");
950 new_fname = less_gets(sizeof("Examine: ") - 1);
957 if (access(new_fname, R_OK) != 0) {
958 print_statusline("Cannot read this file");
962 filename = new_fname;
963 /* files start by = argv. why we assume that argv is infinitely long??
964 files[num_files] = filename;
965 current_file = num_files + 1;
968 num_files = current_file = 1;
972 /* This function changes the file currently being paged. direction can be one of the following:
973 * -1: go back one file
974 * 0: go to the first file
975 * 1: go forward one file */
976 static void change_file(int direction)
978 if (current_file != ((direction > 0) ? num_files : 1)) {
979 current_file = direction ? current_file + direction : 1;
981 filename = xstrdup(files[current_file - 1]);
984 print_statusline(direction > 0 ? "No next file" : "No previous file");
988 static void remove_current_file(void)
995 if (current_file != 1) {
997 for (i = 3; i <= num_files; i++)
998 files[i - 2] = files[i - 1];
1002 for (i = 2; i <= num_files; i++)
1003 files[i - 2] = files[i - 1];
1009 static void colon_process(void)
1013 /* Clear the current line and print a prompt */
1014 print_statusline(" :");
1016 keypress = less_getch(2);
1019 remove_current_file();
1024 #if ENABLE_FEATURE_LESS_FLAGS
1036 less_exit(EXIT_SUCCESS);
1044 #if ENABLE_FEATURE_LESS_REGEXP
1045 static void normalize_match_pos(int match)
1047 if (match >= num_matches)
1048 match = num_matches - 1;
1054 static void goto_match(int match)
1060 /* Try to find next match if eof isn't reached yet */
1061 if (match >= num_matches && eof_error > 0) {
1062 wanted_match = match; /* "I want to read until I see N'th match" */
1066 normalize_match_pos(match);
1067 buffer_line(match_lines[match_pos]);
1069 print_statusline("No matches found");
1073 static void fill_match_lines(unsigned pos)
1077 /* Run the regex on each line of the current file */
1078 while (pos <= max_fline) {
1079 /* If this line matches */
1080 if (regexec(&pattern, flines[pos], 0, NULL, 0) == 0
1081 /* and we didn't match it last time */
1082 && !(num_matches && match_lines[num_matches-1] == pos)
1084 match_lines = xrealloc_vector(match_lines, 4, num_matches);
1085 match_lines[num_matches++] = pos;
1091 static void regex_process(void)
1093 char *uncomp_regex, *err;
1095 /* Reset variables */
1100 if (pattern_valid) {
1105 /* Get the uncompiled regular expression from the user */
1107 bb_putchar((option_mask32 & LESS_STATE_MATCH_BACKWARDS) ? '?' : '/');
1108 uncomp_regex = less_gets(1);
1109 if (!uncomp_regex[0]) {
1115 /* Compile the regex and check for errors */
1116 err = regcomp_or_errmsg(&pattern, uncomp_regex,
1117 option_mask32 & FLAG_I ? REG_ICASE : 0);
1120 print_statusline(err);
1127 fill_match_lines(0);
1128 while (match_pos < num_matches) {
1129 if ((int)match_lines[match_pos] > cur_fline)
1133 if (option_mask32 & LESS_STATE_MATCH_BACKWARDS)
1136 /* It's possible that no matches are found yet.
1137 * goto_match() will read input looking for match,
1139 goto_match(match_pos);
1143 static void number_process(int first_digit)
1147 char num_input[sizeof(int)*4]; /* more than enough */
1150 num_input[0] = first_digit;
1152 /* Clear the current line, print a prompt, and then print the digit */
1154 printf(":%c", first_digit);
1156 /* Receive input until a letter is given */
1158 while (i < sizeof(num_input)-1) {
1159 num_input[i] = less_getch(i + 1);
1160 if (!num_input[i] || !isdigit(num_input[i]))
1162 bb_putchar(num_input[i]);
1166 /* Take the final letter out of the digits string */
1167 keypress = num_input[i];
1168 num_input[i] = '\0';
1169 num = bb_strtou(num_input, NULL, 10);
1170 /* on format error, num == -1 */
1171 if (num < 1 || num > MAXLINES) {
1176 /* We now know the number and the letter entered, so we process them */
1178 case KEY_DOWN: case 'z': case 'd': case 'e': case ' ': case '\015':
1181 case KEY_UP: case 'b': case 'w': case 'y': case 'u':
1184 case 'g': case '<': case 'G': case '>':
1185 cur_fline = num + max_displayed_line;
1187 buffer_line(num - 1);
1190 num = num * (max_fline / 100); /* + max_fline / 2; */
1191 cur_fline = num + max_displayed_line;
1195 #if ENABLE_FEATURE_LESS_REGEXP
1197 goto_match(match_pos + num);
1200 option_mask32 &= ~LESS_STATE_MATCH_BACKWARDS;
1204 option_mask32 |= LESS_STATE_MATCH_BACKWARDS;
1211 #if ENABLE_FEATURE_LESS_FLAGCS
1212 static void flag_change(void)
1218 keypress = less_getch(1);
1222 option_mask32 ^= FLAG_M;
1225 option_mask32 ^= FLAG_m;
1228 option_mask32 ^= FLAG_E;
1231 option_mask32 ^= FLAG_TILDE;
1236 static void show_flag_status(void)
1243 keypress = less_getch(1);
1247 flag_val = option_mask32 & FLAG_M;
1250 flag_val = option_mask32 & FLAG_m;
1253 flag_val = option_mask32 & FLAG_TILDE;
1256 flag_val = option_mask32 & FLAG_N;
1259 flag_val = option_mask32 & FLAG_E;
1267 printf(HIGHLIGHT"The status of the flag is: %u"NORMAL, flag_val != 0);
1271 static void save_input_to_file(void)
1273 const char *msg = "";
1278 print_statusline("Log file: ");
1279 current_line = less_gets(sizeof("Log file: ")-1);
1280 if (current_line[0]) {
1281 fp = fopen_for_write(current_line);
1283 msg = "Error opening log file";
1286 for (i = 0; i <= max_fline; i++)
1287 fprintf(fp, "%s\n", flines[i]);
1292 print_statusline(msg);
1296 #if ENABLE_FEATURE_LESS_MARKS
1297 static void add_mark(void)
1301 print_statusline("Mark: ");
1302 letter = less_getch(sizeof("Mark: ") - 1);
1304 if (isalpha(letter)) {
1305 /* If we exceed 15 marks, start overwriting previous ones */
1306 if (num_marks == 14)
1309 mark_lines[num_marks][0] = letter;
1310 mark_lines[num_marks][1] = cur_fline;
1313 print_statusline("Invalid mark letter");
1317 static void goto_mark(void)
1322 print_statusline("Go to mark: ");
1323 letter = less_getch(sizeof("Go to mark: ") - 1);
1326 if (isalpha(letter)) {
1327 for (i = 0; i <= num_marks; i++)
1328 if (letter == mark_lines[i][0]) {
1329 buffer_line(mark_lines[i][1]);
1332 if (num_marks == 14 && letter != mark_lines[14][0])
1333 print_statusline("Mark not set");
1335 print_statusline("Invalid mark letter");
1339 #if ENABLE_FEATURE_LESS_BRACKETS
1340 static char opp_bracket(char bracket)
1343 case '{': case '[': /* '}' == '{' + 2. Same for '[' */
1345 case '(': /* ')' == '(' + 1 */
1357 static void match_right_bracket(char bracket)
1361 if (strchr(flines[cur_fline], bracket) == NULL) {
1362 print_statusline("No bracket in top line");
1365 bracket = opp_bracket(bracket);
1366 for (i = cur_fline + 1; i < max_fline; i++) {
1367 if (strchr(flines[i], bracket) != NULL) {
1372 print_statusline("No matching bracket found");
1375 static void match_left_bracket(char bracket)
1379 if (strchr(flines[cur_fline + max_displayed_line], bracket) == NULL) {
1380 print_statusline("No bracket in bottom line");
1384 bracket = opp_bracket(bracket);
1385 for (i = cur_fline + max_displayed_line; i >= 0; i--) {
1386 if (strchr(flines[i], bracket) != NULL) {
1391 print_statusline("No matching bracket found");
1393 #endif /* FEATURE_LESS_BRACKETS */
1395 static void keypress_process(int keypress)
1398 case KEY_DOWN: case 'e': case 'j': case 0x0d:
1401 case KEY_UP: case 'y': case 'k':
1404 case PAGE_DOWN: case ' ': case 'z': case 'f':
1405 buffer_down(max_displayed_line + 1);
1407 case PAGE_UP: case 'w': case 'b':
1408 buffer_up(max_displayed_line + 1);
1411 buffer_down((max_displayed_line + 1) / 2);
1414 buffer_up((max_displayed_line + 1) / 2);
1416 case KEY_HOME: case 'g': case 'p': case '<': case '%':
1419 case KEY_END: case 'G': case '>':
1420 cur_fline = MAXLINES;
1422 buffer_line(cur_fline);
1425 less_exit(EXIT_SUCCESS);
1427 #if ENABLE_FEATURE_LESS_MARKS
1444 save_input_to_file();
1449 #if ENABLE_FEATURE_LESS_FLAGS
1454 #if ENABLE_FEATURE_LESS_REGEXP
1456 option_mask32 &= ~LESS_STATE_MATCH_BACKWARDS;
1460 goto_match(match_pos + 1);
1463 goto_match(match_pos - 1);
1466 option_mask32 |= LESS_STATE_MATCH_BACKWARDS;
1470 #if ENABLE_FEATURE_LESS_FLAGCS
1479 #if ENABLE_FEATURE_LESS_BRACKETS
1480 case '{': case '(': case '[':
1481 match_right_bracket(keypress);
1483 case '}': case ')': case ']':
1484 match_left_bracket(keypress);
1490 #if ENABLE_FEATURE_LESS_REWRAP
1491 case '*': /* Should be -N command / option */
1492 option_mask32 ^= FLAG_N;
1493 get_terminal_width_height(kbd_fd, &width, &max_displayed_line);
1494 if (width < 20) /* 20: two tabstops + 4 */
1496 if (max_displayed_line < 3)
1497 max_displayed_line = 3;
1498 max_displayed_line -= 2;
1500 buffer = xmalloc((max_displayed_line+1) * sizeof(char *));
1502 buffer_fill_and_print();
1504 case '&': /* Should be -S command / option */
1505 option_mask32 ^= LESS_STATE_NO_WRAP;
1506 buffer_fill_and_print();
1511 if (isdigit(keypress))
1512 number_process(keypress);
1515 static void sig_catcher(int sig)
1520 int less_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
1521 int less_main(int argc, char **argv)
1527 /* TODO: -x: do not interpret backspace, -xx: tab also */
1528 /* -xxx: newline also */
1529 /* -w N: assume width N (-xxx -w 32: hex viewer of sorts) */
1530 getopt32(argv, "EMmN~I");
1536 /* Another popular pager, most, detects when stdout
1537 * is not a tty and turns into cat. This makes sense. */
1538 if (!isatty(STDOUT_FILENO))
1539 return bb_cat(argv);
1540 kbd_fd = open(CURRENT_TTY, O_RDONLY);
1542 return bb_cat(argv);
1546 if (isatty(STDIN_FILENO)) {
1547 /* Just "less"? No args and no redirection? */
1548 bb_error_msg("missing filename");
1552 filename = xstrdup(files[0]);
1554 get_terminal_width_height(kbd_fd, &width, &max_displayed_line);
1555 /* 20: two tabstops + 4 */
1556 if (width < 20 || max_displayed_line < 3)
1557 return bb_cat(argv);
1558 max_displayed_line -= 2;
1560 buffer = xmalloc((max_displayed_line+1) * sizeof(char *));
1561 if (option_mask32 & FLAG_TILDE)
1562 empty_line_marker = "";
1564 tcgetattr(kbd_fd, &term_orig);
1565 term_less = term_orig;
1566 term_less.c_lflag &= ~(ICANON | ECHO);
1567 term_less.c_iflag &= ~(IXON | ICRNL);
1568 /*term_less.c_oflag &= ~ONLCR;*/
1569 term_less.c_cc[VMIN] = 1;
1570 term_less.c_cc[VTIME] = 0;
1572 /* We want to restore term_orig on exit */
1573 bb_signals(BB_FATAL_SIGS, sig_catcher);
1577 keypress = less_getch(-1); /* -1: do not position cursor */
1578 keypress_process(keypress);
1583 Help text of less version 418 is below.
1584 If you are implementing something, keeping
1585 key and/or command line switch compatibility is a good idea:
1588 SUMMARY OF LESS COMMANDS
1590 Commands marked with * may be preceded by a number, N.
1591 Notes in parentheses indicate the behavior if N is given.
1592 h H Display this help.
1594 ---------------------------------------------------------------------------
1596 e ^E j ^N CR * Forward one line (or N lines).
1597 y ^Y k ^K ^P * Backward one line (or N lines).
1598 f ^F ^V SPACE * Forward one window (or N lines).
1599 b ^B ESC-v * Backward one window (or N lines).
1600 z * Forward one window (and set window to N).
1601 w * Backward one window (and set window to N).
1602 ESC-SPACE * Forward one window, but don't stop at end-of-file.
1603 d ^D * Forward one half-window (and set half-window to N).
1604 u ^U * Backward one half-window (and set half-window to N).
1605 ESC-) RightArrow * Left one half screen width (or N positions).
1606 ESC-( LeftArrow * Right one half screen width (or N positions).
1607 F Forward forever; like "tail -f".
1608 r ^R ^L Repaint screen.
1609 R Repaint screen, discarding buffered input.
1610 ---------------------------------------------------
1611 Default "window" is the screen height.
1612 Default "half-window" is half of the screen height.
1613 ---------------------------------------------------------------------------
1615 /pattern * Search forward for (N-th) matching line.
1616 ?pattern * Search backward for (N-th) matching line.
1617 n * Repeat previous search (for N-th occurrence).
1618 N * Repeat previous search in reverse direction.
1619 ESC-n * Repeat previous search, spanning files.
1620 ESC-N * Repeat previous search, reverse dir. & spanning files.
1621 ESC-u Undo (toggle) search highlighting.
1622 ---------------------------------------------------
1623 Search patterns may be modified by one or more of:
1624 ^N or ! Search for NON-matching lines.
1625 ^E or * Search multiple files (pass thru END OF FILE).
1626 ^F or @ Start search at FIRST file (for /) or last file (for ?).
1627 ^K Highlight matches, but don't move (KEEP position).
1628 ^R Don't use REGULAR EXPRESSIONS.
1629 ---------------------------------------------------------------------------
1631 g < ESC-< * Go to first line in file (or line N).
1632 G > ESC-> * Go to last line in file (or line N).
1633 p % * Go to beginning of file (or N percent into file).
1634 t * Go to the (N-th) next tag.
1635 T * Go to the (N-th) previous tag.
1636 { ( [ * Find close bracket } ) ].
1637 } ) ] * Find open bracket { ( [.
1638 ESC-^F <c1> <c2> * Find close bracket <c2>.
1639 ESC-^B <c1> <c2> * Find open bracket <c1>
1640 ---------------------------------------------------
1641 Each "find close bracket" command goes forward to the close bracket
1642 matching the (N-th) open bracket in the top line.
1643 Each "find open bracket" command goes backward to the open bracket
1644 matching the (N-th) close bracket in the bottom line.
1645 m<letter> Mark the current position with <letter>.
1646 '<letter> Go to a previously marked position.
1647 '' Go to the previous position.
1649 ---------------------------------------------------
1650 A mark is any upper-case or lower-case letter.
1651 Certain marks are predefined:
1652 ^ means beginning of the file
1653 $ means end of the file
1654 ---------------------------------------------------------------------------
1656 :e [file] Examine a new file.
1658 :n * Examine the (N-th) next file from the command line.
1659 :p * Examine the (N-th) previous file from the command line.
1660 :x * Examine the first (or N-th) file from the command line.
1661 :d Delete the current file from the command line list.
1662 = ^G :f Print current file name.
1663 ---------------------------------------------------------------------------
1664 MISCELLANEOUS COMMANDS
1665 -<flag> Toggle a command line option [see OPTIONS below].
1666 --<name> Toggle a command line option, by name.
1667 _<flag> Display the setting of a command line option.
1668 __<name> Display the setting of an option, by name.
1669 +cmd Execute the less cmd each time a new file is examined.
1670 !command Execute the shell command with $SHELL.
1671 |Xcommand Pipe file between current pos & mark X to shell command.
1672 v Edit the current file with $VISUAL or $EDITOR.
1673 V Print version number of "less".
1674 ---------------------------------------------------------------------------
1676 Most options may be changed either on the command line,
1677 or from within less by using the - or -- command.
1678 Options may be given in one of two forms: either a single
1679 character preceded by a -, or a name preceeded by --.
1681 Display help (from command line).
1682 -a ........ --search-skip-screen
1683 Forward search skips current screen.
1684 -b [N] .... --buffers=[N]
1686 -B ........ --auto-buffers
1687 Don't automatically allocate buffers for pipes.
1688 -c ........ --clear-screen
1689 Repaint by clearing rather than scrolling.
1692 -D [xn.n] . --color=xn.n
1693 Set screen colors. (MS-DOS only)
1694 -e -E .... --quit-at-eof --QUIT-AT-EOF
1695 Quit at end of file.
1697 Force open non-regular files.
1698 -F ........ --quit-if-one-screen
1699 Quit if entire file fits on first screen.
1700 -g ........ --hilite-search
1701 Highlight only last match for searches.
1702 -G ........ --HILITE-SEARCH
1703 Don't highlight any matches for searches.
1704 -h [N] .... --max-back-scroll=[N]
1705 Backward scroll limit.
1706 -i ........ --ignore-case
1707 Ignore case in searches that do not contain uppercase.
1708 -I ........ --IGNORE-CASE
1709 Ignore case in all searches.
1710 -j [N] .... --jump-target=[N]
1711 Screen position of target lines.
1712 -J ........ --status-column
1713 Display a status column at left edge of screen.
1714 -k [file] . --lesskey-file=[file]
1716 -L ........ --no-lessopen
1717 Ignore the LESSOPEN environment variable.
1718 -m -M .... --long-prompt --LONG-PROMPT
1720 -n -N .... --line-numbers --LINE-NUMBERS
1721 Don't use line numbers.
1722 -o [file] . --log-file=[file]
1723 Copy to log file (standard input only).
1724 -O [file] . --LOG-FILE=[file]
1725 Copy to log file (unconditionally overwrite).
1726 -p [pattern] --pattern=[pattern]
1727 Start at pattern (from command line).
1728 -P [prompt] --prompt=[prompt]
1730 -q -Q .... --quiet --QUIET --silent --SILENT
1731 Quiet the terminal bell.
1732 -r -R .... --raw-control-chars --RAW-CONTROL-CHARS
1733 Output "raw" control characters.
1734 -s ........ --squeeze-blank-lines
1735 Squeeze multiple blank lines.
1736 -S ........ --chop-long-lines
1738 -t [tag] .. --tag=[tag]
1740 -T [tagsfile] --tag-file=[tagsfile]
1741 Use an alternate tags file.
1742 -u -U .... --underline-special --UNDERLINE-SPECIAL
1743 Change handling of backspaces.
1744 -V ........ --version
1745 Display the version number of "less".
1746 -w ........ --hilite-unread
1747 Highlight first new line after forward-screen.
1748 -W ........ --HILITE-UNREAD
1749 Highlight first new line after any forward movement.
1750 -x [N[,...]] --tabs=[N[,...]]
1752 -X ........ --no-init
1753 Don't use termcap init/deinit strings.
1755 Don't use termcap keypad init/deinit strings.
1756 -y [N] .... --max-forw-scroll=[N]
1757 Forward scroll limit.
1758 -z [N] .... --window=[N]
1760 -" [c[c]] . --quotes=[c[c]]
1761 Set shell quote characters.
1763 Don't display tildes after end of file.
1764 -# [N] .... --shift=[N]
1765 Horizontal scroll amount (0 = one half screen width)
1767 ---------------------------------------------------------------------------
1769 These keys can be used to edit text being entered
1770 on the "command line" at the bottom of the screen.
1771 RightArrow ESC-l Move cursor right one character.
1772 LeftArrow ESC-h Move cursor left one character.
1773 CNTL-RightArrow ESC-RightArrow ESC-w Move cursor right one word.
1774 CNTL-LeftArrow ESC-LeftArrow ESC-b Move cursor left one word.
1775 HOME ESC-0 Move cursor to start of line.
1776 END ESC-$ Move cursor to end of line.
1777 BACKSPACE Delete char to left of cursor.
1778 DELETE ESC-x Delete char under cursor.
1779 CNTL-BACKSPACE ESC-BACKSPACE Delete word to left of cursor.
1780 CNTL-DELETE ESC-DELETE ESC-X Delete word under cursor.
1781 CNTL-U ESC (MS-DOS only) Delete entire line.
1782 UpArrow ESC-k Retrieve previous command line.
1783 DownArrow ESC-j Retrieve next command line.
1784 TAB Complete filename & cycle.
1785 SHIFT-TAB ESC-TAB Complete filename & reverse cycle.
1786 CNTL-L Complete filename, list all.