ratatui/widgets/
paragraph.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
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
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
use unicode_width::UnicodeWidthStr;

use crate::{
    buffer::Buffer,
    layout::{Alignment, Position, Rect},
    style::{Style, Styled},
    text::{Line, StyledGrapheme, Text},
    widgets::{
        block::BlockExt,
        reflow::{LineComposer, LineTruncator, WordWrapper, WrappedLine},
        Block, Widget, WidgetRef,
    },
};

const fn get_line_offset(line_width: u16, text_area_width: u16, alignment: Alignment) -> u16 {
    match alignment {
        Alignment::Center => (text_area_width / 2).saturating_sub(line_width / 2),
        Alignment::Right => text_area_width.saturating_sub(line_width),
        Alignment::Left => 0,
    }
}

/// A widget to display some text.
///
/// It is used to display a block of text. The text can be styled and aligned. It can also be
/// wrapped to the next line if it is too long to fit in the given area.
///
/// The text can be any type that can be converted into a [`Text`]. By default, the text is styled
/// with [`Style::default()`], not wrapped, and aligned to the left.
///
/// The text can be wrapped to the next line if it is too long to fit in the given area. The
/// wrapping can be configured with the [`wrap`] method. For more complex wrapping, consider using
/// the [Textwrap crate].
///
/// The text can be aligned to the left, right, or center. The alignment can be configured with the
/// [`alignment`] method or with the [`left_aligned`], [`right_aligned`], and [`centered`] methods.
///
/// The text can be scrolled to show a specific part of the text. The scroll offset can be set with
/// the [`scroll`] method.
///
/// The text can be surrounded by a [`Block`] with a title and borders. The block can be configured
/// with the [`block`] method.
///
/// The style of the text can be set with the [`style`] method. This style will be applied to the
/// entire widget, including the block if one is present. Any style set on the block or text will be
/// added to this style. See the [`Style`] type for more information on how styles are combined.
///
/// Note: If neither wrapping or a block is needed, consider rendering the [`Text`], [`Line`], or
/// [`Span`] widgets directly.
///
/// [Textwrap crate]: https://crates.io/crates/textwrap
/// [`wrap`]: Self::wrap
/// [`alignment`]: Self::alignment
/// [`left_aligned`]: Self::left_aligned
/// [`right_aligned`]: Self::right_aligned
/// [`centered`]: Self::centered
/// [`scroll`]: Self::scroll
/// [`block`]: Self::block
/// [`style`]: Self::style
///
/// # Example
///
/// ```
/// use ratatui::{
///     layout::Alignment,
///     style::{Style, Stylize},
///     text::{Line, Span},
///     widgets::{Block, Paragraph, Wrap},
/// };
///
/// let text = vec![
///     Line::from(vec![
///         Span::raw("First"),
///         Span::styled("line", Style::new().green().italic()),
///         ".".into(),
///     ]),
///     Line::from("Second line".red()),
///     "Third line".into(),
/// ];
/// Paragraph::new(text)
///     .block(Block::bordered().title("Paragraph"))
///     .style(Style::new().white().on_black())
///     .alignment(Alignment::Center)
///     .wrap(Wrap { trim: true });
/// ```
///
/// [`Span`]: crate::text::Span
#[derive(Debug, Default, Clone, Eq, PartialEq, Hash)]
pub struct Paragraph<'a> {
    /// A block to wrap the widget in
    block: Option<Block<'a>>,
    /// Widget style
    style: Style,
    /// How to wrap the text
    wrap: Option<Wrap>,
    /// The text to display
    text: Text<'a>,
    /// Scroll
    scroll: Position,
    /// Alignment of the text
    alignment: Alignment,
}

/// Describes how to wrap text across lines.
///
/// ## Examples
///
/// ```
/// use ratatui::{
///     text::Text,
///     widgets::{Paragraph, Wrap},
/// };
///
/// let bullet_points = Text::from(
///     r#"Some indented points:
///     - First thing goes here and is long so that it wraps
///     - Here is another point that is long enough to wrap"#,
/// );
///
/// // With leading spaces trimmed (window width of 30 chars):
/// Paragraph::new(bullet_points.clone()).wrap(Wrap { trim: true });
/// // Some indented points:
/// // - First thing goes here and is
/// // long so that it wraps
/// // - Here is another point that
/// // is long enough to wrap
///
/// // But without trimming, indentation is preserved:
/// Paragraph::new(bullet_points).wrap(Wrap { trim: false });
/// // Some indented points:
/// //     - First thing goes here
/// // and is long so that it wraps
/// //     - Here is another point
/// // that is long enough to wrap
/// ```
#[derive(Debug, Default, Clone, Copy, Eq, PartialEq, Hash)]
pub struct Wrap {
    /// Should leading whitespace be trimmed
    pub trim: bool,
}

type Horizontal = u16;
type Vertical = u16;

