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 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
42 pub(crate) fn on_char_typed(
44 position: FilePosition,
46 ) -> Option<SourceChange> {
47 assert!(TRIGGER_CHARS.contains(char_typed));
48 let file = &db.parse(position.file_id).tree();
49 assert_eq!(file.syntax().text().char_at(position.offset), Some(char_typed));
50 let edit = on_char_typed_inner(file, position.offset, char_typed)?;
51 Some(SourceFileEdit { file_id: position.file_id, edit }.into())
54 fn on_char_typed_inner(file: &SourceFile, offset: TextSize, char_typed: char) -> Option<TextEdit> {
55 assert!(TRIGGER_CHARS.contains(char_typed));
57 '.' => on_dot_typed(file, offset),
58 '=' => on_eq_typed(file, offset),
59 '>' => on_arrow_typed(file, offset),
64 /// Returns an edit which should be applied after `=` was typed. Primarily,
65 /// this works when adding `let =`.
66 // FIXME: use a snippet completion instead of this hack here.
67 fn on_eq_typed(file: &SourceFile, offset: TextSize) -> Option<TextEdit> {
68 assert_eq!(file.syntax().text().char_at(offset), Some('='));
69 let let_stmt: ast::LetStmt = find_node_at_offset(file.syntax(), offset)?;
70 if let_stmt.semicolon_token().is_some() {
73 if let Some(expr) = let_stmt.initializer() {
74 let expr_range = expr.syntax().text_range();
75 if expr_range.contains(offset) && offset != expr_range.start() {
78 if file.syntax().text().slice(offset..expr_range.start()).contains_char('\n') {
84 let offset = let_stmt.syntax().text_range().end();
85 Some(TextEdit::insert(offset, ";".to_string()))
88 /// Returns an edit which should be applied when a dot ('.') is typed on a blank line, indenting the line appropriately.
89 fn on_dot_typed(file: &SourceFile, offset: TextSize) -> Option<TextEdit> {
90 assert_eq!(file.syntax().text().char_at(offset), Some('.'));
92 file.syntax().token_at_offset(offset).left_biased().and_then(ast::Whitespace::cast)?;
94 let current_indent = {
95 let text = whitespace.text();
96 let newline = text.rfind('\n')?;
99 let current_indent_len = TextSize::of(current_indent);
101 let parent = whitespace.syntax().parent();
102 // Make sure dot is a part of call chain
103 if !matches!(parent.kind(), FIELD_EXPR | METHOD_CALL_EXPR) {
106 let prev_indent = IndentLevel::from_node(&parent);
107 let target_indent = format!(" {}", prev_indent);
108 let target_indent_len = TextSize::of(&target_indent);
109 if current_indent_len == target_indent_len {
113 Some(TextEdit::replace(TextRange::new(offset - current_indent_len, offset), target_indent))
116 /// Adds a space after an arrow when `fn foo() { ... }` is turned into `fn foo() -> { ... }`
117 fn on_arrow_typed(file: &SourceFile, offset: TextSize) -> Option<TextEdit> {
118 let file_text = file.syntax().text();
119 assert_eq!(file_text.char_at(offset), Some('>'));
120 let after_arrow = offset + TextSize::of('>');
121 if file_text.char_at(after_arrow) != Some('{') {
124 if find_node_at_offset::<ast::RetType>(file.syntax(), offset).is_none() {
128 Some(TextEdit::insert(after_arrow, " ".to_string()))
133 use test_utils::{assert_eq_text, extract_offset};
137 fn do_type_char(char_typed: char, before: &str) -> Option<String> {
138 let (offset, before) = extract_offset(before);
139 let edit = TextEdit::insert(offset, char_typed.to_string());
140 let mut before = before.to_string();
141 edit.apply(&mut before);
142 let parse = SourceFile::parse(&before);
143 on_char_typed_inner(&parse.tree(), offset, char_typed).map(|it| {
144 it.apply(&mut before);
149 fn type_char(char_typed: char, ra_fixture_before: &str, ra_fixture_after: &str) {
150 let actual = do_type_char(char_typed, ra_fixture_before)
151 .unwrap_or_else(|| panic!("typing `{}` did nothing", char_typed));
153 assert_eq_text!(ra_fixture_after, &actual);
156 fn type_char_noop(char_typed: char, before: &str) {
157 let file_change = do_type_char(char_typed, before);
158 assert!(file_change.is_none())
162 fn test_on_eq_typed() {
199 fn indents_new_chain_call() {
227 fn indents_new_chain_call_with_semi() {
255 fn indents_new_chain_call_with_let() {
276 fn indents_continued_chain_call() {
307 fn indents_middle_of_chain_call() {
312 let var = enum_defvariant_list().unwrap()
320 let var = enum_defvariant_list().unwrap()
331 let var = enum_defvariant_list().unwrap()
341 fn dont_indent_freestanding_dot() {
361 fn adds_space_after_return_type() {
362 type_char('>', "fn foo() -<|>{ 92 }", "fn foo() -> { 92 }")