-
Notifications
You must be signed in to change notification settings - Fork 25
/
Copy pathmore.rs
2982 lines (2830 loc) · 105 KB
/
more.rs
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
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//
// Copyright (c) 2024 Jeff Garzik
//
// This file is part of the posixutils-rs project covered under
// the MIT License. For the full license text, please see the LICENSE
// file in the root directory of this project.
// SPDX-License-Identifier: MIT
//
use clap::Parser;
use gettextrs::{bind_textdomain_codeset, gettext, setlocale, textdomain, LocaleCategory};
use libc::{
getegid, getgid, getuid, regcomp, regex_t, regexec, setgid, setuid, REG_ICASE, REG_NOMATCH,
};
use std::collections::HashMap;
use std::ffi::CString;
use std::fs::File;
use std::io::{stdout, BufRead, BufReader, Cursor, Read, Seek, SeekFrom, Write};
use std::ops::{Not, Range};
use std::os::fd::AsRawFd;
use std::path::PathBuf;
use std::process::{exit, ExitStatus};
use std::ptr;
use std::str::FromStr;
use std::sync::mpsc::{channel, Receiver, TryRecvError};
use std::sync::Mutex;
use std::time::Duration;
use termion::{clear::*, cursor::*, event::*, input::*, raw::*, screen::*, style::*, *};
const LINES_PER_PAGE: u16 = 24;
const NUM_COLUMNS: u16 = 80;
const DEFAULT_EDITOR: &str = "vi";
const CONVERT_STRING_BUF_SIZE: usize = 64;
const PROJECT_NAME: &str = "posixutils-rs";
/// Last acceptable pressed mouse button
static LAST_MOUSE_BUTTON: Mutex<Option<MouseButton>> = Mutex::new(None);
/// Inform terminal input handler thread that program is closing
static NEED_QUIT: Mutex<bool> = Mutex::new(false);
/// more - display files on a page-by-page basis.
#[derive(Parser)]
#[command(version, about = gettext("more - display files on a page-by-page basis"))]
struct Args {
/// Do not scroll, display text and clean line ends
#[arg(
short = 'c',
long = "print-over",
help = gettext("Do not scroll, display text and clean line ends")
)]
print_over: bool,
/// Exit on end-of-file
#[arg(
short = 'e',
long = "exit-on-eof",
help = gettext("Exit on end-of-file")
)]
exit_on_eof: bool,
/// Perform pattern matching in searches without regard to case
#[arg(
short = 'i',
long = "ignore-case",
help = gettext("Perform pattern matching in searches without regard to case")
)]
case_insensitive: bool,
/// Execute the more command(s) in the command arguments in the order specified
#[arg(
short = 'p',
long = "execute",
help = gettext("Execute the more command(s) in the command arguments in the order specified")
)]
commands: Option<String>,
/// Squeeze multiple blank lines into one
#[arg(
short = 's',
long = "squeeze",
help = gettext("Squeeze multiple blank lines into one")
)]
squeeze: bool,
/// Write the screenful of the file containing the tag named by the tagstring argument
#[arg(
short = 't',
long = "tag",
help = gettext("Write the screenful of the file containing the tag named by the tagstring argument")
)]
tag: Option<String>,
/// Suppress underlining and bold
#[arg(
short = 'u',
long = "plain",
help = gettext("Suppress underlining and bold")
)]
plain: bool,
/// The number of lines per screenful
#[arg(
short = 'n',
long = "lines",
help = gettext("The number of lines per screenful")
)]
lines: Option<u16>,
/// Enable interactive session test
#[arg(
short = 'd',
long = "test",
help = gettext("Enable interactive session test")
)]
test: bool,
/// A pathnames of an input files
#[arg(
name = "FILES",
help = gettext("A pathnames of input files")
)]
input_files: Vec<String>,
}
/// Commands that can be executed in interactive mode after appropriate patterns input
#[derive(Debug, Clone, PartialOrd, Ord, PartialEq, Eq)]
enum Command {
/// If [`parse`] can`t recognise patterns in cmd str then it returns this
Unknown,
/// Write a summary of implementation-defined commands
Help,
/// Scroll forward count lines, with one default screenful
ScrollForwardOneScreenful(Option<usize>),
/// Scroll backward count lines, with one default screenful
ScrollBackwardOneScreenful(Option<usize>),
/// Scroll forward count lines. Default is one screenful
ScrollForwardOneLine {
count: Option<usize>,
/// Selects a default count relative to an existing <space> input
is_space: bool,
},
/// Scroll backward count lines. The entire count lines shall be written
ScrollBackwardOneLine(Option<usize>),
/// Scroll forward count lines. Default is one half of the screen size
ScrollForwardOneHalfScreenful(Option<usize>),
/// Display beginning lines count screenful after current screen last line
SkipForwardOneLine(Option<usize>),
/// Scroll backward count lines. Default is one half of the screen size
ScrollBackwardOneHalfScreenful(Option<usize>),
/// Display the screenful beginning with line count
GoToBeginningOfFile(Option<usize>),
/// If count is specified display beginning lines or last of file screenful
GoToEOF(Option<usize>),
/// Refresh the screen
RefreshScreen,
/// Refresh the screen, discarding any buffered input
DiscardAndRefresh,
/// Mark the current position with the letter - one lowercase letter
MarkPosition(char),
/// Return to the position that was marked, making it as current position
ReturnMark(char),
/// Return to the position from which the last large movement command was executed
ReturnPreviousPosition,
/// Display the screenful beginning with the countth line containing the pattern
SearchForwardPattern {
count: Option<usize>,
/// Inverse pattern
is_not: bool,
pattern: String,
},
/// Display the screenful beginning with the countth previous line containing the pattern
SearchBackwardPattern {
count: Option<usize>,
/// Inverse pattern
is_not: bool,
pattern: String,
},
/// Repeat the previous search for countth line containing the last pattern
RepeatSearch(Option<usize>),
/// Repeat the previous search oppositely for the countth line containing the last pattern
RepeatSearchReverse(Option<usize>),
/// Examine a new file. Default [filename] (current file) shall be re-examined
ExamineNewFile(String),
/// Examine the next file. If count is specified, the countth next file shall be examined
ExamineNextFile(Option<usize>),
/// Examine the previous file. If count is specified, the countth next file shall be examined
ExaminePreviousFile(Option<usize>),
/// If tagstring isn't the current file, examine the file, as if :e command was executed.
/// Display beginning screenful with the tag
GoToTag(String),
/// Invoke an editor to edit the current file being examined. Editor shall be taken
/// from EDITOR, or shall default to vi.
InvokeEditor,
/// Write a message for which the information references the first byte of the line
/// after the last line of the file on the screen
DisplayPosition,
/// Exit more
Quit,
}
/// All more errors
#[derive(Debug, Clone, thiserror::Error)]
enum MoreError {
/// Errors raised in [`SeekPositions`] level
#[error("{}", .0)]
SeekPositions(#[from] SeekPositionsError),
/// Errors raised in [`SourceContext`] level
#[error("{}", .0)]
SourceContext(#[from] SourceContextError),
/// Attempt set [`String`] on [`Terminal`] that goes beyond
#[error("Set chars outside screen is forbidden")]
SetOutside,
/// Attempt set [`Prompt`] on [`Terminal`] longer that [`Terminal`] width
#[error("Input too long")]
InputTooLong,
/// Read [`std::io::Stdin`] is failed
#[error("Couldn't read from stdin")]
InputRead,
/// Calling [`std::process::Command`] for editor is failed
#[error("Editor process failed")]
EditorFailed,
/// Calling [`std::process::Command`] for ctags is failed
#[error("Couldn't call ctags")]
CTagsFailed,
/// Open, read [`File`] is failed
#[error("Couldn't read file \'{}\'", .0)]
FileRead(String),
/// [`Output`], [`Regex`] parse errors
#[error("Couldn't parse {}", .0)]
StringParse(String),
/// Attempt execute [`Command::UnknownCommand`]
#[error("Couldn't execute unknown command")]
UnknownCommand,
/// [`Terminal`] init is failed
#[error("Terminal isn't initialized")]
TerminalInit,
/// [`Terminal`] size is too small
#[error("Can't execute commands for too small terminal")]
TerminalOutput,
/// [`Terminal`] size read is failed
#[error("Couldn't get current terminal size")]
SizeRead,
/// Attempt update [`SourceContext::current_screen`] without [`Terminal`]
#[error("Terminal operations is forbidden")]
MissingTerminal,
/// Search has no results
#[error("Couldn't find \'{}\' pattern", .0)]
PatternNotFound(String),
}
/// All [`SeekPositions`] errors
#[derive(Debug, Clone, thiserror::Error)]
enum SeekPositionsError {
/// [`Output`], [`Regex`] parse errors
#[error("Couldn't parse {}", .0)]
StringParse(String),
/// Attempt seek buffer out of bounds
#[error("Couldn't seek to {} position", .0)]
OutOfRange(u64),
/// Source open, read errors
#[error("Couldn't read {}", .0)]
FileRead(String),
}
/// All [`SourceContext`] errors
#[derive(Debug, Clone, thiserror::Error)]
enum SourceContextError {
/// Attempt execute previous search when it is [`None`]
#[error("No previous regular expression")]
MissingLastSearch,
/// Attempt move current position to mark when it isn`t set
#[error("Couldn't find mark for \'{}", .0)]
MissingMark(char),
}
/// Sets display style for every [`Screen`] char on [`Terminal`]
#[derive(Debug, Clone, Copy, PartialOrd, Ord, PartialEq, Eq)]
enum StyleType {
/// Default style
None,
/// Underlined text
Underscore,
/// Black text, white background
Negative,
}
/// Buffer that stores content that must be displayed on [`Terminal`]
#[derive(Debug, Clone)]
struct Screen(Vec<Vec<(char, StyleType)>>);
impl Screen {
/// Creates new [`Screen`]
fn new(size: (usize, usize)) -> Self {
let row = [(' ', StyleType::None)];
let row = row.repeat(size.1);
let mut matrix = vec![row.clone()];
let lines_count = size.0.max(2) - 1;
for _ in 0..lines_count {
matrix.push(row.clone())
}
Self(matrix)
}
/// Sets string range on [`Screen`]
fn set_str(
&mut self,
position: (usize, usize),
string: String,
style: StyleType,
) -> Result<(), MoreError> {
if position.0 >= self.0.len()
|| (self.0[0].len() as isize - position.1 as isize) < string.len() as isize
{
return Err(MoreError::SetOutside);
}
let mut chars = string.chars();
self.0[position.0]
.iter_mut()
.skip(position.1)
.for_each(|(c, st)| {
if let Some(ch) = chars.next() {
*c = ch;
*st = style;
}
});
Ok(())
}
/// Set string ([`Vec<(char, StyleType)>`]) range on [`Screen`]
fn set_raw(
&mut self,
position: (usize, usize),
string: Vec<(char, StyleType)>,
) -> Result<(), MoreError> {
if position.0 > self.0.len()
|| (self.0[0].len() as isize - position.1 as isize) < string.len() as isize
{
return Err(MoreError::SetOutside);
}
let mut chars = string.iter();
self.0[position.0]
.iter_mut()
.skip(position.1)
.for_each(|c| {
if let Some(ch) = chars.next() {
*c = *ch;
}
});
Ok(())
}
/// Fill [`Screen`] with (' ', [StyleType::None])
fn clear(&mut self) {
self.0.iter_mut().for_each(|line| {
line.fill((' ', StyleType::None));
});
}
}
/// Defines search, scroll direction
#[derive(Debug, Clone, PartialOrd, Ord, PartialEq, Eq)]
enum Direction {
/// Direction to bigger position
Forward,
/// Direction to smaller position
Backward,
}
impl Not for Direction {
type Output = Direction;
fn not(self) -> Self::Output {
match self {
Direction::Forward => Direction::Backward,
Direction::Backward => Direction::Forward,
}
}
}
/// Defines set of methods that can be used for any [`Source`]'s.
/// Used for storage and processing of any [`Source`] type in
/// [`SeekPositions`]
trait SeekRead: Seek + Read {}
impl<T: Seek + Read> SeekRead for Box<T> {}
impl SeekRead for File {}
impl SeekRead for Cursor<String> {}
/// Universal cursor that can read lines, seek
/// over any [`SeekRead`] source
struct SeekPositions {
/// Buffer with previous seek positions of all lines beginnings
positions: Vec<u64>,
/// Terminal width for spliting long lines. If [`None`], lines not splited by length
line_len: Option<usize>,
/// Stream size
stream_len: u64,
/// Count of all lines in source
lines_count: usize,
/// Source that handles info for creating [`SeekRead`] buffer
source: Source,
/// Buffer for which is seek and read is applied
buffer: Box<dyn SeekRead>,
/// Shrink all sequences of <newline>'s to one <newline>
squeeze_lines: bool,
/// Suppress underlining and bold
plain: bool,
/// Iteration over [`SeekPositions`] buffer has reached end
is_ended: bool,
/// Char positions for stylized text
style_positions: Vec<(Range<usize>, StyleType)>,
}
impl SeekPositions {
/// Creates new [`SeekPositions`]
fn new(
source: Source,
line_len: Option<usize>,
squeeze_lines: bool,
plain: bool,
) -> Result<Self, MoreError> {
let buffer: Box<dyn SeekRead> = match source.clone() {
Source::File(path) => {
let Ok(file) = File::open(path.clone()) else {
return Err(MoreError::SeekPositions(SeekPositionsError::FileRead(
path.to_str().unwrap_or("<file>").to_string(),
)));
};
let buffer: Box<dyn SeekRead> = Box::new(file);
buffer
}
Source::Buffer(buffer) => {
let buffer: Box<dyn SeekRead> = Box::new(buffer);
buffer
}
};
let mut seek_pos = Self {
positions: vec![],
line_len,
stream_len: 0,
lines_count: 0,
source: source.clone(),
buffer,
squeeze_lines,
plain,
is_ended: false,
style_positions: vec![],
};
(seek_pos.lines_count, seek_pos.stream_len) = seek_pos.lines_count_and_stream_len();
if seek_pos.lines_count as u64 > seek_pos.stream_len {
return Err(MoreError::FileRead(source.clone().name()));
}
Ok(seek_pos)
}
/// Counts all buffer lines and set [`SeekPositions`] to previous state
fn lines_count_and_stream_len(&mut self) -> (usize, u64) {
let current_line = self.current_line();
let _ = self.buffer.rewind();
let mut count = 0;
while self.next().is_some() {
count += 1;
}
{
let mut reader = BufReader::new(&mut self.buffer);
let mut buf = vec![];
let _ = reader.read_to_end(&mut buf);
if !buf.is_empty() {
count += 1;
}
}
let stream_position = self.buffer.stream_position().unwrap_or(0);
let _ = self.buffer.rewind();
let mut i = 0;
self.positions = vec![0];
while i < current_line {
if self.next().is_none() {
break;
};
i += 1;
}
(count, stream_position)
}
/// Read line from current seek position with removing styling control chars
fn read_line(&mut self) -> Result<String, MoreError> {
let current_seek = self.current();
let mut line = if let Some(next_seek) = self.next() {
self.next_back();
let mut line_buf = vec![b' '; (next_seek - current_seek) as usize];
self.buffer.read_exact(&mut line_buf).map_err(|_| {
MoreError::SeekPositions(SeekPositionsError::FileRead(self.source.name()))
})?;
String::from_utf8(Vec::from_iter(line_buf)).map_err(|_| {
MoreError::SeekPositions(SeekPositionsError::StringParse(self.source.name()))
})?
} else {
let mut line_buf = vec![];
let _ = self.buffer.read_to_end(&mut line_buf);
String::from_utf8(Vec::from_iter(line_buf)).unwrap_or_default()
};
if line.is_empty() {
return Ok(String::new());
}
for (rng, _) in self.style_positions.iter().rev() {
if rng.end > line.len() {
continue;
};
let new = line[rng.clone()]
.chars()
.filter(|ch| *ch != '\x08' && *ch != '_' && *ch != '\r')
.collect::<String>();
if !new.is_empty() {
let new = new[..1].to_string();
if line.len() >= rng.end {
line.replace_range(rng.clone(), &new);
}
}
}
Ok(line)
}
/// Returns current seek position
fn current(&self) -> u64 {
*self.positions.last().unwrap_or(&0)
}
/// Returns current line index
fn current_line(&self) -> usize {
self.positions.len()
}
/// Sets current line to [`position`]
fn set_current(&mut self, position: usize) {
self.is_ended = false;
while self.current_line() != position {
if self.current_line() < position && self.next().is_none() {
self.is_ended = true;
break;
} else if self.current_line() > position && self.next_back().is_none() {
break;
}
}
}
/// Returns full lines count fo current source
fn len_lines(&self) -> usize {
self.lines_count
}
/// Returns stream len fo current source
fn _len(&self) -> u64 {
self.stream_len
}
/// Seek to certain [`position`] over current source
fn seek(&mut self, position: u64) -> Result<(), MoreError> {
let err = Err(MoreError::SeekPositions(SeekPositionsError::OutOfRange(
position,
)));
if position > self.stream_len {
return err;
}
loop {
if self.next() > Some(position) && Some(position) > self.next_back() {
break;
} else if self.current() < position {
if self.next().is_none() {
return err;
}
} else if self.current() > position {
if self.next_back().is_none() {
return err;
}
} else {
break;
}
}
Ok(())
}
/// Returns nth position of choosen [`char`] if it exists
pub fn find_n_line(&mut self, n: usize) -> Option<u64> {
let last_seek = self.current();
let mut n_char_seek = None;
let _ = self.buffer.rewind();
let mut i = 0;
let mut seek_pos = 0;
{
let reader = BufReader::new(&mut self.buffer).lines();
for line in reader {
if let Ok(line) = line {
seek_pos += line.as_bytes().len();
}
i += 1;
if i >= n {
n_char_seek = Some(seek_pos as u64);
break;
}
}
}
let _ = self.seek(last_seek);
n_char_seek
}
/// Search 'EOF', '\n', if line length bigger than [`Self::line_len`],
/// then return next line len as [`Self::line_len`]. Skip next line
/// after that [`Self::buffer`] seek position will be at last char
/// position of next line. When this function search line end, it
/// skips styled text control bytes and add range for replacing this
/// bytes with text to [`Self::style_positions`]. [`Self::style_positions`]
/// used in [`Self::read_line`] for formating styled text.
fn find_next_line_len_with_skip(&mut self) -> usize {
let mut style_positions = vec![];
let mut buffer_str = String::new();
self.is_ended = false;
let mut line_len = 0;
let mut need_add_chars = 0;
let max_line_len = self.line_len.unwrap_or(usize::MAX) as u64;
let mut n_count = 0;
let mut r_count = 0;
{
let reader = BufReader::new(&mut self.buffer);
let mut bytes = reader.bytes();
let mut buf = Vec::with_capacity(CONVERT_STRING_BUF_SIZE);
loop {
let Some(Ok(byte)) = bytes.next() else {
self.is_ended = true;
break;
};
match byte {
b'\r' => {
line_len += 1;
buffer_str.push(byte as char);
buf.push(byte);
r_count += 1;
continue;
}
b'\n' => {
line_len += 1;
if self.squeeze_lines {
n_count += 1;
loop {
let Some(Ok(byte)) = bytes.next() else {
self.is_ended = true;
break;
};
match byte {
b'\n' => {
line_len += 1;
n_count += 1;
buffer_str.push(byte as char);
}
b'\r' => {
line_len += 1;
r_count += 1;
buffer_str.push(byte as char);
}
_ => break,
}
}
let diff = 1 + r_count.min(1);
if n_count > 1 && line_len > diff {
line_len -= diff;
for _ in 0..diff {
buffer_str.pop();
}
}
}
break;
}
byte if byte.is_ascii_control() && byte != b'\x08' => {
line_len += 1;
break;
}
_ => {
if !self.plain {
if let Some(mut new_style_positions) = continious_styled_parse(
&mut buffer_str,
&mut need_add_chars,
line_len,
) {
style_positions.append(&mut new_style_positions);
} else {
buffer_str.push(byte as char);
line_len += 1;
continue;
}
}
buffer_str.push(byte as char);
line_len += 1;
}
}
buf.push(byte);
if buf.len() >= CONVERT_STRING_BUF_SIZE {
if let Err(err) = std::str::from_utf8(&buf) {
buf = buf[err.valid_up_to()..].to_vec();
} else {
buf.clear();
}
}
if line_len as u64 >= max_line_len + need_add_chars {
if line_len > buffer_str.len() {
line_len -= buffer_str.len() + 1;
}
if let Err(err) = std::str::from_utf8(&buf) {
line_len -= buf.len() - err.valid_up_to();
}
break;
}
}
}
if !self.plain {
let mut new_style_positions = last_styled_parse(
&mut buffer_str,
&mut line_len,
max_line_len as usize,
self.is_ended,
);
if buffer_str.len() < 3 && !self.is_ended {
style_positions.pop();
}
style_positions.append(&mut new_style_positions);
self.style_positions = style_positions;
}
line_len
}
}
/// Parse last chars before current position in [`SeekPositions::buffer`]
/// for finding styled control sequences during
/// [`SeekPositions::find_next_line_len_with_skip`] loop
///
/// # Arguments
///
/// * `buffer_str` - last chars in [SeekPositions::buffer] stream that can
/// contain styling sequences.
/// * `need_add_chars` - text styling control char count. This count will be
/// used for checking if line length is bigger than max line length.
/// * `line_len` - next line length at that moment in
/// [`SeekPositions::find_next_line_len_with_skip`] loop.
fn continious_styled_parse(
buffer_str: &mut String,
need_add_chars: &mut u64,
line_len: usize,
) -> Option<Vec<(Range<usize>, StyleType)>> {
let check_styled = |(i, ch, first): (usize, &char, char)| {
(i % 2 == 0 && *ch == first) || (i % 2 == 1 && *ch == '\x08')
};
let mut style_positions = vec![];
let buffer = buffer_str.chars().collect::<Vec<char>>();
if buffer.len() == 3 && (buffer.starts_with(&['_', '\x08']) || buffer.ends_with(&['\x08', '_']))
{
style_positions.push(((line_len - buffer.len())..line_len, StyleType::Underscore));
*need_add_chars += 2;
buffer_str.clear();
} else if buffer.len() < 3 {
let is_styled = buffer
.iter()
.enumerate()
.map(|(i, ch)| (i, ch, buffer[0]))
.all(check_styled);
if is_styled {
return None;
} else {
buffer_str.remove(0);
}
} else if buffer.len() >= 3 {
let is_styled = buffer
.iter()
.enumerate()
.map(|(i, ch)| (i, ch, buffer[0]))
.all(check_styled);
if !is_styled {
style_positions.push((
(line_len - buffer.len())..(line_len - 1),
StyleType::Negative,
));
*need_add_chars += ((buffer.len() as f32) / 2.0).floor() as u64;
} else {
return None;
}
let last = buffer_str.chars().last();
buffer_str.clear();
if let Some(last) = last {
buffer_str.push(last);
}
}
Some(style_positions)
}
/// Parse last chars before current position in [`SeekPositions::buffer`]
/// for finding styled control sequences after
/// [`SeekPositions::find_next_line_len_with_skip`] loop
///
/// # Arguments
///
/// * `buffer_str` - last chars in [SeekPositions::buffer] stream that can
/// contain styling sequences.
/// * `line_len` - next line length at that moment in
/// [`SeekPositions::find_next_line_len_with_skip`] loop.
///
/// * `max_line_len` - line that length bigger than this value will be splited
/// * `is_ended` - indicate that [SeekPositions::buffer] stream reached `EOF`
fn last_styled_parse(
buffer_str: &mut str,
line_len: &mut usize,
max_line_len: usize,
is_ended: bool,
) -> Vec<(Range<usize>, StyleType)> {
let check_styled = |(i, ch, first): (usize, &char, char)| {
(i % 2 == 0 && *ch == first) || (i % 2 == 1 && *ch == '\x08')
};
let mut style_positions = vec![];
let l = buffer_str
.chars()
.filter(|ch| *ch == '\n' || *ch == '\r' || *ch == ' ')
.count();
let buffer = buffer_str
.chars()
.filter(|ch| *ch != '\n' && *ch != '\r' && *ch != ' ')
.collect::<Vec<char>>();
if !buffer.is_empty() && buffer.len() < 3 && max_line_len > l + 2 && *line_len >= max_line_len {
*line_len -= l + 2;
} else if buffer.len() == 3
&& (buffer.starts_with(&['_', '\x08']) || buffer.ends_with(&['\x08', '_']))
{
style_positions.push((
(*line_len - buffer.len() - l - (!is_ended as usize))
..(*line_len - (!is_ended as usize)),
StyleType::Underscore,
));
} else if buffer.len() >= 3
&& buffer
.iter()
.enumerate()
.map(|(i, ch)| (i, ch, buffer[0]))
.all(check_styled)
{
style_positions.push((
(*line_len - buffer.len() - l - (!is_ended as usize))
..(*line_len - (!is_ended as usize)),
StyleType::Negative,
));
}
style_positions
}
impl Iterator for SeekPositions {
type Item = u64;
/// Iter over [`SeekRead`] buffer lines in forward direction
fn next(&mut self) -> Option<Self::Item> {
let current_position = *self.positions.last().unwrap_or(&0);
if self.buffer.seek(SeekFrom::Start(current_position)).is_err() {
return None;
}
let line_len = self.find_next_line_len_with_skip();
let Ok(stream_position) = self.buffer.stream_position() else {
return None;
};
let next_position = current_position + line_len as u64;
if self.is_ended || next_position >= stream_position {
let _ = self.buffer.seek(SeekFrom::Start(current_position));
None
} else {
if self.buffer.seek(SeekFrom::Start(next_position)).is_err() {
return None;
};
self.positions.push(next_position);
Some(next_position)
}
}
}
impl DoubleEndedIterator for SeekPositions {
/// Iter over [`SeekRead`] buffer lines in backward direction
fn next_back(&mut self) -> Option<Self::Item> {
let _ = self.positions.pop();
let _ = self
.buffer
.seek(SeekFrom::Start(*self.positions.last().unwrap_or(&0)));
self.positions.last().cloned()
}
}
/// Inforamtion about [`SeekRead`] source for [`SeekPositions`]
#[derive(Debug, Clone)]
enum Source {
/// Path to file that can be used for seek and read with [`SeekPositions`]
File(PathBuf),
/// [`Cursor`] on [`String`] that can be used for seek and read with [`SeekPositions`]
Buffer(Cursor<String>),
}
impl Source {
/// Returns [`String`] that identify [`Source`]
fn name(&mut self) -> String {
match self {
Source::File(path) => path.to_str().unwrap_or("<file>").to_owned(),
Source::Buffer(cursor) => {
let current_pos = cursor.stream_position().unwrap_or(0);
let _ = cursor.seek(SeekFrom::Start(0));
let mut line = String::new();
if BufRead::read_line(cursor, &mut line).is_err() {
line = "<buffer>".to_owned();
}
if line.len() > 15 {
if let Some(sub) = line.get(..15) {
line = sub.to_owned() + "...";
}
}
let _ = cursor.seek(SeekFrom::Start(current_pos));
line
}
}
}
}
/// Context of more current source, last search, flags etc
struct SourceContext {
/// Current [`Source`] for seek and read
current_source: Source,
/// Last [`Source`] that was handled previously
last_source: Source,
/// [`SeekPositions`] used for seek and read over [`Source`]
seek_positions: SeekPositions,
/// Current [`Source`] header lines count
header_lines_count: Option<usize>,
/// Used by more [`Terminal`] size
terminal_size: Option<(usize, usize)>,
/// Last writen screen from previous [`Source`]
previous_source_screen: Option<Screen>,
/// Current [`Screen`]
screen: Option<Screen>,
/// Position of last line
last_line: usize,
/// Current search pattern
current_pattern: String,
/// Last search settings
last_search: Option<(regex_t, bool, Direction)>,
/// Storage for marks that were set durring current [`Source`] processing
marked_positions: HashMap<char, usize>,
/// Flag that [`true`] if input files count is more that 1
is_many_files: bool,
/// Shrink all sequences of <newline>'s to one <newline>
squeeze_lines: bool,
/// Suppress underlining and bold
plain: bool,
/// Is source reached end
is_ended_file: bool,
}
impl SourceContext {
/// New [`SourceContext`]
pub fn new(
source: Source,
terminal_size: Option<(usize, usize)>,
is_many_files: bool,
squeeze_lines: bool,
plain: bool,
) -> Result<Self, MoreError> {
Ok(Self {
current_source: source.clone(),
last_source: source.clone(),
seek_positions: SeekPositions::new(
source.clone(),
terminal_size.map(|size| size.1),
squeeze_lines,
plain,
)?,
header_lines_count: if let Source::File(path) = source {
let header = format_file_header(path, terminal_size.map(|(_, c)| c))?;
Some(header.len())
} else {
None
},
terminal_size,
previous_source_screen: None,
screen: terminal_size.map(|t| Screen::new((t.0 - 1, t.1))),
last_line: 0,
current_pattern: "".to_string(),
last_search: None,
marked_positions: HashMap::new(),
is_many_files,
squeeze_lines,
plain,
is_ended_file: false,
})
}
/// Returns current [`Screen`]
pub fn screen(&self) -> Option<Screen> {
self.screen.clone()
}