1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
use std::{
fs::File,
io::{stdin, stdout, BufReader, Read, Stdout, Write},
path::Path,
time::Duration,
};
use clap::{crate_version, Arg, ArgAction, Command};
use crossterm::event::KeyEventKind;
use crossterm::{
event::{self, Event, KeyCode, KeyEvent, KeyModifiers},
execute, queue,
style::Attribute,
terminal,
};
use is_terminal::IsTerminal;
use unicode_segmentation::UnicodeSegmentation;
use unicode_width::UnicodeWidthStr;
use uucore::display::Quotable;
use uucore::error::{UResult, USimpleError, UUsageError};
use uucore::{format_usage, help_about, help_usage};
const ABOUT: &str = help_about!("more.md");
const USAGE: &str = help_usage!("more.md");
const BELL: &str = "\x07";
pub mod options {
pub const SILENT: &str = "silent";
pub const LOGICAL: &str = "logical";
pub const NO_PAUSE: &str = "no-pause";
pub const PRINT_OVER: &str = "print-over";
pub const CLEAN_PRINT: &str = "clean-print";
pub const SQUEEZE: &str = "squeeze";
pub const PLAIN: &str = "plain";
pub const LINES: &str = "lines";
pub const NUMBER: &str = "number";
pub const PATTERN: &str = "pattern";
pub const FROM_LINE: &str = "from-line";
pub const FILES: &str = "files";
}
const MULTI_FILE_TOP_PROMPT: &str = "::::::::::::::\n{}\n::::::::::::::\n";
#[uucore::main]
pub fn uumain(args: impl uucore::Args) -> UResult<()> {
let matches = uu_app().get_matches_from(args);
let mut buff = String::new();
let silent = matches.get_flag(options::SILENT);
if let Some(files) = matches.get_many::<String>(options::FILES) {
let mut stdout = setup_term();
let length = files.len();
let mut files_iter = files.map(|s| s.as_str()).peekable();
while let (Some(file), next_file) = (files_iter.next(), files_iter.peek()) {
let file = Path::new(file);
if file.is_dir() {
terminal::disable_raw_mode().unwrap();
return Err(UUsageError::new(
1,
format!("{} is a directory.", file.quote()),
));
}
if !file.exists() {
terminal::disable_raw_mode().unwrap();
return Err(USimpleError::new(
1,
format!("cannot open {}: No such file or directory", file.quote()),
));
}
if length > 1 {
buff.push_str(&MULTI_FILE_TOP_PROMPT.replace("{}", file.to_str().unwrap()));
}
let mut reader = BufReader::new(File::open(file).unwrap());
reader.read_to_string(&mut buff).unwrap();
more(&buff, &mut stdout, next_file.copied(), silent)?;
buff.clear();
}
reset_term(&mut stdout);
} else if !std::io::stdin().is_terminal() {
stdin().read_to_string(&mut buff).unwrap();
let mut stdout = setup_term();
more(&buff, &mut stdout, None, silent)?;
reset_term(&mut stdout);
} else {
return Err(UUsageError::new(1, "bad usage"));
}
Ok(())
}
pub fn uu_app() -> Command {
Command::new(uucore::util_name())
.about(ABOUT)
.override_usage(format_usage(USAGE))
.version(crate_version!())
.infer_long_args(true)
.arg(
Arg::new(options::SILENT)
.short('d')
.long(options::SILENT)
.help("Display help instead of ringing bell")
.action(ArgAction::SetTrue),
)
.arg(
Arg::new(options::FILES)
.required(false)
.action(ArgAction::Append)
.help("Path to the files to be read")
.value_hint(clap::ValueHint::FilePath),
)
}
#[cfg(not(target_os = "fuchsia"))]
fn setup_term() -> std::io::Stdout {
let stdout = stdout();
terminal::enable_raw_mode().unwrap();
stdout
}
#[cfg(target_os = "fuchsia")]
#[inline(always)]
fn setup_term() -> usize {
0
}
#[cfg(not(target_os = "fuchsia"))]
fn reset_term(stdout: &mut std::io::Stdout) {
terminal::disable_raw_mode().unwrap();
queue!(stdout, terminal::Clear(terminal::ClearType::CurrentLine)).unwrap();
print!("\r");
stdout.flush().unwrap();
}
#[cfg(target_os = "fuchsia")]
#[inline(always)]
fn reset_term(_: &mut usize) {}
fn more(buff: &str, stdout: &mut Stdout, next_file: Option<&str>, silent: bool) -> UResult<()> {
let (cols, rows) = terminal::size().unwrap();
let lines = break_buff(buff, usize::from(cols));
let mut pager = Pager::new(rows, lines, next_file, silent);
pager.draw(stdout, None);
if pager.should_close() {
return Ok(());
}
loop {
let mut wrong_key = None;
if event::poll(Duration::from_millis(10)).unwrap() {
match event::read().unwrap() {
Event::Key(KeyEvent {
kind: KeyEventKind::Release,
..
}) => continue,
Event::Key(KeyEvent {
code: KeyCode::Char('q'),
modifiers: KeyModifiers::NONE,
kind: KeyEventKind::Press,
..
})
| Event::Key(KeyEvent {
code: KeyCode::Char('c'),
modifiers: KeyModifiers::CONTROL,
kind: KeyEventKind::Press,
..
}) => {
reset_term(stdout);
std::process::exit(0);
}
Event::Key(KeyEvent {
code: KeyCode::Down,
modifiers: KeyModifiers::NONE,
..
})
| Event::Key(KeyEvent {
code: KeyCode::Char(' '),
modifiers: KeyModifiers::NONE,
..
}) => {
if pager.should_close() {
return Ok(());
} else {
pager.page_down();
}
}
Event::Key(KeyEvent {
code: KeyCode::Up,
modifiers: KeyModifiers::NONE,
..
}) => {
pager.page_up();
}
Event::Key(KeyEvent {
code: KeyCode::Char('j'),
modifiers: KeyModifiers::NONE,
..
}) => {
if pager.should_close() {
return Ok(());
} else {
pager.next_line();
}
}
Event::Key(KeyEvent {
code: KeyCode::Char('k'),
modifiers: KeyModifiers::NONE,
..
}) => {
pager.prev_line();
}
Event::Resize(col, row) => {
pager.page_resize(col, row);
}
Event::Key(KeyEvent {
code: KeyCode::Char(k),
..
}) => wrong_key = Some(k),
_ => continue,
}
pager.draw(stdout, wrong_key);
}
}
}
struct Pager<'a> {
upper_mark: usize,
content_rows: u16,
lines: Vec<String>,
next_file: Option<&'a str>,
line_count: usize,
silent: bool,
}
impl<'a> Pager<'a> {
fn new(rows: u16, lines: Vec<String>, next_file: Option<&'a str>, silent: bool) -> Self {
let line_count = lines.len();
Self {
upper_mark: 0,
content_rows: rows.saturating_sub(1),
lines,
next_file,
line_count,
silent,
}
}
fn should_close(&mut self) -> bool {
self.upper_mark
.saturating_add(self.content_rows.into())
.ge(&self.line_count)
}
fn page_down(&mut self) {
if self
.upper_mark
.saturating_add(self.content_rows as usize * 2)
.ge(&self.line_count)
{
self.upper_mark = self.line_count - self.content_rows as usize;
return;
}
self.upper_mark = self.upper_mark.saturating_add(self.content_rows.into());
}
fn page_up(&mut self) {
self.upper_mark = self.upper_mark.saturating_sub(self.content_rows.into());
}
fn next_line(&mut self) {
self.upper_mark = self.upper_mark.saturating_add(1);
}
fn prev_line(&mut self) {
self.upper_mark = self.upper_mark.saturating_sub(1);
}
fn page_resize(&mut self, _: u16, row: u16) {
self.content_rows = row.saturating_sub(1);
}
fn draw(&self, stdout: &mut std::io::Stdout, wrong_key: Option<char>) {
let lower_mark = self
.line_count
.min(self.upper_mark.saturating_add(self.content_rows.into()));
self.draw_lines(stdout);
self.draw_prompt(stdout, lower_mark, wrong_key);
stdout.flush().unwrap();
}
fn draw_lines(&self, stdout: &mut std::io::Stdout) {
execute!(stdout, terminal::Clear(terminal::ClearType::CurrentLine)).unwrap();
let displayed_lines = self
.lines
.iter()
.skip(self.upper_mark)
.take(self.content_rows.into());
for line in displayed_lines {
stdout.write_all(format!("\r{line}\n").as_bytes()).unwrap();
}
}
fn draw_prompt(&self, stdout: &mut Stdout, lower_mark: usize, wrong_key: Option<char>) {
let status_inner = if lower_mark == self.line_count {
format!("Next file: {}", self.next_file.unwrap_or_default())
} else {
format!(
"{}%",
(lower_mark as f64 / self.line_count as f64 * 100.0).round() as u16
)
};
let status = format!("--More--({status_inner})");
let banner = match (self.silent, wrong_key) {
(true, Some(key)) => format!(
"{status} [Unknown key: '{key}'. Press 'h' for instructions. (unimplemented)]"
),
(true, None) => format!("{status}[Press space to continue, 'q' to quit.]"),
(false, Some(_)) => format!("{status}{BELL}"),
(false, None) => status,
};
write!(
stdout,
"\r{}{}{}",
Attribute::Reverse,
banner,
Attribute::Reset
)
.unwrap();
}
}
fn break_buff(buff: &str, cols: usize) -> Vec<String> {
let mut lines = Vec::with_capacity(buff.lines().count());
for l in buff.lines() {
lines.append(&mut break_line(l, cols));
}
lines
}
fn break_line(line: &str, cols: usize) -> Vec<String> {
let width = UnicodeWidthStr::width(line);
let mut lines = Vec::new();
if width < cols {
lines.push(line.to_string());
return lines;
}
let gr_idx = UnicodeSegmentation::grapheme_indices(line, true);
let mut last_index = 0;
let mut total_width = 0;
for (index, grapheme) in gr_idx {
let width = UnicodeWidthStr::width(grapheme);
total_width += width;
if total_width > cols {
lines.push(line[last_index..index].to_string());
last_index = index;
total_width = width;
}
}
if last_index != line.len() {
lines.push(line[last_index..].to_string());
}
lines
}
#[cfg(test)]
mod tests {
use super::break_line;
use unicode_width::UnicodeWidthStr;
#[test]
fn test_break_lines_long() {
let mut test_string = String::with_capacity(100);
for _ in 0..200 {
test_string.push('#');
}
let lines = break_line(&test_string, 80);
let widths: Vec<usize> = lines
.iter()
.map(|s| UnicodeWidthStr::width(&s[..]))
.collect();
assert_eq!((80, 80, 40), (widths[0], widths[1], widths[2]));
}
#[test]
fn test_break_lines_short() {
let mut test_string = String::with_capacity(100);
for _ in 0..20 {
test_string.push('#');
}
let lines = break_line(&test_string, 80);
assert_eq!(20, lines[0].len());
}
#[test]
fn test_break_line_zwj() {
let mut test_string = String::with_capacity(1100);
for _ in 0..20 {
test_string.push_str("👩🏻🔬");
}
let lines = break_line(&test_string, 80);
let widths: Vec<usize> = lines
.iter()
.map(|s| UnicodeWidthStr::width(&s[..]))
.collect();
assert_eq!((78, 42), (widths[0], widths[1]));
}
}