iced_core/text/
highlighter.rs

1//! Highlight text.
2use crate::Color;
3
4use std::ops::Range;
5
6/// A type capable of highlighting text.
7///
8/// A [`Highlighter`] highlights lines in sequence. When a line changes,
9/// it must be notified and the lines after the changed one must be fed
10/// again to the [`Highlighter`].
11pub trait Highlighter: 'static {
12    /// The settings to configure the [`Highlighter`].
13    type Settings: PartialEq + Clone;
14
15    /// The output of the [`Highlighter`].
16    type Highlight;
17
18    /// The highlight iterator type.
19    type Iterator<'a>: Iterator<Item = (Range<usize>, Self::Highlight)>
20    where
21        Self: 'a;
22
23    /// Creates a new [`Highlighter`] from its [`Self::Settings`].
24    fn new(settings: &Self::Settings) -> Self;
25
26    /// Updates the [`Highlighter`] with some new [`Self::Settings`].
27    fn update(&mut self, new_settings: &Self::Settings);
28
29    /// Notifies the [`Highlighter`] that the line at the given index has changed.
30    fn change_line(&mut self, line: usize);
31
32    /// Highlights the given line.
33    ///
34    /// If a line changed prior to this, the first line provided here will be the
35    /// line that changed.
36    fn highlight_line(&mut self, line: &str) -> Self::Iterator<'_>;
37
38    /// Returns the current line of the [`Highlighter`].
39    ///
40    /// If `change_line` has been called, this will normally be the least index
41    /// that changed.
42    fn current_line(&self) -> usize;
43}
44
45/// A highlighter that highlights nothing.
46#[derive(Debug, Clone, Copy)]
47pub struct PlainText;
48
49impl Highlighter for PlainText {
50    type Settings = ();
51    type Highlight = ();
52
53    type Iterator<'a> = std::iter::Empty<(Range<usize>, Self::Highlight)>;
54
55    fn new(_settings: &Self::Settings) -> Self {
56        Self
57    }
58
59    fn update(&mut self, _new_settings: &Self::Settings) {}
60
61    fn change_line(&mut self, _line: usize) {}
62
63    fn highlight_line(&mut self, _line: &str) -> Self::Iterator<'_> {
64        std::iter::empty()
65    }
66
67    fn current_line(&self) -> usize {
68        usize::MAX
69    }
70}
71
72/// The format of some text.
73#[derive(Debug, Clone, Copy, PartialEq)]
74pub struct Format<Font> {
75    /// The [`Color`] of the text.
76    pub color: Option<Color>,
77    /// The `Font` of the text.
78    pub font: Option<Font>,
79}
80
81impl<Font> Default for Format<Font> {
82    fn default() -> Self {
83        Self {
84            color: None,
85            font: None,
86        }
87    }
88}