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 GPLv2 or later, see file LICENSE in this source tree.
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
33 /* The escape codes for highlighted and normal text */
34 #define HIGHLIGHT ESC"[7m"
35 #define NORMAL ESC"[0m"
36 /* The escape code to home and clear to the end of screen */
37 #define CLEAR ESC"[H\033[J"
38 /* The escape code to clear to the end of line */
39 #define CLEAR_2_EOL ESC"[K"
42 /* Absolute max of lines eaten */
43 MAXLINES = CONFIG_FEATURE_LESS_MAXLINES,
44 /* This many "after the end" lines we will show (at max) */
48 /* Command line options */
56 FLAG_S = (1 << 6) * ENABLE_FEATURE_LESS_DASHCMD,
57 /* hijack command line options variable for internal state vars */
58 LESS_STATE_MATCH_BACKWARDS = 1 << 15,
61 #if !ENABLE_FEATURE_LESS_REGEXP
62 enum { pattern_valid = 0 };
66 int cur_fline; /* signed */
67 int kbd_fd; /* fd to get input from */
69 /* last position in last line, taking into account tabs */
72 unsigned max_lineno; /* this one tracks linewrap */
73 unsigned max_displayed_line;
75 #if ENABLE_FEATURE_LESS_WINCH
76 unsigned winch_counter;
78 ssize_t eof_error; /* eof if 0, error if < 0 */
80 ssize_t readeof; /* must be signed */
83 const char *empty_line_marker;
85 unsigned current_file;
88 #if ENABLE_FEATURE_LESS_MARKS
90 unsigned mark_lines[15][2];
92 #if ENABLE_FEATURE_LESS_REGEXP
93 unsigned *match_lines;
94 int match_pos; /* signed! */
95 int wanted_match; /* signed! */
98 smallint pattern_valid;
101 struct termios term_orig, term_less;
102 char kbd_input[KEYCODE_BUFFER_SIZE];
104 #define G (*ptr_to_globals)
105 #define cur_fline (G.cur_fline )
106 #define kbd_fd (G.kbd_fd )
107 #define less_gets_pos (G.less_gets_pos )
108 #define last_line_pos (G.last_line_pos )
109 #define max_fline (G.max_fline )
110 #define max_lineno (G.max_lineno )
111 #define max_displayed_line (G.max_displayed_line)
112 #define width (G.width )
113 #define winch_counter (G.winch_counter )
114 /* This one is 100% not cached by compiler on read access */
115 #define WINCH_COUNTER (*(volatile unsigned *)&winch_counter)
116 #define eof_error (G.eof_error )
117 #define readpos (G.readpos )
118 #define readeof (G.readeof )
119 #define buffer (G.buffer )
120 #define flines (G.flines )
121 #define empty_line_marker (G.empty_line_marker )
122 #define num_files (G.num_files )
123 #define current_file (G.current_file )
124 #define filename (G.filename )
125 #define files (G.files )
126 #define num_marks (G.num_marks )
127 #define mark_lines (G.mark_lines )
128 #if ENABLE_FEATURE_LESS_REGEXP
129 #define match_lines (G.match_lines )
130 #define match_pos (G.match_pos )
131 #define num_matches (G.num_matches )
132 #define wanted_match (G.wanted_match )
133 #define pattern (G.pattern )
134 #define pattern_valid (G.pattern_valid )
136 #define terminated (G.terminated )
137 #define term_orig (G.term_orig )
138 #define term_less (G.term_less )
139 #define kbd_input (G.kbd_input )
140 #define INIT_G() do { \
141 SET_PTR_TO_GLOBALS(xzalloc(sizeof(G))); \
142 less_gets_pos = -1; \
143 empty_line_marker = "~"; \
148 IF_FEATURE_LESS_REGEXP(wanted_match = -1;) \
151 /* flines[] are lines read from stdin, each in malloc'ed buffer.
152 * Line numbers are stored as uint32_t prepended to each line.
153 * Pointer is adjusted so that flines[i] points directly past
154 * line number. Accesor: */
155 #define MEMPTR(p) ((char*)(p) - 4)
156 #define LINENO(p) (*(uint32_t*)((p) - 4))
159 /* Reset terminal input to normal */
160 static void set_tty_cooked(void)
163 tcsetattr(kbd_fd, TCSANOW, &term_orig);
166 /* Move the cursor to a position (x,y), where (0,0) is the
167 top-left corner of the console */
168 static void move_cursor(int line, int row)
170 printf(ESC"[%u;%uH", line, row);
173 static void clear_line(void)
175 printf(ESC"[%u;0H" CLEAR_2_EOL, max_displayed_line + 2);
178 static void print_hilite(const char *str)
180 printf(HIGHLIGHT"%s"NORMAL, str);
183 static void print_statusline(const char *str)
186 printf(HIGHLIGHT"%.*s"NORMAL, width - 1, str);
189 /* Exit the program gracefully */
190 static void less_exit(int code)
195 kill_myself_with_sig(- code); /* does not return */
199 #if (ENABLE_FEATURE_LESS_DASHCMD && ENABLE_FEATURE_LESS_LINENUMS) \
200 || ENABLE_FEATURE_LESS_WINCH
201 static void re_wrap(void)
207 int new_cur_fline = 0;
210 const char **old_flines = flines;
212 char **new_flines = NULL;
215 if (option_mask32 & FLAG_N)
228 if (*d == '\t') /* tab */
232 if (new_line_pos >= w) {
234 /* new line is full, create next one */
237 sz = (d - linebuf) + 1; /* + 1: NUL */
238 d = ((char*)xmalloc(sz + 4)) + 4;
240 memcpy(d, linebuf, sz);
241 new_flines = xrealloc_vector(new_flines, 8, dst_idx);
242 new_flines[dst_idx] = d;
244 if (new_line_pos < w) {
245 /* if we came here thru "goto next_new" */
246 if (src_idx > max_fline)
255 /* *d == NUL: old line ended, go to next old one */
256 free(MEMPTR(old_flines[src_idx]));
257 /* btw, convert cur_fline... */
258 if (cur_fline == src_idx)
259 new_cur_fline = dst_idx;
261 /* no more lines? finish last new line (and exit the loop) */
262 if (src_idx > max_fline)
264 s = old_flines[src_idx];
265 if (lineno != LINENO(s)) {
266 /* this is not a continuation line!
267 * create next _new_ line too */
273 flines = (const char **)new_flines;
275 max_fline = dst_idx - 1;
276 last_line_pos = new_line_pos;
277 cur_fline = new_cur_fline;
278 /* max_lineno is screen-size independent */
279 #if ENABLE_FEATURE_LESS_REGEXP
285 #if ENABLE_FEATURE_LESS_REGEXP
286 static void fill_match_lines(unsigned pos);
288 #define fill_match_lines(pos) ((void)0)
291 /* Devilishly complex routine.
293 * Has to deal with EOF and EPIPE on input,
294 * with line wrapping, with last line not ending in '\n'
295 * (possibly not ending YET!), with backspace and tabs.
296 * It reads input again if last time we got an EOF (thus supporting
297 * growing files) or EPIPE (watching output of slow process like make).
300 * flines[] - array of lines already read. Linewrap may cause
301 * one source file line to occupy several flines[n].
302 * flines[max_fline] - last line, possibly incomplete.
303 * terminated - 1 if flines[max_fline] is 'terminated'
304 * (if there was '\n' [which isn't stored itself, we just remember
306 * max_lineno - last line's number, this one doesn't increment
307 * on line wrap, only on "real" new lines.
308 * readbuf[0..readeof-1] - small preliminary buffer.
309 * readbuf[readpos] - next character to add to current line.
310 * last_line_pos - screen line position of next char to be read
311 * (takes into account tabs and backspaces)
312 * eof_error - < 0 error, == 0 EOF, > 0 not EOF/error
314 static void read_lines(void)
316 #define readbuf bb_common_bufsiz1
317 char *current_line, *p;
319 char last_terminated = terminated;
320 #if ENABLE_FEATURE_LESS_REGEXP
321 unsigned old_max_fline = max_fline;
322 time_t last_time = 0;
323 unsigned seconds_p1 = 3; /* seconds_to_loop + 1 */
326 if (option_mask32 & FLAG_N)
329 IF_FEATURE_LESS_REGEXP(again0:)
331 p = current_line = ((char*)xmalloc(w + 4)) + 4;
332 max_fline += last_terminated;
333 if (!last_terminated) {
334 const char *cp = flines[max_fline];
336 p += strlen(current_line);
337 free(MEMPTR(flines[max_fline]));
338 /* last_line_pos is still valid from previous read_lines() */
343 while (1) { /* read lines until we reach cur_fline or wanted_match */
346 while (1) { /* read chars until we have a line */
348 /* if no unprocessed chars left, eat more */
349 if (readpos >= readeof) {
351 eof_error = safe_read(STDIN_FILENO, readbuf, sizeof(readbuf));
358 c = readbuf[readpos];
359 /* backspace? [needed for manpages] */
360 /* <tab><bs> is (a) insane and */
361 /* (b) harder to do correctly, so we refuse to do it */
362 if (c == '\x8' && last_line_pos && p[-1] != '\t') {
363 readpos++; /* eat it */
365 /* was buggy (p could end up <= current_line)... */
370 size_t new_last_line_pos = last_line_pos + 1;
372 new_last_line_pos += 7;
373 new_last_line_pos &= (~7);
375 if ((int)new_last_line_pos >= w)
377 last_line_pos = new_last_line_pos;
379 /* ok, we will eat this char */
386 /* NUL is substituted by '\n'! */
387 if (c == '\0') c = '\n';
390 } /* end of "read chars until we have a line" loop */
391 /* Corner case: linewrap with only "" wrapping to next line */
392 /* Looks ugly on screen, so we do not store this empty line */
393 if (!last_terminated && !current_line[0]) {
399 last_terminated = terminated;
400 flines = xrealloc_vector(flines, 8, max_fline);
402 flines[max_fline] = (char*)xrealloc(MEMPTR(current_line), strlen(current_line) + 1 + 4) + 4;
403 LINENO(flines[max_fline]) = max_lineno;
407 if (max_fline >= MAXLINES) {
408 eof_error = 0; /* Pretend we saw EOF */
411 if (!(option_mask32 & FLAG_S)
412 ? (max_fline > cur_fline + max_displayed_line)
413 : (max_fline >= cur_fline
414 && max_lineno > LINENO(flines[cur_fline]) + max_displayed_line)
416 #if !ENABLE_FEATURE_LESS_REGEXP
419 if (wanted_match >= num_matches) { /* goto_match called us */
420 fill_match_lines(old_max_fline);
421 old_max_fline = max_fline;
423 if (wanted_match < num_matches)
427 if (eof_error <= 0) {
429 if (errno == EAGAIN) {
430 /* not yet eof or error, reset flag (or else
431 * we will hog CPU - select() will return
435 print_statusline(bb_msg_read_error);
438 #if !ENABLE_FEATURE_LESS_REGEXP
441 if (wanted_match < num_matches) {
443 } else { /* goto_match called us */
444 time_t t = time(NULL);
445 if (t != last_time) {
447 if (--seconds_p1 == 0)
451 goto again0; /* go loop again (max 2 seconds) */
456 current_line = ((char*)xmalloc(w + 4)) + 4;
459 } /* end of "read lines until we reach cur_fline" loop */
460 fill_match_lines(old_max_fline);
461 #if ENABLE_FEATURE_LESS_REGEXP
462 /* prevent us from being stuck in search for a match */
468 #if ENABLE_FEATURE_LESS_FLAGS
469 /* Interestingly, writing calc_percent as a function saves around 32 bytes
471 static int calc_percent(void)
473 unsigned p = (100 * (cur_fline+max_displayed_line+1) + max_fline/2) / (max_fline+1);
474 return p <= 100 ? p : 100;
477 /* Print a status line if -M was specified */
478 static void m_status_print(void)
482 if (less_gets_pos >= 0) /* don't touch statusline while input is done! */
486 printf(HIGHLIGHT"%s", filename);
488 printf(" (file %i of %i)", current_file, num_files);
489 printf(" lines %i-%i/%i ",
490 cur_fline + 1, cur_fline + max_displayed_line + 1,
492 if (cur_fline >= (int)(max_fline - max_displayed_line)) {
493 printf("(END)"NORMAL);
494 if (num_files > 1 && current_file != num_files)
495 printf(HIGHLIGHT" - next: %s"NORMAL, files[current_file]);
498 percentage = calc_percent();
499 printf("%i%%"NORMAL, percentage);
503 /* Print the status line */
504 static void status_print(void)
508 if (less_gets_pos >= 0) /* don't touch statusline while input is done! */
511 /* Change the status if flags have been set */
512 #if ENABLE_FEATURE_LESS_FLAGS
513 if (option_mask32 & (FLAG_M|FLAG_m)) {
521 if (cur_fline && cur_fline < (int)(max_fline - max_displayed_line)) {
529 printf(HIGHLIGHT"%s (file %i of %i)"NORMAL,
530 p, current_file, num_files);
536 static void cap_cur_fline(int nlines)
541 if (cur_fline + max_displayed_line > max_fline + TILDES) {
545 diff = max_fline - (cur_fline + max_displayed_line) + TILDES;
546 /* As the number of lines requested was too large, we just move
547 * to the end of the file */
553 static const char controls[] ALIGN1 =
554 /* NUL: never encountered; TAB: not converted */
555 /**/"\x01\x02\x03\x04\x05\x06\x07\x08" "\x0a\x0b\x0c\x0d\x0e\x0f"
556 "\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1a\x1b\x1c\x1d\x1e\x1f"
557 "\x7f\x9b"; /* DEL and infamous Meta-ESC :( */
558 static const char ctrlconv[] ALIGN1 =
559 /* why 40 instead of 4a below? - it is a replacement for '\n'.
560 * '\n' is a former NUL - we subst it with @, not J */
561 "\x40\x41\x42\x43\x44\x45\x46\x47\x48\x49\x40\x4b\x4c\x4d\x4e\x4f"
562 "\x50\x51\x52\x53\x54\x55\x56\x57\x58\x59\x5a\x5b\x5c\x5d\x5e\x5f";
564 static void lineno_str(char *nbuf9, const char *line)
567 if (option_mask32 & FLAG_N) {
571 if (line == empty_line_marker) {
572 memset(nbuf9, ' ', 8);
576 /* Width of 7 preserves tab spacing in the text */
578 n = LINENO(line) + 1;
583 sprintf(nbuf9, fmt, n);
588 #if ENABLE_FEATURE_LESS_REGEXP
589 static void print_found(const char *line)
594 regmatch_t match_structs;
598 const char *str = line;
603 n = strcspn(str, controls);
610 n = strspn(str, controls);
617 /* buf[] holds quarantined version of str */
619 /* Each part of the line that matches has the HIGHLIGHT
620 and NORMAL escape sequences placed around it.
621 NB: we regex against line, but insert text
622 from quarantined copy (buf[]) */
628 while (match_status == 0) {
629 char *new = xasprintf("%s%.*s"HIGHLIGHT"%.*s"NORMAL,
630 growline ? growline : "",
631 match_structs.rm_so, str,
632 match_structs.rm_eo - match_structs.rm_so,
633 str + match_structs.rm_so);
636 str += match_structs.rm_eo;
637 line += match_structs.rm_eo;
640 /* Most of the time doesn't find the regex, optimize for that */
641 match_status = regexec(&pattern, line, 1, &match_structs, eflags);
642 /* if even "" matches, treat it as "not a match" */
643 if (match_structs.rm_so >= match_structs.rm_eo)
647 lineno_str(nbuf9, line);
649 printf(CLEAR_2_EOL"%s%s\n", nbuf9, str);
652 printf(CLEAR_2_EOL"%s%s%s\n", nbuf9, growline, str);
656 void print_found(const char *line);
659 static void print_ascii(const char *str)
666 lineno_str(nbuf9, str);
667 printf(CLEAR_2_EOL"%s", nbuf9);
670 n = strcspn(str, controls);
673 printf("%.*s", (int) n, str);
676 n = strspn(str, controls);
681 else if (*str == (char)0x9b)
682 /* VT100's CSI, aka Meta-ESC. Who's inventor? */
683 /* I want to know who committed this sin */
686 *p++ = ctrlconv[(unsigned char)*str];
695 /* Print the buffer */
696 static void buffer_print(void)
701 for (i = 0; i <= max_displayed_line; i++)
703 print_found(buffer[i]);
705 print_ascii(buffer[i]);
709 static void buffer_fill_and_print(void)
712 #if ENABLE_FEATURE_LESS_DASHCMD
713 int fpos = cur_fline;
715 if (option_mask32 & FLAG_S) {
716 /* Go back to the beginning of this line */
717 while (fpos && LINENO(flines[fpos]) == LINENO(flines[fpos-1]))
722 while (i <= max_displayed_line && fpos <= max_fline) {
723 int lineno = LINENO(flines[fpos]);
724 buffer[i] = flines[fpos];
728 } while ((fpos <= max_fline)
729 && (option_mask32 & FLAG_S)
730 && lineno == LINENO(flines[fpos])
734 for (i = 0; i <= max_displayed_line && cur_fline + i <= max_fline; i++) {
735 buffer[i] = flines[cur_fline + i];
738 for (; i <= max_displayed_line; i++) {
739 buffer[i] = empty_line_marker;
744 /* Move the buffer up and down in the file in order to scroll */
745 static void buffer_down(int nlines)
749 cap_cur_fline(nlines);
750 buffer_fill_and_print();
753 static void buffer_up(int nlines)
756 if (cur_fline < 0) cur_fline = 0;
758 buffer_fill_and_print();
761 static void buffer_line(int linenum)
767 if (linenum + max_displayed_line > max_fline)
768 linenum = max_fline - max_displayed_line + TILDES;
772 buffer_fill_and_print();
775 static void open_file_and_read_lines(void)
778 xmove_fd(xopen(filename, O_RDONLY), STDIN_FILENO);
780 /* "less" with no arguments in argv[] */
781 /* For status line only */
782 filename = xstrdup(bb_msg_standard_input);
791 /* Reinitialize everything for a new file - free the memory and start over */
792 static void reinitialize(void)
797 for (i = 0; i <= max_fline; i++)
798 free(MEMPTR(flines[i]));
806 open_file_and_read_lines();
807 buffer_fill_and_print();
810 static int getch_nowait(void)
813 struct pollfd pfd[2];
815 pfd[0].fd = STDIN_FILENO;
816 pfd[0].events = POLLIN;
818 pfd[1].events = POLLIN;
820 tcsetattr(kbd_fd, TCSANOW, &term_less);
821 /* NB: select/poll returns whenever read will not block. Therefore:
822 * if eof is reached, select/poll will return immediately
823 * because read will immediately return 0 bytes.
824 * Even if select/poll says that input is available, read CAN block
825 * (switch fd into O_NONBLOCK'ed mode to avoid it)
828 /* Are we interested in stdin? */
829 //TODO: reuse code for determining this
830 if (!(option_mask32 & FLAG_S)
831 ? !(max_fline > cur_fline + max_displayed_line)
832 : !(max_fline >= cur_fline
833 && max_lineno > LINENO(flines[cur_fline]) + max_displayed_line)
835 if (eof_error > 0) /* did NOT reach eof yet */
836 rd = 0; /* yes, we are interested in stdin */
838 /* Position cursor if line input is done */
839 if (less_gets_pos >= 0)
840 move_cursor(max_displayed_line + 2, less_gets_pos + 1);
843 if (kbd_input[0] == 0) { /* if nothing is buffered */
844 #if ENABLE_FEATURE_LESS_WINCH
847 /* NB: SIGWINCH interrupts poll() */
848 r = poll(pfd + rd, 2 - rd, -1);
849 if (/*r < 0 && errno == EINTR &&*/ winch_counter)
850 return '\\'; /* anything which has no defined function */
854 safe_poll(pfd + rd, 2 - rd, -1);
858 /* We have kbd_fd in O_NONBLOCK mode, read inside read_key()
859 * would not block even if there is no input available */
860 rd = read_key(kbd_fd, kbd_input, /*timeout off:*/ -2);
862 if (errno == EAGAIN) {
863 /* No keyboard input available. Since poll() did return,
864 * we should have input on stdin */
866 buffer_fill_and_print();
869 /* EOF/error (ssh session got killed etc) */
876 /* Grab a character from input without requiring the return key.
877 * May return KEYCODE_xxx values.
878 * Note that this function works best with raw input. */
879 static int less_getch(int pos)
888 /* Discard Ctrl-something chars */
889 if (i >= 0 && i < ' ' && i != 0x0d && i != 8)
894 static char* less_gets(int sz)
898 char *result = xzalloc(1);
902 less_gets_pos = sz + i;
915 if (c < ' ') /* filters out KEYCODE_xxx too (<0) */
917 if (i >= width - sz - 1)
918 continue; /* len limit */
921 result = xrealloc(result, i+1);
925 static void examine_file(void)
929 print_statusline("Examine: ");
930 new_fname = less_gets(sizeof("Examine: ") - 1);
937 if (access(new_fname, R_OK) != 0) {
938 print_statusline("Cannot read this file");
942 filename = new_fname;
943 /* files start by = argv. why we assume that argv is infinitely long??
944 files[num_files] = filename;
945 current_file = num_files + 1;
948 num_files = current_file = 1;
952 /* This function changes the file currently being paged. direction can be one of the following:
953 * -1: go back one file
954 * 0: go to the first file
955 * 1: go forward one file */
956 static void change_file(int direction)
958 if (current_file != ((direction > 0) ? num_files : 1)) {
959 current_file = direction ? current_file + direction : 1;
961 filename = xstrdup(files[current_file - 1]);
964 print_statusline(direction > 0 ? "No next file" : "No previous file");
968 static void remove_current_file(void)
975 if (current_file != 1) {
977 for (i = 3; i <= num_files; i++)
978 files[i - 2] = files[i - 1];
982 for (i = 2; i <= num_files; i++)
983 files[i - 2] = files[i - 1];
989 static void colon_process(void)
993 /* Clear the current line and print a prompt */
994 print_statusline(" :");
996 keypress = less_getch(2);
999 remove_current_file();
1004 #if ENABLE_FEATURE_LESS_FLAGS
1016 less_exit(EXIT_SUCCESS);
1024 #if ENABLE_FEATURE_LESS_REGEXP
1025 static void normalize_match_pos(int match)
1027 if (match >= num_matches)
1028 match = num_matches - 1;
1034 static void goto_match(int match)
1040 /* Try to find next match if eof isn't reached yet */
1041 if (match >= num_matches && eof_error > 0) {
1042 wanted_match = match; /* "I want to read until I see N'th match" */
1046 normalize_match_pos(match);
1047 buffer_line(match_lines[match_pos]);
1049 print_statusline("No matches found");
1053 static void fill_match_lines(unsigned pos)
1057 /* Run the regex on each line of the current file */
1058 while (pos <= max_fline) {
1059 /* If this line matches */
1060 if (regexec(&pattern, flines[pos], 0, NULL, 0) == 0
1061 /* and we didn't match it last time */
1062 && !(num_matches && match_lines[num_matches-1] == pos)
1064 match_lines = xrealloc_vector(match_lines, 4, num_matches);
1065 match_lines[num_matches++] = pos;
1071 static void regex_process(void)
1073 char *uncomp_regex, *err;
1075 /* Reset variables */
1080 if (pattern_valid) {
1085 /* Get the uncompiled regular expression from the user */
1087 bb_putchar((option_mask32 & LESS_STATE_MATCH_BACKWARDS) ? '?' : '/');
1088 uncomp_regex = less_gets(1);
1089 if (!uncomp_regex[0]) {
1095 /* Compile the regex and check for errors */
1096 err = regcomp_or_errmsg(&pattern, uncomp_regex,
1097 (option_mask32 & FLAG_I) ? REG_ICASE : 0);
1100 print_statusline(err);
1107 fill_match_lines(0);
1108 while (match_pos < num_matches) {
1109 if ((int)match_lines[match_pos] > cur_fline)
1113 if (option_mask32 & LESS_STATE_MATCH_BACKWARDS)
1116 /* It's possible that no matches are found yet.
1117 * goto_match() will read input looking for match,
1119 goto_match(match_pos);
1123 static void number_process(int first_digit)
1128 char num_input[sizeof(int)*4]; /* more than enough */
1130 num_input[0] = first_digit;
1132 /* Clear the current line, print a prompt, and then print the digit */
1134 printf(":%c", first_digit);
1136 /* Receive input until a letter is given */
1138 while (i < sizeof(num_input)-1) {
1139 keypress = less_getch(i + 1);
1140 if ((unsigned)keypress > 255 || !isdigit(num_input[i]))
1142 num_input[i] = keypress;
1143 bb_putchar(keypress);
1147 num_input[i] = '\0';
1148 num = bb_strtou(num_input, NULL, 10);
1149 /* on format error, num == -1 */
1150 if (num < 1 || num > MAXLINES) {
1155 /* We now know the number and the letter entered, so we process them */
1157 case KEYCODE_DOWN: case 'z': case 'd': case 'e': case ' ': case '\015':
1160 case KEYCODE_UP: case 'b': case 'w': case 'y': case 'u':
1163 case 'g': case '<': case 'G': case '>':
1164 cur_fline = num + max_displayed_line;
1166 buffer_line(num - 1);
1169 num = num * (max_fline / 100); /* + max_fline / 2; */
1170 cur_fline = num + max_displayed_line;
1174 #if ENABLE_FEATURE_LESS_REGEXP
1176 goto_match(match_pos + num);
1179 option_mask32 &= ~LESS_STATE_MATCH_BACKWARDS;
1183 option_mask32 |= LESS_STATE_MATCH_BACKWARDS;
1190 #if ENABLE_FEATURE_LESS_DASHCMD
1191 static void flag_change(void)
1197 keypress = less_getch(1);
1201 option_mask32 ^= FLAG_M;
1204 option_mask32 ^= FLAG_m;
1207 option_mask32 ^= FLAG_E;
1210 option_mask32 ^= FLAG_TILDE;
1213 option_mask32 ^= FLAG_S;
1214 buffer_fill_and_print();
1216 #if ENABLE_FEATURE_LESS_LINENUMS
1218 option_mask32 ^= FLAG_N;
1220 buffer_fill_and_print();
1227 static void show_flag_status(void)
1234 keypress = less_getch(1);
1238 flag_val = option_mask32 & FLAG_M;
1241 flag_val = option_mask32 & FLAG_m;
1244 flag_val = option_mask32 & FLAG_TILDE;
1247 flag_val = option_mask32 & FLAG_N;
1250 flag_val = option_mask32 & FLAG_E;
1258 printf(HIGHLIGHT"The status of the flag is: %u"NORMAL, flag_val != 0);
1262 #endif /* ENABLE_FEATURE_LESS_DASHCMD */
1264 static void save_input_to_file(void)
1266 const char *msg = "";
1271 print_statusline("Log file: ");
1272 current_line = less_gets(sizeof("Log file: ")-1);
1273 if (current_line[0]) {
1274 fp = fopen_for_write(current_line);
1276 msg = "Error opening log file";
1279 for (i = 0; i <= max_fline; i++)
1280 fprintf(fp, "%s\n", flines[i]);
1285 print_statusline(msg);
1289 #if ENABLE_FEATURE_LESS_MARKS
1290 static void add_mark(void)
1294 print_statusline("Mark: ");
1295 letter = less_getch(sizeof("Mark: ") - 1);
1297 if (isalpha(letter)) {
1298 /* If we exceed 15 marks, start overwriting previous ones */
1299 if (num_marks == 14)
1302 mark_lines[num_marks][0] = letter;
1303 mark_lines[num_marks][1] = cur_fline;
1306 print_statusline("Invalid mark letter");
1310 static void goto_mark(void)
1315 print_statusline("Go to mark: ");
1316 letter = less_getch(sizeof("Go to mark: ") - 1);
1319 if (isalpha(letter)) {
1320 for (i = 0; i <= num_marks; i++)
1321 if (letter == mark_lines[i][0]) {
1322 buffer_line(mark_lines[i][1]);
1325 if (num_marks == 14 && letter != mark_lines[14][0])
1326 print_statusline("Mark not set");
1328 print_statusline("Invalid mark letter");
1332 #if ENABLE_FEATURE_LESS_BRACKETS
1333 static char opp_bracket(char bracket)
1336 case '{': case '[': /* '}' == '{' + 2. Same for '[' */
1338 case '(': /* ')' == '(' + 1 */
1350 static void match_right_bracket(char bracket)
1354 if (strchr(flines[cur_fline], bracket) == NULL) {
1355 print_statusline("No bracket in top line");
1358 bracket = opp_bracket(bracket);
1359 for (i = cur_fline + 1; i < max_fline; i++) {
1360 if (strchr(flines[i], bracket) != NULL) {
1365 print_statusline("No matching bracket found");
1368 static void match_left_bracket(char bracket)
1372 if (strchr(flines[cur_fline + max_displayed_line], bracket) == NULL) {
1373 print_statusline("No bracket in bottom line");
1377 bracket = opp_bracket(bracket);
1378 for (i = cur_fline + max_displayed_line; i >= 0; i--) {
1379 if (strchr(flines[i], bracket) != NULL) {
1384 print_statusline("No matching bracket found");
1386 #endif /* FEATURE_LESS_BRACKETS */
1388 static void keypress_process(int keypress)
1391 case KEYCODE_DOWN: case 'e': case 'j': case 0x0d:
1394 case KEYCODE_UP: case 'y': case 'k':
1397 case KEYCODE_PAGEDOWN: case ' ': case 'z': case 'f':
1398 buffer_down(max_displayed_line + 1);
1400 case KEYCODE_PAGEUP: case 'w': case 'b':
1401 buffer_up(max_displayed_line + 1);
1404 buffer_down((max_displayed_line + 1) / 2);
1407 buffer_up((max_displayed_line + 1) / 2);
1409 case KEYCODE_HOME: case 'g': case 'p': case '<': case '%':
1412 case KEYCODE_END: case 'G': case '>':
1413 cur_fline = MAXLINES;
1415 buffer_line(cur_fline);
1418 less_exit(EXIT_SUCCESS);
1420 #if ENABLE_FEATURE_LESS_MARKS
1437 save_input_to_file();
1442 #if ENABLE_FEATURE_LESS_FLAGS
1447 #if ENABLE_FEATURE_LESS_REGEXP
1449 option_mask32 &= ~LESS_STATE_MATCH_BACKWARDS;
1453 goto_match(match_pos + 1);
1456 goto_match(match_pos - 1);
1459 option_mask32 |= LESS_STATE_MATCH_BACKWARDS;
1463 #if ENABLE_FEATURE_LESS_DASHCMD
1474 #if ENABLE_FEATURE_LESS_BRACKETS
1475 case '{': case '(': case '[':
1476 match_right_bracket(keypress);
1478 case '}': case ')': case ']':
1479 match_left_bracket(keypress);
1487 if (isdigit(keypress))
1488 number_process(keypress);
1491 static void sig_catcher(int sig)
1496 #if ENABLE_FEATURE_LESS_WINCH
1497 static void sigwinch_handler(int sig UNUSED_PARAM)
1503 int less_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
1504 int less_main(int argc, char **argv)
1510 /* TODO: -x: do not interpret backspace, -xx: tab also */
1511 /* -xxx: newline also */
1512 /* -w N: assume width N (-xxx -w 32: hex viewer of sorts) */
1513 getopt32(argv, "EMmN~I" IF_FEATURE_LESS_DASHCMD("S"));
1519 /* Another popular pager, most, detects when stdout
1520 * is not a tty and turns into cat. This makes sense. */
1521 if (!isatty(STDOUT_FILENO))
1522 return bb_cat(argv);
1525 if (isatty(STDIN_FILENO)) {
1526 /* Just "less"? No args and no redirection? */
1527 bb_error_msg("missing filename");
1531 filename = xstrdup(files[0]);
1534 if (option_mask32 & FLAG_TILDE)
1535 empty_line_marker = "";
1537 kbd_fd = open(CURRENT_TTY, O_RDONLY);
1539 return bb_cat(argv);
1542 tcgetattr(kbd_fd, &term_orig);
1543 term_less = term_orig;
1544 term_less.c_lflag &= ~(ICANON | ECHO);
1545 term_less.c_iflag &= ~(IXON | ICRNL);
1546 /*term_less.c_oflag &= ~ONLCR;*/
1547 term_less.c_cc[VMIN] = 1;
1548 term_less.c_cc[VTIME] = 0;
1550 get_terminal_width_height(kbd_fd, &width, &max_displayed_line);
1551 /* 20: two tabstops + 4 */
1552 if (width < 20 || max_displayed_line < 3)
1553 return bb_cat(argv);
1554 max_displayed_line -= 2;
1556 /* We want to restore term_orig on exit */
1557 bb_signals(BB_FATAL_SIGS, sig_catcher);
1558 #if ENABLE_FEATURE_LESS_WINCH
1559 signal(SIGWINCH, sigwinch_handler);
1562 buffer = xmalloc((max_displayed_line+1) * sizeof(char *));
1565 #if ENABLE_FEATURE_LESS_WINCH
1566 while (WINCH_COUNTER) {
1569 get_terminal_width_height(kbd_fd, &width, &max_displayed_line);
1570 /* 20: two tabstops + 4 */
1573 if (max_displayed_line < 3)
1574 max_displayed_line = 3;
1575 max_displayed_line -= 2;
1577 buffer = xmalloc((max_displayed_line+1) * sizeof(char *));
1578 /* Avoid re-wrap and/or redraw if we already know
1579 * we need to do it again. These ops are expensive */
1585 buffer_fill_and_print();
1586 /* This took some time. Loop back and check,
1587 * were there another SIGWINCH? */
1590 keypress = less_getch(-1); /* -1: do not position cursor */
1591 keypress_process(keypress);
1596 Help text of less version 418 is below.
1597 If you are implementing something, keeping
1598 key and/or command line switch compatibility is a good idea:
1601 SUMMARY OF LESS COMMANDS
1603 Commands marked with * may be preceded by a number, N.
1604 Notes in parentheses indicate the behavior if N is given.
1605 h H Display this help.
1607 ---------------------------------------------------------------------------
1609 e ^E j ^N CR * Forward one line (or N lines).
1610 y ^Y k ^K ^P * Backward one line (or N lines).
1611 f ^F ^V SPACE * Forward one window (or N lines).
1612 b ^B ESC-v * Backward one window (or N lines).
1613 z * Forward one window (and set window to N).
1614 w * Backward one window (and set window to N).
1615 ESC-SPACE * Forward one window, but don't stop at end-of-file.
1616 d ^D * Forward one half-window (and set half-window to N).
1617 u ^U * Backward one half-window (and set half-window to N).
1618 ESC-) RightArrow * Left one half screen width (or N positions).
1619 ESC-( LeftArrow * Right one half screen width (or N positions).
1620 F Forward forever; like "tail -f".
1621 r ^R ^L Repaint screen.
1622 R Repaint screen, discarding buffered input.
1623 ---------------------------------------------------
1624 Default "window" is the screen height.
1625 Default "half-window" is half of the screen height.
1626 ---------------------------------------------------------------------------
1628 /pattern * Search forward for (N-th) matching line.
1629 ?pattern * Search backward for (N-th) matching line.
1630 n * Repeat previous search (for N-th occurrence).
1631 N * Repeat previous search in reverse direction.
1632 ESC-n * Repeat previous search, spanning files.
1633 ESC-N * Repeat previous search, reverse dir. & spanning files.
1634 ESC-u Undo (toggle) search highlighting.
1635 ---------------------------------------------------
1636 Search patterns may be modified by one or more of:
1637 ^N or ! Search for NON-matching lines.
1638 ^E or * Search multiple files (pass thru END OF FILE).
1639 ^F or @ Start search at FIRST file (for /) or last file (for ?).
1640 ^K Highlight matches, but don't move (KEEP position).
1641 ^R Don't use REGULAR EXPRESSIONS.
1642 ---------------------------------------------------------------------------
1644 g < ESC-< * Go to first line in file (or line N).
1645 G > ESC-> * Go to last line in file (or line N).
1646 p % * Go to beginning of file (or N percent into file).
1647 t * Go to the (N-th) next tag.
1648 T * Go to the (N-th) previous tag.
1649 { ( [ * Find close bracket } ) ].
1650 } ) ] * Find open bracket { ( [.
1651 ESC-^F <c1> <c2> * Find close bracket <c2>.
1652 ESC-^B <c1> <c2> * Find open bracket <c1>
1653 ---------------------------------------------------
1654 Each "find close bracket" command goes forward to the close bracket
1655 matching the (N-th) open bracket in the top line.
1656 Each "find open bracket" command goes backward to the open bracket
1657 matching the (N-th) close bracket in the bottom line.
1658 m<letter> Mark the current position with <letter>.
1659 '<letter> Go to a previously marked position.
1660 '' Go to the previous position.
1662 ---------------------------------------------------
1663 A mark is any upper-case or lower-case letter.
1664 Certain marks are predefined:
1665 ^ means beginning of the file
1666 $ means end of the file
1667 ---------------------------------------------------------------------------
1669 :e [file] Examine a new file.
1671 :n * Examine the (N-th) next file from the command line.
1672 :p * Examine the (N-th) previous file from the command line.
1673 :x * Examine the first (or N-th) file from the command line.
1674 :d Delete the current file from the command line list.
1675 = ^G :f Print current file name.
1676 ---------------------------------------------------------------------------
1677 MISCELLANEOUS COMMANDS
1678 -<flag> Toggle a command line option [see OPTIONS below].
1679 --<name> Toggle a command line option, by name.
1680 _<flag> Display the setting of a command line option.
1681 __<name> Display the setting of an option, by name.
1682 +cmd Execute the less cmd each time a new file is examined.
1683 !command Execute the shell command with $SHELL.
1684 |Xcommand Pipe file between current pos & mark X to shell command.
1685 v Edit the current file with $VISUAL or $EDITOR.
1686 V Print version number of "less".
1687 ---------------------------------------------------------------------------
1689 Most options may be changed either on the command line,
1690 or from within less by using the - or -- command.
1691 Options may be given in one of two forms: either a single
1692 character preceded by a -, or a name preceeded by --.
1694 Display help (from command line).
1695 -a ........ --search-skip-screen
1696 Forward search skips current screen.
1697 -b [N] .... --buffers=[N]
1699 -B ........ --auto-buffers
1700 Don't automatically allocate buffers for pipes.
1701 -c ........ --clear-screen
1702 Repaint by clearing rather than scrolling.
1705 -D [xn.n] . --color=xn.n
1706 Set screen colors. (MS-DOS only)
1707 -e -E .... --quit-at-eof --QUIT-AT-EOF
1708 Quit at end of file.
1710 Force open non-regular files.
1711 -F ........ --quit-if-one-screen
1712 Quit if entire file fits on first screen.
1713 -g ........ --hilite-search
1714 Highlight only last match for searches.
1715 -G ........ --HILITE-SEARCH
1716 Don't highlight any matches for searches.
1717 -h [N] .... --max-back-scroll=[N]
1718 Backward scroll limit.
1719 -i ........ --ignore-case
1720 Ignore case in searches that do not contain uppercase.
1721 -I ........ --IGNORE-CASE
1722 Ignore case in all searches.
1723 -j [N] .... --jump-target=[N]
1724 Screen position of target lines.
1725 -J ........ --status-column
1726 Display a status column at left edge of screen.
1727 -k [file] . --lesskey-file=[file]
1729 -L ........ --no-lessopen
1730 Ignore the LESSOPEN environment variable.
1731 -m -M .... --long-prompt --LONG-PROMPT
1733 -n -N .... --line-numbers --LINE-NUMBERS
1734 Don't use line numbers.
1735 -o [file] . --log-file=[file]
1736 Copy to log file (standard input only).
1737 -O [file] . --LOG-FILE=[file]
1738 Copy to log file (unconditionally overwrite).
1739 -p [pattern] --pattern=[pattern]
1740 Start at pattern (from command line).
1741 -P [prompt] --prompt=[prompt]
1743 -q -Q .... --quiet --QUIET --silent --SILENT
1744 Quiet the terminal bell.
1745 -r -R .... --raw-control-chars --RAW-CONTROL-CHARS
1746 Output "raw" control characters.
1747 -s ........ --squeeze-blank-lines
1748 Squeeze multiple blank lines.
1749 -S ........ --chop-long-lines
1751 -t [tag] .. --tag=[tag]
1753 -T [tagsfile] --tag-file=[tagsfile]
1754 Use an alternate tags file.
1755 -u -U .... --underline-special --UNDERLINE-SPECIAL
1756 Change handling of backspaces.
1757 -V ........ --version
1758 Display the version number of "less".
1759 -w ........ --hilite-unread
1760 Highlight first new line after forward-screen.
1761 -W ........ --HILITE-UNREAD
1762 Highlight first new line after any forward movement.
1763 -x [N[,...]] --tabs=[N[,...]]
1765 -X ........ --no-init
1766 Don't use termcap init/deinit strings.
1768 Don't use termcap keypad init/deinit strings.
1769 -y [N] .... --max-forw-scroll=[N]
1770 Forward scroll limit.
1771 -z [N] .... --window=[N]
1773 -" [c[c]] . --quotes=[c[c]]
1774 Set shell quote characters.
1776 Don't display tildes after end of file.
1777 -# [N] .... --shift=[N]
1778 Horizontal scroll amount (0 = one half screen width)
1780 ---------------------------------------------------------------------------
1782 These keys can be used to edit text being entered
1783 on the "command line" at the bottom of the screen.
1784 RightArrow ESC-l Move cursor right one character.
1785 LeftArrow ESC-h Move cursor left one character.
1786 CNTL-RightArrow ESC-RightArrow ESC-w Move cursor right one word.
1787 CNTL-LeftArrow ESC-LeftArrow ESC-b Move cursor left one word.
1788 HOME ESC-0 Move cursor to start of line.
1789 END ESC-$ Move cursor to end of line.
1790 BACKSPACE Delete char to left of cursor.
1791 DELETE ESC-x Delete char under cursor.
1792 CNTL-BACKSPACE ESC-BACKSPACE Delete word to left of cursor.
1793 CNTL-DELETE ESC-DELETE ESC-X Delete word under cursor.
1794 CNTL-U ESC (MS-DOS only) Delete entire line.
1795 UpArrow ESC-k Retrieve previous command line.
1796 DownArrow ESC-j Retrieve next command line.
1797 TAB Complete filename & cycle.
1798 SHIFT-TAB ESC-TAB Complete filename & reverse cycle.
1799 CNTL-L Complete filename, list all.