more: accept and ignore a bunch of options
[oweals/busybox.git] / util-linux / more.c
1 /* vi: set sw=4 ts=4: */
2 /*
3  * Mini more implementation for busybox
4  *
5  * Copyright (C) 1995, 1996 by Bruce Perens <bruce@pixar.com>.
6  * Copyright (C) 1999-2004 by Erik Andersen <andersen@codepoet.org>
7  *
8  * Latest version blended together by Erik Andersen <andersen@codepoet.org>,
9  * based on the original more implementation by Bruce, and code from the
10  * Debian boot-floppies team.
11  *
12  * Termios corrects by Vladimir Oleynik <dzo@simtreas.ru>
13  *
14  * Licensed under GPLv2 or later, see file LICENSE in this source tree.
15  */
16
17 //usage:#define more_trivial_usage
18 //usage:       "[FILE]..."
19 //usage:#define more_full_usage "\n\n"
20 //usage:       "View FILE (or stdin) one screenful at a time"
21 //usage:
22 //usage:#define more_example_usage
23 //usage:       "$ dmesg | more\n"
24
25 #include "libbb.h"
26 #include "common_bufsiz.h"
27
28 /* Support for FEATURE_USE_TERMIOS */
29
30 struct globals {
31         int cin_fileno;
32         struct termios initial_settings;
33         struct termios new_settings;
34 } FIX_ALIASING;
35 #define G (*(struct globals*)bb_common_bufsiz1)
36 #define initial_settings (G.initial_settings)
37 #define new_settings     (G.new_settings    )
38 #define cin_fileno       (G.cin_fileno      )
39 #define INIT_G() do { setup_common_bufsiz(); } while (0)
40
41 #define setTermSettings(fd, argp) \
42 do { \
43         if (ENABLE_FEATURE_USE_TERMIOS) \
44                 tcsetattr(fd, TCSANOW, argp); \
45 } while (0)
46 #define getTermSettings(fd, argp) tcgetattr(fd, argp)
47
48 static void gotsig(int sig UNUSED_PARAM)
49 {
50         /* bb_putchar_stderr doesn't use stdio buffering,
51          * therefore it is safe in signal handler */
52         bb_putchar_stderr('\n');
53         setTermSettings(cin_fileno, &initial_settings);
54         _exit(EXIT_FAILURE);
55 }
56
57 #define CONVERTED_TAB_SIZE 8
58
59 int more_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
60 int more_main(int argc UNUSED_PARAM, char **argv)
61 {
62         int c = c; /* for compiler */
63         int lines;
64         int input = 0;
65         int spaces = 0;
66         int please_display_more_prompt;
67         struct stat st;
68         FILE *file;
69         FILE *cin;
70         int len;
71         unsigned terminal_width;
72         unsigned terminal_height;
73
74         INIT_G();
75
76         /* Parse options */
77         /* Accepted but ignored: */
78         /* -d   Display help instead of ringing bell is pressed */
79         /* -f   Count logical lines (IOW: long lines are not folded) */
80         /* -l   Do not pause after any line containing a ^L (form feed) */
81         /* -s   Squeeze blank lines into one */
82         /* -u   Suppress underlining */
83         getopt32(argv, "dflsu");
84         argv += optind;
85
86         /* Another popular pager, most, detects when stdout
87          * is not a tty and turns into cat. This makes sense. */
88         if (!isatty(STDOUT_FILENO))
89                 return bb_cat(argv);
90         cin = fopen_for_read(CURRENT_TTY);
91         if (!cin)
92                 return bb_cat(argv);
93
94         if (ENABLE_FEATURE_USE_TERMIOS) {
95                 cin_fileno = fileno(cin);
96                 getTermSettings(cin_fileno, &initial_settings);
97                 new_settings = initial_settings;
98                 new_settings.c_lflag &= ~(ICANON | ECHO);
99                 new_settings.c_cc[VMIN] = 1;
100                 new_settings.c_cc[VTIME] = 0;
101                 setTermSettings(cin_fileno, &new_settings);
102                 bb_signals(0
103                         + (1 << SIGINT)
104                         + (1 << SIGQUIT)
105                         + (1 << SIGTERM)
106                         , gotsig);
107         }
108
109         do {
110                 file = stdin;
111                 if (*argv) {
112                         file = fopen_or_warn(*argv, "r");
113                         if (!file)
114                                 continue;
115                 }
116                 st.st_size = 0;
117                 fstat(fileno(file), &st);
118
119                 please_display_more_prompt = 0;
120                 /* never returns w, h <= 1 */
121                 get_terminal_width_height(fileno(cin), &terminal_width, &terminal_height);
122                 terminal_height -= 1;
123
124                 len = 0;
125                 lines = 0;
126                 while (spaces || (c = getc(file)) != EOF) {
127                         int wrap;
128                         if (spaces)
129                                 spaces--;
130  loop_top:
131                         if (input != 'r' && please_display_more_prompt) {
132                                 len = printf("--More-- ");
133                                 if (st.st_size != 0) {
134                                         uoff_t d = (uoff_t)st.st_size / 100;
135                                         if (d == 0)
136                                                 d = 1;
137                                         len += printf("(%u%% of %"OFF_FMT"u bytes)",
138                                                 (int) ((uoff_t)ftello(file) / d),
139                                                 st.st_size);
140                                 }
141                                 fflush_all();
142
143                                 /*
144                                  * We've just displayed the "--More--" prompt, so now we need
145                                  * to get input from the user.
146                                  */
147                                 for (;;) {
148                                         input = getc(cin);
149                                         input = tolower(input);
150                                         if (!ENABLE_FEATURE_USE_TERMIOS)
151                                                 printf("\033[A"); /* cursor up */
152                                         /* Erase the last message */
153                                         printf("\r%*s\r", len, "");
154
155                                         /* Due to various multibyte escape
156                                          * sequences, it's not ok to accept
157                                          * any input as a command to scroll
158                                          * the screen. We only allow known
159                                          * commands, else we show help msg. */
160                                         if (input == ' ' || input == '\n' || input == 'q' || input == 'r')
161                                                 break;
162                                         len = printf("(Enter:next line Space:next page Q:quit R:show the rest)");
163                                 }
164                                 len = 0;
165                                 lines = 0;
166                                 please_display_more_prompt = 0;
167
168                                 if (input == 'q')
169                                         goto end;
170
171                                 /* The user may have resized the terminal.
172                                  * Re-read the dimensions. */
173                                 if (ENABLE_FEATURE_USE_TERMIOS) {
174                                         get_terminal_width_height(cin_fileno, &terminal_width, &terminal_height);
175                                         terminal_height -= 1;
176                                 }
177                         }
178
179                         /* Crudely convert tabs into spaces, which are
180                          * a bajillion times easier to deal with. */
181                         if (c == '\t') {
182                                 spaces = ((unsigned)~len) % CONVERTED_TAB_SIZE;
183                                 c = ' ';
184                         }
185
186                         /*
187                          * There are two input streams to worry about here:
188                          *
189                          * c    : the character we are reading from the file being "mored"
190                          * input: a character received from the keyboard
191                          *
192                          * If we hit a newline in the _file_ stream, we want to test and
193                          * see if any characters have been hit in the _input_ stream. This
194                          * allows the user to quit while in the middle of a file.
195                          */
196                         wrap = (++len > terminal_width);
197                         if (c == '\n' || wrap) {
198                                 /* Then outputting this character
199                                  * will move us to a new line. */
200                                 if (++lines >= terminal_height || input == '\n')
201                                         please_display_more_prompt = 1;
202                                 len = 0;
203                         }
204                         if (c != '\n' && wrap) {
205                                 /* Then outputting this will also put a character on
206                                  * the beginning of that new line. Thus we first want to
207                                  * display the prompt (if any), so we skip the putchar()
208                                  * and go back to the top of the loop, without reading
209                                  * a new character. */
210                                 goto loop_top;
211                         }
212                         /* My small mind cannot fathom backspaces and UTF-8 */
213                         putchar(c);
214                         die_if_ferror_stdout(); /* if tty was destroyed (closed xterm, etc) */
215                 }
216                 fclose(file);
217                 fflush_all();
218         } while (*argv && *++argv);
219  end:
220         setTermSettings(cin_fileno, &initial_settings);
221         return 0;
222 }