aboutsummaryrefslogtreecommitdiff
path: root/crates/ra_assists/src/handlers/split_import.rs
diff options
context:
space:
mode:
Diffstat (limited to 'crates/ra_assists/src/handlers/split_import.rs')
-rw-r--r--crates/ra_assists/src/handlers/split_import.rs69
1 files changed, 69 insertions, 0 deletions
diff --git a/crates/ra_assists/src/handlers/split_import.rs b/crates/ra_assists/src/handlers/split_import.rs
new file mode 100644
index 000000000..2c3f07a79
--- /dev/null
+++ b/crates/ra_assists/src/handlers/split_import.rs
@@ -0,0 +1,69 @@
1use std::iter::successors;
2
3use ra_syntax::{ast, AstNode, TextUnit, T};
4
5use crate::{Assist, AssistCtx, AssistId};
6
7// Assist: split_import
8//
9// Wraps the tail of import into braces.
10//
11// ```
12// use std::<|>collections::HashMap;
13// ```
14// ->
15// ```
16// use std::{collections::HashMap};
17// ```
18pub(crate) fn split_import(ctx: AssistCtx) -> Option<Assist> {
19 let colon_colon = ctx.find_token_at_offset(T![::])?;
20 let path = ast::Path::cast(colon_colon.parent())?;
21 let top_path = successors(Some(path), |it| it.parent_path()).last()?;
22
23 let use_tree = top_path.syntax().ancestors().find_map(ast::UseTree::cast);
24 if use_tree.is_none() {
25 return None;
26 }
27
28 let l_curly = colon_colon.text_range().end();
29 let r_curly = match top_path.syntax().parent().and_then(ast::UseTree::cast) {
30 Some(tree) => tree.syntax().text_range().end(),
31 None => top_path.syntax().text_range().end(),
32 };
33
34 ctx.add_assist(AssistId("split_import"), "Split import", |edit| {
35 edit.target(colon_colon.text_range());
36 edit.insert(l_curly, "{");
37 edit.insert(r_curly, "}");
38 edit.set_cursor(l_curly + TextUnit::of_str("{"));
39 })
40}
41
42#[cfg(test)]
43mod tests {
44 use super::*;
45 use crate::helpers::{check_assist, check_assist_target};
46
47 #[test]
48 fn test_split_import() {
49 check_assist(
50 split_import,
51 "use crate::<|>db::RootDatabase;",
52 "use crate::{<|>db::RootDatabase};",
53 )
54 }
55
56 #[test]
57 fn split_import_works_with_trees() {
58 check_assist(
59 split_import,
60 "use crate:<|>:db::{RootDatabase, FileSymbol}",
61 "use crate::{<|>db::{RootDatabase, FileSymbol}}",
62 )
63 }
64
65 #[test]
66 fn split_import_target() {
67 check_assist_target(split_import, "use crate::<|>db::{RootDatabase, FileSymbol}", "::");
68 }
69}