diff --git a/crates/ra_analysis/src/lib.rs b/crates/ra_analysis/src/lib.rs index 77f77e9a8c94..c8f846c5685b 100644 --- a/crates/ra_analysis/src/lib.rs +++ b/crates/ra_analysis/src/lib.rs @@ -12,41 +12,39 @@ macro_rules! ctry { }; } -mod db; -mod imp; mod completion; +mod db; mod goto_defenition; -mod symbol_index; +mod imp; pub mod mock_analysis; mod runnables; +mod symbol_index; mod extend_selection; -mod syntax_highlighting; mod hover; +mod syntax_highlighting; use std::{fmt, sync::Arc}; -use rustc_hash::FxHashMap; -use ra_syntax::{SourceFileNode, TextRange, TextUnit, SmolStr, SyntaxKind}; +use ra_syntax::{SmolStr, SourceFileNode, SyntaxKind, TextRange, TextUnit}; use ra_text_edit::TextEdit; use rayon::prelude::*; use relative_path::RelativePathBuf; +use rustc_hash::FxHashMap; use salsa::ParallelDatabase; -use crate::symbol_index::{SymbolIndex, FileSymbol}; +use crate::symbol_index::{FileSymbol, SymbolIndex}; pub use crate::{ completion::{CompletionItem, CompletionItemKind, InsertText}, runnables::{Runnable, RunnableKind}, }; -pub use ra_editor::{ - Fold, FoldKind, HighlightedRange, LineIndex, StructureNode, Severity -}; pub use hir::FnSignatureInfo; +pub use ra_editor::{Fold, FoldKind, HighlightedRange, LineIndex, Severity, StructureNode}; pub use ra_db::{ - Canceled, Cancelable, FilePosition, FileRange, LocalSyntaxPtr, - CrateGraph, CrateId, SourceRootId, FileId, SyntaxDatabase, FilesDatabase + Cancelable, Canceled, CrateGraph, CrateId, FileId, FilePosition, FileRange, FilesDatabase, + LocalSyntaxPtr, SourceRootId, SyntaxDatabase, }; #[derive(Default)] @@ -346,7 +344,7 @@ impl Analysis { let edit = ra_editor::on_enter(&file, position.offset)?; Some(SourceChange::from_local_edit(position.file_id, edit)) } - /// Returns an edit which should be applied after `=` was typed. Primaraly, + /// Returns an edit which should be applied after `=` was typed. Primarily, /// this works when adding `let =`. // FIXME: use a snippet completion instead of this hack here. pub fn on_eq_typed(&self, position: FilePosition) -> Option { @@ -354,6 +352,12 @@ impl Analysis { let edit = ra_editor::on_eq_typed(&file, position.offset)?; Some(SourceChange::from_local_edit(position.file_id, edit)) } + /// Returns an edit which should be applied when a dot ('.') is typed on a blank line, indenting the line appropriately. + pub fn on_dot_typed(&self, position: FilePosition) -> Option { + let file = self.db.source_file(position.file_id); + let edit = ra_editor::on_dot_typed(&file, position.offset)?; + Some(SourceChange::from_local_edit(position.file_id, edit)) + } /// Returns a tree representation of symbols in the file. Useful to draw a /// file outline. pub fn file_structure(&self, file_id: FileId) -> Vec { diff --git a/crates/ra_editor/src/lib.rs b/crates/ra_editor/src/lib.rs index ac283e2e0990..a3c85ed5dad5 100644 --- a/crates/ra_editor/src/lib.rs +++ b/crates/ra_editor/src/lib.rs @@ -16,7 +16,7 @@ pub use self::{ line_index::{LineCol, LineIndex}, line_index_utils::translate_offset_with_edit, structure::{file_structure, StructureNode}, - typing::{join_lines, on_enter, on_eq_typed}, + typing::{join_lines, on_enter, on_dot_typed, on_eq_typed}, diagnostics::diagnostics }; use ra_text_edit::TextEditBuilder; diff --git a/crates/ra_editor/src/typing.rs b/crates/ra_editor/src/typing.rs index 1b568e96cddd..12500854c41e 100644 --- a/crates/ra_editor/src/typing.rs +++ b/crates/ra_editor/src/typing.rs @@ -1,17 +1,17 @@ use std::mem; +use itertools::Itertools; use ra_syntax::{ algo::{find_covering_node, find_leaf_at_offset, LeafAtOffset}, ast, text_utils::intersect, - AstNode, SourceFileNode, SyntaxKind, + AstNode, Direction, SourceFileNode, SyntaxKind, SyntaxKind::*, SyntaxNodeRef, TextRange, TextUnit, }; use ra_text_edit::text_utils::contains_offset_nonstrict; -use itertools::Itertools; -use crate::{find_node_at_offset, TextEditBuilder, LocalEdit}; +use crate::{find_node_at_offset, LocalEdit, TextEditBuilder}; pub fn join_lines(file: &SourceFileNode, range: TextRange) -> LocalEdit { let range = if range.is_empty() { @@ -136,6 +136,56 @@ pub fn on_eq_typed(file: &SourceFileNode, offset: TextUnit) -> Option }) } +pub fn on_dot_typed(file: &SourceFileNode, offset: TextUnit) -> Option { + let before_dot_offset = offset - TextUnit::of_char('.'); + + let whitespace = find_leaf_at_offset(file.syntax(), before_dot_offset).left_biased()?; + + // find whitespace just left of the dot + ast::Whitespace::cast(whitespace)?; + + // make sure there is a method call + let method_call = whitespace + .siblings(Direction::Prev) + // first is whitespace + .skip(1) + .next()?; + + ast::MethodCallExprNode::cast(method_call)?; + + // find how much the _method call is indented + let method_chain_indent = method_call + .parent()? + .siblings(Direction::Prev) + .skip(1) + .next()? + .leaf_text() + .map(|x| last_line_indent_in_whitespace(x))?; + + let current_indent = TextUnit::of_str(last_line_indent_in_whitespace(whitespace.leaf_text()?)); + // TODO: indent is always 4 spaces now. A better heuristic could look on the previous line(s) + + let target_indent = TextUnit::of_str(method_chain_indent) + TextUnit::from_usize(4); + + let diff = target_indent - current_indent; + + let indent = "".repeat(diff.to_usize()); + + let cursor_position = offset + diff; + let mut edit = TextEditBuilder::default(); + edit.insert(before_dot_offset, indent); + Some(LocalEdit { + label: "indent dot".to_string(), + edit: edit.finish(), + cursor_position: Some(cursor_position), + }) +} + +/// Finds the last line in the whitespace +fn last_line_indent_in_whitespace(ws: &str) -> &str { + ws.split('\n').last().unwrap_or("") +} + fn remove_newline( edit: &mut TextEditBuilder, node: SyntaxNodeRef, @@ -283,7 +333,9 @@ fn compute_ws(left: SyntaxNodeRef, right: SyntaxNodeRef) -> &'static str { #[cfg(test)] mod tests { use super::*; - use crate::test_utils::{add_cursor, check_action, extract_offset, extract_range, assert_eq_text}; + use crate::test_utils::{ + add_cursor, assert_eq_text, check_action, extract_offset, extract_range, +}; fn check_join_lines(before: &str, after: &str) { check_action(before, after, |file, offset| { @@ -614,6 +666,115 @@ fn foo() { // "); } + #[test] + fn test_on_dot_typed() { + fn do_check(before: &str, after: &str) { + let (offset, before) = extract_offset(before); + let file = SourceFileNode::parse(&before); + if let Some(result) = on_eq_typed(&file, offset) { + let actual = result.edit.apply(&before); + assert_eq_text!(after, &actual); + }; + } + // indent if continuing chain call + do_check( + r" + pub fn child(&self, db: &impl HirDatabase, name: &Name) -> Cancelable> { + self.child_impl(db, name) + .<|> + } +", + r" + pub fn child(&self, db: &impl HirDatabase, name: &Name) -> Cancelable> { + self.child_impl(db, name) + . + } +", + ); + + // do not indent if already indented + do_check( + r" + pub fn child(&self, db: &impl HirDatabase, name: &Name) -> Cancelable> { + self.child_impl(db, name) + .<|> + } +", + r" + pub fn child(&self, db: &impl HirDatabase, name: &Name) -> Cancelable> { + self.child_impl(db, name) + . + } +", + ); + + // indent if the previous line is already indented + do_check( + r" + pub fn child(&self, db: &impl HirDatabase, name: &Name) -> Cancelable> { + self.child_impl(db, name) + .first() + .<|> + } +", + r" + pub fn child(&self, db: &impl HirDatabase, name: &Name) -> Cancelable> { + self.child_impl(db, name) + .first() + . + } +", + ); + + // don't indent if indent matches previous line + do_check( + r" + pub fn child(&self, db: &impl HirDatabase, name: &Name) -> Cancelable> { + self.child_impl(db, name) + .first() + .<|> + } +", + r" + pub fn child(&self, db: &impl HirDatabase, name: &Name) -> Cancelable> { + self.child_impl(db, name) + .first() + . + } +", + ); + + // don't indent if there is no method call on previous line + do_check( + r" + pub fn child(&self, db: &impl HirDatabase, name: &Name) -> Cancelable> { + .<|> + } +", + r" + pub fn child(&self, db: &impl HirDatabase, name: &Name) -> Cancelable> { + . + } +", + ); + + // indent to match previous expr + do_check( + r" + pub fn child(&self, db: &impl HirDatabase, name: &Name) -> Cancelable> { + self.child_impl(db, name) +.<|> + } +", + r" + pub fn child(&self, db: &impl HirDatabase, name: &Name) -> Cancelable> { + self.child_impl(db, name) + . + } +", + ); + } + #[test] fn test_on_enter() { fn apply_on_enter(before: &str) -> Option { diff --git a/crates/ra_lsp_server/src/caps.rs b/crates/ra_lsp_server/src/caps.rs index a74f9f27b63f..2599a4ca6020 100644 --- a/crates/ra_lsp_server/src/caps.rs +++ b/crates/ra_lsp_server/src/caps.rs @@ -37,7 +37,7 @@ pub fn server_capabilities() -> ServerCapabilities { document_range_formatting_provider: None, document_on_type_formatting_provider: Some(DocumentOnTypeFormattingOptions { first_trigger_character: "=".to_string(), - more_trigger_character: None, + more_trigger_character: Some(vec![".".to_string()]), }), folding_range_provider: Some(FoldingRangeProviderCapability::Simple(true)), rename_provider: Some(RenameProviderCapability::Options(RenameOptions { diff --git a/crates/ra_lsp_server/src/main_loop.rs b/crates/ra_lsp_server/src/main_loop.rs index 60d9671dee7b..2dc1be26aac1 100644 --- a/crates/ra_lsp_server/src/main_loop.rs +++ b/crates/ra_lsp_server/src/main_loop.rs @@ -1,13 +1,11 @@ mod handlers; mod subscriptions; -use std::{ - fmt, - path::PathBuf, - sync::Arc, -}; +use std::{fmt, path::PathBuf, sync::Arc}; -use crossbeam_channel::{unbounded, select, Receiver, Sender, RecvError}; +use crossbeam_channel::{select, unbounded, Receiver, RecvError, Sender}; +use failure::{bail, format_err}; +use failure_derive::Fail; use gen_lsp_server::{ handle_shutdown, ErrorCode, RawMessage, RawNotification, RawRequest, RawResponse, }; @@ -15,11 +13,9 @@ use languageserver_types::NumberOrString; use ra_analysis::{Canceled, FileId, LibraryData}; use ra_vfs::VfsTask; use rayon; -use threadpool::ThreadPool; use rustc_hash::FxHashSet; use serde::{de::DeserializeOwned, Serialize}; -use failure::{format_err, bail}; -use failure_derive::Fail; +use threadpool::ThreadPool; use crate::{ main_loop::subscriptions::Subscriptions, diff --git a/crates/ra_lsp_server/src/main_loop/handlers.rs b/crates/ra_lsp_server/src/main_loop/handlers.rs index 1baed73ade86..51f134e8a408 100644 --- a/crates/ra_lsp_server/src/main_loop/handlers.rs +++ b/crates/ra_lsp_server/src/main_loop/handlers.rs @@ -2,15 +2,16 @@ use std::collections::HashMap; use gen_lsp_server::ErrorCode; use languageserver_types::{ - CodeActionResponse, Command, Diagnostic, - DiagnosticSeverity, DocumentSymbol, Documentation, FoldingRange, FoldingRangeKind, - FoldingRangeParams, Location, MarkupContent, MarkupKind, MarkedString, Position, - PrepareRenameResponse, RenameParams, SymbolInformation, TextDocumentIdentifier, TextEdit, - Range, WorkspaceEdit, ParameterInformation, ParameterLabel, SignatureInformation, Hover, - HoverContents, DocumentFormattingParams, DocumentHighlight, + CodeActionResponse, Command, Diagnostic, DiagnosticSeverity, DocumentFormattingParams, + DocumentHighlight, DocumentSymbol, Documentation, FoldingRange, FoldingRangeKind, + FoldingRangeParams, Hover, HoverContents, Location, MarkedString, MarkupContent, MarkupKind, + ParameterInformation, ParameterLabel, Position, PrepareRenameResponse, Range, RenameParams, + SignatureInformation, SymbolInformation, TextDocumentIdentifier, TextEdit, WorkspaceEdit, }; -use ra_analysis::{FileId, FoldKind, Query, RunnableKind, FileRange, FilePosition, Severity}; -use ra_syntax::{TextUnit, text_utils::intersect}; +use ra_analysis::{ + FileId, FilePosition, FileRange, FoldKind, Query, RunnableKind, Severity, SourceChange, +}; +use ra_syntax::{text_utils::intersect, TextUnit}; use ra_text_edit::text_utils::contains_offset_nonstrict; use rustc_hash::FxHashMap; use serde_json::to_value; @@ -92,29 +93,35 @@ pub fn handle_on_type_formatting( world: ServerWorld, params: req::DocumentOnTypeFormattingParams, ) -> Result>> { - if params.ch != "=" { - return Ok(None); + let analysis: Option Option>> = match params.ch.as_str() { + "=" => Some(Box::new(|pos| world.analysis().on_eq_typed(pos))), + "." => Some(Box::new(|pos| world.analysis().on_dot_typed(pos))), + _ => None, + }; + + if let Some(ana) = analysis { + let file_id = params.text_document.try_conv_with(&world)?; + let line_index = world.analysis().file_line_index(file_id); + let position = FilePosition { + file_id, + offset: params.position.conv_with(&line_index), + }; + + if let Some(mut action) = ana(position) { + let change: Vec = action + .source_file_edits + .pop() + .unwrap() + .edit + .as_atoms() + .iter() + .map_conv_with(&line_index) + .collect(); + return Ok(Some(change)); + } } - let file_id = params.text_document.try_conv_with(&world)?; - let line_index = world.analysis().file_line_index(file_id); - let position = FilePosition { - file_id, - offset: params.position.conv_with(&line_index), - }; - let edits = match world.analysis().on_eq_typed(position) { - None => return Ok(None), - Some(mut action) => action - .source_file_edits - .pop() - .unwrap() - .edit - .as_atoms() - .iter() - .map_conv_with(&line_index) - .collect(), - }; - Ok(Some(edits)) + return Ok(None); } pub fn handle_document_symbol(