impl<'a> Paragraph<'a> {
    /// Creates a new [`Paragraph`] widget with the given text.
    ///
    /// The `text` parameter can be a [`Text`] or any type that can be converted into a [`Text`]. By
    /// default, the text is styled with [`Style::default()`], not wrapped, and aligned to the left.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use ratatui::{
    ///     style::{Style, Stylize},
    ///     text::{Line, Text},
    ///     widgets::Paragraph,
    /// };
    ///
    /// let paragraph = Paragraph::new("Hello, world!");
    /// let paragraph = Paragraph::new(String::from("Hello, world!"));
    /// let paragraph = Paragraph::new(Text::raw("Hello, world!"));
    /// let paragraph = Paragraph::new(Text::styled("Hello, world!", Style::default()));
    /// let paragraph = Paragraph::new(Line::from(vec!["Hello, ".into(), "world!".red()]));
    /// ```
    pub fn new<T>(text: T) -> Self
    where
        T: Into<Text<'a>>,
    {
        Self {
            block: None,
            style: Style::default(),
            wrap: None,
            text: text.into(),
            scroll: Position::ORIGIN,
            alignment: Alignment::Left,
        }
    }

    /// Surrounds the [`Paragraph`] widget with a [`Block`].
    ///
    /// # Example
    ///
    /// ```rust
    /// use ratatui::widgets::{Block, Paragraph};
    ///
    /// let paragraph = Paragraph::new("Hello, world!").block(Block::bordered().title("Paragraph"));
    /// ```
    #[must_use = "method moves the value of self and returns the modified value"]
    pub fn block(mut self, block: Block<'a>) -> Self {
        self.block = Some(block);
        self
    }

    /// Sets the style of the entire widget.
    ///
    /// `style` accepts any type that is convertible to [`Style`] (e.g. [`Style`], [`Color`], or
    /// your own type that implements [`Into<Style>`]).
    ///
    /// This applies to the entire widget, including the block if one is present. Any style set on
    /// the block or text will be added to this style.
    ///
    /// # Example
    ///
    /// ```rust
    /// use ratatui::{
    ///     style::{Style, Stylize},
    ///     widgets::Paragraph,
    /// };
    ///
    /// let paragraph = Paragraph::new("Hello, world!").style(Style::new().red().on_white());
    /// ```
    ///
    /// [`Color`]: crate::style::Color
    #[must_use = "method moves the value of self and returns the modified value"]
    pub fn style<S: Into<Style>>(mut self, style: S) -> Self {
        self.style = style.into();
        self
    }

    /// Sets the wrapping configuration for the widget.
    ///
    /// See [`Wrap`] for more information on the different options.
    ///
    /// # Example
    ///
    /// ```rust
    /// use ratatui::widgets::{Paragraph, Wrap};
    ///
    /// let paragraph = Paragraph::new("Hello, world!").wrap(Wrap { trim: true });
    /// ```
    #[must_use = "method moves the value of self and returns the modified value"]
    pub const fn wrap(mut self, wrap: Wrap) -> Self {
        self.wrap = Some(wrap);
        self
    }

    /// Set the scroll offset for the given paragraph
    ///
    /// The scroll offset is a tuple of (y, x) offset. The y offset is the number of lines to
    /// scroll, and the x offset is the number of characters to scroll. The scroll offset is applied
    /// after the text is wrapped and aligned.
    ///
    /// Note: the order of the tuple is (y, x) instead of (x, y), which is different from general
    /// convention across the crate.
    ///
    /// For more information about future scrolling design and concerns, see [RFC: Design of
    /// Scrollable Widgets](https://github.com/ratatui/ratatui/issues/174) on GitHub.
    #[must_use = "method moves the value of self and returns the modified value"]
    pub const fn scroll(mut self, offset: (Vertical, Horizontal)) -> Self {
        self.scroll = Position {
            x: offset.1,
            y: offset.0,
        };
        self
    }

    /// Set the text alignment for the given paragraph
    ///
    /// The alignment is a variant of the [`Alignment`] enum which can be one of Left, Right, or
    /// Center. If no alignment is specified, the text in a paragraph will be left-aligned.
    ///
    /// # Example
    ///
    /// ```rust
    /// use ratatui::{layout::Alignment, widgets::Paragraph};
    ///
    /// let paragraph = Paragraph::new("Hello World").alignment(Alignment::Center);
    /// ```
    #[must_use = "method moves the value of self and returns the modified value"]
    pub const fn alignment(mut self, alignment: Alignment) -> Self {
        self.alignment = alignment;
        self
    }

    /// Left-aligns the text in the given paragraph.
    ///
    /// Convenience shortcut for `Paragraph::alignment(Alignment::Left)`.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use ratatui::widgets::Paragraph;
    ///
    /// let paragraph = Paragraph::new("Hello World").left_aligned();
    /// ```
    #[must_use = "method moves the value of self and returns the modified value"]
    pub const fn left_aligned(self) -> Self {
        self.alignment(Alignment::Left)
    }

    /// Center-aligns the text in the given paragraph.
    ///
    /// Convenience shortcut for `Paragraph::alignment(Alignment::Center)`.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use ratatui::widgets::Paragraph;
    ///
    /// let paragraph = Paragraph::new("Hello World").centered();
    /// ```
    #[must_use = "method moves the value of self and returns the modified value"]
    pub const fn centered(self) -> Self {
        self.alignment(Alignment::Center)
    }

