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::{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()?;
99 // Remove the `{` to get a better parse tree, and reparse
100 let file = file.reparse(&Indel::delete(brace_token.text_range()));
102 if let Some(edit) = brace_expr(&file.tree(), offset) {
106 if let Some(edit) = brace_use_path(&file.tree(), offset) {
112 fn brace_use_path(file: &SourceFile, offset: TextSize) -> Option<TextEdit> {
113 let segment: ast::PathSegment = find_node_at_offset(file.syntax(), offset)?;
114 if segment.syntax().text_range().start() != offset {
118 let tree: ast::UseTree = find_node_at_offset(file.syntax(), offset)?;
120 Some(TextEdit::insert(
121 tree.syntax().text_range().end() + TextSize::of("{"),
126 fn brace_expr(file: &SourceFile, offset: TextSize) -> Option<TextEdit> {
127 let mut expr: ast::Expr = find_node_at_offset(file.syntax(), offset)?;
128 if expr.syntax().text_range().start() != offset {
132 // Enclose the outermost expression starting at `offset`
133 while let Some(parent) = expr.syntax().parent() {
134 if parent.text_range().start() != expr.syntax().text_range().start() {
138 match ast::Expr::cast(parent) {
139 Some(parent) => expr = parent,
144 // If it's a statement in a block, we don't know how many statements should be included
145 if ast::ExprStmt::can_cast(expr.syntax().parent()?.kind()) {
149 // Insert `}` right after the expression.
150 Some(TextEdit::insert(
151 expr.syntax().text_range().end() + TextSize::of("{"),
157 /// Returns an edit which should be applied after `=` was typed. Primarily,
158 /// this works when adding `let =`.
159 // FIXME: use a snippet completion instead of this hack here.
160 fn on_eq_typed(file: &SourceFile, offset: TextSize) -> Option<TextEdit> {
161 if !stdx::always!(file.syntax().text().char_at(offset) == Some('=')) {
164 let let_stmt: ast::LetStmt = find_node_at_offset(file.syntax(), offset)?;
165 if let_stmt.semicolon_token().is_some() {
168 if let Some(expr) = let_stmt.initializer() {
169 let expr_range = expr.syntax().text_range();
170 if expr_range.contains(offset) && offset != expr_range.start() {
173 if file.syntax().text().slice(offset..expr_range.start()).contains_char('\n') {
179 let offset = let_stmt.syntax().text_range().end();
180 Some(TextEdit::insert(offset, ";".to_string()))
183 /// Returns an edit which should be applied when a dot ('.') is typed on a blank line, indenting the line appropriately.
184 fn on_dot_typed(file: &SourceFile, offset: TextSize) -> Option<TextEdit> {
185 if !stdx::always!(file.syntax().text().char_at(offset) == Some('.')) {
189 file.syntax().token_at_offset(offset).left_biased().and_then(ast::Whitespace::cast)?;
191 let current_indent = {
192 let text = whitespace.text();
193 let newline = text.rfind('\n')?;
196 let current_indent_len = TextSize::of(current_indent);
198 let parent = whitespace.syntax().parent()?;
199 // Make sure dot is a part of call chain
200 if !matches!(parent.kind(), FIELD_EXPR | METHOD_CALL_EXPR) {
203 let prev_indent = IndentLevel::from_node(&parent);
204 let target_indent = format!(" {}", prev_indent);
205 let target_indent_len = TextSize::of(&target_indent);
206 if current_indent_len == target_indent_len {
210 Some(TextEdit::replace(TextRange::new(offset - current_indent_len, offset), target_indent))
213 /// Adds a space after an arrow when `fn foo() { ... }` is turned into `fn foo() -> { ... }`
214 fn on_arrow_typed(file: &SourceFile, offset: TextSize) -> Option<TextEdit> {
215 let file_text = file.syntax().text();
216 if !stdx::always!(file_text.char_at(offset) == Some('>')) {
219 let after_arrow = offset + TextSize::of('>');
220 if file_text.char_at(after_arrow) != Some('{') {
223 if find_node_at_offset::<ast::RetType>(file.syntax(), offset).is_none() {
227 Some(TextEdit::insert(after_arrow, " ".to_string()))
232 use test_utils::{assert_eq_text, extract_offset};
236 fn do_type_char(char_typed: char, before: &str) -> Option<String> {
237 let (offset, mut before) = extract_offset(before);
238 let edit = TextEdit::insert(offset, char_typed.to_string());
239 edit.apply(&mut before);
240 let parse = SourceFile::parse(&before);
241 on_char_typed_inner(&parse, offset, char_typed).map(|it| {
242 it.apply(&mut before);
247 fn type_char(char_typed: char, ra_fixture_before: &str, ra_fixture_after: &str) {
248 let actual = do_type_char(char_typed, ra_fixture_before)
249 .unwrap_or_else(|| panic!("typing `{}` did nothing", char_typed));
251 assert_eq_text!(ra_fixture_after, &actual);
254 fn type_char_noop(char_typed: char, ra_fixture_before: &str) {
255 let file_change = do_type_char(char_typed, ra_fixture_before);
256 assert!(file_change.is_none())
260 fn test_on_eq_typed() {
297 fn indents_new_chain_call() {
325 fn indents_new_chain_call_with_semi() {
353 fn indents_new_chain_call_with_let() {
374 fn indents_continued_chain_call() {
405 fn indents_middle_of_chain_call() {
410 let var = enum_defvariant_list().unwrap()
418 let var = enum_defvariant_list().unwrap()
429 let var = enum_defvariant_list().unwrap()
439 fn dont_indent_freestanding_dot() {
459 fn adds_space_after_return_type() {
472 fn adds_closing_brace_for_expr() {
476 fn f() { match () { _ => $0() } }
479 fn f() { match () { _ => {()} } }
494 fn f() { let x = $0(); }
497 fn f() { let x = {()}; }
503 fn f() { let x = $0a.b(); }
506 fn f() { let x = {a.b()}; }
523 const S: () = $0a.b();
527 const S: () = {a.b()};
553 fn adds_closing_brace_for_use_tree() {
566 use some::{Path, $0Other};
569 use some::{Path, {Other}};
575 use some::{$0Path, Other};
578 use some::{{Path}, Other};
584 use some::path::$0to::Item;
587 use some::path::{to::Item};
593 use some::$0path::to::Item;
596 use some::{path::to::Item};
602 use $0some::path::to::Item;
605 use {some::path::to::Item};
611 use some::path::$0to::{Item};
614 use some::path::{to::{Item}};
630 use some::pa$0th::to::Item;