Skip to content

Visual Studio Code, rebuilt in Rust

Rust
13.6 KB
Raw Blame
//! Mouse selection with alacritty_terminal 0.25's rules (`selection.rs`, `term/search.rs`, `Term::selection_to_string`),
//! which the port's selection tests and copy behavior were written against. Its anchors follow their cells as output
//! scrolls, the way xterm.js's selection follows the buffer.

use std::mem;

use crate::{Column, Flags, Line, Point, Side, Term, TrackedPoint};

#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum SelectionType {
    Simple,
    Block,
    Semantic,
    Lines,
}

/// The selected cells, `start` to `end` inclusive.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct SelectionRange {
    pub start: Point,
    pub end: Point,
    pub is_block: bool,
}

impl SelectionRange {
    pub fn contains(&self, point: Point) -> bool {
        self.start.line <= point.line
            && self.end.line >= point.line
            && (self.start.column <= point.column || (self.start.line != point.line && !self.is_block))
            && (self.end.column >= point.column || (self.end.line != point.line && !self.is_block))
    }
}

struct Anchor {
    point: TrackedPoint,
    side: Side,
}

pub(crate) struct Selection {
    ty: SelectionType,
    start: Anchor,
    end: Anchor,
}

#[derive(Clone, Copy, PartialEq)]
struct Resolved {
    point: Point,
    side: Side,
}

const BRACKET_PAIRS: [(char, char); 4] = [('(', ')'), ('[', ']'), ('{', '}'), ('<', '>')];

impl Term {
    pub fn start_selection(&mut self, ty: SelectionType, point: Point, side: Side) {
        let point = self.clamp(point);
        self.selection = Some(Selection { ty, start: Anchor { point: self.track(point), side }, end: Anchor { point: self.track(point), side } });
    }

    pub fn update_selection(&mut self, point: Point, side: Side) {
        let point = self.clamp(point);
        let tracked = self.track(point);
        if let Some(selection) = &mut self.selection {
            selection.end = Anchor { point: tracked, side };
        }
    }

    pub fn clear_selection(&mut self) {
        self.selection = None;
    }

    pub fn has_selection(&self) -> bool {
        self.selection.is_some()
    }

    /// A selection that covers at least one cell.
    pub fn has_nonempty_selection(&self) -> bool {
        self.anchors().is_some_and(|(ty, start, end)| !is_empty(ty, start, end))
    }

    fn clamp(&self, point: Point) -> Point {
        let last = self.last_column();
        let mut point = Point::new(point.line, point.column.min(last));
        if point.line < self.topmost_line() {
            point = Point::new(self.topmost_line(), Column(0));
        } else if point.line > self.bottommost_line() {
            point = Point::new(self.bottommost_line(), last);
        }
        point
    }

    fn anchors(&self) -> Option<(SelectionType, Resolved, Resolved)> {
        let selection = self.selection.as_ref()?;
        let start = Resolved { point: self.tracked_point(&selection.start.point)?, side: selection.start.side };
        let end = Resolved { point: self.tracked_point(&selection.end.point)?, side: selection.end.side };
        Some((selection.ty, start, end))
    }

    pub fn selection_range(&self) -> Option<SelectionRange> {
        let (ty, mut start, mut end) = self.anchors()?;
        if start.point > end.point {
            mem::swap(&mut start, &mut end);
        }
        start.point = self.clamp(start.point);
        end.point = self.clamp(end.point);
        match ty {
            SelectionType::Simple => self.range_simple(ty, start, end),
            SelectionType::Block => range_block(ty, start, end),
            SelectionType::Semantic => Some(self.range_semantic(start.point, end.point)),
            SelectionType::Lines => Some(SelectionRange { start: self.line_search_left(start.point), end: self.line_search_right(end.point), is_block: false }),
        }
    }

    fn range_simple(&self, ty: SelectionType, mut start: Resolved, mut end: Resolved) -> Option<SelectionRange> {
        if is_empty(ty, start, end) {
            return None;
        }
        let columns = self.columns();
        if end.side == Side::Left && start.point != end.point {
            if end.point.column.0 == 0 {
                end.point = Point::new(end.point.line - 1, Column(columns - 1));
            } else {
                end.point.column -= 1;
            }
        }
        if start.side == Side::Right && start.point != end.point {
            start.point.column += 1;
            if start.point.column.0 == columns {
                start.point = Point::new(start.point.line + 1, Column(0));
            }
        }
        Some(SelectionRange { start: start.point, end: end.point, is_block: false })
    }

