2099 lines · 67.8 KB · Rust
RawDownload
use std::ops::Range; use crate::{    motion::right,    state::{Mode, Operator},    Vim,};use editor::{    display_map::{DisplaySnapshot, ToDisplayPoint},    movement::{self, FindRange},    Bias, DisplayPoint, Editor,};use gpui::{actions, impl_actions, ViewContext};use itertools::Itertools;use language::{BufferSnapshot, CharKind, Point, Selection, TextObject, TreeSitterOptions};use multi_buffer::MultiBufferRow;use schemars::JsonSchema;use serde::Deserialize; #[derive(Copy, Clone, Debug, PartialEq, Eq, Deserialize, JsonSchema)]pub enum Object {    Word { ignore_punctuation: bool },    Subword { ignore_punctuation: bool },    Sentence,    Paragraph,    Quotes,    BackQuotes,    AnyQuotes,    DoubleQuotes,    VerticalBars,    Parentheses,    SquareBrackets,    CurlyBrackets,    AngleBrackets,    Argument,    IndentObj { include_below: bool },    Tag,    Method,    Class,    Comment,} #[derive(Clone, Deserialize, JsonSchema, PartialEq)]#[serde(rename_all = "camelCase")]struct Word {    #[serde(default)]    ignore_punctuation: bool,} #[derive(Clone, Deserialize, JsonSchema, PartialEq)]#[serde(rename_all = "camelCase")]struct Subword {    #[serde(default)]    ignore_punctuation: bool,}#[derive(Clone, Deserialize, JsonSchema, PartialEq)]#[serde(rename_all = "camelCase")]struct IndentObj {    #[serde(default)]    include_below: bool,} impl_actions!(vim, [Word, Subword, IndentObj]); actions!(    vim,    [        Sentence,        Paragraph,        Quotes,        BackQuotes,        AnyQuotes,        DoubleQuotes,        VerticalBars,        Parentheses,        SquareBrackets,        CurlyBrackets,        AngleBrackets,        Argument,        Tag,        Method,        Class,        Comment    ]); pub fn register(editor: &mut Editor, cx: &mut ViewContext<Vim>) {    Vim::action(        editor,        cx,        |vim, &Word { ignore_punctuation }: &Word, cx| {            vim.object(Object::Word { ignore_punctuation }, cx)        },    );    Vim::action(        editor,        cx,        |vim, &Subword { ignore_punctuation }: &Subword, cx| {            vim.object(Object::Subword { ignore_punctuation }, cx)        },    );    Vim::action(editor, cx, |vim, _: &Tag, cx| vim.object(Object::Tag, cx));    Vim::action(editor, cx, |vim, _: &Sentence, cx| {        vim.object(Object::Sentence, cx)    });    Vim::action(editor, cx, |vim, _: &Paragraph, cx| {        vim.object(Object::Paragraph, cx)    });    Vim::action(editor, cx, |vim, _: &Quotes, cx| {        vim.object(Object::Quotes, cx)    });    Vim::action(editor, cx, |vim, _: &BackQuotes, cx| {        vim.object(Object::BackQuotes, cx)    });    Vim::action(editor, cx, |vim, _: &AnyQuotes, cx| {        vim.object(Object::AnyQuotes, cx)    });    Vim::action(editor, cx, |vim, _: &DoubleQuotes, cx| {        vim.object(Object::DoubleQuotes, cx)    });    Vim::action(editor, cx, |vim, _: &Parentheses, cx| {        vim.object(Object::Parentheses, cx)    });    Vim::action(editor, cx, |vim, _: &SquareBrackets, cx| {        vim.object(Object::SquareBrackets, cx)    });    Vim::action(editor, cx, |vim, _: &CurlyBrackets, cx| {        vim.object(Object::CurlyBrackets, cx)    });    Vim::action(editor, cx, |vim, _: &AngleBrackets, cx| {        vim.object(Object::AngleBrackets, cx)    });    Vim::action(editor, cx, |vim, _: &VerticalBars, cx| {        vim.object(Object::VerticalBars, cx)    });    Vim::action(editor, cx, |vim, _: &Argument, cx| {        vim.object(Object::Argument, cx)    });    Vim::action(editor, cx, |vim, _: &Method, cx| {        vim.object(Object::Method, cx)    });    Vim::action(editor, cx, |vim, _: &Class, cx| {        vim.object(Object::Class, cx)    });    Vim::action(editor, cx, |vim, _: &Comment, cx| {        if !matches!(vim.active_operator(), Some(Operator::Object { .. })) {            vim.push_operator(Operator::Object { around: true }, cx);        }        vim.object(Object::Comment, cx)    });    Vim::action(        editor,        cx,        |vim, &IndentObj { include_below }: &IndentObj, cx| {            vim.object(Object::IndentObj { include_below }, cx)        },    );} impl Vim {    fn object(&mut self, object: Object, cx: &mut ViewContext<Self>) {        match self.mode {            Mode::Normal => self.normal_object(object, cx),            Mode::Visual | Mode::VisualLine | Mode::VisualBlock => self.visual_object(object, cx),            Mode::Insert | Mode::Replace | Mode::HelixNormal => {                // Shouldn't execute a text object in insert mode. Ignoring            }        }    }} impl Object {    pub fn is_multiline(self) -> bool {        match self {            Object::Word { .. }            | Object::Subword { .. }            | Object::Quotes            | Object::BackQuotes            | Object::AnyQuotes            | Object::VerticalBars            | Object::DoubleQuotes => false,            Object::Sentence            | Object::Paragraph            | Object::Parentheses            | Object::Tag            | Object::AngleBrackets            | Object::CurlyBrackets            | Object::SquareBrackets            | Object::Argument            | Object::Method            | Object::Class            | Object::Comment            | Object::IndentObj { .. } => true,        }    }     pub fn always_expands_both_ways(self) -> bool {        match self {            Object::Word { .. }            | Object::Subword { .. }            | Object::Sentence            | Object::Paragraph            | Object::Argument            | Object::IndentObj { .. } => false,            Object::Quotes            | Object::BackQuotes            | Object::AnyQuotes            | Object::DoubleQuotes            | Object::VerticalBars            | Object::Parentheses            | Object::SquareBrackets            | Object::Tag            | Object::Method            | Object::Class            | Object::Comment            | Object::CurlyBrackets            | Object::AngleBrackets => true,        }    }     pub fn target_visual_mode(self, current_mode: Mode, around: bool) -> Mode {        match self {            Object::Word { .. }            | Object::Subword { .. }            | Object::Sentence            | Object::Quotes            | Object::AnyQuotes            | Object::BackQuotes            | Object::DoubleQuotes => {                if current_mode == Mode::VisualBlock {                    Mode::VisualBlock                } else {                    Mode::Visual                }            }            Object::Parentheses            | Object::SquareBrackets            | Object::CurlyBrackets            | Object::AngleBrackets            | Object::VerticalBars            | Object::Tag            | Object::Comment            | Object::Argument            | Object::IndentObj { .. } => Mode::Visual,            Object::Method | Object::Class => {                if around {                    Mode::VisualLine                } else {                    Mode::Visual                }            }            Object::Paragraph => Mode::VisualLine,        }    }     pub fn range(        self,        map: &DisplaySnapshot,        selection: Selection<DisplayPoint>,        around: bool,    ) -> Option<Range<DisplayPoint>> {        let relative_to = selection.head();        match self {            Object::Word { ignore_punctuation } => {                if around {                    around_word(map, relative_to, ignore_punctuation)                } else {                    in_word(map, relative_to, ignore_punctuation)                }            }            Object::Subword { ignore_punctuation } => {                if around {                    around_subword(map, relative_to, ignore_punctuation)                } else {                    in_subword(map, relative_to, ignore_punctuation)                }            }            Object::Sentence => sentence(map, relative_to, around),            Object::Paragraph => paragraph(map, relative_to, around),            Object::Quotes => {                surrounding_markers(map, relative_to, around, self.is_multiline(), '\'', '\'')            }            Object::BackQuotes => {                surrounding_markers(map, relative_to, around, self.is_multiline(), '`', '`')            }            Object::AnyQuotes => {                let quote_types = ['\'', '"', '`']; // Types of quotes to handle                let relative_offset = relative_to.to_offset(map, Bias::Left) as isize;                 // Find the closest matching quote range                quote_types                    .iter()                    .flat_map(|&quote| {                        // Get ranges for each quote type                        surrounding_markers(                            map,                            relative_to,                            around,                            self.is_multiline(),                            quote,                            quote,                        )                    })                    .min_by_key(|range| {                        // Calculate proximity of ranges to the cursor                        let start_distance = (relative_offset                            - range.start.to_offset(map, Bias::Left) as isize)                            .abs();                        let end_distance = (relative_offset                            - range.end.to_offset(map, Bias::Right) as isize)                            .abs();                        start_distance + end_distance                    })            }            Object::DoubleQuotes => {                surrounding_markers(map, relative_to, around, self.is_multiline(), '"', '"')            }            Object::VerticalBars => {                surrounding_markers(map, relative_to, around, self.is_multiline(), '|', '|')            }            Object::Parentheses => {                surrounding_markers(map, relative_to, around, self.is_multiline(), '(', ')')            }            Object::Tag => {                let head = selection.head();                let range = selection.range();                surrounding_html_tag(map, head, range, around)            }            Object::SquareBrackets => {                surrounding_markers(map, relative_to, around, self.is_multiline(), '[', ']')            }            Object::CurlyBrackets => {                surrounding_markers(map, relative_to, around, self.is_multiline(), '{', '}')            }            Object::AngleBrackets => {                surrounding_markers(map, relative_to, around, self.is_multiline(), '<', '>')            }            Object::Method => text_object(                map,                relative_to,                if around {                    TextObject::AroundFunction                } else {                    TextObject::InsideFunction                },            ),            Object::Comment => text_object(                map,                relative_to,                if around {                    TextObject::AroundComment                } else {                    TextObject::InsideComment                },            ),            Object::Class => text_object(                map,                relative_to,                if around {                    TextObject::AroundClass                } else {                    TextObject::InsideClass                },            ),            Object::Argument => argument(map, relative_to, around),            Object::IndentObj { include_below } => indent(map, relative_to, around, include_below),        }    }     pub fn expand_selection(        self,        map: &DisplaySnapshot,        selection: &mut Selection<DisplayPoint>,        around: bool,    ) -> bool {        if let Some(range) = self.range(map, selection.clone(), around) {            selection.start = range.start;            selection.end = range.end;            true        } else {            false        }    }} /// Returns a range that surrounds the word `relative_to` is in.////// If `relative_to` is at the start of a word, return the word./// If `relative_to` is between words, return the space between.fn in_word(    map: &DisplaySnapshot,    relative_to: DisplayPoint,    ignore_punctuation: bool,) -> Option<Range<DisplayPoint>> {    // Use motion::right so that we consider the character under the cursor when looking for the start    let classifier = map        .buffer_snapshot        .char_classifier_at(relative_to.to_point(map))        .ignore_punctuation(ignore_punctuation);    let start = movement::find_preceding_boundary_display_point(        map,        right(map, relative_to, 1),        movement::FindRange::SingleLine,        |left, right| classifier.kind(left) != classifier.kind(right),    );     let end = movement::find_boundary(map, relative_to, FindRange::SingleLine, |left, right| {        classifier.kind(left) != classifier.kind(right)    });     Some(start..end)} fn in_subword(    map: &DisplaySnapshot,    relative_to: DisplayPoint,    ignore_punctuation: bool,) -> Option<Range<DisplayPoint>> {    let offset = relative_to.to_offset(map, Bias::Left);    // Use motion::right so that we consider the character under the cursor when looking for the start    let classifier = map        .buffer_snapshot        .char_classifier_at(relative_to.to_point(map))        .ignore_punctuation(ignore_punctuation);    let in_subword = map        .buffer_chars_at(offset)        .next()        .map(|(c, _)| {            if classifier.is_word('-') {                !classifier.is_whitespace(c) && c != '_' && c != '-'            } else {                !classifier.is_whitespace(c) && c != '_'            }        })        .unwrap_or(false);     let start = if in_subword {        movement::find_preceding_boundary_display_point(            map,            right(map, relative_to, 1),            movement::FindRange::SingleLine,            |left, right| {                let is_word_start = classifier.kind(left) != classifier.kind(right);                let is_subword_start = classifier.is_word('-') && left == '-' && right != '-'                    || left == '_' && right != '_'                    || left.is_lowercase() && right.is_uppercase();                is_word_start || is_subword_start            },        )    } else {        movement::find_boundary(map, relative_to, FindRange::SingleLine, |left, right| {            let is_word_start = classifier.kind(left) != classifier.kind(right);            let is_subword_start = classifier.is_word('-') && left == '-' && right != '-'                || left == '_' && right != '_'                || left.is_lowercase() && right.is_uppercase();            is_word_start || is_subword_start        })    };     let end = movement::find_boundary(map, relative_to, FindRange::SingleLine, |left, right| {        let is_word_end = classifier.kind(left) != classifier.kind(right);        let is_subword_end = classifier.is_word('-') && left != '-' && right == '-'            || left != '_' && right == '_'            || left.is_lowercase() && right.is_uppercase();        is_word_end || is_subword_end    });     Some(start..end)} pub fn surrounding_html_tag(    map: &DisplaySnapshot,    head: DisplayPoint,    range: Range<DisplayPoint>,    around: bool,) -> Option<Range<DisplayPoint>> {    fn read_tag(chars: impl Iterator<Item = char>) -> String {        chars            .take_while(|c| c.is_alphanumeric() || *c == ':' || *c == '-' || *c == '_' || *c == '.')            .collect()    }    fn open_tag(mut chars: impl Iterator<Item = char>) -> Option<String> {        if Some('<') != chars.next() {            return None;        }        Some(read_tag(chars))    }    fn close_tag(mut chars: impl Iterator<Item = char>) -> Option<String> {        if (Some('<'), Some('/')) != (chars.next(), chars.next()) {            return None;        }        Some(read_tag(chars))    }     let snapshot = &map.buffer_snapshot;    let offset = head.to_offset(map, Bias::Left);    let mut excerpt = snapshot.excerpt_containing(offset..offset)?;    let buffer = excerpt.buffer();    let offset = excerpt.map_offset_to_buffer(offset); 

Lines 1–500 of 2099.