cosmic-text/src/edit/mod.rs

349 lines
10 KiB
Rust
Raw Normal View History

#[cfg(not(feature = "std"))]
2023-11-13 12:37:07 -07:00
use alloc::{string::String, vec::Vec};
2023-11-28 10:42:50 -07:00
use core::cmp;
use unicode_segmentation::UnicodeSegmentation;
#[cfg(feature = "swash")]
use crate::Color;
use crate::{AttrsList, BorrowedWithFontSystem, Buffer, Cursor, FontSystem};
pub use self::editor::*;
mod editor;
#[cfg(feature = "syntect")]
pub use self::syntect::*;
#[cfg(feature = "syntect")]
mod syntect;
#[cfg(feature = "vi")]
pub use self::vi::*;
#[cfg(feature = "vi")]
mod vi;
/// An action to perform on an [`Editor`]
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum Action {
/// Move cursor to previous character ([Self::Left] in LTR, [Self::Right] in RTL)
Previous,
/// Move cursor to next character ([Self::Right] in LTR, [Self::Left] in RTL)
Next,
/// Move cursor left
Left,
/// Move cursor right
Right,
/// Move cursor up
Up,
/// Move cursor down
Down,
/// Move cursor to start of line
Home,
/// Move cursor to start of line, skipping whitespace
SoftHome,
/// Move cursor to end of line
End,
2022-12-29 19:05:15 -08:00
/// Move cursor to start of paragraph
ParagraphStart,
/// Move cursor to end of paragraph
ParagraphEnd,
/// Move cursor up one page
PageUp,
2022-12-29 19:05:15 -08:00
/// Move cursor down one page
PageDown,
2022-12-29 19:05:15 -08:00
/// Move cursor up or down by a number of pixels
Vertical(i32),
/// Escape, clears selection
Escape,
/// Insert character at cursor
Insert(char),
/// Create new line
Enter,
/// Delete text behind cursor
Backspace,
/// Delete text in front of cursor
Delete,
2023-11-01 13:31:53 -06:00
// Indent text (typically Tab)
Indent,
// Unindent text (typically Shift+Tab)
Unindent,
/// Mouse click at specified position
2023-11-01 13:31:53 -06:00
Click {
x: i32,
y: i32,
},
/// Mouse double click at specified position
DoubleClick {
x: i32,
y: i32,
},
/// Mouse triple click at specified position
TripleClick {
x: i32,
y: i32,
},
/// Mouse drag to specified position
2023-11-01 13:31:53 -06:00
Drag {
x: i32,
y: i32,
},
/// Scroll specified number of lines
2023-11-01 13:31:53 -06:00
Scroll {
lines: i32,
},
2022-12-29 19:05:15 -08:00
/// Move cursor to previous word boundary
PreviousWord,
/// Move cursor to next word boundary
NextWord,
/// Move cursor to next word boundary to the left
LeftWord,
/// Move cursor to next word boundary to the right
RightWord,
/// Move cursor to the start of the document
BufferStart,
/// Move cursor to the end of the document
BufferEnd,
2023-11-07 15:56:31 -07:00
/// Move cursor to specific line
GotoLine(usize),
}
2023-11-13 13:31:06 -07:00
/// A unique change to an editor
2023-11-13 12:37:07 -07:00
#[derive(Clone, Debug)]
2023-11-13 13:31:06 -07:00
pub struct ChangeItem {
/// Cursor indicating start of change
pub start: Cursor,
/// Cursor indicating end of change
pub end: Cursor,
/// Text to be inserted or deleted
pub text: String,
/// Insert if true, delete if false
pub insert: bool,
2023-11-13 12:37:07 -07:00
}
2023-11-13 13:31:06 -07:00
impl ChangeItem {
// Reverse change item (in place)
pub fn reverse(&mut self) {
self.insert = !self.insert;
}
}
/// A set of change items grouped into one logical change
2023-11-13 12:37:07 -07:00
#[derive(Clone, Debug, Default)]
pub struct Change {
2023-11-13 13:31:06 -07:00
/// Change items grouped into one change
pub items: Vec<ChangeItem>,
}
impl Change {
// Reverse change (in place)
pub fn reverse(&mut self) {
self.items.reverse();
for item in self.items.iter_mut() {
item.reverse();
}
}
2023-11-13 12:37:07 -07:00
}
2023-11-28 10:42:50 -07:00
/// Selection mode
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum Selection {
/// No selection
None,
/// Normal selection
Normal(Cursor),
/// Select by lines
Line(Cursor),
/// Select by words
Word(Cursor),
2023-11-28 10:42:50 -07:00
//TODO: Select block
}
/// A trait to allow easy replacements of [`Editor`], like `SyntaxEditor`
pub trait Edit {
2023-03-12 10:30:27 +01:00
/// Mutably borrows `self` together with an [`FontSystem`] for more convenient methods
fn borrow_with<'a>(
&'a mut self,
font_system: &'a mut FontSystem,
) -> BorrowedWithFontSystem<'a, Self>
where
Self: Sized,
{
BorrowedWithFontSystem {
inner: self,
font_system,
}
}
/// Get the internal [`Buffer`]
fn buffer(&self) -> &Buffer;
/// Get the internal [`Buffer`], mutably
fn buffer_mut(&mut self) -> &mut Buffer;
2023-06-10 12:38:14 +01:00
/// Get the current cursor
fn cursor(&self) -> Cursor;
2023-06-10 12:38:14 +01:00
/// Set the current cursor
fn set_cursor(&mut self, cursor: Cursor);
/// Get the current selection position
2023-11-28 10:42:50 -07:00
fn selection(&self) -> Selection;
2022-11-21 15:49:12 -07:00
/// Set the current selection position
2023-11-28 10:42:50 -07:00
fn set_selection(&mut self, selection: Selection);
/// Get the bounds of the current selection
//TODO: will not work with Block select
fn selection_bounds(&self) -> Option<(Cursor, Cursor)> {
let cursor = self.cursor();
match self.selection() {
Selection::None => None,
Selection::Normal(select) => match select.line.cmp(&cursor.line) {
cmp::Ordering::Greater => Some((cursor, select)),
cmp::Ordering::Less => Some((select, cursor)),
cmp::Ordering::Equal => {
/* select.line == cursor.line */
if select.index < cursor.index {
Some((select, cursor))
} else {
/* select.index >= cursor.index */
Some((cursor, select))
}
}
},
Selection::Line(select) => {
let start_line = cmp::min(select.line, cursor.line);
let end_line = cmp::max(select.line, cursor.line);
let end_index = self.buffer().lines[end_line].text().len();
Some((Cursor::new(start_line, 0), Cursor::new(end_line, end_index)))
}
Selection::Word(select) => {
let (mut start, mut end) = match select.line.cmp(&cursor.line) {
cmp::Ordering::Greater => (cursor, select),
cmp::Ordering::Less => (select, cursor),
cmp::Ordering::Equal => {
/* select.line == cursor.line */
if select.index < cursor.index {
(select, cursor)
} else {
/* select.index >= cursor.index */
(cursor, select)
}
}
};
// Move start to beginning of word
{
let line = &self.buffer().lines[start.line];
start.index = line
.text()
.unicode_word_indices()
.rev()
.map(|(i, _)| i)
.find(|&i| i < start.index)
.unwrap_or(0);
}
// Move end to end of word
{
let line = &self.buffer().lines[end.line];
end.index = line
.text()
.unicode_word_indices()
.map(|(i, word)| i + word.len())
.find(|&i| i > end.index)
.unwrap_or(line.text().len());
}
Some((start, end))
}
2023-11-28 10:42:50 -07:00
}
}
2022-11-21 15:49:12 -07:00
2023-11-16 08:59:43 -07:00
/// Get the current automatic indentation setting
fn auto_indent(&self) -> bool;
/// Enable or disable automatic indentation
fn set_auto_indent(&mut self, auto_indent: bool);
2023-11-01 13:31:53 -06:00
/// Get the current tab width
2023-11-16 08:38:48 -07:00
fn tab_width(&self) -> u16;
2023-11-01 13:31:53 -06:00
2023-11-15 09:21:13 -07:00
/// Set the current tab width. A `tab_width` of 0 is not allowed, and will be ignored
2023-11-16 08:38:48 -07:00
fn set_tab_width(&mut self, tab_width: u16);
2023-11-01 13:31:53 -06:00
/// Shape lines until scroll, after adjusting scroll if the cursor moved
2023-03-12 10:30:20 +01:00
fn shape_as_needed(&mut self, font_system: &mut FontSystem);
/// Delete text starting at start Cursor and ending at end Cursor
fn delete_range(&mut self, start: Cursor, end: Cursor);
/// Insert text at specified cursor with specified attrs_list
fn insert_at(&mut self, cursor: Cursor, data: &str, attrs_list: Option<AttrsList>) -> Cursor;
/// Copy selection
2023-09-16 15:57:41 +02:00
fn copy_selection(&self) -> Option<String>;
/// Delete selection, adjusting cursor and returning true if there was a selection
// Also used by backspace, delete, insert, and enter when there is a selection
fn delete_selection(&mut self) -> bool;
2022-12-29 10:20:11 -08:00
/// Insert a string at the current cursor or replacing the current selection with the given
/// attributes, or with the previous character's attributes if None is given.
fn insert_string(&mut self, data: &str, attrs_list: Option<AttrsList>) {
self.delete_selection();
let new_cursor = self.insert_at(self.cursor(), data, attrs_list);
self.set_cursor(new_cursor);
}
2022-12-29 10:20:11 -08:00
2023-11-13 13:31:06 -07:00
/// Apply a change
fn apply_change(&mut self, change: &Change) -> bool;
2023-11-13 12:37:07 -07:00
/// Start collecting change
fn start_change(&mut self);
/// Get completed change
fn finish_change(&mut self) -> Option<Change>;
/// Perform an [Action] on the editor
2023-03-12 10:30:20 +01:00
fn action(&mut self, font_system: &mut FontSystem, action: Action);
/// Draw the editor
#[cfg(feature = "swash")]
2023-03-12 10:30:20 +01:00
fn draw<F>(
&self,
font_system: &mut FontSystem,
cache: &mut crate::SwashCache,
color: Color,
f: F,
) where
2023-01-04 20:03:03 -07:00
F: FnMut(i32, i32, u32, u32, Color);
}
impl<'a, T: Edit> BorrowedWithFontSystem<'a, T> {
/// Get the internal [`Buffer`], mutably
pub fn buffer_mut(&mut self) -> BorrowedWithFontSystem<Buffer> {
BorrowedWithFontSystem {
inner: self.inner.buffer_mut(),
font_system: self.font_system,
}
}
/// Shape lines until scroll, after adjusting scroll if the cursor moved
pub fn shape_as_needed(&mut self) {
self.inner.shape_as_needed(self.font_system);
}
/// Perform an [Action] on the editor
pub fn action(&mut self, action: Action) {
self.inner.action(self.font_system, action);
}
/// Draw the editor
#[cfg(feature = "swash")]
2023-03-12 10:30:20 +01:00
pub fn draw<F>(&mut self, cache: &mut crate::SwashCache, color: Color, f: F)
where
F: FnMut(i32, i32, u32, u32, Color),
{
self.inner.draw(self.font_system, cache, color, f);
}
}