Debian Codegraph @

helix-lsp/src/client.rs

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