more: hardcode FEATURE_USE_TERMIOS=y in this applet; code shrink
[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 //config:config MORE
17 //config:       bool "more"
18 //config:       default y
19 //config:       help
20 //config:         more is a simple utility which allows you to read text one screen
21 //config:         sized page at a time. If you want to read text that is larger than
22 //config:         the screen, and you are using anything faster than a 300 baud modem,
23 //config:         you will probably find this utility very helpful. If you don't have
24 //config:         any need to reading text files, you can leave this disabled.
25
26 //applet:IF_MORE(APPLET(more, BB_DIR_BIN, BB_SUID_DROP))
27
28 //kbuild:lib-$(CONFIG_MORE) += more.o
29
30 //usage:#define more_trivial_usage
31 //usage:       "[FILE]..."
32 //usage:#define more_full_usage "\n\n"
33 //usage:       "View FILE (or stdin) one screenful at a time"
34 //usage:
35 //usage:#define more_example_usage
36 //usage:       "$ dmesg | more\n"
37
38 #include "libbb.h"
39 #include "common_bufsiz.h"
40
41 struct globals {
42         int tty_fileno;
43         unsigned terminal_width;
44         unsigned terminal_height;
45         struct termios initial_settings;
46         struct termios new_settings;
47 } FIX_ALIASING;
48 #define G (*(struct globals*)bb_common_bufsiz1)
49 #define INIT_G() do { setup_common_bufsiz(); } while (0)
50
51 static void get_wh(void)
52 {
53         /* never returns w, h <= 1 */
54         get_terminal_width_height(G.tty_fileno, &G.terminal_width, &G.terminal_height);
55         G.terminal_height -= 1;
56 }
57
58 static void tcsetattr_tty_TCSANOW(struct termios *settings)
59 {
60         tcsetattr(G.tty_fileno, TCSANOW, settings);
61 }
62
63 static void gotsig(int sig UNUSED_PARAM)
64 {
65         /* bb_putchar_stderr doesn't use stdio buffering,
66          * therefore it is safe in signal handler */
67         bb_putchar_stderr('\n');
68         tcsetattr_tty_TCSANOW(&G.initial_settings);
69         _exit(EXIT_FAILURE);
70 }
71
72 #define CONVERTED_TAB_SIZE 8
73
74 int more_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
75 int more_main(int argc UNUSED_PARAM, char **argv)
76 {
77         int c = c; /* for compiler */
78         int input = 0;
79         int spaces = 0;
80         int please_display_more_prompt;
81         FILE *tty;
82
83         INIT_G();
84
85         /* Parse options */
86         /* Accepted but ignored: */
87         /* -d   Display help instead of ringing bell */
88         /* -f   Count logical lines (IOW: long lines are not folded) */
89         /* -l   Do not pause after any line containing a ^L (form feed) */
90         /* -s   Squeeze blank lines into one */
91         /* -u   Suppress underlining */
92         getopt32(argv, "dflsu");
93         argv += optind;
94
95         /* Another popular pager, most, detects when stdout
96          * is not a tty and turns into cat. This makes sense. */
97         if (!isatty(STDOUT_FILENO))
98                 return bb_cat(argv);
99         tty = fopen_for_read(CURRENT_TTY);
100         if (!tty)
101                 return bb_cat(argv);
102
103         G.tty_fileno = fileno(tty);
104         tcgetattr(G.tty_fileno, &G.initial_settings);
105         G.new_settings = G.initial_settings;
106         G.new_settings.c_lflag &= ~(ICANON | ECHO);
107         G.new_settings.c_cc[VMIN] = 1;
108         G.new_settings.c_cc[VTIME] = 0;
109         tcsetattr_tty_TCSANOW(&G.new_settings);
110         bb_signals(BB_FATAL_SIGS, gotsig);
111
112         do {
113                 struct stat st;
114                 FILE *file;
115                 int len;
116                 int lines;
117
118                 file = stdin;
119                 if (*argv) {
120                         file = fopen_or_warn(*argv, "r");
121                         if (!file)
122                                 continue;
123                 }
124                 st.st_size = 0;
125                 fstat(fileno(file), &st);
126
127                 get_wh();
128
129                 please_display_more_prompt = 0;
130                 len = 0;
131                 lines = 0;
132                 for (;;) {
133                         int wrap;
134
135                         if (spaces)
136                                 spaces--;
137                         else {
138                                 c = getc(file);
139                                 if (c == EOF) break;
140                         }
141  loop_top:
142                         if (input != 'r' && please_display_more_prompt) {
143                                 len = printf("--More-- ");
144                                 if (st.st_size != 0) {
145                                         uoff_t d = (uoff_t)st.st_size / 100;
146                                         if (d == 0)
147                                                 d = 1;
148                                         len += printf("(%u%% of %"OFF_FMT"u bytes)",
149                                                 (int) ((uoff_t)ftello(file) / d),
150                                                 st.st_size);
151                                 }
152
153                                 /*
154                                  * We've just displayed the "--More--" prompt, so now we need
155                                  * to get input from the user.
156                                  */
157                                 for (;;) {
158                                         fflush_all();
159                                         input = getc(tty);
160                                         input = tolower(input);
161                                         /* Erase the last message */
162                                         printf("\r%*s\r", len, "");
163
164                                         if (input == 'q')
165                                                 goto end;
166                                         /* Due to various multibyte escape
167                                          * sequences, it's not ok to accept
168                                          * any input as a command to scroll
169                                          * the screen. We only allow known
170                                          * commands, else we show help msg. */
171                                         if (input == ' ' || input == '\n' || input == 'r')
172                                                 break;
173                                         len = printf("(Enter:next line Space:next page Q:quit R:show the rest)");
174                                 }
175                                 len = 0;
176                                 lines = 0;
177                                 please_display_more_prompt = 0;
178
179                                 /* The user may have resized the terminal.
180                                  * Re-read the dimensions. */
181                                 get_wh();
182                         }
183
184                         /* Crudely convert tabs into spaces, which are
185                          * a bajillion times easier to deal with. */
186                         if (c == '\t') {
187                                 spaces = ((unsigned)~len) % CONVERTED_TAB_SIZE;
188                                 c = ' ';
189                         }
190
191                         /*
192                          * There are two input streams to worry about here:
193                          *
194                          * c    : the character we are reading from the file being "mored"
195                          * input: a character received from the keyboard
196                          *
197                          * If we hit a newline in the _file_ stream, we want to test and
198                          * see if any characters have been hit in the _input_ stream. This
199                          * allows the user to quit while in the middle of a file.
200                          */
201                         wrap = (++len > G.terminal_width);
202                         if (c == '\n' || wrap) {
203                                 /* Then outputting this character
204                                  * will move us to a new line. */
205                                 if (++lines >= G.terminal_height || input == '\n')
206                                         please_display_more_prompt = 1;
207                                 len = 0;
208                         }
209                         if (c != '\n' && wrap) {
210                                 /* Then outputting this will also put a character on
211                                  * the beginning of that new line. Thus we first want to
212                                  * display the prompt (if any), so we skip the putchar()
213                                  * and go back to the top of the loop, without reading
214                                  * a new character. */
215                                 goto loop_top;
216                         }
217                         /* My small mind cannot fathom backspaces and UTF-8 */
218                         putchar(c);
219                         die_if_ferror_stdout(); /* if tty was destroyed (closed xterm, etc) */
220                 }
221                 fclose(file);
222                 fflush_all();
223         } while (*argv && *++argv);
224  end:
225         tcsetattr_tty_TCSANOW(&G.initial_settings);
226         return 0;
227 }