Unnamed repository; edit this file 'description' to name the repository.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
//! Input event handling, currently backed by crossterm.
use anyhow::{anyhow, Error};
use helix_core::unicode::width::UnicodeWidthStr;
use serde::de::{self, Deserialize, Deserializer};
use std::fmt;

use crate::keyboard::{KeyCode, KeyModifiers};

/// Represents a key event.
// We use a newtype here because we want to customize Deserialize and Display.
#[derive(Debug, PartialEq, Eq, PartialOrd, Clone, Copy, Hash)]
pub struct KeyEvent {
    pub code: KeyCode,
    pub modifiers: KeyModifiers,
}

impl KeyEvent {
    /// If a character was pressed, return it.
    pub fn char(&self) -> Option<char> {
        match self.code {
            KeyCode::Char(ch) => Some(ch),
            _ => None,
        }
    }
}

pub(crate) mod keys {
    pub(crate) const BACKSPACE: &str = "backspace";
    pub(crate) const ENTER: &str = "ret";
    pub(crate) const LEFT: &str = "left";
    pub(crate) const RIGHT: &str = "right";
    pub(crate) const UP: &str = "up";
    pub(crate) const DOWN: &str = "down";
    pub(crate) const HOME: &str = "home";
    pub(crate) const END: &str = "end";
    pub(crate) const PAGEUP: &str = "pageup";
    pub(crate) const PAGEDOWN: &str = "pagedown";
    pub(crate) const TAB: &str = "tab";
    pub(crate) const BACKTAB: &str = "backtab";
    pub(crate) const DELETE: &str = "del";
    pub(crate) const INSERT: &str = "ins";
    pub(crate) const NULL: &str = "null";
    pub(crate) const ESC: &str = "esc";
    pub(crate) const SPACE: &str = "space";
    pub(crate) const LESS_THAN: &str = "lt";
    pub(crate) const GREATER_THAN: &str = "gt";
    pub(crate) const PLUS: &str = "plus";
    pub(crate) const MINUS: &str = "minus";
    pub(crate) const SEMICOLON: &str = "semicolon";
    pub(crate) const PERCENT: &str = "percent";
}

impl fmt::Display for KeyEvent {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_fmt(format_args!(
            "{}{}{}",
            if self.modifiers.contains(KeyModifiers::SHIFT) {
                "S-"
            } else {
                ""
            },
            if self.modifiers.contains(KeyModifiers::ALT) {
                "A-"
            } else {
                ""
            },
            if self.modifiers.contains(KeyModifiers::CONTROL) {
                "C-"
            } else {
                ""
            },
        ))?;
        match self.code {
            KeyCode::Backspace => f.write_str(keys::BACKSPACE)?,
            KeyCode::Enter => f.write_str(keys::ENTER)?,
            KeyCode::Left => f.write_str(keys::LEFT)?,
            KeyCode::Right => f.write_str(keys::RIGHT)?,
            KeyCode::Up => f.write_str(keys::UP)?,
            KeyCode::Down => f.write_str(keys::DOWN)?,
            KeyCode::Home => f.write_str(keys::HOME)?,
            KeyCode::End => f.write_str(keys::END)?,
            KeyCode::PageUp => f.write_str(keys::PAGEUP)?,
            KeyCode::PageDown => f.write_str(keys::PAGEDOWN)?,
            KeyCode::Tab => f.write_str(keys::TAB)?,
            KeyCode::BackTab => f.write_str(keys::BACKTAB)?,
            KeyCode::Delete => f.write_str(keys::DELETE)?,
            KeyCode::Insert => f.write_str(keys::INSERT)?,
            KeyCode::Null => f.write_str(keys::NULL)?,
            KeyCode::Esc => f.write_str(keys::ESC)?,
            KeyCode::Char(' ') => f.write_str(keys::SPACE)?,
            KeyCode::Char('<') => f.write_str(keys::LESS_THAN)?,
            KeyCode::Char('>') => f.write_str(keys::GREATER_THAN)?,
            KeyCode::Char('+') => f.write_str(keys::PLUS)?,
            KeyCode::Char('-') => f.write_str(keys::MINUS)?,
            KeyCode::Char(';') => f.write_str(keys::SEMICOLON)?,
            KeyCode::Char('%') => f.write_str(keys::PERCENT)?,
            KeyCode::F(i) => f.write_fmt(format_args!("F{}", i))?,
            KeyCode::Char(c) => f.write_fmt(format_args!("{}", c))?,
        };
        Ok(())
    }
}