    /// Right-aligns the text in the given paragraph.
    ///
    /// Convenience shortcut for `Paragraph::alignment(Alignment::Right)`.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use ratatui::widgets::Paragraph;
    ///
    /// let paragraph = Paragraph::new("Hello World").right_aligned();
    /// ```
    #[must_use = "method moves the value of self and returns the modified value"]
    pub const fn right_aligned(self) -> Self {
        self.alignment(Alignment::Right)
    }

    /// Calculates the number of lines needed to fully render.
    ///
    /// Given a max line width, this method calculates the number of lines that a paragraph will
    /// need in order to be fully rendered. For paragraphs that do not use wrapping, this count is
    /// simply the number of lines present in the paragraph.
    ///
    /// This method will also account for the [`Block`] if one is set through [`Self::block`].
    ///
    /// Note: The design for text wrapping is not stable and might affect this API.
    ///
    /// # Example
    ///
    /// ```ignore
    /// use ratatui::{widgets::{Paragraph, Wrap}};
    ///
    /// let paragraph = Paragraph::new("Hello World")
    ///     .wrap(Wrap { trim: false });
    /// assert_eq!(paragraph.line_count(20), 1);
    /// assert_eq!(paragraph.line_count(10), 2);
    /// ```
    #[instability::unstable(
        feature = "rendered-line-info",
        issue = "https://github.com/ratatui/ratatui/issues/293"
    )]
    pub fn line_count(&self, width: u16) -> usize {
        if width < 1 {
            return 0;
        }

        let (top, bottom) = self
            .block
            .as_ref()
            .map(Block::vertical_space)
            .unwrap_or_default();

        let count = if let Some(Wrap { trim }) = self.wrap {
            let styled = self.text.iter().map(|line| {
                let graphemes = line
                    .spans
                    .iter()
                    .flat_map(|span| span.styled_graphemes(self.style));
                let alignment = line.alignment.unwrap_or(self.alignment);
                (graphemes, alignment)
            });
            let mut line_composer = WordWrapper::new(styled, width, trim);
            let mut count = 0;
            while line_composer.next_line().is_some() {
                count += 1;
            }
            count
        } else {
            self.text.height()
        };

        count
            .saturating_add(top as usize)
            .saturating_add(bottom as usize)
    }

    /// Calculates the shortest line width needed to avoid any word being wrapped or truncated.
    ///
    /// Accounts for the [`Block`] if a block is set through [`Self::block`].
    ///
    /// Note: The design for text wrapping is not stable and might affect this API.
    ///
    /// # Example
    ///
    /// ```ignore
    /// use ratatui::{widgets::Paragraph};
    ///
    /// let paragraph = Paragraph::new("Hello World");
    /// assert_eq!(paragraph.line_width(), 11);
    ///
    /// let paragraph = Paragraph::new("Hello World\nhi\nHello World!!!");
    /// assert_eq!(paragraph.line_width(), 14);
    /// ```
    #[instability::unstable(
        feature = "rendered-line-info",
        issue = "https://github.com/ratatui/ratatui/issues/293"
    )]
    pub fn line_width(&self) -> usize {
        let width = self.text.iter().map(Line::width).max().unwrap_or_default();
        let (left, right) = self
            .block
            .as_ref()
            .map(Block::horizontal_space)
            .unwrap_or_default();

        width
            .saturating_add(left as usize)
            .saturating_add(right as usize)
    }
}

impl Widget for Paragraph<'_> {
    fn render(self, area: Rect, buf: &mut Buffer) {
        self.render_ref(area, buf);
    }
}

impl WidgetRef for Paragraph<'_> {
    fn render_ref(&self, area: Rect, buf: &mut Buffer) {
        buf.set_style(area, self.style);
        self.block.render_ref(area, buf);
        let inner = self.block.inner_if_some(area);
        self.render_paragraph(inner, buf);
    }
}

impl Paragraph<'_> {
    fn render_paragraph(&self, text_area: Rect, buf: &mut Buffer) {
        if text_area.is_empty() {
            return;
        }

        buf.set_style(text_area, self.style);
        let styled = self.text.iter().map(|line| {
            let graphemes = line.styled_graphemes(self.text.style);
            let alignment = line.alignment.unwrap_or(self.alignment);
            (graphemes, alignment)
        });

        if let Some(Wrap { trim }) = self.wrap {
            let line_composer = WordWrapper::new(styled, text_area.width, trim);
            self.render_text(line_composer, text_area, buf);
        } else {
            let mut line_composer = LineTruncator::new(styled, text_area.width);
            line_composer.set_horizontal_offset(self.scroll.x);
            self.render_text(line_composer, text_area, buf);
        }
    }
}

