Skip to content

Commit

Permalink
Merge pull request #81 from achristmascarl/expose-selection-start
Browse files Browse the repository at this point in the history
Expose `selection_start`
  • Loading branch information
rhysd committed Aug 8, 2024
2 parents 93cfabd + 75f5111 commit b7a7e3d
Showing 1 changed file with 31 additions and 3 deletions.
34 changes: 31 additions & 3 deletions src/textarea.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1430,7 +1430,7 @@ impl<'a> TextArea<'a> {
self.select_style
}

fn selection_range(&self) -> Option<(Pos, Pos)> {
fn selection_range_(&self) -> Option<(Pos, Pos)> {
let (sr, sc) = self.selection_start?;
let (er, ec) = self.cursor;
let (so, eo) = (self.line_offset(sr, sc), self.line_offset(er, ec));
Expand All @@ -1444,7 +1444,7 @@ impl<'a> TextArea<'a> {
}

fn take_selection_range(&mut self) -> Option<(Pos, Pos)> {
let range = self.selection_range();
let range = self.selection_range_();
self.cancel_selection();
range
}
Expand Down Expand Up @@ -1608,7 +1608,7 @@ impl<'a> TextArea<'a> {
hl.search(matches, self.search.style);
}

if let Some((start, end)) = self.selection_range() {
if let Some((start, end)) = self.selection_range_() {
hl.selection(row, start.row, start.offset, end.row, end.offset);
}

Expand Down Expand Up @@ -2040,6 +2040,34 @@ impl<'a> TextArea<'a> {
self.cursor
}

/// Get the current selection range. A tuple (selection_start, cursor) of 0-base character-wise (row, col)
/// positions. The selection start position will always come first, even when it is ahead of
/// the cursor.
/// ```
/// use tui_textarea::TextArea;
/// use tui_textarea::CursorMove;
///
/// let mut textarea = TextArea::from(["abc"]);
/// assert_eq!(textarea.selection_range(), None);
///
/// textarea.start_selection();
/// assert_eq!(textarea.selection_range(), Some(((0, 0), (0, 0))));
///
/// textarea.move_cursor(CursorMove::Forward);
/// assert_eq!(textarea.selection_range(), Some(((0, 0), (0, 1))));
///
/// textarea.cancel_selection();
/// assert_eq!(textarea.selection_range(), None);
///
/// textarea.start_selection();
/// textarea.move_cursor(CursorMove::Back);
/// assert_eq!(textarea.selection_range(), Some(((0, 1), (0, 0))));
/// ```
pub fn selection_range(&self) -> Option<((usize, usize), (usize, usize))> {
self.selection_start
.map(|selection_start| (selection_start, self.cursor))
}

/// Set text alignment. When [`Alignment::Center`] or [`Alignment::Right`] is set, line number is automatically
/// disabled because those alignments don't work well with line numbers.
/// ```
Expand Down

0 comments on commit b7a7e3d

Please sign in to comment.