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 pub(crate) const TRIGGER_CHARS: &str = ".=>";
38 // Feature: On Typing Assists
40 // Some features trigger on typing certain characters:
42 // - typing `let =` tries to smartly add `;` if `=` is followed by an existing expression
43 // - typing `.` in a chain method call auto-indents
47 // Add the following to `settings.json`:
50 // "editor.formatOnType": true,
52 pub(crate) fn on_char_typed(
54 position: FilePosition,
56 ) -> Option<SourceChange> {
57 assert!(TRIGGER_CHARS.contains(char_typed));
58 let file = &db.parse(position.file_id).tree();
59 assert_eq!(file.syntax().text().char_at(position.offset), Some(char_typed));
60 let edit = on_char_typed_inner(file, position.offset, char_typed)?;
61 Some(SourceChange::from_text_edit(position.file_id, edit))
64 fn on_char_typed_inner(file: &SourceFile, offset: TextSize, char_typed: char) -> Option<TextEdit> {
65 assert!(TRIGGER_CHARS.contains(char_typed));
67 '.' => on_dot_typed(file, offset),
68 '=' => on_eq_typed(file, offset),
69 '>' => on_arrow_typed(file, offset),
74 /// Returns an edit which should be applied after `=` was typed. Primarily,
75 /// this works when adding `let =`.
76 // FIXME: use a snippet completion instead of this hack here.
77 fn on_eq_typed(file: &SourceFile, offset: TextSize) -> Option<TextEdit> {
78 assert_eq!(file.syntax().text().char_at(offset), Some('='));
79 let let_stmt: ast::LetStmt = find_node_at_offset(file.syntax(), offset)?;
80 if let_stmt.semicolon_token().is_some() {
83 if let Some(expr) = let_stmt.initializer() {
84 let expr_range = expr.syntax().text_range();
85 if expr_range.contains(offset) && offset != expr_range.start() {
88 if file.syntax().text().slice(offset..expr_range.start()).contains_char('\n') {
94 let offset = let_stmt.syntax().text_range().end();
95 Some(TextEdit::insert(offset, ";".to_string()))
98 /// Returns an edit which should be applied when a dot ('.') is typed on a blank line, indenting the line appropriately.
99 fn on_dot_typed(file: &SourceFile, offset: TextSize) -> Option<TextEdit> {
100 assert_eq!(file.syntax().text().char_at(offset), Some('.'));
102 file.syntax().token_at_offset(offset).left_biased().and_then(ast::Whitespace::cast)?;
104 let current_indent = {
105 let text = whitespace.text();
106 let newline = text.rfind('\n')?;
109 let current_indent_len = TextSize::of(current_indent);
111 let parent = whitespace.syntax().parent()?;
112 // Make sure dot is a part of call chain
113 if !matches!(parent.kind(), FIELD_EXPR | METHOD_CALL_EXPR) {
116 let prev_indent = IndentLevel::from_node(&parent);
117 let target_indent = format!(" {}", prev_indent);
118 let target_indent_len = TextSize::of(&target_indent);
119 if current_indent_len == target_indent_len {
123 Some(TextEdit::replace(TextRange::new(offset - current_indent_len, offset), target_indent))
126 /// Adds a space after an arrow when `fn foo() { ... }` is turned into `fn foo() -> { ... }`
127 fn on_arrow_typed(file: &SourceFile, offset: TextSize) -> Option<TextEdit> {
128 let file_text = file.syntax().text();
129 assert_eq!(file_text.char_at(offset), Some('>'));
130 let after_arrow = offset + TextSize::of('>');
131 if file_text.char_at(after_arrow) != Some('{') {
134 if find_node_at_offset::<ast::RetType>(file.syntax(), offset).is_none() {
138 Some(TextEdit::insert(after_arrow, " ".to_string()))
143 use test_utils::{assert_eq_text, extract_offset};
147 fn do_type_char(char_typed: char, before: &str) -> Option<String> {
148 let (offset, mut before) = extract_offset(before);
149 let edit = TextEdit::insert(offset, char_typed.to_string());
150 edit.apply(&mut before);
151 let parse = SourceFile::parse(&before);
152 on_char_typed_inner(&parse.tree(), offset, char_typed).map(|it| {
153 it.apply(&mut before);
158 fn type_char(char_typed: char, ra_fixture_before: &str, ra_fixture_after: &str) {
159 let actual = do_type_char(char_typed, ra_fixture_before)
160 .unwrap_or_else(|| panic!("typing `{}` did nothing", char_typed));
162 assert_eq_text!(ra_fixture_after, &actual);
165 fn type_char_noop(char_typed: char, before: &str) {
166 let file_change = do_type_char(char_typed, before);
167 assert!(file_change.is_none())
171 fn test_on_eq_typed() {
208 fn indents_new_chain_call() {
236 fn indents_new_chain_call_with_semi() {
264 fn indents_new_chain_call_with_let() {
285 fn indents_continued_chain_call() {
316 fn indents_middle_of_chain_call() {
321 let var = enum_defvariant_list().unwrap()
329 let var = enum_defvariant_list().unwrap()
340 let var = enum_defvariant_list().unwrap()
350 fn dont_indent_freestanding_dot() {
370 fn adds_space_after_return_type() {
371 type_char('>', "fn foo() -$0{ 92 }", "fn foo() -> { 92 }")