    fn range_semantic(&self, mut start: Point, mut end: Point) -> SelectionRange {
        if start == end
            && let Some(matching) = self.bracket_search(start)
        {
            if matching < start {
                start = matching;
            } else {
                end = matching;
            }
            return SelectionRange { start, end, is_block: false };
        }
        SelectionRange { start: self.semantic_search_left(start), end: self.semantic_search_right(end), is_block: false }
    }

    /// The cell after `point`, wrapping to the next line; `None` past the last cell.
    pub fn next_point(&self, point: Point) -> Option<Point> {
        if point.column < self.last_column() {
            return Some(Point::new(point.line, point.column + 1));
        }
        (point.line < self.bottommost_line()).then(|| Point::new(point.line + 1, Column(0)))
    }

    /// The cell before `point`, wrapping to the previous line; `None` before the first cell.
    pub fn previous_point(&self, point: Point) -> Option<Point> {
        if point.column.0 > 0 {
            return Some(Point::new(point.line, point.column - 1));
        }
        (point.line > self.topmost_line()).then(|| Point::new(point.line - 1, self.last_column()))
    }

    fn bracket_search(&self, point: Point) -> Option<Point> {
        let start_char = self.cell(point).c;
        let (forward, end_char) = BRACKET_PAIRS.iter().find_map(|&(open, close)| match start_char {
            c if c == open => Some((true, close)),
            c if c == close => Some((false, open)),
            _ => None,
        })?;
        let mut skip_pairs = 0;
        let mut point = point;
        loop {
            point = if forward { self.next_point(point)? } else { self.previous_point(point)? };
            let c = self.cell(point).c;
            if c == end_char && skip_pairs == 0 {
                return Some(point);
            } else if c == start_char {
                skip_pairs += 1;
            } else if c == end_char {
                skip_pairs -= 1;
            }
        }
    }

    pub fn semantic_search_left(&self, point: Point) -> Point {
        let spacers = Flags::WIDE_CHAR_SPACER | Flags::LEADING_WIDE_CHAR_SPACER;
        match self.inline_search_left(point, self.semantic_escape_chars()) {
            Ok(found) => {
                let mut next = self.next_point(found);
                while let Some(point) = next {
                    if !self.cell(point).flags.intersects(spacers) {
                        return point;
                    }
                    next = self.next_point(point);
                }
                found
            }
            Err(point) => point,
        }
    }

    pub fn semantic_search_right(&self, point: Point) -> Point {
        match self.inline_search_right(point, self.semantic_escape_chars()) {
            Ok(found) => self.previous_point(found).unwrap_or(found),
            Err(point) => point,
        }
    }

    fn inline_search_left(&self, mut point: Point, needles: &str) -> Result<Point, Point> {
        point.line = point.line.max(self.topmost_line());
        let spacers = Flags::WIDE_CHAR_SPACER | Flags::LEADING_WIDE_CHAR_SPACER;
        let mut previous = self.previous_point(point);
        while let Some(candidate) = previous {
            let cell = self.cell(candidate);
            if candidate.column == self.last_column() && !cell.flags.contains(Flags::WRAPLINE) {
                break;
            }
            point = candidate;
            if !cell.flags.intersects(spacers) && needles.contains(cell.c) {
                return Ok(point);
            }
            previous = self.previous_point(point);
        }
        Err(point)
    }

    fn inline_search_right(&self, mut point: Point, needles: &str) -> Result<Point, Point> {
        point.line = point.line.max(self.topmost_line());
        let spacers = Flags::WIDE_CHAR_SPACER | Flags::LEADING_WIDE_CHAR_SPACER;
        let last_column = self.last_column();
        if point.column == last_column && !self.cell(point).flags.contains(Flags::WRAPLINE) {
            return Err(point);
        }
        let mut next = self.next_point(point);
        while let Some(candidate) = next {
            point = candidate;
            let cell = self.cell(point);
            if !cell.flags.intersects(spacers) && needles.contains(cell.c) {
                return Ok(point);
            }
            if point.column == last_column && !cell.flags.contains(Flags::WRAPLINE) {
                break;
            }
            next = self.next_point(point);
        }
        Err(point)
    }

