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,
53 // image::https://user-images.githubusercontent.com/48062697/113166163-69758500-923a-11eb-81ee-eb33ec380399.gif[]
54 // image::https://user-images.githubusercontent.com/48062697/113171066-105c2000-923f-11eb-87ab-f4a263346567.gif[]
55 pub(crate) fn on_char_typed(
57 position: FilePosition,
59 ) -> Option<SourceChange> {
60 assert!(TRIGGER_CHARS.contains(char_typed));
61 let file = &db.parse(position.file_id).tree();
62 assert_eq!(file.syntax().text().char_at(position.offset), Some(char_typed));
63 let edit = on_char_typed_inner(file, position.offset, char_typed)?;
64 Some(SourceChange::from_text_edit(position.file_id, edit))
67 fn on_char_typed_inner(file: &SourceFile, offset: TextSize, char_typed: char) -> Option<TextEdit> {
68 assert!(TRIGGER_CHARS.contains(char_typed));
70 '.' => on_dot_typed(file, offset),
71 '=' => on_eq_typed(file, offset),
72 '>' => on_arrow_typed(file, offset),
77 /// Returns an edit which should be applied after `=` was typed. Primarily,
78 /// this works when adding `let =`.
79 // FIXME: use a snippet completion instead of this hack here.
80 fn on_eq_typed(file: &SourceFile, offset: TextSize) -> Option<TextEdit> {
81 assert_eq!(file.syntax().text().char_at(offset), Some('='));
82 let let_stmt: ast::LetStmt = find_node_at_offset(file.syntax(), offset)?;
83 if let_stmt.semicolon_token().is_some() {
86 if let Some(expr) = let_stmt.initializer() {
87 let expr_range = expr.syntax().text_range();
88 if expr_range.contains(offset) && offset != expr_range.start() {
91 if file.syntax().text().slice(offset..expr_range.start()).contains_char('\n') {
97 let offset = let_stmt.syntax().text_range().end();
98 Some(TextEdit::insert(offset, ";".to_string()))
101 /// Returns an edit which should be applied when a dot ('.') is typed on a blank line, indenting the line appropriately.
102 fn on_dot_typed(file: &SourceFile, offset: TextSize) -> Option<TextEdit> {
103 assert_eq!(file.syntax().text().char_at(offset), Some('.'));
105 file.syntax().token_at_offset(offset).left_biased().and_then(ast::Whitespace::cast)?;
107 let current_indent = {
108 let text = whitespace.text();
109 let newline = text.rfind('\n')?;
112 let current_indent_len = TextSize::of(current_indent);
114 let parent = whitespace.syntax().parent()?;
115 // Make sure dot is a part of call chain
116 if !matches!(parent.kind(), FIELD_EXPR | METHOD_CALL_EXPR) {
119 let prev_indent = IndentLevel::from_node(&parent);
120 let target_indent = format!(" {}", prev_indent);
121 let target_indent_len = TextSize::of(&target_indent);
122 if current_indent_len == target_indent_len {
126 Some(TextEdit::replace(TextRange::new(offset - current_indent_len, offset), target_indent))
129 /// Adds a space after an arrow when `fn foo() { ... }` is turned into `fn foo() -> { ... }`
130 fn on_arrow_typed(file: &SourceFile, offset: TextSize) -> Option<TextEdit> {
131 let file_text = file.syntax().text();
132 assert_eq!(file_text.char_at(offset), Some('>'));
133 let after_arrow = offset + TextSize::of('>');
134 if file_text.char_at(after_arrow) != Some('{') {
137 if find_node_at_offset::<ast::RetType>(file.syntax(), offset).is_none() {
141 Some(TextEdit::insert(after_arrow, " ".to_string()))
146 use test_utils::{assert_eq_text, extract_offset};
150 fn do_type_char(char_typed: char, before: &str) -> Option<String> {
151 let (offset, mut before) = extract_offset(before);
152 let edit = TextEdit::insert(offset, char_typed.to_string());
153 edit.apply(&mut before);
154 let parse = SourceFile::parse(&before);
155 on_char_typed_inner(&parse.tree(), offset, char_typed).map(|it| {
156 it.apply(&mut before);
161 fn type_char(char_typed: char, ra_fixture_before: &str, ra_fixture_after: &str) {
162 let actual = do_type_char(char_typed, ra_fixture_before)
163 .unwrap_or_else(|| panic!("typing `{}` did nothing", char_typed));
165 assert_eq_text!(ra_fixture_after, &actual);
168 fn type_char_noop(char_typed: char, before: &str) {
169 let file_change = do_type_char(char_typed, before);
170 assert!(file_change.is_none())
174 fn test_on_eq_typed() {
211 fn indents_new_chain_call() {
239 fn indents_new_chain_call_with_semi() {
267 fn indents_new_chain_call_with_let() {
288 fn indents_continued_chain_call() {
319 fn indents_middle_of_chain_call() {
324 let var = enum_defvariant_list().unwrap()
332 let var = enum_defvariant_list().unwrap()
343 let var = enum_defvariant_list().unwrap()
353 fn dont_indent_freestanding_dot() {
373 fn adds_space_after_return_type() {
374 type_char('>', "fn foo() -$0{ 92 }", "fn foo() -> { 92 }")