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},
20 source_change::SourceFileEdits,
24 algo::find_node_at_offset,
25 ast::{self, edit::IndentLevel, AstToken},
27 SyntaxKind::{FIELD_EXPR, METHOD_CALL_EXPR},
31 use text_edit::TextEdit;
33 use crate::SourceChange;
35 pub(crate) use on_enter::on_enter;
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,
53 pub(crate) fn on_char_typed(
55 position: FilePosition,
57 ) -> Option<SourceChange> {
58 assert!(TRIGGER_CHARS.contains(char_typed));
59 let file = &db.parse(position.file_id).tree();
60 assert_eq!(file.syntax().text().char_at(position.offset), Some(char_typed));
61 let edit = on_char_typed_inner(file, position.offset, char_typed)?;
62 Some(SourceFileEdits::from_text_edit(position.file_id, edit).into())
65 fn on_char_typed_inner(file: &SourceFile, offset: TextSize, char_typed: char) -> Option<TextEdit> {
66 assert!(TRIGGER_CHARS.contains(char_typed));
68 '.' => on_dot_typed(file, offset),
69 '=' => on_eq_typed(file, offset),
70 '>' => on_arrow_typed(file, offset),
75 /// Returns an edit which should be applied after `=` was typed. Primarily,
76 /// this works when adding `let =`.
77 // FIXME: use a snippet completion instead of this hack here.
78 fn on_eq_typed(file: &SourceFile, offset: TextSize) -> Option<TextEdit> {
79 assert_eq!(file.syntax().text().char_at(offset), Some('='));
80 let let_stmt: ast::LetStmt = find_node_at_offset(file.syntax(), offset)?;
81 if let_stmt.semicolon_token().is_some() {
84 if let Some(expr) = let_stmt.initializer() {
85 let expr_range = expr.syntax().text_range();
86 if expr_range.contains(offset) && offset != expr_range.start() {
89 if file.syntax().text().slice(offset..expr_range.start()).contains_char('\n') {
95 let offset = let_stmt.syntax().text_range().end();
96 Some(TextEdit::insert(offset, ";".to_string()))
99 /// Returns an edit which should be applied when a dot ('.') is typed on a blank line, indenting the line appropriately.
100 fn on_dot_typed(file: &SourceFile, offset: TextSize) -> Option<TextEdit> {
101 assert_eq!(file.syntax().text().char_at(offset), Some('.'));
103 file.syntax().token_at_offset(offset).left_biased().and_then(ast::Whitespace::cast)?;
105 let current_indent = {
106 let text = whitespace.text();
107 let newline = text.rfind('\n')?;
110 let current_indent_len = TextSize::of(current_indent);
112 let parent = whitespace.syntax().parent();
113 // Make sure dot is a part of call chain
114 if !matches!(parent.kind(), FIELD_EXPR | METHOD_CALL_EXPR) {
117 let prev_indent = IndentLevel::from_node(&parent);
118 let target_indent = format!(" {}", prev_indent);
119 let target_indent_len = TextSize::of(&target_indent);
120 if current_indent_len == target_indent_len {
124 Some(TextEdit::replace(TextRange::new(offset - current_indent_len, offset), target_indent))
127 /// Adds a space after an arrow when `fn foo() { ... }` is turned into `fn foo() -> { ... }`
128 fn on_arrow_typed(file: &SourceFile, offset: TextSize) -> Option<TextEdit> {
129 let file_text = file.syntax().text();
130 assert_eq!(file_text.char_at(offset), Some('>'));
131 let after_arrow = offset + TextSize::of('>');
132 if file_text.char_at(after_arrow) != Some('{') {
135 if find_node_at_offset::<ast::RetType>(file.syntax(), offset).is_none() {
139 Some(TextEdit::insert(after_arrow, " ".to_string()))
144 use test_utils::{assert_eq_text, extract_offset};
148 fn do_type_char(char_typed: char, before: &str) -> Option<String> {
149 let (offset, before) = extract_offset(before);
150 let edit = TextEdit::insert(offset, char_typed.to_string());
151 let mut before = before.to_string();
152 edit.apply(&mut before);
153 let parse = SourceFile::parse(&before);
154 on_char_typed_inner(&parse.tree(), offset, char_typed).map(|it| {
155 it.apply(&mut before);
160 fn type_char(char_typed: char, ra_fixture_before: &str, ra_fixture_after: &str) {
161 let actual = do_type_char(char_typed, ra_fixture_before)
162 .unwrap_or_else(|| panic!("typing `{}` did nothing", char_typed));
164 assert_eq_text!(ra_fixture_after, &actual);
167 fn type_char_noop(char_typed: char, before: &str) {
168 let file_change = do_type_char(char_typed, before);
169 assert!(file_change.is_none())
173 fn test_on_eq_typed() {
210 fn indents_new_chain_call() {
238 fn indents_new_chain_call_with_semi() {
266 fn indents_new_chain_call_with_let() {
287 fn indents_continued_chain_call() {
318 fn indents_middle_of_chain_call() {
323 let var = enum_defvariant_list().unwrap()
331 let var = enum_defvariant_list().unwrap()
342 let var = enum_defvariant_list().unwrap()
352 fn dont_indent_freestanding_dot() {
372 fn adds_space_after_return_type() {
373 type_char('>', "fn foo() -$0{ 92 }", "fn foo() -> { 92 }")