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::find_node_at_offset,
24 ast::{self, edit::IndentLevel, AstToken},
25 AstNode, Parse, SourceFile, SyntaxKind, TextRange, TextSize,
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 // Feature: On Typing Assists
39 // Some features trigger on typing certain characters:
41 // - typing `let =` tries to smartly add `;` if `=` is followed by an existing expression
42 // - typing `.` in a chain method call auto-indents
43 // - typing `{` in front of an expression inserts a closing `}` after the expression
47 // Add the following to `settings.json`:
50 // "editor.formatOnType": true,
53 // image::https://user-images.githubusercontent.com/48062697/113166163-69758500-923a-11eb-81ee-eb33ec380399.gif[]
54 // image::https://user-images.githubusercontent.com/48062697/113171066-105c2000-923f-11eb-87ab-f4a263346567.gif[]
55 pub(crate) fn on_char_typed(
57 position: FilePosition,
59 ) -> Option<SourceChange> {
60 if !stdx::always!(TRIGGER_CHARS.contains(char_typed)) {
63 let file = &db.parse(position.file_id);
64 if !stdx::always!(file.tree().syntax().text().char_at(position.offset) == Some(char_typed)) {
67 let edit = on_char_typed_inner(file, position.offset, char_typed)?;
68 Some(SourceChange::from_text_edit(position.file_id, edit))
71 fn on_char_typed_inner(
72 file: &Parse<SourceFile>,
75 ) -> Option<TextEdit> {
76 if !stdx::always!(TRIGGER_CHARS.contains(char_typed)) {
80 '.' => on_dot_typed(&file.tree(), offset),
81 '=' => on_eq_typed(&file.tree(), offset),
82 '>' => on_arrow_typed(&file.tree(), offset),
83 '{' => on_opening_brace_typed(file, offset),
88 /// Inserts a closing `}` when the user types an opening `{`, wrapping an existing expression in a
89 /// block, or a part of a `use` item.
90 fn on_opening_brace_typed(file: &Parse<SourceFile>, offset: TextSize) -> Option<TextEdit> {
91 if !stdx::always!(file.tree().syntax().text().char_at(offset) == Some('{')) {
95 let brace_token = file.tree().syntax().token_at_offset(offset).right_biased()?;
96 if brace_token.kind() != SyntaxKind::L_CURLY {
100 // Remove the `{` to get a better parse tree, and reparse.
101 let range = brace_token.text_range();
102 if !stdx::always!(range.len() == TextSize::of('{')) {
105 let file = file.reparse(&Indel::delete(range));
107 if let Some(edit) = brace_expr(&file.tree(), offset) {
111 if let Some(edit) = brace_use_path(&file.tree(), offset) {
117 fn brace_use_path(file: &SourceFile, offset: TextSize) -> Option<TextEdit> {
118 let segment: ast::PathSegment = find_node_at_offset(file.syntax(), offset)?;
119 if segment.syntax().text_range().start() != offset {
123 let tree: ast::UseTree = find_node_at_offset(file.syntax(), offset)?;
125 Some(TextEdit::insert(
126 tree.syntax().text_range().end() + TextSize::of("{"),
131 fn brace_expr(file: &SourceFile, offset: TextSize) -> Option<TextEdit> {
132 let mut expr: ast::Expr = find_node_at_offset(file.syntax(), offset)?;
133 if expr.syntax().text_range().start() != offset {
137 // Enclose the outermost expression starting at `offset`
138 while let Some(parent) = expr.syntax().parent() {
139 if parent.text_range().start() != expr.syntax().text_range().start() {
143 match ast::Expr::cast(parent) {
144 Some(parent) => expr = parent,
149 // If it's a statement in a block, we don't know how many statements should be included
150 if ast::ExprStmt::can_cast(expr.syntax().parent()?.kind()) {
154 // Insert `}` right after the expression.
155 Some(TextEdit::insert(
156 expr.syntax().text_range().end() + TextSize::of("{"),
162 /// Returns an edit which should be applied after `=` was typed. Primarily,
163 /// this works when adding `let =`.
164 // FIXME: use a snippet completion instead of this hack here.
165 fn on_eq_typed(file: &SourceFile, offset: TextSize) -> Option<TextEdit> {
166 if !stdx::always!(file.syntax().text().char_at(offset) == Some('=')) {
169 let let_stmt: ast::LetStmt = find_node_at_offset(file.syntax(), offset)?;
170 if let_stmt.semicolon_token().is_some() {
173 if let Some(expr) = let_stmt.initializer() {
174 let expr_range = expr.syntax().text_range();
175 if expr_range.contains(offset) && offset != expr_range.start() {
178 if file.syntax().text().slice(offset..expr_range.start()).contains_char('\n') {
184 let offset = let_stmt.syntax().text_range().end();
185 Some(TextEdit::insert(offset, ";".to_string()))
188 /// Returns an edit which should be applied when a dot ('.') is typed on a blank line, indenting the line appropriately.
189 fn on_dot_typed(file: &SourceFile, offset: TextSize) -> Option<TextEdit> {
190 if !stdx::always!(file.syntax().text().char_at(offset) == Some('.')) {
194 file.syntax().token_at_offset(offset).left_biased().and_then(ast::Whitespace::cast)?;
196 // if prior is fn call over multiple lines dont indent
197 // or if previous is method call over multiples lines keep that indent
198 let current_indent = {
199 let text = whitespace.text();
200 let (_prefix, suffix) = text.rsplit_once('\n')?;
203 let current_indent_len = TextSize::of(current_indent);
205 let parent = whitespace.syntax().parent()?;
206 // Make sure dot is a part of call chain
207 let receiver = if let Some(field_expr) = ast::FieldExpr::cast(parent.clone()) {
209 } else if let Some(method_call_expr) = ast::MethodCallExpr::cast(parent.clone()) {
210 method_call_expr.receiver()?
215 let receiver_is_multiline = receiver.syntax().text().find_char('\n').is_some();
216 let target_indent = match (receiver, receiver_is_multiline) {
217 // if receiver is multiline field or method call, just take the previous `.` indentation
218 (ast::Expr::MethodCallExpr(expr), true) => {
219 expr.dot_token().as_ref().map(IndentLevel::from_token)
221 (ast::Expr::FieldExpr(expr), true) => {
222 expr.dot_token().as_ref().map(IndentLevel::from_token)
224 // if receiver is multiline expression, just keeps its indentation
225 (_, true) => Some(IndentLevel::from_node(&parent)),
228 let target_indent = match target_indent {
230 // in all other cases, take previous indentation and indent once
231 None => IndentLevel::from_node(&parent) + 1,
235 if current_indent_len == TextSize::of(&target_indent) {
239 Some(TextEdit::replace(TextRange::new(offset - current_indent_len, offset), target_indent))
242 /// Adds a space after an arrow when `fn foo() { ... }` is turned into `fn foo() -> { ... }`
243 fn on_arrow_typed(file: &SourceFile, offset: TextSize) -> Option<TextEdit> {
244 let file_text = file.syntax().text();
245 if !stdx::always!(file_text.char_at(offset) == Some('>')) {
248 let after_arrow = offset + TextSize::of('>');
249 if file_text.char_at(after_arrow) != Some('{') {
252 if find_node_at_offset::<ast::RetType>(file.syntax(), offset).is_none() {
256 Some(TextEdit::insert(after_arrow, " ".to_string()))
261 use test_utils::{assert_eq_text, extract_offset};
265 fn do_type_char(char_typed: char, before: &str) -> Option<String> {
266 let (offset, mut before) = extract_offset(before);
267 let edit = TextEdit::insert(offset, char_typed.to_string());
268 edit.apply(&mut before);
269 let parse = SourceFile::parse(&before);
270 on_char_typed_inner(&parse, offset, char_typed).map(|it| {
271 it.apply(&mut before);
276 fn type_char(char_typed: char, ra_fixture_before: &str, ra_fixture_after: &str) {
277 let actual = do_type_char(char_typed, ra_fixture_before)
278 .unwrap_or_else(|| panic!("typing `{}` did nothing", char_typed));
280 assert_eq_text!(ra_fixture_after, &actual);
283 fn type_char_noop(char_typed: char, ra_fixture_before: &str) {
284 let file_change = do_type_char(char_typed, ra_fixture_before);
285 assert!(file_change.is_none())
289 fn test_on_eq_typed() {
326 fn indents_new_chain_call() {
354 fn indents_new_chain_call_with_semi() {
382 fn indents_new_chain_call_with_let() {
403 fn indents_continued_chain_call() {
434 fn indents_middle_of_chain_call() {
439 let var = enum_defvariant_list().unwrap()
447 let var = enum_defvariant_list().unwrap()
458 let var = enum_defvariant_list().unwrap()
468 fn dont_indent_freestanding_dot() {
488 fn adds_space_after_return_type() {
501 fn adds_closing_brace_for_expr() {
505 fn f() { match () { _ => $0() } }
508 fn f() { match () { _ => {()} } }
523 fn f() { let x = $0(); }
526 fn f() { let x = {()}; }
532 fn f() { let x = $0a.b(); }
535 fn f() { let x = {a.b()}; }
552 const S: () = $0a.b();
556 const S: () = {a.b()};
582 fn noop_in_string_literal() {
583 // Regression test for #9351
587 fn check_with(ra_fixture: &str, expect: Expect) {
589 enum E { T(), R$0, C }
597 let actual = completion_list(&format!("{}\n{}", base, ra_fixture));
598 expect.assert_eq(&actual)
605 fn adds_closing_brace_for_use_tree() {
618 use some::{Path, $0Other};
621 use some::{Path, {Other}};
627 use some::{$0Path, Other};
630 use some::{{Path}, Other};
636 use some::path::$0to::Item;
639 use some::path::{to::Item};
645 use some::$0path::to::Item;
648 use some::{path::to::Item};
654 use $0some::path::to::Item;
657 use {some::path::to::Item};
663 use some::path::$0to::{Item};
666 use some::path::{to::{Item}};
682 use some::pa$0th::to::Item;
688 fn regression_629() {
694 CompletionKind::Reference,
696 field.name().to_string(),
708 CompletionKind::Reference,
710 field.name().to_string(),