impl<'a> Paragraph<'a> {
    fn render_text<C: LineComposer<'a>>(&self, mut composer: C, area: Rect, buf: &mut Buffer) {
        let mut y = 0;
        while let Some(WrappedLine {
            line: current_line,
            width: current_line_width,
            alignment: current_line_alignment,
        }) = composer.next_line()
        {
            if y >= self.scroll.y {
                let mut x = get_line_offset(current_line_width, area.width, current_line_alignment);
                for StyledGrapheme { symbol, style } in current_line {
                    let width = symbol.width();
                    if width == 0 {
                        continue;
                    }
                    // If the symbol is empty, the last char which rendered last time will
                    // leave on the line. It's a quick fix.
                    let symbol = if symbol.is_empty() { " " } else { symbol };
                    buf[(area.left() + x, area.top() + y - self.scroll.y)]
                        .set_symbol(symbol)
                        .set_style(*style);
                    x += width as u16;
                }
            }
            y += 1;
            if y >= area.height + self.scroll.y {
                break;
            }
        }
    }
}

impl<'a> Styled for Paragraph<'a> {
    type Item = Self;

    fn style(&self) -> Style {
        self.style
    }

    fn set_style<S: Into<Style>>(self, style: S) -> Self::Item {
        self.style(style)
    }
}

#[cfg(test)]
mod test {
    use super::*;
    use crate::{
        backend::TestBackend,
        buffer::Buffer,
        layout::{Alignment, Rect},
        style::{Color, Modifier, Style, Stylize},
        text::{Line, Span, Text},
        widgets::{block::Position, Borders, Widget},
        Terminal,
    };

    /// Tests the [`Paragraph`] widget against the expected [`Buffer`] by rendering it onto an equal
    /// area and comparing the rendered and expected content.
    /// This can be used for easy testing of varying configured paragraphs with the same expected
    /// buffer or any other test case really.
    #[track_caller]
    fn test_case(paragraph: &Paragraph, expected: &Buffer) {
        let backend = TestBackend::new(expected.area.width, expected.area.height);
        let mut terminal = Terminal::new(backend).unwrap();
        terminal
            .draw(|f| f.render_widget(paragraph.clone(), f.area()))
            .unwrap();
        terminal.backend().assert_buffer(expected);
    }

    #[test]
    fn zero_width_char_at_end_of_line() {
        let line = "foo\u{200B}";
        for paragraph in [
            Paragraph::new(line),
            Paragraph::new(line).wrap(Wrap { trim: false }),
            Paragraph::new(line).wrap(Wrap { trim: true }),
        ] {
            test_case(&paragraph, &Buffer::with_lines(["foo"]));
            test_case(&paragraph, &Buffer::with_lines(["foo   "]));
            test_case(&paragraph, &Buffer::with_lines(["foo   ", "      "]));
            test_case(&paragraph, &Buffer::with_lines(["foo", "   "]));
        }
    }

    #[test]
    fn test_render_empty_paragraph() {
        for paragraph in [
            Paragraph::new(""),
            Paragraph::new("").wrap(Wrap { trim: false }),
            Paragraph::new("").wrap(Wrap { trim: true }),
        ] {
            test_case(&paragraph, &Buffer::with_lines([" "]));
            test_case(&paragraph, &Buffer::with_lines(["          "]));
            test_case(&paragraph, &Buffer::with_lines(["     "; 10]));
            test_case(&paragraph, &Buffer::with_lines([" ", " "]));
        }
    }

    #[test]
    fn test_render_single_line_paragraph() {
        let text = "Hello, world!";
        for paragraph in [
            Paragraph::new(text),
            Paragraph::new(text).wrap(Wrap { trim: false }),
            Paragraph::new(text).wrap(Wrap { trim: true }),
        ] {
            test_case(&paragraph, &Buffer::with_lines(["Hello, world!  "]));
            test_case(&paragraph, &Buffer::with_lines(["Hello, world!"]));
            test_case(
                &paragraph,
                &Buffer::with_lines(["Hello, world!  ", "               "]),
            );
            test_case(
                &paragraph,
                &Buffer::with_lines(["Hello, world!", "             "]),
            );
        }
    }

    #[test]
    fn test_render_multi_line_paragraph() {
        let text = "This is a\nmultiline\nparagraph.";
        for paragraph in [
            Paragraph::new(text),
            Paragraph::new(text).wrap(Wrap { trim: false }),
            Paragraph::new(text).wrap(Wrap { trim: true }),
        ] {
            test_case(
                &paragraph,
                &Buffer::with_lines(["This is a ", "multiline ", "paragraph."]),
            );
            test_case(
                &paragraph,
                &Buffer::with_lines(["This is a      ", "multiline      ", "paragraph.     "]),
            );
            test_case(
                &paragraph,
                &Buffer::with_lines([
                    "This is a      ",
                    "multiline      ",
                    "paragraph.     ",
                    "               ",
                    "               ",
                ]),
            );
        }
    }

