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 /* The escape codes for highlighted and normal text */
32 #define HIGHLIGHT "\033[7m"
33 #define NORMAL "\033[0m"
34 /* The escape code to clear the screen */
35 #define CLEAR "\033[H\033[J"
36 /* The escape code to clear to end of line */
37 #define CLEAR_2_EOL "\033[K"
40 /* Absolute max of lines eaten */
41 MAXLINES = CONFIG_FEATURE_LESS_MAXLINES,
42 /* This many "after the end" lines we will show (at max) */
46 /* Command line options */
54 FLAG_S = (1 << 6) * ENABLE_FEATURE_LESS_DASHCMD,
55 /* hijack command line options variable for internal state vars */
56 LESS_STATE_MATCH_BACKWARDS = 1 << 15,
59 #if !ENABLE_FEATURE_LESS_REGEXP
60 enum { pattern_valid = 0 };
64 int cur_fline; /* signed */
65 int kbd_fd; /* fd to get input from */
67 /* last position in last line, taking into account tabs */
70 unsigned max_lineno; /* this one tracks linewrap */
71 unsigned max_displayed_line;
73 #if ENABLE_FEATURE_LESS_WINCH
74 unsigned winch_counter;
76 ssize_t eof_error; /* eof if 0, error if < 0 */
78 ssize_t readeof; /* must be signed */
81 const char *empty_line_marker;
83 unsigned current_file;
86 #if ENABLE_FEATURE_LESS_MARKS
88 unsigned mark_lines[15][2];
90 #if ENABLE_FEATURE_LESS_REGEXP
91 unsigned *match_lines;
92 int match_pos; /* signed! */
93 int wanted_match; /* signed! */
96 smallint pattern_valid;
99 struct termios term_orig, term_less;
100 char kbd_input[KEYCODE_BUFFER_SIZE];
102 #define G (*ptr_to_globals)
103 #define cur_fline (G.cur_fline )
104 #define kbd_fd (G.kbd_fd )
105 #define less_gets_pos (G.less_gets_pos )
106 #define last_line_pos (G.last_line_pos )
107 #define max_fline (G.max_fline )
108 #define max_lineno (G.max_lineno )
109 #define max_displayed_line (G.max_displayed_line)
110 #define width (G.width )
111 #define winch_counter (G.winch_counter )
112 /* This one is 100% not cached by compiler on read access */
113 #define WINCH_COUNTER (*(volatile unsigned *)&winch_counter)
114 #define eof_error (G.eof_error )
115 #define readpos (G.readpos )
116 #define readeof (G.readeof )
117 #define buffer (G.buffer )
118 #define flines (G.flines )
119 #define empty_line_marker (G.empty_line_marker )
120 #define num_files (G.num_files )
121 #define current_file (G.current_file )
122 #define filename (G.filename )
123 #define files (G.files )
124 #define num_marks (G.num_marks )
125 #define mark_lines (G.mark_lines )
126 #if ENABLE_FEATURE_LESS_REGEXP
127 #define match_lines (G.match_lines )
128 #define match_pos (G.match_pos )
129 #define num_matches (G.num_matches )
130 #define wanted_match (G.wanted_match )
131 #define pattern (G.pattern )
132 #define pattern_valid (G.pattern_valid )
134 #define terminated (G.terminated )
135 #define term_orig (G.term_orig )
136 #define term_less (G.term_less )
137 #define kbd_input (G.kbd_input )
138 #define INIT_G() do { \
139 SET_PTR_TO_GLOBALS(xzalloc(sizeof(G))); \
140 less_gets_pos = -1; \
141 empty_line_marker = "~"; \
146 IF_FEATURE_LESS_REGEXP(wanted_match = -1;) \
149 /* flines[] are lines read from stdin, each in malloc'ed buffer.
150 * Line numbers are stored as uint32_t prepended to each line.
151 * Pointer is adjusted so that flines[i] points directly past
152 * line number. Accesor: */
153 #define MEMPTR(p) ((char*)(p) - 4)
154 #define LINENO(p) (*(uint32_t*)((p) - 4))
157 /* Reset terminal input to normal */
158 static void set_tty_cooked(void)
161 tcsetattr(kbd_fd, TCSANOW, &term_orig);
164 /* Move the cursor to a position (x,y), where (0,0) is the
165 top-left corner of the console */
166 static void move_cursor(int line, int row)
168 printf("\033[%u;%uH", line, row);
171 static void clear_line(void)
173 printf("\033[%u;0H" CLEAR_2_EOL, max_displayed_line + 2);
176 static void print_hilite(const char *str)
178 printf(HIGHLIGHT"%s"NORMAL, str);
181 static void print_statusline(const char *str)
184 printf(HIGHLIGHT"%.*s"NORMAL, width - 1, str);
187 /* Exit the program gracefully */
188 static void less_exit(int code)
193 kill_myself_with_sig(- code); /* does not return */
197 #if (ENABLE_FEATURE_LESS_DASHCMD && ENABLE_FEATURE_LESS_LINENUMS) \
198 || ENABLE_FEATURE_LESS_WINCH
199 static void re_wrap(void)
205 int new_cur_fline = 0;
208 const char **old_flines = flines;
210 char **new_flines = NULL;
213 if (option_mask32 & FLAG_N)
226 if (*d == '\t') /* tab */
230 if (new_line_pos >= w) {
232 /* new line is full, create next one */
235 sz = (d - linebuf) + 1; /* + 1: NUL */
236 d = ((char*)xmalloc(sz + 4)) + 4;
238 memcpy(d, linebuf, sz);
239 new_flines = xrealloc_vector(new_flines, 8, dst_idx);
240 new_flines[dst_idx] = d;
242 if (new_line_pos < w) {
243 /* if we came here thru "goto next_new" */
244 if (src_idx > max_fline)
253 /* *d == NUL: old line ended, go to next old one */
254 free(MEMPTR(old_flines[src_idx]));
255 /* btw, convert cur_fline... */
256 if (cur_fline == src_idx)
257 new_cur_fline = dst_idx;
259 /* no more lines? finish last new line (and exit the loop) */
260 if (src_idx > max_fline)
262 s = old_flines[src_idx];
263 if (lineno != LINENO(s)) {
264 /* this is not a continuation line!
265 * create next _new_ line too */
271 flines = (const char **)new_flines;
273 max_fline = dst_idx - 1;
274 last_line_pos = new_line_pos;
275 cur_fline = new_cur_fline;
276 /* max_lineno is screen-size independent */
277 #if ENABLE_FEATURE_LESS_REGEXP
283 #if ENABLE_FEATURE_LESS_REGEXP
284 static void fill_match_lines(unsigned pos);
286 #define fill_match_lines(pos) ((void)0)
289 /* Devilishly complex routine.
291 * Has to deal with EOF and EPIPE on input,
292 * with line wrapping, with last line not ending in '\n'
293 * (possibly not ending YET!), with backspace and tabs.
294 * It reads input again if last time we got an EOF (thus supporting
295 * growing files) or EPIPE (watching output of slow process like make).
298 * flines[] - array of lines already read. Linewrap may cause
299 * one source file line to occupy several flines[n].
300 * flines[max_fline] - last line, possibly incomplete.
301 * terminated - 1 if flines[max_fline] is 'terminated'
302 * (if there was '\n' [which isn't stored itself, we just remember
304 * max_lineno - last line's number, this one doesn't increment
305 * on line wrap, only on "real" new lines.
306 * readbuf[0..readeof-1] - small preliminary buffer.
307 * readbuf[readpos] - next character to add to current line.
308 * last_line_pos - screen line position of next char to be read
309 * (takes into account tabs and backspaces)
310 * eof_error - < 0 error, == 0 EOF, > 0 not EOF/error
312 static void read_lines(void)
314 #define readbuf bb_common_bufsiz1
315 char *current_line, *p;
317 char last_terminated = terminated;
318 #if ENABLE_FEATURE_LESS_REGEXP
319 unsigned old_max_fline = max_fline;
320 time_t last_time = 0;
321 unsigned seconds_p1 = 3; /* seconds_to_loop + 1 */
324 if (option_mask32 & FLAG_N)
327 IF_FEATURE_LESS_REGEXP(again0:)
329 p = current_line = ((char*)xmalloc(w + 4)) + 4;
330 max_fline += last_terminated;
331 if (!last_terminated) {
332 const char *cp = flines[max_fline];
334 p += strlen(current_line);
335 free(MEMPTR(flines[max_fline]));
336 /* last_line_pos is still valid from previous read_lines() */
341 while (1) { /* read lines until we reach cur_fline or wanted_match */
344 while (1) { /* read chars until we have a line */
346 /* if no unprocessed chars left, eat more */
347 if (readpos >= readeof) {
349 eof_error = safe_read(STDIN_FILENO, readbuf, sizeof(readbuf));
356 c = readbuf[readpos];
357 /* backspace? [needed for manpages] */
358 /* <tab><bs> is (a) insane and */
359 /* (b) harder to do correctly, so we refuse to do it */
360 if (c == '\x8' && last_line_pos && p[-1] != '\t') {
361 readpos++; /* eat it */
363 /* was buggy (p could end up <= current_line)... */
368 size_t new_last_line_pos = last_line_pos + 1;
370 new_last_line_pos += 7;
371 new_last_line_pos &= (~7);
373 if ((int)new_last_line_pos >= w)
375 last_line_pos = new_last_line_pos;
377 /* ok, we will eat this char */
384 /* NUL is substituted by '\n'! */
385 if (c == '\0') c = '\n';
388 } /* end of "read chars until we have a line" loop */
389 /* Corner case: linewrap with only "" wrapping to next line */
390 /* Looks ugly on screen, so we do not store this empty line */
391 if (!last_terminated && !current_line[0]) {
397 last_terminated = terminated;
398 flines = xrealloc_vector(flines, 8, max_fline);
400 flines[max_fline] = (char*)xrealloc(MEMPTR(current_line), strlen(current_line) + 1 + 4) + 4;
401 LINENO(flines[max_fline]) = max_lineno;
405 if (max_fline >= MAXLINES) {
406 eof_error = 0; /* Pretend we saw EOF */
409 if (!(option_mask32 & FLAG_S)
410 ? (max_fline > cur_fline + max_displayed_line)
411 : (max_fline >= cur_fline
412 && max_lineno > LINENO(flines[cur_fline]) + max_displayed_line)
414 #if !ENABLE_FEATURE_LESS_REGEXP
417 if (wanted_match >= num_matches) { /* goto_match called us */
418 fill_match_lines(old_max_fline);
419 old_max_fline = max_fline;
421 if (wanted_match < num_matches)
425 if (eof_error <= 0) {
427 if (errno == EAGAIN) {
428 /* not yet eof or error, reset flag (or else
429 * we will hog CPU - select() will return
433 print_statusline("read error");
436 #if !ENABLE_FEATURE_LESS_REGEXP
439 if (wanted_match < num_matches) {
441 } else { /* goto_match called us */
442 time_t t = time(NULL);
443 if (t != last_time) {
445 if (--seconds_p1 == 0)
449 goto again0; /* go loop again (max 2 seconds) */
454 current_line = ((char*)xmalloc(w + 4)) + 4;
457 } /* end of "read lines until we reach cur_fline" loop */
458 fill_match_lines(old_max_fline);
459 #if ENABLE_FEATURE_LESS_REGEXP
460 /* prevent us from being stuck in search for a match */
466 #if ENABLE_FEATURE_LESS_FLAGS
467 /* Interestingly, writing calc_percent as a function saves around 32 bytes
469 static int calc_percent(void)
471 unsigned p = (100 * (cur_fline+max_displayed_line+1) + max_fline/2) / (max_fline+1);
472 return p <= 100 ? p : 100;
475 /* Print a status line if -M was specified */
476 static void m_status_print(void)
480 if (less_gets_pos >= 0) /* don't touch statusline while input is done! */
484 printf(HIGHLIGHT"%s", filename);
486 printf(" (file %i of %i)", current_file, num_files);
487 printf(" lines %i-%i/%i ",
488 cur_fline + 1, cur_fline + max_displayed_line + 1,
490 if (cur_fline >= (int)(max_fline - max_displayed_line)) {
491 printf("(END)"NORMAL);
492 if (num_files > 1 && current_file != num_files)
493 printf(HIGHLIGHT" - next: %s"NORMAL, files[current_file]);
496 percentage = calc_percent();
497 printf("%i%%"NORMAL, percentage);
501 /* Print the status line */
502 static void status_print(void)
506 if (less_gets_pos >= 0) /* don't touch statusline while input is done! */
509 /* Change the status if flags have been set */
510 #if ENABLE_FEATURE_LESS_FLAGS
511 if (option_mask32 & (FLAG_M|FLAG_m)) {
519 if (cur_fline && cur_fline < (int)(max_fline - max_displayed_line)) {
527 printf(HIGHLIGHT"%s (file %i of %i)"NORMAL,
528 p, current_file, num_files);
534 static void cap_cur_fline(int nlines)
539 if (cur_fline + max_displayed_line > max_fline + TILDES) {
543 diff = max_fline - (cur_fline + max_displayed_line) + TILDES;
544 /* As the number of lines requested was too large, we just move
545 to the end of the file */
551 static const char controls[] ALIGN1 =
552 /* NUL: never encountered; TAB: not converted */
553 /**/"\x01\x02\x03\x04\x05\x06\x07\x08" "\x0a\x0b\x0c\x0d\x0e\x0f"
554 "\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1a\x1b\x1c\x1d\x1e\x1f"
555 "\x7f\x9b"; /* DEL and infamous Meta-ESC :( */
556 static const char ctrlconv[] ALIGN1 =
557 /* '\n': it's a former NUL - subst with '@', not 'J' */
558 "\x40\x41\x42\x43\x44\x45\x46\x47\x48\x49\x40\x4b\x4c\x4d\x4e\x4f"
559 "\x50\x51\x52\x53\x54\x55\x56\x57\x58\x59\x5a\x5b\x5c\x5d\x5e\x5f";
561 static void lineno_str(char *nbuf9, const char *line)
564 if (option_mask32 & FLAG_N) {
568 if (line == empty_line_marker) {
569 memset(nbuf9, ' ', 8);
573 /* Width of 7 preserves tab spacing in the text */
575 n = LINENO(line) + 1;
580 sprintf(nbuf9, fmt, n);
585 #if ENABLE_FEATURE_LESS_REGEXP
586 static void print_found(const char *line)
591 regmatch_t match_structs;
595 const char *str = line;
600 n = strcspn(str, controls);
607 n = strspn(str, controls);
614 /* buf[] holds quarantined version of str */
616 /* Each part of the line that matches has the HIGHLIGHT
617 and NORMAL escape sequences placed around it.
618 NB: we regex against line, but insert text
619 from quarantined copy (buf[]) */
625 while (match_status == 0) {
626 char *new = xasprintf("%s%.*s"HIGHLIGHT"%.*s"NORMAL,
628 match_structs.rm_so, str,
629 match_structs.rm_eo - match_structs.rm_so,
630 str + match_structs.rm_so);
633 str += match_structs.rm_eo;
634 line += match_structs.rm_eo;
637 /* Most of the time doesn't find the regex, optimize for that */
638 match_status = regexec(&pattern, line, 1, &match_structs, eflags);
639 /* if even "" matches, treat it as "not a match" */
640 if (match_structs.rm_so >= match_structs.rm_eo)
644 lineno_str(nbuf9, line);
646 printf(CLEAR_2_EOL"%s%s\n", nbuf9, str);
649 printf(CLEAR_2_EOL"%s%s%s\n", nbuf9, growline, str);
653 void print_found(const char *line);
656 static void print_ascii(const char *str)
663 lineno_str(nbuf9, str);
664 printf(CLEAR_2_EOL"%s", nbuf9);
667 n = strcspn(str, controls);
670 printf("%.*s", (int) n, str);
673 n = strspn(str, controls);
678 else if (*str == (char)0x9b)
679 /* VT100's CSI, aka Meta-ESC. Who's inventor? */
680 /* I want to know who committed this sin */
683 *p++ = ctrlconv[(unsigned char)*str];
692 /* Print the buffer */
693 static void buffer_print(void)
698 for (i = 0; i <= max_displayed_line; i++)
700 print_found(buffer[i]);
702 print_ascii(buffer[i]);
706 static void buffer_fill_and_print(void)
709 #if ENABLE_FEATURE_LESS_DASHCMD
710 int fpos = cur_fline;
712 if (option_mask32 & FLAG_S) {
713 /* Go back to the beginning of this line */
714 while (fpos && LINENO(flines[fpos]) == LINENO(flines[fpos-1]))
719 while (i <= max_displayed_line && fpos <= max_fline) {
720 int lineno = LINENO(flines[fpos]);
721 buffer[i] = flines[fpos];
725 } while ((fpos <= max_fline)
726 && (option_mask32 & FLAG_S)
727 && lineno == LINENO(flines[fpos])
731 for (i = 0; i <= max_displayed_line && cur_fline + i <= max_fline; i++) {
732 buffer[i] = flines[cur_fline + i];
735 for (; i <= max_displayed_line; i++) {
736 buffer[i] = empty_line_marker;
741 /* Move the buffer up and down in the file in order to scroll */
742 static void buffer_down(int nlines)
746 cap_cur_fline(nlines);
747 buffer_fill_and_print();
750 static void buffer_up(int nlines)
753 if (cur_fline < 0) cur_fline = 0;
755 buffer_fill_and_print();
758 static void buffer_line(int linenum)
764 if (linenum + max_displayed_line > max_fline)
765 linenum = max_fline - max_displayed_line + TILDES;
769 buffer_fill_and_print();
772 static void open_file_and_read_lines(void)
775 xmove_fd(xopen(filename, O_RDONLY), STDIN_FILENO);
777 /* "less" with no arguments in argv[] */
778 /* For status line only */
779 filename = xstrdup(bb_msg_standard_input);
788 /* Reinitialize everything for a new file - free the memory and start over */
789 static void reinitialize(void)
794 for (i = 0; i <= max_fline; i++)
795 free(MEMPTR(flines[i]));
803 open_file_and_read_lines();
804 buffer_fill_and_print();
807 static int getch_nowait(void)
810 struct pollfd pfd[2];
812 pfd[0].fd = STDIN_FILENO;
813 pfd[0].events = POLLIN;
815 pfd[1].events = POLLIN;
817 tcsetattr(kbd_fd, TCSANOW, &term_less);
818 /* NB: select/poll returns whenever read will not block. Therefore:
819 * if eof is reached, select/poll will return immediately
820 * because read will immediately return 0 bytes.
821 * Even if select/poll says that input is available, read CAN block
822 * (switch fd into O_NONBLOCK'ed mode to avoid it)
825 /* Are we interested in stdin? */
826 //TODO: reuse code for determining this
827 if (!(option_mask32 & FLAG_S)
828 ? !(max_fline > cur_fline + max_displayed_line)
829 : !(max_fline >= cur_fline
830 && max_lineno > LINENO(flines[cur_fline]) + max_displayed_line)
832 if (eof_error > 0) /* did NOT reach eof yet */
833 rd = 0; /* yes, we are interested in stdin */
835 /* Position cursor if line input is done */
836 if (less_gets_pos >= 0)
837 move_cursor(max_displayed_line + 2, less_gets_pos + 1);
840 if (kbd_input[0] == 0) { /* if nothing is buffered */
841 #if ENABLE_FEATURE_LESS_WINCH
844 /* NB: SIGWINCH interrupts poll() */
845 r = poll(pfd + rd, 2 - rd, -1);
846 if (/*r < 0 && errno == EINTR &&*/ winch_counter)
847 return '\\'; /* anything which has no defined function */
851 safe_poll(pfd + rd, 2 - rd, -1);
855 /* We have kbd_fd in O_NONBLOCK mode, read inside read_key()
856 * would not block even if there is no input available */
857 rd = read_key(kbd_fd, kbd_input);
859 if (errno == EAGAIN) {
860 /* No keyboard input available. Since poll() did return,
861 * we should have input on stdin */
863 buffer_fill_and_print();
866 /* EOF/error (ssh session got killed etc) */
873 /* Grab a character from input without requiring the return key.
874 * May return KEYCODE_xxx values.
875 * Note that this function works best with raw input. */
876 static int less_getch(int pos)
885 /* Discard Ctrl-something chars */
886 if (i >= 0 && i < ' ' && i != 0x0d && i != 8)
891 static char* less_gets(int sz)
895 char *result = xzalloc(1);
899 less_gets_pos = sz + i;
912 if (c < ' ') /* filters out KEYCODE_xxx too (<0) */
914 if (i >= width - sz - 1)
915 continue; /* len limit */
918 result = xrealloc(result, i+1);
922 static void examine_file(void)
926 print_statusline("Examine: ");
927 new_fname = less_gets(sizeof("Examine: ") - 1);
934 if (access(new_fname, R_OK) != 0) {
935 print_statusline("Cannot read this file");
939 filename = new_fname;
940 /* files start by = argv. why we assume that argv is infinitely long??
941 files[num_files] = filename;
942 current_file = num_files + 1;
945 num_files = current_file = 1;
949 /* This function changes the file currently being paged. direction can be one of the following:
950 * -1: go back one file
951 * 0: go to the first file
952 * 1: go forward one file */
953 static void change_file(int direction)
955 if (current_file != ((direction > 0) ? num_files : 1)) {
956 current_file = direction ? current_file + direction : 1;
958 filename = xstrdup(files[current_file - 1]);
961 print_statusline(direction > 0 ? "No next file" : "No previous file");
965 static void remove_current_file(void)
972 if (current_file != 1) {
974 for (i = 3; i <= num_files; i++)
975 files[i - 2] = files[i - 1];
979 for (i = 2; i <= num_files; i++)
980 files[i - 2] = files[i - 1];
986 static void colon_process(void)
990 /* Clear the current line and print a prompt */
991 print_statusline(" :");
993 keypress = less_getch(2);
996 remove_current_file();
1001 #if ENABLE_FEATURE_LESS_FLAGS
1013 less_exit(EXIT_SUCCESS);
1021 #if ENABLE_FEATURE_LESS_REGEXP
1022 static void normalize_match_pos(int match)
1024 if (match >= num_matches)
1025 match = num_matches - 1;
1031 static void goto_match(int match)
1037 /* Try to find next match if eof isn't reached yet */
1038 if (match >= num_matches && eof_error > 0) {
1039 wanted_match = match; /* "I want to read until I see N'th match" */
1043 normalize_match_pos(match);
1044 buffer_line(match_lines[match_pos]);
1046 print_statusline("No matches found");
1050 static void fill_match_lines(unsigned pos)
1054 /* Run the regex on each line of the current file */
1055 while (pos <= max_fline) {
1056 /* If this line matches */
1057 if (regexec(&pattern, flines[pos], 0, NULL, 0) == 0
1058 /* and we didn't match it last time */
1059 && !(num_matches && match_lines[num_matches-1] == pos)
1061 match_lines = xrealloc_vector(match_lines, 4, num_matches);
1062 match_lines[num_matches++] = pos;
1068 static void regex_process(void)
1070 char *uncomp_regex, *err;
1072 /* Reset variables */
1077 if (pattern_valid) {
1082 /* Get the uncompiled regular expression from the user */
1084 bb_putchar((option_mask32 & LESS_STATE_MATCH_BACKWARDS) ? '?' : '/');
1085 uncomp_regex = less_gets(1);
1086 if (!uncomp_regex[0]) {
1092 /* Compile the regex and check for errors */
1093 err = regcomp_or_errmsg(&pattern, uncomp_regex,
1094 (option_mask32 & FLAG_I) ? REG_ICASE : 0);
1097 print_statusline(err);
1104 fill_match_lines(0);
1105 while (match_pos < num_matches) {
1106 if ((int)match_lines[match_pos] > cur_fline)
1110 if (option_mask32 & LESS_STATE_MATCH_BACKWARDS)
1113 /* It's possible that no matches are found yet.
1114 * goto_match() will read input looking for match,
1116 goto_match(match_pos);
1120 static void number_process(int first_digit)
1125 char num_input[sizeof(int)*4]; /* more than enough */
1127 num_input[0] = first_digit;
1129 /* Clear the current line, print a prompt, and then print the digit */
1131 printf(":%c", first_digit);
1133 /* Receive input until a letter is given */
1135 while (i < sizeof(num_input)-1) {
1136 keypress = less_getch(i + 1);
1137 if ((unsigned)keypress > 255 || !isdigit(num_input[i]))
1139 num_input[i] = keypress;
1140 bb_putchar(keypress);
1144 num_input[i] = '\0';
1145 num = bb_strtou(num_input, NULL, 10);
1146 /* on format error, num == -1 */
1147 if (num < 1 || num > MAXLINES) {
1152 /* We now know the number and the letter entered, so we process them */
1154 case KEYCODE_DOWN: case 'z': case 'd': case 'e': case ' ': case '\015':
1157 case KEYCODE_UP: case 'b': case 'w': case 'y': case 'u':
1160 case 'g': case '<': case 'G': case '>':
1161 cur_fline = num + max_displayed_line;
1163 buffer_line(num - 1);
1166 num = num * (max_fline / 100); /* + max_fline / 2; */
1167 cur_fline = num + max_displayed_line;
1171 #if ENABLE_FEATURE_LESS_REGEXP
1173 goto_match(match_pos + num);
1176 option_mask32 &= ~LESS_STATE_MATCH_BACKWARDS;
1180 option_mask32 |= LESS_STATE_MATCH_BACKWARDS;
1187 #if ENABLE_FEATURE_LESS_DASHCMD
1188 static void flag_change(void)
1194 keypress = less_getch(1);
1198 option_mask32 ^= FLAG_M;
1201 option_mask32 ^= FLAG_m;
1204 option_mask32 ^= FLAG_E;
1207 option_mask32 ^= FLAG_TILDE;
1210 option_mask32 ^= FLAG_S;
1211 buffer_fill_and_print();
1213 #if ENABLE_FEATURE_LESS_LINENUMS
1215 option_mask32 ^= FLAG_N;
1217 buffer_fill_and_print();
1224 static void show_flag_status(void)
1231 keypress = less_getch(1);
1235 flag_val = option_mask32 & FLAG_M;
1238 flag_val = option_mask32 & FLAG_m;
1241 flag_val = option_mask32 & FLAG_TILDE;
1244 flag_val = option_mask32 & FLAG_N;
1247 flag_val = option_mask32 & FLAG_E;
1255 printf(HIGHLIGHT"The status of the flag is: %u"NORMAL, flag_val != 0);
1259 #endif /* ENABLE_FEATURE_LESS_DASHCMD */
1261 static void save_input_to_file(void)
1263 const char *msg = "";
1268 print_statusline("Log file: ");
1269 current_line = less_gets(sizeof("Log file: ")-1);
1270 if (current_line[0]) {
1271 fp = fopen_for_write(current_line);
1273 msg = "Error opening log file";
1276 for (i = 0; i <= max_fline; i++)
1277 fprintf(fp, "%s\n", flines[i]);
1282 print_statusline(msg);
1286 #if ENABLE_FEATURE_LESS_MARKS
1287 static void add_mark(void)
1291 print_statusline("Mark: ");
1292 letter = less_getch(sizeof("Mark: ") - 1);
1294 if (isalpha(letter)) {
1295 /* If we exceed 15 marks, start overwriting previous ones */
1296 if (num_marks == 14)
1299 mark_lines[num_marks][0] = letter;
1300 mark_lines[num_marks][1] = cur_fline;
1303 print_statusline("Invalid mark letter");
1307 static void goto_mark(void)
1312 print_statusline("Go to mark: ");
1313 letter = less_getch(sizeof("Go to mark: ") - 1);
1316 if (isalpha(letter)) {
1317 for (i = 0; i <= num_marks; i++)
1318 if (letter == mark_lines[i][0]) {
1319 buffer_line(mark_lines[i][1]);
1322 if (num_marks == 14 && letter != mark_lines[14][0])
1323 print_statusline("Mark not set");
1325 print_statusline("Invalid mark letter");
1329 #if ENABLE_FEATURE_LESS_BRACKETS
1330 static char opp_bracket(char bracket)
1333 case '{': case '[': /* '}' == '{' + 2. Same for '[' */
1335 case '(': /* ')' == '(' + 1 */
1347 static void match_right_bracket(char bracket)
1351 if (strchr(flines[cur_fline], bracket) == NULL) {
1352 print_statusline("No bracket in top line");
1355 bracket = opp_bracket(bracket);
1356 for (i = cur_fline + 1; i < max_fline; i++) {
1357 if (strchr(flines[i], bracket) != NULL) {
1362 print_statusline("No matching bracket found");
1365 static void match_left_bracket(char bracket)
1369 if (strchr(flines[cur_fline + max_displayed_line], bracket) == NULL) {
1370 print_statusline("No bracket in bottom line");
1374 bracket = opp_bracket(bracket);
1375 for (i = cur_fline + max_displayed_line; i >= 0; i--) {
1376 if (strchr(flines[i], bracket) != NULL) {
1381 print_statusline("No matching bracket found");
1383 #endif /* FEATURE_LESS_BRACKETS */
1385 static void keypress_process(int keypress)
1388 case KEYCODE_DOWN: case 'e': case 'j': case 0x0d:
1391 case KEYCODE_UP: case 'y': case 'k':
1394 case KEYCODE_PAGEDOWN: case ' ': case 'z': case 'f':
1395 buffer_down(max_displayed_line + 1);
1397 case KEYCODE_PAGEUP: case 'w': case 'b':
1398 buffer_up(max_displayed_line + 1);
1401 buffer_down((max_displayed_line + 1) / 2);
1404 buffer_up((max_displayed_line + 1) / 2);
1406 case KEYCODE_HOME: case 'g': case 'p': case '<': case '%':
1409 case KEYCODE_END: case 'G': case '>':
1410 cur_fline = MAXLINES;
1412 buffer_line(cur_fline);
1415 less_exit(EXIT_SUCCESS);
1417 #if ENABLE_FEATURE_LESS_MARKS
1434 save_input_to_file();
1439 #if ENABLE_FEATURE_LESS_FLAGS
1444 #if ENABLE_FEATURE_LESS_REGEXP
1446 option_mask32 &= ~LESS_STATE_MATCH_BACKWARDS;
1450 goto_match(match_pos + 1);
1453 goto_match(match_pos - 1);
1456 option_mask32 |= LESS_STATE_MATCH_BACKWARDS;
1460 #if ENABLE_FEATURE_LESS_DASHCMD
1471 #if ENABLE_FEATURE_LESS_BRACKETS
1472 case '{': case '(': case '[':
1473 match_right_bracket(keypress);
1475 case '}': case ')': case ']':
1476 match_left_bracket(keypress);
1484 if (isdigit(keypress))
1485 number_process(keypress);
1488 static void sig_catcher(int sig)
1493 #if ENABLE_FEATURE_LESS_WINCH
1494 static void sigwinch_handler(int sig UNUSED_PARAM)
1500 int less_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
1501 int less_main(int argc, char **argv)
1507 /* TODO: -x: do not interpret backspace, -xx: tab also */
1508 /* -xxx: newline also */
1509 /* -w N: assume width N (-xxx -w 32: hex viewer of sorts) */
1510 getopt32(argv, "EMmN~I" IF_FEATURE_LESS_DASHCMD("S"));
1516 /* Another popular pager, most, detects when stdout
1517 * is not a tty and turns into cat. This makes sense. */
1518 if (!isatty(STDOUT_FILENO))
1519 return bb_cat(argv);
1522 if (isatty(STDIN_FILENO)) {
1523 /* Just "less"? No args and no redirection? */
1524 bb_error_msg("missing filename");
1528 filename = xstrdup(files[0]);
1531 if (option_mask32 & FLAG_TILDE)
1532 empty_line_marker = "";
1534 kbd_fd = open(CURRENT_TTY, O_RDONLY);
1536 return bb_cat(argv);
1539 tcgetattr(kbd_fd, &term_orig);
1540 term_less = term_orig;
1541 term_less.c_lflag &= ~(ICANON | ECHO);
1542 term_less.c_iflag &= ~(IXON | ICRNL);
1543 /*term_less.c_oflag &= ~ONLCR;*/
1544 term_less.c_cc[VMIN] = 1;
1545 term_less.c_cc[VTIME] = 0;
1547 get_terminal_width_height(kbd_fd, &width, &max_displayed_line);
1548 /* 20: two tabstops + 4 */
1549 if (width < 20 || max_displayed_line < 3)
1550 return bb_cat(argv);
1551 max_displayed_line -= 2;
1553 /* We want to restore term_orig on exit */
1554 bb_signals(BB_FATAL_SIGS, sig_catcher);
1555 #if ENABLE_FEATURE_LESS_WINCH
1556 signal(SIGWINCH, sigwinch_handler);
1559 buffer = xmalloc((max_displayed_line+1) * sizeof(char *));
1562 #if ENABLE_FEATURE_LESS_WINCH
1563 while (WINCH_COUNTER) {
1566 get_terminal_width_height(kbd_fd, &width, &max_displayed_line);
1567 /* 20: two tabstops + 4 */
1570 if (max_displayed_line < 3)
1571 max_displayed_line = 3;
1572 max_displayed_line -= 2;
1574 buffer = xmalloc((max_displayed_line+1) * sizeof(char *));
1575 /* Avoid re-wrap and/or redraw if we already know
1576 * we need to do it again. These ops are expensive */
1582 buffer_fill_and_print();
1583 /* This took some time. Loop back and check,
1584 * were there another SIGWINCH? */
1587 keypress = less_getch(-1); /* -1: do not position cursor */
1588 keypress_process(keypress);
1593 Help text of less version 418 is below.
1594 If you are implementing something, keeping
1595 key and/or command line switch compatibility is a good idea:
1598 SUMMARY OF LESS COMMANDS
1600 Commands marked with * may be preceded by a number, N.
1601 Notes in parentheses indicate the behavior if N is given.
1602 h H Display this help.
1604 ---------------------------------------------------------------------------
1606 e ^E j ^N CR * Forward one line (or N lines).
1607 y ^Y k ^K ^P * Backward one line (or N lines).
1608 f ^F ^V SPACE * Forward one window (or N lines).
1609 b ^B ESC-v * Backward one window (or N lines).
1610 z * Forward one window (and set window to N).
1611 w * Backward one window (and set window to N).
1612 ESC-SPACE * Forward one window, but don't stop at end-of-file.
1613 d ^D * Forward one half-window (and set half-window to N).
1614 u ^U * Backward one half-window (and set half-window to N).
1615 ESC-) RightArrow * Left one half screen width (or N positions).
1616 ESC-( LeftArrow * Right one half screen width (or N positions).
1617 F Forward forever; like "tail -f".
1618 r ^R ^L Repaint screen.
1619 R Repaint screen, discarding buffered input.
1620 ---------------------------------------------------
1621 Default "window" is the screen height.
1622 Default "half-window" is half of the screen height.
1623 ---------------------------------------------------------------------------
1625 /pattern * Search forward for (N-th) matching line.
1626 ?pattern * Search backward for (N-th) matching line.
1627 n * Repeat previous search (for N-th occurrence).
1628 N * Repeat previous search in reverse direction.
1629 ESC-n * Repeat previous search, spanning files.
1630 ESC-N * Repeat previous search, reverse dir. & spanning files.
1631 ESC-u Undo (toggle) search highlighting.
1632 ---------------------------------------------------
1633 Search patterns may be modified by one or more of:
1634 ^N or ! Search for NON-matching lines.
1635 ^E or * Search multiple files (pass thru END OF FILE).
1636 ^F or @ Start search at FIRST file (for /) or last file (for ?).
1637 ^K Highlight matches, but don't move (KEEP position).
1638 ^R Don't use REGULAR EXPRESSIONS.
1639 ---------------------------------------------------------------------------
1641 g < ESC-< * Go to first line in file (or line N).
1642 G > ESC-> * Go to last line in file (or line N).
1643 p % * Go to beginning of file (or N percent into file).
1644 t * Go to the (N-th) next tag.
1645 T * Go to the (N-th) previous tag.
1646 { ( [ * Find close bracket } ) ].
1647 } ) ] * Find open bracket { ( [.
1648 ESC-^F <c1> <c2> * Find close bracket <c2>.
1649 ESC-^B <c1> <c2> * Find open bracket <c1>
1650 ---------------------------------------------------
1651 Each "find close bracket" command goes forward to the close bracket
1652 matching the (N-th) open bracket in the top line.
1653 Each "find open bracket" command goes backward to the open bracket
1654 matching the (N-th) close bracket in the bottom line.
1655 m<letter> Mark the current position with <letter>.
1656 '<letter> Go to a previously marked position.
1657 '' Go to the previous position.
1659 ---------------------------------------------------
1660 A mark is any upper-case or lower-case letter.
1661 Certain marks are predefined:
1662 ^ means beginning of the file
1663 $ means end of the file
1664 ---------------------------------------------------------------------------
1666 :e [file] Examine a new file.
1668 :n * Examine the (N-th) next file from the command line.
1669 :p * Examine the (N-th) previous file from the command line.
1670 :x * Examine the first (or N-th) file from the command line.
1671 :d Delete the current file from the command line list.
1672 = ^G :f Print current file name.
1673 ---------------------------------------------------------------------------
1674 MISCELLANEOUS COMMANDS
1675 -<flag> Toggle a command line option [see OPTIONS below].
1676 --<name> Toggle a command line option, by name.
1677 _<flag> Display the setting of a command line option.
1678 __<name> Display the setting of an option, by name.
1679 +cmd Execute the less cmd each time a new file is examined.
1680 !command Execute the shell command with $SHELL.
1681 |Xcommand Pipe file between current pos & mark X to shell command.
1682 v Edit the current file with $VISUAL or $EDITOR.
1683 V Print version number of "less".
1684 ---------------------------------------------------------------------------
1686 Most options may be changed either on the command line,
1687 or from within less by using the - or -- command.
1688 Options may be given in one of two forms: either a single
1689 character preceded by a -, or a name preceeded by --.
1691 Display help (from command line).
1692 -a ........ --search-skip-screen
1693 Forward search skips current screen.
1694 -b [N] .... --buffers=[N]
1696 -B ........ --auto-buffers
1697 Don't automatically allocate buffers for pipes.
1698 -c ........ --clear-screen
1699 Repaint by clearing rather than scrolling.
1702 -D [xn.n] . --color=xn.n
1703 Set screen colors. (MS-DOS only)
1704 -e -E .... --quit-at-eof --QUIT-AT-EOF
1705 Quit at end of file.
1707 Force open non-regular files.
1708 -F ........ --quit-if-one-screen
1709 Quit if entire file fits on first screen.
1710 -g ........ --hilite-search
1711 Highlight only last match for searches.
1712 -G ........ --HILITE-SEARCH
1713 Don't highlight any matches for searches.
1714 -h [N] .... --max-back-scroll=[N]
1715 Backward scroll limit.
1716 -i ........ --ignore-case
1717 Ignore case in searches that do not contain uppercase.
1718 -I ........ --IGNORE-CASE
1719 Ignore case in all searches.
1720 -j [N] .... --jump-target=[N]
1721 Screen position of target lines.
1722 -J ........ --status-column
1723 Display a status column at left edge of screen.
1724 -k [file] . --lesskey-file=[file]
1726 -L ........ --no-lessopen
1727 Ignore the LESSOPEN environment variable.
1728 -m -M .... --long-prompt --LONG-PROMPT
1730 -n -N .... --line-numbers --LINE-NUMBERS
1731 Don't use line numbers.
1732 -o [file] . --log-file=[file]
1733 Copy to log file (standard input only).
1734 -O [file] . --LOG-FILE=[file]
1735 Copy to log file (unconditionally overwrite).
1736 -p [pattern] --pattern=[pattern]
1737 Start at pattern (from command line).
1738 -P [prompt] --prompt=[prompt]
1740 -q -Q .... --quiet --QUIET --silent --SILENT
1741 Quiet the terminal bell.
1742 -r -R .... --raw-control-chars --RAW-CONTROL-CHARS
1743 Output "raw" control characters.
1744 -s ........ --squeeze-blank-lines
1745 Squeeze multiple blank lines.
1746 -S ........ --chop-long-lines
1748 -t [tag] .. --tag=[tag]
1750 -T [tagsfile] --tag-file=[tagsfile]
1751 Use an alternate tags file.
1752 -u -U .... --underline-special --UNDERLINE-SPECIAL
1753 Change handling of backspaces.
1754 -V ........ --version
1755 Display the version number of "less".
1756 -w ........ --hilite-unread
1757 Highlight first new line after forward-screen.
1758 -W ........ --HILITE-UNREAD
1759 Highlight first new line after any forward movement.
1760 -x [N[,...]] --tabs=[N[,...]]
1762 -X ........ --no-init
1763 Don't use termcap init/deinit strings.
1765 Don't use termcap keypad init/deinit strings.
1766 -y [N] .... --max-forw-scroll=[N]
1767 Forward scroll limit.
1768 -z [N] .... --window=[N]
1770 -" [c[c]] . --quotes=[c[c]]
1771 Set shell quote characters.
1773 Don't display tildes after end of file.
1774 -# [N] .... --shift=[N]
1775 Horizontal scroll amount (0 = one half screen width)
1777 ---------------------------------------------------------------------------
1779 These keys can be used to edit text being entered
1780 on the "command line" at the bottom of the screen.
1781 RightArrow ESC-l Move cursor right one character.
1782 LeftArrow ESC-h Move cursor left one character.
1783 CNTL-RightArrow ESC-RightArrow ESC-w Move cursor right one word.
1784 CNTL-LeftArrow ESC-LeftArrow ESC-b Move cursor left one word.
1785 HOME ESC-0 Move cursor to start of line.
1786 END ESC-$ Move cursor to end of line.
1787 BACKSPACE Delete char to left of cursor.
1788 DELETE ESC-x Delete char under cursor.
1789 CNTL-BACKSPACE ESC-BACKSPACE Delete word to left of cursor.
1790 CNTL-DELETE ESC-DELETE ESC-X Delete word under cursor.
1791 CNTL-U ESC (MS-DOS only) Delete entire line.
1792 UpArrow ESC-k Retrieve previous command line.
1793 DownArrow ESC-j Retrieve next command line.
1794 TAB Complete filename & cycle.
1795 SHIFT-TAB ESC-TAB Complete filename & reverse cycle.
1796 CNTL-L Complete filename, list all.