forked from PaulJuliusMartinez/jless
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlineprinter.rs
1984 lines (1642 loc) · 65.5 KB
/
lineprinter.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
use std::collections::hash_map::Entry;
use std::fmt;
use std::fmt::Write;
use std::iter::Peekable;
use std::ops::Range;
use regex::Regex;
use crate::flatjson::{FlatJson, OptionIndex, Row, Value};
use crate::highlighting;
use crate::search::MatchRangeIter;
use crate::terminal;
use crate::terminal::{Color, Style, Terminal};
use crate::truncatedstrview::TruncatedStrView;
use crate::viewer::Mode;
// This module is responsible for printing single lines of JSON to
// the screen, complete with syntax highlighting and highlighting
// of search matches.
//
// A single line is one of the following:
// - The start of a non-empty object or array
// - The end of a non-empty object or array
// - A key/value pair of an object
// - An element of an array
// - Or a top-level primitive
//
// Objects and containers can be collapsed, and at certain times
// we show previews next to containers.
//
// The viewer can be in one of two modes: Line mode, or Data mode.
// In Line mode, the goal is that the text on the screen is mostly
// valid JSON. In Data mode, we try to present a "cleaner" version
// of the data, by for example, not showing quotes around object keys
// or trailing commas.
//
// Here's the main set of differences:
// Line Mode Data Mode
// Quotes around object keys: Yes Only when not a valid JS identifier
// Trailing commas: Yes No
// Object and Array previews: Only when collapsed Always
// Array Indexes: No Yes
// Open delimiters: Yes No
// Line for closing delimiters: Yes No
//
// In addition to the above behavior that depends on the current
// viewer mode, when rendering a line we also apply syntax
// highlighting and highlight search results. The currently focused
// search result is also displayed slightly differently.
//
// Great care is taken to highlight every character that is actually
// part of a match, including quotes around keys and string values,
// and even other syntax (colons, commas, and spaces). It is
// difficult to keep track of everything as the text displayed on
// the screen doesn't exactly match the source JSON. Beware of
// off-by-one errors.
//
//
// Naturally, there may be cases where an entire line does not fit
// on the screen without wrapping. Rather than implement line
// wrapping (which seems difficult), we truncate values and show
// ellipses to indicate truncated content. When printing out multiple
// values, such as the key and value of an Object entry, the index
// and element of an array, or the many container elements in an
// object preview, we fill in the available space from left to right
// while keeping track of what still needs to be displayed so we
// can show appropriate truncation indicators.
//
// Here are some examples:
//
// key: "long text her…" |
// medium_length_key: t… |
//
// If something is totally off the screen we just show a '>':
//
// really_long_key_h…: > |
// [10…]: >|
// "d": >|
// >|
const FOCUSED_LINE: &str = "▶ ";
const NOT_FOCUSED_LINE: &str = " ";
const FOCUSED_COLLAPSED_CONTAINER: &str = "▶ ";
const FOCUSED_EXPANDED_CONTAINER: &str = "▼ ";
const COLLAPSED_CONTAINER: &str = "▷ ";
const EXPANDED_CONTAINER: &str = "▽ ";
const INDICATOR_WIDTH: isize = 2;
const NO_FOCUSED_MATCH: Range<usize> = 0..0;
lazy_static::lazy_static! {
pub static ref JS_IDENTIFIER: Regex = Regex::new("^[_$a-zA-Z][_$a-zA-Z0-9]*$").unwrap();
}
enum LabelType {
Key,
Index,
}
#[derive(Eq, PartialEq)]
enum DelimiterPair {
None,
Quote,
Square,
}
impl DelimiterPair {
fn left(&self) -> &'static str {
match self {
DelimiterPair::None => "",
DelimiterPair::Quote => "\"",
DelimiterPair::Square => "[",
}
}
fn right(&self) -> &'static str {
match self {
DelimiterPair::None => "",
DelimiterPair::Quote => "\"",
DelimiterPair::Square => "]",
}
}
fn width(&self) -> isize {
match self {
DelimiterPair::None => 0,
_ => 2,
}
}
}
// What line number should be displayed
#[derive(Copy, Clone)]
pub struct LineNumber {
pub absolute: Option<usize>,
pub relative: Option<usize>,
pub max_width: isize,
}
pub struct LinePrinter<'a, 'b> {
pub mode: Mode,
pub terminal: &'a mut dyn Terminal,
// The entire FlatJson data structure and the specific line
// we're printing out.
pub flatjson: &'a FlatJson,
pub row: &'a Row,
pub line_number: LineNumber,
// Width of the terminal and how much we should indent the line.
pub width: isize,
pub indentation: isize,
// Line-by-line formatting options
pub focused: bool,
pub focused_because_matching_container_pair: bool,
pub trailing_comma: bool,
// For highlighting
pub search_matches: Option<Peekable<MatchRangeIter<'b>>>,
pub focused_search_match: &'a Range<usize>,
// It's unfortunate that this has to be exposed publicly; it's only
// used internally to disable the special syntax highlighting for
// the current focused match in container previews.
pub emphasize_focused_search_match: bool,
// For remembering horizontal scroll positions of long lines.
pub cached_truncated_value: Option<Entry<'a, usize, TruncatedStrView>>,
}
impl<'a, 'b> LinePrinter<'a, 'b> {
pub fn print_line(&mut self) -> fmt::Result {
self.terminal.reset_style()?;
let mut available_space = self.width;
let space_used_for_line_number = self.print_line_number(available_space)?;
available_space -= space_used_for_line_number;
let expected_space_used_for_indicators = INDICATOR_WIDTH + self.indentation;
let space_used_for_indicators =
self.print_focus_and_container_indicators(available_space)?;
if space_used_for_indicators == expected_space_used_for_indicators {
available_space -= space_used_for_indicators;
let space_used_for_label = self.fill_in_label(available_space)?;
available_space -= space_used_for_label;
if self.has_label() && space_used_for_label == 0 {
self.print_truncated_indicator()?;
} else {
let space_used_for_value = self.fill_in_value(available_space)?;
if space_used_for_value == 0 {
self.print_truncated_indicator()?;
}
}
} else {
self.print_truncated_indicator()?;
}
Ok(())
}
// Absolute | Relative | Focused | Format
// ---------+----------+---------+--------
// N | N | - | Nothing
// Y | N | N | Right aligned, dimmed
// Y | N | Y | Right aligned, yellow
// N | Y | N | Right aligned, dimmed
// N | Y | Y | Right aligned, yellow
// Y | Y | N | Relative, right aligned, dimmed
// Y | Y | Y | Absolute, left aligned, yellow
fn print_line_number(&mut self, available_space: isize) -> Result<isize, fmt::Error> {
let LineNumber {
absolute,
relative,
max_width,
} = self.line_number;
// If the line number is going to fill up all the available space (or overfill it)
// then don't print the line number.
if max_width + 1 >= available_space {
return Ok(0);
}
let (n, style, right_aligned) = match (absolute, relative, self.focused) {
(None, None, _) => return Ok(0),
(Some(n), None, false) | (None, Some(n), false) | (Some(_), Some(n), false) => {
(n, &highlighting::DIMMED_STYLE, true)
}
(Some(n), None, true) | (None, Some(n), true) => {
(n, &highlighting::CURRENT_LINE_NUMBER, true)
}
(Some(n), Some(_), true) => (n, &highlighting::CURRENT_LINE_NUMBER, false),
};
self.terminal.set_style(style)?;
if right_aligned {
write!(self.terminal, "{: >1$}", n, max_width as usize)?;
} else {
write!(self.terminal, "{: <1$}", n, max_width as usize)?;
}
self.terminal.reset_style()?;
write!(self.terminal, " ")?;
Ok(max_width + 1)
}
fn print_focus_and_container_indicators(
&mut self,
mut available_space: isize,
) -> Result<isize, fmt::Error> {
let mut used_space = 0;
match self.mode {
Mode::Line => {
if available_space >= INDICATOR_WIDTH + 1 {
if self.focused {
write!(self.terminal, "{FOCUSED_LINE}")?;
} else {
write!(self.terminal, "{NOT_FOCUSED_LINE}")?;
}
used_space += INDICATOR_WIDTH;
available_space -= INDICATOR_WIDTH;
let space_available_for_indentation = self.indentation.min(available_space - 1);
used_space += space_available_for_indentation;
self.print_n_spaces(space_available_for_indentation)?;
}
}
Mode::Data => {
let space_available_for_indentation =
self.indentation.min(available_space - 1 - INDICATOR_WIDTH);
used_space += space_available_for_indentation;
self.print_n_spaces(space_available_for_indentation)?;
if space_available_for_indentation == self.indentation {
if self.row.is_primitive() {
if self.focused {
write!(self.terminal, "{FOCUSED_LINE}")?;
} else {
write!(self.terminal, "{NOT_FOCUSED_LINE}")?;
}
} else {
self.print_container_indicator()?;
}
used_space += 2;
}
}
}
Ok(used_space)
}
fn print_n_spaces(&mut self, n: isize) -> fmt::Result {
for _ in 0..n {
write!(self.terminal, " ")?;
}
Ok(())
}
fn print_container_indicator(&mut self) -> fmt::Result {
debug_assert!(self.row.is_opening_of_container());
let collapsed = self.row.is_collapsed();
let indicator = match (self.focused, collapsed) {
(true, true) => FOCUSED_COLLAPSED_CONTAINER,
(true, false) => FOCUSED_EXPANDED_CONTAINER,
(false, true) => COLLAPSED_CONTAINER,
(false, false) => EXPANDED_CONTAINER,
};
write!(self.terminal, "{indicator}")
}
pub fn fill_in_label(&mut self, mut available_space: isize) -> Result<isize, fmt::Error> {
if !self.has_label() {
return Ok(0);
}
let mut index_label_buffer = String::new();
let (label_ref, label_range, delimiter) =
self.get_label_range_and_delimiter(&mut index_label_buffer, &self.flatjson.1);
let mut used_space = 0;
let mut dummy_search_matches = None;
let (style, highlighted_style) = self.get_label_styles();
let matches_iter = if self.row.key_range.is_some() {
&mut self.search_matches
} else {
&mut dummy_search_matches
};
// Remove two characters for either "" or [].
available_space -= delimiter.width();
// Remove two characters for ": "
available_space -= 2;
// Remove one character for either ">" or a single character
// of the value.
available_space -= 1;
let truncated_view = TruncatedStrView::init_start(label_ref, available_space);
let space_used_for_label = truncated_view.used_space();
if space_used_for_label.is_none() {
return Ok(0);
}
let space_used_for_label = space_used_for_label.unwrap();
used_space += space_used_for_label;
let mut label_open_delimiter_range_start = None;
let mut label_range_start = None;
let mut label_close_delimiter_range_start = None;
let mut object_separator_range_start = None;
if let Some(range) = label_range {
label_open_delimiter_range_start = Some(range.start);
label_range_start = Some(range.start + 1);
label_close_delimiter_range_start = Some(range.end - 1);
object_separator_range_start = Some(range.end);
}
let mut matches = matches_iter.as_mut();
// Print out start of label
highlighting::highlight_matches(
self.terminal,
delimiter.left(),
label_open_delimiter_range_start,
style,
highlighted_style,
&mut matches,
self.focused_search_match,
)?;
// Print out the label itself
highlighting::highlight_truncated_str_view(
self.terminal,
label_ref,
&truncated_view,
label_range_start,
style,
highlighted_style,
&mut matches,
self.focused_search_match,
)?;
// Print out end of label
highlighting::highlight_matches(
self.terminal,
delimiter.right(),
label_close_delimiter_range_start,
style,
highlighted_style,
&mut matches,
self.focused_search_match,
)?;
// Print out separator between label and value
highlighting::highlight_matches(
self.terminal,
": ",
object_separator_range_start,
&highlighting::DEFAULT_STYLE,
&highlighting::SEARCH_MATCH_HIGHLIGHTED,
&mut matches,
self.focused_search_match,
)?;
used_space += delimiter.width();
used_space += 2;
Ok(used_space)
}
// Check if a line has a label. A line has a label if it has
// a key, or if we are in data mode and we have a parent.
fn has_label(&self) -> bool {
self.row.key_range.is_some() || (self.mode == Mode::Data && self.row.parent.is_some())
}
// Get the type of a label, either Key or Index.
fn label_type(&self) -> LabelType {
debug_assert!(self.has_label());
if self.row.key_range.is_some() {
LabelType::Key
} else {
LabelType::Index
}
}
fn get_label_range_and_delimiter<'l, 'fj: 'l>(
&self,
label: &'l mut String,
pretty_printed: &'fj str,
) -> (&'l str, Option<Range<usize>>, DelimiterPair) {
debug_assert!(self.has_label());
if let Some(key_range) = &self.row.key_range {
let key_without_delimiter = &pretty_printed[key_range.start + 1..key_range.end - 1];
let key_open_delimiter = &pretty_printed[key_range.start..key_range.start + 1];
let mut delimiter = DelimiterPair::None;
if key_open_delimiter == "[" {
delimiter = DelimiterPair::Square;
} else if self.mode == Mode::Line || !JS_IDENTIFIER.is_match(key_without_delimiter) {
delimiter = DelimiterPair::Quote;
}
(key_without_delimiter, Some(key_range.clone()), delimiter)
} else {
let parent = self.row.parent.unwrap();
debug_assert!(self.flatjson[parent].is_array());
write!(label, "{}", self.row.index_in_parent).unwrap();
(label.as_str(), None, DelimiterPair::Square)
}
}
fn get_label_styles(&self) -> (&'static Style, &'static Style) {
match self.label_type() {
LabelType::Key => {
if self.focused {
(
&highlighting::INVERTED_BOLD_BLUE_STYLE,
&highlighting::BOLD_INVERTED_STYLE,
)
} else {
(
&highlighting::BLUE_STYLE,
&highlighting::SEARCH_MATCH_HIGHLIGHTED,
)
}
}
LabelType::Index => {
let style = if self.focused {
&highlighting::BOLD_INVERTED_STYLE
} else {
&highlighting::DIMMED_STYLE
};
// No match highlighting for index labels.
(style, &highlighting::DEFAULT_STYLE)
}
}
}
fn fill_in_value(&mut self, mut available_space: isize) -> Result<isize, fmt::Error> {
// Object values are sufficiently complicated that we'll handle them
// in a separate function.
if self.row.is_container() {
return self.fill_in_container_value(available_space, self.row);
}
let mut value_ref = &self.flatjson.1[self.row.range.clone()];
let mut quoted = false;
let color = Self::color_for_value_type(&self.row.value);
// Strip quotes from strings.
if self.row.is_string() {
value_ref = &value_ref[1..value_ref.len() - 1];
quoted = true;
}
let mut used_space = 0;
if quoted {
available_space -= 2;
}
if self.trailing_comma {
available_space -= 1;
}
let truncated_view = self.initialize_value_truncated_view_or_update_cached(available_space);
let space_used_for_value = truncated_view.used_space();
if space_used_for_value.is_none() {
return Ok(0);
}
let space_used_for_value = space_used_for_value.unwrap();
used_space += space_used_for_value;
// If we are just going to show a single ellipsis, we want
// to show a '>' instead.
if truncated_view.is_completely_elided() && !quoted && !self.trailing_comma {
return Ok(0);
}
// Print out the value.
let style = Style {
fg: color,
..Style::default()
};
let delimiter = if quoted {
DelimiterPair::Quote
} else {
DelimiterPair::None
};
if quoted {
used_space += 2;
}
self.highlight_delimited_and_truncated_item(
delimiter,
value_ref,
&truncated_view,
Some(self.row.range.clone()),
(&style, &highlighting::SEARCH_MATCH_HIGHLIGHTED),
)?;
if self.trailing_comma {
used_space += 1;
self.highlight_str(
",",
Some(self.row.range.end),
(
&highlighting::DEFAULT_STYLE,
&highlighting::SEARCH_MATCH_HIGHLIGHTED,
),
)?;
}
Ok(used_space)
}
// We use TruncatedStrViews to manage truncating values when they
// are too long for the screen, and also to handle scrolling
// horizontally through those long values.
//
// The scroll state needs to be persisted across renders, so the
// ScreenWriter keeps a HashMap of TruncatedStrViews, and passes
// in an Entry for the LinePrinter to modify.
//
// (Since setting up this map is a pain for testing, it's passed
// in as an Option.)
//
// If we are rendering a line for the first time, most of the
// time we will initialize the TruncatedStrView from the start of
// the string. BUT, if we just jumped to a search result on this
// line, then we want to initialize the TruncatedStrView focused
// on the search result.
//
// If we've already rendered a line, the available space for the
// line may have updated, so, we will resize the TruncatedStrView.
fn initialize_value_truncated_view_or_update_cached(
&mut self,
available_space: isize,
) -> TruncatedStrView {
debug_assert!(self.row.is_primitive());
let mut value_ref = &self.flatjson.1[self.row.range.clone()];
let mut value_range = self.row.range.clone();
// Strip quotes from strings.
if self.row.is_string() {
value_ref = &value_ref[1..value_ref.len() - 1];
value_range.start += 1;
value_range.end -= 1;
}
self.cached_truncated_value
.take()
.map(|entry| {
*entry
.and_modify(|tsv| {
*tsv = tsv.resize(value_ref, available_space);
})
.or_insert_with(|| {
let tsv = TruncatedStrView::init_start(value_ref, available_space);
// If we're showing a line for the first time, we might
// need to focus on a search match that we just jumped to.
let no_overlap = self.focused_search_match.end <= value_range.start
|| value_range.end <= self.focused_search_match.start;
// NOTE: If the focused search match starts at the closing
// quote of a string, maybe we should use init_back so that
// you can see the end of the string and it's more explicit
// that the middle of the string isn't part of the search
// match.
if no_overlap {
return tsv;
}
let offset_focused_range = Range {
start: self
.focused_search_match
.start
.saturating_sub(value_range.start),
end: (self.focused_search_match.end - value_range.start)
.min(value_ref.len()),
};
tsv.focus(value_ref, &offset_focused_range)
})
})
.unwrap_or_else(|| TruncatedStrView::init_start(value_ref, available_space))
}
fn color_for_value_type(value: &Value) -> Color {
debug_assert!(value.is_primitive());
match value {
Value::Null => terminal::LIGHT_BLACK,
Value::Boolean => terminal::YELLOW,
Value::Number => terminal::MAGENTA,
Value::String => terminal::GREEN,
Value::EmptyObject => terminal::WHITE,
Value::EmptyArray => terminal::WHITE,
_ => unreachable!(),
}
}
// Print out an object value on a line. There are three main variables at
// play here that determine what we should print out: the viewer mode,
// whether we're at the start or end of the container, and whether the
// container is expanded or collapsed. Whether the line is focused also
// determines the style in which the line is printed, but doesn't affect
// what actually gets printed.
//
// These are the 8 cases:
//
// Mode | Start/End | State | Displayed
// -----+-----------+-----------+---------------------------
// Line | Start | Expanded | Open char
// Line | Start | Collapsed | Preview + trailing comma?
// Line | End | Expanded | Close char + trailing comma?
// Line | End | Collapsed | IMPOSSIBLE
// Data | Start | Expanded | Preview
// Data | Start | Collapsed | Preview + trailing comma?
// Data | End | Expanded | IMPOSSIBLE
// Data | End | Collapsed | IMPOSSIBLE
fn fill_in_container_value(
&mut self,
available_space: isize,
row: &Row,
) -> Result<isize, fmt::Error> {
debug_assert!(row.is_container());
let mode = self.mode;
let side = row.is_opening_of_container();
let expanded_state = row.is_expanded();
const LINE: Mode = Mode::Line;
const DATA: Mode = Mode::Data;
const OPEN: bool = true;
const CLOSE: bool = false;
const EXPANDED: bool = true;
const COLLAPSED: bool = false;
match (mode, side, expanded_state) {
(LINE, OPEN, EXPANDED) => self.fill_in_container_open_char(available_space, row),
(LINE, CLOSE, EXPANDED) => self.fill_in_container_close_char(available_space, row),
(LINE, OPEN, COLLAPSED) | (DATA, OPEN, EXPANDED) | (DATA, OPEN, COLLAPSED) => {
// Don't highlight the current focused match in the preview.
//
// When the container is expanded, it's confusing because two things are
// highlighted and you're not sure which is focused.
//
// When the container is collapsed, it's misleading because the first match
// isn't really "focused", and hitting 'n' won't jump to the next one in
// the preview (if more than one is visible).
self.emphasize_focused_search_match = false;
let result = self.fill_in_container_preview(available_space, row);
self.emphasize_focused_search_match = true;
result
}
// Impossible states
(LINE, CLOSE, COLLAPSED) => panic!("Can't focus closing of collapsed container"),
(DATA, CLOSE, _) => panic!("Can't focus closing of container in Data mode"),
}
}
fn fill_in_container_open_char(
&mut self,
available_space: isize,
row: &Row,
) -> Result<isize, fmt::Error> {
if available_space > 0 {
let style = if self.focused || self.focused_because_matching_container_pair {
&highlighting::BOLD_STYLE
} else {
&highlighting::DEFAULT_STYLE
};
self.highlight_str(
row.value.container_type().unwrap().open_str(),
Some(self.row.range.start),
(style, &highlighting::SEARCH_MATCH_HIGHLIGHTED),
)?;
Ok(1)
} else {
Ok(0)
}
}
fn fill_in_container_close_char(
&mut self,
available_space: isize,
row: &Row,
) -> Result<isize, fmt::Error> {
let needed_space = if self.trailing_comma { 2 } else { 1 };
if available_space >= needed_space {
let style = if self.focused || self.focused_because_matching_container_pair {
&highlighting::BOLD_STYLE
} else {
&highlighting::DEFAULT_STYLE
};
self.highlight_str(
row.value.container_type().unwrap().close_str(),
Some(self.row.range.start),
(style, &highlighting::SEARCH_MATCH_HIGHLIGHTED),
)?;
if self.trailing_comma {
self.highlight_str(
",",
Some(self.row.range.end),
(
&highlighting::DEFAULT_STYLE,
&highlighting::SEARCH_MATCH_HIGHLIGHTED,
),
)?;
}
Ok(needed_space)
} else {
Ok(0)
}
}
fn fill_in_container_preview(
&mut self,
mut available_space: isize,
row: &Row,
) -> Result<isize, fmt::Error> {
if self.trailing_comma {
available_space -= 1;
}
let always_quote_string_object_keys = self.mode == Mode::Line;
let is_nested = false;
let mut used_space = self.generate_container_preview(
row,
available_space,
is_nested,
always_quote_string_object_keys,
)?;
if self.trailing_comma {
used_space += 1;
if self.trailing_comma {
self.highlight_str(
",",
Some(self.row.range.end),
(
&highlighting::DEFAULT_STYLE,
&highlighting::SEARCH_MATCH_HIGHLIGHTED,
),
)?;
}
}
Ok(used_space)
}
fn size_of_container_and_num_digits_required(&self, row: &Row) -> (isize, isize) {
let container_size = {
let close_container = &self.flatjson[row.pair_index().unwrap()];
let last_child_index = close_container.last_child().unwrap();
(self.flatjson[last_child_index].index_in_parent as isize) + 1
};
// We are assuming container_size is never 0.
let space_needed_for_size = (isize::ilog10(container_size) as isize) + 1;
(container_size, space_needed_for_size)
}
fn generate_container_preview(
&mut self,
row: &Row,
mut available_space: isize,
is_nested: bool,
always_quote_string_object_keys: bool,
) -> Result<isize, fmt::Error> {
debug_assert!(row.is_opening_of_container());
let (container_size, space_needed_for_container_size) =
self.size_of_container_and_num_digits_required(row);
// Minimum amount of space required:
// - top level: (123) […]
// - nested: […]
let mut min_space_needed = 3;
if !is_nested {
min_space_needed += 3 + space_needed_for_container_size;
}
if available_space < min_space_needed {
return Ok(0);
}
let mut num_printed = 0;
if !is_nested {
self.terminal.set_fg(terminal::LIGHT_BLACK)?;
write!(self.terminal, "({container_size}) ")?;
available_space -= 3 + space_needed_for_container_size;
num_printed += 3 + space_needed_for_container_size;
}
let container_type = row.value.container_type().unwrap();
available_space -= 2;
// Create a copy of self.search_matches
let original_search_matches = self.search_matches.clone();
self.highlight_str(
container_type.open_str(),
Some(self.row.range.start),
highlighting::PREVIEW_STYLES,
)?;
num_printed += 1;
let mut next_sibling = row.first_child();
let mut is_first_child = true;
while let OptionIndex::Index(child) = next_sibling {
next_sibling = self.flatjson[child].next_sibling;
// If there are still more elements, we'll print out ", …" at the end,
let space_needed_at_end_of_container = if next_sibling.is_some() { 3 } else { 0 };
let space_available_for_elem = available_space - space_needed_at_end_of_container;
let is_only_child = is_first_child && next_sibling.is_nil();
let used_space = self.fill_in_container_elem_preview(
&self.flatjson[child],
space_available_for_elem,
always_quote_string_object_keys,
is_only_child,
)?;
if used_space == 0 {
// No room for anything else, let's close out the object.
// If we're not the first child, the previous elem will have
// printed the ", " separator.
self.highlight_str("…", None, highlighting::PREVIEW_STYLES)?;
// This variable isn't used again, but if it were, we'd need this
// line for correctness. Unfortunately Cargo check complains about it,
// so we'll just leave it here commented out in case code moves around
// and we need it.
// available_space -= 1;
num_printed += 1;
break;
} else {
// Successfully printed elem out, let's print a separator.
if next_sibling.is_some() {
self.highlight_str(
", ",
Some(self.flatjson[child].range.end),
highlighting::PREVIEW_STYLES,
)?;
available_space -= 2;
num_printed += 2;
}
}
available_space -= used_space;
num_printed += used_space;
is_first_child = false;
}
self.highlight_str(
container_type.close_str(),
Some(self.row.range.end - 1),
highlighting::PREVIEW_STYLES,
)?;
num_printed += 1;
self.search_matches = original_search_matches;
Ok(num_printed)
}
// {a…: …, …}
//
// [a, …]
fn fill_in_container_elem_preview(
&mut self,
row: &Row,
mut available_space: isize,
always_quote_string_object_keys: bool,
is_only_child: bool,
) -> Result<isize, fmt::Error> {
let mut used_space = 0;
if let Some(key_range) = &row.key_range {
let key_without_delimiter_range = key_range.start + 1..key_range.end - 1;
let key_ref = &self.flatjson.1[key_without_delimiter_range];
let key_open_delimiter = &self.flatjson.1[key_range.start..key_range.start + 1];
let mut delimiter = DelimiterPair::None;
if key_open_delimiter == "[" {
delimiter = DelimiterPair::Square;
} else if always_quote_string_object_keys || !JS_IDENTIFIER.is_match(key_ref) {
delimiter = DelimiterPair::Quote;
}
// Need at least one character for value, and two characters for ": "
let mut space_available_for_key = available_space - 3;
space_available_for_key -= delimiter.width();
let truncated_view = TruncatedStrView::init_start(key_ref, space_available_for_key);
let space_used_for_label = truncated_view.used_space();
if space_used_for_label.is_none() || truncated_view.is_completely_elided() {
return Ok(0);
}
let space_used_for_label = space_used_for_label.unwrap();
used_space += space_used_for_label;
available_space -= space_used_for_label;
used_space += delimiter.width();
available_space -= delimiter.width();
self.highlight_delimited_and_truncated_item(
delimiter,
key_ref,
&truncated_view,
Some(key_range.clone()),
highlighting::PREVIEW_STYLES,
)?;
used_space += 2;
available_space -= 2;
self.highlight_str(": ", Some(key_range.end), highlighting::PREVIEW_STYLES)?;