    #[test]
    fn test_render_paragraph_with_block() {
        // We use the slightly unconventional "worlds" instead of "world" here to make sure when we
        // can truncate this without triggering the typos linter.
        let text = "Hello, worlds!";
        let truncated_paragraph = Paragraph::new(text).block(Block::bordered().title("Title"));
        let wrapped_paragraph = truncated_paragraph.clone().wrap(Wrap { trim: false });
        let trimmed_paragraph = truncated_paragraph.clone().wrap(Wrap { trim: true });

        for paragraph in [&truncated_paragraph, &wrapped_paragraph, &trimmed_paragraph] {
            #[rustfmt::skip]
            test_case(
                paragraph,
                &Buffer::with_lines([
                    "┌Title─────────┐",
                    "│Hello, worlds!│",
                    "└──────────────┘",
                ]),
            );
            test_case(
                paragraph,
                &Buffer::with_lines([
                    "┌Title───────────┐",
                    "│Hello, worlds!  │",
                    "└────────────────┘",
                ]),
            );
            test_case(
                paragraph,
                &Buffer::with_lines([
                    "┌Title────────────┐",
                    "│Hello, worlds!   │",
                    "│                 │",
                    "└─────────────────┘",
                ]),
            );
        }

        test_case(
            &truncated_paragraph,
            &Buffer::with_lines([
                "┌Title───────┐",
                "│Hello, world│",
                "│            │",
                "└────────────┘",
            ]),
        );
        test_case(
            &wrapped_paragraph,
            &Buffer::with_lines([
                "┌Title──────┐",
                "│Hello,     │",
                "│worlds!    │",
                "└───────────┘",
            ]),
        );
        test_case(
            &trimmed_paragraph,
            &Buffer::with_lines([
                "┌Title──────┐",
                "│Hello,     │",
                "│worlds!    │",
                "└───────────┘",
            ]),
        );
    }

    #[test]
    fn test_render_line_styled() {
        let l0 = Line::raw("unformatted");
        let l1 = Line::styled("bold text", Style::new().bold());
        let l2 = Line::styled("cyan text", Style::new().cyan());
        let l3 = Line::styled("dim text", Style::new().dim());
        let paragraph = Paragraph::new(vec![l0, l1, l2, l3]);

        let mut expected =
            Buffer::with_lines(["unformatted", "bold text", "cyan text", "dim text"]);
        expected.set_style(Rect::new(0, 1, 9, 1), Style::new().bold());
        expected.set_style(Rect::new(0, 2, 9, 1), Style::new().cyan());
        expected.set_style(Rect::new(0, 3, 8, 1), Style::new().dim());

        test_case(&paragraph, &expected);
    }

    #[test]
    fn test_render_line_spans_styled() {
        let l0 = Line::default().spans([
            Span::styled("bold", Style::new().bold()),
            Span::raw(" and "),
            Span::styled("cyan", Style::new().cyan()),
        ]);
        let l1 = Line::default().spans([Span::raw("unformatted")]);
        let paragraph = Paragraph::new(vec![l0, l1]);

        let mut expected = Buffer::with_lines(["bold and cyan", "unformatted"]);
        expected.set_style(Rect::new(0, 0, 4, 1), Style::new().bold());
        expected.set_style(Rect::new(9, 0, 4, 1), Style::new().cyan());

        test_case(&paragraph, &expected);
    }

    #[test]
    fn test_render_paragraph_with_block_with_bottom_title_and_border() {
        let block = Block::new()
            .borders(Borders::BOTTOM)
            .title_position(Position::Bottom)
            .title("Title");
        let paragraph = Paragraph::new("Hello, world!").block(block);
        test_case(
            &paragraph,
            &Buffer::with_lines(["Hello, world!  ", "Title──────────"]),
        );
    }

    #[test]
    fn test_render_paragraph_with_word_wrap() {
        let text = "This is a long line of text that should wrap      and contains a superultramegagigalong word.";
        let wrapped_paragraph = Paragraph::new(text).wrap(Wrap { trim: false });
        let trimmed_paragraph = Paragraph::new(text).wrap(Wrap { trim: true });

        test_case(
            &wrapped_paragraph,
            &Buffer::with_lines([
                "This is a long line",
                "of text that should",
                "wrap      and      ",
                "contains a         ",
                "superultramegagigal",
                "ong word.          ",
            ]),
        );
        test_case(
            &wrapped_paragraph,
            &Buffer::with_lines([
                "This is a   ",
                "long line of",
                "text that   ",
                "should wrap ",
                "    and     ",
                "contains a  ",
                "superultrame",
                "gagigalong  ",
                "word.       ",
            ]),
        );

        test_case(
            &trimmed_paragraph,
            &Buffer::with_lines([
                "This is a long line",
                "of text that should",
                "wrap      and      ",
                "contains a         ",
                "superultramegagigal",
                "ong word.          ",
            ]),
        );
        test_case(
            &trimmed_paragraph,
            &Buffer::with_lines([
                "This is a   ",
                "long line of",
                "text that   ",
                "should wrap ",
                "and contains",
                "a           ",
                "superultrame",
                "gagigalong  ",
                "word.       ",
            ]),
        );
    }

    #[test]
    fn test_render_paragraph_with_line_truncation() {
        let text = "This is a long line of text that should be truncated.";
        let truncated_paragraph = Paragraph::new(text);

        test_case(
            &truncated_paragraph,
            &Buffer::with_lines(["This is a long line of"]),
        );
        test_case(
            &truncated_paragraph,
            &Buffer::with_lines(["This is a long line of te"]),
        );
        test_case(
            &truncated_paragraph,
            &Buffer::with_lines(["This is a long line of "]),
        );
        test_case(
            &truncated_paragraph.clone().scroll((0, 2)),
            &Buffer::with_lines(["is is a long line of te"]),
        );
    }

