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
48 // Add the following to `settings.json`:
51 // "editor.formatOnType": true,
54 // image::https://user-images.githubusercontent.com/48062697/113166163-69758500-923a-11eb-81ee-eb33ec380399.gif[]
55 // image::https://user-images.githubusercontent.com/48062697/113171066-105c2000-923f-11eb-87ab-f4a263346567.gif[]
56 pub(crate) fn on_char_typed(
58 position: FilePosition,
60 ) -> Option<SourceChange> {
61 assert!(TRIGGER_CHARS.contains(char_typed));
62 let file = &db.parse(position.file_id);
63 assert_eq!(file.tree().syntax().text().char_at(position.offset), Some(char_typed));
64 let edit = on_char_typed_inner(file, position.offset, char_typed)?;
65 Some(SourceChange::from_text_edit(position.file_id, edit))
68 fn on_char_typed_inner(
69 file: &Parse<SourceFile>,
72 ) -> Option<TextEdit> {
73 assert!(TRIGGER_CHARS.contains(char_typed));
75 '.' => on_dot_typed(&file.tree(), offset),
76 '=' => on_eq_typed(&file.tree(), offset),
77 '>' => on_arrow_typed(&file.tree(), offset),
78 '{' => on_opening_brace_typed(file, offset),
83 /// Inserts a closing `}` when the user types an opening `{`, wrapping an existing expression in a
85 fn on_opening_brace_typed(file: &Parse<SourceFile>, offset: TextSize) -> Option<TextEdit> {
86 stdx::always!(file.tree().syntax().text().char_at(offset) == Some('{'));
88 let brace_token = file.tree().syntax().token_at_offset(offset).right_biased()?;
90 // Remove the `{` to get a better parse tree, and reparse
91 let file = file.reparse(&Indel::delete(brace_token.text_range()));
93 let mut expr: ast::Expr = find_node_at_offset(file.tree().syntax(), offset)?;
94 if expr.syntax().text_range().start() != offset {
98 // Enclose the outermost expression starting at `offset`
99 while let Some(parent) = expr.syntax().parent() {
100 if parent.text_range().start() != expr.syntax().text_range().start() {
104 match ast::Expr::cast(parent) {
105 Some(parent) => expr = parent,
110 // If it's a statement in a block, we don't know how many statements should be included
111 if ast::ExprStmt::can_cast(expr.syntax().parent()?.kind()) {
115 // Insert `}` right after the expression.
116 Some(TextEdit::insert(expr.syntax().text_range().end() + TextSize::of("{"), "}".to_string()))
119 /// Returns an edit which should be applied after `=` was typed. Primarily,
120 /// this works when adding `let =`.
121 // FIXME: use a snippet completion instead of this hack here.
122 fn on_eq_typed(file: &SourceFile, offset: TextSize) -> Option<TextEdit> {
123 stdx::always!(file.syntax().text().char_at(offset) == Some('='));
124 let let_stmt: ast::LetStmt = find_node_at_offset(file.syntax(), offset)?;
125 if let_stmt.semicolon_token().is_some() {
128 if let Some(expr) = let_stmt.initializer() {
129 let expr_range = expr.syntax().text_range();
130 if expr_range.contains(offset) && offset != expr_range.start() {
133 if file.syntax().text().slice(offset..expr_range.start()).contains_char('\n') {
139 let offset = let_stmt.syntax().text_range().end();
140 Some(TextEdit::insert(offset, ";".to_string()))
143 /// Returns an edit which should be applied when a dot ('.') is typed on a blank line, indenting the line appropriately.
144 fn on_dot_typed(file: &SourceFile, offset: TextSize) -> Option<TextEdit> {
145 stdx::always!(file.syntax().text().char_at(offset) == Some('.'));
147 file.syntax().token_at_offset(offset).left_biased().and_then(ast::Whitespace::cast)?;
149 let current_indent = {
150 let text = whitespace.text();
151 let newline = text.rfind('\n')?;
154 let current_indent_len = TextSize::of(current_indent);
156 let parent = whitespace.syntax().parent()?;
157 // Make sure dot is a part of call chain
158 if !matches!(parent.kind(), FIELD_EXPR | METHOD_CALL_EXPR) {
161 let prev_indent = IndentLevel::from_node(&parent);
162 let target_indent = format!(" {}", prev_indent);
163 let target_indent_len = TextSize::of(&target_indent);
164 if current_indent_len == target_indent_len {
168 Some(TextEdit::replace(TextRange::new(offset - current_indent_len, offset), target_indent))
171 /// Adds a space after an arrow when `fn foo() { ... }` is turned into `fn foo() -> { ... }`
172 fn on_arrow_typed(file: &SourceFile, offset: TextSize) -> Option<TextEdit> {
173 let file_text = file.syntax().text();
174 stdx::always!(file_text.char_at(offset) == Some('>'));
175 let after_arrow = offset + TextSize::of('>');
176 if file_text.char_at(after_arrow) != Some('{') {
179 if find_node_at_offset::<ast::RetType>(file.syntax(), offset).is_none() {
183 Some(TextEdit::insert(after_arrow, " ".to_string()))
188 use test_utils::{assert_eq_text, extract_offset};
192 fn do_type_char(char_typed: char, before: &str) -> Option<String> {
193 let (offset, mut before) = extract_offset(before);
194 let edit = TextEdit::insert(offset, char_typed.to_string());
195 edit.apply(&mut before);
196 let parse = SourceFile::parse(&before);
197 on_char_typed_inner(&parse, offset, char_typed).map(|it| {
198 it.apply(&mut before);
203 fn type_char(char_typed: char, ra_fixture_before: &str, ra_fixture_after: &str) {
204 let actual = do_type_char(char_typed, ra_fixture_before)
205 .unwrap_or_else(|| panic!("typing `{}` did nothing", char_typed));
207 assert_eq_text!(ra_fixture_after, &actual);
210 fn type_char_noop(char_typed: char, before: &str) {
211 let file_change = do_type_char(char_typed, before);
212 assert!(file_change.is_none())
216 fn test_on_eq_typed() {
253 fn indents_new_chain_call() {
281 fn indents_new_chain_call_with_semi() {
309 fn indents_new_chain_call_with_let() {
330 fn indents_continued_chain_call() {
361 fn indents_middle_of_chain_call() {
366 let var = enum_defvariant_list().unwrap()
374 let var = enum_defvariant_list().unwrap()
385 let var = enum_defvariant_list().unwrap()
395 fn dont_indent_freestanding_dot() {
415 fn adds_space_after_return_type() {
416 type_char('>', "fn foo() -$0{ 92 }", "fn foo() -> { 92 }")
420 fn adds_closing_brace() {
424 fn f() { match () { _ => $0() } }
427 fn f() { match () { _ => {()} } }
442 fn f() { let x = $0(); }
445 fn f() { let x = {()}; }
451 fn f() { let x = $0a.b(); }
454 fn f() { let x = {a.b()}; }
471 const S: () = $0a.b();
475 const S: () = {a.b()};