Debian Codegraph @

helix-term/src/handlers/code_action_hint.rs

raw symbols SCIP
1 use std::{collections::HashSet, time::Duration};
2
3 use futures_util::stream::FuturesUnordered;
4 use helix_event::{cancelable_future, register_hook, send_blocking, AsyncHook};
5 use helix_lsp::lsp::{CodeAction, CodeActionOrCommand, CodeActionTriggerKind};
6 use helix_view::{
7 events::{
8 ConfigDidChange, DiagnosticsDidChange, DocumentDidChange, DocumentDidOpen,
9 LanguageServerExited, LanguageServerInitialized, SelectionDidChange,
10 },
11 handlers::{lsp::CodeActionHintEvent, Handlers},
12 DocumentId, Editor, ViewId,
13 };
14 use tokio::time::Instant;
15 use tokio_stream::StreamExt;
16
17 use crate::{commands::code_actions_for_range, job};
18
19 #[derive(Debug, Default)]
20 pub(super) struct Handler {
21 doc_ids: HashSet<(DocumentId, ViewId)>,
22 }
23
24 impl AsyncHook for Handler {
25 type Event = CodeActionHintEvent;
26
27 fn handle_event(
28 &mut self,
29 event: Self::Event,
30 _timeout: Option<tokio::time::Instant>,
31 ) -> Option<tokio::time::Instant> {
32 self.doc_ids.insert((event.document_id, event.view_id));
33 Some(Instant::now() + Duration::from_millis(200))
34 }
35
36 fn finish_debounce(&mut self) {
37 let ids = std::mem::take(&mut self.doc_ids);
38 job::dispatch_blocking(move |editor, _| {
39 for (doc_id, view_id) in ids {
40 request_code_action_hint(editor, doc_id, view_id);
41 }
42 })
43 }
44 }
45
46 fn request_code_action_hint(editor: &mut Editor, doc_id: DocumentId, view_id: ViewId) {
47 if !editor.config().code_action_hint() {
48 return;
49 }
50
51 let Some(doc) = editor.document_mut(doc_id) else {
52 return;
53 };
54
55 doc.ensure_view_init(view_id);
56
57 let selection_range = doc.selection(view_id).primary();
58 let mut futures: FuturesUnordered<_> =
59 code_actions_for_range(doc, selection_range, None, CodeActionTriggerKind::AUTOMATIC)
60 .into_iter()
61 .map(|(request, _)| async move {
62 let Some(mut actions) = request.await? else {
63 return anyhow::Ok(Vec::new());
64 };
65
66 // remove disabled code actions
67 actions.retain(|action| {
68 matches!(
69 action,
70 CodeActionOrCommand::Command(_)
71 | CodeActionOrCommand::CodeAction(CodeAction { disabled: None, .. })
72 )
73 });
74
75 Ok(actions)
76 })
77 .collect();
78
79 if futures.is_empty() {
80 doc.clear_code_action_hints(view_id);
81 return;
82 };
83
84 let cancel = doc.code_action_controller(view_id).restart();
85
86 tokio::spawn(async move {
87 let mut actions = Vec::new();
88
89 loop {
90 match cancelable_future(futures.next(), &cancel).await {
91 Some(output) => match output {
92 Some(Ok(mut lsp_items)) => actions.append(&mut lsp_items),
93 Some(Err(err)) => log::error!("while gathering code actions: {err}"),
94 None => break,
95 },
96 // The request was cancelled.
97 None => return,
98 }
99 }
100
101 job::dispatch(move |editor, _| {
102 apply_code_action_hint(editor, doc_id, view_id, actions);
103 })
104 .await;
105 });
106 }
107
108 fn apply_code_action_hint(
109 editor: &mut Editor,
110 doc_id: DocumentId,
111 view_id: ViewId,
112 code_actions: Vec<CodeActionOrCommand>,
113 ) {
114 let Some(doc) = editor.document_mut(doc_id) else {
115 return;
116 };
117 if code_actions.is_empty() {
118 doc.clear_code_action_hints(view_id);
119 return;
120 }
121 doc.set_code_action_hints(view_id);
122 }
123
124 pub(super) fn register_hooks(handlers: &Handlers) {
125 let tx = handlers.code_action_hint.clone();
126 register_hook!(move |event: &mut SelectionDidChange<'_>| {
127 if event.doc.config.load().code_action_hint() {
128 let doc_id = event.doc.id();
129 let view_id = event.view;
130
131 // clear stale hints
132 event.doc.clear_code_action_hints(view_id);
133 send_blocking(
134 &tx,
135 CodeActionHintEvent {
136 document_id: doc_id,
137 view_id,
138 },
139 );
140 }
141 Ok(())
142 });
143
144 let tx = handlers.code_action_hint.clone();
145 register_hook!(move |event: &mut DocumentDidOpen<'_>| {
146 if !event.editor.config().code_action_hint() {
147 return Ok(());
148 }
149 let view_id = event.editor.tree.focus;
150 if event.editor.tree.try_get(view_id).is_none() {
151 return Ok(());
152 }
153 send_blocking(
154 &tx,
155 CodeActionHintEvent {
156 document_id: event.doc,
157 view_id,
158 },
159 );
160 Ok(())
161 });
162
163 let tx = handlers.code_action_hint.clone();
164 register_hook!(move |event: &mut DiagnosticsDidChange<'_>| {
165 if event.editor.config().code_action_hint() {
166 let doc_id = event.doc;
167 let views: Vec<_> = event
168 .editor
169 .tree
170 .views()
171 .map(|(view, _)| (view.id, view.doc))
172 .collect();
173 for (view_id, view_doc) in views {
174 if view_doc == doc_id {
175 send_blocking(
176 &tx,
177 CodeActionHintEvent {
178 document_id: doc_id,
179 view_id,
180 },
181 );
182 }
183 }
184 }
185 Ok(())
186 });
187
188 let tx = handlers.code_action_hint.clone();
189 register_hook!(move |event: &mut DocumentDidChange<'_>| {
190 if event.doc.config.load().code_action_hint() && !event.ghost_transaction {
191 let doc_id = event.doc.id();
192 let view_id = event.view;
193
194 // clear stale hints
195 event.doc.clear_code_action_hints(view_id);
196 send_blocking(
197 &tx,
198 CodeActionHintEvent {
199 document_id: doc_id,
200 view_id,
201 },
202 );
203 }
204 Ok(())
205 });
206
207 let tx = handlers.code_action_hint.clone();
208 register_hook!(move |event: &mut LanguageServerInitialized<'_>| {
209 if !event.editor.config().code_action_hint() {
210 return Ok(());
211 }
212 let view_id = event.editor.tree.focus;
213 let Some(view) = event.editor.tree.try_get(view_id) else {
214 return Ok(());
215 };
216 let doc_id = view.doc;
217 send_blocking(
218 &tx,
219 CodeActionHintEvent {
220 document_id: doc_id,
221 view_id,
222 },
223 );
224 Ok(())
225 });
226
227 register_hook!(move |event: &mut LanguageServerExited<'_>| {
228 for doc in event.editor.documents_mut() {
229 if doc.supports_language_server(event.server_id) {
230 doc.clear_all_code_action_hints();
231 }
232 }
233 Ok(())
234 });
235
236 let tx = handlers.code_action_hint.clone();
237 register_hook!(move |event: &mut ConfigDidChange<'_>| {
238 // When code action hints are turned on, request them immediately
239 // for the focused view instead of waiting for the next selection change.
240 if !event.old.code_action_hint() && event.new.code_action_hint() {
241 let view_id = event.editor.tree.focus;
242 let Some(view) = event.editor.tree.try_get(view_id) else {
243 return Ok(());
244 };
245
246 send_blocking(
247 &tx,
248 CodeActionHintEvent {
249 document_id: view.doc,
250 view_id,
251 },
252 );
253 return Ok(());
254 }
255
256 // When code action hints are turned off, clear any that were
257 // previously rendered across open documents.
258 if event.old.code_action_hint() && !event.new.code_action_hint() {
259 for doc in event.editor.documents_mut() {
260 doc.clear_all_code_action_hints();
261 }
262 }
263 Ok(())
264 });
265 }