impl UnicodeWidthStr for KeyEvent {
    fn width(&self) -> usize {
        use helix_core::unicode::width::UnicodeWidthChar;
        let mut width = match self.code {
            KeyCode::Backspace => keys::BACKSPACE.len(),
            KeyCode::Enter => keys::ENTER.len(),
            KeyCode::Left => keys::LEFT.len(),
            KeyCode::Right => keys::RIGHT.len(),
            KeyCode::Up => keys::UP.len(),
            KeyCode::Down => keys::DOWN.len(),
            KeyCode::Home => keys::HOME.len(),
            KeyCode::End => keys::END.len(),
            KeyCode::PageUp => keys::PAGEUP.len(),
            KeyCode::PageDown => keys::PAGEDOWN.len(),
            KeyCode::Tab => keys::TAB.len(),
            KeyCode::BackTab => keys::BACKTAB.len(),
            KeyCode::Delete => keys::DELETE.len(),
            KeyCode::Insert => keys::INSERT.len(),
            KeyCode::Null => keys::NULL.len(),
            KeyCode::Esc => keys::ESC.len(),
            KeyCode::Char(' ') => keys::SPACE.len(),
            KeyCode::Char('<') => keys::LESS_THAN.len(),
            KeyCode::Char('>') => keys::GREATER_THAN.len(),
            KeyCode::Char('+') => keys::PLUS.len(),
            KeyCode::Char('-') => keys::MINUS.len(),
            KeyCode::Char(';') => keys::SEMICOLON.len(),
            KeyCode::Char('%') => keys::PERCENT.len(),
            KeyCode::F(1..=9) => 2,
            KeyCode::F(_) => 3,
            KeyCode::Char(c) => c.width().unwrap_or(0),
        };
        if self.modifiers.contains(KeyModifiers::SHIFT) {
            width += 2;
        }
        if self.modifiers.contains(KeyModifiers::ALT) {
            width += 2;
        }
        if self.modifiers.contains(KeyModifiers::CONTROL) {
            width += 2;
        }
        width
    }

    fn width_cjk(&self) -> usize {
        self.width()
    }
}

impl std::str::FromStr for KeyEvent {
    type Err = Error;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        let mut tokens: Vec<_> = s.split('-').collect();
        let code = match tokens.pop().ok_or_else(|| anyhow!("Missing key code"))? {
            keys::BACKSPACE => KeyCode::Backspace,
            keys::ENTER => KeyCode::Enter,
            keys::LEFT => KeyCode::Left,
            keys::RIGHT => KeyCode::Right,
            keys::UP => KeyCode::Up,
            keys::DOWN => KeyCode::Down,
            keys::HOME => KeyCode::Home,
            keys::END => KeyCode::End,
            keys::PAGEUP => KeyCode::PageUp,
            keys::PAGEDOWN => KeyCode::PageDown,
            keys::TAB => KeyCode::Tab,
            keys::BACKTAB => KeyCode::BackTab,
            keys::DELETE => KeyCode::Delete,
            keys::INSERT => KeyCode::Insert,
            keys::NULL => KeyCode::Null,
            keys::ESC => KeyCode::Esc,
            keys::SPACE => KeyCode::Char(' '),
            keys::LESS_THAN => KeyCode::Char('<'),
            keys::GREATER_THAN => KeyCode::Char('>'),
            keys::PLUS => KeyCode::Char('+'),
            keys::MINUS => KeyCode::Char('-'),
            keys::SEMICOLON => KeyCode::Char(';'),
            keys::PERCENT => KeyCode::Char('%'),
            single if single.chars().count() == 1 => KeyCode::Char(single.chars().next().unwrap()),
            function if function.len() > 1 && function.starts_with('F') => {
                let function: String = function.chars().skip(1).collect();
                let function = str::parse::<u8>(&function)?;
                (function > 0 && function < 13)
                    .then(|| KeyCode::F(function))
                    .ok_or_else(|| anyhow!("Invalid function key '{}'", function))?
            }
            invalid => return Err(anyhow!("Invalid key code '{}'", invalid)),
        };

