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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
//! Segments — the atoms of rendering.
//!
//! Port of upstream `rich/segment.py`. A [`Segment`] is a piece of text with an
//! optional [`Style`]. Everything renderable ultimately becomes a stream of
//! segments, which the [`Console`](crate::console::Console) turns into bytes.
//!
//! Control-code segments carry a `control` flag; the typed control sequences
//! that populate them live in [`control`](crate::control).
use crate::cells::cell_len;
use crate::style::Style;
/// A span of text with an optional style. Mirrors `rich.segment.Segment`.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Segment {
/// The text: a [`CompactString`](crate::CompactString), kept inline up
/// to 24 bytes, so a short run allocates nothing. It reads as a `&str`.
pub text: crate::CompactString,
pub style: Option<Style>,
/// Whether this segment carries terminal control codes rather than content.
pub control: bool,
}
impl Segment {
/// A plain content segment.
pub fn new(text: impl Into<crate::CompactString>, style: Option<Style>) -> Self {
Segment {
text: text.into(),
style,
control: false,
}
}
/// A newline segment (`Segment.line()` upstream).
pub fn line() -> Self {
Segment {
text: crate::CompactString::const_new("\n"),
style: None,
control: false,
}
}
/// A control segment (carries no visible width).
pub fn control(text: impl Into<crate::CompactString>) -> Self {
Segment {
text: text.into(),
style: None,
control: true,
}
}
/// The number of terminal cells this segment occupies (0 for control).
pub fn cell_length(&self) -> usize {
if self.control {
0
} else {
cell_len(&self.text)
}
}
/// Merge adjacent segments that share the same style and control flag.
/// Port of `Segment.simplify`.
pub fn simplify(segments: &[Segment]) -> Vec<Segment> {
let mut out: Vec<Segment> = Vec::with_capacity(segments.len());
for segment in segments {
match out.last_mut() {
Some(last) if last.style == segment.style && last.control == segment.control => {
last.text.push_str(&segment.text);
}
_ => out.push(segment.clone()),
}
}
out
}
/// Remove all colour from a segment stream, keeping every other attribute.
/// Port of `Segment.remove_color`.
pub fn remove_color(segments: &[Segment]) -> Vec<Segment> {
segments
.iter()
.map(|segment| Segment {
text: segment.text.clone(),
style: segment.style.as_ref().map(Style::without_color),
control: segment.control,
})
.collect()
}
/// Apply `style` as a base *under* each segment's own style (that segment's
/// style wins on top). Control segments are left untouched. Port of
/// `Segment.apply_style` (the `style`-only path).
///
/// Line-break segments (`"\n"`) are also left unstyled: upstream's
/// line-oriented print pipeline re-emits row separators plain, so styling
/// them would add stray SGR runs around every newline.
pub fn apply_style(segments: &[Segment], style: &Style) -> Vec<Segment> {
segments
.iter()
.map(|segment| {
if segment.control || segment.text == "\n" {
segment.clone()
} else {
let combined = match &segment.style {
Some(own) => style.combine(own),
None => style.clone(),
};
Segment {
text: segment.text.clone(),
style: Some(combined),
control: false,
}
}
})
.collect()
}
/// Split a flat segment stream into lines, breaking on `\n`.
///
/// Port of `Segment.split_lines`. Newline characters are consumed (not kept
/// in the output); a trailing newline yields a final empty line only if
/// there was content after the last break — or an explicit empty segment,
/// which is how a renderable whose last line is empty says so (the
/// port's streams separate lines rather than end them).
pub fn split_lines(segments: &[Segment]) -> Vec<Vec<Segment>> {
let mut lines: Vec<Vec<Segment>> = Vec::new();
let mut current: Vec<Segment> = Vec::new();
// An empty segment right after a break: the final line is empty.
let mut empty_last_line = false;
for segment in segments {
if segment.control || !segment.text.contains('\n') {
if !segment.text.is_empty() {
current.push(segment.clone());
} else if !segment.control && current.is_empty() && !lines.is_empty() {
empty_last_line = true;
}
continue;
}
empty_last_line = false;
let mut parts = segment.text.split('\n').peekable();
while let Some(part) = parts.next() {
if !part.is_empty() {
current.push(Segment::new(part, segment.style.clone()));
}
if parts.peek().is_some() {
// The break between parts closes the current line.
lines.push(std::mem::take(&mut current));
}
}
}
if !current.is_empty() || empty_last_line {
lines.push(current);
}
lines
}
/// [`split_lines`](Self::split_lines) of segments the caller is done
/// with: each is moved into its line rather than cloned, which a render
/// does once for every segment it makes (docs/PORTING.md, "Performance
/// notes"). `split_lines_owned_matches_split_lines` holds the two together.
pub(crate) fn split_lines_owned(segments: Vec<Segment>) -> Vec<Vec<Segment>> {
let mut lines: Vec<Vec<Segment>> = Vec::new();
let mut current: Vec<Segment> = Vec::new();
let mut empty_last_line = false;
for segment in segments {
if segment.control || !segment.text.contains('\n') {
if !segment.text.is_empty() {
current.push(segment);
} else if !segment.control && current.is_empty() && !lines.is_empty() {
empty_last_line = true;
}
continue;
}
empty_last_line = false;
let mut parts = segment.text.split('\n').peekable();
while let Some(part) = parts.next() {
if !part.is_empty() {
current.push(Segment::new(part, segment.style.clone()));
}
if parts.peek().is_some() {
lines.push(std::mem::take(&mut current));
}
}
}
if !current.is_empty() || empty_last_line {
lines.push(current);
}
lines
}
/// Shape a set of lines into exactly `height` rows of `width` cells: crop
/// extra rows, pad each row to `width`, and append blank rows to reach
/// `height`. Port of `Segment.set_shape` (`style=None`, `new_lines=False`).
pub fn set_shape(lines: Vec<Vec<Segment>>, width: usize, height: usize) -> Vec<Vec<Segment>> {
let mut shaped: Vec<Vec<Segment>> = lines
.into_iter()
.take(height)
.map(|line| Segment::adjust_line_length(&line, width, None))
.collect();
while shaped.len() < height {
shaped.push(vec![Segment::new(" ".repeat(width), None)]);
}
shaped
}
/// Fold every line to at most `width` cells, breaking at **word boundaries**
/// the way upstream's word wrapping does.
///
/// [`fold_lines`](Self::fold_lines) breaks wherever the row happens to fill
/// up, which splits identifiers and words mid-character-run
/// (`epsilon, z` / `eta, eta, theta)`). Upstream's `word_wrap=True` routes
/// through `_wrap.divide_line`, which we already port for `Text` — this
/// applies the same break offsets to a styled segment run, so styles survive
/// the split.
///
/// A word longer than `width` is still folded mid-word; there is nowhere
/// else to break it.
pub fn fold_lines_words(segments: &[Segment], width: usize) -> Vec<Segment> {
if width == 0 {
return segments.to_vec();
}
let mut out = Vec::new();
let lines = Self::split_lines(segments);
let last = lines.len().saturating_sub(1);
for (index, line) in lines.into_iter().enumerate() {
let plain: String = line
.iter()
.filter(|segment| !segment.control)
.map(|segment| segment.text.as_str())
.collect();
let breaks = crate::wrap::divide_line(&plain, width, true);
let mut char_pos = 0usize;
let mut next_break = 0usize;
for segment in line {
if segment.control {
out.push(segment);
continue;
}
let mut buf = String::new();
for ch in segment.text.chars() {
while next_break < breaks.len() && char_pos == breaks[next_break] {
if !buf.is_empty() {
out.push(Segment::new(buf.clone(), segment.style.clone()));
buf.clear();
}
out.push(Segment::line());
next_break += 1;
}
buf.push(ch);
char_pos += 1;
}
if !buf.is_empty() {
out.push(Segment::new(buf, segment.style.clone()));
}
}
if index != last {
out.push(Segment::line());
}
}
out
}
/// Fold every line to at most `width` cells, carrying the overflow onto
/// continuation lines instead of discarding it.
///
/// [`crop_lines`](Self::crop_lines) is the display backstop and **throws the
/// remainder away** — correct for a renderable that has already wrapped
/// itself, and data loss for one that emits a long line verbatim. Styles are
/// preserved across the split.
///
/// This breaks wherever the row happens to fill up, so it splits words. That
/// is right only for content upstream folds *without* word wrapping. A
/// renderable whose upstream counterpart goes through `Text.wrap` wants
/// [`fold_lines_words`](Self::fold_lines_words) instead: reaching for this
/// one is what made `--json` print `over t` / `he lazy` where rich prints
/// `over ` / `the lazy`.
pub fn fold_lines(segments: &[Segment], width: usize) -> Vec<Segment> {
if width == 0 {
return segments.to_vec();
}
let mut out = Vec::new();
let lines = Self::split_lines(segments);
let last = lines.len().saturating_sub(1);
for (index, line) in lines.into_iter().enumerate() {
let mut used = 0usize;
for segment in line {
if segment.control {
out.push(segment);
continue;
}
// Walk the segment in cell-sized pieces, breaking whenever the
// current row is full.
let mut remaining = segment.text.as_str();
while !remaining.is_empty() {
let room = width.saturating_sub(used);
if room == 0 {
out.push(Segment::line());
used = 0;
continue;
}
let chunks = crate::cells::chop_cells(remaining, room);
let mut head = chunks.first().cloned().unwrap_or_default();
if head.is_empty() {
if used > 0 {
// The row has content but no space for this
// character; start a fresh one and try again.
out.push(Segment::line());
used = 0;
continue;
}
// Already at the start of a row and the glyph STILL does
// not fit — a 2-cell glyph at width 1. Emit it anyway,
// overflowing by a cell.
//
// A whole *grapheme*, not a single code point: taking one
// code point off `"❤️"` emits a bare `❤` and leaves a
// stranded variation selector to be emitted on the next
// row, where it silently re-widens whatever character
// precedes it.
//
// Retrying here instead was an infinite loop that
// allocated a line break per iteration: ~400 MB/s until
// the process was killed. Every branch of this loop must
// consume input.
let (spans, _) = crate::cells::split_graphemes(remaining);
let take = spans.first().map_or(remaining.len(), |span| span.1);
head = remaining[..take].to_string();
}
used += crate::cells::cell_len(&head);
remaining = &remaining[head.len()..];
out.push(Segment::new(head, segment.style.clone()));
if !remaining.is_empty() {
out.push(Segment::line());
used = 0;
}
}
}
if index != last {
out.push(Segment::line());
}
}
out
}
/// Crop every line in a segment stream to at most `width` cells, discarding
/// the excess and leaving short lines alone.
///
/// Port of `Segment.split_and_crop_lines` with `pad=False`, which is what
/// `Console.print(crop=True)` applies to the finished stream. It is the only
/// thing standing between an [`Overflow::Ignore`](crate::console::Overflow)
/// text and a line that runs off the side of the terminal.
///
/// As upstream, any non-control segment containing `\n` is split there —
/// a print `end` such as `"!!\n"` arrives as one segment, and cropping it
/// whole would lose its newline — and each newline is re-emitted as a bare
/// [`Segment::line`]. A line is cropped only when it is wider than `width`;
/// then everything past the edge goes, zero-width characters and control
/// segments included (`adjust_line_length`).
pub fn crop_lines(segments: &[Segment], width: usize) -> Vec<Segment> {
let mut result: Vec<Segment> = Vec::with_capacity(segments.len());
let mut line: Vec<Segment> = Vec::new();
for segment in segments {
if !segment.control && segment.text.contains('\n') {
let mut pieces = segment.text.split('\n').peekable();
while let Some(piece) = pieces.next() {
if !piece.is_empty() {
line.push(Segment::new(piece, segment.style.clone()));
}
if pieces.peek().is_some() {
result.extend(Segment::crop_line(&line, width));
result.push(Segment::line());
line.clear();
}
}
} else {
line.push(segment.clone());
}
}
if !line.is_empty() {
result.extend(Segment::crop_line(&line, width));
}
result
}
/// The crop half of `Segment.adjust_line_length`: a line no wider than
/// `length` is returned whole; a wider one keeps segments while they end
/// strictly inside `length` (control segments always), cuts the first one
/// that reaches the edge with `set_cell_size`, and drops the rest.
fn crop_line(line: &[Segment], length: usize) -> Vec<Segment> {
let line_length: usize = line.iter().map(Segment::cell_length).sum();
if line_length <= length {
return line.to_vec();
}
let mut new_line: Vec<Segment> = Vec::new();
let mut used = 0usize;
for segment in line {
let segment_length = segment.cell_length();
if used + segment_length < length || segment.control {
new_line.push(segment.clone());
used += segment_length;
} else {
let cropped = crate::cells::set_cell_size(&segment.text, length - used);
new_line.push(Segment::new(cropped, segment.style.clone()));
break;
}
}
new_line
}
/// Pad (with a styled space run) or crop a single line to exactly `length`
/// cells. Port of `Segment.adjust_line_length`.
pub fn adjust_line_length(
line: &[Segment],
length: usize,
style: Option<Style>,
) -> Vec<Segment> {
let line_length: usize = line.iter().map(Segment::cell_length).sum();
if line_length < length {
let mut new_line = line.to_vec();
new_line.push(Segment::new(" ".repeat(length - line_length), style));
new_line
} else {
Segment::crop_line(line, length)
}
}
}
impl Segment {
/// Whether the segment carries control codes. Port of
/// `Segment.is_control`.
pub fn is_control(&self) -> bool {
self.control
}
/// Split into two segments at cell `cut`. A double-width character
/// that straddles the cut becomes a space on each side. Port of
/// `Segment.split_cells`.
pub fn split_cells(&self, cut: usize) -> (Segment, Segment) {
let with_text = |text: String| Segment {
text: text.into(),
style: self.style.clone(),
control: self.control,
};
let chars: Vec<char> = self.text.chars().collect();
if chars.iter().all(|&c| crate::cells::char_cell_width(c) == 1) {
if cut >= chars.len() {
return (self.clone(), with_text(String::new()));
}
return (
with_text(chars[..cut].iter().collect()),
with_text(chars[cut..].iter().collect()),
);
}
let cell_length = self.cell_length();
if cut >= cell_length {
return (self.clone(), with_text(String::new()));
}
let size = |c: char| crate::cells::char_cell_width(c);
let text = |range: std::ops::Range<usize>| -> String { chars[range].iter().collect() };
let mut pos = ((cut as f64 / cell_length as f64) * chars.len() as f64) as usize;
// Upstream searches without a bound, and loops forever when the cut
// falls inside a multi-character grapheme; this gives up after one
// pass over the text and splits as `cells.split_text` does.
for _ in 0..=chars.len() * 2 + 2 {
let cell_pos = crate::cells::cell_len(&text(0..pos));
if cell_pos == cut {
return (with_text(text(0..pos)), with_text(text(pos..chars.len())));
}
if cell_pos + 1 == cut && pos < chars.len() && size(chars[pos]) == 2 {
return (
with_text(text(0..pos) + " "),
with_text(" ".to_string() + &text(pos + 1..chars.len())),
);
}
if cell_pos == cut + 1 && pos > 0 && size(chars[pos - 1]) == 2 {
return (
with_text(text(0..pos - 1) + " "),
with_text(" ".to_string() + &text(pos..chars.len())),
);
}
if cell_pos < cut {
pos = (pos + 1).min(chars.len());
} else {
pos = pos.saturating_sub(1);
}
}
let (before, after) = crate::cells::split_text(&self.text, cut);
(with_text(before), with_text(after))
}
/// Apply `style` under each segment's own style and `post_style` over
/// it; control segments lose their style. Port of `Segment.apply_style`
/// with both arguments ([`apply_style`](Self::apply_style) is the
/// port's line-aware form of the `style`-only path).
pub fn apply_style_with(
segments: &[Segment],
style: Option<&Style>,
post_style: Option<&Style>,
) -> Vec<Segment> {
let style = style.filter(|style| !style.is_null());
let post_style = post_style.filter(|style| !style.is_null());
segments
.iter()
.map(|segment| {
let mut own = segment.style.clone();
if let Some(style) = style {
own = if segment.control {
None
} else {
Some(match &own {
Some(own) => style.combine(own),
None => style.clone(),
})
};
}
if let Some(post_style) = post_style {
own = if segment.control {
None
} else {
Some(match own.filter(|own| !own.is_null()) {
Some(own) => own.combine(post_style),
None => post_style.clone(),
})
};
}
Segment {
text: segment.text.clone(),
style: own,
control: segment.control,
}
})
.collect()
}
/// Keep only the control segments (`is_control`) or only the others.
/// Port of `Segment.filter_control`.
pub fn filter_control(segments: &[Segment], is_control: bool) -> Vec<Segment> {
segments
.iter()
.filter(|segment| segment.control == is_control)
.cloned()
.collect()
}
/// Split into lines on `\n`, each with whether a newline ended it; a
/// last line without one comes only when it holds something. Port of
/// `Segment.split_lines_terminator`.
pub fn split_lines_terminator(segments: &[Segment]) -> Vec<(Vec<Segment>, bool)> {
let mut lines = Vec::new();
let mut line: Vec<Segment> = Vec::new();
for segment in segments {
if segment.text.contains('\n') && !segment.control {
let mut pieces = segment.text.split('\n').peekable();
while let Some(piece) = pieces.next() {
if !piece.is_empty() {
line.push(Segment::new(piece, segment.style.clone()));
}
if pieces.peek().is_some() {
lines.push((std::mem::take(&mut line), true));
}
}
} else {
line.push(segment.clone());
}
}
if !line.is_empty() {
lines.push((line, false));
}
lines
}
/// Split into lines on `\n` and fit each to `length` cells, padding with
/// `style` when `pad` is set and ending each terminated line with a
/// newline segment when `include_new_lines` is. Port of
/// `Segment.split_and_crop_lines`.
pub fn split_and_crop_lines(
segments: &[Segment],
length: usize,
style: Option<&Style>,
pad: bool,
include_new_lines: bool,
) -> Vec<Vec<Segment>> {
Segment::split_lines_terminator(segments)
.into_iter()
.map(|(line, terminated)| {
let mut cropped =
Segment::adjust_line_length_with(&line, length, style.cloned(), pad);
if terminated && include_new_lines {
cropped.push(Segment::line());
}
cropped
})
.collect()
}
/// [`adjust_line_length`](Self::adjust_line_length) with upstream's `pad`
/// argument: a short line is padded only when it is set. Port of
/// `Segment.adjust_line_length`.
pub fn adjust_line_length_with(
line: &[Segment],
length: usize,
style: Option<Style>,
pad: bool,
) -> Vec<Segment> {
let line_length: usize = line.iter().map(Segment::cell_length).sum();
if line_length < length && !pad {
return line.to_vec();
}
Segment::adjust_line_length(line, length, style)
}
/// The cell length of a line, control segments excluded. Port of
/// `Segment.get_line_length`.
pub fn get_line_length(line: &[Segment]) -> usize {
line.iter()
.filter(|segment| !segment.control)
.map(|segment| cell_len(&segment.text))
.sum()
}
/// The width of the widest line and the number of lines. Port of
/// `Segment.get_shape`.
pub fn get_shape(lines: &[Vec<Segment>]) -> (usize, usize) {
let width = lines
.iter()
.map(|line| Segment::get_line_length(line))
.max()
.unwrap_or(0);
(width, lines.len())
}
/// Every line adjusted to `width`, then blank lines of `style` added up
/// to `height` (the line count when `None`); blank lines end in `\n`
/// with `new_lines`. Port of `Segment.set_shape`, which, unlike
/// [`set_shape`](Self::set_shape), does not drop lines past `height`.
pub fn set_shape_with(
lines: &[Vec<Segment>],
width: usize,
height: Option<usize>,
style: Option<&Style>,
new_lines: bool,
) -> Vec<Vec<Segment>> {
let height = height.filter(|&height| height > 0).unwrap_or(lines.len());
let mut shaped: Vec<Vec<Segment>> = lines
.iter()
.map(|line| Segment::adjust_line_length(line, width, style.cloned()))
.collect();
while shaped.len() < height {
shaped.push(vec![Segment::blank(width, style, new_lines)]);
}
shaped
}
/// A blank line of `width` cells in `style`.
fn blank(width: usize, style: Option<&Style>, new_lines: bool) -> Segment {
let mut text = " ".repeat(width);
if new_lines {
text.push('\n');
}
Segment::new(text, style.cloned())
}
/// Lines aligned to the top of `height` rows: blank lines of `style`
/// below. Port of `Segment.align_top`.
pub fn align_top(
lines: &[Vec<Segment>],
width: usize,
height: usize,
style: Option<&Style>,
new_lines: bool,
) -> Vec<Vec<Segment>> {
Segment::align_vertical(lines, width, height, style, new_lines, |extra| (0, extra))
}
/// Lines aligned to the bottom of `height` rows: blank lines above. Port
/// of `Segment.align_bottom`.
pub fn align_bottom(
lines: &[Vec<Segment>],
width: usize,
height: usize,
style: Option<&Style>,
new_lines: bool,
) -> Vec<Vec<Segment>> {
Segment::align_vertical(lines, width, height, style, new_lines, |extra| (extra, 0))
}
/// Lines in the middle of `height` rows, the odd blank line below. Port
/// of `Segment.align_middle`.
pub fn align_middle(
lines: &[Vec<Segment>],
width: usize,
height: usize,
style: Option<&Style>,
new_lines: bool,
) -> Vec<Vec<Segment>> {
Segment::align_vertical(lines, width, height, style, new_lines, |extra| {
(extra / 2, extra - extra / 2)
})
}
/// The shared body of the `align_*` methods: `split` divides the extra
/// rows into (above, below). With exactly `height` rows the lines come
/// back unchanged, and with more they are cut to `height`.
fn align_vertical(
lines: &[Vec<Segment>],
width: usize,
height: usize,
style: Option<&Style>,
new_lines: bool,
split: impl Fn(usize) -> (usize, usize),
) -> Vec<Vec<Segment>> {
if lines.len() >= height {
return lines[..height].to_vec();
}
let (above, below) = split(height - lines.len());
let blank = vec![Segment::blank(width, style, new_lines)];
let mut aligned = vec![blank.clone(); above];
aligned.extend(lines.iter().cloned());
aligned.extend(std::iter::repeat_n(blank, below));
aligned
}
/// The segments with every hyperlink removed. Port of
/// `Segment.strip_links`.
pub fn strip_links(segments: &[Segment]) -> Vec<Segment> {
segments
.iter()
.map(|segment| match &segment.style {
Some(style) if !segment.control => Segment {
text: segment.text.clone(),
style: (!style.is_null()).then(|| style.update_link(None)),
control: false,
},
_ => segment.clone(),
})
.collect()
}
/// The segments with no styles at all. Port of `Segment.strip_styles`.
pub fn strip_styles(segments: &[Segment]) -> Vec<Segment> {
segments
.iter()
.map(|segment| Segment {
text: segment.text.clone(),
style: None,
control: segment.control,
})
.collect()
}
/// Cut the segments at each cell offset in `cuts` (ascending), one list
/// per piece; a segment that straddles a cut is split with
/// [`split_cells`](Self::split_cells). Port of `Segment.divide`.
pub fn divide(segments: &[Segment], cuts: &[usize]) -> Vec<Vec<Segment>> {
let mut result = Vec::new();
let mut cuts = cuts.iter().copied();
let mut cut = loop {
match cuts.next() {
None => return result,
Some(0) => result.push(Vec::new()),
Some(cut) => break cut,
}
};
let mut pieces: Vec<Segment> = Vec::new();
let mut pos = 0usize;
for segment in segments {
let mut segment = segment.clone();
while !segment.text.is_empty() {
let end_pos = if segment.control {
pos
} else {
pos + cell_len(&segment.text)
};
if end_pos < cut {
pieces.push(segment.clone());
pos = end_pos;
break;
}
if end_pos == cut {
pieces.push(segment.clone());
result.push(std::mem::take(&mut pieces));
pos = end_pos;
match cuts.next() {
Some(next) => cut = next,
None => {
if !pieces.is_empty() {
result.push(pieces);
}
return result;
}
}
break;
}
let (before, after) = segment.split_cells(cut - pos);
segment = after;
pieces.push(before);
result.push(std::mem::take(&mut pieces));
pos = cut;
match cuts.next() {
Some(next) => cut = next,
None => {
if !pieces.is_empty() {
result.push(pieces);
}
return result;
}
}
}
}
result.push(pieces);
result
}
}
/// A list of segments that renders as they are, or one per line with
/// `new_lines`. Port of `rich.segment.Segments`.
#[derive(Clone, Debug, Default)]
pub struct Segments {
pub segments: Vec<Segment>,
pub new_lines: bool,
}
impl Segments {
pub fn new(segments: Vec<Segment>, new_lines: bool) -> Self {
Segments {
segments,
new_lines,
}
}
}
impl crate::protocol::Renderable for Segments {
/// Upstream ends each segment with a newline under `new_lines`; this
/// port's renderables separate lines, so the last newline is left to
/// the caller.
fn rich_render(
&self,
_console: &crate::console::Console,
_options: &crate::console::ConsoleOptions,
) -> Vec<Segment> {
if !self.new_lines {
return self.segments.clone();
}
let mut out = Vec::with_capacity(self.segments.len() * 2);
for (index, segment) in self.segments.iter().enumerate() {
if index > 0 {
out.push(Segment::line());
}
out.push(segment.clone());
}
out
}
}
/// Lines of segments that render one after another, each ending in a
/// newline with `new_lines`. Port of `rich.segment.SegmentLines`.
#[derive(Clone, Debug, Default)]
pub struct SegmentLines {
pub lines: Vec<Vec<Segment>>,
pub new_lines: bool,
}
impl SegmentLines {
pub fn new(lines: Vec<Vec<Segment>>, new_lines: bool) -> Self {
SegmentLines { lines, new_lines }
}
}
impl crate::protocol::Renderable for SegmentLines {
/// As [`Segments`], the last line's newline is left to the caller.
fn rich_render(
&self,
_console: &crate::console::Console,
_options: &crate::console::ConsoleOptions,
) -> Vec<Segment> {
let mut out = Vec::new();
for (index, line) in self.lines.iter().enumerate() {
if index > 0 && self.new_lines {
out.push(Segment::line());
}
out.extend(line.iter().cloned());
}
out
}
}
#[cfg(test)]
mod tests {
use super::*;
/// Moving the segments splits them as cloning them does, on every
/// sequence of up to five segments drawn from the kinds that matter.
#[test]
fn split_lines_owned_matches_split_lines() {
let bold = Style::parse("bold").unwrap();
let kinds = [
Segment::new("ab", None),
Segment::new("", None),
Segment::new("\n", Some(bold.clone())),
Segment::new("x\ny\n", Some(bold)),
Segment::new("\n\nz", None),
Segment::line(),
Segment::control("\x1b[2J"),
];
let mut sequences: Vec<Vec<Segment>> = vec![Vec::new()];
for _ in 0..5 {
sequences = sequences
.iter()
.flat_map(|sequence| {
kinds.iter().map(move |kind| {
let mut next = sequence.clone();
next.push(kind.clone());
next
})
})
.collect();
for sequence in &sequences {
assert_eq!(
Segment::split_lines_owned(sequence.clone()),
Segment::split_lines(sequence),
"{sequence:?}"
);
}
}
}
/// Cropping is per line, leaves short lines alone, and keeps zero-width
/// control segments so cursor moves survive.
#[test]
fn crop_lines_cuts_each_line_independently() {
let segments = vec![
Segment::new("hello world", None),
Segment::line(),
Segment::new("hi", None),
Segment::line(),
Segment::control("\x1b[2A"),
Segment::new("abcdefgh", None),
];
let cropped = Segment::crop_lines(&segments, 5);
let texts: Vec<&str> = cropped.iter().map(|s| s.text.as_str()).collect();
assert_eq!(texts, vec!["hello", "\n", "hi", "\n", "\x1b[2A", "abcde"]);
}
/// A print `end` such as `"!!\n"` arrives as one segment; it is split
/// at the newline before cropping, so the newline survives
/// (`print("xy", end="!!\n")` at width 3 is `"xy!\n"`).
#[test]
fn crop_lines_keeps_a_newline_inside_a_segment() {
let segments = vec![Segment::new("xy", None), Segment::new("!!\n", None)];
let cropped = Segment::crop_lines(&segments, 3);
let texts: Vec<&str> = cropped.iter().map(|s| s.text.as_str()).collect();
assert_eq!(texts, vec!["xy", "!", "\n"]);
}
/// Past the crop edge everything goes, zero-width characters included,
/// as upstream's `adjust_line_length` breaks at the edge.
#[test]
fn crop_lines_drops_zero_width_characters_past_the_edge() {
let segments = vec![
Segment::new("abc", None),
Segment::new("\u{200b}", None),
Segment::new("d", None),
];
let cropped = Segment::crop_lines(&segments, 3);
let texts: Vec<&str> = cropped.iter().map(|s| s.text.as_str()).collect();
assert_eq!(texts, vec!["abc"]);
// A line that fits is left whole, trailing zero-width included.
let fits = Segment::crop_lines(&segments[..2], 3);
assert_eq!(fits.len(), 2);
}
/// A wide character straddling the crop is dropped whole and its cell padded,
/// so the line still occupies exactly the requested width.
#[test]
fn crop_lines_pads_a_split_wide_character() {
let segments = vec![Segment::new("aa你好", None)];
let cropped = Segment::crop_lines(&segments, 5);
assert_eq!(cropped[0].text, "aa你 ");
}
/// A crop boundary falling between segments keeps the styles of the ones it
/// kept and drops the rest entirely.
#[test]
fn crop_lines_preserves_styles_and_drops_the_tail() {
let bold = Style::parse("bold").unwrap();
let segments = vec![
Segment::new("abc", Some(bold.clone())),
Segment::new("defgh", None),
];
let cropped = Segment::crop_lines(&segments, 3);
assert_eq!(cropped.len(), 1);
assert_eq!(cropped[0].text, "abc");
assert_eq!(cropped[0].style, Some(bold));
}
#[test]
fn cell_length_ignores_control() {
assert_eq!(Segment::new("abc", None).cell_length(), 3);
assert_eq!(Segment::control("\x1b[2J").cell_length(), 0);
}
#[test]
fn fold_lines_carries_the_overflow_instead_of_dropping_it() {
let segments = vec![Segment::new("abcdefghij", None)];
let folded = Segment::fold_lines(&segments, 4);
let text: String = folded.iter().map(|s| s.text.as_str()).collect();
// Every character survives; only line breaks are added.
assert_eq!(text.replace('\n', ""), "abcdefghij");
assert_eq!(Segment::split_lines(&folded).len(), 3);
}
#[test]
fn fold_lines_preserves_styles_across_a_break() {
let style = Style::parse("bold").expect("valid style");
let segments = vec![Segment::new("abcdef", Some(style.clone()))];
let folded = Segment::fold_lines(&segments, 3);
for segment in folded.iter().filter(|s| !s.text.contains('\n')) {
assert_eq!(segment.style.as_ref(), Some(&style), "style lost on fold");
}
}
/// A glyph wider than the whole row is emitted anyway, overflowing — but as
/// a whole grapheme. Taking a single code point off `"❤️"` put the bare `❤`
/// on one row and stranded the variation selector at the start of the next,
/// where it silently re-widens whatever character follows it.
#[test]
fn fold_lines_never_splits_a_grapheme() {
let heart = "\u{2764}\u{fe0f}";
let segments = vec![Segment::new(heart.repeat(3), None)];
let folded = Segment::fold_lines(&segments, 1);
let rows: Vec<String> = Segment::split_lines(&folded)
.iter()
.map(|line| line.iter().map(|s| s.text.as_str()).collect())
.collect();
assert_eq!(rows, vec![heart, heart, heart]);
}
#[test]
fn crop_lines_still_drops_the_overflow() {
// fold_lines is the alternative, not a replacement: crop stays the
// display backstop for renderables that already wrapped themselves.
let segments = vec![Segment::new("abcdefghij", None)];
let cropped = Segment::crop_lines(&segments, 4);
let text: String = cropped.iter().map(|s| s.text.as_str()).collect();
assert_eq!(text, "abcd");
}
#[test]
fn fold_lines_terminates_when_a_glyph_is_wider_than_the_width() {
// A 2-cell character with 1 column available used to loop forever,
// pushing a line break per iteration (~400 MB/s until killed). Every
// branch of the fold loop must consume input.
let segments = vec![Segment::new("\u{4f60}\u{4f60}", None)];
let folded = Segment::fold_lines(&segments, 1);
let text: String = folded.iter().map(|s| s.text.as_str()).collect();
assert_eq!(
text.matches('\u{4f60}').count(),
2,
"both characters should survive, overflowing rather than looping"
);
}
/// The word-wrapping fold breaks *between* words, leaving the space that
/// separated them at the end of the finished row — exactly where
/// `_wrap.divide_line` puts the offset.
#[test]
fn fold_lines_words_breaks_between_words() {
let segments = vec![Segment::new("the quick brown fox", None)];
// 12, not 10: at 10 a character fold would land on the same boundary by
// luck and the test would pass either way.
let folded = Segment::fold_lines_words(&segments, 12);
let lines: Vec<String> = Segment::split_lines(&folded)
.iter()
.map(|line| line.iter().map(|s| s.text.as_str()).collect())
.collect();
assert_eq!(lines, vec!["the quick ", "brown fox"]);
}
/// A break landing inside a styled run must not drop the style, or a wrapped
/// JSON string would lose its colour halfway down.
#[test]
fn fold_lines_words_preserves_styles_across_a_break() {
let green = Style::parse("green").expect("valid style");
let segments = vec![
Segment::new("key: ", None),
Segment::new("alpha beta gamma", Some(green.clone())),
];
let folded = Segment::fold_lines_words(&segments, 12);
let styled: String = folded
.iter()
.filter(|s| s.style.as_ref() == Some(&green))
.map(|s| s.text.as_str())
.collect();
assert_eq!(styled, "alpha beta gamma", "style lost across the break");
}
/// Nothing may be dropped: a word wider than the row still has to fold, and
/// the offsets have to line up with the segments they cut.
#[test]
fn fold_lines_words_keeps_every_character() {
let segments = vec![
Segment::new("short ", None),
Segment::new("z".repeat(25), None),
Segment::new(" tail", None),
];
for width in 1..=30 {
let folded = Segment::fold_lines_words(&segments, width);
let text: String = folded.iter().map(|s| s.text.as_str()).collect();
assert_eq!(
text.replace('\n', ""),
format!("short {} tail", "z".repeat(25)),
"width {width} lost or reordered characters"
);
}
}
/// Control segments carry no cells, so they must ride through untouched
/// rather than count against the width or vanish.
#[test]
fn fold_lines_words_keeps_control_segments() {
let segments = vec![
Segment::control("\x1b]8;;http://x\x1b\\"),
Segment::new("alpha beta", None),
];
let folded = Segment::fold_lines_words(&segments, 8);
assert_eq!(folded.iter().filter(|s| s.control).count(), 1);
let text: String = folded
.iter()
.filter(|s| !s.control)
.map(|s| s.text.as_str())
.collect();
assert_eq!(text, "alpha \nbeta");
}
#[test]
fn fold_lines_terminates_at_every_narrow_width() {
// Mixed widths: ASCII, CJK, and an emoji, folded at each width from 1.
let sample = "a\u{4f60}b\u{1f600}c";
for width in 1..=6 {
let folded = Segment::fold_lines(&[Segment::new(sample, None)], width);
let text: String = folded.iter().map(|s| s.text.as_str()).collect();
assert!(
text.contains('c'),
"width {width} lost the tail, or did not terminate"
);
}
}
}