From 4c121bfa2f2a7a06f01143e3203c650156e2fb4e Mon Sep 17 00:00:00 2001 From: Aleksey Kladov Date: Sun, 26 Aug 2018 10:43:03 +0300 Subject: extend selection to comments --- crates/libeditor/src/extend_selection.rs | 34 ++++++++++++++++++++++++++++++-- crates/libeditor/tests/test.rs | 12 +++++++++++ 2 files changed, 44 insertions(+), 2 deletions(-) (limited to 'crates') diff --git a/crates/libeditor/src/extend_selection.rs b/crates/libeditor/src/extend_selection.rs index d1724b528..154f89671 100644 --- a/crates/libeditor/src/extend_selection.rs +++ b/crates/libeditor/src/extend_selection.rs @@ -1,7 +1,7 @@ use libsyntax2::{ File, TextRange, SyntaxNodeRef, - SyntaxKind::WHITESPACE, - algo::{find_leaf_at_offset, find_covering_node, ancestors}, + SyntaxKind::*, + algo::{find_leaf_at_offset, find_covering_node, ancestors, Direction, siblings}, }; pub fn extend_selection(file: &File, range: TextRange) -> Option { @@ -28,9 +28,39 @@ pub(crate) fn extend(root: SyntaxNodeRef, range: TextRange) -> Option return Some(ws.range()); }; let node = find_covering_node(root, range); + if node.kind() == COMMENT && range == node.range() { + if let Some(range) = extend_comments(node) { + return Some(range); + } + } match ancestors(node).skip_while(|n| n.range() == range).next() { None => None, Some(parent) => Some(parent.range()), } } + +fn extend_comments(node: SyntaxNodeRef) -> Option { + let left = adj_comments(node, Direction::Backward); + let right = adj_comments(node, Direction::Forward); + if left != right { + Some(TextRange::from_to( + left.range().start(), + right.range().end(), + )) + } else { + None + } +} + +fn adj_comments(node: SyntaxNodeRef, dir: Direction) -> SyntaxNodeRef { + let mut res = node; + for node in siblings(node, dir) { + match node.kind() { + COMMENT => res = node, + WHITESPACE if !node.leaf_text().unwrap().as_str().contains("\n\n") => (), + _ => break + } + } + res +} diff --git a/crates/libeditor/tests/test.rs b/crates/libeditor/tests/test.rs index 9d59f4cdf..20de2f240 100644 --- a/crates/libeditor/tests/test.rs +++ b/crates/libeditor/tests/test.rs @@ -40,6 +40,18 @@ impl S { }"#, &["fn foo() {\n\n }"] ); + do_check( + r#" +fn bar(){} + +// fn foo() { +// 1 + <|>1 +// } + +// fn foo(){} +"#, + &["// 1 + 1", "// fn foo() {\n// 1 + 1\n// }"] + ); } #[test] -- cgit v1.2.3