|
1 | 1 | use hir::db::HirDatabase;
|
2 | 2 | use ra_syntax::{
|
3 |
| - ast, AstNode, SyntaxNode, Direction, TextRange, |
| 3 | + ast::{ self, NameOwner }, AstNode, SyntaxNode, Direction, TextRange, |
4 | 4 | SyntaxKind::{ PATH, PATH_SEGMENT, COLONCOLON, COMMA }
|
5 | 5 | };
|
6 | 6 | use crate::assist_ctx::{AssistCtx, Assist, AssistBuilder};
|
@@ -513,9 +513,20 @@ pub(crate) fn auto_import(mut ctx: AssistCtx<impl HirDatabase>) -> Option<Assist
|
513 | 513 | return None;
|
514 | 514 | }
|
515 | 515 |
|
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 | + } |
519 | 530 |
|
520 | 531 | ctx.build()
|
521 | 532 | }
|
@@ -762,4 +773,27 @@ use std::fmt<|>;
|
762 | 773 | ",
|
763 | 774 | );
|
764 | 775 | }
|
| 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 | + } |
765 | 799 | }
|
0 commit comments