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!
18 use ide_db::base_db::{FilePosition, SourceDatabase};
19 use ide_db::{source_change::SourceFileEdit, RootDatabase};
21 algo::find_node_at_offset,
22 ast::{self, edit::IndentLevel, AstToken},
24 SyntaxKind::{FIELD_EXPR, METHOD_CALL_EXPR},
28 use text_edit::TextEdit;
30 use crate::SourceChange;
32 pub(crate) use on_enter::on_enter;
34 pub(crate) const TRIGGER_CHARS: &str = ".=>";
36 // Feature: On Typing Assists
38 // Some features trigger on typing certain characters:
40 // - typing `let =` tries to smartly add `;` if `=` is followed by an existing expression
41 // - typing `.` in a chain method call auto-indents
45 // Add the following to `settings.json`:
48 // "editor.formatOnType": true,
50 pub(crate) fn on_char_typed(
52 position: FilePosition,
54 ) -> Option<SourceChange> {
55 assert!(TRIGGER_CHARS.contains(char_typed));
56 let file = &db.parse(position.file_id).tree();
57 assert_eq!(file.syntax().text().char_at(position.offset), Some(char_typed));
58 let edit = on_char_typed_inner(file, position.offset, char_typed)?;
59 Some(SourceFileEdit { file_id: position.file_id, edit }.into())
62 fn on_char_typed_inner(file: &SourceFile, offset: TextSize, char_typed: char) -> Option<TextEdit> {
63 assert!(TRIGGER_CHARS.contains(char_typed));
65 '.' => on_dot_typed(file, offset),
66 '=' => on_eq_typed(file, offset),
67 '>' => on_arrow_typed(file, offset),
72 /// Returns an edit which should be applied after `=` was typed. Primarily,
73 /// this works when adding `let =`.
74 // FIXME: use a snippet completion instead of this hack here.
75 fn on_eq_typed(file: &SourceFile, offset: TextSize) -> Option<TextEdit> {
76 assert_eq!(file.syntax().text().char_at(offset), Some('='));
77 let let_stmt: ast::LetStmt = find_node_at_offset(file.syntax(), offset)?;
78 if let_stmt.semicolon_token().is_some() {
81 if let Some(expr) = let_stmt.initializer() {
82 let expr_range = expr.syntax().text_range();
83 if expr_range.contains(offset) && offset != expr_range.start() {
86 if file.syntax().text().slice(offset..expr_range.start()).contains_char('\n') {
92 let offset = let_stmt.syntax().text_range().end();
93 Some(TextEdit::insert(offset, ";".to_string()))
96 /// Returns an edit which should be applied when a dot ('.') is typed on a blank line, indenting the line appropriately.
97 fn on_dot_typed(file: &SourceFile, offset: TextSize) -> Option<TextEdit> {
98 assert_eq!(file.syntax().text().char_at(offset), Some('.'));
100 file.syntax().token_at_offset(offset).left_biased().and_then(ast::Whitespace::cast)?;
102 let current_indent = {
103 let text = whitespace.text();
104 let newline = text.rfind('\n')?;
107 let current_indent_len = TextSize::of(current_indent);
109 let parent = whitespace.syntax().parent();
110 // Make sure dot is a part of call chain
111 if !matches!(parent.kind(), FIELD_EXPR | METHOD_CALL_EXPR) {
114 let prev_indent = IndentLevel::from_node(&parent);
115 let target_indent = format!(" {}", prev_indent);
116 let target_indent_len = TextSize::of(&target_indent);
117 if current_indent_len == target_indent_len {
121 Some(TextEdit::replace(TextRange::new(offset - current_indent_len, offset), target_indent))
124 /// Adds a space after an arrow when `fn foo() { ... }` is turned into `fn foo() -> { ... }`
125 fn on_arrow_typed(file: &SourceFile, offset: TextSize) -> Option<TextEdit> {
126 let file_text = file.syntax().text();
127 assert_eq!(file_text.char_at(offset), Some('>'));
128 let after_arrow = offset + TextSize::of('>');
129 if file_text.char_at(after_arrow) != Some('{') {
132 if find_node_at_offset::<ast::RetType>(file.syntax(), offset).is_none() {
136 Some(TextEdit::insert(after_arrow, " ".to_string()))
141 use test_utils::{assert_eq_text, extract_offset};
145 fn do_type_char(char_typed: char, before: &str) -> Option<String> {
146 let (offset, before) = extract_offset(before);
147 let edit = TextEdit::insert(offset, char_typed.to_string());
148 let mut before = before.to_string();
149 edit.apply(&mut before);
150 let parse = SourceFile::parse(&before);
151 on_char_typed_inner(&parse.tree(), offset, char_typed).map(|it| {
152 it.apply(&mut before);
157 fn type_char(char_typed: char, ra_fixture_before: &str, ra_fixture_after: &str) {
158 let actual = do_type_char(char_typed, ra_fixture_before)
159 .unwrap_or_else(|| panic!("typing `{}` did nothing", char_typed));
161 assert_eq_text!(ra_fixture_after, &actual);
164 fn type_char_noop(char_typed: char, before: &str) {
165 let file_change = do_type_char(char_typed, before);
166 assert!(file_change.is_none())
170 fn test_on_eq_typed() {
207 fn indents_new_chain_call() {
235 fn indents_new_chain_call_with_semi() {
263 fn indents_new_chain_call_with_let() {
284 fn indents_continued_chain_call() {
315 fn indents_middle_of_chain_call() {
320 let var = enum_defvariant_list().unwrap()
328 let var = enum_defvariant_list().unwrap()
339 let var = enum_defvariant_list().unwrap()
349 fn dont_indent_freestanding_dot() {
369 fn adds_space_after_return_type() {
370 type_char('>', "fn foo() -$0{ 92 }", "fn foo() -> { 92 }")