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
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 let mut expr: ast::Expr = find_node_at_offset(file.tree().syntax(), offset)?;
103 if expr.syntax().text_range().start() != offset {
107 // Enclose the outermost expression starting at `offset`
108 while let Some(parent) = expr.syntax().parent() {
109 if parent.text_range().start() != expr.syntax().text_range().start() {
113 match ast::Expr::cast(parent) {
114 Some(parent) => expr = parent,
119 // If it's a statement in a block, we don't know how many statements should be included
120 if ast::ExprStmt::can_cast(expr.syntax().parent()?.kind()) {
124 // Insert `}` right after the expression.
125 Some(TextEdit::insert(expr.syntax().text_range().end() + TextSize::of("{"), "}".to_string()))
128 /// Returns an edit which should be applied after `=` was typed. Primarily,
129 /// this works when adding `let =`.
130 // FIXME: use a snippet completion instead of this hack here.
131 fn on_eq_typed(file: &SourceFile, offset: TextSize) -> Option<TextEdit> {
132 if !stdx::always!(file.syntax().text().char_at(offset) == Some('=')) {
135 let let_stmt: ast::LetStmt = find_node_at_offset(file.syntax(), offset)?;
136 if let_stmt.semicolon_token().is_some() {
139 if let Some(expr) = let_stmt.initializer() {
140 let expr_range = expr.syntax().text_range();
141 if expr_range.contains(offset) && offset != expr_range.start() {
144 if file.syntax().text().slice(offset..expr_range.start()).contains_char('\n') {
150 let offset = let_stmt.syntax().text_range().end();
151 Some(TextEdit::insert(offset, ";".to_string()))
154 /// Returns an edit which should be applied when a dot ('.') is typed on a blank line, indenting the line appropriately.
155 fn on_dot_typed(file: &SourceFile, offset: TextSize) -> Option<TextEdit> {
156 if !stdx::always!(file.syntax().text().char_at(offset) == Some('.')) {
160 file.syntax().token_at_offset(offset).left_biased().and_then(ast::Whitespace::cast)?;
162 let current_indent = {
163 let text = whitespace.text();
164 let newline = text.rfind('\n')?;
167 let current_indent_len = TextSize::of(current_indent);
169 let parent = whitespace.syntax().parent()?;
170 // Make sure dot is a part of call chain
171 if !matches!(parent.kind(), FIELD_EXPR | METHOD_CALL_EXPR) {
174 let prev_indent = IndentLevel::from_node(&parent);
175 let target_indent = format!(" {}", prev_indent);
176 let target_indent_len = TextSize::of(&target_indent);
177 if current_indent_len == target_indent_len {
181 Some(TextEdit::replace(TextRange::new(offset - current_indent_len, offset), target_indent))
184 /// Adds a space after an arrow when `fn foo() { ... }` is turned into `fn foo() -> { ... }`
185 fn on_arrow_typed(file: &SourceFile, offset: TextSize) -> Option<TextEdit> {
186 let file_text = file.syntax().text();
187 if !stdx::always!(file_text.char_at(offset) == Some('>')) {
190 let after_arrow = offset + TextSize::of('>');
191 if file_text.char_at(after_arrow) != Some('{') {
194 if find_node_at_offset::<ast::RetType>(file.syntax(), offset).is_none() {
198 Some(TextEdit::insert(after_arrow, " ".to_string()))
203 use test_utils::{assert_eq_text, extract_offset};
207 fn do_type_char(char_typed: char, before: &str) -> Option<String> {
208 let (offset, mut before) = extract_offset(before);
209 let edit = TextEdit::insert(offset, char_typed.to_string());
210 edit.apply(&mut before);
211 let parse = SourceFile::parse(&before);
212 on_char_typed_inner(&parse, offset, char_typed).map(|it| {
213 it.apply(&mut before);
218 fn type_char(char_typed: char, ra_fixture_before: &str, ra_fixture_after: &str) {
219 let actual = do_type_char(char_typed, ra_fixture_before)
220 .unwrap_or_else(|| panic!("typing `{}` did nothing", char_typed));
222 assert_eq_text!(ra_fixture_after, &actual);
225 fn type_char_noop(char_typed: char, before: &str) {
226 let file_change = do_type_char(char_typed, before);
227 assert!(file_change.is_none())
231 fn test_on_eq_typed() {
268 fn indents_new_chain_call() {
296 fn indents_new_chain_call_with_semi() {
324 fn indents_new_chain_call_with_let() {
345 fn indents_continued_chain_call() {
376 fn indents_middle_of_chain_call() {
381 let var = enum_defvariant_list().unwrap()
389 let var = enum_defvariant_list().unwrap()
400 let var = enum_defvariant_list().unwrap()
410 fn dont_indent_freestanding_dot() {
430 fn adds_space_after_return_type() {
431 type_char('>', "fn foo() -$0{ 92 }", "fn foo() -> { 92 }")
435 fn adds_closing_brace() {
439 fn f() { match () { _ => $0() } }
442 fn f() { match () { _ => {()} } }
457 fn f() { let x = $0(); }
460 fn f() { let x = {()}; }
466 fn f() { let x = $0a.b(); }
469 fn f() { let x = {a.b()}; }
486 const S: () = $0a.b();
490 const S: () = {a.b()};