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)]
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 { start: anchor, end: cursor }
25        } else {
26            Selection { start: cursor, end: anchor }
27        }
28    }
29
30    pub fn is_active(&self) -> bool {
31        self.start != self.end
32    }
33    
34    pub fn is_empty(&self) -> bool {
35        self.start.max(self.end) == self.start.min(self.end)
36    }
37
38    pub fn contains(&self, index: usize) -> bool {
39        index >= self.start && index < self.end
40    }
41    
42    pub fn sorted(&self) -> (usize, usize) {
43        if self.start <= self.end {
44            (self.start, self.end)
45        } else {
46            (self.end, self.start)
47        }
48    }
49}