1 //! This module handles auto-magic editing actions applied together with users
2 //! edits. For example, if the user typed
8 //! | // <- cursor is here
11 //! and types `.` next, we want to indent the dot.
13 //! Language server executes such typing assists synchronously. That is, they
14 //! block user's typing and should be pretty fast for this reason!
19 base_db::{FilePosition, SourceDatabase},
23 algo::{ancestors_at_offset, find_node_at_offset},
24 ast::{self, edit::IndentLevel, AstToken},
25 AstNode, Parse, SourceFile, SyntaxKind, TextRange, TextSize, T,
28 use text_edit::{Indel, TextEdit};
30 use crate::SourceChange;
32 pub(crate) use on_enter::on_enter;
34 // Don't forget to add new trigger characters to `server_capabilities` in `caps.rs`.
35 pub(crate) const TRIGGER_CHARS: &str = ".=<>{";
37 struct ExtendedTextEdit {
42 // Feature: On Typing Assists
44 // Some features trigger on typing certain characters:
46 // - typing `let =` tries to smartly add `;` if `=` is followed by an existing expression
47 // - typing `=` between two expressions adds `;` when in statement position
48 // - typing `=` to turn an assignment into an equality comparison removes `;` when in expression position
49 // - typing `.` in a chain method call auto-indents
50 // - typing `{` in front of an expression inserts a closing `}` after the expression
51 // - typing `{` in a use item adds a closing `}` in the right place
55 // Add the following to `settings.json`:
58 // "editor.formatOnType": true,
61 // image::https://user-images.githubusercontent.com/48062697/113166163-69758500-923a-11eb-81ee-eb33ec380399.gif[]
62 // image::https://user-images.githubusercontent.com/48062697/113171066-105c2000-923f-11eb-87ab-f4a263346567.gif[]
63 pub(crate) fn on_char_typed(
65 position: FilePosition,
67 ) -> Option<SourceChange> {
68 if !stdx::always!(TRIGGER_CHARS.contains(char_typed)) {
71 let file = &db.parse(position.file_id);
72 if !stdx::always!(file.tree().syntax().text().char_at(position.offset) == Some(char_typed)) {
75 let edit = on_char_typed_inner(file, position.offset, char_typed)?;
76 let mut sc = SourceChange::from_text_edit(position.file_id, edit.edit);
77 sc.is_snippet = edit.is_snippet;
81 fn on_char_typed_inner(
82 file: &Parse<SourceFile>,
85 ) -> Option<ExtendedTextEdit> {
86 if !stdx::always!(TRIGGER_CHARS.contains(char_typed)) {
89 return match char_typed {
90 '.' => conv(on_dot_typed(&file.tree(), offset)),
91 '=' => conv(on_eq_typed(&file.tree(), offset)),
92 '<' => on_left_angle_typed(&file.tree(), offset),
93 '>' => conv(on_right_angle_typed(&file.tree(), offset)),
94 '{' => conv(on_opening_brace_typed(file, offset)),
98 fn conv(text_edit: Option<TextEdit>) -> Option<ExtendedTextEdit> {
99 Some(ExtendedTextEdit { edit: text_edit?, is_snippet: false })
103 /// Inserts a closing `}` when the user types an opening `{`, wrapping an existing expression in a
104 /// block, or a part of a `use` item.
105 fn on_opening_brace_typed(file: &Parse<SourceFile>, offset: TextSize) -> Option<TextEdit> {
106 if !stdx::always!(file.tree().syntax().text().char_at(offset) == Some('{')) {
110 let brace_token = file.tree().syntax().token_at_offset(offset).right_biased()?;
111 if brace_token.kind() != SyntaxKind::L_CURLY {
115 // Remove the `{` to get a better parse tree, and reparse.
116 let range = brace_token.text_range();
117 if !stdx::always!(range.len() == TextSize::of('{')) {
120 let file = file.reparse(&Indel::delete(range));
122 if let Some(edit) = brace_expr(&file.tree(), offset) {
126 if let Some(edit) = brace_use_path(&file.tree(), offset) {
132 fn brace_use_path(file: &SourceFile, offset: TextSize) -> Option<TextEdit> {
133 let segment: ast::PathSegment = find_node_at_offset(file.syntax(), offset)?;
134 if segment.syntax().text_range().start() != offset {
138 let tree: ast::UseTree = find_node_at_offset(file.syntax(), offset)?;
140 Some(TextEdit::insert(
141 tree.syntax().text_range().end() + TextSize::of("{"),
146 fn brace_expr(file: &SourceFile, offset: TextSize) -> Option<TextEdit> {
147 let mut expr: ast::Expr = find_node_at_offset(file.syntax(), offset)?;
148 if expr.syntax().text_range().start() != offset {
152 // Enclose the outermost expression starting at `offset`
153 while let Some(parent) = expr.syntax().parent() {
154 if parent.text_range().start() != expr.syntax().text_range().start() {
158 match ast::Expr::cast(parent) {
159 Some(parent) => expr = parent,
164 // If it's a statement in a block, we don't know how many statements should be included
165 if ast::ExprStmt::can_cast(expr.syntax().parent()?.kind()) {
169 // Insert `}` right after the expression.
170 Some(TextEdit::insert(
171 expr.syntax().text_range().end() + TextSize::of("{"),
177 /// Returns an edit which should be applied after `=` was typed. Primarily,
178 /// this works when adding `let =`.
179 // FIXME: use a snippet completion instead of this hack here.
180 fn on_eq_typed(file: &SourceFile, offset: TextSize) -> Option<TextEdit> {
181 if !stdx::always!(file.syntax().text().char_at(offset) == Some('=')) {
185 if let Some(edit) = let_stmt(file, offset) {
188 if let Some(edit) = assign_expr(file, offset) {
191 if let Some(edit) = assign_to_eq(file, offset) {
197 fn assign_expr(file: &SourceFile, offset: TextSize) -> Option<TextEdit> {
198 let binop: ast::BinExpr = find_node_at_offset(file.syntax(), offset)?;
199 if !matches!(binop.op_kind(), Some(ast::BinaryOp::Assignment { op: None })) {
203 // Parent must be `ExprStmt` or `StmtList` for `;` to be valid.
204 if let Some(expr_stmt) = ast::ExprStmt::cast(binop.syntax().parent()?) {
205 if expr_stmt.semicolon_token().is_some() {
209 if !ast::StmtList::can_cast(binop.syntax().parent()?.kind()) {
214 let expr = binop.rhs()?;
215 let expr_range = expr.syntax().text_range();
216 if expr_range.contains(offset) && offset != expr_range.start() {
219 if file.syntax().text().slice(offset..expr_range.start()).contains_char('\n') {
222 let offset = expr.syntax().text_range().end();
223 Some(TextEdit::insert(offset, ";".to_string()))
226 /// `a =$0 b;` removes the semicolon if an expression is valid in this context.
227 fn assign_to_eq(file: &SourceFile, offset: TextSize) -> Option<TextEdit> {
228 let binop: ast::BinExpr = find_node_at_offset(file.syntax(), offset)?;
229 if !matches!(binop.op_kind(), Some(ast::BinaryOp::CmpOp(ast::CmpOp::Eq { negated: false })))
234 let expr_stmt = ast::ExprStmt::cast(binop.syntax().parent()?)?;
235 let semi = expr_stmt.semicolon_token()?;
237 if expr_stmt.syntax().next_sibling().is_some() {
238 // Not the last statement in the list.
242 Some(TextEdit::delete(semi.text_range()))
245 fn let_stmt(file: &SourceFile, offset: TextSize) -> Option<TextEdit> {
246 let let_stmt: ast::LetStmt = find_node_at_offset(file.syntax(), offset)?;
247 if let_stmt.semicolon_token().is_some() {
250 let expr = let_stmt.initializer()?;
251 let expr_range = expr.syntax().text_range();
252 if expr_range.contains(offset) && offset != expr_range.start() {
255 if file.syntax().text().slice(offset..expr_range.start()).contains_char('\n') {
258 let offset = let_stmt.syntax().text_range().end();
259 Some(TextEdit::insert(offset, ";".to_string()))
263 /// Returns an edit which should be applied when a dot ('.') is typed on a blank line, indenting the line appropriately.
264 fn on_dot_typed(file: &SourceFile, offset: TextSize) -> Option<TextEdit> {
265 if !stdx::always!(file.syntax().text().char_at(offset) == Some('.')) {
269 file.syntax().token_at_offset(offset).left_biased().and_then(ast::Whitespace::cast)?;
271 // if prior is fn call over multiple lines dont indent
272 // or if previous is method call over multiples lines keep that indent
273 let current_indent = {
274 let text = whitespace.text();
275 let (_prefix, suffix) = text.rsplit_once('\n')?;
278 let current_indent_len = TextSize::of(current_indent);
280 let parent = whitespace.syntax().parent()?;
281 // Make sure dot is a part of call chain
282 let receiver = if let Some(field_expr) = ast::FieldExpr::cast(parent.clone()) {
284 } else if let Some(method_call_expr) = ast::MethodCallExpr::cast(parent.clone()) {
285 method_call_expr.receiver()?
290 let receiver_is_multiline = receiver.syntax().text().find_char('\n').is_some();
291 let target_indent = match (receiver, receiver_is_multiline) {
292 // if receiver is multiline field or method call, just take the previous `.` indentation
293 (ast::Expr::MethodCallExpr(expr), true) => {
294 expr.dot_token().as_ref().map(IndentLevel::from_token)
296 (ast::Expr::FieldExpr(expr), true) => {
297 expr.dot_token().as_ref().map(IndentLevel::from_token)
299 // if receiver is multiline expression, just keeps its indentation
300 (_, true) => Some(IndentLevel::from_node(&parent)),
303 let target_indent = match target_indent {
305 // in all other cases, take previous indentation and indent once
306 None => IndentLevel::from_node(&parent) + 1,
310 if current_indent_len == TextSize::of(&target_indent) {
314 Some(TextEdit::replace(TextRange::new(offset - current_indent_len, offset), target_indent))
317 /// Add closing `>` for generic arguments/parameters.
318 fn on_left_angle_typed(file: &SourceFile, offset: TextSize) -> Option<ExtendedTextEdit> {
319 let file_text = file.syntax().text();
320 if !stdx::always!(file_text.char_at(offset) == Some('<')) {
324 // Find the next non-whitespace char in the line.
325 let mut next_offset = offset + TextSize::of('<');
326 while file_text.char_at(next_offset) == Some(' ') {
327 next_offset += TextSize::of(' ')
329 if file_text.char_at(next_offset) == Some('>') {
333 let range = TextRange::at(offset, TextSize::of('<'));
334 if let Some(t) = file.syntax().token_at_offset(offset).left_biased() {
335 if T![impl] == t.kind() {
336 return Some(ExtendedTextEdit {
337 edit: TextEdit::replace(range, "<$0>".to_string()),
343 if ancestors_at_offset(file.syntax(), offset)
345 ast::GenericParamList::can_cast(n.kind()) || ast::GenericArgList::can_cast(n.kind())
349 return Some(ExtendedTextEdit {
350 edit: TextEdit::replace(range, "<$0>".to_string()),
358 /// Adds a space after an arrow when `fn foo() { ... }` is turned into `fn foo() -> { ... }`
359 fn on_right_angle_typed(file: &SourceFile, offset: TextSize) -> Option<TextEdit> {
360 let file_text = file.syntax().text();
361 if !stdx::always!(file_text.char_at(offset) == Some('>')) {
364 let after_arrow = offset + TextSize::of('>');
365 if file_text.char_at(after_arrow) != Some('{') {
368 if find_node_at_offset::<ast::RetType>(file.syntax(), offset).is_none() {
372 Some(TextEdit::insert(after_arrow, " ".to_string()))
377 use test_utils::{assert_eq_text, extract_offset};
381 impl ExtendedTextEdit {
382 fn apply(&self, text: &mut String) {
383 self.edit.apply(text);
387 fn do_type_char(char_typed: char, before: &str) -> Option<String> {
388 let (offset, mut before) = extract_offset(before);
389 let edit = TextEdit::insert(offset, char_typed.to_string());
390 edit.apply(&mut before);
391 let parse = SourceFile::parse(&before);
392 on_char_typed_inner(&parse, offset, char_typed).map(|it| {
393 it.apply(&mut before);
398 fn type_char(char_typed: char, ra_fixture_before: &str, ra_fixture_after: &str) {
399 let actual = do_type_char(char_typed, ra_fixture_before)
400 .unwrap_or_else(|| panic!("typing `{}` did nothing", char_typed));
402 assert_eq_text!(ra_fixture_after, &actual);
405 fn type_char_noop(char_typed: char, ra_fixture_before: &str) {
406 let file_change = do_type_char(char_typed, ra_fixture_before);
407 assert!(file_change.is_none())
411 fn test_semi_after_let() {
448 fn test_semi_after_assign() {
559 fn indents_new_chain_call() {
587 fn indents_new_chain_call_with_semi() {
615 fn indents_new_chain_call_with_let() {
636 fn indents_continued_chain_call() {
667 fn indents_middle_of_chain_call() {
672 let var = enum_defvariant_list().unwrap()
680 let var = enum_defvariant_list().unwrap()
691 let var = enum_defvariant_list().unwrap()
701 fn dont_indent_freestanding_dot() {
721 fn adds_space_after_return_type() {
734 fn adds_closing_brace_for_expr() {
738 fn f() { match () { _ => $0() } }
741 fn f() { match () { _ => {()} } }
756 fn f() { let x = $0(); }
759 fn f() { let x = {()}; }
765 fn f() { let x = $0a.b(); }
768 fn f() { let x = {a.b()}; }
785 const S: () = $0a.b();
789 const S: () = {a.b()};
815 fn noop_in_string_literal() {
816 // Regression test for #9351
820 fn check_with(ra_fixture: &str, expect: Expect) {
822 enum E { T(), R$0, C }
830 let actual = completion_list(&format!("{}\n{}", base, ra_fixture));
831 expect.assert_eq(&actual)
838 fn noop_in_item_position_with_macro() {
839 type_char_noop('{', r#"$0println!();"#);
843 fn main() $0println!("hello");
849 fn adds_closing_brace_for_use_tree() {
862 use some::{Path, $0Other};
865 use some::{Path, {Other}};
871 use some::{$0Path, Other};
874 use some::{{Path}, Other};
880 use some::path::$0to::Item;
883 use some::path::{to::Item};
889 use some::$0path::to::Item;
892 use some::{path::to::Item};
898 use $0some::path::to::Item;
901 use {some::path::to::Item};
907 use some::path::$0to::{Item};
910 use some::path::{to::{Item}};
926 use some::pa$0th::to::Item;
932 fn adds_closing_angle_bracket_for_generic_args() {
950 fn foo(bar: &[u64]) {
951 bar.iter().collect::$0();
955 fn foo(bar: &[u64]) {
956 bar.iter().collect::<$0>();
963 fn adds_closing_angle_bracket_for_generic_params() {
1066 fn dont_add_closing_angle_bracket_for_comparison() {
1095 fn dont_add_closing_angle_bracket_if_it_is_already_there() {
1107 fn foo(bar: &[u64]) {
1108 bar.iter().collect::$0 >();
1181 fn regression_629() {
1186 CompletionItem::new(
1187 CompletionKind::Reference,
1189 field.name().to_string(),
1200 CompletionItem::new(
1201 CompletionKind::Reference,
1203 field.name().to_string(),