liso 1.3.1

Line Input with Simultaneous Output: input lines are editable, output lines are never scrambled, and all of it thread safe.
Documentation
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
use super::*;

mod add_ansi;

/// An individual styled span within a line.
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct LineElement {
    /// The style in effect.
    pub(crate) style: Style,
    /// The foreground color (if any).
    pub(crate) fg: Option<Color>,
    /// The background color (if any).
    pub(crate) bg: Option<Color>,
    /// The start (inclusive) and end (exclusive) range of text within the
    /// parent `Line` to which these attributes apply.
    pub(crate) start: usize,
    pub(crate) end: usize,
}

/// This is a line of text, with optional styling information, ready for
/// display. The [`liso!`](macro.liso.html) macro is extremely convenient for
/// building these. You can also pass a `String`, `&str`, or `Cow<str>` to
/// most Liso functions that accept a `Line`.
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Line {
    pub(crate) text: String,
    pub(crate) elements: Vec<LineElement>,
}

impl Line {
    /// Creates a new, empty line.
    pub fn new() -> Line {
        Line {
            text: String::new(),
            elements: Vec::new(),
        }
    }
    /// Creates a new line, containing the given, unstyled, text. Creates a new
    /// copy iff the passed `Cow` is borrowed or contains control characters.
    pub fn from_cow(i: Cow<str>) -> Line {
        let mut ret = Line::new();
        ret.add_text(i);
        ret
    }
    /// Creates a new line, containing the given, unstyled, text. Always copies
    /// the passed string.
    ///
    /// Unlike the one from the `FromStr` trait, this function always succeeds.
    #[allow(clippy::should_implement_trait)]
    pub fn from_str(i: &str) -> Line {
        Line::from_cow(Cow::Borrowed(i))
    }
    /// Creates a new line, containing the given, unstyled, text. Creates a new
    /// copy iff the passed `String` contains control characters.
    pub fn from_string(i: String) -> Line {
        Line::from_cow(Cow::Owned(i))
    }
    /// Returns all the text in the line, without any styling information.
    pub fn as_str(&self) -> &str {
        &self.text
    }
    fn append_text(&mut self, i: Cow<str>) {
        if i.len() == 0 {
            return;
        }
        if self.text.is_empty() {
            // The line didn't have any text or elements yet.
            match self.elements.last_mut() {
                None => {
                    self.elements.push(LineElement {
                        style: Style::PLAIN,
                        fg: None,
                        bg: None,
                        start: 0,
                        end: i.len(),
                    });
                }
                Some(x) => {
                    assert_eq!(x.start, 0);
                    assert_eq!(x.end, 0);
                    x.end = i.len();
                }
            }
            self.text = i.into_owned();
        } else {
            // The line did have some text.
            let start = self.text.len();
            let end = start + i.len();
            self.text += &i[..];
            let endut = self.elements.last_mut().unwrap();
            assert_eq!(endut.end, start);
            endut.end = end;
        }
    }
    /// Adds additional text to the `Line` using the currently-active
    /// [`Style`][1] and [`Color`][2]s..
    ///
    /// You may pass a `String`, `&str`, or `Cow<str>` here, but not a `Line`.
    /// If you want to append styled text, see [`append_line`][3]. If you want
    /// to append the text from a `Line` but discard its style information,
    /// call [`as_str`][4] on that `Line`.
    ///
    /// [1]: struct.Style.html
    /// [2]: enum.Color.html
    /// [3]: #method.append_line
    /// [4]: #method.as_str
    pub fn add_text<'a, T>(&mut self, i: T) -> &mut Line
    where
        T: Into<Cow<'a, str>>,
    {
        let i: Cow<str> = i.into();
        if i.len() == 0 {
            return self;
        }
        // we regard as a control character anything in the C0 and C1 control
        // character blocks, as well as the U+2028 LINE SEPARATOR and
        // U+2029 PARAGRAPH SEPARATOR characters. Except newliso!
        let mut control_iterator = i.match_indices(|x: char| {
            (x.is_control() && x != '\n') || x == '\u{2028}' || x == '\u{2029}'
        });
        let first_control_pos = control_iterator.next();
        match first_control_pos {
            None => {
                // No control characters to expand. Put it in directly.
                self.append_text(i);
            }
            Some(mut pos) => {
                let mut plain_start = 0;
                loop {
                    if pos.0 != plain_start {
                        self.append_text(Cow::Borrowed(
                            &i[plain_start..pos.0],
                        ));
                    }
                    let control_char = pos.1.chars().next().unwrap();
                    self.toggle_style(Style::INVERSE);
                    let control_char = control_char as u32;
                    let addendum = if control_char < 32 {
                        format!("^{}", (b'@' + (control_char as u8)) as char)
                    } else {
                        format!("U+{:04X}", control_char)
                    };
                    self.append_text(Cow::Owned(addendum));
                    self.toggle_style(Style::INVERSE);
                    plain_start = pos.0 + pos.1.len();
                    match control_iterator.next() {
                        None => break,
                        Some(nu) => pos = nu,
                    }
                }
                if plain_start != i.len() {
                    self.append_text(Cow::Borrowed(&i[plain_start..]));
                }
            }
        }
        self
    }
    /// Returns the currently active [`Style`][1].
    ///
    /// [1]: struct.Style.html
    pub fn get_style(&self) -> Style {
        match self.elements.last() {
            None => Style::PLAIN,
            Some(x) => x.style,
        }
    }
    /// Change the active [`Style`][1] to exactly that given.
    ///
    /// [1]: struct.Style.html
    pub fn set_style(&mut self, nu: Style) -> &mut Line {
        let (fg, bg) = match self.elements.last_mut() {
            // case 1: no elements yet, make one.
            None => {
                // (fall through)
                (None, None)
            }
            Some(x) => {
                // case 2: no change to attributes
                if x.style == nu {
                    return self;
                }
                // case 3: last element doesn't have text yet.
                else if x.start == x.end {
                    x.style = nu;
                    return self;
                }
                (x.fg, x.bg)
            }
        };
        // (case 1 fall through, or...)
        // case 4: an element with text is here.
        self.elements.push(LineElement {
            style: nu,
            fg,
            bg,
            start: self.text.len(),
            end: self.text.len(),
        });
        self
    }
    /// Toggle every given [`Style`][1].
    ///
    /// [1]: struct.Style.html
    pub fn toggle_style(&mut self, nu: Style) -> &mut Line {
        let old = self.get_style();
        self.set_style(old ^ nu)
    }
    /// Activate the given [`Style`][1]s, leaving any already-active `Style`s
    /// active.
    ///
    /// [1]: struct.Style.html
    pub fn activate_style(&mut self, nu: Style) -> &mut Line {
        let old = self.get_style();
        self.set_style(old | nu)
    }
    /// Deactivate the given [`Style`][1]s, without touching any unmentioned
    /// `Style`s that were already active.
    ///
    /// [1]: struct.Style.html
    pub fn deactivate_style(&mut self, nu: Style) -> &mut Line {
        let old = self.get_style();
        self.set_style(old - nu)
    }
    /// Deactivate *all* [`Style`][1]s. Same as calling
    /// `set_style(Style::PLAIN)`.
    ///
    /// [1]: struct.Style.html
    pub fn clear_style(&mut self) -> &mut Line {
        self.set_style(Style::PLAIN)
    }
    /// Gets the current [`Color`][1]s, both foreground and background.
    ///
    /// [1]: enum.Color.html
    pub fn get_colors(&self) -> (Option<Color>, Option<Color>) {
        match self.elements.last() {
            None => (None, None),
            Some(x) => (x.fg, x.bg),
        }
    }
    /// Sets the foreground [`Color`][1].
    ///
    /// [1]: enum.Color.html
    pub fn set_fg_color(&mut self, nu: Option<Color>) -> &mut Line {
        let (fg, bg) = self.get_colors();
        if nu != fg {
            self.set_colors(nu, bg);
        }
        self
    }
    /// Sets the background [`Color`][1].
    ///
    /// [1]: enum.Color.html
    pub fn set_bg_color(&mut self, nu: Option<Color>) -> &mut Line {
        let (fg, bg) = self.get_colors();
        if nu != bg {
            self.set_colors(fg, nu);
        }
        self
    }
    /// Sets both the foreground and background [`Color`][1].
    ///
    /// [1]: enum.Color.html
    pub fn set_colors(
        &mut self,
        fg: Option<Color>,
        bg: Option<Color>,
    ) -> &mut Line {
        let prev_style = match self.elements.last_mut() {
            // case 1: no elements yet, make one.
            None => Style::PLAIN,
            Some(x) => {
                // case 2: no change to style
                if x.fg == fg && x.bg == bg {
                    return self;
                }
                // case 3: last element doesn't have text yet.
                else if x.start == x.end {
                    x.fg = fg;
                    x.bg = bg;
                    return self;
                }
                x.style
            }
        };
        // (case 1 fall through, or...)
        // case 3: an element with text is here.
        self.elements.push(LineElement {
            style: prev_style,
            fg,
            bg,
            start: self.text.len(),
            end: self.text.len(),
        });
        self
    }
    /// Reset ALL [`Style`][1] and [`Color`][2] information to default.
    /// Equivalent to:
    ///
    /// ```
    /// # use liso::Style;
    /// # let mut line = liso::Line::new();
    /// # liso::liso_add!(line, fg=green, bg=red, underline);
    /// line.set_style(Style::PLAIN).set_colors(None, None);
    /// # assert_eq!(line, liso::liso!(plain, fg=none, bg=none));
    /// ```
    ///
    /// (In fact, that is the body of this function.)
    ///
    /// [1]: struct.Style.html
    /// [2]: enum.Color.html
    pub fn reset_all(&mut self) -> &mut Line {
        self.set_style(Style::PLAIN).set_colors(None, None)
    }
    /// Returns true if this line contains no text. (It may yet contain some
    /// [`Style`][1] or [`Color`][2] information.)
    ///
    /// [1]: struct.Style.html
    /// [2]: enum.Color.html
    pub fn is_empty(&self) -> bool {
        self.text.is_empty()
    }
    /// Returns the number of **BYTES** of text this line contains.
    pub fn len(&self) -> usize {
        self.text.len()
    }
    /// Iterate over chars of the line, including [`Style`][1] and [`Color`][2]
    /// information, one `char` at a time.
    ///
    /// The usual caveats about the difference between a `char` and a character
    /// apply. Unicode etc.
    ///
    /// Yields: `(byte_index, character, style, fgcolor, bgcolor)`
    ///
    /// [1]: struct.Style.html
    /// [2]: enum.Color.html
    pub fn chars(&self) -> LineCharIterator<'_> {
        LineCharIterator::new(self)
    }
    /// Add a linebreak and then clear [`Style`][1] and [`Color`][2]s.
    ///
    /// Equivalent to:
    ///
    /// ```
    /// # use liso::Style;
    /// # let mut line = liso::Line::new();
    /// # liso::liso_add!(line, fg=green, bg=red, underline);
    /// line.add_text("\n");
    /// line.set_style(Style::empty());
    /// line.set_colors(None, None);
    /// # assert_eq!(line, liso::liso!(fg=green, bg=red, underline,
    /// #   "\n", reset));
    /// ```
    ///
    /// (In fact, that is the body of this function.)
    ///
    /// [1]: struct.Style.html
    /// [2]: enum.Color.html
    pub fn reset_and_break(&mut self) {
        self.add_text("\n");
        self.set_style(Style::empty());
        self.set_colors(None, None);
    }
    /// Append another Line to ourselves, including [`Style`][1] and
    /// [`Color`][2] information. You may want to [`reset_and_break`][3] first.
    ///
    /// [1]: struct.Style.html
    /// [2]: enum.Color.html
    /// [3]: #method.reset_and_break
    pub fn append_line(&mut self, other: &Line) {
        for element in other.elements.iter() {
            self.set_style(element.style);
            self.set_colors(element.fg, element.bg);
            self.add_text(&other.text[element.start..element.end]);
        }
    }
    /// Insert linebreaks as necessary to make it so that no line within this
    /// `Line` is wider than the given number of columns. Only available with
    /// the `wrap` feature, which is enabled by default.
    ///
    /// Rather than calling this method yourself, you definitely want to use
    /// the [`wrapln`](struct.Output.html#method.wrapln) method instead of the
    /// [`println`](struct.Output.html#method.println) method. That way, Liso
    /// will automatically wrap the line of text to the correct width for the
    /// user's terminal.
    #[cfg(feature = "wrap")]
    pub fn wrap_to_width(&mut self, width: usize) {
        assert!(width > 0);
        let newline_positions: Vec<usize> = self
            .text
            .chars()
            .enumerate()
            .filter_map(|(n, c)| if c == '\n' { Some(n) } else { None })
            .chain(Some(self.text.len()))
            .collect();
        let start_iter = newline_positions
            .iter()
            .rev()
            .skip(1)
            .map(|x| *x + 1)
            .chain(Some(0usize));
        let end_iter = newline_positions.iter().rev();
        for (start, &end) in start_iter.zip(end_iter) {
            if start >= end {
                continue;
            }
            let wrap_vec = textwrap::wrap(&self.text[start..end], width);
            let mut edit_vec = Vec::with_capacity(wrap_vec.len());
            let mut cur_end = start;
            for el in wrap_vec.into_iter() {
                // We're pretty sure we didn't use any features that would require
                // an owned Cow. In fact, if we're wrong, the whole feature won't
                // work.
                let slice = match el {
                    Cow::Borrowed(x) => x,
                    Cow::Owned(_) => {
                        panic!("We needed textwrap to do borrows only!")
                    }
                };
                let (start, end) =
                    convert_subset_slice_to_range(&self.text, slice);
                debug_assert!(start <= end);
                if start == end {
                    continue;
                }
                assert!(start >= cur_end);
                if start != 0 {
                    edit_vec.push(cur_end..start);
                }
                cur_end = end;
            }
            for range in edit_vec.into_iter().rev() {
                if range.start > 0
                    && self.text.as_bytes()[range.start - 1] == b'\n'
                {
                    continue;
                }
                self.erase_and_insert_newline(range);
            }
        }
    }
    // Internal use only.
    #[cfg(feature = "wrap")]
    fn erase_and_insert_newline(&mut self, range: std::ops::Range<usize>) {
        let delta_bytes = 1 - (range.end as isize - range.start as isize);
        self.text.replace_range(range.clone(), "\n");
        let mut elements_len = self.elements.len();
        let mut i = self.elements.len();
        loop {
            if i == 0 {
                break;
            }
            i -= 1;
            let element = &mut self.elements[i];
            if element.end >= range.end {
                element.end = ((element.end as isize) + delta_bytes) as usize;
            } else if element.end > range.start {
                element.end = range.start;
            }
            if element.start >= range.end {
                element.start =
                    ((element.start as isize) + delta_bytes) as usize;
            } else if element.start > range.start {
                element.start = range.start;
            }
            if element.end <= element.start {
                if i == elements_len - 1 {
                    // preserve the last element, even if empty
                    element.end = element.start;
                } else {
                    self.elements.remove(i);
                    elements_len -= 1;
                    continue;
                }
            }
            if element.start >= range.start {
                break; // all subsequent elements will be before the edit
            }
        }
    }
}

