From 29c34213916f8be84d5c715899e5e0629e36adac Mon Sep 17 00:00:00 2001 From: Josh Stone Date: Wed, 16 Sep 2020 10:05:41 -0700 Subject: Don't return any TextEdit if formatting is unchanged I found that `textDocument/formatting` was always returning a full `TextEdit` replacement, even when there are no changes, which caused Vim (w/ vim-lsp) to always indicate a modified buffer after formatting. We can easily compare whether there were changes and return `null` if not, so the client knows there's nothing to do. --- crates/rust-analyzer/src/handlers.rs | 13 ++++++--- crates/rust-analyzer/tests/rust-analyzer/main.rs | 36 ++++++++++++++++++++++++ 2 files changed, 45 insertions(+), 4 deletions(-) (limited to 'crates') diff --git a/crates/rust-analyzer/src/handlers.rs b/crates/rust-analyzer/src/handlers.rs index 64cb4d96c..c0943a54d 100644 --- a/crates/rust-analyzer/src/handlers.rs +++ b/crates/rust-analyzer/src/handlers.rs @@ -748,10 +748,15 @@ pub(crate) fn handle_formatting( } } - Ok(Some(vec![lsp_types::TextEdit { - range: Range::new(Position::new(0, 0), end_position), - new_text: captured_stdout, - }])) + if *file == captured_stdout { + // The document is already formatted correctly -- no edits needed. + Ok(None) + } else { + Ok(Some(vec![lsp_types::TextEdit { + range: Range::new(Position::new(0, 0), end_position), + new_text: captured_stdout, + }])) + } } fn handle_fixes( diff --git a/crates/rust-analyzer/tests/rust-analyzer/main.rs b/crates/rust-analyzer/tests/rust-analyzer/main.rs index 0880d0425..06726f957 100644 --- a/crates/rust-analyzer/tests/rust-analyzer/main.rs +++ b/crates/rust-analyzer/tests/rust-analyzer/main.rs @@ -259,6 +259,42 @@ pub use std::collections::HashMap; ); } +#[test] +fn test_format_document_unchanged() { + if skip_slow_tests() { + return; + } + + let server = project( + r#" +//- /Cargo.toml +[package] +name = "foo" +version = "0.0.0" + +//- /src/lib.rs +fn main() {} +"#, + ) + .wait_until_workspace_is_loaded(); + + server.request::( + DocumentFormattingParams { + text_document: server.doc_id("src/lib.rs"), + options: FormattingOptions { + tab_size: 4, + insert_spaces: false, + insert_final_newline: None, + trim_final_newlines: None, + trim_trailing_whitespace: None, + properties: HashMap::new(), + }, + work_done_progress_params: WorkDoneProgressParams::default(), + }, + json!(null), + ); +} + #[test] fn test_missing_module_code_action() { if skip_slow_tests() { -- cgit v1.2.3