aboutsummaryrefslogtreecommitdiff
path: root/crates/ra_assists/src/split_import.rs
diff options
context:
space:
mode:
Diffstat (limited to 'crates/ra_assists/src/split_import.rs')
-rw-r--r--crates/ra_assists/src/split_import.rs57
1 files changed, 57 insertions, 0 deletions
diff --git a/crates/ra_assists/src/split_import.rs b/crates/ra_assists/src/split_import.rs
new file mode 100644
index 000000000..7e34be087
--- /dev/null
+++ b/crates/ra_assists/src/split_import.rs
@@ -0,0 +1,57 @@
1use hir::db::HirDatabase;
2use ra_syntax::{
3 TextUnit, AstNode, SyntaxKind::COLONCOLON,
4 ast,
5 algo::generate,
6};
7
8use crate::{AssistCtx, Assist};
9
10pub(crate) fn split_import(ctx: AssistCtx<impl HirDatabase>) -> Option<Assist> {
11 let colon_colon = ctx
12 .leaf_at_offset()
13 .find(|leaf| leaf.kind() == COLONCOLON)?;
14 let path = colon_colon.parent().and_then(ast::Path::cast)?;
15 let top_path = generate(Some(path), |it| it.parent_path()).last()?;
16
17 let use_tree = top_path.syntax().ancestors().find_map(ast::UseTree::cast);
18 if use_tree.is_none() {
19 return None;
20 }
21
22 let l_curly = colon_colon.range().end();
23 let r_curly = match top_path.syntax().parent().and_then(ast::UseTree::cast) {
24 Some(tree) => tree.syntax().range().end(),
25 None => top_path.syntax().range().end(),
26 };
27
28 ctx.build("split import", |edit| {
29 edit.insert(l_curly, "{");
30 edit.insert(r_curly, "}");
31 edit.set_cursor(l_curly + TextUnit::of_str("{"));
32 })
33}
34
35#[cfg(test)]
36mod tests {
37 use super::*;
38 use crate::helpers::check_assist;
39
40 #[test]
41 fn test_split_import() {
42 check_assist(
43 split_import,
44 "use crate::<|>db::RootDatabase;",
45 "use crate::{<|>db::RootDatabase};",
46 )
47 }
48
49 #[test]
50 fn split_import_works_with_trees() {
51 check_assist(
52 split_import,
53 "use algo:<|>:visitor::{Visitor, visit}",
54 "use algo::{<|>visitor::{Visitor, visit}}",
55 )
56 }
57}