Skip to main content

ratatui_code_editor/
selection.rs

1#[derive(Debug, Clone, Copy)]
2pub enum SelectionSnap {
3    None,
4    Word { anchor: usize },
5    Line { anchor: usize },
6}
7
8#[derive(Debug, Clone, Copy, PartialEq, Eq)]
9pub struct Selection {
10    pub start: usize,
11    pub end: usize,
12}
13
14impl Selection {
15    pub fn new(a: usize, b: usize) -> Self {
16        Self {
17            start: a.min(b),
18            end: a.max(b),
19        }
20    }
21
22    pub fn from_anchor_and_cursor(anchor: usize, cursor: usize) -> Self {
23        if anchor <= cursor {
24            Selection {
25                start: anchor,
26                end: cursor,
27            }
28        } else {
29            Selection {
30                start: cursor,
31                end: anchor,
32            }
33        }
34    }
35
36    pub fn is_active(&self) -> bool {
37        self.start != self.end
38    }
39
40    pub fn is_empty(&self) -> bool {
41        self.start.max(self.end) == self.start.min(self.end)
42    }
43
44    pub fn contains(&self, index: usize) -> bool {
45        index >= self.start && index < self.end
46    }
47
48    pub fn sorted(&self) -> (usize, usize) {
49        if self.start <= self.end {
50            (self.start, self.end)
51        } else {
52            (self.end, self.start)
53        }
54    }
55}