    /// The first line of the logical line `point` is on.
    pub fn line_search_left(&self, mut point: Point) -> Point {
        while point.line > self.topmost_line() && self.wraps(point.line - 1) {
            point.line -= 1;
        }
        Point::new(point.line, Column(0))
    }

    /// The last line of the logical line `point` is on.
    pub fn line_search_right(&self, mut point: Point) -> Point {
        while point.line.0 + 1 < self.screen_lines() as i32 && self.wraps(point.line) {
            point.line += 1;
        }
        Point::new(point.line, self.last_column())
    }

    pub fn selection_to_string(&self) -> Option<String> {
        let ty = self.selection.as_ref()?.ty;
        let SelectionRange { start, end, .. } = self.selection_range()?;
        let mut text = String::new();
        match ty {
            SelectionType::Block => {
                for line in start.line.0..end.line.0 {
                    text += self.line_to_string(Line(line), start.column, end.column, start.column.0 != 0).trim_end();
                    text += "\n";
                }
                text += self.line_to_string(end.line, start.column, end.column, true).trim_end();
            }
            SelectionType::Lines => text = self.bounds_to_string(start, end) + "\n",
            _ => text = self.bounds_to_string(start, end),
        }
        Some(text)
    }

    pub fn bounds_to_string(&self, start: Point, end: Point) -> String {
        let mut text = String::new();
        for line in start.line.0..=end.line.0 {
            let line = Line(line);
            let start_column = if line == start.line { start.column } else { Column(0) };
            let end_column = if line == end.line { end.column } else { self.last_column() };
            text += &self.line_to_string(line, start_column, end_column, line == end.line);
        }
        text.strip_suffix('\n').map(str::to_owned).unwrap_or(text)
    }

    /// Columns `start..end` of `line` as alacritty's `line_to_string`: `end` itself is read too, up to the text's end.
    fn line_to_string(&self, line: Line, mut start: Column, end: Column, include_wrapped_wide: bool) -> String {
        let row = self.row(line);
        let length = row.line_length().min(end + 1);
        if row[start].flags.contains(Flags::WIDE_CHAR_SPACER) {
            start -= 1;
        }
        let mut text = String::new();
        for column in start.0..length.0 {
            let cell = &row[Column(column)];
            if !cell.flags.intersects(Flags::WIDE_CHAR_SPACER | Flags::LEADING_WIDE_CHAR_SPACER) {
                text.push(cell.c);
                text.extend(&cell.zerowidth);
            }
        }
        if end >= self.last_column() && (length.0 == 0 || !row[length - 1].flags.contains(Flags::WRAPLINE)) {
            text.push('\n');
        }
        if length.0 == self.columns() && length.0 >= 2 && row[length - 1].flags.contains(Flags::LEADING_WIDE_CHAR_SPACER) && include_wrapped_wide {
            text.push(self.cell(Point::new(line - 1, Column(0))).c);
        }
        text
    }
}

fn is_empty(ty: SelectionType, start: Resolved, end: Resolved) -> bool {
    match ty {
        SelectionType::Simple => {
            let (start, end) = if start.point > end.point { (end, start) } else { (start, end) };
            start == end || (start.side == Side::Right && end.side == Side::Left && start.point.line == end.point.line && start.point.column + 1 == end.point.column)
        }
        SelectionType::Block => {
            (start.point.column == end.point.column && start.side == end.side)
                || (start.point.column + 1 == end.point.column && start.side == Side::Right && end.side == Side::Left)
                || (end.point.column + 1 == start.point.column && start.side == Side::Left && end.side == Side::Right)
        }
        SelectionType::Semantic | SelectionType::Lines => false,
    }
}

fn range_block(ty: SelectionType, mut start: Resolved, mut end: Resolved) -> Option<SelectionRange> {
    if is_empty(ty, start, end) {
        return None;
    }
    if start.point.column > end.point.column {
        mem::swap(&mut start.side, &mut end.side);
        mem::swap(&mut start.point.column, &mut end.point.column);
    }
    if end.side == Side::Left && start.point != end.point && end.point.column.0 > 0 {
        end.point.column -= 1;
    }
    if start.side == Side::Right && start.point != end.point {
        start.point.column += 1;
    }
    Some(SelectionRange { start: start.point, end: end.point, is_block: true })
}