cosmic_text/edit/
mod.rs

1use alloc::sync::Arc;
2#[cfg(not(feature = "std"))]
3use alloc::{string::String, vec::Vec};
4use core::cmp;
5use unicode_segmentation::UnicodeSegmentation;
6
7use crate::{AttrsList, BorrowedWithFontSystem, Buffer, Cursor, FontSystem, Motion};
8
9pub use self::editor::*;
10mod editor;
11
12#[cfg(feature = "syntect")]
13pub use self::syntect::*;
14#[cfg(feature = "syntect")]
15mod syntect;
16
17#[cfg(feature = "vi")]
18pub use self::vi::*;
19#[cfg(feature = "vi")]
20mod vi;
21
22/// An action to perform on an [`Editor`]
23#[derive(Clone, Copy, Debug, Eq, PartialEq)]
24pub enum Action {
25    /// Move the cursor with some motion
26    Motion(Motion),
27    /// Escape, clears selection
28    Escape,
29    /// Insert character at cursor
30    Insert(char),
31    /// Create new line
32    Enter,
33    /// Delete text behind cursor
34    Backspace,
35    /// Delete text in front of cursor
36    Delete,
37    // Indent text (typically Tab)
38    Indent,
39    // Unindent text (typically Shift+Tab)
40    Unindent,
41    /// Mouse click at specified position
42    Click {
43        x: i32,
44        y: i32,
45    },
46    /// Mouse double click at specified position
47    DoubleClick {
48        x: i32,
49        y: i32,
50    },
51    /// Mouse triple click at specified position
52    TripleClick {
53        x: i32,
54        y: i32,
55    },
56    /// Mouse drag to specified position
57    Drag {
58        x: i32,
59        y: i32,
60    },
61    /// Scroll specified number of lines
62    Scroll {
63        lines: i32,
64    },
65}
66
67#[derive(Debug)]
68pub enum BufferRef<'buffer> {
69    Owned(Buffer),
70    Borrowed(&'buffer mut Buffer),
71    Arc(Arc<Buffer>),
72}
73
74impl Clone for BufferRef<'_> {
75    fn clone(&self) -> Self {
76        match self {
77            Self::Owned(buffer) => Self::Owned(buffer.clone()),
78            Self::Borrowed(buffer) => Self::Owned((*buffer).clone()),
79            Self::Arc(buffer) => Self::Arc(buffer.clone()),
80        }
81    }
82}
83
84impl From<Buffer> for BufferRef<'_> {
85    fn from(buffer: Buffer) -> Self {
86        Self::Owned(buffer)
87    }
88}
89
90impl<'buffer> From<&'buffer mut Buffer> for BufferRef<'buffer> {
91    fn from(buffer: &'buffer mut Buffer) -> Self {
92        Self::Borrowed(buffer)
93    }
94}
95
96impl From<Arc<Buffer>> for BufferRef<'_> {
97    fn from(arc: Arc<Buffer>) -> Self {
98        Self::Arc(arc)
99    }
100}
101
102/// A unique change to an editor
103#[derive(Clone, Debug)]
104pub struct ChangeItem {
105    /// Cursor indicating start of change
106    pub start: Cursor,
107    /// Cursor indicating end of change
108    pub end: Cursor,
109    /// Text to be inserted or deleted
110    pub text: String,
111    /// Insert if true, delete if false
112    pub insert: bool,
113}
114
115impl ChangeItem {
116    // Reverse change item (in place)
117    pub fn reverse(&mut self) {
118        self.insert = !self.insert;
119    }
120}
121
122/// A set of change items grouped into one logical change
123#[derive(Clone, Debug, Default)]
124pub struct Change {
125    /// Change items grouped into one change
126    pub items: Vec<ChangeItem>,
127}
128
129impl Change {
130    // Reverse change (in place)
131    pub fn reverse(&mut self) {
132        self.items.reverse();
133        for item in self.items.iter_mut() {
134            item.reverse();
135        }
136    }
137}
138
139/// Selection mode
140#[derive(Clone, Copy, Debug, Eq, PartialEq)]
141pub enum Selection {
142    /// No selection
143    None,
144    /// Normal selection
145    Normal(Cursor),
146    /// Select by lines
147    Line(Cursor),
148    /// Select by words
149    Word(Cursor),
150    //TODO: Select block
151}
152
153/// A trait to allow easy replacements of [`Editor`], like `SyntaxEditor`
154pub trait Edit<'buffer> {
155    /// Mutably borrows `self` together with an [`FontSystem`] for more convenient methods
156    fn borrow_with<'font_system>(
157        &'font_system mut self,
158        font_system: &'font_system mut FontSystem,
159    ) -> BorrowedWithFontSystem<'font_system, Self>
160    where
161        Self: Sized,
162    {
163        BorrowedWithFontSystem {
164            inner: self,
165            font_system,
166        }
167    }
168
169    /// Get the internal [`BufferRef`]
170    fn buffer_ref(&self) -> &BufferRef<'buffer>;
171
172    /// Get the internal [`BufferRef`]
173    fn buffer_ref_mut(&mut self) -> &mut BufferRef<'buffer>;
174
175    /// Get the internal [`Buffer`]
176    fn with_buffer<F: FnOnce(&Buffer) -> T, T>(&self, f: F) -> T {
177        match self.buffer_ref() {
178            BufferRef::Owned(buffer) => f(buffer),
179            BufferRef::Borrowed(buffer) => f(buffer),
180            BufferRef::Arc(buffer) => f(buffer),
181        }
182    }
183
184    /// Get the internal [`Buffer`], mutably
185    fn with_buffer_mut<F: FnOnce(&mut Buffer) -> T, T>(&mut self, f: F) -> T {
186        match self.buffer_ref_mut() {
187            BufferRef::Owned(buffer) => f(buffer),
188            BufferRef::Borrowed(buffer) => f(buffer),
189            BufferRef::Arc(buffer) => f(Arc::make_mut(buffer)),
190        }
191    }
192
193    /// Get the [`Buffer`] redraw flag
194    fn redraw(&self) -> bool {
195        self.with_buffer(|buffer| buffer.redraw())
196    }
197
198    /// Set the [`Buffer`] redraw flag
199    fn set_redraw(&mut self, redraw: bool) {
200        self.with_buffer_mut(|buffer| buffer.set_redraw(redraw));
201    }
202
203    /// Get the current cursor
204    fn cursor(&self) -> Cursor;
205
206    /// Set the current cursor
207    fn set_cursor(&mut self, cursor: Cursor);
208
209    /// Get the current selection position
210    fn selection(&self) -> Selection;
211
212    /// Set the current selection position
213    fn set_selection(&mut self, selection: Selection);
214
215    /// Get the bounds of the current selection
216    //TODO: will not work with Block select
217    fn selection_bounds(&self) -> Option<(Cursor, Cursor)> {
218        self.with_buffer(|buffer| {
219            let cursor = self.cursor();
220            match self.selection() {
221                Selection::None => None,
222                Selection::Normal(select) => match select.line.cmp(&cursor.line) {
223                    cmp::Ordering::Greater => Some((cursor, select)),
224                    cmp::Ordering::Less => Some((select, cursor)),
225                    cmp::Ordering::Equal => {
226                        /* select.line == cursor.line */
227                        if select.index < cursor.index {
228                            Some((select, cursor))
229                        } else {
230                            /* select.index >= cursor.index */
231                            Some((cursor, select))
232                        }
233                    }
234                },
235                Selection::Line(select) => {
236                    let start_line = cmp::min(select.line, cursor.line);
237                    let end_line = cmp::max(select.line, cursor.line);
238                    let end_index = buffer.lines[end_line].text().len();
239                    Some((Cursor::new(start_line, 0), Cursor::new(end_line, end_index)))
240                }
241                Selection::Word(select) => {
242                    let (mut start, mut end) = match select.line.cmp(&cursor.line) {
243                        cmp::Ordering::Greater => (cursor, select),
244                        cmp::Ordering::Less => (select, cursor),
245                        cmp::Ordering::Equal => {
246                            /* select.line == cursor.line */
247                            if select.index < cursor.index {
248                                (select, cursor)
249                            } else {
250                                /* select.index >= cursor.index */
251                                (cursor, select)
252                            }
253                        }
254                    };
255
256                    // Move start to beginning of word
257                    {
258                        let line = &buffer.lines[start.line];
259                        start.index = line
260                            .text()
261                            .unicode_word_indices()
262                            .rev()
263                            .map(|(i, _)| i)
264                            .find(|&i| i < start.index)
265                            .unwrap_or(0);
266                    }
267
268                    // Move end to end of word
269                    {
270                        let line = &buffer.lines[end.line];
271                        end.index = line
272                            .text()
273                            .unicode_word_indices()
274                            .map(|(i, word)| i + word.len())
275                            .find(|&i| i > end.index)
276                            .unwrap_or(line.text().len());
277                    }
278
279                    Some((start, end))
280                }
281            }
282        })
283    }
284
285    /// Get the current automatic indentation setting
286    fn auto_indent(&self) -> bool;
287
288    /// Enable or disable automatic indentation
289    fn set_auto_indent(&mut self, auto_indent: bool);
290
291    /// Get the current tab width
292    fn tab_width(&self) -> u16;
293
294    /// Set the current tab width. A `tab_width` of 0 is not allowed, and will be ignored
295    fn set_tab_width(&mut self, font_system: &mut FontSystem, tab_width: u16);
296
297    /// Shape lines until scroll, after adjusting scroll if the cursor moved
298    fn shape_as_needed(&mut self, font_system: &mut FontSystem, prune: bool);
299
300    /// Delete text starting at start Cursor and ending at end Cursor
301    fn delete_range(&mut self, start: Cursor, end: Cursor);
302
303    /// Insert text at specified cursor with specified `attrs_list`
304    fn insert_at(&mut self, cursor: Cursor, data: &str, attrs_list: Option<AttrsList>) -> Cursor;
305
306    /// Copy selection
307    fn copy_selection(&self) -> Option<String>;
308
309    /// Delete selection, adjusting cursor and returning true if there was a selection
310    // Also used by backspace, delete, insert, and enter when there is a selection
311    fn delete_selection(&mut self) -> bool;
312
313    /// Insert a string at the current cursor or replacing the current selection with the given
314    /// attributes, or with the previous character's attributes if None is given.
315    fn insert_string(&mut self, data: &str, attrs_list: Option<AttrsList>) {
316        self.delete_selection();
317        let new_cursor = self.insert_at(self.cursor(), data, attrs_list);
318        self.set_cursor(new_cursor);
319    }
320
321    /// Apply a change
322    fn apply_change(&mut self, change: &Change) -> bool;
323
324    /// Start collecting change
325    fn start_change(&mut self);
326
327    /// Get completed change
328    fn finish_change(&mut self) -> Option<Change>;
329
330    /// Perform an [Action] on the editor
331    fn action(&mut self, font_system: &mut FontSystem, action: Action);
332
333    /// Get X and Y position of the top left corner of the cursor
334    fn cursor_position(&self) -> Option<(i32, i32)>;
335}
336
337impl<'buffer, E: Edit<'buffer>> BorrowedWithFontSystem<'_, E> {
338    /// Get the internal [`Buffer`], mutably
339    pub fn with_buffer_mut<F: FnOnce(&mut BorrowedWithFontSystem<Buffer>) -> T, T>(
340        &mut self,
341        f: F,
342    ) -> T {
343        self.inner.with_buffer_mut(|buffer| {
344            let mut borrowed = BorrowedWithFontSystem {
345                inner: buffer,
346                font_system: self.font_system,
347            };
348            f(&mut borrowed)
349        })
350    }
351
352    /// Set the current tab width. A `tab_width` of 0 is not allowed, and will be ignored
353    pub fn set_tab_width(&mut self, tab_width: u16) {
354        self.inner.set_tab_width(self.font_system, tab_width);
355    }
356
357    /// Shape lines until scroll, after adjusting scroll if the cursor moved
358    pub fn shape_as_needed(&mut self, prune: bool) {
359        self.inner.shape_as_needed(self.font_system, prune);
360    }
361
362    /// Perform an [Action] on the editor
363    pub fn action(&mut self, action: Action) {
364        self.inner.action(self.font_system, action);
365    }
366}