rust/crates/ra_ide_api_light/src/extend_selection.rs

405 lines
10 KiB
Rust
Raw Normal View History

2018-09-16 11:54:24 +02:00
use ra_syntax::{
2019-01-07 14:53:24 +01:00
Direction, SyntaxNode, TextRange, TextUnit,
algo::{find_covering_node, find_leaf_at_offset, LeafAtOffset},
2018-08-26 09:43:03 +02:00
SyntaxKind::*,
2018-08-07 17:28:30 +02:00
};
2019-01-07 14:53:24 +01:00
pub fn extend_selection(root: &SyntaxNode, range: TextRange) -> Option<TextRange> {
let string_kinds = [COMMENT, STRING, RAW_STRING, BYTE_STRING, RAW_BYTE_STRING];
2019-01-09 20:35:38 +01:00
let list_kinds = [
FIELD_PAT_LIST,
MATCH_ARM_LIST,
NAMED_FIELD_DEF_LIST,
POS_FIELD_DEF_LIST,
NAMED_FIELD_LIST,
2019-01-09 20:35:38 +01:00
ENUM_VARIANT_LIST,
USE_TREE_LIST,
TYPE_PARAM_LIST,
TYPE_ARG_LIST,
PARAM_LIST,
ARG_LIST,
ARRAY_EXPR,
];
2018-08-07 17:28:30 +02:00
if range.is_empty() {
let offset = range.start();
let mut leaves = find_leaf_at_offset(root, offset);
2018-09-04 11:48:39 +02:00
if leaves.clone().all(|it| it.kind() == WHITESPACE) {
return Some(extend_ws(root, leaves.next()?, offset));
2018-08-07 17:28:30 +02:00
}
let leaf_range = match leaves {
2018-09-04 11:48:39 +02:00
LeafAtOffset::None => return None,
LeafAtOffset::Single(l) => {
if string_kinds.contains(&l.kind()) {
extend_single_word_in_comment_or_string(l, offset).unwrap_or_else(|| l.range())
} else {
l.range()
}
}
LeafAtOffset::Between(l, r) => pick_best(l, r).range(),
2018-09-04 11:48:39 +02:00
};
return Some(leaf_range);
2018-08-07 17:28:30 +02:00
};
let node = find_covering_node(root, range);
2019-01-09 20:35:38 +01:00
// Using shallowest node with same range allows us to traverse siblings.
let node = node
.ancestors()
.take_while(|n| n.range() == node.range())
.last()
.unwrap();
if range == node.range() {
if string_kinds.contains(&node.kind()) {
if let Some(range) = extend_comments(node) {
return Some(range);
}
}
if node.parent().map(|n| list_kinds.contains(&n.kind())) == Some(true) {
if let Some(range) = extend_list_item(node) {
return Some(range);
}
2018-08-26 09:43:03 +02:00
}
}
2018-08-07 17:28:30 +02:00
match node.ancestors().skip_while(|n| n.range() == range).next() {
2018-08-07 17:28:30 +02:00
None => None,
Some(parent) => Some(parent.range()),
}
}
2018-08-26 09:43:03 +02:00
fn extend_single_word_in_comment_or_string(
2019-01-07 14:53:24 +01:00
leaf: &SyntaxNode,
offset: TextUnit,
) -> Option<TextRange> {
let text: &str = leaf.leaf_text()?;
2018-10-04 15:35:55 +02:00
let cursor_position: u32 = (offset - leaf.range().start()).into();
let (before, after) = text.split_at(cursor_position as usize);
2018-12-09 15:50:56 +01:00
fn non_word_char(c: char) -> bool {
!(c.is_alphanumeric() || c == '_')
}
let start_idx = before.rfind(non_word_char)? as u32;
let end_idx = after.find(non_word_char).unwrap_or(after.len()) as u32;
let from: TextUnit = (start_idx + 1).into();
let to: TextUnit = (cursor_position + end_idx).into();
2018-10-04 15:35:55 +02:00
let range = TextRange::from_to(from, to);
if range.is_empty() {
None
} else {
Some(range + leaf.range().start())
}
}
2019-01-07 14:53:24 +01:00
fn extend_ws(root: &SyntaxNode, ws: &SyntaxNode, offset: TextUnit) -> TextRange {
2018-09-04 11:48:39 +02:00
let ws_text = ws.leaf_text().unwrap();
let suffix = TextRange::from_to(offset, ws.range().end()) - ws.range().start();
let prefix = TextRange::from_to(ws.range().start(), offset) - ws.range().start();
let ws_suffix = &ws_text.as_str()[suffix];
let ws_prefix = &ws_text.as_str()[prefix];
if ws_text.contains('\n') && !ws_suffix.contains('\n') {
2018-09-04 11:48:39 +02:00
if let Some(node) = ws.next_sibling() {
let start = match ws_prefix.rfind('\n') {
Some(idx) => ws.range().start() + TextUnit::from((idx + 1) as u32),
None => node.range().start(),
2018-09-04 11:48:39 +02:00
};
let end = if root.text().char_at(node.range().end()) == Some('\n') {
node.range().end() + TextUnit::of_char('\n')
} else {
node.range().end()
};
return TextRange::from_to(start, end);
}
}
ws.range()
}
2019-01-07 14:53:24 +01:00
fn pick_best<'a>(l: &'a SyntaxNode, r: &'a SyntaxNode) -> &'a SyntaxNode {
2018-09-04 11:48:39 +02:00
return if priority(r) > priority(l) { r } else { l };
2019-01-07 14:53:24 +01:00
fn priority(n: &SyntaxNode) -> usize {
2018-09-04 11:48:39 +02:00
match n.kind() {
WHITESPACE => 0,
2018-09-19 12:55:47 +02:00
IDENT | SELF_KW | SUPER_KW | CRATE_KW | LIFETIME => 2,
2018-09-04 11:48:39 +02:00
_ => 1,
}
}
}
2019-01-09 20:35:38 +01:00
/// Extend list item selection to include nearby comma and whitespace.
fn extend_list_item(node: &SyntaxNode) -> Option<TextRange> {
fn is_single_line_ws(node: &SyntaxNode) -> bool {
node.kind() == WHITESPACE && !node.leaf_text().unwrap().contains('\n')
}
fn nearby_comma(node: &SyntaxNode, dir: Direction) -> Option<&SyntaxNode> {
node.siblings(dir)
.skip(1)
.skip_while(|node| is_single_line_ws(node))
.next()
.filter(|node| node.kind() == COMMA)
}
if let Some(comma_node) = nearby_comma(node, Direction::Prev) {
return Some(TextRange::from_to(
comma_node.range().start(),
node.range().end(),
));
}
if let Some(comma_node) = nearby_comma(node, Direction::Next) {
// Include any following whitespace when comma if after list item.
let final_node = comma_node
.siblings(Direction::Next)
.skip(1)
.next()
.filter(|node| is_single_line_ws(node))
.unwrap_or(comma_node);
return Some(TextRange::from_to(
node.range().start(),
final_node.range().end(),
));
}
return None;
}
2019-01-07 14:53:24 +01:00
fn extend_comments(node: &SyntaxNode) -> Option<TextRange> {
2018-10-02 17:14:33 +02:00
let prev = adj_comments(node, Direction::Prev);
let next = adj_comments(node, Direction::Next);
if prev != next {
Some(TextRange::from_to(prev.range().start(), next.range().end()))
2018-08-26 09:43:03 +02:00
} else {
None
}
}
2019-01-07 14:53:24 +01:00
fn adj_comments(node: &SyntaxNode, dir: Direction) -> &SyntaxNode {
2018-08-26 09:43:03 +02:00
let mut res = node;
2018-10-02 17:14:33 +02:00
for node in node.siblings(dir) {
2018-08-26 09:43:03 +02:00
match node.kind() {
COMMENT => res = node,
WHITESPACE if !node.leaf_text().unwrap().as_str().contains("\n\n") => (),
_ => break,
2018-08-26 09:43:03 +02:00
}
}
res
}
2018-08-28 13:47:12 +02:00
#[cfg(test)]
mod tests {
2019-01-07 14:53:24 +01:00
use ra_syntax::{SourceFile, AstNode};
2018-08-28 13:47:12 +02:00
use test_utils::extract_offset;
2019-01-07 14:53:24 +01:00
use super::*;
2018-08-28 13:47:12 +02:00
fn do_check(before: &str, afters: &[&str]) {
let (cursor, before) = extract_offset(before);
2019-01-07 14:53:24 +01:00
let file = SourceFile::parse(&before);
2018-08-28 13:47:12 +02:00
let mut range = TextRange::offset_len(cursor, 0.into());
for &after in afters {
range = extend_selection(file.syntax(), range).unwrap();
2018-08-28 13:47:12 +02:00
let actual = &before[range];
assert_eq!(after, actual);
}
}
#[test]
fn test_extend_selection_arith() {
do_check(r#"fn foo() { <|>1 + 1 }"#, &["1", "1 + 1", "{ 1 + 1 }"]);
2018-08-28 13:47:12 +02:00
}
#[test]
2019-01-09 20:35:38 +01:00
fn test_extend_selection_list() {
do_check(r#"fn foo(<|>x: i32) {}"#, &["x", "x: i32"]);
do_check(
r#"fn foo(<|>x: i32, y: i32) {}"#,
&["x", "x: i32", "x: i32, "],
);
do_check(
r#"fn foo(<|>x: i32,y: i32) {}"#,
&["x", "x: i32", "x: i32,"],
);
do_check(
r#"fn foo(x: i32, <|>y: i32) {}"#,
&["y", "y: i32", ", y: i32"],
);
do_check(
r#"fn foo(x: i32, <|>y: i32, ) {}"#,
&["y", "y: i32", ", y: i32"],
);
do_check(
r#"fn foo(x: i32,<|>y: i32) {}"#,
&["y", "y: i32", ",y: i32"],
);
do_check(
r#"const FOO: [usize; 2] = [ 22<|> , 33];"#,
&["22", "22 , "],
);
do_check(r#"const FOO: [usize; 2] = [ 22 , 33<|>];"#, &["33", ", 33"]);
do_check(
r#"const FOO: [usize; 2] = [ 22 , 33<|> ,];"#,
&["33", ", 33"],
);
do_check(
r#"
const FOO: [usize; 2] = [
22,
<|>33,
]"#,
&["33", "33,"],
);
do_check(
r#"
const FOO: [usize; 2] = [
22
, 33<|>,
]"#,
&["33", ", 33"],
);
}
#[test]
fn test_extend_selection_start_of_the_line() {
2018-08-28 13:47:12 +02:00
do_check(
r#"
impl S {
<|> fn foo() {
}
}"#,
&[" fn foo() {\n\n }\n"],
2018-08-28 13:47:12 +02:00
);
}
2018-10-08 16:33:13 +02:00
#[test]
fn test_extend_selection_doc_comments() {
do_check(
r#"
struct A;
/// bla
/// bla
struct B {
<|>
}
"#,
&[
"\n \n",
"{\n \n}",
"/// bla\n/// bla\nstruct B {\n \n}",
],
2018-10-08 16:33:13 +02:00
)
}
2018-08-28 13:47:12 +02:00
#[test]
fn test_extend_selection_comments() {
do_check(
r#"
fn bar(){}
// fn foo() {
// 1 + <|>1
// }
// fn foo(){}
"#,
&["1", "// 1 + 1", "// fn foo() {\n// 1 + 1\n// }"],
2018-08-28 13:47:12 +02:00
);
do_check(
r#"
// #[derive(Debug, Clone, Copy, PartialEq, Eq)]
// pub enum Direction {
// <|> Next,
// Prev
// }
"#,
&[
"// Next,",
"// #[derive(Debug, Clone, Copy, PartialEq, Eq)]\n// pub enum Direction {\n// Next,\n// Prev\n// }",
],
);
2018-12-09 15:50:56 +01:00
do_check(
r#"
/*
foo
_bar1<|>*/
"#,
&["_bar1", "/*\nfoo\n_bar1*/"],
);
do_check(
r#"
//!<|>foo_2 bar
"#,
&["foo_2", "//!foo_2 bar"],
);
do_check(
r#"
/<|>/foo bar
"#,
&["//foo bar"],
);
2018-08-28 13:47:12 +02:00
}
2018-09-04 11:48:39 +02:00
#[test]
fn test_extend_selection_prefer_idents() {
do_check(
r#"
fn main() { foo<|>+bar;}
"#,
&["foo", "foo+bar"],
2018-09-04 11:48:39 +02:00
);
do_check(
r#"
fn main() { foo+<|>bar;}
"#,
&["bar", "foo+bar"],
2018-09-04 11:48:39 +02:00
);
}
2018-09-19 12:55:47 +02:00
#[test]
fn test_extend_selection_prefer_lifetimes() {
do_check(r#"fn foo<<|>'a>() {}"#, &["'a", "<'a>"]);
do_check(r#"fn foo<'a<|>>() {}"#, &["'a", "<'a>"]);
2018-09-19 12:55:47 +02:00
}
#[test]
fn test_extend_selection_select_first_word() {
do_check(r#"// foo bar b<|>az quxx"#, &["baz", "// foo bar baz quxx"]);
do_check(
r#"
impl S {
fn foo() {
// hel<|>lo world
}
}
"#,
&["hello", "// hello world"],
);
}
#[test]
fn test_extend_selection_string() {
do_check(
r#"
fn bar(){}
" fn f<|>oo() {"
"#,
&["foo", "\" fn foo() {\""],
);
}
2018-08-28 13:47:12 +02:00
}