    #[test]
    fn test_render_paragraph_with_left_alignment() {
        let text = "Hello, world!";
        let truncated_paragraph = Paragraph::new(text).alignment(Alignment::Left);
        let wrapped_paragraph = truncated_paragraph.clone().wrap(Wrap { trim: false });
        let trimmed_paragraph = truncated_paragraph.clone().wrap(Wrap { trim: true });

        for paragraph in [&truncated_paragraph, &wrapped_paragraph, &trimmed_paragraph] {
            test_case(paragraph, &Buffer::with_lines(["Hello, world!  "]));
            test_case(paragraph, &Buffer::with_lines(["Hello, world!"]));
        }

        test_case(&truncated_paragraph, &Buffer::with_lines(["Hello, wor"]));
        test_case(
            &wrapped_paragraph,
            &Buffer::with_lines(["Hello,    ", "world!    "]),
        );
        test_case(
            &trimmed_paragraph,
            &Buffer::with_lines(["Hello,    ", "world!    "]),
        );
    }

    #[test]
    fn test_render_paragraph_with_center_alignment() {
        let text = "Hello, world!";
        let truncated_paragraph = Paragraph::new(text).alignment(Alignment::Center);
        let wrapped_paragraph = truncated_paragraph.clone().wrap(Wrap { trim: false });
        let trimmed_paragraph = truncated_paragraph.clone().wrap(Wrap { trim: true });

        for paragraph in [&truncated_paragraph, &wrapped_paragraph, &trimmed_paragraph] {
            test_case(paragraph, &Buffer::with_lines([" Hello, world! "]));
            test_case(paragraph, &Buffer::with_lines(["  Hello, world! "]));
            test_case(paragraph, &Buffer::with_lines(["  Hello, world!  "]));
            test_case(paragraph, &Buffer::with_lines(["Hello, world!"]));
        }

        test_case(&truncated_paragraph, &Buffer::with_lines(["Hello, wor"]));
        test_case(
            &wrapped_paragraph,
            &Buffer::with_lines(["  Hello,  ", "  world!  "]),
        );
        test_case(
            &trimmed_paragraph,
            &Buffer::with_lines(["  Hello,  ", "  world!  "]),
        );
    }

    #[test]
    fn test_render_paragraph_with_right_alignment() {
        let text = "Hello, world!";
        let truncated_paragraph = Paragraph::new(text).alignment(Alignment::Right);
        let wrapped_paragraph = truncated_paragraph.clone().wrap(Wrap { trim: false });
        let trimmed_paragraph = truncated_paragraph.clone().wrap(Wrap { trim: true });

        for paragraph in [&truncated_paragraph, &wrapped_paragraph, &trimmed_paragraph] {
            test_case(paragraph, &Buffer::with_lines(["  Hello, world!"]));
            test_case(paragraph, &Buffer::with_lines(["Hello, world!"]));
        }

        test_case(&truncated_paragraph, &Buffer::with_lines(["Hello, wor"]));
        test_case(
            &wrapped_paragraph,
            &Buffer::with_lines(["    Hello,", "    world!"]),
        );
        test_case(
            &trimmed_paragraph,
            &Buffer::with_lines(["    Hello,", "    world!"]),
        );
    }

    #[test]
    fn test_render_paragraph_with_scroll_offset() {
        let text = "This is a\ncool\nmultiline\nparagraph.";
        let truncated_paragraph = Paragraph::new(text).scroll((2, 0));
        let wrapped_paragraph = truncated_paragraph.clone().wrap(Wrap { trim: false });
        let trimmed_paragraph = truncated_paragraph.clone().wrap(Wrap { trim: true });

        for paragraph in [&truncated_paragraph, &wrapped_paragraph, &trimmed_paragraph] {
            test_case(
                paragraph,
                &Buffer::with_lines(["multiline   ", "paragraph.  ", "            "]),
            );
            test_case(paragraph, &Buffer::with_lines(["multiline   "]));
        }

        test_case(
            &truncated_paragraph.clone().scroll((2, 4)),
            &Buffer::with_lines(["iline   ", "graph.  "]),
        );
        test_case(
            &wrapped_paragraph,
            &Buffer::with_lines(["cool   ", "multili", "ne     "]),
        );
    }

    #[test]
    fn test_render_paragraph_with_zero_width_area() {
        let text = "Hello, world!";
        let area = Rect::new(0, 0, 0, 3);

        for paragraph in [
            Paragraph::new(text),
            Paragraph::new(text).wrap(Wrap { trim: false }),
            Paragraph::new(text).wrap(Wrap { trim: true }),
        ] {
            test_case(&paragraph, &Buffer::empty(area));
            test_case(&paragraph.clone().scroll((2, 4)), &Buffer::empty(area));
        }
    }

    #[test]
    fn test_render_paragraph_with_zero_height_area() {
        let text = "Hello, world!";
        let area = Rect::new(0, 0, 10, 0);

        for paragraph in [
            Paragraph::new(text),
            Paragraph::new(text).wrap(Wrap { trim: false }),
            Paragraph::new(text).wrap(Wrap { trim: true }),
        ] {
            test_case(&paragraph, &Buffer::empty(area));
            test_case(&paragraph.clone().scroll((2, 4)), &Buffer::empty(area));
        }
    }