        let mut modifiers = KeyModifiers::empty();
        for token in tokens {
            let flag = match token {
                "S" => KeyModifiers::SHIFT,
                "A" => KeyModifiers::ALT,
                "C" => KeyModifiers::CONTROL,
                _ => return Err(anyhow!("Invalid key modifier '{}-'", token)),
            };

            if modifiers.contains(flag) {
                return Err(anyhow!("Repeated key modifier '{}-'", token));
            }
            modifiers.insert(flag);
        }

        Ok(KeyEvent { code, modifiers })
    }
}

impl<'de> Deserialize<'de> for KeyEvent {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: Deserializer<'de>,
    {
        let s = String::deserialize(deserializer)?;
        s.parse().map_err(de::Error::custom)
    }
}

#[cfg(feature = "term")]
impl From<crossterm::event::KeyEvent> for KeyEvent {
    fn from(
        crossterm::event::KeyEvent { code, modifiers }: crossterm::event::KeyEvent,
    ) -> KeyEvent {
        KeyEvent {
            code: code.into(),
            modifiers: modifiers.into(),
        }
    }
}

#[cfg(test)]
mod test {
    use super::*;

    #[test]
    fn parsing_unmodified_keys() {
        assert_eq!(
            str::parse::<KeyEvent>("backspace").unwrap(),
            KeyEvent {
                code: KeyCode::Backspace,
                modifiers: KeyModifiers::NONE
            }
        );

        assert_eq!(
            str::parse::<KeyEvent>("left").unwrap(),
            KeyEvent {
                code: KeyCode::Left,
                modifiers: KeyModifiers::NONE
            }
        );

        assert_eq!(
            str::parse::<KeyEvent>(",").unwrap(),
            KeyEvent {
                code: KeyCode::Char(','),
                modifiers: KeyModifiers::NONE
            }
        );

        assert_eq!(
            str::parse::<KeyEvent>("w").unwrap(),
            KeyEvent {
                code: KeyCode::Char('w'),
                modifiers: KeyModifiers::NONE
            }
        );

        assert_eq!(
            str::parse::<KeyEvent>("F12").unwrap(),
            KeyEvent {
                code: KeyCode::F(12),
                modifiers: KeyModifiers::NONE
            }
        );
    }

    #[test]
    fn parsing_modified_keys() {
        assert_eq!(
            str::parse::<KeyEvent>("S-minus").unwrap(),
            KeyEvent {
                code: KeyCode::Char('-'),
                modifiers: KeyModifiers::SHIFT
            }
        );

        assert_eq!(
            str::parse::<KeyEvent>("C-A-S-F12").unwrap(),
            KeyEvent {
                code: KeyCode::F(12),
                modifiers: KeyModifiers::SHIFT | KeyModifiers::CONTROL | KeyModifiers::ALT
            }
        );

        assert_eq!(
            str::parse::<KeyEvent>("S-C-2").unwrap(),
            KeyEvent {
                code: KeyCode::Char('2'),
                modifiers: KeyModifiers::SHIFT | KeyModifiers::CONTROL
            }
        );
    }

