aboutsummaryrefslogtreecommitdiff
path: root/crates/ra_assists/src/utils/insert_use.rs
diff options
context:
space:
mode:
Diffstat (limited to 'crates/ra_assists/src/utils/insert_use.rs')
-rw-r--r--crates/ra_assists/src/utils/insert_use.rs27
1 files changed, 24 insertions, 3 deletions
diff --git a/crates/ra_assists/src/utils/insert_use.rs b/crates/ra_assists/src/utils/insert_use.rs
index f89c288da..50a62ee82 100644
--- a/crates/ra_assists/src/utils/insert_use.rs
+++ b/crates/ra_assists/src/utils/insert_use.rs
@@ -2,13 +2,15 @@
2// FIXME: rewrite according to the plan, outlined in 2// FIXME: rewrite according to the plan, outlined in
3// https://github.com/rust-analyzer/rust-analyzer/issues/3301#issuecomment-592931553 3// https://github.com/rust-analyzer/rust-analyzer/issues/3301#issuecomment-592931553
4 4
5use std::iter::successors;
6
5use either::Either; 7use either::Either;
6use hir::{self, ModPath}; 8use hir::{self, ModPath};
7use syntax::{ 9use syntax::{
8 ast::{self, NameOwner, VisibilityOwner}, 10 ast::{self, NameOwner, VisibilityOwner},
9 AstNode, Direction, SmolStr, 11 AstNode, AstToken, Direction, SmolStr,
10 SyntaxKind::{PATH, PATH_SEGMENT}, 12 SyntaxKind::{PATH, PATH_SEGMENT},
11 SyntaxNode, T, 13 SyntaxNode, SyntaxToken, T,
12}; 14};
13use text_edit::TextEditBuilder; 15use text_edit::TextEditBuilder;
14 16
@@ -442,7 +444,7 @@ fn make_assist_add_new_use(
442 edit: &mut TextEditBuilder, 444 edit: &mut TextEditBuilder,
443) { 445) {
444 if let Some(anchor) = anchor { 446 if let Some(anchor) = anchor {
445 let indent = ra_fmt::leading_indent(anchor); 447 let indent = leading_indent(anchor);
446 let mut buf = String::new(); 448 let mut buf = String::new();
447 if after { 449 if after {
448 buf.push_str("\n"); 450 buf.push_str("\n");
@@ -524,3 +526,22 @@ fn make_assist_add_nested_import(
524 edit.insert(end, "}".to_string()); 526 edit.insert(end, "}".to_string());
525 } 527 }
526} 528}
529
530/// If the node is on the beginning of the line, calculate indent.
531fn leading_indent(node: &SyntaxNode) -> Option<SmolStr> {
532 for token in prev_tokens(node.first_token()?) {
533 if let Some(ws) = ast::Whitespace::cast(token.clone()) {
534 let ws_text = ws.text();
535 if let Some(pos) = ws_text.rfind('\n') {
536 return Some(ws_text[pos + 1..].into());
537 }
538 }
539 if token.text().contains('\n') {
540 break;
541 }
542 }
543 return None;
544 fn prev_tokens(token: SyntaxToken) -> impl Iterator<Item = SyntaxToken> {
545 successors(token.prev_token(), |token| token.prev_token())
546 }
547}