Debian Codegraph @

helix-lsp/src/client.rs

raw symbols ◀ ▶ SCIP
1 Debian patch touch this file
1 use crate::{
2 file_operations::FileOperationsInterest,
3 find_lsp_workspace, jsonrpc,
4 transport::{Payload, Transport},
5 Call, Error, LanguageServerId, OffsetEncoding, Result,
6 };
7 use log::info;
8
9 use crate::lsp::{
10 self, notification::DidChangeWorkspaceFolders, CodeActionCapabilityResolveSupport,
11 DidChangeWorkspaceFoldersParams, OneOf, PositionEncodingKind, SignatureHelp, Url,
12 WorkspaceFolder, WorkspaceFoldersChangeEvent,
13 };
14 use helix_core::{
15 find_workspace,
16 syntax::config::{LanguageServerFeature, RootMarkers},
17 ChangeSet, Rope,
18 };
19 use helix_loader::VERSION_AND_GIT_HASH;
20 use helix_stdx::path;
21 use parking_lot::Mutex;
22 use serde::Deserialize;
23 use serde_json::Value;
24 use std::{collections::HashMap, path::PathBuf};
25 use std::{
26 ffi::OsStr,
•27 sync::Arc,
28 };
29 use std::{future::Future, sync::OnceLock};
30 use std::{path::Path, process::Stdio};
•31 use portable_atomic::{AtomicU64, Ordering};
32 use tokio::{
33 io::{BufReader, BufWriter},
34 process::{Child, Command},
35 sync::{
36 mpsc::{channel, UnboundedReceiver, UnboundedSender},
37 Notify, OnceCell,
38 },
39 };
40
41 fn workspace_for_uri(uri: lsp::Url) -> WorkspaceFolder {
42 lsp::WorkspaceFolder {
43 name: uri
44 .path()
45 .rsplit('/')
46 .find(|segment| !segment.is_empty())
47 .map(|basename| basename.to_string())
48 .unwrap_or_default(),
49 uri,
50 }
51 }
52
53 #[derive(Debug)]
54 pub struct Client {
55 id: LanguageServerId,
56 name: String,
57 _process: Child,
58 server_tx: UnboundedSender<Payload>,
59 request_counter: AtomicU64,
60 pub(crate) capabilities: OnceCell<lsp::ServerCapabilities>,
61 pub(crate) file_operation_interest: OnceLock<FileOperationsInterest>,
62 config: Option<Value>,
63 root_path: std::path::PathBuf,
64 root_uri: Option<lsp::Url>,
65 workspace_folders: Mutex<Vec<lsp::WorkspaceFolder>>,
66 initialize_notify: Arc<Notify>,
67 /// Notified by the transport once `exit` has been flushed to the server's stdin.
68 shutdown_flushed: Arc<Notify>,
69 /// workspace folders added while the server is still initializing
70 req_timeout: u64,
71 }
72
73 impl Client {
74 pub fn try_add_doc(
75 self: &Arc<Self>,
76 root_markers: &RootMarkers,
77 manual_roots: &[PathBuf],
78 doc_path: Option<&std::path::Path>,
79 may_support_workspace: bool,
80 ) -> bool {
81 let (workspace, workspace_is_cwd) = find_workspace();
82 let workspace = path::normalize(workspace);
83 let root = find_lsp_workspace(
84 doc_path
85 .and_then(|x| x.parent().and_then(|x| x.to_str()))
86 .unwrap_or("."),
87 root_markers,
88 manual_roots,
89 &workspace,
90 workspace_is_cwd,
91 );
92 let root_uri = root
93 .as_ref()
94 .and_then(|root| lsp::Url::from_file_path(root).ok());
95
96 if self.root_path == root.unwrap_or(workspace)
97 || root_uri.as_ref().is_some_and(|root_uri| {
98 self.workspace_folders
99 .lock()
100 .iter()
101 .any(|workspace| &workspace.uri == root_uri)
102 })
103 {
104 // workspace URI is already registered so we can use this client
105 return true;
106 }
107
108 // this server definitely doesn't support multiple workspace, no need to check capabilities
109 if !may_support_workspace {
110 return false;
111 }
112
113 let Some(capabilities) = self.capabilities.get() else {
114 let client = Arc::clone(self);
115 // initialization hasn't finished yet, deal with this new root later
116 // TODO: In the edgecase that a **new root** is added
117 // for an LSP that **doesn't support workspace_folders** before initaliation is finished
118 // the new roots are ignored.
119 // That particular edgecase would require retroactively spawning new LSP
120 // clients and therefore also require us to retroactively update the corresponding
121 // documents LSP client handle. It's doable but a pretty weird edgecase so let's
122 // wait and see if anyone ever runs into it.
123 tokio::spawn(async move {
124 client.initialize_notify.notified().await;
125 if let Some(workspace_folders_caps) = client
126 .capabilities()
127 .workspace
128 .as_ref()
129 .and_then(|cap| cap.workspace_folders.as_ref())
130 .filter(|cap| cap.supported.unwrap_or(false))
131 {
132 client.add_workspace_folder(
133 root_uri,
134 workspace_folders_caps.change_notifications.as_ref(),
135 );
136 }
137 });
138 return true;
139 };
140
141 if let Some(workspace_folders_caps) = capabilities
142 .workspace
143 .as_ref()
144 .and_then(|cap| cap.workspace_folders.as_ref())
145 .filter(|cap| cap.supported.unwrap_or(false))
146 {
147 self.add_workspace_folder(
148 root_uri,
149 workspace_folders_caps.change_notifications.as_ref(),
150 );
151 true
152 } else {
153 // the server doesn't support multi workspaces, we need a new client
154 false
155 }
156 }
157
158 fn add_workspace_folder(
159 &self,
160 root_uri: Option<lsp::Url>,
161 change_notifications: Option<&OneOf<bool, String>>,
162 ) {
163 // root_uri is None just means that there isn't really any LSP workspace
164 // associated with this file. For servers that support multiple workspaces
165 // there is just one server so we can always just use that shared instance.
166 // No need to add a new workspace root here as there is no logical root for this file
167 // let the server deal with this
168 let Some(root_uri) = root_uri else {
169 return;
170 };
171
172 // server supports workspace folders, let's add the new root to the list
173 self.workspace_folders
174 .lock()
175 .push(workspace_for_uri(root_uri.clone()));
176 if Some(&OneOf::Left(false)) == change_notifications {
177 // server specifically opted out of DidWorkspaceChange notifications
178 // let's assume the server will request the workspace folders itself
179 // and that we can therefore reuse the client (but are done now)
180 return;
181 }
182 self.did_change_workspace(vec![workspace_for_uri(root_uri)], Vec::new())
183 }
184
185 /// Merge FormattingOptions with 'config.format' and return it
186 fn get_merged_formatting_options(
187 &self,
188 options: lsp::FormattingOptions,
189 ) -> lsp::FormattingOptions {
190 let config_format = self
191 .config
192 .as_ref()
193 .and_then(|cfg| cfg.get("format"))
194 .and_then(|fmt| HashMap::<String, lsp::FormattingProperty>::deserialize(fmt).ok());
195
196 if let Some(mut properties) = config_format {
197 // passed in options take precedence over 'config.format'
198 properties.extend(options.properties);
199 lsp::FormattingOptions {
200 properties,
201 ..options
202 }
203 } else {
204 options
205 }
206 }
207
208 #[allow(clippy::type_complexity, clippy::too_many_arguments)]
209 pub fn start(
210 cmd: &str,
211 args: &[String],
212 config: Option<Value>,
213 server_environment: impl IntoIterator<Item = (impl AsRef<OsStr>, impl AsRef<OsStr>)>,
214 root_path: PathBuf,
215 root_uri: Option<lsp::Url>,
216 id: LanguageServerId,
217 name: String,
218 req_timeout: u64,
219 ) -> Result<(
220 Self,
221 UnboundedReceiver<(LanguageServerId, Call)>,
222 Arc<Notify>,
223 )> {
224 info!("Starting lsp {name:?} in root {root_path:?}");
225 // Resolve path to the binary
226 let cmd = helix_stdx::env::which(cmd)?;
227
228 let process = Command::new(cmd)
229 .envs(server_environment)
230 .args(args)
231 .stdin(Stdio::piped())
232 .stdout(Stdio::piped())
233 .stderr(Stdio::piped())
234 .current_dir(&root_path)
235 // make sure the process is reaped on drop
236 .kill_on_drop(true)
237 .spawn();
238
239 let mut process = process?;
240
241 // TODO: do we need bufreader/writer here? or do we use async wrappers on unblock?
242 let writer = BufWriter::new(process.stdin.take().expect("Failed to open stdin"));
243 let reader = BufReader::new(process.stdout.take().expect("Failed to open stdout"));
244 let stderr = BufReader::new(process.stderr.take().expect("Failed to open stderr"));
245
246 let (server_rx, server_tx, initialize_notify, shutdown_flushed) =
247 Transport::start(reader, writer, stderr, id, name.clone());
248
249 let workspace_folders = root_uri
250 .clone()
251 .map(|root| vec![workspace_for_uri(root)])
252 .unwrap_or_default();
253
254 let client = Self {
255 id,
256 name,
257 _process: process,
258 server_tx,
259 request_counter: AtomicU64::new(0),
260 capabilities: OnceCell::new(),
261 file_operation_interest: OnceLock::new(),
262 config,
263 req_timeout,
264 root_path,
265 root_uri,
266 workspace_folders: Mutex::new(workspace_folders),
267 initialize_notify: initialize_notify.clone(),
268 shutdown_flushed,
269 };
270
271 Ok((client, server_rx, initialize_notify))
272 }
273
274 pub fn name(&self) -> &str {
275 &self.name
276 }
277
278 pub fn id(&self) -> LanguageServerId {
279 self.id
280 }
281
282 fn next_request_id(&self) -> jsonrpc::Id {
283 let id = self.request_counter.fetch_add(1, Ordering::Relaxed);
284 jsonrpc::Id::Num(id)
285 }
286
287 fn value_into_params(value: Value) -> jsonrpc::Params {
288 use jsonrpc::Params;
289
290 match value {
291 Value::Null => Params::None,
292 Value::Bool(_) | Value::Number(_) | Value::String(_) => Params::Array(vec![value]),
293 Value::Array(vec) => Params::Array(vec),
294 Value::Object(map) => Params::Map(map),
295 }
296 }
297
298 pub fn is_initialized(&self) -> bool {
299 self.capabilities.get().is_some()
300 }
301
302 pub fn capabilities(&self) -> &lsp::ServerCapabilities {
303 self.capabilities
304 .get()
305 .expect("language server not yet initialized!")
306 }
307
308 pub(crate) fn file_operations_intests(&self) -> &FileOperationsInterest {
309 self.file_operation_interest
310 .get_or_init(|| FileOperationsInterest::new(self.capabilities()))
311 }
312
313 /// Client has to be initialized otherwise this function panics
314 #[inline]
315 pub fn supports_feature(&self, feature: LanguageServerFeature) -> bool {
316 let capabilities = self.capabilities();
317
318 use lsp::*;
319 match feature {
320 LanguageServerFeature::Format => matches!(
321 capabilities.document_formatting_provider,
322 Some(OneOf::Left(true) | OneOf::Right(_))
323 ),
324 LanguageServerFeature::GotoDeclaration => matches!(
325 capabilities.declaration_provider,
326 Some(
327 DeclarationCapability::Simple(true)
328 | DeclarationCapability::RegistrationOptions(_)
329 | DeclarationCapability::Options(_),
330 )
331 ),
332 LanguageServerFeature::GotoDefinition => matches!(
333 capabilities.definition_provider,
334 Some(OneOf::Left(true) | OneOf::Right(_))
335 ),
336 LanguageServerFeature::GotoTypeDefinition => matches!(
337 capabilities.type_definition_provider,
338 Some(
339 TypeDefinitionProviderCapability::Simple(true)
340 | TypeDefinitionProviderCapability::Options(_),
341 )
342 ),
343 LanguageServerFeature::GotoReference => matches!(
344 capabilities.references_provider,
345 Some(OneOf::Left(true) | OneOf::Right(_))
346 ),
347 LanguageServerFeature::GotoImplementation => matches!(
348 capabilities.implementation_provider,
349 Some(
350 ImplementationProviderCapability::Simple(true)
351 | ImplementationProviderCapability::Options(_),
352 )
353 ),
354 LanguageServerFeature::SignatureHelp => capabilities.signature_help_provider.is_some(),
355 LanguageServerFeature::Hover => matches!(
356 capabilities.hover_provider,
357 Some(HoverProviderCapability::Simple(true) | HoverProviderCapability::Options(_),)
358 ),
359 LanguageServerFeature::DocumentHighlight => matches!(
360 capabilities.document_highlight_provider,
361 Some(OneOf::Left(true) | OneOf::Right(_))
362 ),
363 LanguageServerFeature::Completion => capabilities.completion_provider.is_some(),
364 LanguageServerFeature::CodeAction => matches!(
365 capabilities.code_action_provider,
366 Some(
367 CodeActionProviderCapability::Simple(true)
368 | CodeActionProviderCapability::Options(_),
369 )
370 ),
371 LanguageServerFeature::DocumentLinks => capabilities.document_link_provider.is_some(),
372 LanguageServerFeature::WorkspaceCommand => {
373 capabilities.execute_command_provider.is_some()
374 }
375 LanguageServerFeature::DocumentSymbols => matches!(
376 capabilities.document_symbol_provider,
377 Some(OneOf::Left(true) | OneOf::Right(_))
378 ),
379 LanguageServerFeature::WorkspaceSymbols => matches!(
380 capabilities.workspace_symbol_provider,
381 Some(OneOf::Left(true) | OneOf::Right(_))
382 ),
383 LanguageServerFeature::Diagnostics => true, // there's no extra server capability
384 LanguageServerFeature::PullDiagnostics => capabilities.diagnostic_provider.is_some(),
385 LanguageServerFeature::RenameSymbol => matches!(
386 capabilities.rename_provider,
387 Some(OneOf::Left(true)) | Some(OneOf::Right(_))
388 ),
389 LanguageServerFeature::InlayHints => matches!(
390 capabilities.inlay_hint_provider,
391 Some(OneOf::Left(true) | OneOf::Right(InlayHintServerCapabilities::Options(_)))
392 ),
393 LanguageServerFeature::DocumentColors => matches!(
394 capabilities.color_provider,
395 Some(
396 ColorProviderCapability::Simple(true)
397 | ColorProviderCapability::ColorProvider(_)
398 | ColorProviderCapability::Options(_)
399 )
400 ),
401 LanguageServerFeature::CallHierarchy => matches!(
402 capabilities.call_hierarchy_provider,
403 Some(
404 CallHierarchyServerCapability::Simple(true)
405 | CallHierarchyServerCapability::Options(_)
406 )
407 ),
408 }
409 }
410
411 pub fn offset_encoding(&self) -> OffsetEncoding {
412 self.capabilities()
413 .position_encoding
414 .as_ref()
415 .and_then(|encoding| match encoding.as_str() {
416 "utf-8" => Some(OffsetEncoding::Utf8),
417 "utf-16" => Some(OffsetEncoding::Utf16),
418 "utf-32" => Some(OffsetEncoding::Utf32),
419 encoding => {
420 log::error!("Server provided invalid position encoding {encoding}, defaulting to utf-16");
421 None
422 },
423 })
424 .unwrap_or_default()
425 }
426
427 pub fn config(&self) -> Option<&Value> {
428 self.config.as_ref()
429 }
430
431 pub async fn workspace_folders(
432 &self,
433 ) -> parking_lot::MutexGuard<'_, Vec<lsp::WorkspaceFolder>> {
434 self.workspace_folders.lock()
435 }
436
437 /// Execute a RPC request on the language server.
438 fn call<R: lsp::request::Request>(
439 &self,
440 params: R::Params,
441 ) -> impl Future<Output = Result<R::Result>>
442 where
443 R::Params: serde::Serialize,
444 {
445 self.call_with_ref::<R>(&params)
446 }
447
448 fn call_with_ref<R: lsp::request::Request>(
449 &self,
450 params: &R::Params,
451 ) -> impl Future<Output = Result<R::Result>>
452 where
453 R::Params: serde::Serialize,
454 {
455 self.call_with_timeout::<R>(params, self.req_timeout)
456 }
457
458 fn call_with_timeout<R: lsp::request::Request>(
459 &self,
460 params: &R::Params,
461 timeout_secs: u64,
462 ) -> impl Future<Output = Result<R::Result>>
463 where
464 R::Params: serde::Serialize,
465 {
466 let server_tx = self.server_tx.clone();
467 let id = self.next_request_id();
468
469 // It's important that this is not part of the future so that it gets executed right away
470 // and the request order stays consistent.
471 let rx = serde_json::to_value(params)
472 .map_err(Error::from)
473 .and_then(|params| {
474 let request = jsonrpc::MethodCall {
475 jsonrpc: Some(jsonrpc::Version::V2),
476 id: id.clone(),
477 method: R::METHOD.to_string(),
478 params: Self::value_into_params(params),
479 };
480 let (tx, rx) = channel::<Result<Value>>(1);
481 server_tx
482 .send(Payload::Request {
483 chan: tx,
484 value: request,
485 })
486 .map_err(|e| Error::Other(e.into()))?;
487 Ok(rx)
488 });
489
490 async move {
491 use std::time::Duration;
492 use tokio::time::timeout;
493 // TODO: delay other calls until initialize success
494 timeout(Duration::from_secs(timeout_secs), rx?.recv())
495 .await
496 .map_err(|_| Error::Timeout(id))? // return Timeout
497 .ok_or(Error::StreamClosed)?
498 .and_then(|value| serde_json::from_value(value).map_err(Into::into))
499 }
500 }
501
502 /// Send a RPC notification to the language server.
503 pub fn notify<R: lsp::notification::Notification>(&self, params: R::Params)
504 where
505 R::Params: serde::Serialize,
506 {
507 let server_tx = self.server_tx.clone();
508
509 let params = match serde_json::to_value(params) {
510 Ok(params) => params,
511 Err(err) => {
512 log::error!(
513 "Failed to serialize params for notification '{}' for server '{}': {err}",
514 R::METHOD,
515 self.name,
516 );
517 return;
518 }
519 };
520
521 let notification = jsonrpc::Notification {
522 jsonrpc: Some(jsonrpc::Version::V2),
523 method: R::METHOD.to_string(),
524 params: Self::value_into_params(params),
525 };
526
527 if let Err(err) = server_tx.send(Payload::Notification(notification)) {
528 log::error!(
529 "Failed to send notification '{}' to server '{}': {err}",
530 R::METHOD,
531 self.name
532 );
533 }
534 }
535
536 /// Reply to a language server RPC call.
537 pub fn reply(
538 &self,
539 id: jsonrpc::Id,
540 result: core::result::Result<Value, jsonrpc::Error>,
541 ) -> Result<()> {
542 use jsonrpc::{Failure, Output, Success, Version};
543
544 let server_tx = self.server_tx.clone();
545
546 let output = match result {
547 Ok(result) => Output::Success(Success {
548 jsonrpc: Some(Version::V2),
549 id,
550 result,
551 }),
552 Err(error) => Output::Failure(Failure {
553 jsonrpc: Some(Version::V2),
554 id,
555 error,
556 }),
557 };
558
559 server_tx
560 .send(Payload::Response(output))
561 .map_err(|e| Error::Other(e.into()))?;
562
563 Ok(())
564 }
565
566 // -------------------------------------------------------------------------------------------
567 // General messages
568 // -------------------------------------------------------------------------------------------
569
570 pub(crate) async fn initialize(&self, enable_snippets: bool) -> Result<lsp::InitializeResult> {
571 if let Some(config) = &self.config {
572 log::info!("Using custom LSP config: {}", config);
573 }
574
575 #[allow(deprecated)]
576 let params = lsp::InitializeParams {
577 process_id: Some(std::process::id()),
578 workspace_folders: Some(self.workspace_folders.lock().clone()),
579 // root_path is obsolete, but some clients like pyright still use it so we specify both.
580 // clients will prefer _uri if possible
581 root_path: self.root_path.to_str().map(|path| path.to_owned()),
582 root_uri: self.root_uri.clone(),
583 initialization_options: self.config.clone(),
584 capabilities: lsp::ClientCapabilities {
585 workspace: Some(lsp::WorkspaceClientCapabilities {
586 configuration: Some(true),
587 did_change_configuration: Some(lsp::DynamicRegistrationClientCapabilities {
588 dynamic_registration: Some(false),
589 }),
590 workspace_folders: Some(true),
591 apply_edit: Some(true),
592 symbol: Some(lsp::WorkspaceSymbolClientCapabilities {
593 dynamic_registration: Some(false),
594 symbol_kind: Some(lsp::SymbolKindCapability {
595 value_set: Some(lsp::SymbolKind::all()),
596 }),
597 ..Default::default()
598 }),
599 execute_command: Some(lsp::DynamicRegistrationClientCapabilities {
600 dynamic_registration: Some(false),
601 }),
602 inlay_hint: Some(lsp::InlayHintWorkspaceClientCapabilities {
603 refresh_support: Some(false),
604 }),
605 workspace_edit: Some(lsp::WorkspaceEditClientCapabilities {
606 document_changes: Some(true),
607 resource_operations: Some(vec![
608 lsp::ResourceOperationKind::Create,
609 lsp::ResourceOperationKind::Rename,
610 lsp::ResourceOperationKind::Delete,
611 ]),
612 failure_handling: Some(lsp::FailureHandlingKind::Abort),
613 normalizes_line_endings: Some(false),
614 change_annotation_support: None,
615 }),
616 did_change_watched_files: Some(lsp::DidChangeWatchedFilesClientCapabilities {
617 dynamic_registration: Some(true),
618 relative_pattern_support: Some(true),
619 }),
620 file_operations: Some(lsp::WorkspaceFileOperationsClientCapabilities {
621 will_create: Some(true),
622 did_create: Some(true),
623 will_rename: Some(true),
624 did_rename: Some(true),
625 will_delete: Some(true),
626 did_delete: Some(true),
627 ..Default::default()
628 }),
629 diagnostic: Some(lsp::DiagnosticWorkspaceClientCapabilities {
630 refresh_support: Some(true),
631 }),
632 ..Default::default()
633 }),
634 text_document: Some(lsp::TextDocumentClientCapabilities {
635 completion: Some(lsp::CompletionClientCapabilities {
636 completion_item: Some(lsp::CompletionItemCapability {
637 snippet_support: Some(enable_snippets),
638 resolve_support: Some(lsp::CompletionItemCapabilityResolveSupport {
639 properties: vec![
640 String::from("documentation"),
641 String::from("detail"),
642 String::from("additionalTextEdits"),
643 ],
644 }),
645 insert_replace_support: Some(true),
646 deprecated_support: Some(true),
647 tag_support: Some(lsp::TagSupport {
648 value_set: vec![lsp::CompletionItemTag::DEPRECATED],
649 }),
650 ..Default::default()
651 }),
652 completion_item_kind: Some(lsp::CompletionItemKindCapability {
653 ..Default::default()
654 }),
655 context_support: None, // additional context information Some(true)
656 ..Default::default()
657 }),
658 hover: Some(lsp::HoverClientCapabilities {
659 // if not specified, rust-analyzer returns plaintext marked as markdown but
660 // badly formatted.
661 content_format: Some(vec![lsp::MarkupKind::Markdown]),
662 ..Default::default()
663 }),
664 signature_help: Some(lsp::SignatureHelpClientCapabilities {
665 signature_information: Some(lsp::SignatureInformationSettings {
666 documentation_format: Some(vec![lsp::MarkupKind::Markdown]),
667 parameter_information: Some(lsp::ParameterInformationSettings {
668 label_offset_support: Some(true),
669 }),
670 active_parameter_support: Some(true),
671 }),
672 ..Default::default()
673 }),
674 rename: Some(lsp::RenameClientCapabilities {
675 dynamic_registration: Some(false),
676 prepare_support: Some(true),
677 prepare_support_default_behavior: None,
678 honors_change_annotations: Some(false),
679 }),
680 formatting: Some(lsp::DocumentFormattingClientCapabilities {
681 dynamic_registration: Some(false),
682 }),
683 code_action: Some(lsp::CodeActionClientCapabilities {
684 code_action_literal_support: Some(lsp::CodeActionLiteralSupport {
685 code_action_kind: lsp::CodeActionKindLiteralSupport {
686 value_set: [
687 lsp::CodeActionKind::EMPTY,
688 lsp::CodeActionKind::QUICKFIX,
689 lsp::CodeActionKind::REFACTOR,
690 lsp::CodeActionKind::REFACTOR_EXTRACT,
691 lsp::CodeActionKind::REFACTOR_INLINE,
692 lsp::CodeActionKind::REFACTOR_REWRITE,
693 lsp::CodeActionKind::SOURCE,
694 lsp::CodeActionKind::SOURCE_ORGANIZE_IMPORTS,
695 lsp::CodeActionKind::SOURCE_FIX_ALL,
696 ]
697 .iter()
698 .map(|kind| kind.as_str().to_string())
699 .collect(),
700 },
701 }),
702 is_preferred_support: Some(true),
703 disabled_support: Some(true),
704 data_support: Some(true),
705 resolve_support: Some(CodeActionCapabilityResolveSupport {
706 properties: vec!["edit".to_owned(), "command".to_owned()],
707 }),
708 ..Default::default()
709 }),
710 diagnostic: Some(lsp::DiagnosticClientCapabilities {
711 dynamic_registration: Some(false),
712 related_document_support: Some(true),
713 }),
714 publish_diagnostics: Some(lsp::PublishDiagnosticsClientCapabilities {
715 version_support: Some(true),
716 tag_support: Some(lsp::TagSupport {
717 value_set: vec![
718 lsp::DiagnosticTag::UNNECESSARY,
719 lsp::DiagnosticTag::DEPRECATED,
720 ],
721 }),
722 ..Default::default()
723 }),
724 inlay_hint: Some(lsp::InlayHintClientCapabilities {
725 dynamic_registration: Some(false),
726 resolve_support: None,
727 }),
728 document_link: Some(lsp::DocumentLinkClientCapabilities {
729 dynamic_registration: Some(false),
730 tooltip_support: Some(false),
731 }),
732 call_hierarchy: Some(lsp::DynamicRegistrationClientCapabilities {
733 dynamic_registration: Some(false),
734 }),
735 document_symbol: Some(lsp::DocumentSymbolClientCapabilities {
736 dynamic_registration: Some(false),
737 symbol_kind: Some(lsp::SymbolKindCapability {
738 value_set: Some(lsp::SymbolKind::all()),
739 }),
740 hierarchical_document_symbol_support: Some(false),
741 ..Default::default()
742 }),
743 ..Default::default()
744 }),
745 window: Some(lsp::WindowClientCapabilities {
746 show_message: Some(lsp::ShowMessageRequestClientCapabilities {
747 message_action_item: Some(lsp::MessageActionItemCapabilities {
748 additional_properties_support: Some(true),
749 }),
750 }),
751 work_done_progress: Some(true),
752 show_document: Some(lsp::ShowDocumentClientCapabilities { support: true }),
753 }),
754 general: Some(lsp::GeneralClientCapabilities {
755 position_encodings: Some(vec![
756 PositionEncodingKind::UTF8,
757 PositionEncodingKind::UTF32,
758 PositionEncodingKind::UTF16,
759 ]),
760 ..Default::default()
761 }),
762 ..Default::default()
763 },
764 trace: None,
765 client_info: Some(lsp::ClientInfo {
766 name: String::from("helix"),
767 version: Some(String::from(VERSION_AND_GIT_HASH)),
768 }),
769 locale: None, // TODO
770 work_done_progress_params: lsp::WorkDoneProgressParams::default(),
771 };
772
773 self.call::<lsp::request::Initialize>(params).await
774 }
775
776 pub async fn shutdown(&self) -> Result<()> {
777 self.call::<lsp::request::Shutdown>(()).await
778 }
779
780 pub fn exit(&self) {
781 self.notify::<lsp::notification::Exit>(())
782 }
783
784 /// Tries to shut down the language server but returns
785 /// early if server responds with an error.
786 pub async fn shutdown_and_exit(&self) -> Result<()> {
787 self.shutdown().await?;
788 self.exit();
789 Ok(())
790 }
791
792 /// Sends the LSP shutdown request followed immediately by the exit
793 /// notification, without waiting for the shutdown response (fire-and-forget).
794 /// The server receives both in order and exits on its own; any late shutdown
795 /// response is discarded. Quitting therefore never blocks on a slow server
796 /// (e.g. gopls flushing ~1k log messages before it would answer `shutdown`).
797 ///
798 /// The child process is not waited on here: it is killed by `kill_on_drop`
799 /// when this `Client` is dropped. `close_language_servers` first gives a short
800 /// grace window so the `exit` reaches stdin and well-behaved servers can begin
801 /// exiting before the kill.
802 pub fn force_shutdown(&self) {
803 let request = jsonrpc::MethodCall {
804 jsonrpc: Some(jsonrpc::Version::V2),
805 id: self.next_request_id(),
806 method: <lsp::request::Shutdown as lsp::request::Request>::METHOD.to_string(),
807 params: jsonrpc::Params::None,
808 };
809 // The response receiver is dropped immediately; we do not wait for a reply.
810 let (chan, _) = tokio::sync::mpsc::channel(1);
811 let _ = self.server_tx.send(Payload::Request {
812 chan,
813 value: request,
814 });
815 self.exit();
816 }
817
818 /// Resolves once the `exit` notification has been written to the server's stdin
819 /// (i.e. helix's *outbound* write completed — independent of how slow the server
820 /// is, since it doesn't wait for any server response).
821 pub async fn wait_shutdown_flushed(&self) {
822 self.shutdown_flushed.notified().await;
823 }
824
825 // -------------------------------------------------------------------------------------------
826 // Workspace
827 // -------------------------------------------------------------------------------------------
828
829 pub fn did_change_configuration(&self, settings: Value) {
830 self.notify::<lsp::notification::DidChangeConfiguration>(
831 lsp::DidChangeConfigurationParams { settings },
832 )
833 }
834
835 pub fn did_change_workspace(&self, added: Vec<WorkspaceFolder>, removed: Vec<WorkspaceFolder>) {
836 self.notify::<DidChangeWorkspaceFolders>(DidChangeWorkspaceFoldersParams {
837 event: WorkspaceFoldersChangeEvent { added, removed },
838 })
839 }
840
841 fn file_operation_uri(path: &Path, is_dir: bool) -> Option<String> {
842 let url = if is_dir {
843 Url::from_directory_path(path)
844 } else {
845 Url::from_file_path(path)
846 };
847 Some(url.ok()?.to_string())
848 }
849
850 pub fn will_create(
851 &self,
852 path: &Path,
853 is_dir: bool,
854 ) -> Option<impl Future<Output = Result<Option<lsp::WorkspaceEdit>>>> {
855 let capabilities = self.file_operations_intests();
856 if !capabilities.will_create.has_interest(path, is_dir) {
857 return None;
858 }
859
860 let files = vec![lsp::FileCreate {
861 uri: Self::file_operation_uri(path, is_dir)?,
862 }];
863 Some(self.call_with_timeout::<lsp::request::WillCreateFiles>(
864 &lsp::CreateFilesParams { files },
865 5,
866 ))
867 }
868
869 pub fn did_create(&self, path: &Path, is_dir: bool) -> Option<()> {
870 let capabilities = self.file_operations_intests();
871 if !capabilities.did_create.has_interest(path, is_dir) {
872 return None;
873 }
874
875 let files = vec![lsp::FileCreate {
876 uri: Self::file_operation_uri(path, is_dir)?,
877 }];
878 self.notify::<lsp::notification::DidCreateFiles>(lsp::CreateFilesParams { files });
879 Some(())
880 }
881
882 pub fn will_rename(
883 &self,
884 old_path: &Path,
885 new_path: &Path,
886 is_dir: bool,
887 ) -> Option<impl Future<Output = Result<Option<lsp::WorkspaceEdit>>>> {
888 let capabilities = self.file_operations_intests();
889 if !capabilities.will_rename.has_interest(old_path, is_dir) {
890 return None;
891 }
892 let files = vec![lsp::FileRename {
893 old_uri: Self::file_operation_uri(old_path, is_dir)?,
894 new_uri: Self::file_operation_uri(new_path, is_dir)?,
895 }];
896 Some(self.call_with_timeout::<lsp::request::WillRenameFiles>(
897 &lsp::RenameFilesParams { files },
898 5,
899 ))
900 }
901
902 pub fn did_rename(&self, old_path: &Path, new_path: &Path, is_dir: bool) -> Option<()> {
903 let capabilities = self.file_operations_intests();
904 if !capabilities.did_rename.has_interest(new_path, is_dir) {
905 return None;
906 }
907
908 let files = vec![lsp::FileRename {
909 old_uri: Self::file_operation_uri(old_path, is_dir)?,
910 new_uri: Self::file_operation_uri(new_path, is_dir)?,
911 }];
912 self.notify::<lsp::notification::DidRenameFiles>(lsp::RenameFilesParams { files });
913 Some(())
914 }
915
916 pub fn will_delete(
917 &self,
918 path: &Path,
919 is_dir: bool,
920 ) -> Option<impl Future<Output = Result<Option<lsp::WorkspaceEdit>>>> {
921 let capabilities = self.file_operations_intests();
922 if !capabilities.will_delete.has_interest(path, is_dir) {
923 return None;
924 }
925
926 let files = vec![lsp::FileDelete {
927 uri: Self::file_operation_uri(path, is_dir)?,
928 }];
929 Some(self.call_with_timeout::<lsp::request::WillDeleteFiles>(
930 &lsp::DeleteFilesParams { files },
931 5,
932 ))
933 }
934
935 pub fn did_delete(&self, path: &Path, is_dir: bool) -> Option<()> {
936 let capabilities = self.file_operations_intests();
937 if !capabilities.did_delete.has_interest(path, is_dir) {
938 return None;
939 }
940
941 let files = vec![lsp::FileDelete {
942 uri: Self::file_operation_uri(path, is_dir)?,
943 }];
944 self.notify::<lsp::notification::DidDeleteFiles>(lsp::DeleteFilesParams { files });
945 Some(())
946 }
947
948 // -------------------------------------------------------------------------------------------
949 // Text document
950 // -------------------------------------------------------------------------------------------
951
952 pub fn text_document_did_open(
953 &self,
954 uri: lsp::Url,
955 version: i32,
956 doc: &Rope,
957 language_id: String,
958 ) {
959 self.notify::<lsp::notification::DidOpenTextDocument>(lsp::DidOpenTextDocumentParams {
960 text_document: lsp::TextDocumentItem {
961 uri,
962 language_id,
963 version,
964 text: String::from(doc),
965 },
966 })
967 }
968
969 pub fn changeset_to_changes(
970 old_text: &Rope,
971 new_text: &Rope,
972 changeset: &ChangeSet,
973 offset_encoding: OffsetEncoding,
974 ) -> Vec<lsp::TextDocumentContentChangeEvent> {
975 let mut iter = changeset.changes().iter().peekable();
976 let mut old_pos = 0;
977 let mut new_pos = 0;
978
979 let mut changes = Vec::new();
980
981 use crate::util::pos_to_lsp_pos;
982 use helix_core::Operation::*;
983
984 // this is dumb. TextEdit describes changes to the initial doc (concurrent), but
985 // TextDocumentContentChangeEvent describes a series of changes (sequential).
986 // So S -> S1 -> S2, meaning positioning depends on the previous edits.
987 //
988 // Calculation is therefore a bunch trickier.
989
990 use helix_core::RopeSlice;
991 fn traverse(
992 pos: lsp::Position,
993 text: RopeSlice,
994 offset_encoding: OffsetEncoding,
995 ) -> lsp::Position {
996 let lsp::Position {
997 mut line,
998 mut character,
999 } = pos;
1000
1001 let mut chars = text.chars().peekable();
1002 while let Some(ch) = chars.next() {
1003 // LSP only considers \n, \r or \r\n as line endings
1004 if ch == '\n' || ch == '\r' {
1005 // consume a \r\n
1006 if ch == '\r' && chars.peek() == Some(&'\n') {
1007 chars.next();
1008 }
1009 line += 1;
1010 character = 0;
1011 } else {
1012 character += match offset_encoding {
1013 OffsetEncoding::Utf8 => ch.len_utf8() as u32,
1014 OffsetEncoding::Utf16 => ch.len_utf16() as u32,
1015 OffsetEncoding::Utf32 => 1,
1016 };
1017 }
1018 }
1019 lsp::Position { line, character }
1020 }
1021
1022 let old_text = old_text.slice(..);
1023
1024 while let Some(change) = iter.next() {
1025 let len = match change {
1026 Delete(i) | Retain(i) => *i,
1027 Insert(_) => 0,
1028 };
1029 let mut old_end = old_pos + len;
1030
1031 match change {
1032 Retain(i) => {
1033 new_pos += i;
1034 }
1035 Delete(_) => {
1036 let start = pos_to_lsp_pos(new_text, new_pos, offset_encoding);
1037 let end = traverse(start, old_text.slice(old_pos..old_end), offset_encoding);
1038
1039 // deletion
1040 changes.push(lsp::TextDocumentContentChangeEvent {
1041 range: Some(lsp::Range::new(start, end)),
1042 text: "".to_string(),
1043 range_length: None,
1044 });
1045 }
1046 Insert(s) => {
1047 let start = pos_to_lsp_pos(new_text, new_pos, offset_encoding);
1048
1049 new_pos += s.chars().count();
1050
1051 // a subsequent delete means a replace, consume it
1052 let end = if let Some(Delete(len)) = iter.peek() {
1053 old_end = old_pos + len;
1054 let end =
1055 traverse(start, old_text.slice(old_pos..old_end), offset_encoding);
1056
1057 iter.next();
1058
1059 // replacement
1060 end
1061 } else {
1062 // insert
1063 start
1064 };
1065
1066 changes.push(lsp::TextDocumentContentChangeEvent {
1067 range: Some(lsp::Range::new(start, end)),
1068 text: s.to_string(),
1069 range_length: None,
1070 });
1071 }
1072 }
1073 old_pos = old_end;
1074 }
1075
1076 changes
1077 }
1078
1079 pub fn text_document_did_change(
1080 &self,
1081 text_document: lsp::VersionedTextDocumentIdentifier,
1082 old_text: &Rope,
1083 new_text: &Rope,
1084 changes: &ChangeSet,
1085 ) -> Option<()> {
1086 let capabilities = self.capabilities.get().unwrap();
1087
1088 // Return early if the server does not support document sync.
1089 let sync_capabilities = match capabilities.text_document_sync {
1090 Some(
1091 lsp::TextDocumentSyncCapability::Kind(kind)
1092 | lsp::TextDocumentSyncCapability::Options(lsp::TextDocumentSyncOptions {
1093 change: Some(kind),
1094 ..
1095 }),
1096 ) => kind,
1097 // None | SyncOptions { changes: None }
1098 _ => return None,
1099 };
1100
1101 let changes = match sync_capabilities {
1102 lsp::TextDocumentSyncKind::FULL => {
1103 vec![lsp::TextDocumentContentChangeEvent {
1104 // range = None -> whole document
1105 range: None, //Some(Range)
1106 range_length: None, // u64 apparently deprecated
1107 text: new_text.to_string(),
1108 }]
1109 }
1110 lsp::TextDocumentSyncKind::INCREMENTAL => {
1111 Self::changeset_to_changes(old_text, new_text, changes, self.offset_encoding())
1112 }
1113 lsp::TextDocumentSyncKind::NONE => return None,
1114 kind => unimplemented!("{:?}", kind),
1115 };
1116
1117 self.notify::<lsp::notification::DidChangeTextDocument>(lsp::DidChangeTextDocumentParams {
1118 text_document,
1119 content_changes: changes,
1120 });
1121 Some(())
1122 }
1123
1124 pub fn text_document_did_close(&self, text_document: lsp::TextDocumentIdentifier) {
1125 self.notify::<lsp::notification::DidCloseTextDocument>(lsp::DidCloseTextDocumentParams {
1126 text_document,
1127 })
1128 }
1129
1130 // will_save / will_save_wait_until
1131
1132 pub fn text_document_did_save(
1133 &self,
1134 text_document: lsp::TextDocumentIdentifier,
1135 text: &Rope,
1136 ) -> Option<()> {
1137 let capabilities = self.capabilities.get().unwrap();
1138
1139 let include_text = match &capabilities.text_document_sync.as_ref()? {
1140 lsp::TextDocumentSyncCapability::Options(lsp::TextDocumentSyncOptions {
1141 save: options,
1142 ..
1143 }) => match options.as_ref()? {
1144 lsp::TextDocumentSyncSaveOptions::Supported(true) => false,
1145 lsp::TextDocumentSyncSaveOptions::SaveOptions(lsp::SaveOptions {
1146 include_text,
1147 }) => include_text.unwrap_or(false),
1148 lsp::TextDocumentSyncSaveOptions::Supported(false) => return None,
1149 },
1150 // see: https://github.com/microsoft/language-server-protocol/issues/288
1151 lsp::TextDocumentSyncCapability::Kind(..) => false,
1152 };
1153
1154 self.notify::<lsp::notification::DidSaveTextDocument>(lsp::DidSaveTextDocumentParams {
1155 text_document,
1156 text: include_text.then_some(text.into()),
1157 });
1158 Some(())
1159 }
1160
1161 pub fn completion(
1162 &self,
1163 text_document: lsp::TextDocumentIdentifier,
1164 position: lsp::Position,
1165 work_done_token: Option<lsp::ProgressToken>,
1166 context: lsp::CompletionContext,
1167 ) -> Option<impl Future<Output = Result<Option<lsp::CompletionResponse>>>> {
1168 let capabilities = self.capabilities.get().unwrap();
1169
1170 // Return early if the server does not support completion.
1171 capabilities.completion_provider.as_ref()?;
1172
1173 let params = lsp::CompletionParams {
1174 text_document_position: lsp::TextDocumentPositionParams {
1175 text_document,
1176 position,
1177 },
1178 context: Some(context),
1179 // TODO: support these tokens by async receiving and updating the choice list
1180 work_done_progress_params: lsp::WorkDoneProgressParams { work_done_token },
1181 partial_result_params: lsp::PartialResultParams {
1182 partial_result_token: None,
1183 },
1184 };
1185
1186 Some(self.call::<lsp::request::Completion>(params))
1187 }
1188
1189 pub fn resolve_completion_item(
1190 &self,
1191 completion_item: &lsp::CompletionItem,
1192 ) -> impl Future<Output = Result<lsp::CompletionItem>> {
1193 self.call_with_ref::<lsp::request::ResolveCompletionItem>(completion_item)
1194 }
1195
1196 pub fn resolve_code_action(
1197 &self,
1198 code_action: &lsp::CodeAction,
1199 ) -> Option<impl Future<Output = Result<lsp::CodeAction>>> {
1200 let capabilities = self.capabilities.get().unwrap();
1201
1202 // Return early if the server does not support resolving code actions.
1203 match capabilities.code_action_provider {
1204 Some(lsp::CodeActionProviderCapability::Options(lsp::CodeActionOptions {
1205 resolve_provider: Some(true),
1206 ..
1207 })) => (),
1208 _ => return None,
1209 }
1210
1211 Some(self.call_with_ref::<lsp::request::CodeActionResolveRequest>(code_action))
1212 }
1213
1214 pub fn text_document_signature_help(
1215 &self,
1216 text_document: lsp::TextDocumentIdentifier,
1217 position: lsp::Position,
1218 work_done_token: Option<lsp::ProgressToken>,
1219 ) -> Option<impl Future<Output = Result<Option<SignatureHelp>>>> {
1220 let capabilities = self.capabilities.get().unwrap();
1221
1222 // Return early if the server does not support signature help.
1223 capabilities.signature_help_provider.as_ref()?;
1224
1225 let params = lsp::SignatureHelpParams {
1226 text_document_position_params: lsp::TextDocumentPositionParams {
1227 text_document,
1228 position,
1229 },
1230 work_done_progress_params: lsp::WorkDoneProgressParams { work_done_token },
1231 context: None,
1232 // lsp::SignatureHelpContext
1233 };
1234
1235 Some(self.call::<lsp::request::SignatureHelpRequest>(params))
1236 }
1237
1238 pub fn text_document_range_inlay_hints(
1239 &self,
1240 text_document: lsp::TextDocumentIdentifier,
1241 range: lsp::Range,
1242 work_done_token: Option<lsp::ProgressToken>,
1243 ) -> Option<impl Future<Output = Result<Option<Vec<lsp::InlayHint>>>>> {
1244 let capabilities = self.capabilities.get().unwrap();
1245
1246 match capabilities.inlay_hint_provider {
1247 Some(
1248 lsp::OneOf::Left(true)
1249 | lsp::OneOf::Right(lsp::InlayHintServerCapabilities::Options(_)),
1250 ) => (),
1251 _ => return None,
1252 }
1253
1254 let params = lsp::InlayHintParams {
1255 text_document,
1256 range,
1257 work_done_progress_params: lsp::WorkDoneProgressParams { work_done_token },
1258 };
1259
1260 Some(self.call::<lsp::request::InlayHintRequest>(params))
1261 }
1262
1263 pub fn text_document_document_color(
1264 &self,
1265 text_document: lsp::TextDocumentIdentifier,
1266 work_done_token: Option<lsp::ProgressToken>,
1267 ) -> Option<impl Future<Output = Result<Vec<lsp::ColorInformation>>>> {
1268 self.capabilities.get().unwrap().color_provider.as_ref()?;
1269 let params = lsp::DocumentColorParams {
1270 text_document,
1271 work_done_progress_params: lsp::WorkDoneProgressParams {
1272 work_done_token: work_done_token.clone(),
1273 },
1274 partial_result_params: helix_lsp_types::PartialResultParams {
1275 partial_result_token: work_done_token,
1276 },
1277 };
1278
1279 Some(self.call::<lsp::request::DocumentColor>(params))
1280 }
1281
1282 pub fn text_document_document_link(
1283 &self,
1284 text_document: lsp::TextDocumentIdentifier,
1285 work_done_token: Option<lsp::ProgressToken>,
1286 ) -> Option<impl Future<Output = Result<Option<Vec<lsp::DocumentLink>>>>> {
1287 if !self.supports_feature(LanguageServerFeature::DocumentLinks) {
1288 return None;
1289 }
1290
1291 let params = lsp::DocumentLinkParams {
1292 text_document,
1293 work_done_progress_params: lsp::WorkDoneProgressParams { work_done_token },
1294 partial_result_params: lsp::PartialResultParams::default(),
1295 };
1296
1297 Some(self.call::<lsp::request::DocumentLinkRequest>(params))
1298 }
1299
1300 pub fn resolve_document_link(
1301 &self,
1302 params: lsp::DocumentLink,
1303 ) -> Option<impl Future<Output = Result<lsp::DocumentLink>>> {
1304 if !self.supports_feature(LanguageServerFeature::DocumentLinks) {
1305 return None;
1306 }
1307
1308 Some(self.call::<lsp::request::DocumentLinkResolve>(params))
1309 }
1310
1311 pub fn text_document_hover(
1312 &self,
1313 text_document: lsp::TextDocumentIdentifier,
1314 position: lsp::Position,
1315 work_done_token: Option<lsp::ProgressToken>,
1316 ) -> Option<impl Future<Output = Result<Option<lsp::Hover>>>> {
1317 let capabilities = self.capabilities.get().unwrap();
1318
1319 // Return early if the server does not support hover.
1320 match capabilities.hover_provider {
1321 Some(
1322 lsp::HoverProviderCapability::Simple(true)
1323 | lsp::HoverProviderCapability::Options(_),
1324 ) => (),
1325 _ => return None,
1326 }
1327
1328 let params = lsp::HoverParams {
1329 text_document_position_params: lsp::TextDocumentPositionParams {
1330 text_document,
1331 position,
1332 },
1333 work_done_progress_params: lsp::WorkDoneProgressParams { work_done_token },
1334 // lsp::SignatureHelpContext
1335 };
1336
1337 Some(self.call::<lsp::request::HoverRequest>(params))
1338 }
1339
1340 // formatting
1341
1342 pub fn text_document_formatting(
1343 &self,
1344 text_document: lsp::TextDocumentIdentifier,
1345 options: lsp::FormattingOptions,
1346 work_done_token: Option<lsp::ProgressToken>,
1347 ) -> Option<impl Future<Output = Result<Option<Vec<lsp::TextEdit>>>>> {
1348 let capabilities = self.capabilities.get().unwrap();
1349
1350 // Return early if the server does not support formatting.
1351 match capabilities.document_formatting_provider {
1352 Some(lsp::OneOf::Left(true) | lsp::OneOf::Right(_)) => (),
1353 _ => return None,
1354 };
1355
1356 let options = self.get_merged_formatting_options(options);
1357
1358 let params = lsp::DocumentFormattingParams {
1359 text_document,
1360 options,
1361 work_done_progress_params: lsp::WorkDoneProgressParams { work_done_token },
1362 };
1363
1364 Some(self.call::<lsp::request::Formatting>(params))
1365 }
1366
1367 pub fn text_document_range_formatting(
1368 &self,
1369 text_document: lsp::TextDocumentIdentifier,
1370 range: lsp::Range,
1371 options: lsp::FormattingOptions,
1372 work_done_token: Option<lsp::ProgressToken>,
1373 ) -> Option<impl Future<Output = Result<Option<Vec<lsp::TextEdit>>>>> {
1374 let capabilities = self.capabilities.get().unwrap();
1375
1376 // Return early if the server does not support range formatting.
1377 match capabilities.document_range_formatting_provider {
1378 Some(lsp::OneOf::Left(true) | lsp::OneOf::Right(_)) => (),
1379 _ => return None,
1380 };
1381
1382 let options = self.get_merged_formatting_options(options);
1383
1384 let params = lsp::DocumentRangeFormattingParams {
1385 text_document,
1386 range,
1387 options,
1388 work_done_progress_params: lsp::WorkDoneProgressParams { work_done_token },
1389 };
1390
1391 Some(self.call::<lsp::request::RangeFormatting>(params))
1392 }
1393
1394 pub fn text_document_diagnostic(
1395 &self,
1396 text_document: lsp::TextDocumentIdentifier,
1397 previous_result_id: Option<String>,
1398 ) -> Option<impl Future<Output = Result<lsp::DocumentDiagnosticReportResult>>> {
1399 let capabilities = self.capabilities();
1400
1401 // Return early if the server does not support pull diagnostic.
1402 let identifier = match capabilities.diagnostic_provider.as_ref()? {
1403 lsp::DiagnosticServerCapabilities::Options(cap) => cap.identifier.clone(),
1404 lsp::DiagnosticServerCapabilities::RegistrationOptions(cap) => {
1405 cap.diagnostic_options.identifier.clone()
1406 }
1407 };
1408
1409 let params = lsp::DocumentDiagnosticParams {
1410 text_document,
1411 identifier,
1412 previous_result_id,
1413 work_done_progress_params: lsp::WorkDoneProgressParams::default(),
1414 partial_result_params: lsp::PartialResultParams::default(),
1415 };
1416
1417 Some(self.call::<lsp::request::DocumentDiagnosticRequest>(params))
1418 }
1419
1420 pub fn text_document_document_highlight(
1421 &self,
1422 text_document: lsp::TextDocumentIdentifier,
1423 position: lsp::Position,
1424 work_done_token: Option<lsp::ProgressToken>,
1425 ) -> Option<impl Future<Output = Result<Option<Vec<lsp::DocumentHighlight>>>>> {
1426 let capabilities = self.capabilities.get().unwrap();
1427
1428 // Return early if the server does not support document highlight.
1429 match capabilities.document_highlight_provider {
1430 Some(lsp::OneOf::Left(true) | lsp::OneOf::Right(_)) => (),
1431 _ => return None,
1432 }
1433
1434 let params = lsp::DocumentHighlightParams {
1435 text_document_position_params: lsp::TextDocumentPositionParams {
1436 text_document,
1437 position,
1438 },
1439 work_done_progress_params: lsp::WorkDoneProgressParams { work_done_token },
1440 partial_result_params: lsp::PartialResultParams {
1441 partial_result_token: None,
1442 },
1443 };
1444
1445 Some(self.call::<lsp::request::DocumentHighlightRequest>(params))
1446 }
1447
1448 fn goto_request<
1449 T: lsp::request::Request<
1450 Params = lsp::GotoDefinitionParams,
1451 Result = Option<lsp::GotoDefinitionResponse>,
1452 >,
1453 >(
1454 &self,
1455 text_document: lsp::TextDocumentIdentifier,
1456 position: lsp::Position,
1457 work_done_token: Option<lsp::ProgressToken>,
1458 ) -> impl Future<Output = Result<T::Result>> {
1459 let params = lsp::GotoDefinitionParams {
1460 text_document_position_params: lsp::TextDocumentPositionParams {
1461 text_document,
1462 position,
1463 },
1464 work_done_progress_params: lsp::WorkDoneProgressParams { work_done_token },
1465 partial_result_params: lsp::PartialResultParams {
1466 partial_result_token: None,
1467 },
1468 };
1469
1470 self.call::<T>(params)
1471 }
1472
1473 pub fn goto_definition(
1474 &self,
1475 text_document: lsp::TextDocumentIdentifier,
1476 position: lsp::Position,
1477 work_done_token: Option<lsp::ProgressToken>,
1478 ) -> Option<impl Future<Output = Result<Option<lsp::GotoDefinitionResponse>>>> {
1479 let capabilities = self.capabilities.get().unwrap();
1480
1481 // Return early if the server does not support goto-definition.
1482 match capabilities.definition_provider {
1483 Some(lsp::OneOf::Left(true) | lsp::OneOf::Right(_)) => (),
1484 _ => return None,
1485 }
1486
1487 Some(self.goto_request::<lsp::request::GotoDefinition>(
1488 text_document,
1489 position,
1490 work_done_token,
1491 ))
1492 }
1493
1494 pub fn goto_declaration(
1495 &self,
1496 text_document: lsp::TextDocumentIdentifier,
1497 position: lsp::Position,
1498 work_done_token: Option<lsp::ProgressToken>,
1499 ) -> Option<impl Future<Output = Result<Option<lsp::GotoDefinitionResponse>>>> {
1500 let capabilities = self.capabilities.get().unwrap();
1501
1502 // Return early if the server does not support goto-declaration.
1503 match capabilities.declaration_provider {
1504 Some(
1505 lsp::DeclarationCapability::Simple(true)
1506 | lsp::DeclarationCapability::RegistrationOptions(_)
1507 | lsp::DeclarationCapability::Options(_),
1508 ) => (),
1509 _ => return None,
1510 }
1511
1512 Some(self.goto_request::<lsp::request::GotoDeclaration>(
1513 text_document,
1514 position,
1515 work_done_token,
1516 ))
1517 }
1518
1519 pub fn goto_type_definition(
1520 &self,
1521 text_document: lsp::TextDocumentIdentifier,
1522 position: lsp::Position,
1523 work_done_token: Option<lsp::ProgressToken>,
1524 ) -> Option<impl Future<Output = Result<Option<lsp::GotoDefinitionResponse>>>> {
1525 let capabilities = self.capabilities.get().unwrap();
1526
1527 // Return early if the server does not support goto-type-definition.
1528 match capabilities.type_definition_provider {
1529 Some(
1530 lsp::TypeDefinitionProviderCapability::Simple(true)
1531 | lsp::TypeDefinitionProviderCapability::Options(_),
1532 ) => (),
1533 _ => return None,
1534 }
1535
1536 Some(self.goto_request::<lsp::request::GotoTypeDefinition>(
1537 text_document,
1538 position,
1539 work_done_token,
1540 ))
1541 }
1542
1543 pub fn goto_implementation(
1544 &self,
1545 text_document: lsp::TextDocumentIdentifier,
1546 position: lsp::Position,
1547 work_done_token: Option<lsp::ProgressToken>,
1548 ) -> Option<impl Future<Output = Result<Option<lsp::GotoDefinitionResponse>>>> {
1549 let capabilities = self.capabilities.get().unwrap();
1550
1551 // Return early if the server does not support goto-definition.
1552 match capabilities.implementation_provider {
1553 Some(
1554 lsp::ImplementationProviderCapability::Simple(true)
1555 | lsp::ImplementationProviderCapability::Options(_),
1556 ) => (),
1557 _ => return None,
1558 }
1559
1560 Some(self.goto_request::<lsp::request::GotoImplementation>(
1561 text_document,
1562 position,
1563 work_done_token,
1564 ))
1565 }
1566
1567 pub fn goto_reference(
1568 &self,
1569 text_document: lsp::TextDocumentIdentifier,
1570 position: lsp::Position,
1571 include_declaration: bool,
1572 work_done_token: Option<lsp::ProgressToken>,
1573 ) -> Option<impl Future<Output = Result<Option<Vec<lsp::Location>>>>> {
1574 let capabilities = self.capabilities.get().unwrap();
1575
1576 // Return early if the server does not support goto-reference.
1577 match capabilities.references_provider {
1578 Some(lsp::OneOf::Left(true) | lsp::OneOf::Right(_)) => (),
1579 _ => return None,
1580 }
1581
1582 let params = lsp::ReferenceParams {
1583 text_document_position: lsp::TextDocumentPositionParams {
1584 text_document,
1585 position,
1586 },
1587 context: lsp::ReferenceContext {
1588 include_declaration,
1589 },
1590 work_done_progress_params: lsp::WorkDoneProgressParams { work_done_token },
1591 partial_result_params: lsp::PartialResultParams {
1592 partial_result_token: None,
1593 },
1594 };
1595
1596 Some(self.call::<lsp::request::References>(params))
1597 }
1598
1599 pub fn document_symbols(
1600 &self,
1601 text_document: lsp::TextDocumentIdentifier,
1602 ) -> Option<impl Future<Output = Result<Option<lsp::DocumentSymbolResponse>>>> {
1603 let capabilities = self.capabilities.get().unwrap();
1604
1605 // Return early if the server does not support document symbols.
1606 match capabilities.document_symbol_provider {
1607 Some(lsp::OneOf::Left(true) | lsp::OneOf::Right(_)) => (),
1608 _ => return None,
1609 }
1610
1611 let params = lsp::DocumentSymbolParams {
1612 text_document,
1613 work_done_progress_params: lsp::WorkDoneProgressParams::default(),
1614 partial_result_params: lsp::PartialResultParams::default(),
1615 };
1616
1617 Some(self.call::<lsp::request::DocumentSymbolRequest>(params))
1618 }
1619
1620 pub fn prepare_call_hierarchy(
1621 &self,
1622 text_document: lsp::TextDocumentIdentifier,
1623 position: lsp::Position,
1624 ) -> Option<impl Future<Output = Result<Option<Vec<lsp::CallHierarchyItem>>>>> {
1625 let capabilities = self.capabilities.get().unwrap();
1626
1627 match capabilities.call_hierarchy_provider {
1628 Some(
1629 lsp::CallHierarchyServerCapability::Simple(true)
1630 | lsp::CallHierarchyServerCapability::Options(_),
1631 ) => (),
1632 _ => return None,
1633 }
1634
1635 let params = lsp::CallHierarchyPrepareParams {
1636 text_document_position_params: lsp::TextDocumentPositionParams {
1637 text_document,
1638 position,
1639 },
1640 work_done_progress_params: lsp::WorkDoneProgressParams::default(),
1641 };
1642
1643 Some(self.call::<lsp::request::CallHierarchyPrepare>(params))
1644 }
1645
1646 pub fn call_hierarchy_incoming(
1647 &self,
1648 item: lsp::CallHierarchyItem,
1649 ) -> Option<impl Future<Output = Result<Option<Vec<lsp::CallHierarchyIncomingCall>>>>> {
1650 let capabilities = self.capabilities.get().unwrap();
1651
1652 match capabilities.call_hierarchy_provider {
1653 Some(
1654 lsp::CallHierarchyServerCapability::Simple(true)
1655 | lsp::CallHierarchyServerCapability::Options(_),
1656 ) => (),
1657 _ => return None,
1658 }
1659
1660 let params = lsp::CallHierarchyIncomingCallsParams {
1661 item,
1662 work_done_progress_params: lsp::WorkDoneProgressParams::default(),
1663 partial_result_params: lsp::PartialResultParams::default(),
1664 };
1665
1666 Some(self.call::<lsp::request::CallHierarchyIncomingCalls>(params))
1667 }
1668
1669 pub fn call_hierarchy_outgoing(
1670 &self,
1671 item: lsp::CallHierarchyItem,
1672 ) -> Option<impl Future<Output = Result<Option<Vec<lsp::CallHierarchyOutgoingCall>>>>> {
1673 let capabilities = self.capabilities.get().unwrap();
1674
1675 match capabilities.call_hierarchy_provider {
1676 Some(
1677 lsp::CallHierarchyServerCapability::Simple(true)
1678 | lsp::CallHierarchyServerCapability::Options(_),
1679 ) => (),
1680 _ => return None,
1681 }
1682
1683 let params = lsp::CallHierarchyOutgoingCallsParams {
1684 item,
1685 work_done_progress_params: lsp::WorkDoneProgressParams::default(),
1686 partial_result_params: lsp::PartialResultParams::default(),
1687 };
1688
1689 Some(self.call::<lsp::request::CallHierarchyOutgoingCalls>(params))
1690 }
1691
1692 pub fn prepare_rename(
1693 &self,
1694 text_document: lsp::TextDocumentIdentifier,
1695 position: lsp::Position,
1696 ) -> Option<impl Future<Output = Result<Option<lsp::PrepareRenameResponse>>>> {
1697 let capabilities = self.capabilities.get().unwrap();
1698
1699 match capabilities.rename_provider {
1700 Some(lsp::OneOf::Right(lsp::RenameOptions {
1701 prepare_provider: Some(true),
1702 ..
1703 })) => (),
1704 _ => return None,
1705 }
1706
1707 let params = lsp::TextDocumentPositionParams {
1708 text_document,
1709 position,
1710 };
1711
1712 Some(self.call::<lsp::request::PrepareRenameRequest>(params))
1713 }
1714
1715 // empty string to get all symbols
1716 pub fn workspace_symbols(
1717 &self,
1718 query: String,
1719 ) -> Option<impl Future<Output = Result<Option<lsp::WorkspaceSymbolResponse>>>> {
1720 let capabilities = self.capabilities.get().unwrap();
1721
1722 // Return early if the server does not support workspace symbols.
1723 match capabilities.workspace_symbol_provider {
1724 Some(lsp::OneOf::Left(true) | lsp::OneOf::Right(_)) => (),
1725 _ => return None,
1726 }
1727
1728 let params = lsp::WorkspaceSymbolParams {
1729 query,
1730 work_done_progress_params: lsp::WorkDoneProgressParams::default(),
1731 partial_result_params: lsp::PartialResultParams::default(),
1732 };
1733
1734 Some(self.call::<lsp::request::WorkspaceSymbolRequest>(params))
1735 }
1736
1737 pub fn code_actions(
1738 &self,
1739 text_document: lsp::TextDocumentIdentifier,
1740 range: lsp::Range,
1741 context: lsp::CodeActionContext,
1742 ) -> Option<impl Future<Output = Result<Option<Vec<lsp::CodeActionOrCommand>>>>> {
1743 let capabilities = self.capabilities.get().unwrap();
1744
1745 // Return early if the server does not support code actions.
1746 match capabilities.code_action_provider {
1747 Some(
1748 lsp::CodeActionProviderCapability::Simple(true)
1749 | lsp::CodeActionProviderCapability::Options(_),
1750 ) => (),
1751 _ => return None,
1752 }
1753
1754 let params = lsp::CodeActionParams {
1755 text_document,
1756 range,
1757 context,
1758 work_done_progress_params: lsp::WorkDoneProgressParams::default(),
1759 partial_result_params: lsp::PartialResultParams::default(),
1760 };
1761
1762 Some(self.call::<lsp::request::CodeActionRequest>(params))
1763 }
1764
1765 pub fn rename_symbol(
1766 &self,
1767 text_document: lsp::TextDocumentIdentifier,
1768 position: lsp::Position,
1769 new_name: String,
1770 ) -> Option<impl Future<Output = Result<Option<lsp::WorkspaceEdit>>>> {
1771 if !self.supports_feature(LanguageServerFeature::RenameSymbol) {
1772 return None;
1773 }
1774
1775 let params = lsp::RenameParams {
1776 text_document_position: lsp::TextDocumentPositionParams {
1777 text_document,
1778 position,
1779 },
1780 new_name,
1781 work_done_progress_params: lsp::WorkDoneProgressParams {
1782 work_done_token: None,
1783 },
1784 };
1785
1786 Some(self.call::<lsp::request::Rename>(params))
1787 }
1788
1789 pub fn command(
1790 &self,
1791 command: lsp::Command,
1792 ) -> Option<impl Future<Output = Result<Option<Value>>>> {
1793 let capabilities = self.capabilities.get().unwrap();
1794
1795 // Return early if the language server does not support executing commands.
1796 capabilities.execute_command_provider.as_ref()?;
1797
1798 let params = lsp::ExecuteCommandParams {
1799 command: command.command,
1800 arguments: command.arguments.unwrap_or_default(),
1801 work_done_progress_params: lsp::WorkDoneProgressParams {
1802 work_done_token: None,
1803 },
1804 };
1805
1806 Some(self.call::<lsp::request::ExecuteCommand>(params))
1807 }
1808
1809 pub fn did_change_watched_files(&self, changes: Vec<lsp::FileEvent>) {
1810 self.notify::<lsp::notification::DidChangeWatchedFiles>(lsp::DidChangeWatchedFilesParams {
1811 changes,
1812 })
1813 }
1814 }