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,
26 SyntaxKind::{self, FIELD_EXPR, METHOD_CALL_EXPR},
30 use text_edit::{Indel, TextEdit};
32 use crate::SourceChange;
34 pub(crate) use on_enter::on_enter;
36 // Don't forget to add new trigger characters to `server_capabilities` in `caps.rs`.
37 pub(crate) const TRIGGER_CHARS: &str = ".=>{";
39 // Feature: On Typing Assists
41 // Some features trigger on typing certain characters:
43 // - typing `let =` tries to smartly add `;` if `=` is followed by an existing expression
44 // - typing `.` in a chain method call auto-indents
45 // - typing `{` in front of an expression inserts a closing `}` after the expression
49 // Add the following to `settings.json`:
52 // "editor.formatOnType": true,
55 // image::https://user-images.githubusercontent.com/48062697/113166163-69758500-923a-11eb-81ee-eb33ec380399.gif[]
56 // image::https://user-images.githubusercontent.com/48062697/113171066-105c2000-923f-11eb-87ab-f4a263346567.gif[]
57 pub(crate) fn on_char_typed(
59 position: FilePosition,
61 ) -> Option<SourceChange> {
62 if !stdx::always!(TRIGGER_CHARS.contains(char_typed)) {
65 let file = &db.parse(position.file_id);
66 if !stdx::always!(file.tree().syntax().text().char_at(position.offset) == Some(char_typed)) {
69 let edit = on_char_typed_inner(file, position.offset, char_typed)?;
70 Some(SourceChange::from_text_edit(position.file_id, edit))
73 fn on_char_typed_inner(
74 file: &Parse<SourceFile>,
77 ) -> Option<TextEdit> {
78 if !stdx::always!(TRIGGER_CHARS.contains(char_typed)) {
82 '.' => on_dot_typed(&file.tree(), offset),
83 '=' => on_eq_typed(&file.tree(), offset),
84 '>' => on_arrow_typed(&file.tree(), offset),
85 '{' => on_opening_brace_typed(file, offset),
90 /// Inserts a closing `}` when the user types an opening `{`, wrapping an existing expression in a
91 /// block, or a part of a `use` item.
92 fn on_opening_brace_typed(file: &Parse<SourceFile>, offset: TextSize) -> Option<TextEdit> {
93 if !stdx::always!(file.tree().syntax().text().char_at(offset) == Some('{')) {
97 let brace_token = file.tree().syntax().token_at_offset(offset).right_biased()?;
98 if brace_token.kind() != SyntaxKind::L_CURLY {
102 // Remove the `{` to get a better parse tree, and reparse.
103 let range = brace_token.text_range();
104 if !stdx::always!(range.len() == TextSize::of('{')) {
107 let file = file.reparse(&Indel::delete(range));
109 if let Some(edit) = brace_expr(&file.tree(), offset) {
113 if let Some(edit) = brace_use_path(&file.tree(), offset) {
119 fn brace_use_path(file: &SourceFile, offset: TextSize) -> Option<TextEdit> {
120 let segment: ast::PathSegment = find_node_at_offset(file.syntax(), offset)?;
121 if segment.syntax().text_range().start() != offset {
125 let tree: ast::UseTree = find_node_at_offset(file.syntax(), offset)?;
127 Some(TextEdit::insert(
128 tree.syntax().text_range().end() + TextSize::of("{"),
133 fn brace_expr(file: &SourceFile, offset: TextSize) -> Option<TextEdit> {
134 let mut expr: ast::Expr = find_node_at_offset(file.syntax(), offset)?;
135 if expr.syntax().text_range().start() != offset {
139 // Enclose the outermost expression starting at `offset`
140 while let Some(parent) = expr.syntax().parent() {
141 if parent.text_range().start() != expr.syntax().text_range().start() {
145 match ast::Expr::cast(parent) {
146 Some(parent) => expr = parent,
151 // If it's a statement in a block, we don't know how many statements should be included
152 if ast::ExprStmt::can_cast(expr.syntax().parent()?.kind()) {
156 // Insert `}` right after the expression.
157 Some(TextEdit::insert(
158 expr.syntax().text_range().end() + TextSize::of("{"),
164 /// Returns an edit which should be applied after `=` was typed. Primarily,
165 /// this works when adding `let =`.
166 // FIXME: use a snippet completion instead of this hack here.
167 fn on_eq_typed(file: &SourceFile, offset: TextSize) -> Option<TextEdit> {
168 if !stdx::always!(file.syntax().text().char_at(offset) == Some('=')) {
171 let let_stmt: ast::LetStmt = find_node_at_offset(file.syntax(), offset)?;
172 if let_stmt.semicolon_token().is_some() {
175 if let Some(expr) = let_stmt.initializer() {
176 let expr_range = expr.syntax().text_range();
177 if expr_range.contains(offset) && offset != expr_range.start() {
180 if file.syntax().text().slice(offset..expr_range.start()).contains_char('\n') {
186 let offset = let_stmt.syntax().text_range().end();
187 Some(TextEdit::insert(offset, ";".to_string()))
190 /// Returns an edit which should be applied when a dot ('.') is typed on a blank line, indenting the line appropriately.
191 fn on_dot_typed(file: &SourceFile, offset: TextSize) -> Option<TextEdit> {
192 if !stdx::always!(file.syntax().text().char_at(offset) == Some('.')) {
196 file.syntax().token_at_offset(offset).left_biased().and_then(ast::Whitespace::cast)?;
198 let current_indent = {
199 let text = whitespace.text();
200 let newline = text.rfind('\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 if !matches!(parent.kind(), FIELD_EXPR | METHOD_CALL_EXPR) {
210 let prev_indent = IndentLevel::from_node(&parent);
211 let target_indent = format!(" {}", prev_indent);
212 let target_indent_len = TextSize::of(&target_indent);
213 if current_indent_len == target_indent_len {
217 Some(TextEdit::replace(TextRange::new(offset - current_indent_len, offset), target_indent))
220 /// Adds a space after an arrow when `fn foo() { ... }` is turned into `fn foo() -> { ... }`
221 fn on_arrow_typed(file: &SourceFile, offset: TextSize) -> Option<TextEdit> {
222 let file_text = file.syntax().text();
223 if !stdx::always!(file_text.char_at(offset) == Some('>')) {
226 let after_arrow = offset + TextSize::of('>');
227 if file_text.char_at(after_arrow) != Some('{') {
230 if find_node_at_offset::<ast::RetType>(file.syntax(), offset).is_none() {
234 Some(TextEdit::insert(after_arrow, " ".to_string()))
239 use test_utils::{assert_eq_text, extract_offset};
243 fn do_type_char(char_typed: char, before: &str) -> Option<String> {
244 let (offset, mut before) = extract_offset(before);
245 let edit = TextEdit::insert(offset, char_typed.to_string());
246 edit.apply(&mut before);
247 let parse = SourceFile::parse(&before);
248 on_char_typed_inner(&parse, offset, char_typed).map(|it| {
249 it.apply(&mut before);
254 fn type_char(char_typed: char, ra_fixture_before: &str, ra_fixture_after: &str) {
255 let actual = do_type_char(char_typed, ra_fixture_before)
256 .unwrap_or_else(|| panic!("typing `{}` did nothing", char_typed));
258 assert_eq_text!(ra_fixture_after, &actual);
261 fn type_char_noop(char_typed: char, ra_fixture_before: &str) {
262 let file_change = do_type_char(char_typed, ra_fixture_before);
263 assert!(file_change.is_none())
267 fn test_on_eq_typed() {
304 fn indents_new_chain_call() {
332 fn indents_new_chain_call_with_semi() {
360 fn indents_new_chain_call_with_let() {
381 fn indents_continued_chain_call() {
412 fn indents_middle_of_chain_call() {
417 let var = enum_defvariant_list().unwrap()
425 let var = enum_defvariant_list().unwrap()
436 let var = enum_defvariant_list().unwrap()
446 fn dont_indent_freestanding_dot() {
466 fn adds_space_after_return_type() {
479 fn adds_closing_brace_for_expr() {
483 fn f() { match () { _ => $0() } }
486 fn f() { match () { _ => {()} } }
501 fn f() { let x = $0(); }
504 fn f() { let x = {()}; }
510 fn f() { let x = $0a.b(); }
513 fn f() { let x = {a.b()}; }
530 const S: () = $0a.b();
534 const S: () = {a.b()};
560 fn noop_in_string_literal() {
561 // Regression test for #9351
565 fn check_with(ra_fixture: &str, expect: Expect) {
567 enum E { T(), R$0, C }
575 let actual = completion_list(&format!("{}\n{}", base, ra_fixture));
576 expect.assert_eq(&actual)
583 fn adds_closing_brace_for_use_tree() {
596 use some::{Path, $0Other};
599 use some::{Path, {Other}};
605 use some::{$0Path, Other};
608 use some::{{Path}, Other};
614 use some::path::$0to::Item;
617 use some::path::{to::Item};
623 use some::$0path::to::Item;
626 use some::{path::to::Item};
632 use $0some::path::to::Item;
635 use {some::path::to::Item};
641 use some::path::$0to::{Item};
644 use some::path::{to::{Item}};
660 use some::pa$0th::to::Item;