Skip to main content

twrite_gpui/editor/
clipboard.rs

1use gpui::{App, ClipboardItem};
2
3use super::Editor;
4
5impl Editor {
6    /// Deletes the currently selected text, returning true if text was deleted.
7    pub fn delete_selection(&mut self) -> bool {
8        if let Some(selection) = self.selection.take() {
9            let range = selection.byte_range();
10            if !range.is_empty() {
11                self.buffer.delete_range(range);
12                return true;
13            }
14        }
15        false
16    }
17
18    /// Replaces the active selection with `text`, or inserts `text` at the cursor position.
19    pub fn replace_selection_or_insert(&mut self, text: &str) {
20        if let Some(selection) = self.selection.take() {
21            let range = selection.byte_range();
22            if !range.is_empty() {
23                self.buffer.replace_range(range, text);
24                return;
25            }
26        }
27        self.buffer.insert(text);
28    }
29
30    /// Copies the currently selected text to the system clipboard.
31    pub fn copy(&self, cx: &App) {
32        if let Some(sel) = self.selection {
33            let range = sel.byte_range();
34            if !range.is_empty() {
35                let text = self.buffer.text().byte_slice(range).to_string();
36                cx.write_to_clipboard(ClipboardItem::new_string(text));
37            }
38        }
39    }
40
41    /// Cuts the currently selected text and copies it to the system clipboard.
42    ///
43    /// Returns `true` if text was cut, or `false` if there was no selection.
44    pub fn cut(&mut self, cx: &App) -> bool {
45        if let Some(sel) = self.selection.take() {
46            let range = sel.byte_range();
47            if !range.is_empty() {
48                let text = self.buffer.text().byte_slice(range.clone()).to_string();
49                cx.write_to_clipboard(ClipboardItem::new_string(text));
50                self.buffer.delete_range(range);
51                self.selection = None;
52                return true;
53            }
54        }
55        false
56    }
57
58    /// Pastes text from the system clipboard, replacing the current selection or inserting at cursor.
59    ///
60    /// Returns `true` if text was pasted, or `false` if the clipboard was empty.
61    pub fn paste(&mut self, cx: &App) -> bool {
62        if let Some(text) = cx.read_from_clipboard().and_then(|item| item.text())
63            && !text.is_empty()
64        {
65            self.replace_selection_or_insert(&text);
66            self.selection = None;
67            return true;
68        }
69        false
70    }
71}