Debian Codegraph @

helix-tui/src/text.rs

raw symbols SCIP
1 //! Primitives for styled text.
2 //!
3 //! A terminal UI is at its root a lot of strings. In order to make it accessible and stylish,
4 //! those strings may be associated to a set of styles. `tui` has three ways to represent them:
5 //! - A single line string where all graphemes have the same style is represented by a [`Span`].
6 //! - A single line string where each grapheme may have its own style is represented by [`Spans`].
7 //! - A multiple line string where each grapheme may have its own style is represented by a
8 //! [`Text`].
9 //!
10 //! These types form a hierarchy: [`Spans`] is a collection of [`Span`] and each line of [`Text`]
11 //! is a [`Spans`].
12 //!
13 //! Keep in mind that a lot of widgets will use those types to advertise what kind of string is
14 //! supported for their properties. Moreover, `tui` provides convenient `From` implementations so
15 //! that you can start by using simple `String` or `&str` and then promote them to the previous
16 //! primitives when you need additional styling capabilities.
17 //!
18 //! For example, for the [`crate::widgets::Block`] widget, all the following calls are valid to set
19 //! its `title` property (which is a [`Spans`] under the hood):
20 //!
21 //! ```rust
22 //! # use helix_tui::widgets::Block;
23 //! # use helix_tui::text::{Span, Spans};
24 //! # use helix_view::graphics::{Color, Style};
25 //! // A simple string with no styling.
26 //! // Converted to Spans(vec![
27 //! // Span { content: Cow::Borrowed("My title"), style: Style { .. } }
28 //! // ])
29 //! let block = Block::default().title("My title");
30 //!
31 //! // A simple string with a unique style.
32 //! // Converted to Spans(vec![
33 //! // Span { content: Cow::Borrowed("My title"), style: Style { fg: Some(Color::Yellow), .. }
34 //! // ])
35 //! let block = Block::default().title(
36 //! Span::styled("My title", Style::default().fg(Color::Yellow))
37 //! );
38 //!
39 //! // A string with multiple styles.
40 //! // Converted to Spans(vec![
41 //! // Span { content: Cow::Borrowed("My"), style: Style { fg: Some(Color::Yellow), .. } },
42 //! // Span { content: Cow::Borrowed(" title"), .. }
43 //! // ])
44 //! let block = Block::default().title(vec![
45 //! Span::styled("My", Style::default().fg(Color::Yellow)),
46 //! Span::raw(" title"),
47 //! ]);
48 //! ```
49 use helix_core::line_ending::str_is_line_ending;
50 use helix_core::unicode::width::UnicodeWidthStr;
51 use helix_view::graphics::Style;
52 use std::borrow::Cow;
53 use unicode_segmentation::UnicodeSegmentation;
54
55 /// A grapheme associated to a style.
56 #[derive(Debug, Clone, PartialEq, Eq)]
57 pub struct StyledGrapheme<'a> {
58 pub symbol: &'a str,
59 pub style: Style,
60 }
61
62 /// A string where all graphemes have the same style.
63 #[derive(Debug, Clone, PartialEq, Eq)]
64 pub struct Span<'a> {
65 pub content: Cow<'a, str>,
66 pub style: Style,
67 }
68
69 impl<'a> Span<'a> {
70 /// Create a span with no style.
71 ///
72 /// ## Examples
73 ///
74 /// ```rust
75 /// # use helix_tui::text::Span;
76 /// Span::raw("My text");
77 /// Span::raw(String::from("My text"));
78 /// ```
79 pub fn raw<T>(content: T) -> Span<'a>
80 where
81 T: Into<Cow<'a, str>>,
82 {
83 Span {
84 content: content.into(),
85 style: Style::default(),
86 }
87 }
88
89 /// Create a span with a style.
90 ///
91 /// # Examples
92 ///
93 /// ```rust
94 /// # use helix_tui::text::Span;
95 /// # use helix_view::graphics::{Color, Modifier, Style};
96 /// let style = Style::default().fg(Color::Yellow).add_modifier(Modifier::ITALIC);
97 /// Span::styled("My text", style);
98 /// Span::styled(String::from("My text"), style);
99 /// ```
100 pub fn styled<T>(content: T, style: Style) -> Span<'a>
101 where
102 T: Into<Cow<'a, str>>,
103 {
104 Span {
105 content: content.into(),
106 style,
107 }
108 }
109
110 /// Returns the width of the content held by this span.
111 pub fn width(&self) -> usize {
112 self.content.width()
113 }
114
115 /// Returns an iterator over the graphemes held by this span.
116 ///
117 /// `base_style` is the [`Style`] that will be patched with each grapheme [`Style`] to get
118 /// the resulting [`Style`].
119 ///
120 /// ## Examples
121 ///
122 /// ```rust
123 /// # use helix_tui::text::{Span, StyledGrapheme};
124 /// # use helix_view::graphics::{Color, Modifier, Style};
125 /// # use std::iter::Iterator;
126 /// let style = Style::default().fg(Color::Yellow);
127 /// let span = Span::styled("Text", style);
128 /// let style = Style::default().fg(Color::Green).bg(Color::Black);
129 /// let styled_graphemes = span.styled_graphemes(style);
130 /// assert_eq!(
131 /// vec![
132 /// StyledGrapheme {
133 /// symbol: "T",
134 /// style: Style {
135 /// fg: Some(Color::Yellow),
136 /// bg: Some(Color::Black),
137 /// underline_color: None,
138 /// underline_style: None,
139 /// add_modifier: Modifier::empty(),
140 /// sub_modifier: Modifier::empty(),
141 /// },
142 /// },
143 /// StyledGrapheme {
144 /// symbol: "e",
145 /// style: Style {
146 /// fg: Some(Color::Yellow),
147 /// bg: Some(Color::Black),
148 /// underline_color: None,
149 /// underline_style: None,
150 /// add_modifier: Modifier::empty(),
151 /// sub_modifier: Modifier::empty(),
152 /// },
153 /// },
154 /// StyledGrapheme {
155 /// symbol: "x",
156 /// style: Style {
157 /// fg: Some(Color::Yellow),
158 /// bg: Some(Color::Black),
159 /// underline_color: None,
160 /// underline_style: None,
161 /// add_modifier: Modifier::empty(),
162 /// sub_modifier: Modifier::empty(),
163 /// },
164 /// },
165 /// StyledGrapheme {
166 /// symbol: "t",
167 /// style: Style {
168 /// fg: Some(Color::Yellow),
169 /// bg: Some(Color::Black),
170 /// underline_color: None,
171 /// underline_style: None,
172 /// add_modifier: Modifier::empty(),
173 /// sub_modifier: Modifier::empty(),
174 /// },
175 /// },
176 /// ],
177 /// styled_graphemes.collect::<Vec<StyledGrapheme>>()
178 /// );
179 /// ```
180 pub fn styled_graphemes(
181 &'a self,
182 base_style: Style,
183 ) -> impl Iterator<Item = StyledGrapheme<'a>> {
184 UnicodeSegmentation::graphemes(self.content.as_ref(), true)
185 .map(move |g| StyledGrapheme {
186 symbol: g,
187 style: base_style.patch(self.style),
188 })
189 .filter(|s| !str_is_line_ending(s.symbol))
190 }
191 }
192
193 impl<'a> From<String> for Span<'a> {
194 fn from(s: String) -> Span<'a> {
195 Span::raw(s)
196 }
197 }
198
199 impl<'a> From<&'a str> for Span<'a> {
200 fn from(s: &'a str) -> Span<'a> {
201 Span::raw(s)
202 }
203 }
204
205 impl<'a> From<Cow<'a, str>> for Span<'a> {
206 fn from(s: Cow<'a, str>) -> Span<'a> {
207 Span::raw(s)
208 }
209 }
210
211 /// A string composed of clusters of graphemes, each with their own style.
212 #[derive(Debug, Default, Clone, PartialEq, Eq)]
213 pub struct Spans<'a>(pub Vec<Span<'a>>);
214
215 impl Spans<'_> {
216 /// Returns the width of the underlying string.
217 ///
218 /// ## Examples
219 ///
220 /// ```rust
221 /// # use helix_tui::text::{Span, Spans};
222 /// # use helix_view::graphics::{Color, Style};
223 /// let spans = Spans::from(vec![
224 /// Span::styled("My", Style::default().fg(Color::Yellow)),
225 /// Span::raw(" text"),
226 /// ]);
227 /// assert_eq!(7, spans.width());
228 /// ```
229 pub fn width(&self) -> usize {
230 self.0.iter().map(Span::width).sum()
231 }
232 }
233
234 impl<'a> From<String> for Spans<'a> {
235 fn from(s: String) -> Spans<'a> {
236 Spans(vec![Span::from(s)])
237 }
238 }
239
240 impl<'a> From<&'a str> for Spans<'a> {
241 fn from(s: &'a str) -> Spans<'a> {
242 Spans(vec![Span::from(s)])
243 }
244 }
245
246 impl<'a> From<Cow<'a, str>> for Spans<'a> {
247 fn from(s: Cow<'a, str>) -> Spans<'a> {
248 Spans(vec![Span::raw(s)])
249 }
250 }
251
252 impl<'a> From<Vec<Span<'a>>> for Spans<'a> {
253 fn from(spans: Vec<Span<'a>>) -> Spans<'a> {
254 Spans(spans)
255 }
256 }
257
258 impl<'a> From<Span<'a>> for Spans<'a> {
259 fn from(span: Span<'a>) -> Spans<'a> {
260 Spans(vec![span])
261 }
262 }
263
264 impl<'a> From<Spans<'a>> for String {
265 fn from(line: Spans<'a>) -> String {
266 line.0.iter().map(|s| &*s.content).collect()
267 }
268 }
269
270 impl<'a> From<&Spans<'a>> for String {
271 fn from(line: &Spans<'a>) -> String {
272 line.0.iter().map(|s| &*s.content).collect()
273 }
274 }
275
276 /// A string split over multiple lines where each line is composed of several clusters, each with
277 /// their own style.
278 ///
279 /// A [`Text`], like a [`Span`], can be constructed using one of the many `From` implementations
280 /// or via the [`Text::raw`] and [`Text::styled`] methods. Helpfully, [`Text`] also implements
281 /// [`core::iter::Extend`] which enables the concatenation of several [`Text`] blocks.
282 ///
283 /// ```rust
284 /// # use helix_tui::text::Text;
285 /// # use helix_view::graphics::{Color, Modifier, Style};
286 /// let style = Style::default().fg(Color::Yellow).add_modifier(Modifier::ITALIC);
287 ///
288 /// // An initial two lines of `Text` built from a `&str`
289 /// let mut text = Text::from("The first line\nThe second line");
290 /// assert_eq!(2, text.height());
291 ///
292 /// // Adding two more unstyled lines
293 /// text.extend(Text::raw("These are two\nmore lines!"));
294 /// assert_eq!(4, text.height());
295 ///
296 /// // Adding a final two styled lines
297 /// text.extend(Text::styled("Some more lines\nnow with more style!", style));
298 /// assert_eq!(6, text.height());
299 /// ```
300 #[derive(Debug, Default, Clone, PartialEq, Eq)]
301 pub struct Text<'a> {
302 pub lines: Vec<Spans<'a>>,
303 }
304
305 impl<'a> Text<'a> {
306 /// Create some text (potentially multiple lines) with no style.
307 ///
308 /// ## Examples
309 ///
310 /// ```rust
311 /// # use helix_tui::text::Text;
312 /// Text::raw("The first line\nThe second line");
313 /// Text::raw(String::from("The first line\nThe second line"));
314 /// ```
315 pub fn raw<T>(content: T) -> Text<'a>
316 where
317 T: Into<Cow<'a, str>>,
318 {
319 Text {
320 lines: match content.into() {
321 Cow::Borrowed(s) => s.lines().map(Spans::from).collect(),
322 Cow::Owned(s) => s.lines().map(|l| Spans::from(l.to_owned())).collect(),
323 },
324 }
325 }
326
327 /// Create some text (potentially multiple lines) with a style.
328 ///
329 /// # Examples
330 ///
331 /// ```rust
332 /// # use helix_tui::text::Text;
333 /// # use helix_view::graphics::{Color, Modifier, Style};
334 /// let style = Style::default().fg(Color::Yellow).add_modifier(Modifier::ITALIC);
335 /// Text::styled("The first line\nThe second line", style);
336 /// Text::styled(String::from("The first line\nThe second line"), style);
337 /// ```
338 pub fn styled<T>(content: T, style: Style) -> Text<'a>
339 where
340 T: Into<Cow<'a, str>>,
341 {
342 let mut text = Text::raw(content);
343 text.patch_style(style);
344 text
345 }
346
347 /// Returns the max width of all the lines.
348 ///
349 /// ## Examples
350 ///
351 /// ```rust
352 /// use helix_tui::text::Text;
353 /// let text = Text::from("The first line\nThe second line");
354 /// assert_eq!(15, text.width());
355 /// ```
356 pub fn width(&self) -> usize {
357 self.lines
358 .iter()
359 .map(Spans::width)
360 .max()
361 .unwrap_or_default()
362 }
363
364 /// Returns the height.
365 ///
366 /// ## Examples
367 ///
368 /// ```rust
369 /// use helix_tui::text::Text;
370 /// let text = Text::from("The first line\nThe second line");
371 /// assert_eq!(2, text.height());
372 /// ```
373 pub fn height(&self) -> usize {
374 self.lines.len()
375 }
376
377 /// Patch text with a new style. Only updates fields that are in the new style.
378 ///
379 /// # Examples
380 ///
381 /// ```rust
382 /// # use helix_tui::text::Text;
383 /// # use helix_view::graphics::{Color, Style};
384 /// let style1 = Style::default().fg(Color::Yellow);
385 /// let style2 = Style::default().fg(Color::Yellow).bg(Color::Black);
386 /// let mut half_styled_text = Text::styled(String::from("The first line\nThe second line"), style1);
387 /// let full_styled_text = Text::styled(String::from("The first line\nThe second line"), style2);
388 /// assert_ne!(half_styled_text, full_styled_text);
389 ///
390 /// half_styled_text.patch_style(Style::default().bg(Color::Black));
391 /// assert_eq!(half_styled_text, full_styled_text);
392 /// ```
393 pub fn patch_style(&mut self, style: Style) {
394 for line in &mut self.lines {
395 for span in &mut line.0 {
396 span.style = span.style.patch(style);
397 }
398 }
399 }
400
401 /// Apply a new style to existing text.
402 ///
403 /// # Examples
404 ///
405 /// ```rust
406 /// # use helix_tui::text::Text;
407 /// # use helix_view::graphics::{Color, Modifier, Style};
408 /// let style = Style::default().fg(Color::Yellow).add_modifier(Modifier::ITALIC);
409 /// let mut raw_text = Text::raw("The first line\nThe second line");
410 /// let styled_text = Text::styled(String::from("The first line\nThe second line"), style);
411 /// assert_ne!(raw_text, styled_text);
412 ///
413 /// raw_text.set_style(style);
414 /// assert_eq!(raw_text, styled_text);
415 /// ```
416 pub fn set_style(&mut self, style: Style) {
417 for line in &mut self.lines {
418 for span in &mut line.0 {
419 span.style = style;
420 }
421 }
422 }
423 }
424
425 impl<'a> From<String> for Text<'a> {
426 fn from(s: String) -> Text<'a> {
427 Text::raw(s)
428 }
429 }
430
431 impl<'a> From<&'a str> for Text<'a> {
432 fn from(s: &'a str) -> Text<'a> {
433 Text::raw(s)
434 }
435 }
436
437 impl<'a> From<Cow<'a, str>> for Text<'a> {
438 fn from(s: Cow<'a, str>) -> Text<'a> {
439 Text::raw(s)
440 }
441 }
442
443 impl<'a> From<Span<'a>> for Text<'a> {
444 fn from(span: Span<'a>) -> Text<'a> {
445 Text {
446 lines: vec![Spans::from(span)],
447 }
448 }
449 }
450
451 impl<'a> From<Spans<'a>> for Text<'a> {
452 fn from(spans: Spans<'a>) -> Text<'a> {
453 Text { lines: vec![spans] }
454 }
455 }
456
457 impl<'a> From<Vec<Spans<'a>>> for Text<'a> {
458 fn from(lines: Vec<Spans<'a>>) -> Text<'a> {
459 Text { lines }
460 }
461 }
462
463 impl<'a> From<Text<'a>> for String {
464 fn from(text: Text<'a>) -> String {
465 String::from(&text)
466 }
467 }
468
469 impl<'a> From<&Text<'a>> for String {
470 fn from(text: &Text<'a>) -> String {
471 let size = text
472 .lines
473 .iter()
474 .flat_map(|spans| spans.0.iter().map(|span| span.content.len()))
475 .sum::<usize>()
476 + text.lines.len().saturating_sub(1); // for newline after each line
477 let mut output = String::with_capacity(size);
478
479 for spans in &text.lines {
480 if !output.is_empty() {
481 output.push('\n');
482 }
483 for span in &spans.0 {
484 output.push_str(&span.content);
485 }
486 }
487 output
488 }
489 }
490
491 impl<'a> IntoIterator for Text<'a> {
492 type Item = Spans<'a>;
493 type IntoIter = std::vec::IntoIter<Self::Item>;
494
495 fn into_iter(self) -> Self::IntoIter {
496 self.lines.into_iter()
497 }
498 }
499
500 impl<'a> Extend<Spans<'a>> for Text<'a> {
501 fn extend<T: IntoIterator<Item = Spans<'a>>>(&mut self, iter: T) {
502 self.lines.extend(iter);
503 }
504 }