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},
26 SyntaxKind::{FIELD_EXPR, METHOD_CALL_EXPR},
30 use text_edit::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).tree();
63 assert_eq!(file.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(file: &SourceFile, offset: TextSize, char_typed: char) -> Option<TextEdit> {
69 assert!(TRIGGER_CHARS.contains(char_typed));
71 '.' => on_dot_typed(file, offset),
72 '=' => on_eq_typed(file, offset),
73 '>' => on_arrow_typed(file, offset),
74 '{' => on_opening_brace_typed(file, offset),
79 /// Inserts a closing `}` when the user types an opening `{`, wrapping an existing expression in a
81 fn on_opening_brace_typed(file: &SourceFile, offset: TextSize) -> Option<TextEdit> {
82 stdx::always!(file.syntax().text().char_at(offset) == Some('{'));
83 let brace_token = file.syntax().token_at_offset(offset).right_biased()?;
84 let block = ast::BlockExpr::cast(brace_token.parent()?)?;
86 // We expect a block expression enclosing exactly 1 preexisting expression. It can be parsed as
87 // either the trailing expr or an ExprStmt.
89 match block.statements().next() {
90 Some(ast::Stmt::ExprStmt(it)) => {
91 // Use the expression span to place `}` before the `;`
92 it.expr()?.syntax().text_range().end()
94 None => block.tail_expr()?.syntax().text_range().end(),
99 Some(TextEdit::insert(offset, "}".to_string()))
102 /// Returns an edit which should be applied after `=` was typed. Primarily,
103 /// this works when adding `let =`.
104 // FIXME: use a snippet completion instead of this hack here.
105 fn on_eq_typed(file: &SourceFile, offset: TextSize) -> Option<TextEdit> {
106 stdx::always!(file.syntax().text().char_at(offset) == Some('='));
107 let let_stmt: ast::LetStmt = find_node_at_offset(file.syntax(), offset)?;
108 if let_stmt.semicolon_token().is_some() {
111 if let Some(expr) = let_stmt.initializer() {
112 let expr_range = expr.syntax().text_range();
113 if expr_range.contains(offset) && offset != expr_range.start() {
116 if file.syntax().text().slice(offset..expr_range.start()).contains_char('\n') {
122 let offset = let_stmt.syntax().text_range().end();
123 Some(TextEdit::insert(offset, ";".to_string()))
126 /// Returns an edit which should be applied when a dot ('.') is typed on a blank line, indenting the line appropriately.
127 fn on_dot_typed(file: &SourceFile, offset: TextSize) -> Option<TextEdit> {
128 stdx::always!(file.syntax().text().char_at(offset) == Some('.'));
130 file.syntax().token_at_offset(offset).left_biased().and_then(ast::Whitespace::cast)?;
132 let current_indent = {
133 let text = whitespace.text();
134 let newline = text.rfind('\n')?;
137 let current_indent_len = TextSize::of(current_indent);
139 let parent = whitespace.syntax().parent()?;
140 // Make sure dot is a part of call chain
141 if !matches!(parent.kind(), FIELD_EXPR | METHOD_CALL_EXPR) {
144 let prev_indent = IndentLevel::from_node(&parent);
145 let target_indent = format!(" {}", prev_indent);
146 let target_indent_len = TextSize::of(&target_indent);
147 if current_indent_len == target_indent_len {
151 Some(TextEdit::replace(TextRange::new(offset - current_indent_len, offset), target_indent))
154 /// Adds a space after an arrow when `fn foo() { ... }` is turned into `fn foo() -> { ... }`
155 fn on_arrow_typed(file: &SourceFile, offset: TextSize) -> Option<TextEdit> {
156 let file_text = file.syntax().text();
157 stdx::always!(file_text.char_at(offset) == Some('>'));
158 let after_arrow = offset + TextSize::of('>');
159 if file_text.char_at(after_arrow) != Some('{') {
162 if find_node_at_offset::<ast::RetType>(file.syntax(), offset).is_none() {
166 Some(TextEdit::insert(after_arrow, " ".to_string()))
171 use test_utils::{assert_eq_text, extract_offset};
175 fn do_type_char(char_typed: char, before: &str) -> Option<String> {
176 let (offset, mut before) = extract_offset(before);
177 let edit = TextEdit::insert(offset, char_typed.to_string());
178 edit.apply(&mut before);
179 let parse = SourceFile::parse(&before);
180 on_char_typed_inner(&parse.tree(), offset, char_typed).map(|it| {
181 it.apply(&mut before);
186 fn type_char(char_typed: char, ra_fixture_before: &str, ra_fixture_after: &str) {
187 let actual = do_type_char(char_typed, ra_fixture_before)
188 .unwrap_or_else(|| panic!("typing `{}` did nothing", char_typed));
190 assert_eq_text!(ra_fixture_after, &actual);
193 fn type_char_noop(char_typed: char, before: &str) {
194 let file_change = do_type_char(char_typed, before);
195 assert!(file_change.is_none())
199 fn test_on_eq_typed() {
236 fn indents_new_chain_call() {
264 fn indents_new_chain_call_with_semi() {
292 fn indents_new_chain_call_with_let() {
313 fn indents_continued_chain_call() {
344 fn indents_middle_of_chain_call() {
349 let var = enum_defvariant_list().unwrap()
357 let var = enum_defvariant_list().unwrap()
368 let var = enum_defvariant_list().unwrap()
378 fn dont_indent_freestanding_dot() {
398 fn adds_space_after_return_type() {
399 type_char('>', "fn foo() -$0{ 92 }", "fn foo() -> { 92 }")
403 fn adds_closing_brace() {
404 type_char('{', r"fn f() { match () { _ => $0() } }", r"fn f() { match () { _ => {()} } }");
405 type_char('{', r"fn f() { $0(); }", r"fn f() { {()}; }");
406 type_char('{', r"fn f() { let x = $0(); }", r"fn f() { let x = {()}; }");