-
Notifications
You must be signed in to change notification settings - Fork 26
/
text_renderer.rs
1991 lines (1752 loc) · 62.9 KB
/
text_renderer.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
//! Implementations of the `Renderer` trait.
//!
//! This module implements helpers and concrete types for rendering from HTML
//! into different text formats.
use crate::Colour;
use crate::Error;
use super::Renderer;
use std::cell::Cell;
use std::mem;
use std::ops::Deref;
use std::ops::DerefMut;
use std::rc::Rc;
use std::vec;
use std::{collections::LinkedList, fmt::Debug};
use unicode_width::{UnicodeWidthChar, UnicodeWidthStr};
/// Context to use during tree parsing.
/// This mainly gives access to a Renderer, but needs to be able to push
/// new ones on for nested structures.
#[derive(Clone, Debug)]
pub struct TextRenderer<D: TextDecorator> {
subrender: Vec<SubRenderer<D>>,
links: Vec<String>,
}
impl<D: TextDecorator> Deref for TextRenderer<D> {
type Target = SubRenderer<D>;
fn deref(&self) -> &Self::Target {
self.subrender.last().expect("Underflow in renderer stack")
}
}
impl<D: TextDecorator> DerefMut for TextRenderer<D> {
fn deref_mut(&mut self) -> &mut Self::Target {
self.subrender
.last_mut()
.expect("Underflow in renderer stack")
}
}
impl<D: TextDecorator> TextRenderer<D> {
/// Construct new stack of renderer
pub fn new(subrenderer: SubRenderer<D>) -> TextRenderer<D> {
TextRenderer {
subrender: vec![subrenderer],
links: Vec::new(),
}
}
// hack overloads start_link method otherwise coming from the Renderer trait
// impl on SubRenderer
/// Add link to global link collection
pub fn start_link(&mut self, target: &str) -> crate::Result<()> {
self.links.push(target.to_string());
self.subrender.last_mut().unwrap().start_link(target)?;
Ok(())
}
/// Push a new builder onto the stack
pub fn push(&mut self, builder: SubRenderer<D>) {
self.subrender.push(builder);
}
/// Pop off the top builder and return it.
/// Panics if empty
pub fn pop(&mut self) -> SubRenderer<D> {
self.subrender
.pop()
.expect("Attempt to pop a subrender from empty stack")
}
/// Pop off the only builder and return it.
/// panics if there aren't exactly 1 available.
pub fn into_inner(mut self) -> (SubRenderer<D>, Vec<String>) {
assert_eq!(self.subrender.len(), 1);
(
self.subrender
.pop()
.expect("Attempt to pop a subrenderer from an empty stack"),
self.links,
)
}
}
/// A wrapper around a String with extra metadata.
#[derive(Debug, Clone, PartialEq)]
pub struct TaggedString<T> {
/// The wrapped text.
pub s: String,
/// The metadata.
pub tag: T,
}
impl<T: Debug + PartialEq> TaggedString<T> {
/// Returns the tagged string’s display width in columns.
///
/// See [`unicode_width::UnicodeWidthStr::width`][] for more information.
///
/// [`unicode_width::UnicodeWidthStr::width`]: https://docs.rs/unicode-width/latest/unicode_width/trait.UnicodeWidthStr.html
pub fn width(&self) -> usize {
self.s.width()
}
}
/// An element of a line of tagged text: either a TaggedString or a
/// marker appearing in between document characters.
#[derive(Clone, Debug, PartialEq)]
pub enum TaggedLineElement<T> {
/// A string with tag information attached.
Str(TaggedString<T>),
/// A zero-width marker indicating the start of a named HTML fragment.
FragmentStart(String),
}
impl<T> TaggedLineElement<T> {
/// Return true if this element is non-empty.
/// FragmentStart is considered empty.
fn has_content(&self) -> bool {
match self {
TaggedLineElement::Str(_) => true,
TaggedLineElement::FragmentStart(_) => false,
}
}
}
/// A line of tagged text (composed of a set of `TaggedString`s).
#[derive(Debug, Clone, PartialEq)]
pub struct TaggedLine<T> {
v: Vec<TaggedLineElement<T>>,
}
impl<T: Debug + Eq + PartialEq + Clone + Default> TaggedLine<T> {
/// Create an empty `TaggedLine`.
pub fn new() -> TaggedLine<T> {
TaggedLine { v: Vec::new() }
}
/// Create a new TaggedLine from a string and tag.
pub fn from_string(s: String, tag: &T) -> TaggedLine<T> {
TaggedLine {
v: vec![TaggedLineElement::Str(TaggedString {
s: s,
tag: tag.clone(),
})],
}
}
/// Join the line into a String, ignoring the tags and markers.
pub fn into_string(self) -> String {
let mut s = String::new();
for tle in self.v {
if let TaggedLineElement::Str(ts) = tle {
s.push_str(&ts.s);
}
}
s
}
/// Return true if the line is non-empty
pub fn is_empty(&self) -> bool {
for elt in &self.v {
if elt.has_content() {
return false;
}
}
true
}
/// Add a new tagged string fragment to the line
pub fn push_str(&mut self, ts: TaggedString<T>) {
use self::TaggedLineElement::Str;
if !self.v.is_empty() {
if let Str(ref mut ts_prev) = self.v.last_mut().unwrap() {
if ts_prev.tag == ts.tag {
ts_prev.s.push_str(&ts.s);
return;
}
}
}
self.v.push(Str(ts));
}
/// Add a new general TaggedLineElement to the line
pub fn push(&mut self, tle: TaggedLineElement<T>) {
use self::TaggedLineElement::Str;
if let Str(ts) = tle {
self.push_str(ts);
} else {
self.v.push(tle);
}
}
/// Add a new fragment to the start of the line
pub fn insert_front(&mut self, ts: TaggedString<T>) {
use self::TaggedLineElement::Str;
self.v.insert(0, Str(ts));
}
/// Add text with a particular tag to self
pub fn push_char(&mut self, c: char, tag: &T) {
use self::TaggedLineElement::Str;
if !self.v.is_empty() {
if let Str(ref mut ts_prev) = self.v.last_mut().unwrap() {
if ts_prev.tag == *tag {
ts_prev.s.push(c);
return;
}
}
}
let mut s = String::new();
s.push(c);
self.v.push(Str(TaggedString {
s,
tag: tag.clone(),
}));
}
/// Drain tl and use to extend self.
pub fn consume(&mut self, tl: &mut TaggedLine<T>) {
for ts in tl.v.drain(..) {
self.push(ts);
}
}
/// Drain the contained items
pub fn drain_all(&mut self) -> vec::Drain<TaggedLineElement<T>> {
self.v.drain(..)
}
/// Iterator over the chars in this line.
#[cfg_attr(feature = "clippy", allow(needless_lifetimes))]
pub fn chars<'a>(&'a self) -> impl Iterator<Item = char> + 'a {
use self::TaggedLineElement::Str;
self.v.iter().flat_map(|tle| {
if let Str(ts) = tle {
ts.s.chars()
} else {
"".chars()
}
})
}
#[cfg(feature = "html_trace")]
/// Return a string contents for debugging.
fn to_string(&self) -> String {
self.chars().collect()
}
/// Iterator over TaggedLineElements
pub fn iter<'a>(&'a self) -> impl Iterator<Item = &TaggedLineElement<T>> + 'a {
self.v.iter()
}
/// Iterator over the tagged strings in this line, ignoring any fragments.
pub fn tagged_strings(&self) -> impl Iterator<Item = &TaggedString<T>> {
self.v.iter().filter_map(|tle| match tle {
TaggedLineElement::Str(ts) => Some(ts),
_ => None,
})
}
/// Converts the tagged line into an iterator over the tagged strings in this line, ignoring
/// any fragments.
pub fn into_tagged_strings(self) -> impl Iterator<Item = TaggedString<T>> {
self.v.into_iter().filter_map(|tle| match tle {
TaggedLineElement::Str(ts) => Some(ts),
_ => None,
})
}
/// Return the width of the line in cells
pub fn width(&self) -> usize {
self.tagged_strings().map(TaggedString::width).sum()
}
/// Pad this line to width with spaces (or if already at least this wide, do
/// nothing).
pub fn pad_to(&mut self, width: usize, tag: &T) {
use self::TaggedLineElement::Str;
let my_width = self.width();
if width > my_width {
self.v.push(Str(TaggedString {
s: format!("{: <width$}", "", width = width - my_width),
tag: tag.clone(),
}));
}
}
}
/// A type to build up wrapped text, allowing extra metadata for
/// spans.
#[derive(Debug, Clone)]
struct WrappedBlock<T> {
width: usize,
text: Vec<TaggedLine<T>>,
textlen: usize,
line: TaggedLine<T>,
linelen: usize,
spacetag: Option<T>, // Tag for the whitespace before the current word
word: TaggedLine<T>, // The current word (with no whitespace).
wordlen: usize,
pre_wrapped: bool, // If true, we've been forced to wrap a <pre> line.
pad_blocks: bool,
allow_overflow: bool,
}
impl<T: Clone + Eq + Debug + Default> WrappedBlock<T> {
pub fn new(width: usize, pad_blocks: bool, allow_overflow: bool) -> WrappedBlock<T> {
WrappedBlock {
width,
text: Vec::new(),
textlen: 0,
line: TaggedLine::new(),
linelen: 0,
spacetag: None,
word: TaggedLine::new(),
wordlen: 0,
pre_wrapped: false,
pad_blocks,
allow_overflow,
}
}
fn flush_word(&mut self) -> Result<(), Error> {
use self::TaggedLineElement::Str;
/* Finish the word. */
html_trace_quiet!("flush_word: word={:?}, linelen={}", self.word, self.linelen);
if !self.word.is_empty() {
self.pre_wrapped = false;
let space_in_line = self.width - self.linelen;
let space_needed = self.wordlen + if self.linelen > 0 { 1 } else { 0 }; // space
if space_needed <= space_in_line {
html_trace!("Got enough space");
if self.linelen > 0 {
self.line.push(Str(TaggedString {
s: " ".into(),
tag: self.spacetag.clone().unwrap_or_else(|| Default::default()),
}));
self.linelen += 1;
html_trace!("linelen incremented to {}", self.linelen);
}
self.line.consume(&mut self.word);
self.linelen += self.wordlen;
html_trace!("linelen increased by wordlen to {}", self.linelen);
} else {
html_trace!("Not enough space");
/* Start a new line */
self.flush_line();
if self.wordlen <= self.width {
html_trace!("wordlen <= width");
let mut new_word = TaggedLine::new();
mem::swap(&mut new_word, &mut self.word);
mem::swap(&mut self.line, &mut new_word);
self.linelen = self.wordlen;
html_trace!("linelen set to wordlen {}", self.linelen);
} else {
html_trace!("Splitting the word");
/* We need to split the word. */
let mut word = TaggedLine::new();
mem::swap(&mut word, &mut self.word);
let mut wordbits = word.drain_all();
/* Note: there's always at least one piece */
let mut opt_elt = wordbits.next();
let mut lineleft = self.width;
while let Some(elt) = opt_elt.take() {
html_trace!("Take element {:?}", elt);
if let Str(piece) = elt {
let w = piece.width();
if w <= lineleft {
self.line.push(Str(piece));
lineleft -= w;
self.linelen += w;
html_trace!("linelen had w={} added to {}", w, self.linelen);
opt_elt = wordbits.next();
} else {
/* Split into two */
let mut split_idx = 0;
for (idx, c) in piece.s.char_indices() {
let c_w = UnicodeWidthChar::width(c).unwrap();
if c_w <= lineleft {
lineleft -= c_w;
} else {
// Check if we've made no progress, for example
// if the first character is 2 cells wide and we
// only have a width of 1.
if idx == 0 && self.line.width() == 0 {
if self.allow_overflow {
split_idx = c.len_utf8();
break;
} else {
return Err(Error::TooNarrow);
}
}
split_idx = idx;
break;
}
}
self.line.push(Str(TaggedString {
s: piece.s[..split_idx].into(),
tag: piece.tag.clone(),
}));
self.force_flush_line();
lineleft = self.width;
if split_idx == piece.s.len() {
opt_elt = None;
} else {
opt_elt = Some(Str(TaggedString {
s: piece.s[split_idx..].into(),
tag: piece.tag,
}));
}
}
} else {
self.line.push(elt);
opt_elt = wordbits.next();
}
}
}
}
}
self.wordlen = 0;
Ok(())
}
fn flush_line(&mut self) {
if !self.line.is_empty() {
self.force_flush_line();
}
}
fn force_flush_line(&mut self) {
let mut tmp_line = TaggedLine::new();
mem::swap(&mut tmp_line, &mut self.line);
if self.pad_blocks {
let tmp_tag;
let tag = if let Some(st) = self.spacetag.as_ref() {
st
} else {
tmp_tag = Default::default();
&tmp_tag
};
tmp_line.pad_to(self.width, tag);
}
self.text.push(tmp_line);
self.linelen = 0;
}
fn flush(&mut self) -> Result<(), Error> {
self.flush_word()?;
self.flush_line();
Ok(())
}
/// Consume self and return a vector of lines.
/*
pub fn into_untagged_lines(mut self) -> Vec<String> {
self.flush();
let mut result = Vec::new();
for line in self.text.into_iter() {
let mut line_s = String::new();
for TaggedString{ s, .. } in line.into_iter() {
line_s.push_str(&s);
}
result.push(line_s);
}
result
}
*/
/// Consume self and return vector of lines including annotations.
pub fn into_lines(mut self) -> Result<Vec<TaggedLine<T>>, Error> {
self.flush()?;
Ok(self.text)
}
pub fn add_text(&mut self, text: &str, tag: &T) -> Result<(), Error> {
html_trace!("WrappedBlock::add_text({}), {:?}", text, tag);
for c in text.chars() {
if c.is_whitespace() {
/* Whitespace is mostly ignored, except to terminate words. */
self.flush_word()?;
self.spacetag = Some(tag.clone());
} else if let Some(charwidth) = UnicodeWidthChar::width(c) {
/* Not whitespace; add to the current word. */
self.word.push_char(c, tag);
self.wordlen += charwidth;
}
html_trace_quiet!(" Added char {:?}, wordlen={}", c, self.wordlen);
}
Ok(())
}
pub fn add_preformatted_text(
&mut self,
text: &str,
tag_main: &T,
tag_wrapped: &T,
) -> Result<(), Error> {
html_trace!(
"WrappedBlock::add_preformatted_text({}), {:?}/{:?}",
text,
tag_main,
tag_wrapped
);
// Make sure that any previous word has been sent to the line, as we
// bypass the word buffer.
self.flush_word()?;
for c in text.chars() {
if let Some(charwidth) = UnicodeWidthChar::width(c) {
if self.linelen + charwidth > self.width {
self.flush_line();
self.pre_wrapped = true;
}
self.line.push_char(
c,
if self.pre_wrapped {
tag_wrapped
} else {
tag_main
},
);
self.linelen += charwidth;
} else {
match c {
'\n' => {
self.force_flush_line();
self.pre_wrapped = false;
}
'\t' => {
let tab_stop = 8;
let mut at_least_one_space = false;
while self.linelen % tab_stop != 0 || !at_least_one_space {
if self.linelen >= self.width {
self.flush_line();
} else {
self.line.push_char(
' ',
if self.pre_wrapped {
tag_wrapped
} else {
tag_main
},
);
self.linelen += 1;
at_least_one_space = true;
}
}
}
_ => {}
}
}
html_trace_quiet!(" Added char {:?}", c);
}
Ok(())
}
pub fn add_element(&mut self, elt: TaggedLineElement<T>) {
self.word.push(elt);
}
pub fn text_len(&self) -> usize {
self.textlen + self.linelen + self.wordlen
}
pub fn is_empty(&self) -> bool {
self.text_len() == 0
}
}
/// Allow decorating/styling text.
///
/// Decorating refers to adding extra text around the rendered version
/// of some elements, such as surrounding emphasised text with `*` like
/// in markdown: `Some *bold* text`. The decorations are formatted and
/// wrapped along with the rest of the rendered text. This is suitable
/// for rendering HTML to an environment where terminal attributes are
/// not available.
///
/// In addition, instances of `TextDecorator` can also return annotations
/// of an associated type `Annotation` which will be associated with spans of
/// text. This can be anything from `()` as for `PlainDecorator` or a more
/// featured type such as `RichAnnotation`. The annotated spans (`TaggedLine`)
/// can be used by application code to add e.g. terminal colours or underlines.
pub trait TextDecorator {
/// An annotation which can be added to text, and which will
/// be attached to spans of text.
type Annotation: Eq + PartialEq + Debug + Clone + Default;
/// Return an annotation and rendering prefix for a link.
fn decorate_link_start(&mut self, url: &str) -> (String, Self::Annotation);
/// Return a suffix for after a link.
fn decorate_link_end(&mut self) -> String;
/// Return an annotation and rendering prefix for em
fn decorate_em_start(&self) -> (String, Self::Annotation);
/// Return a suffix for after an em.
fn decorate_em_end(&self) -> String;
/// Return an annotation and rendering prefix for strong
fn decorate_strong_start(&self) -> (String, Self::Annotation);
/// Return a suffix for after a strong.
fn decorate_strong_end(&self) -> String;
/// Return an annotation and rendering prefix for strikeout
fn decorate_strikeout_start(&self) -> (String, Self::Annotation);
/// Return a suffix for after a strikeout.
fn decorate_strikeout_end(&self) -> String;
/// Return an annotation and rendering prefix for code
fn decorate_code_start(&self) -> (String, Self::Annotation);
/// Return a suffix for after a code.
fn decorate_code_end(&self) -> String;
/// Return an annotation for the initial part of a preformatted line
fn decorate_preformat_first(&self) -> Self::Annotation;
/// Return an annotation for a continuation line when a preformatted
/// line doesn't fit.
fn decorate_preformat_cont(&self) -> Self::Annotation;
/// Return an annotation and rendering prefix for a link.
fn decorate_image(&mut self, src: &str, title: &str) -> (String, Self::Annotation);
/// Return prefix string of header in specific level.
fn header_prefix(&self, level: usize) -> String;
/// Return prefix string of quoted block.
fn quote_prefix(&self) -> String;
/// Return prefix string of unordered list item.
fn unordered_item_prefix(&self) -> String;
/// Return prefix string of ith ordered list item.
fn ordered_item_prefix(&self, i: i64) -> String;
/// Return a new decorator of the same type which can be used
/// for sub blocks.
fn make_subblock_decorator(&self) -> Self;
/// Return an annotation corresponding to adding colour, or none.
fn push_colour(&mut self, _: Colour) -> Option<Self::Annotation> {
None
}
/// Pop the last colour pushed if we pushed one.
fn pop_colour(&mut self) -> bool {
false
}
/// Return an annotation corresponding to adding background colour, or none.
fn push_bgcolour(&mut self, _: Colour) -> Option<Self::Annotation> {
None
}
/// Pop the last background colour pushed if we pushed one.
fn pop_bgcolour(&mut self) -> bool {
false
}
/// Return an annotation and rendering prefix for superscript text
fn decorate_superscript_start(&self) -> (String, Self::Annotation) {
("^{".into(), Default::default())
}
/// Return a suffix for after a superscript.
fn decorate_superscript_end(&self) -> String {
"}".into()
}
/// Finish with a document, and return extra lines (eg footnotes)
/// to add to the rendered text.
fn finalise(&mut self, links: Vec<String>) -> Vec<TaggedLine<Self::Annotation>>;
}
/// A space on a horizontal row.
#[derive(Copy, Clone, Debug)]
pub enum BorderSegHoriz {
/// Pure horizontal line
Straight,
/// Joined with a line above
JoinAbove,
/// Joins with a line below
JoinBelow,
/// Joins both ways
JoinCross,
/// Horizontal line, but separating two table cells from a row
/// which wouldn't fit next to each other.
StraightVert,
}
/// A dividing line between table rows which tracks intersections
/// with vertical lines.
#[derive(Clone, Debug)]
pub struct BorderHoriz<T: Clone> {
/// The segments for the line.
pub segments: Vec<BorderSegHoriz>,
/// The tag associated with the lines
pub tag: T,
}
impl<T: Clone> BorderHoriz<T> {
/// Create a new blank border line.
pub fn new(width: usize, tag: T) -> Self {
BorderHoriz {
segments: vec![BorderSegHoriz::Straight; width],
tag,
}
}
/// Create a new blank border line.
pub fn new_type(width: usize, linetype: BorderSegHoriz, tag: T) -> Self {
BorderHoriz {
segments: vec![linetype; width],
tag,
}
}
/// Stretch the line to at least the specified width
pub fn stretch_to(&mut self, width: usize) {
use self::BorderSegHoriz::*;
while width > self.segments.len() {
self.segments.push(Straight);
}
}
/// Make a join to a line above at the xth cell
pub fn join_above(&mut self, x: usize) {
use self::BorderSegHoriz::*;
self.stretch_to(x + 1);
let prev = self.segments[x];
self.segments[x] = match prev {
Straight | JoinAbove => JoinAbove,
JoinBelow | JoinCross => JoinCross,
StraightVert => StraightVert,
}
}
/// Make a join to a line below at the xth cell
pub fn join_below(&mut self, x: usize) {
use self::BorderSegHoriz::*;
self.stretch_to(x + 1);
let prev = self.segments[x];
self.segments[x] = match prev {
Straight | JoinBelow => JoinBelow,
JoinAbove | JoinCross => JoinCross,
StraightVert => StraightVert,
}
}
/// Merge a (possibly partial) border line below into this one.
pub fn merge_from_below(&mut self, other: &BorderHoriz<T>, pos: usize) {
use self::BorderSegHoriz::*;
for (idx, seg) in other.segments.iter().enumerate() {
match *seg {
Straight | StraightVert => (),
JoinAbove | JoinBelow | JoinCross => {
self.join_below(idx + pos);
}
}
}
}
/// Merge a (possibly partial) border line above into this one.
pub fn merge_from_above(&mut self, other: &BorderHoriz<T>, pos: usize) {
use self::BorderSegHoriz::*;
for (idx, seg) in other.segments.iter().enumerate() {
match *seg {
Straight | StraightVert => (),
JoinAbove | JoinBelow | JoinCross => {
self.join_above(idx + pos);
}
}
}
}
/// Return a string of spaces and vertical lines which would match
/// just above this line.
pub fn to_vertical_lines_above(&self) -> String {
use self::BorderSegHoriz::*;
self.segments
.iter()
.map(|seg| match *seg {
Straight | JoinBelow | StraightVert => ' ',
JoinAbove | JoinCross => '│',
})
.collect()
}
/// Turn into a string with drawing characters
pub fn into_string(self) -> String {
self.segments
.into_iter()
.map(|seg| match seg {
BorderSegHoriz::Straight => '─',
BorderSegHoriz::StraightVert => '/',
BorderSegHoriz::JoinAbove => '┴',
BorderSegHoriz::JoinBelow => '┬',
BorderSegHoriz::JoinCross => '┼',
})
.collect::<String>()
}
/// Return a string without destroying self
pub fn to_string(&self) -> String {
self.clone().into_string()
}
}
/// A line, which can either be text or a line.
#[derive(Clone, Debug)]
pub enum RenderLine<T: PartialEq + Eq + Clone + Debug + Default> {
/// Some rendered text
Text(TaggedLine<T>),
/// A table border line
Line(BorderHoriz<T>),
}
impl<T: PartialEq + Eq + Clone + Debug + Default> RenderLine<T> {
/// Turn the rendered line into a String
pub fn into_string(self) -> String {
match self {
RenderLine::Text(tagged) => tagged.into_string(),
RenderLine::Line(border) => border.into_string(),
}
}
/// Convert into a `TaggedLine<T>`, if necessary squashing the
/// BorderHoriz into one.
pub fn into_tagged_line(self) -> TaggedLine<T> {
use self::TaggedLineElement::Str;
match self {
RenderLine::Text(tagged) => tagged,
RenderLine::Line(border) => {
let mut tagged = TaggedLine::new();
let tag = border.tag.clone();
tagged.push(Str(TaggedString {
s: border.into_string(),
tag,
}));
tagged
}
}
}
#[cfg(feature = "html_trace")]
/// For testing, return a simple string of the contents.
fn to_string(&self) -> String {
match self {
RenderLine::Text(tagged) => tagged.to_string(),
RenderLine::Line(border) => border.to_string(),
}
}
/// Return whether this line has any text content
/// Borders do not count as text.
fn has_content(&self) -> bool {
match self {
RenderLine::Text(line) => !line.is_empty(),
RenderLine::Line(_) => false,
}
}
}
/// A renderer which just outputs plain text with
/// annotations depending on a decorator.
#[derive(Clone)]
pub struct SubRenderer<D: TextDecorator> {
width: usize,
options: RenderOptions,
lines: LinkedList<RenderLine<Vec<D::Annotation>>>,
/// True at the end of a block, meaning we should add
/// a blank line if any other text is added.
at_block_end: bool,
wrapping: Option<WrappedBlock<Vec<D::Annotation>>>,
decorator: D,
ann_stack: Vec<D::Annotation>,
text_filter_stack: Vec<fn(&str) -> Option<String>>,
/// The depth of `<pre>` block stacking.
pre_depth: usize,
}
impl<D: TextDecorator + Debug> std::fmt::Debug for SubRenderer<D> {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
f.debug_struct("SubRenderer")
.field("width", &self.width)
.field("lines", &self.lines)
.field("decorator", &self.decorator)
.field("ann_stack", &self.ann_stack)
.field("pre_depth", &self.pre_depth)
.finish()
}
}
/// Rendering options.
#[derive(Clone)]
#[non_exhaustive]
pub struct RenderOptions {
/// The maximum text wrap width. If set, paragraphs of text will only be wrapped
/// to that width or less, though the overall width can be larger (e.g. for indented
/// blocks or side-by-side table cells).
pub wrap_width: Option<usize>,
/// The minimum text width to use when wrapping.
pub min_wrap_width: usize,
/// If true, then allow the output to be wider than specified instead of returning
/// `Err(TooNarrow)`.
pub allow_width_overflow: bool,
/// Whether to always pad lines out to the full width.
/// This may give a better output when the parent block
/// has a background colour set.
pub pad_block_width: bool,
}
impl Default for RenderOptions {
fn default() -> Self {
Self {
wrap_width: Default::default(),
min_wrap_width: crate::MIN_WIDTH,
allow_width_overflow: Default::default(),
pad_block_width: Default::default(),
}
}
}
impl<D: TextDecorator> SubRenderer<D> {
/// Render links as lines
pub fn finalise(&mut self, links: Vec<String>) -> Vec<TaggedLine<D::Annotation>> {
self.decorator.finalise(links)
}
/// Construct a new empty SubRenderer.
pub fn new(width: usize, options: RenderOptions, decorator: D) -> SubRenderer<D> {
html_trace!("new({})", width);
SubRenderer {
width,
options,
lines: LinkedList::new(),
at_block_end: false,
wrapping: None,
decorator,
ann_stack: Vec::new(),
pre_depth: 0,
text_filter_stack: Vec::new(),
}
}
fn ensure_wrapping_exists(&mut self) {
if self.wrapping.is_none() {
let wwidth = match self.options.wrap_width {
Some(ww) => ww.min(self.width),
None => self.width,
};
self.wrapping = Some(WrappedBlock::new(
wwidth,
self.options.pad_block_width,
self.options.allow_width_overflow,
));
}
}
/// Get the current line wrapping context (and create if
/// needed).
fn current_text(&mut self) -> &mut WrappedBlock<Vec<D::Annotation>> {
self.ensure_wrapping_exists();
self.wrapping.as_mut().unwrap()
}
/// Add a prerendered (multiline) string with the current annotations.
pub fn add_subblock(&mut self, s: &str) {
use self::TaggedLineElement::Str;
html_trace!("add_subblock({}, {})", self.width, s);
let tag = self.ann_stack.clone();
self.lines.extend(s.lines().map(|l| {
let mut line = TaggedLine::new();
line.push(Str(TaggedString {
s: l.into(),
tag: tag.clone(),
}));