Unnamed repository; edit this file 'description' to name the repository.
Diffstat (limited to 'helix-lsp/src/client.rs')
| -rw-r--r-- | helix-lsp/src/client.rs | 609 |
1 files changed, 277 insertions, 332 deletions
diff --git a/helix-lsp/src/client.rs b/helix-lsp/src/client.rs index 22a8dd89..f3f7e279 100644 --- a/helix-lsp/src/client.rs +++ b/helix-lsp/src/client.rs @@ -1,31 +1,29 @@ use crate::{ - file_operations::FileOperationsInterest, + config::LanguageServerConfig, find_lsp_workspace, jsonrpc, transport::{Payload, Transport}, - Call, Error, LanguageServerId, OffsetEncoding, Result, + Call, Error, OffsetEncoding, Result, }; -use crate::lsp::{ - self, notification::DidChangeWorkspaceFolders, CodeActionCapabilityResolveSupport, - DidChangeWorkspaceFoldersParams, OneOf, PositionEncodingKind, SignatureHelp, Url, - WorkspaceFolder, WorkspaceFoldersChangeEvent, +use anyhow::Context; +use helix_config::{self as config, OptionManager}; +use helix_core::{find_workspace, path, syntax::LanguageServerFeature, ChangeSet, Rope}; +use helix_loader::{self, VERSION_AND_GIT_HASH}; +use lsp::{ + notification::DidChangeWorkspaceFolders, CodeActionCapabilityResolveSupport, + DidChangeWorkspaceFoldersParams, OneOf, PositionEncodingKind, WorkspaceFolder, + WorkspaceFoldersChangeEvent, }; -use helix_core::{find_workspace, syntax::config::LanguageServerFeature, ChangeSet, Rope}; -use helix_loader::VERSION_AND_GIT_HASH; -use helix_stdx::path; +use lsp_types as lsp; use parking_lot::Mutex; -use serde::Deserialize; use serde_json::Value; -use std::{collections::HashMap, path::PathBuf}; -use std::{ - ffi::OsStr, - sync::{ - atomic::{AtomicU64, Ordering}, - Arc, - }, +use std::future::Future; +use std::path::PathBuf; +use std::process::Stdio; +use std::sync::{ + atomic::{AtomicU64, Ordering}, + Arc, }; -use std::{future::Future, sync::OnceLock}; -use std::{path::Path, process::Stdio}; use tokio::{ io::{BufReader, BufWriter}, process::{Child, Command}, @@ -39,7 +37,7 @@ fn workspace_for_uri(uri: lsp::Url) -> WorkspaceFolder { lsp::WorkspaceFolder { name: uri .path_segments() - .and_then(|mut segments| segments.next_back()) + .and_then(|segments| segments.last()) .map(|basename| basename.to_string()) .unwrap_or_default(), uri, @@ -48,20 +46,17 @@ fn workspace_for_uri(uri: lsp::Url) -> WorkspaceFolder { #[derive(Debug)] pub struct Client { - id: LanguageServerId, + id: usize, name: String, _process: Child, server_tx: UnboundedSender<Payload>, request_counter: AtomicU64, pub(crate) capabilities: OnceCell<lsp::ServerCapabilities>, - pub(crate) file_operation_interest: OnceLock<FileOperationsInterest>, - config: Option<Value>, root_path: std::path::PathBuf, root_uri: Option<lsp::Url>, workspace_folders: Mutex<Vec<lsp::WorkspaceFolder>>, initialize_notify: Arc<Notify>, - /// workspace folders added while the server is still initializing - req_timeout: u64, + config: Arc<OptionManager>, } impl Client { @@ -73,7 +68,7 @@ impl Client { may_support_workspace: bool, ) -> bool { let (workspace, workspace_is_cwd) = find_workspace(); - let workspace = path::normalize(workspace); + let workspace = path::get_normalized_path(&workspace); let root = find_lsp_workspace( doc_path .and_then(|x| x.parent().and_then(|x| x.to_str())) @@ -88,7 +83,7 @@ impl Client { .and_then(|root| lsp::Url::from_file_path(root).ok()); if self.root_path == root.unwrap_or(workspace) - || root_uri.as_ref().is_some_and(|root_uri| { + || root_uri.as_ref().map_or(false, |root_uri| { self.workspace_folders .lock() .iter() @@ -125,7 +120,7 @@ impl Client { { client.add_workspace_folder( root_uri, - workspace_folders_caps.change_notifications.as_ref(), + &workspace_folders_caps.change_notifications, ); } }); @@ -138,10 +133,7 @@ impl Client { .and_then(|cap| cap.workspace_folders.as_ref()) .filter(|cap| cap.supported.unwrap_or(false)) { - self.add_workspace_folder( - root_uri, - workspace_folders_caps.change_notifications.as_ref(), - ); + self.add_workspace_folder(root_uri, &workspace_folders_caps.change_notifications); true } else { // the server doesn't support multi workspaces, we need a new client @@ -152,7 +144,7 @@ impl Client { fn add_workspace_folder( &self, root_uri: Option<lsp::Url>, - change_notifications: Option<&OneOf<bool, String>>, + change_notifications: &Option<OneOf<bool, String>>, ) { // root_uri is None just means that there isn't really any LSP workspace // associated with this file. For servers that support multiple workspaces @@ -167,64 +159,34 @@ impl Client { self.workspace_folders .lock() .push(workspace_for_uri(root_uri.clone())); - if Some(&OneOf::Left(false)) == change_notifications { + if &Some(OneOf::Left(false)) == change_notifications { // server specifically opted out of DidWorkspaceChange notifications // let's assume the server will request the workspace folders itself // and that we can therefore reuse the client (but are done now) return; } - self.did_change_workspace(vec![workspace_for_uri(root_uri)], Vec::new()) - } - - /// Merge FormattingOptions with 'config.format' and return it - fn get_merged_formatting_options( - &self, - options: lsp::FormattingOptions, - ) -> lsp::FormattingOptions { - let config_format = self - .config - .as_ref() - .and_then(|cfg| cfg.get("format")) - .and_then(|fmt| HashMap::<String, lsp::FormattingProperty>::deserialize(fmt).ok()); - - if let Some(mut properties) = config_format { - // passed in options take precedence over 'config.format' - properties.extend(options.properties); - lsp::FormattingOptions { - properties, - ..options - } - } else { - options - } + tokio::spawn(self.did_change_workspace(vec![workspace_for_uri(root_uri)], Vec::new())); } #[allow(clippy::type_complexity, clippy::too_many_arguments)] pub fn start( - cmd: &str, - args: &[String], - config: Option<Value>, - server_environment: impl IntoIterator<Item = (impl AsRef<OsStr>, impl AsRef<OsStr>)>, - root_path: PathBuf, - root_uri: Option<lsp::Url>, - id: LanguageServerId, + config: Arc<OptionManager>, + root_markers: &[String], + manual_roots: &[PathBuf], + id: usize, name: String, - req_timeout: u64, - ) -> Result<( - Self, - UnboundedReceiver<(LanguageServerId, Call)>, - Arc<Notify>, - )> { + doc_path: Option<&std::path::PathBuf>, + ) -> Result<(Self, UnboundedReceiver<(usize, Call)>, Arc<Notify>)> { // Resolve path to the binary - let cmd = helix_stdx::env::which(cmd)?; + let cmd = which::which(config.command().as_deref().context("no command defined")?) + .map_err(|err| anyhow::anyhow!(err))?; let process = Command::new(cmd) - .envs(server_environment) - .args(args) + .envs(config.enviorment().iter().map(|(k, v)| (&**k, &**v))) + .args(config.args().iter().map(|v| &**v)) .stdin(Stdio::piped()) .stdout(Stdio::piped()) .stderr(Stdio::piped()) - .current_dir(&root_path) // make sure the process is reaped on drop .kill_on_drop(true) .spawn(); @@ -238,6 +200,22 @@ impl Client { let (server_rx, server_tx, initialize_notify) = Transport::start(reader, writer, stderr, id, name.clone()); + let (workspace, workspace_is_cwd) = find_workspace(); + let workspace = path::get_normalized_path(&workspace); + let root = find_lsp_workspace( + doc_path + .and_then(|x| x.parent().and_then(|x| x.to_str())) + .unwrap_or("."), + root_markers, + manual_roots, + &workspace, + workspace_is_cwd, + ); + + // `root_uri` and `workspace_folder` can be empty in case there is no workspace + // `root_url` can not, use `workspace` as a fallback + let root_path = root.clone().unwrap_or_else(|| workspace.clone()); + let root_uri = root.and_then(|root| lsp::Url::from_file_path(root).ok()); let workspace_folders = root_uri .clone() @@ -251,9 +229,7 @@ impl Client { server_tx, request_counter: AtomicU64::new(0), capabilities: OnceCell::new(), - file_operation_interest: OnceLock::new(), config, - req_timeout, root_path, root_uri, workspace_folders: Mutex::new(workspace_folders), @@ -267,7 +243,7 @@ impl Client { &self.name } - pub fn id(&self) -> LanguageServerId { + pub fn id(&self) -> usize { self.id } @@ -297,11 +273,6 @@ impl Client { .expect("language server not yet initialized!") } - pub(crate) fn file_operations_intests(&self) -> &FileOperationsInterest { - self.file_operation_interest - .get_or_init(|| FileOperationsInterest::new(self.capabilities())) - } - /// Client has to be initialized otherwise this function panics #[inline] pub fn supports_feature(&self, feature: LanguageServerFeature) -> bool { @@ -372,7 +343,6 @@ impl Client { Some(OneOf::Left(true) | OneOf::Right(_)) ), LanguageServerFeature::Diagnostics => true, // there's no extra server capability - LanguageServerFeature::PullDiagnostics => capabilities.diagnostic_provider.is_some(), LanguageServerFeature::RenameSymbol => matches!( capabilities.rename_provider, Some(OneOf::Left(true)) | Some(OneOf::Right(_)) @@ -381,14 +351,6 @@ impl Client { capabilities.inlay_hint_provider, Some(OneOf::Left(true) | OneOf::Right(InlayHintServerCapabilities::Options(_))) ), - LanguageServerFeature::DocumentColors => matches!( - capabilities.color_provider, - Some( - ColorProviderCapability::Simple(true) - | ColorProviderCapability::ColorProvider(_) - | ColorProviderCapability::Options(_) - ) - ), } } @@ -408,8 +370,8 @@ impl Client { .unwrap_or_default() } - pub fn config(&self) -> Option<&Value> { - self.config.as_ref() + pub fn config(&self) -> config::Guard<Option<Box<Value>>> { + self.config.server_config() } pub async fn workspace_folders( @@ -419,101 +381,93 @@ impl Client { } /// Execute a RPC request on the language server. - fn call<R: lsp::request::Request>( - &self, - params: R::Params, - ) -> impl Future<Output = Result<R::Result>> + async fn request<R: lsp::request::Request>(&self, params: R::Params) -> Result<R::Result> where R::Params: serde::Serialize, + R::Result: core::fmt::Debug, // TODO: temporary { - self.call_with_ref::<R>(¶ms) + // a future that resolves into the response + let json = self.call::<R>(params).await?; + let response = serde_json::from_value(json)?; + Ok(response) } - fn call_with_ref<R: lsp::request::Request>( + /// Execute a RPC request on the language server. + fn call<R: lsp::request::Request>( &self, - params: &R::Params, - ) -> impl Future<Output = Result<R::Result>> + params: R::Params, + ) -> impl Future<Output = Result<Value>> where R::Params: serde::Serialize, { - self.call_with_timeout::<R>(params, self.req_timeout) + self.call_with_timeout::<R>(params, self.config.timeout()) } fn call_with_timeout<R: lsp::request::Request>( &self, - params: &R::Params, + params: R::Params, timeout_secs: u64, - ) -> impl Future<Output = Result<R::Result>> + ) -> impl Future<Output = Result<Value>> where R::Params: serde::Serialize, { let server_tx = self.server_tx.clone(); let id = self.next_request_id(); - // It's important that this is not part of the future so that it gets executed right away - // and the request order stays consistent. - let rx = serde_json::to_value(params) - .map_err(Error::from) - .and_then(|params| { - let request = jsonrpc::MethodCall { - jsonrpc: Some(jsonrpc::Version::V2), - id: id.clone(), - method: R::METHOD.to_string(), - params: Self::value_into_params(params), - }; - let (tx, rx) = channel::<Result<Value>>(1); - server_tx - .send(Payload::Request { - chan: tx, - value: request, - }) - .map_err(|e| Error::Other(e.into()))?; - Ok(rx) - }); - async move { use std::time::Duration; use tokio::time::timeout; + + let params = serde_json::to_value(params)?; + + let request = jsonrpc::MethodCall { + jsonrpc: Some(jsonrpc::Version::V2), + id: id.clone(), + method: R::METHOD.to_string(), + params: Self::value_into_params(params), + }; + + let (tx, mut rx) = channel::<Result<Value>>(1); + + server_tx + .send(Payload::Request { + chan: tx, + value: request, + }) + .map_err(|e| Error::Other(e.into()))?; + // TODO: delay other calls until initialize success - timeout(Duration::from_secs(timeout_secs), rx?.recv()) + timeout(Duration::from_secs(timeout_secs), rx.recv()) .await .map_err(|_| Error::Timeout(id))? // return Timeout .ok_or(Error::StreamClosed)? - .and_then(|value| serde_json::from_value(value).map_err(Into::into)) } } /// Send a RPC notification to the language server. - pub fn notify<R: lsp::notification::Notification>(&self, params: R::Params) + pub fn notify<R: lsp::notification::Notification>( + &self, + params: R::Params, + ) -> impl Future<Output = Result<()>> where R::Params: serde::Serialize, { let server_tx = self.server_tx.clone(); - let params = match serde_json::to_value(params) { - Ok(params) => params, - Err(err) => { - log::error!( - "Failed to serialize params for notification '{}' for server '{}': {err}", - R::METHOD, - self.name, - ); - return; - } - }; + async move { + let params = serde_json::to_value(params)?; - let notification = jsonrpc::Notification { - jsonrpc: Some(jsonrpc::Version::V2), - method: R::METHOD.to_string(), - params: Self::value_into_params(params), - }; + let notification = jsonrpc::Notification { + jsonrpc: Some(jsonrpc::Version::V2), + method: R::METHOD.to_string(), + params: Self::value_into_params(params), + }; + + server_tx + .send(Payload::Notification(notification)) + .map_err(|e| Error::Other(e.into()))?; - if let Err(err) = server_tx.send(Payload::Notification(notification)) { - log::error!( - "Failed to send notification '{}' to server '{}': {err}", - R::METHOD, - self.name - ); + Ok(()) } } @@ -522,29 +476,31 @@ impl Client { &self, id: jsonrpc::Id, result: core::result::Result<Value, jsonrpc::Error>, - ) -> Result<()> { + ) -> impl Future<Output = Result<()>> { use jsonrpc::{Failure, Output, Success, Version}; let server_tx = self.server_tx.clone(); - let output = match result { - Ok(result) => Output::Success(Success { - jsonrpc: Some(Version::V2), - id, - result, - }), - Err(error) => Output::Failure(Failure { - jsonrpc: Some(Version::V2), - id, - error, - }), - }; + async move { + let output = match result { + Ok(result) => Output::Success(Success { + jsonrpc: Some(Version::V2), + id, + result: serde_json::to_value(result)?, + }), + Err(error) => Output::Failure(Failure { + jsonrpc: Some(Version::V2), + id, + error, + }), + }; - server_tx - .send(Payload::Response(output)) - .map_err(|e| Error::Other(e.into()))?; + server_tx + .send(Payload::Response(output)) + .map_err(|e| Error::Other(e.into()))?; - Ok(()) + Ok(()) + } } // ------------------------------------------------------------------------------------------- @@ -552,7 +508,7 @@ impl Client { // ------------------------------------------------------------------------------------------- pub(crate) async fn initialize(&self, enable_snippets: bool) -> Result<lsp::InitializeResult> { - if let Some(config) = &self.config { + if let Some(config) = &*self.config() { log::info!("Using custom LSP config: {}", config); } @@ -564,7 +520,7 @@ impl Client { // clients will prefer _uri if possible root_path: self.root_path.to_str().map(|path| path.to_owned()), root_uri: self.root_uri.clone(), - initialization_options: self.config.clone(), + initialization_options: self.config().as_deref().cloned(), capabilities: lsp::ClientCapabilities { workspace: Some(lsp::WorkspaceClientCapabilities { configuration: Some(true), @@ -603,9 +559,6 @@ impl Client { did_rename: Some(true), ..Default::default() }), - diagnostic: Some(lsp::DiagnosticWorkspaceClientCapabilities { - refresh_support: Some(true), - }), ..Default::default() }), text_document: Some(lsp::TextDocumentClientCapabilities { @@ -654,9 +607,6 @@ impl Client { prepare_support_default_behavior: None, honors_change_annotations: Some(false), }), - formatting: Some(lsp::DocumentFormattingClientCapabilities { - dynamic_registration: Some(false), - }), code_action: Some(lsp::CodeActionClientCapabilities { code_action_literal_support: Some(lsp::CodeActionLiteralSupport { code_action_kind: lsp::CodeActionKindLiteralSupport { @@ -683,18 +633,8 @@ impl Client { }), ..Default::default() }), - diagnostic: Some(lsp::DiagnosticClientCapabilities { - dynamic_registration: Some(false), - related_document_support: Some(true), - }), publish_diagnostics: Some(lsp::PublishDiagnosticsClientCapabilities { version_support: Some(true), - tag_support: Some(lsp::TagSupport { - value_set: vec![ - lsp::DiagnosticTag::UNNECESSARY, - lsp::DiagnosticTag::DEPRECATED, - ], - }), ..Default::default() }), inlay_hint: Some(lsp::InlayHintClientCapabilities { @@ -726,14 +666,14 @@ impl Client { work_done_progress_params: lsp::WorkDoneProgressParams::default(), }; - self.call::<lsp::request::Initialize>(params).await + self.request::<lsp::request::Initialize>(params).await } pub async fn shutdown(&self) -> Result<()> { - self.call::<lsp::request::Shutdown>(()).await + self.request::<lsp::request::Shutdown>(()).await } - pub fn exit(&self) { + pub fn exit(&self) -> impl Future<Output = Result<()>> { self.notify::<lsp::notification::Exit>(()) } @@ -741,8 +681,7 @@ impl Client { /// early if server responds with an error. pub async fn shutdown_and_exit(&self) -> Result<()> { self.shutdown().await?; - self.exit(); - Ok(()) + self.exit().await } /// Forcefully shuts down the language server ignoring any errors. @@ -750,74 +689,86 @@ impl Client { if let Err(e) = self.shutdown().await { log::warn!("language server failed to terminate gracefully - {}", e); } - self.exit(); - Ok(()) + self.exit().await } // ------------------------------------------------------------------------------------------- // Workspace // ------------------------------------------------------------------------------------------- - pub fn did_change_configuration(&self, settings: Value) { + pub fn did_change_configuration(&self, settings: Value) -> impl Future<Output = Result<()>> { self.notify::<lsp::notification::DidChangeConfiguration>( lsp::DidChangeConfigurationParams { settings }, ) } - pub fn did_change_workspace(&self, added: Vec<WorkspaceFolder>, removed: Vec<WorkspaceFolder>) { + pub fn did_change_workspace( + &self, + added: Vec<WorkspaceFolder>, + removed: Vec<WorkspaceFolder>, + ) -> impl Future<Output = Result<()>> { self.notify::<DidChangeWorkspaceFolders>(DidChangeWorkspaceFoldersParams { event: WorkspaceFoldersChangeEvent { added, removed }, }) } - pub fn will_rename( + pub fn prepare_file_rename( &self, - old_path: &Path, - new_path: &Path, - is_dir: bool, - ) -> Option<impl Future<Output = Result<Option<lsp::WorkspaceEdit>>>> { - let capabilities = self.file_operations_intests(); - if !capabilities.will_rename.has_interest(old_path, is_dir) { - return None; + old_uri: &lsp::Url, + new_uri: &lsp::Url, + ) -> Option<impl Future<Output = Result<lsp::WorkspaceEdit>>> { + let capabilities = self.capabilities.get().unwrap(); + + // Return early if the server does not support willRename feature + match &capabilities.workspace { + Some(workspace) => match &workspace.file_operations { + Some(op) => { + op.will_rename.as_ref()?; + } + _ => return None, + }, + _ => return None, } - let url_from_path = |path| { - let url = if is_dir { - Url::from_directory_path(path) - } else { - Url::from_file_path(path) - }; - Some(url.ok()?.to_string()) - }; + let files = vec![lsp::FileRename { - old_uri: url_from_path(old_path)?, - new_uri: url_from_path(new_path)?, + old_uri: old_uri.to_string(), + new_uri: new_uri.to_string(), }]; - Some(self.call_with_timeout::<lsp::request::WillRenameFiles>( - &lsp::RenameFilesParams { files }, + let request = self.call_with_timeout::<lsp::request::WillRenameFiles>( + lsp::RenameFilesParams { files }, 5, - )) + ); + + Some(async move { + let json = request.await?; + let response: Option<lsp::WorkspaceEdit> = serde_json::from_value(json)?; + Ok(response.unwrap_or_default()) + }) } - pub fn did_rename(&self, old_path: &Path, new_path: &Path, is_dir: bool) -> Option<()> { - let capabilities = self.file_operations_intests(); - if !capabilities.did_rename.has_interest(new_path, is_dir) { - return None; + pub fn did_file_rename( + &self, + old_uri: &lsp::Url, + new_uri: &lsp::Url, + ) -> Option<impl Future<Output = std::result::Result<(), Error>>> { + let capabilities = self.capabilities.get().unwrap(); + + // Return early if the server does not support DidRename feature + match &capabilities.workspace { + Some(workspace) => match &workspace.file_operations { + Some(op) => { + op.did_rename.as_ref()?; + } + _ => return None, + }, + _ => return None, } - let url_from_path = |path| { - let url = if is_dir { - Url::from_directory_path(path) - } else { - Url::from_file_path(path) - }; - Some(url.ok()?.to_string()) - }; let files = vec![lsp::FileRename { - old_uri: url_from_path(old_path)?, - new_uri: url_from_path(new_path)?, + old_uri: old_uri.to_string(), + new_uri: new_uri.to_string(), }]; - self.notify::<lsp::notification::DidRenameFiles>(lsp::RenameFilesParams { files }); - Some(()) + Some(self.notify::<lsp::notification::DidRenameFiles>(lsp::RenameFilesParams { files })) } // ------------------------------------------------------------------------------------------- @@ -830,7 +781,7 @@ impl Client { version: i32, doc: &Rope, language_id: String, - ) { + ) -> impl Future<Output = Result<()>> { self.notify::<lsp::notification::DidOpenTextDocument>(lsp::DidOpenTextDocumentParams { text_document: lsp::TextDocumentItem { uri, @@ -957,7 +908,7 @@ impl Client { old_text: &Rope, new_text: &Rope, changes: &ChangeSet, - ) -> Option<()> { + ) -> Option<impl Future<Output = Result<()>>> { let capabilities = self.capabilities.get().unwrap(); // Return early if the server does not support document sync. @@ -989,14 +940,18 @@ impl Client { kind => unimplemented!("{:?}", kind), }; - self.notify::<lsp::notification::DidChangeTextDocument>(lsp::DidChangeTextDocumentParams { - text_document, - content_changes: changes, - }); - Some(()) + Some(self.notify::<lsp::notification::DidChangeTextDocument>( + lsp::DidChangeTextDocumentParams { + text_document, + content_changes: changes, + }, + )) } - pub fn text_document_did_close(&self, text_document: lsp::TextDocumentIdentifier) { + pub fn text_document_did_close( + &self, + text_document: lsp::TextDocumentIdentifier, + ) -> impl Future<Output = Result<()>> { self.notify::<lsp::notification::DidCloseTextDocument>(lsp::DidCloseTextDocumentParams { text_document, }) @@ -1008,7 +963,7 @@ impl Client { &self, text_document: lsp::TextDocumentIdentifier, text: &Rope, - ) -> Option<()> { + ) -> Option<impl Future<Output = Result<()>>> { let capabilities = self.capabilities.get().unwrap(); let include_text = match &capabilities.text_document_sync.as_ref()? { @@ -1017,7 +972,7 @@ impl Client { .. }) => match options.as_ref()? { lsp::TextDocumentSyncSaveOptions::Supported(true) => false, - lsp::TextDocumentSyncSaveOptions::SaveOptions(lsp::SaveOptions { + lsp::TextDocumentSyncSaveOptions::SaveOptions(lsp_types::SaveOptions { include_text, }) => include_text.unwrap_or(false), lsp::TextDocumentSyncSaveOptions::Supported(false) => return None, @@ -1026,11 +981,12 @@ impl Client { lsp::TextDocumentSyncCapability::Kind(..) => false, }; - self.notify::<lsp::notification::DidSaveTextDocument>(lsp::DidSaveTextDocumentParams { - text_document, - text: include_text.then_some(text.into()), - }); - Some(()) + Some(self.notify::<lsp::notification::DidSaveTextDocument>( + lsp::DidSaveTextDocumentParams { + text_document, + text: include_text.then_some(text.into()), + }, + )) } pub fn completion( @@ -1038,8 +994,7 @@ impl Client { text_document: lsp::TextDocumentIdentifier, position: lsp::Position, work_done_token: Option<lsp::ProgressToken>, - context: lsp::CompletionContext, - ) -> Option<impl Future<Output = Result<Option<lsp::CompletionResponse>>>> { + ) -> Option<impl Future<Output = Result<Value>>> { let capabilities = self.capabilities.get().unwrap(); // Return early if the server does not support completion. @@ -1050,12 +1005,13 @@ impl Client { text_document, position, }, - context: Some(context), // TODO: support these tokens by async receiving and updating the choice list work_done_progress_params: lsp::WorkDoneProgressParams { work_done_token }, partial_result_params: lsp::PartialResultParams { partial_result_token: None, }, + context: None, + // lsp::CompletionContext { trigger_kind: , trigger_character: Some(), } }; Some(self.call::<lsp::request::Completion>(params)) @@ -1063,15 +1019,26 @@ impl Client { pub fn resolve_completion_item( &self, - completion_item: &lsp::CompletionItem, - ) -> impl Future<Output = Result<lsp::CompletionItem>> { - self.call_with_ref::<lsp::request::ResolveCompletionItem>(completion_item) + completion_item: lsp::CompletionItem, + ) -> Option<impl Future<Output = Result<Value>>> { + let capabilities = self.capabilities.get().unwrap(); + + // Return early if the server does not support resolving completion items. + match capabilities.completion_provider { + Some(lsp::CompletionOptions { + resolve_provider: Some(true), + .. + }) => (), + _ => return None, + } + + Some(self.call::<lsp::request::ResolveCompletionItem>(completion_item)) } pub fn resolve_code_action( &self, - code_action: &lsp::CodeAction, - ) -> Option<impl Future<Output = Result<lsp::CodeAction>>> { + code_action: lsp::CodeAction, + ) -> Option<impl Future<Output = Result<Value>>> { let capabilities = self.capabilities.get().unwrap(); // Return early if the server does not support resolving code actions. @@ -1083,7 +1050,7 @@ impl Client { _ => return None, } - Some(self.call_with_ref::<lsp::request::CodeActionResolveRequest>(code_action)) + Some(self.call::<lsp::request::CodeActionResolveRequest>(code_action)) } pub fn text_document_signature_help( @@ -1091,7 +1058,7 @@ impl Client { text_document: lsp::TextDocumentIdentifier, position: lsp::Position, work_done_token: Option<lsp::ProgressToken>, - ) -> Option<impl Future<Output = Result<Option<SignatureHelp>>>> { + ) -> Option<impl Future<Output = Result<Value>>> { let capabilities = self.capabilities.get().unwrap(); // Return early if the server does not support signature help. @@ -1115,7 +1082,7 @@ impl Client { text_document: lsp::TextDocumentIdentifier, range: lsp::Range, work_done_token: Option<lsp::ProgressToken>, - ) -> Option<impl Future<Output = Result<Option<Vec<lsp::InlayHint>>>>> { + ) -> Option<impl Future<Output = Result<Value>>> { let capabilities = self.capabilities.get().unwrap(); match capabilities.inlay_hint_provider { @@ -1135,31 +1102,12 @@ impl Client { Some(self.call::<lsp::request::InlayHintRequest>(params)) } - pub fn text_document_document_color( - &self, - text_document: lsp::TextDocumentIdentifier, - work_done_token: Option<lsp::ProgressToken>, - ) -> Option<impl Future<Output = Result<Vec<lsp::ColorInformation>>>> { - self.capabilities.get().unwrap().color_provider.as_ref()?; - let params = lsp::DocumentColorParams { - text_document, - work_done_progress_params: lsp::WorkDoneProgressParams { - work_done_token: work_done_token.clone(), - }, - partial_result_params: helix_lsp_types::PartialResultParams { - partial_result_token: work_done_token, - }, - }; - - Some(self.call::<lsp::request::DocumentColor>(params)) - } - pub fn text_document_hover( &self, text_document: lsp::TextDocumentIdentifier, position: lsp::Position, work_done_token: Option<lsp::ProgressToken>, - ) -> Option<impl Future<Output = Result<Option<lsp::Hover>>>> { + ) -> Option<impl Future<Output = Result<Value>>> { let capabilities = self.capabilities.get().unwrap(); // Return early if the server does not support hover. @@ -1190,7 +1138,7 @@ impl Client { text_document: lsp::TextDocumentIdentifier, options: lsp::FormattingOptions, work_done_token: Option<lsp::ProgressToken>, - ) -> Option<impl Future<Output = Result<Option<Vec<lsp::TextEdit>>>>> { + ) -> Option<impl Future<Output = Result<Vec<lsp::TextEdit>>>> { let capabilities = self.capabilities.get().unwrap(); // Return early if the server does not support formatting. @@ -1199,7 +1147,18 @@ impl Client { _ => return None, }; - let options = self.get_merged_formatting_options(options); + // merge FormattingOptions with 'config.format' + let mut config_format = self.config.format(); + let options = if !config_format.is_empty() { + // passed in options take precedence over 'config.format' + config_format.extend(options.properties); + lsp::FormattingOptions { + properties: config_format, + ..options + } + } else { + options + }; let params = lsp::DocumentFormattingParams { text_document, @@ -1207,7 +1166,13 @@ impl Client { work_done_progress_params: lsp::WorkDoneProgressParams { work_done_token }, }; - Some(self.call::<lsp::request::Formatting>(params)) + let request = self.call::<lsp::request::Formatting>(params); + + Some(async move { + let json = request.await?; + let response: Option<Vec<lsp::TextEdit>> = serde_json::from_value(json)?; + Ok(response.unwrap_or_default()) + }) } pub fn text_document_range_formatting( @@ -1216,7 +1181,7 @@ impl Client { range: lsp::Range, options: lsp::FormattingOptions, work_done_token: Option<lsp::ProgressToken>, - ) -> Option<impl Future<Output = Result<Option<Vec<lsp::TextEdit>>>>> { + ) -> Option<impl Future<Output = Result<Vec<lsp::TextEdit>>>> { let capabilities = self.capabilities.get().unwrap(); // Return early if the server does not support range formatting. @@ -1225,8 +1190,6 @@ impl Client { _ => return None, }; - let options = self.get_merged_formatting_options(options); - let params = lsp::DocumentRangeFormattingParams { text_document, range, @@ -1234,33 +1197,13 @@ impl Client { work_done_progress_params: lsp::WorkDoneProgressParams { work_done_token }, }; - Some(self.call::<lsp::request::RangeFormatting>(params)) - } - - pub fn text_document_diagnostic( - &self, - text_document: lsp::TextDocumentIdentifier, - previous_result_id: Option<String>, - ) -> Option<impl Future<Output = Result<lsp::DocumentDiagnosticReportResult>>> { - let capabilities = self.capabilities(); + let request = self.call::<lsp::request::RangeFormatting>(params); - // Return early if the server does not support pull diagnostic. - let identifier = match capabilities.diagnostic_provider.as_ref()? { - lsp::DiagnosticServerCapabilities::Options(cap) => cap.identifier.clone(), - lsp::DiagnosticServerCapabilities::RegistrationOptions(cap) => { - cap.diagnostic_options.identifier.clone() - } - }; - - let params = lsp::DocumentDiagnosticParams { - text_document, - identifier, - previous_result_id, - work_done_progress_params: lsp::WorkDoneProgressParams::default(), - partial_result_params: lsp::PartialResultParams::default(), - }; - - Some(self.call::<lsp::request::DocumentDiagnosticRequest>(params)) + Some(async move { + let json = request.await?; + let response: Option<Vec<lsp::TextEdit>> = serde_json::from_value(json)?; + Ok(response.unwrap_or_default()) + }) } pub fn text_document_document_highlight( @@ -1268,7 +1211,7 @@ impl Client { text_document: lsp::TextDocumentIdentifier, position: lsp::Position, work_done_token: Option<lsp::ProgressToken>, - ) -> Option<impl Future<Output = Result<Option<Vec<lsp::DocumentHighlight>>>>> { + ) -> Option<impl Future<Output = Result<Value>>> { let capabilities = self.capabilities.get().unwrap(); // Return early if the server does not support document highlight. @@ -1301,7 +1244,7 @@ impl Client { text_document: lsp::TextDocumentIdentifier, position: lsp::Position, work_done_token: Option<lsp::ProgressToken>, - ) -> impl Future<Output = Result<T::Result>> { + ) -> impl Future<Output = Result<Value>> { let params = lsp::GotoDefinitionParams { text_document_position_params: lsp::TextDocumentPositionParams { text_document, @@ -1321,7 +1264,7 @@ impl Client { text_document: lsp::TextDocumentIdentifier, position: lsp::Position, work_done_token: Option<lsp::ProgressToken>, - ) -> Option<impl Future<Output = Result<Option<lsp::GotoDefinitionResponse>>>> { + ) -> Option<impl Future<Output = Result<Value>>> { let capabilities = self.capabilities.get().unwrap(); // Return early if the server does not support goto-definition. @@ -1342,7 +1285,7 @@ impl Client { text_document: lsp::TextDocumentIdentifier, position: lsp::Position, work_done_token: Option<lsp::ProgressToken>, - ) -> Option<impl Future<Output = Result<Option<lsp::GotoDefinitionResponse>>>> { + ) -> Option<impl Future<Output = Result<Value>>> { let capabilities = self.capabilities.get().unwrap(); // Return early if the server does not support goto-declaration. @@ -1367,7 +1310,7 @@ impl Client { text_document: lsp::TextDocumentIdentifier, position: lsp::Position, work_done_token: Option<lsp::ProgressToken>, - ) -> Option<impl Future<Output = Result<Option<lsp::GotoDefinitionResponse>>>> { + ) -> Option<impl Future<Output = Result<Value>>> { let capabilities = self.capabilities.get().unwrap(); // Return early if the server does not support goto-type-definition. @@ -1391,7 +1334,7 @@ impl Client { text_document: lsp::TextDocumentIdentifier, position: lsp::Position, work_done_token: Option<lsp::ProgressToken>, - ) -> Option<impl Future<Output = Result<Option<lsp::GotoDefinitionResponse>>>> { + ) -> Option<impl Future<Output = Result<Value>>> { let capabilities = self.capabilities.get().unwrap(); // Return early if the server does not support goto-definition. @@ -1416,7 +1359,7 @@ impl Client { position: lsp::Position, include_declaration: bool, work_done_token: Option<lsp::ProgressToken>, - ) -> Option<impl Future<Output = Result<Option<Vec<lsp::Location>>>>> { + ) -> Option<impl Future<Output = Result<Value>>> { let capabilities = self.capabilities.get().unwrap(); // Return early if the server does not support goto-reference. @@ -1445,7 +1388,7 @@ impl Client { pub fn document_symbols( &self, text_document: lsp::TextDocumentIdentifier, - ) -> Option<impl Future<Output = Result<Option<lsp::DocumentSymbolResponse>>>> { + ) -> Option<impl Future<Output = Result<Value>>> { let capabilities = self.capabilities.get().unwrap(); // Return early if the server does not support document symbols. @@ -1467,7 +1410,7 @@ impl Client { &self, text_document: lsp::TextDocumentIdentifier, position: lsp::Position, - ) -> Option<impl Future<Output = Result<Option<lsp::PrepareRenameResponse>>>> { + ) -> Option<impl Future<Output = Result<Value>>> { let capabilities = self.capabilities.get().unwrap(); match capabilities.rename_provider { @@ -1487,10 +1430,7 @@ impl Client { } // empty string to get all symbols - pub fn workspace_symbols( - &self, - query: String, - ) -> Option<impl Future<Output = Result<Option<lsp::WorkspaceSymbolResponse>>>> { + pub fn workspace_symbols(&self, query: String) -> Option<impl Future<Output = Result<Value>>> { let capabilities = self.capabilities.get().unwrap(); // Return early if the server does not support workspace symbols. @@ -1503,7 +1443,6 @@ impl Client { query, work_done_progress_params: lsp::WorkDoneProgressParams::default(), partial_result_params: lsp::PartialResultParams::default(), - ..Default::default() }; Some(self.call::<lsp::request::WorkspaceSymbolRequest>(params)) @@ -1514,7 +1453,7 @@ impl Client { text_document: lsp::TextDocumentIdentifier, range: lsp::Range, context: lsp::CodeActionContext, - ) -> Option<impl Future<Output = Result<Option<Vec<lsp::CodeActionOrCommand>>>>> { + ) -> Option<impl Future<Output = Result<Value>>> { let capabilities = self.capabilities.get().unwrap(); // Return early if the server does not support code actions. @@ -1542,7 +1481,7 @@ impl Client { text_document: lsp::TextDocumentIdentifier, position: lsp::Position, new_name: String, - ) -> Option<impl Future<Output = Result<Option<lsp::WorkspaceEdit>>>> { + ) -> Option<impl Future<Output = Result<lsp::WorkspaceEdit>>> { if !self.supports_feature(LanguageServerFeature::RenameSymbol) { return None; } @@ -1558,13 +1497,16 @@ impl Client { }, }; - Some(self.call::<lsp::request::Rename>(params)) + let request = self.call::<lsp::request::Rename>(params); + + Some(async move { + let json = request.await?; + let response: Option<lsp::WorkspaceEdit> = serde_json::from_value(json)?; + Ok(response.unwrap_or_default()) + }) } - pub fn command( - &self, - command: lsp::Command, - ) -> Option<impl Future<Output = Result<Option<Value>>>> { + pub fn command(&self, command: lsp::Command) -> Option<impl Future<Output = Result<Value>>> { let capabilities = self.capabilities.get().unwrap(); // Return early if the language server does not support executing commands. @@ -1581,7 +1523,10 @@ impl Client { Some(self.call::<lsp::request::ExecuteCommand>(params)) } - pub fn did_change_watched_files(&self, changes: Vec<lsp::FileEvent>) { + pub fn did_change_watched_files( + &self, + changes: Vec<lsp::FileEvent>, + ) -> impl Future<Output = std::result::Result<(), Error>> { self.notify::<lsp::notification::DidChangeWatchedFiles>(lsp::DidChangeWatchedFilesParams { changes, }) |