Debian Codegraph @

helix-term/src/handlers/completion/resolve.rs

raw symbols SCIP
1 use std::sync::Arc;
2
3 use helix_lsp::lsp;
4 use tokio::sync::mpsc::Sender;
5 use tokio::time::{Duration, Instant};
6
7 use helix_event::{send_blocking, AsyncHook, TaskController, TaskHandle};
8 use helix_view::Editor;
9
10 use super::LspCompletionItem;
11 use crate::handlers::completion::CompletionItem;
12 use crate::job;
13
14 /// A hook for resolving incomplete completion items.
15 ///
16 /// From the [LSP spec](https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification/#textDocument_completion):
17 ///
18 /// > If computing full completion items is expensive, servers can additionally provide a
19 /// > handler for the completion item resolve request. ...
20 /// > A typical use case is for example: the `textDocument/completion` request doesn't fill
21 /// > in the `documentation` property for returned completion items since it is expensive
22 /// > to compute. When the item is selected in the user interface then a
23 /// > 'completionItem/resolve' request is sent with the selected completion item as a parameter.
24 /// > The returned completion item should have the documentation property filled in.
25 pub struct ResolveHandler {
26 last_request: Option<Arc<LspCompletionItem>>,
27 resolver: Sender<ResolveRequest>,
28 }
29
30 impl ResolveHandler {
31 pub fn new() -> ResolveHandler {
32 ResolveHandler {
33 last_request: None,
34 resolver: ResolveTimeout::default().spawn(),
35 }
36 }
37
38 pub fn ensure_item_resolved(&mut self, editor: &mut Editor, item: &mut LspCompletionItem) {
39 if item.resolved {
40 return;
41 }
42 // We consider an item to be fully resolved if it has non-empty, none-`None` details,
43 // docs and additional text-edits. Ideally we could use `is_some` instead of this
44 // check but some language servers send values like `Some([])` for additional text
45 // edits although the items need to be resolved. This is probably a consequence of
46 // how `null` works in the JavaScript world.
47 let is_resolved = item
48 .item
49 .documentation
50 .as_ref()
51 .is_some_and(|docs| match docs {
52 lsp::Documentation::String(text) => !text.is_empty(),
53 lsp::Documentation::MarkupContent(markup) => !markup.value.is_empty(),
54 })
55 && item
56 .item
57 .detail
58 .as_ref()
59 .is_some_and(|detail| !detail.is_empty())
60 && item
61 .item
62 .additional_text_edits
63 .as_ref()
64 .is_some_and(|edits| !edits.is_empty());
65 if is_resolved {
66 item.resolved = true;
67 return;
68 }
69 if self.last_request.as_deref().is_some_and(|it| it == item) {
70 return;
71 }
72 let Some(ls) = editor.language_servers.get_by_id(item.provider).cloned() else {
73 item.resolved = true;
74 return;
75 };
76 if matches!(
77 ls.capabilities().completion_provider,
78 Some(lsp::CompletionOptions {
79 resolve_provider: Some(true),
80 ..
81 })
82 ) {
83 let item = Arc::new(item.clone());
84 self.last_request = Some(item.clone());
85 send_blocking(&self.resolver, ResolveRequest { item, ls })
86 } else {
87 item.resolved = true;
88 }
89 }
90 }
91
92 struct ResolveRequest {
93 item: Arc<LspCompletionItem>,
94 ls: Arc<helix_lsp::Client>,
95 }
96
97 #[derive(Default)]
98 struct ResolveTimeout {
99 next_request: Option<ResolveRequest>,
100 in_flight: Option<Arc<LspCompletionItem>>,
101 task_controller: TaskController,
102 }
103
104 impl AsyncHook for ResolveTimeout {
105 type Event = ResolveRequest;
106
107 fn handle_event(
108 &mut self,
109 request: Self::Event,
110 timeout: Option<tokio::time::Instant>,
111 ) -> Option<tokio::time::Instant> {
112 if self
113 .next_request
114 .as_ref()
115 .is_some_and(|old_request| old_request.item == request.item)
116 {
117 timeout
118 } else if self
119 .in_flight
120 .as_ref()
121 .is_some_and(|old_request| old_request.item == request.item.item)
122 {
123 self.next_request = None;
124 None
125 } else {
126 self.next_request = Some(request);
127 Some(Instant::now() + Duration::from_millis(150))
128 }
129 }
130
131 fn finish_debounce(&mut self) {
132 let Some(request) = self.next_request.take() else {
133 return;
134 };
135 let token = self.task_controller.restart();
136 self.in_flight = Some(request.item.clone());
137 tokio::spawn(request.execute(token));
138 }
139 }
140
141 impl ResolveRequest {
142 async fn execute(self, cancel: TaskHandle) {
143 let future = self.ls.resolve_completion_item(&self.item.item);
144 let Some(resolved_item) = helix_event::cancelable_future(future, cancel).await else {
145 return;
146 };
147 job::dispatch(move |_, compositor| {
148 if let Some(completion) = &mut compositor
149 .find::<crate::ui::EditorView>()
150 .unwrap()
151 .completion
152 {
153 let resolved_item = CompletionItem::Lsp(match resolved_item {
154 Ok(item) => LspCompletionItem {
155 item,
156 resolved: true,
157 ..*self.item
158 },
159 Err(err) => {
160 log::error!("completion resolve request failed: {err}");
161 // set item to resolved so we don't request it again
162 // we could also remove it but that oculd be odd ui
163 let mut item = (*self.item).clone();
164 item.resolved = true;
165 item
166 }
167 });
168 completion.replace_item(&*self.item, resolved_item);
169 };
170 })
171 .await
172 }
173 }