impl Default for Line {
    fn default() -> Self {
        Self::new()
    }
}

impl From<String> for Line {
    fn from(val: String) -> Self {
        Line::from_string(val)
    }
}

impl From<&str> for Line {
    fn from(val: &str) -> Self {
        Line::from_str(val)
    }
}

impl From<Cow<'_, str>> for Line {
    fn from(val: Cow<'_, str>) -> Self {
        Line::from_cow(val)
    }
}

impl FromStr for Line {
    type Err = ();
    fn from_str(s: &str) -> Result<Self, Self::Err> {
        Ok(Line::from_str(s))
    }
}
/// Allows you to iterate over the characters in a [`Line`](struct.Line.html),
/// one at a time, along with their [`Style`][1] and [`Color`][2] information.
/// This is returned by [`Line::chars()`](struct.Line.html#method.chars).
///
/// [1]: struct.Style.html
/// [2]: enum.Color.html
pub struct LineCharIterator<'a> {
    line: &'a Line,
    cur_element: usize,
    indices: std::str::CharIndices<'a>,
}

/// A single character from a `Line`, along with the byte index it begins at,
/// and the [`Style`][1] and [`Color`][2]s it would be displayed with. This is
/// yielded by [`LineCharIterator`](struct.LineCharIterator.html), which is
/// returned by [`Line::chars()`](struct.Line.html#method.chars).
///
/// [1]: struct.Style.html
/// [2]: enum.Color.html
#[derive(Clone, Copy, Debug)]
pub struct LineChar {
    /// Byte index within the `Line` of the first byte of this `char`.
    pub index: usize,
    /// The actual `char`. This is an individual Unicode code point. *Most*
    /// code points correspond to single *characters*, but some are combining
    /// characters (which change the rendering of nearby printable characters),
    /// and some are invisible. And even the code points that are single
    /// *characters* don't correspond to single *graphemes*. (This uncertainty
    /// applies to all uses of Unicode, including other places in Rust where
    /// you have a `char`.)
    pub ch: char,
    /// [`Style`](struct.Style.html) (bold, inverse, etc.) that would be used
    /// to display this `char`.
    pub style: Style,
    /// Foreground [`Color`](enum.Color.html) that would be used to display
    /// this `char`.
    pub fg: Option<Color>,
    /// Background [`Color`](enum.Color.html) that would be used to display
    /// this `char`.
    pub bg: Option<Color>,
}

