Skip to content

Commit 6518fb2

Browse files
committed
auto_import: import in enclosing module instead of file
1 parent 468e1d4 commit 6518fb2

File tree

1 file changed

+38
-4
lines changed

1 file changed

+38
-4
lines changed

crates/ra_assists/src/auto_import.rs

+38-4
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
use hir::db::HirDatabase;
22
use ra_syntax::{
3-
ast, AstNode, SyntaxNode, Direction, TextRange,
3+
ast::{ self, NameOwner }, AstNode, SyntaxNode, Direction, TextRange,
44
SyntaxKind::{ PATH, PATH_SEGMENT, COLONCOLON, COMMA }
55
};
66
use crate::assist_ctx::{AssistCtx, Assist, AssistBuilder};
@@ -513,9 +513,20 @@ pub(crate) fn auto_import(mut ctx: AssistCtx<impl HirDatabase>) -> Option<Assist
513513
return None;
514514
}
515515

516-
ctx.add_action(format!("import {} in the current file", fmt_segments(&segments)), |edit| {
517-
apply_auto_import(current_file.syntax(), path, &segments, edit);
518-
});
516+
if let Some(module) = path.syntax().ancestors().find_map(ast::Module::cast) {
517+
if let (Some(item_list), Some(name)) = (module.item_list(), module.name()) {
518+
ctx.add_action(
519+
format!("import {} in mod {}", fmt_segments(&segments), name.text()),
520+
|edit| {
521+
apply_auto_import(item_list.syntax(), path, &segments, edit);
522+
},
523+
);
524+
}
525+
} else {
526+
ctx.add_action(format!("import {} in the current file", fmt_segments(&segments)), |edit| {
527+
apply_auto_import(current_file.syntax(), path, &segments, edit);
528+
});
529+
}
519530

520531
ctx.build()
521532
}
@@ -762,4 +773,27 @@ use std::fmt<|>;
762773
",
763774
);
764775
}
776+
777+
#[test]
778+
fn test_auto_import_file_add_use_no_anchor_in_mod_mod() {
779+
check_assist(
780+
auto_import,
781+
"
782+
mod foo {
783+
mod bar {
784+
std::fmt::Debug<|>
785+
}
786+
}
787+
",
788+
"
789+
mod foo {
790+
mod bar {
791+
use std::fmt::Debug;
792+
793+
Debug<|>
794+
}
795+
}
796+
",
797+
);
798+
}
765799
}

0 commit comments

Comments
 (0)