    #[test]
    fn parsing_nonsensical_keys_fails() {
        assert!(str::parse::<KeyEvent>("F13").is_err());
        assert!(str::parse::<KeyEvent>("F0").is_err());
        assert!(str::parse::<KeyEvent>("aaa").is_err());
        assert!(str::parse::<KeyEvent>("S-S-a").is_err());
        assert!(str::parse::<KeyEvent>("C-A-S-C-1").is_err());
        assert!(str::parse::<KeyEvent>("FU").is_err());
        assert!(str::parse::<KeyEvent>("123").is_err());
        assert!(str::parse::<KeyEvent>("S--").is_err());
    }
}
o_line { line_back += 1; } // do not include current paragraph on paragraph end (include next) if !(curr_empty_to_line && last_char) { let mut lines = slice.lines_at(line_back); lines.reverse(); let mut lines = lines.map(rope_is_line_ending).peekable(); while lines.next_if(|&e| e).is_some() { line_back -= 1; } while lines.next_if(|&e| !e).is_some() { line_back -= 1; } } // skip character after paragraph boundary if curr_empty_to_line && last_char { line += 1; } let mut lines = slice.lines_at(line).map(rope_is_line_ending).peekable(); let mut count_done = 0; // count how many non-whitespace paragraphs done for _ in 0..count { let mut done = false; while lines.next_if(|&e| !e).is_some() { line += 1; done = true; } while lines.next_if(|&e| e).is_some() { line += 1; } count_done += done as usize; } // search one paragraph backwards for last paragraph // makes `map` at the end of the paragraph with trailing newlines useful let last_paragraph = count_done != count && lines.peek().is_none(); if last_paragraph { let mut lines = slice.lines_at(line_back); lines.reverse(); let mut lines = lines.map(rope_is_line_ending).peekable(); while lines.next_if(|&e| e).is_some() { line_back -= 1; } while lines.next_if(|&e| !e).is_some() { line_back -= 1; } } // handle last whitespaces part separately depending on textobject match textobject { TextObject::Around => {} TextObject::Inside => { // remove last whitespace paragraph let mut lines = slice.lines_at(line); lines.reverse(); let mut lines = lines.map(rope_is_line_ending).peekable(); while lines.next_if(|&e| e).is_some() { line -= 1; } } TextObject::Movement => unreachable!(), } let anchor = slice.line_to_char(line_back); let head = slice.line_to_char(line); Range::new(anchor, head) } pub fn textobject_pair_surround( syntax: Option<&Syntax>, slice: RopeSlice, range: Range, textobject: TextObject, ch: char, count: usize, ) -> Range { textobject_pair_surround_impl(syntax, slice, range, textobject, Some(ch), count) } pub fn textobject_pair_surround_closest( syntax: Option<&Syntax>, slice: RopeSlice, range: Range, textobject: TextObject, count: usize, ) -> Range { textobject_pair_surround_impl(syntax, slice, range, textobject, None, count) } fn textobject_pair_surround_impl( syntax: Option<&Syntax>, slice: RopeSlice, range: Range, textobject: TextObject, ch: Option<char>, count: usize, ) -> Range { let pair_pos = match ch { Some(ch) => surround::find_nth_pairs_pos(slice, ch, range, count), None => surround::find_nth_closest_pairs_pos(syntax, slice, range, count), }; pair_pos .map(|(anchor, head)| match textobject { TextObject::Inside => { if anchor < head { Range::new(next_grapheme_boundary(slice, anchor), head) } else { Range::new(anchor, next_grapheme_boundary(slice, head)) } } TextObject::Around => { if anchor < head { Range::new(anchor, next_grapheme_boundary(slice, head)) } else { Range::new(next_grapheme_boundary(slice, anchor), head) } } TextObject::Movement => unreachable!(), }) .unwrap_or(range) } /// Transform the given range to select text objects based on tree-sitter. /// `object_name` is a query capture base name like "function", "class", etc. /// `slice_tree` is the tree-sitter node corresponding to given text slice. pub fn textobject_treesitter( slice: RopeSlice, range: Range, textobject: TextObject, object_name: &str, slice_tree: Node, lang_config: &LanguageConfiguration, _count: usize, ) -> Range { let get_range = move || -> Option<Range> { let byte_pos = slice.char_to_byte(range.cursor(slice)); let capture_name = format!("{}.{}", object_name, textobject); // eg. function.inner let mut cursor = QueryCursor::new(); let node = lang_config .textobject_query()? .capture_nodes(&capture_name, slice_tree, slice, &mut cursor)? .filter(|node| node.byte_range().contains(&byte_pos)) .min_by_key(|node| node.byte_range().len())?; let len = slice.len_bytes(); let start_byte = node.start_byte(); let end_byte = node.end_byte(); if start_byte >= len || end_byte >= len { return None; } let start_char = slice.byte_to_char(start_byte); let end_char = slice.byte_to_char(end_byte); Some(Range::new(start_char, end_char)) }; get_range().unwrap_or(range) } #[cfg(test)] mod test { use super::TextObject::*; use super::*; use crate::Range; use ropey::Rope; #[test] fn test_textobject_word() { // (text, [(char position, textobject, final range), ...]) let tests = &[ ( "cursor at beginning of doc", vec![(0, Inside, (0, 6)), (0, Around, (0, 7))], ), ( "cursor at middle of word", vec![ (13, Inside, (10, 16)), (10, Inside, (10, 16)), (15, Inside, (10, 16)), (13, Around, (10, 17)), (10, Around, (10, 17)), (15, Around, (10, 17)), ], ), ( "cursor between word whitespace", vec![(6, Inside, (6, 6)), (6, Around, (6, 6))], ), ( "cursor on word before newline\n", vec![ (22, Inside, (22, 29)), (28, Inside, (22, 29)), (25, Inside, (22, 29)), (22, Around, (21, 29)), (28, Around, (21, 29)), (25, Around, (21, 29)), ], ), ( "cursor on newline\nnext line", vec![(17, Inside, (17, 17)), (17, Around, (17, 17))], ), ( "cursor on word after newline\nnext line", vec![ (29, Inside, (29, 33)), (30, Inside, (29, 33)), (32, Inside, (29, 33)), (29, Around, (29, 34)), (30, Around, (29, 34)), (32, Around, (29, 34)), ], ), ( "cursor on #$%:;* punctuation", vec![ (13, Inside, (10, 16)), (10, Inside, (10, 16)), (15, Inside, (10, 16)), (13, Around, (10, 17)), (10, Around, (10, 17)), (15, Around, (10, 17)), ], ), ( "cursor on punc%^#$:;.tuation", vec![ (14, Inside, (14, 21)), (20, Inside, (14, 21)), (17, Inside, (14, 21)), (14, Around, (14, 21)), (20, Around, (14, 21)), (17, Around, (14, 21)), ], ), ( "cursor in extra whitespace", vec![ (9, Inside, (9, 9)), (10, Inside, (10, 10)), (11, Inside, (11, 11)), (9, Around, (9, 9)), (10, Around, (10, 10)), (11, Around, (11, 11)), ], ), ( "cursor on word with extra whitespace", vec![(11, Inside, (10, 14)), (11, Around, (10, 17))], ), ( "cursor at end with extra whitespace", vec![(28, Inside, (27, 37)), (28, Around, (24, 37))], ), ( "cursor at end of doc", vec![(19, Inside, (17, 20)), (19, Around, (16, 20))], ), ]; for (sample, scenario) in tests { let doc = Rope::from(*sample); let slice = doc.slice(..); for &case in scenario { let (pos, objtype, expected_range) = case; // cursor is a single width selection let range = Range::new(pos, pos + 1); let result = textobject_word(slice, range, objtype, 1, false); assert_eq!( result, expected_range.into(), "\nCase failed: {:?} - {:?}", sample, case ); } } } #[test] fn test_textobject_paragraph_inside_single() { let tests = [ ("#[|]#", "#[|]#"), ("firs#[t|]#\n\nparagraph\n\n", "#[first\n|]#\nparagraph\n\n"), ( "second\n\npa#[r|]#agraph\n\n", "second\n\n#[paragraph\n|]#\n", ), ("#[f|]#irst char\n\n", "#[first char\n|]#\n"), ("last char\n#[\n|]#", "#[last char\n|]#\n"), ( "empty to line\n#[\n|]#paragraph boundary\n\n", "empty to line\n\n#[paragraph boundary\n|]#\n", ), ( "line to empty\n\n#[p|]#aragraph boundary\n\n", "line to empty\n\n#[paragraph boundary\n|]#\n", ), ]; for (before, expected) in tests { let (s, selection) = crate::test::print(before); let text = Rope::from(s.as_str()); let selection = selection .transform(|r| textobject_paragraph(text.slice(..), r, TextObject::Inside, 1)); let actual = crate::test::plain(s.as_ref(), &selection); assert_eq!(actual, expected, "\nbefore: `{:?}`", before); } } #[test] fn test_textobject_paragraph_inside_double() { let tests = [ ( "last two\n\n#[p|]#aragraph\n\nwithout whitespaces\n\n", "last two\n\n#[paragraph\n\nwithout whitespaces\n|]#\n", ), ( "last two\n#[\n|]#paragraph\n\nwithout whitespaces\n\n", "last two\n\n#[paragraph\n\nwithout whitespaces\n|]#\n", ), ]; for (before, expected) in tests { let (s, selection) = crate::test::print(before); let text = Rope::from(s.as_str()); let selection = selection .transform(|r| textobject_paragraph(text.slice(..), r, TextObject::Inside, 2)); let actual = crate::test::plain(s.as_ref(), &selection); assert_eq!(actual, expected, "\nbefore: `{:?}`", before); } } #[test] fn test_textobject_paragraph_around_single() { let tests = [ ("#[|]#", "#[|]#"), ("firs#[t|]#\n\nparagraph\n\n", "#[first\n\n|]#paragraph\n\n"), ( "second\n\npa#[r|]#agraph\n\n", "second\n\n#[paragraph\n\n|]#", ), ("#[f|]#irst char\n\n", "#[first char\n\n|]#"), ("last char\n#[\n|]#", "#[last char\n\n|]#"), ( "empty to line\n#[\n|]#paragraph boundary\n\n", "empty to line\n\n#[paragraph boundary\n\n|]#", ), ( "line to empty\n\n#[p|]#aragraph boundary\n\n", "line to empty\n\n#[paragraph boundary\n\n|]#", ), ]; for (before, expected) in tests { let (s, selection) = crate::test::print(before); let text = Rope::from(s.as_str()); let selection = selection .transform(|r| textobject_paragraph(text.slice(..), r, TextObject::Around, 1)); let actual = crate::test::plain(s.as_ref(), &selection); assert_eq!(actual, expected, "\nbefore: `{:?}`", before); } } #[test] fn test_textobject_surround() { // (text, [(cursor position, textobject, final range, surround char, count), ...]) let tests = &[ ( "simple (single) surround pairs", vec![ (3, Inside, (3, 3), '(', 1), (7, Inside, (8, 14), ')', 1), (10, Inside, (8, 14), '(', 1), (14, Inside, (8, 14), ')', 1), (3, Around, (3, 3), '(', 1), (7, Around, (7, 15), ')', 1), (10, Around, (7, 15), '(', 1), (14, Around, (7, 15), ')', 1), ], ), ( "samexx 'single' surround pairs", vec![ (3, Inside, (3, 3), '\'', 1), (7, Inside, (7, 7), '\'', 1), (10, Inside, (8, 14), '\'', 1), (14, Inside, (14, 14), '\'', 1), (3, Around, (3, 3), '\'', 1), (7, Around, (7, 7), '\'', 1), (10, Around, (7, 15), '\'', 1), (14, Around, (14, 14), '\'', 1), ], ), ( "(nested (surround (pairs)) 3 levels)", vec![ (0, Inside, (1, 35), '(', 1), (6, Inside, (1, 35), ')', 1), (8, Inside, (9, 25), '(', 1), (8, Inside, (9, 35), ')', 2), (20, Inside, (9, 25), '(', 2), (20, Inside, (1, 35), ')', 3), (0, Around, (0, 36), '(', 1), (6, Around, (0, 36), ')', 1), (8, Around, (8, 26), '(', 1), (8, Around, (8, 36), ')', 2), (20, Around, (8, 26), '(', 2), (20, Around, (0, 36), ')', 3), ], ), ( "(mixed {surround [pair] same} line)", vec![ (2, Inside, (1, 34), '(', 1), (9, Inside, (8, 28), '{', 1), (18, Inside, (18, 22), '[', 1), (2, Around, (0, 35), '(', 1), (9, Around, (7, 29), '{', 1), (18, Around, (17, 23), '[', 1), ], ), ( "(stepped (surround) pairs (should) skip)", vec![(22, Inside, (1, 39), '(', 1), (22, Around, (0, 40), '(', 1)], ), ( "[surround pairs{\non different]\nlines}", vec![ (7, Inside, (1, 29), '[', 1), (15, Inside, (16, 36), '{', 1), (7, Around, (0, 30), '[', 1), (15, Around, (15, 37), '{', 1), ], ), ]; for (sample, scenario) in tests { let doc = Rope::from(*sample); let slice = doc.slice(..); for &case in scenario { let (pos, objtype, expected_range, ch, count) = case; let result = textobject_pair_surround(None, slice, Range::point(pos), objtype, ch, count); assert_eq!( result, expected_range.into(), "\nCase failed: {:?} - {:?}", sample, case ); } } } }