impl PartialEq for LineChar {
    fn eq(&self, other: &LineChar) -> bool {
        self.ch == other.ch
            && self.style == other.style
            && self.fg == other.fg
            && self.bg == other.bg
    }
}

impl LineChar {
    /// Returns true if it is definitely impossible to distinguish spaces
    /// printed in the style of both `LineChar`s, false if it might be possible
    /// to distinguish them. Used to optimize endfill when overwriting one line
    /// with another. You probably don't need this method, but in case you do,
    /// here it is.
    ///
    /// In cases whether the answer depends on the specific terminal, returns
    /// false, to be safe. One example is going from inverse video with a
    /// foreground color to non-inverse video with the corresponding background
    /// color. (Some terminals will display the same color differently
    /// depending on whether it's foreground or background, and some of those
    /// terminals implement inverse by simply swapping foreground and
    /// background, therefore we can't count on them looking the same just
    /// because the color indices are the same.)
    pub fn endfills_same_as(&self, other: &LineChar) -> bool {
        let a_underline = self.style.contains(Style::UNDERLINE);
        let b_underline = other.style.contains(Style::UNDERLINE);
        if a_underline != b_underline {
            return false;
        }
        debug_assert_eq!(a_underline, b_underline);
        let a_inverse = self.style.contains(Style::INVERSE);
        let b_inverse = other.style.contains(Style::INVERSE);
        if a_inverse != b_inverse {
            false
        } else if a_inverse {
            debug_assert!(b_inverse);
            if a_underline && self.bg != other.bg {
                return false;
            }
            self.fg == other.fg
        } else {
            debug_assert!(!a_inverse);
            debug_assert!(!b_inverse);
            if a_underline && self.fg != other.fg {
                return false;
            }
            self.bg == other.bg
        }
    }
}

