Skip to main content

iced_core/text/
editor.rs

1//! Edit text.
2use crate::text::highlighter::{self, Highlighter};
3use crate::text::{LineHeight, Wrapping};
4use crate::{Pixels, Point, Rectangle, Size};
5
6use std::borrow::Cow;
7use std::sync::Arc;
8
9/// A component that can be used by widgets to edit multi-line text.
10pub trait Editor: Sized + Default {
11    /// The font of the [`Editor`].
12    type Font: Copy + PartialEq + Default;
13
14    /// Creates a new [`Editor`] laid out with the given text.
15    fn with_text(text: &str) -> Self;
16
17    /// Returns true if the [`Editor`] has no contents.
18    fn is_empty(&self) -> bool;
19
20    /// Returns the current [`Cursor`] of the [`Editor`].
21    fn cursor(&self) -> Cursor;
22
23    /// Returns the current [`Selection`] of the [`Editor`].
24    fn selection(&self) -> Selection;
25
26    /// Returns the current selected text of the [`Editor`].
27    fn copy(&self) -> Option<String>;
28
29    /// Returns the text of the given line in the [`Editor`], if it exists.
30    fn line(&self, index: usize) -> Option<Line<'_>>;
31
32    /// Returns the amount of lines in the [`Editor`].
33    fn line_count(&self) -> usize;
34
35    /// Performs an [`Action`] on the [`Editor`].
36    fn perform(&mut self, action: Action);
37
38    /// Moves the cursor to the given position.
39    fn move_to(&mut self, cursor: Cursor);
40
41    /// Returns the current boundaries of the [`Editor`].
42    fn bounds(&self) -> Size;
43
44    /// Returns the minimum boundaries to fit the current contents of
45    /// the [`Editor`].
46    fn min_bounds(&self) -> Size;
47
48    /// Returns the hint factor of the [`Editor`].
49    fn hint_factor(&self) -> Option<f32>;
50
51    /// Updates the [`Editor`] with some new attributes.
52    fn update(
53        &mut self,
54        new_bounds: Size,
55        new_font: Self::Font,
56        new_size: Pixels,
57        new_line_height: LineHeight,
58        new_wrapping: Wrapping,
59        new_hint_factor: Option<f32>,
60        new_highlighter: &mut impl Highlighter,
61    );
62
63    /// Runs a text [`Highlighter`] in the [`Editor`].
64    fn highlight<H: Highlighter>(
65        &mut self,
66        font: Self::Font,
67        highlighter: &mut H,
68        format_highlight: impl Fn(&H::Highlight) -> highlighter::Format<Self::Font>,
69    );
70}
71
72/// An interaction with an [`Editor`].
73#[derive(Debug, Clone, PartialEq)]
74pub enum Action {
75    /// Apply a [`Motion`].
76    Move(Motion),
77    /// Select text with a given [`Motion`].
78    Select(Motion),
79    /// Select the word at the current cursor.
80    SelectWord,
81    /// Select the line at the current cursor.
82    SelectLine,
83    /// Select the entire buffer.
84    SelectAll,
85    /// Perform an [`Edit`].
86    Edit(Edit),
87    /// Click the [`Editor`] at the given [`Point`].
88    Click(Point),
89    /// Drag the mouse on the [`Editor`] to the given [`Point`].
90    Drag(Point),
91    /// Scroll the [`Editor`] a certain amount of lines.
92    Scroll {
93        /// The amount of lines to scroll.
94        lines: i32,
95    },
96}
97
98impl Action {
99    /// Returns whether the [`Action`] is an editing action.
100    pub fn is_edit(&self) -> bool {
101        matches!(self, Self::Edit(_))
102    }
103}
104
105/// An action that edits text.
106#[derive(Debug, Clone, PartialEq)]
107pub enum Edit {
108    /// Insert the given character.
109    Insert(char),
110    /// Paste the given text.
111    Paste(Arc<String>),
112    /// Break the current line.
113    Enter,
114    /// Indent the current line.
115    Indent,
116    /// Unindent the current line.
117    Unindent,
118    /// Delete the previous character.
119    Backspace,
120    /// Delete the next character.
121    Delete,
122}
123
124/// A cursor movement.
125#[derive(Debug, Clone, Copy, PartialEq)]
126pub enum Motion {
127    /// Move left.
128    Left,
129    /// Move right.
130    Right,
131    /// Move up.
132    Up,
133    /// Move down.
134    Down,
135    /// Move to the left boundary of a word.
136    WordLeft,
137    /// Move to the right boundary of a word.
138    WordRight,
139    /// Move to the start of the line.
140    Home,
141    /// Move to the end of the line.
142    End,
143    /// Move to the start of the previous window.
144    PageUp,
145    /// Move to the start of the next window.
146    PageDown,
147    /// Move to the start of the text.
148    DocumentStart,
149    /// Move to the end of the text.
150    DocumentEnd,
151}
152
153impl Motion {
154    /// Widens the [`Motion`], if possible.
155    pub fn widen(self) -> Self {
156        match self {
157            Self::Left => Self::WordLeft,
158            Self::Right => Self::WordRight,
159            Self::Home => Self::DocumentStart,
160            Self::End => Self::DocumentEnd,
161            _ => self,
162        }
163    }
164
165    /// Returns the [`Direction`] of the [`Motion`].
166    pub fn direction(&self) -> Direction {
167        match self {
168            Self::Left
169            | Self::Up
170            | Self::WordLeft
171            | Self::Home
172            | Self::PageUp
173            | Self::DocumentStart => Direction::Left,
174            Self::Right
175            | Self::Down
176            | Self::WordRight
177            | Self::End
178            | Self::PageDown
179            | Self::DocumentEnd => Direction::Right,
180        }
181    }
182}
183
184/// A direction in some text.
185#[derive(Debug, Clone, Copy, PartialEq, Eq)]
186pub enum Direction {
187    /// <-
188    Left,
189    /// ->
190    Right,
191}
192
193/// The cursor of an [`Editor`].
194#[derive(Debug, Clone)]
195pub enum Selection {
196    /// Cursor without a selection
197    Caret(Point),
198
199    /// Cursor selecting a range of text
200    Range(Vec<Rectangle>),
201}
202
203/// The range of an [`Editor`].
204#[derive(Debug, Clone, Copy, PartialEq)]
205pub struct Cursor {
206    /// The cursor position.
207    pub position: Position,
208
209    /// The selection position, if any.
210    pub selection: Option<Position>,
211}
212
213/// A cursor position in an [`Editor`].
214#[derive(Debug, Clone, Copy, PartialEq)]
215pub struct Position {
216    /// The line of text.
217    pub line: usize,
218    /// The column in the line.
219    pub column: usize,
220}
221
222/// A line of an [`Editor`].
223#[derive(Clone, Debug, Default, Eq, PartialEq)]
224pub struct Line<'a> {
225    /// The raw text of the [`Line`].
226    pub text: Cow<'a, str>,
227    /// The line ending of the [`Line`].
228    pub ending: LineEnding,
229}
230
231/// The line ending of a [`Line`].
232#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
233pub enum LineEnding {
234    /// Use `\n` for line ending (POSIX-style)
235    #[default]
236    Lf,
237    /// Use `\r\n` for line ending (Windows-style)
238    CrLf,
239    /// Use `\r` for line ending (many legacy systems)
240    Cr,
241    /// Use `\n\r` for line ending (some legacy systems)
242    LfCr,
243    /// No line ending
244    None,
245}
246
247impl LineEnding {
248    /// Gets the string representation of the [`LineEnding`].
249    pub fn as_str(self) -> &'static str {
250        match self {
251            Self::Lf => "\n",
252            Self::CrLf => "\r\n",
253            Self::Cr => "\r",
254            Self::LfCr => "\n\r",
255            Self::None => "",
256        }
257    }
258}