Debian Codegraph @

helix-tui/src/widgets/paragraph.rs

raw symbols SCIP
1 use crate::{
2 buffer::Buffer,
3 layout::Alignment,
4 text::{StyledGrapheme, Text},
5 widgets::{
6 reflow::{LineComposer, LineTruncator, WordWrapper},
7 Block, Widget,
8 },
9 };
10 use helix_core::unicode::width::UnicodeWidthStr;
11 use helix_view::graphics::{Rect, Style};
12 use std::iter;
13
14 fn get_line_offset(line_width: u16, text_area_width: u16, alignment: Alignment) -> u16 {
15 match alignment {
16 Alignment::Center => (text_area_width / 2).saturating_sub(line_width / 2),
17 Alignment::Right => text_area_width.saturating_sub(line_width),
18 Alignment::Left => 0,
19 }
20 }
21
22 /// A widget to display some text.
23 ///
24 /// # Examples
25 ///
26 /// ```
27 /// # use helix_tui::text::{Text, Spans, Span};
28 /// # use helix_tui::widgets::{Block, Borders, Paragraph, Wrap};
29 /// # use helix_tui::layout::{Alignment};
30 /// # use helix_view::graphics::{Style, Color, Modifier};
31 /// let text = Text::from(vec![
32 /// Spans::from(vec![
33 /// Span::raw("First"),
34 /// Span::styled("line",Style::default().add_modifier(Modifier::ITALIC)),
35 /// Span::raw("."),
36 /// ]),
37 /// Spans::from(Span::styled("Second line", Style::default().fg(Color::Red))),
38 /// ]);
39 /// Paragraph::new(&text)
40 /// .block(Block::bordered().title("Paragraph"))
41 /// .style(Style::default().fg(Color::White).bg(Color::Black))
42 /// .alignment(Alignment::Center)
43 /// .wrap(Wrap { trim: true });
44 /// ```
45 #[derive(Debug, Clone)]
46 pub struct Paragraph<'a> {
47 /// A block to wrap the widget in
48 block: Option<Block<'a>>,
49 /// Widget style
50 style: Style,
51 /// How to wrap the text
52 wrap: Option<Wrap>,
53 /// The text to display
54 text: &'a Text<'a>,
55 /// Scroll
56 scroll: (u16, u16),
57 /// Alignment of the text
58 alignment: Alignment,
59 }
60
61 /// Describes how to wrap text across lines.
62 ///
63 /// ## Examples
64 ///
65 /// ```
66 /// # use helix_tui::widgets::{Paragraph, Wrap};
67 /// # use helix_tui::text::Text;
68 /// let bullet_points = Text::from(r#"Some indented points:
69 /// - First thing goes here and is long so that it wraps
70 /// - Here is another point that is long enough to wrap"#);
71 ///
72 /// // With leading spaces trimmed (window width of 30 chars):
73 /// Paragraph::new(&bullet_points).wrap(Wrap { trim: true });
74 /// // Some indented points:
75 /// // - First thing goes here and is
76 /// // long so that it wraps
77 /// // - Here is another point that
78 /// // is long enough to wrap
79 ///
80 /// // But without trimming, indentation is preserved:
81 /// Paragraph::new(&bullet_points).wrap(Wrap { trim: false });
82 /// // Some indented points:
83 /// // - First thing goes here
84 /// // and is long so that it wraps
85 /// // - Here is another point
86 /// // that is long enough to wrap
87 /// ```
88 #[derive(Debug, Clone, Copy)]
89 pub struct Wrap {
90 /// Should leading whitespace be trimmed
91 pub trim: bool,
92 }
93
94 impl<'a> Paragraph<'a> {
95 pub fn new(text: &'a Text) -> Paragraph<'a> {
96 Paragraph {
97 block: None,
98 style: Default::default(),
99 wrap: None,
100 text,
101 scroll: (0, 0),
102 alignment: Alignment::Left,
103 }
104 }
105
106 pub fn block(mut self, block: Block<'a>) -> Paragraph<'a> {
107 self.block = Some(block);
108 self
109 }
110
111 pub fn style(mut self, style: Style) -> Paragraph<'a> {
112 self.style = style;
113 self
114 }
115
116 pub fn wrap(mut self, wrap: Wrap) -> Paragraph<'a> {
117 self.wrap = Some(wrap);
118 self
119 }
120
121 pub fn scroll(mut self, offset: (u16, u16)) -> Paragraph<'a> {
122 self.scroll = offset;
123 self
124 }
125
126 pub fn alignment(mut self, alignment: Alignment) -> Paragraph<'a> {
127 self.alignment = alignment;
128 self
129 }
130
131 pub fn required_size(&self, max_text_width: u16) -> (u16, u16) {
132 let style = self.style;
133 let mut styled = self.text.lines.iter().flat_map(|spans| {
134 spans
135 .0
136 .iter()
137 .flat_map(|span| span.styled_graphemes(style))
138 // Required given the way composers work but might be refactored out if we change
139 // composers to operate on lines instead of a stream of graphemes.
140 .chain(iter::once(StyledGrapheme {
141 symbol: "\n",
142 style: self.style,
143 }))
144 });
145 let mut line_composer: Box<dyn LineComposer> = if let Some(Wrap { trim }) = self.wrap {
146 Box::new(WordWrapper::new(&mut styled, max_text_width, trim))
147 } else {
148 let mut line_composer = Box::new(LineTruncator::new(&mut styled, max_text_width));
149 if self.alignment == Alignment::Left {
150 line_composer.set_horizontal_offset(self.scroll.1);
151 }
152 line_composer
153 };
154 let mut text_width = 0;
155 let mut text_height = 0;
156 while let Some((_, line_width)) = line_composer.next_line() {
157 text_width = line_width.max(text_width);
158 text_height += 1;
159 }
160 (text_width, text_height)
161 }
162 }
163
164 impl Widget for Paragraph<'_> {
165 fn render(mut self, area: Rect, buf: &mut Buffer) {
166 buf.set_style(area, self.style);
167 let text_area = match self.block.take() {
168 Some(b) => {
169 let inner_area = b.inner(area);
170 b.render(area, buf);
171 inner_area
172 }
173 None => area,
174 };
175
176 if text_area.height < 1 {
177 return;
178 }
179
180 let style = self.style;
181 let mut styled = self.text.lines.iter().flat_map(|spans| {
182 spans
183 .0
184 .iter()
185 .flat_map(|span| span.styled_graphemes(style))
186 // Required given the way composers work but might be refactored out if we change
187 // composers to operate on lines instead of a stream of graphemes.
188 .chain(iter::once(StyledGrapheme {
189 symbol: "\n",
190 style: self.style,
191 }))
192 });
193
194 let mut line_composer: Box<dyn LineComposer> = if let Some(Wrap { trim }) = self.wrap {
195 Box::new(WordWrapper::new(&mut styled, text_area.width, trim))
196 } else {
197 let mut line_composer = Box::new(LineTruncator::new(&mut styled, text_area.width));
198 if self.alignment == Alignment::Left {
199 line_composer.set_horizontal_offset(self.scroll.1);
200 }
201 line_composer
202 };
203 let mut y = 0;
204 while let Some((current_line, current_line_width)) = line_composer.next_line() {
205 if y >= self.scroll.0 {
206 let mut x = get_line_offset(current_line_width, text_area.width, self.alignment);
207 for StyledGrapheme { symbol, style } in current_line {
208 buf[(text_area.left() + x, text_area.top() + y - self.scroll.0)]
209 .set_symbol(if symbol.is_empty() {
210 // If the symbol is empty, the last char which rendered last time will
211 // leave on the line. It's a quick fix.
212 " "
213 } else {
214 symbol
215 })
216 .set_style(*style);
217 x += symbol.width() as u16;
218 }
219 }
220 y += 1;
221 if y >= text_area.height + self.scroll.0 {
222 break;
223 }
224 }
225 }
226 }