    #[test]
    fn test_render_paragraph_with_styled_text() {
        let text = Line::from(vec![
            Span::styled("Hello, ", Style::default().fg(Color::Red)),
            Span::styled("world!", Style::default().fg(Color::Blue)),
        ]);

        let mut expected_buffer = Buffer::with_lines(["Hello, world!"]);
        expected_buffer.set_style(
            Rect::new(0, 0, 7, 1),
            Style::default().fg(Color::Red).bg(Color::Green),
        );
        expected_buffer.set_style(
            Rect::new(7, 0, 6, 1),
            Style::default().fg(Color::Blue).bg(Color::Green),
        );

        for paragraph in [
            Paragraph::new(text.clone()),
            Paragraph::new(text.clone()).wrap(Wrap { trim: false }),
            Paragraph::new(text.clone()).wrap(Wrap { trim: true }),
        ] {
            test_case(
                &paragraph.style(Style::default().bg(Color::Green)),
                &expected_buffer,
            );
        }
    }

    #[test]
    fn test_render_paragraph_with_special_characters() {
        let text = "Hello, <world>!";
        for paragraph in [
            Paragraph::new(text),
            Paragraph::new(text).wrap(Wrap { trim: false }),
            Paragraph::new(text).wrap(Wrap { trim: true }),
        ] {
            test_case(&paragraph, &Buffer::with_lines(["Hello, <world>!"]));
            test_case(&paragraph, &Buffer::with_lines(["Hello, <world>!     "]));
            test_case(
                &paragraph,
                &Buffer::with_lines(["Hello, <world>!     ", "                    "]),
            );
            test_case(
                &paragraph,
                &Buffer::with_lines(["Hello, <world>!", "               "]),
            );
        }
    }

    #[test]
    fn test_render_paragraph_with_unicode_characters() {
        let text = "こんにちは, 世界! 😃";
        let truncated_paragraph = Paragraph::new(text);
        let wrapped_paragraph = Paragraph::new(text).wrap(Wrap { trim: false });
        let trimmed_paragraph = Paragraph::new(text).wrap(Wrap { trim: true });

        for paragraph in [&truncated_paragraph, &wrapped_paragraph, &trimmed_paragraph] {
            test_case(paragraph, &Buffer::with_lines(["こんにちは, 世界! 😃"]));
            test_case(
                paragraph,
                &Buffer::with_lines(["こんにちは, 世界! 😃     "]),
            );
        }

        test_case(
            &truncated_paragraph,
            &Buffer::with_lines(["こんにちは, 世 "]),
        );
        test_case(
            &wrapped_paragraph,
            &Buffer::with_lines(["こんにちは,    ", "世界! 😃      "]),
        );
        test_case(
            &trimmed_paragraph,
            &Buffer::with_lines(["こんにちは,    ", "世界! 😃      "]),
        );
    }

    #[test]
    fn can_be_stylized() {
        assert_eq!(
            Paragraph::new("").black().on_white().bold().not_dim().style,
            Style::default()
                .fg(Color::Black)
                .bg(Color::White)
                .add_modifier(Modifier::BOLD)
                .remove_modifier(Modifier::DIM)
        );
    }

    #[test]
    fn widgets_paragraph_count_rendered_lines() {
        let paragraph = Paragraph::new("Hello World");
        assert_eq!(paragraph.line_count(20), 1);
        assert_eq!(paragraph.line_count(10), 1);
        let paragraph = Paragraph::new("Hello World").wrap(Wrap { trim: false });
        assert_eq!(paragraph.line_count(20), 1);
        assert_eq!(paragraph.line_count(10), 2);
        let paragraph = Paragraph::new("Hello World").wrap(Wrap { trim: true });
        assert_eq!(paragraph.line_count(20), 1);
        assert_eq!(paragraph.line_count(10), 2);

        let text = "Hello World ".repeat(100);
        let paragraph = Paragraph::new(text.trim());
        assert_eq!(paragraph.line_count(11), 1);
        assert_eq!(paragraph.line_count(6), 1);
        let paragraph = paragraph.wrap(Wrap { trim: false });
        assert_eq!(paragraph.line_count(11), 100);
        assert_eq!(paragraph.line_count(6), 200);
        let paragraph = paragraph.wrap(Wrap { trim: true });
        assert_eq!(paragraph.line_count(11), 100);
        assert_eq!(paragraph.line_count(6), 200);
    }