impl<'a> LineCharIterator<'a> {
    fn new(line: &'a Line) -> LineCharIterator<'a> {
        LineCharIterator {
            line,
            cur_element: 0,
            indices: line.text.char_indices(),
        }
    }
}

impl Iterator for LineCharIterator<'_> {
    type Item = LineChar;
    fn next(&mut self) -> Option<LineChar> {
        let (index, ch) = match self.indices.next() {
            Some(x) => x,
            None => return None,
        };
        while self.cur_element < self.line.elements.len()
            && self.line.elements[self.cur_element].end <= index
        {
            self.cur_element += 1;
        }
        // We should never end up with text in the text string that is not
        // covered by an element.
        debug_assert!(self.cur_element < self.line.elements.len());
        let element = &self.line.elements[self.cur_element];
        Some(LineChar {
            index,
            ch,
            style: element.style,
            fg: element.fg,
            bg: element.bg,
        })
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    #[test]
    fn control_char_splatting() {
        let mut line = Line::new();
        line.add_text(
            "Escape: \u{001B} Some C1 code: \u{008C} \
                       Paragraph separator: \u{2029}",
        );
        assert_eq!(
            line.text,
            "Escape: ^[ Some C1 code: U+008C \
                    Paragraph separator: U+2029"
        );
        assert_eq!(line.elements.len(), 7);
        assert_eq!(line.elements[0].style, Style::PLAIN);
        assert_eq!(line.elements[1].style, Style::INVERSE);
        assert_eq!(line.elements[2].style, Style::PLAIN);
    }
    const MY_BLUE: Option<Color> = Some(Color::Blue);
    const MY_RED: Option<Color> = Some(Color::Red);
    #[test]
    fn line_macro() {
        let mut line = Line::new();
        line.add_text("This is a test");
        line.set_fg_color(Some(Color::Blue));
        line.add_text(" of BLUE TESTS!");
        line.set_fg_color(Some(Color::Red));
        line.add_text(" And RED TESTS!");
        line.set_bg_color(Some(Color::Blue));
        line.add_text(" Now with backgrounds,");
        line.set_bg_color(Some(Color::Red));
        line.add_text(" and other backgrounds!");
        let alt_line = liso![
            "This is a test",
            fg = Blue,
            " of BLUE TESTS!",
            fg = MY_RED,
            " And RED TESTS!",
            bg = MY_BLUE,
            " Now with backgrounds,",
            bg = red,
            " and other backgrounds!",
        ];
        assert_eq!(line, alt_line);
    }
    #[test]
    #[cfg(feature = "wrap")]
    fn line_wrap() {
        let mut line = liso!["This is a simple line wrapping test."];
        line.wrap_to_width(20);
        assert_eq!(line, liso!["This is a simple\nline wrapping test."]);
    }
    #[test]
    #[cfg(feature = "wrap")]
    fn line_wrap_splat() {
        for n in 1..200 {
            let mut line =
                liso!["This is ", bold, "a test", plain, " of line wrapping?"];
            line.wrap_to_width(n);
        }
    }
    #[test]
    #[cfg(feature = "wrap")]
    fn lange_wrap() {
        let mut line = liso!["This is a simple line wrapping test.\n\nIt has two newlines in it."];
        line.wrap_to_width(20);
        assert_eq!(
            line,
            liso!["This is a simple\nline wrapping test.\n\nIt has two newlines\nin it."]
        );
    }
    #[test]
    #[cfg(feature = "wrap")]
    fn sehr_lagne_wrap() {
        const UNWRAPPED: &str = r#"Mike House was Gegory Houses' borther. He was a world renounced doctor from England, London. His arm was cut off in a fetal MIR incident so he had to walk around with a segway. When he leaned forward, the segway would go real fast. One day, Mike House had a new case for his crack team of other doctors that were pretty good, but not as good as Mike House. So Mike House told them, "WE HAVE A NEW CASE!" And the team said, "ALRIGHT!" And then Mike House said, "IF WE DO NOT SAVE HIM, HE WILL DIE!""#;
        const WRAPPED: &str = r#"Mike House was
Gegory Houses'
borther. He was
a world renounced
doctor from England,
London. His arm was
cut off in a fetal
MIR incident so he
had to walk around
with a segway. When
he leaned forward,
the segway would
go real fast. One
day, Mike House
had a new case for
his crack team of
other doctors that
were pretty good,
but not as good as
Mike House. So Mike
House told them, "WE
HAVE A NEW CASE!"
And the team said,
"ALRIGHT!" And then
Mike House said, "IF
WE DO NOT SAVE HIM,
HE WILL DIE!""#;
        let mut line = Line::from_str(UNWRAPPED);
        line.wrap_to_width(20);
        assert_eq!(line.text, WRAPPED);
        assert_eq!(line.elements.last().unwrap().end, line.text.len());
    }
    #[test]
    #[cfg(feature = "wrap")]
    fn non_synthetic_wrap() {
        let src_line = liso!(bold, fg=yellow, "WARNING: ", reset, "\"/home/sbizna/././././././././nobackup/eph/deleteme/d\" and \"/home/sbizna/././././././././nobackup/eph/deleteme/b\" were identical, but will have differing permissions!");
        let dst_line = liso!(bold, fg=yellow, "WARNING: ", reset, "\"/home/sbizna/././././././././nobackup/eph/deleteme/d\" and \"/home/\nsbizna/././././././././nobackup/eph/deleteme/b\" were identical, but will have\ndiffering permissions!");
        let mut line = src_line.clone();
        line.wrap_to_width(80);
        assert_eq!(line, dst_line);
    }
}