    #[test]
    fn widgets_paragraph_rendered_line_count_accounts_block() {
        let block = Block::new();
        let paragraph = Paragraph::new("Hello World").block(block);
        assert_eq!(paragraph.line_count(20), 1);
        assert_eq!(paragraph.line_count(10), 1);

        let block = Block::new().borders(Borders::TOP);
        let paragraph = paragraph.block(block);
        assert_eq!(paragraph.line_count(20), 2);
        assert_eq!(paragraph.line_count(10), 2);

        let block = Block::new().borders(Borders::BOTTOM);
        let paragraph = paragraph.block(block);
        assert_eq!(paragraph.line_count(20), 2);
        assert_eq!(paragraph.line_count(10), 2);

        let block = Block::new().borders(Borders::TOP | Borders::BOTTOM);
        let paragraph = paragraph.block(block);
        assert_eq!(paragraph.line_count(20), 3);
        assert_eq!(paragraph.line_count(10), 3);

        let block = Block::bordered();
        let paragraph = paragraph.block(block);
        assert_eq!(paragraph.line_count(20), 3);
        assert_eq!(paragraph.line_count(10), 3);

        let block = Block::bordered();
        let paragraph = paragraph.block(block).wrap(Wrap { trim: true });
        assert_eq!(paragraph.line_count(20), 3);
        assert_eq!(paragraph.line_count(10), 4);

        let block = Block::bordered();
        let paragraph = paragraph.block(block).wrap(Wrap { trim: false });
        assert_eq!(paragraph.line_count(20), 3);
        assert_eq!(paragraph.line_count(10), 4);

        let text = "Hello World ".repeat(100);
        let block = Block::new();
        let paragraph = Paragraph::new(text.trim()).block(block);
        assert_eq!(paragraph.line_count(11), 1);

        let block = Block::bordered();
        let paragraph = paragraph.block(block);
        assert_eq!(paragraph.line_count(11), 3);
        assert_eq!(paragraph.line_count(6), 3);

        let block = Block::new().borders(Borders::TOP);
        let paragraph = paragraph.block(block);
        assert_eq!(paragraph.line_count(11), 2);
        assert_eq!(paragraph.line_count(6), 2);

        let block = Block::new().borders(Borders::BOTTOM);
        let paragraph = paragraph.block(block);
        assert_eq!(paragraph.line_count(11), 2);
        assert_eq!(paragraph.line_count(6), 2);

        let block = Block::new().borders(Borders::LEFT | Borders::RIGHT);
        let paragraph = paragraph.block(block);
        assert_eq!(paragraph.line_count(11), 1);
        assert_eq!(paragraph.line_count(6), 1);
    }

    #[test]
    fn widgets_paragraph_line_width() {
        let paragraph = Paragraph::new("Hello World");
        assert_eq!(paragraph.line_width(), 11);
        let paragraph = Paragraph::new("Hello World").wrap(Wrap { trim: false });
        assert_eq!(paragraph.line_width(), 11);
        let paragraph = Paragraph::new("Hello World").wrap(Wrap { trim: true });
        assert_eq!(paragraph.line_width(), 11);

        let text = "Hello World ".repeat(100);
        let paragraph = Paragraph::new(text);
        assert_eq!(paragraph.line_width(), 1200);
        let paragraph = paragraph.wrap(Wrap { trim: false });
        assert_eq!(paragraph.line_width(), 1200);
        let paragraph = paragraph.wrap(Wrap { trim: true });
        assert_eq!(paragraph.line_width(), 1200);
    }

    #[test]
    fn widgets_paragraph_line_width_accounts_for_block() {
        let block = Block::bordered();
        let paragraph = Paragraph::new("Hello World").block(block);
        assert_eq!(paragraph.line_width(), 13);

        let block = Block::new().borders(Borders::LEFT);
        let paragraph = Paragraph::new("Hello World").block(block);
        assert_eq!(paragraph.line_width(), 12);

        let block = Block::new().borders(Borders::LEFT);
        let paragraph = Paragraph::new("Hello World")
            .block(block)
            .wrap(Wrap { trim: true });
        assert_eq!(paragraph.line_width(), 12);

        let block = Block::new().borders(Borders::LEFT);
        let paragraph = Paragraph::new("Hello World")
            .block(block)
            .wrap(Wrap { trim: false });
        assert_eq!(paragraph.line_width(), 12);
    }

    #[test]
    fn left_aligned() {
        let p = Paragraph::new("Hello, world!").left_aligned();
        assert_eq!(p.alignment, Alignment::Left);
    }

    #[test]
    fn centered() {
        let p = Paragraph::new("Hello, world!").centered();
        assert_eq!(p.alignment, Alignment::Center);
    }

    #[test]
    fn right_aligned() {
        let p = Paragraph::new("Hello, world!").right_aligned();
        assert_eq!(p.alignment, Alignment::Right);
    }

    /// Regression test for <https://github.com/ratatui/ratatui/issues/990>
    ///
    /// This test ensures that paragraphs with a block and styled text are rendered correctly.
    /// It has been simplified from the original issue but tests the same functionality.
    #[test]
    fn paragraph_block_text_style() {
        let text = Text::styled("Styled text", Color::Green);
        let paragraph = Paragraph::new(text).block(Block::bordered());

        let mut buf = Buffer::empty(Rect::new(0, 0, 20, 3));
        paragraph.render(Rect::new(0, 0, 20, 3), &mut buf);

        let mut expected = Buffer::with_lines([
            "┌──────────────────┐",
            "│Styled text       │",
            "└──────────────────┘",
        ]);
        expected.set_style(Rect::new(1, 1, 11, 1), Style::default().fg(Color::Green));
        assert_eq!(buf, expected);
    }
}