Debian Codegraph @

helix-term/src/commands/lsp.rs

raw symbols SCIP
1 use futures_util::{stream::FuturesUnordered, FutureExt};
2 use helix_lsp::{
3 block_on,
4 lsp::{
5 self, CodeAction, CodeActionKind, CodeActionOrCommand, CodeActionTriggerKind,
6 DiagnosticSeverity, NumberOrString,
7 },
8 util::{diagnostic_to_lsp_diagnostic, lsp_range_to_range, range_to_lsp_range},
9 Client, LanguageServerId, OffsetEncoding,
10 };
11 use tokio_stream::StreamExt;
12 use tui::{text::Span, widgets::Row};
13
14 use super::{align_view, push_jump, Align, Context, Editor};
15
16 use helix_core::{
17 diagnostic::DiagnosticProvider, syntax::config::LanguageServerFeature,
18 text_annotations::InlineAnnotation, Selection, Uri,
19 };
20 use helix_stdx::path;
21 use helix_view::{
22 action::Action as CodeActionItem,
23 document::{DocumentInlayHints, DocumentInlayHintsId},
24 editor::Action,
25 handlers::lsp::SignatureHelpInvoked,
26 theme::Style,
27 Document, DocumentId, View,
28 };
29
30 use crate::{
31 compositor::{self, Compositor},
32 job::{Callback, Job},
33 ui::{self, overlay::overlaid, FileLocation, Picker, Popup, PromptEvent},
34 };
35
36 use std::{
37 collections::{HashSet, VecDeque},
38 fmt::Display,
39 future::Future,
40 path::Path,
41 };
42
43 /// Gets the first language server that is attached to a document which supports a specific feature.
44 /// If there is no configured language server that supports the feature, this displays a status message.
45 /// Using this macro in a context where the editor automatically queries the LSP
46 /// (instead of when the user explicitly does so via a keybind like `gd`)
47 /// will spam the "No configured language server supports \<feature>" status message confusingly.
48 #[macro_export]
49 macro_rules! language_server_with_feature {
50 ($editor:expr, $doc:expr, $feature:expr) => {{
51 let language_server = $doc.language_servers_with_feature($feature).next();
52 match language_server {
53 Some(language_server) => language_server,
54 None => {
55 $editor.set_error(format!(
56 "No configured language server supports {}",
57 $feature
58 ));
59 return;
60 }
61 }
62 }};
63 }
64
65 /// A wrapper around `lsp::Location` that swaps out the LSP URI for `helix_core::Uri` and adds
66 /// the server's offset encoding.
67 #[derive(Debug, Clone, PartialEq, Eq)]
68 struct Location {
69 uri: Uri,
70 range: lsp::Range,
71 offset_encoding: OffsetEncoding,
72 }
73
74 fn lsp_location_to_location(
75 location: lsp::Location,
76 offset_encoding: OffsetEncoding,
77 ) -> Option<Location> {
78 let uri = match location.uri.try_into() {
79 Ok(uri) => uri,
80 Err(err) => {
81 log::warn!("discarding invalid or unsupported URI: {err}");
82 return None;
83 }
84 };
85 Some(Location {
86 uri,
87 range: location.range,
88 offset_encoding,
89 })
90 }
91
92 struct SymbolInformationItem {
93 location: Location,
94 symbol: lsp::SymbolInformation,
95 }
96
97 struct DiagnosticStyles {
98 hint: Style,
99 info: Style,
100 warning: Style,
101 error: Style,
102 }
103
104 struct PickerDiagnostic {
105 location: Location,
106 diag: lsp::Diagnostic,
107 }
108
109 fn location_to_file_location(location: &Location) -> Option<FileLocation<'_>> {
110 let path = location.uri.as_path()?;
111 let line = Some((
112 location.range.start.line as usize,
113 location.range.end.line as usize,
114 ));
115 Some((path.into(), line))
116 }
117
118 fn jump_to_location(editor: &mut Editor, location: &Location, action: Action) {
119 let (view, doc) = current!(editor);
120 push_jump(view, doc);
121
122 let Some(path) = location.uri.as_path() else {
123 let err = format!("unable to convert URI to filepath: {:?}", location.uri);
124 editor.set_error(err);
125 return;
126 };
127 jump_to_position(
128 editor,
129 path,
130 location.range,
131 location.offset_encoding,
132 action,
133 );
134 }
135
136 fn jump_to_position(
137 editor: &mut Editor,
138 path: &Path,
139 range: lsp::Range,
140 offset_encoding: OffsetEncoding,
141 action: Action,
142 ) {
143 let doc = match editor.open(path, action) {
144 Ok(id) => doc_mut!(editor, &id),
145 Err(err) => {
146 let err = format!("failed to open path: {:?}: {:?}", path, err);
147 editor.set_error(err);
148 return;
149 }
150 };
151 let view = view_mut!(editor);
152 // TODO: convert inside server
153 let new_range = if let Some(new_range) = lsp_range_to_range(doc.text(), range, offset_encoding)
154 {
155 new_range
156 } else {
157 log::warn!("lsp position out of bounds - {:?}", range);
158 return;
159 };
160 // we flip the range so that the cursor sits on the start of the symbol
161 // (for example start of the function).
162 doc.set_selection(view.id, Selection::single(new_range.head, new_range.anchor));
163 if action.align_view(view, doc.id()) {
164 align_view(doc, view, Align::Center);
165 }
166 }
167
168 fn display_symbol_kind(kind: lsp::SymbolKind) -> &'static str {
169 match kind {
170 lsp::SymbolKind::FILE => "file",
171 lsp::SymbolKind::MODULE => "module",
172 lsp::SymbolKind::NAMESPACE => "namespace",
173 lsp::SymbolKind::PACKAGE => "package",
174 lsp::SymbolKind::CLASS => "class",
175 lsp::SymbolKind::METHOD => "method",
176 lsp::SymbolKind::PROPERTY => "property",
177 lsp::SymbolKind::FIELD => "field",
178 lsp::SymbolKind::CONSTRUCTOR => "construct",
179 lsp::SymbolKind::ENUM => "enum",
180 lsp::SymbolKind::INTERFACE => "interface",
181 lsp::SymbolKind::FUNCTION => "function",
182 lsp::SymbolKind::VARIABLE => "variable",
183 lsp::SymbolKind::CONSTANT => "constant",
184 lsp::SymbolKind::STRING => "string",
185 lsp::SymbolKind::NUMBER => "number",
186 lsp::SymbolKind::BOOLEAN => "boolean",
187 lsp::SymbolKind::ARRAY => "array",
188 lsp::SymbolKind::OBJECT => "object",
189 lsp::SymbolKind::KEY => "key",
190 lsp::SymbolKind::NULL => "null",
191 lsp::SymbolKind::ENUM_MEMBER => "enummem",
192 lsp::SymbolKind::STRUCT => "struct",
193 lsp::SymbolKind::EVENT => "event",
194 lsp::SymbolKind::OPERATOR => "operator",
195 lsp::SymbolKind::TYPE_PARAMETER => "typeparam",
196 _ => {
197 log::warn!("Unknown symbol kind: {:?}", kind);
198 ""
199 }
200 }
201 }
202
203 #[derive(Copy, Clone, PartialEq)]
204 enum DiagnosticsFormat {
205 ShowSourcePath,
206 HideSourcePath,
207 }
208
209 type DiagnosticsPicker = Picker<PickerDiagnostic, DiagnosticStyles>;
210
211 fn diag_picker(
212 cx: &Context,
213 diagnostics: impl IntoIterator<Item = (Uri, Vec<(lsp::Diagnostic, DiagnosticProvider)>)>,
214 format: DiagnosticsFormat,
215 ) -> DiagnosticsPicker {
216 // TODO: drop current_path comparison and instead use workspace: bool flag?
217
218 // flatten the map to a vec of (url, diag) pairs
219 let mut flat_diag = Vec::new();
220 for (uri, diags) in diagnostics {
221 flat_diag.reserve(diags.len());
222
223 for (diag, provider) in diags {
224 if let Some(ls) = provider
225 .language_server_id()
226 .and_then(|id| cx.editor.language_server_by_id(id))
227 {
228 flat_diag.push(PickerDiagnostic {
229 location: Location {
230 uri: uri.clone(),
231 range: diag.range,
232 offset_encoding: ls.offset_encoding(),
233 },
234 diag,
235 });
236 }
237 }
238 }
239
240 flat_diag.sort_by(|a, b| {
241 a.diag
242 .severity
243 .unwrap_or(lsp::DiagnosticSeverity::HINT)
244 .cmp(&b.diag.severity.unwrap_or(lsp::DiagnosticSeverity::HINT))
245 });
246
247 let styles = DiagnosticStyles {
248 hint: cx.editor.theme.get("hint"),
249 info: cx.editor.theme.get("info"),
250 warning: cx.editor.theme.get("warning"),
251 error: cx.editor.theme.get("error"),
252 };
253
254 let mut columns = vec![
255 ui::PickerColumn::new(
256 "severity",
257 |item: &PickerDiagnostic, styles: &DiagnosticStyles| {
258 match item.diag.severity {
259 Some(DiagnosticSeverity::HINT) => Span::styled("HINT", styles.hint),
260 Some(DiagnosticSeverity::INFORMATION) => Span::styled("INFO", styles.info),
261 Some(DiagnosticSeverity::WARNING) => Span::styled("WARN", styles.warning),
262 Some(DiagnosticSeverity::ERROR) => Span::styled("ERROR", styles.error),
263 _ => Span::raw(""),
264 }
265 .into()
266 },
267 ),
268 ui::PickerColumn::new("source", |item: &PickerDiagnostic, _| {
269 item.diag.source.as_deref().unwrap_or("").into()
270 }),
271 ui::PickerColumn::new("code", |item: &PickerDiagnostic, _| {
272 match item.diag.code.as_ref() {
273 Some(NumberOrString::Number(n)) => n.to_string().into(),
274 Some(NumberOrString::String(s)) => s.as_str().into(),
275 None => "".into(),
276 }
277 }),
278 ui::PickerColumn::new("message", |item: &PickerDiagnostic, _| {
279 item.diag.message.as_str().into()
280 }),
281 ];
282 let mut primary_column = 3; // message
283
284 if format == DiagnosticsFormat::ShowSourcePath {
285 columns.insert(
286 // between message code and message
287 3,
288 ui::PickerColumn::new("path", |item: &PickerDiagnostic, _| {
289 if let Some(path) = item.location.uri.as_path() {
290 path::get_truncated_path(path)
291 .to_string_lossy()
292 .to_string()
293 .into()
294 } else {
295 Default::default()
296 }
297 }),
298 );
299 primary_column += 1;
300 }
301
302 Picker::new(
303 columns,
304 primary_column,
305 flat_diag,
306 styles,
307 move |cx, diag, action| {
308 jump_to_location(cx.editor, &diag.location, action);
309 let (view, doc) = current!(cx.editor);
310 view.diagnostics_handler
311 .immediately_show_diagnostic(doc, view.id);
312 },
313 )
314 .with_preview(move |_editor, diag| location_to_file_location(&diag.location))
315 .truncate_start(false)
316 }
317
318 pub fn symbol_picker(cx: &mut Context) {
319 fn nested_to_flat(
320 list: &mut Vec<SymbolInformationItem>,
321 file: &lsp::TextDocumentIdentifier,
322 uri: &Uri,
323 symbol: lsp::DocumentSymbol,
324 offset_encoding: OffsetEncoding,
325 ) {
326 #[allow(deprecated)]
327 list.push(SymbolInformationItem {
328 symbol: lsp::SymbolInformation {
329 name: symbol.name,
330 kind: symbol.kind,
331 tags: symbol.tags,
332 deprecated: symbol.deprecated,
333 location: lsp::Location::new(file.uri.clone(), symbol.selection_range),
334 container_name: None,
335 },
336 location: Location {
337 uri: uri.clone(),
338 range: symbol.selection_range,
339 offset_encoding,
340 },
341 });
342 for child in symbol.children.into_iter().flatten() {
343 nested_to_flat(list, file, uri, child, offset_encoding);
344 }
345 }
346 let doc = doc!(cx.editor);
347
348 let mut seen_language_servers = HashSet::new();
349
350 let mut futures: FuturesUnordered<_> = doc
351 .language_servers_with_feature(LanguageServerFeature::DocumentSymbols)
352 .filter(|ls| seen_language_servers.insert(ls.id()))
353 .map(|language_server| {
354 let request = language_server.document_symbols(doc.identifier()).unwrap();
355 let offset_encoding = language_server.offset_encoding();
356 let doc_id = doc.identifier();
357 let doc_uri = doc
358 .uri()
359 .expect("docs with active language servers must be backed by paths");
360
361 async move {
362 let symbols = match request.await? {
363 Some(symbols) => symbols,
364 None => return anyhow::Ok(vec![]),
365 };
366 // lsp has two ways to represent symbols (flat/nested)
367 // convert the nested variant to flat, so that we have a homogeneous list
368 let symbols = match symbols {
369 lsp::DocumentSymbolResponse::Flat(symbols) => symbols
370 .into_iter()
371 .map(|symbol| SymbolInformationItem {
372 location: Location {
373 uri: doc_uri.clone(),
374 range: symbol.location.range,
375 offset_encoding,
376 },
377 symbol,
378 })
379 .collect(),
380 lsp::DocumentSymbolResponse::Nested(symbols) => {
381 let mut flat_symbols = Vec::new();
382 for symbol in symbols {
383 nested_to_flat(
384 &mut flat_symbols,
385 &doc_id,
386 &doc_uri,
387 symbol,
388 offset_encoding,
389 )
390 }
391 flat_symbols
392 }
393 };
394 Ok(symbols)
395 }
396 })
397 .collect();
398
399 if futures.is_empty() {
400 cx.editor
401 .set_error("No configured language server supports document symbols");
402 return;
403 }
404
405 cx.jobs.callback(async move {
406 let mut symbols = Vec::new();
407 while let Some(response) = futures.next().await {
408 match response {
409 Ok(mut items) => symbols.append(&mut items),
410 Err(err) => log::error!("Error requesting document symbols: {err}"),
411 }
412 }
413 let call = move |_editor: &mut Editor, compositor: &mut Compositor| {
414 let columns = [
415 ui::PickerColumn::new("kind", |item: &SymbolInformationItem, _| {
416 display_symbol_kind(item.symbol.kind).into()
417 }),
418 // Some symbols in the document symbol picker may have a URI that isn't
419 // the current file. It should be rare though, so we concatenate that
420 // URI in with the symbol name in this picker.
421 ui::PickerColumn::new("name", |item: &SymbolInformationItem, _| {
422 item.symbol.name.as_str().into()
423 }),
424 ui::PickerColumn::new("container", |item: &SymbolInformationItem, _| {
425 item.symbol
426 .container_name
427 .as_deref()
428 .unwrap_or_default()
429 .into()
430 }),
431 ];
432
433 let picker = Picker::new(
434 columns,
435 1, // name column
436 symbols,
437 (),
438 move |cx, item, action| {
439 jump_to_location(cx.editor, &item.location, action);
440 },
441 )
442 .with_preview(move |_editor, item| location_to_file_location(&item.location))
443 .truncate_start(false);
444
445 compositor.push(Box::new(overlaid(picker)))
446 };
447
448 Ok(Callback::EditorCompositor(Box::new(call)))
449 });
450 }
451
452 pub fn workspace_symbol_picker(cx: &mut Context) {
453 use crate::ui::picker::Injector;
454
455 let doc = doc!(cx.editor);
456 if doc
457 .language_servers_with_feature(LanguageServerFeature::WorkspaceSymbols)
458 .count()
459 == 0
460 {
461 cx.editor
462 .set_error("No configured language server supports workspace symbols");
463 return;
464 }
465
466 let get_symbols = |pattern: &str, editor: &mut Editor, _data, injector: &Injector<_, _>| {
467 let doc = doc!(editor);
468 let mut seen_language_servers = HashSet::new();
469 let mut futures: FuturesUnordered<_> = doc
470 .language_servers_with_feature(LanguageServerFeature::WorkspaceSymbols)
471 .filter(|ls| seen_language_servers.insert(ls.id()))
472 .map(|language_server| {
473 let request = language_server
474 .workspace_symbols(pattern.to_string())
475 .unwrap();
476 let offset_encoding = language_server.offset_encoding();
477 async move {
478 let symbols = request
479 .await?
480 .and_then(|resp| match resp {
481 lsp::WorkspaceSymbolResponse::Flat(symbols) => Some(symbols),
482 lsp::WorkspaceSymbolResponse::Nested(_) => None,
483 })
484 .unwrap_or_default();
485
486 let response: Vec<_> = symbols
487 .into_iter()
488 .filter_map(|symbol| {
489 let uri = match Uri::try_from(&symbol.location.uri) {
490 Ok(uri) => uri,
491 Err(err) => {
492 log::warn!("discarding symbol with invalid URI: {err}");
493 return None;
494 }
495 };
496 Some(SymbolInformationItem {
497 location: Location {
498 uri,
499 range: symbol.location.range,
500 offset_encoding,
501 },
502 symbol,
503 })
504 })
505 .collect();
506
507 anyhow::Ok(response)
508 }
509 })
510 .collect();
511
512 if futures.is_empty() {
513 editor.set_error("No configured language server supports workspace symbols");
514 }
515
516 let injector = injector.clone();
517 async move {
518 while let Some(response) = futures.next().await {
519 match response {
520 Ok(items) => {
521 for item in items {
522 injector.push(item)?;
523 }
524 }
525 Err(err) => log::error!("Error requesting workspace symbols: {err}"),
526 }
527 }
528 Ok(())
529 }
530 .boxed()
531 };
532 let columns = [
533 ui::PickerColumn::new("kind", |item: &SymbolInformationItem, _| {
534 display_symbol_kind(item.symbol.kind).into()
535 }),
536 ui::PickerColumn::new("name", |item: &SymbolInformationItem, _| {
537 item.symbol.name.as_str().into()
538 })
539 .without_filtering(),
540 ui::PickerColumn::new("container", |item: &SymbolInformationItem, _| {
541 item.symbol
542 .container_name
543 .as_deref()
544 .unwrap_or_default()
545 .into()
546 }),
547 ui::PickerColumn::new("path", |item: &SymbolInformationItem, _| {
548 if let Some(path) = item.location.uri.as_path() {
549 path::get_relative_path(path)
550 .to_string_lossy()
551 .to_string()
552 .into()
553 } else {
554 item.symbol.location.uri.to_string().into()
555 }
556 }),
557 ];
558
559 let picker = Picker::new(
560 columns,
561 1, // name column
562 [],
563 (),
564 move |cx, item, action| {
565 jump_to_location(cx.editor, &item.location, action);
566 },
567 )
568 .with_preview(|_editor, item| location_to_file_location(&item.location))
569 .with_dynamic_query(get_symbols, None)
570 .truncate_start(false);
571
572 cx.push_layer(Box::new(overlaid(picker)));
573 }
574
575 pub fn diagnostics_picker(cx: &mut Context) {
576 let doc = doc!(cx.editor);
577 if let Some(uri) = doc.uri() {
578 let diagnostics = cx.editor.diagnostics.get(&uri).cloned().unwrap_or_default();
579 let picker = diag_picker(cx, [(uri, diagnostics)], DiagnosticsFormat::HideSourcePath);
580 cx.push_layer(Box::new(overlaid(picker)));
581 }
582 }
583
584 pub fn workspace_diagnostics_picker(cx: &mut Context) {
585 // TODO not yet filtered by LanguageServerFeature, need to do something similar as Document::shown_diagnostics here for all open documents
586 let diagnostics = cx.editor.diagnostics.clone();
587 let picker = diag_picker(cx, diagnostics, DiagnosticsFormat::ShowSourcePath);
588 cx.push_layer(Box::new(overlaid(picker)));
589 }
590
591 impl ui::menu::Item for CodeActionItem {
592 type Data = ();
593 fn format(&self, _data: &Self::Data) -> Row<'_> {
594 self.title().into()
595 }
596 }
597
598 pub fn code_action(cx: &mut Context) {
599 let (view, doc) = current!(cx.editor);
600
601 let selection_range = doc.selection(view.id).primary();
602
603 let mut futures: FuturesUnordered<_> =
604 code_actions_for_range(doc, selection_range, None, CodeActionTriggerKind::INVOKED)
605 .into_iter()
606 .map(|(request, ls_id)| async move {
607 let Some(mut actions) = request.await? else {
608 return anyhow::Ok(Vec::new());
609 };
610
611 // remove disabled code actions
612 actions.retain(|action| {
613 matches!(
614 action,
615 CodeActionOrCommand::Command(_)
616 | CodeActionOrCommand::CodeAction(CodeAction { disabled: None, .. })
617 )
618 });
619
620 Ok(actions
621 .into_iter()
622 .map(|lsp_item| CodeActionItem::lsp(ls_id, lsp_item))
623 .collect())
624 })
625 .collect();
626
627 if futures.is_empty() {
628 cx.editor
629 .set_error("No configured language server supports code actions");
630 return;
631 }
632
633 cx.jobs.callback(async move {
634 let mut actions = Vec::new();
635
636 while let Some(output) = futures.next().await {
637 match output {
638 Ok(mut items) => actions.append(&mut items),
639 Err(err) => log::error!("while gathering code actions: {err}"),
640 }
641 }
642
643 // Sort the gathered actions into a useful order, highest priority first. See
644 // `lsp_code_action_priority` for how LSP actions are ranked.
645 actions.sort_by_key(|action| std::cmp::Reverse(action.priority));
646
647 let call = move |editor: &mut Editor, compositor: &mut Compositor| {
648 if actions.is_empty() {
649 editor.set_error("No code actions available");
650 return;
651 }
652 let mut picker = ui::Menu::new(actions, (), move |editor, action, event| {
653 if event != PromptEvent::Validate {
654 return;
655 }
656 // Always present on validate.
657 action.unwrap().execute(editor);
658 });
659 picker.move_down(); // pre-select the first item
660
661 let popup = Popup::new("code-action", picker)
662 .with_scrollbar(false)
663 .auto_close(true);
664
665 compositor.replace_or_push("code-action", popup);
666 };
667
668 Ok(Callback::EditorCompositor(Box::new(call)))
669 });
670 }
671
672 // Extracting this to a type alias would require boxing this future
673 #[allow(clippy::type_complexity)]
674 pub(crate) fn code_actions_for_range(
675 doc: &Document,
676 range: helix_core::Range,
677 only: Option<Vec<CodeActionKind>>,
678 trigger_kind: CodeActionTriggerKind,
679 ) -> Vec<(
680 impl Future<Output = Result<Option<Vec<CodeActionOrCommand>>, helix_lsp::Error>>,
681 LanguageServerId,
682 )> {
683 let mut seen_language_servers = HashSet::new();
684
685 doc.language_servers_with_feature(LanguageServerFeature::CodeAction)
686 .filter(|ls| seen_language_servers.insert(ls.id()))
687 // TODO this should probably already been filtered in something like "language_servers_with_feature"
688 .filter_map(|language_server| {
689 let offset_encoding = language_server.offset_encoding();
690 let language_server_id = language_server.id();
691 let lsp_range = range_to_lsp_range(doc.text(), range, offset_encoding);
692 // Filter and convert overlapping diagnostics
693 let code_action_context = lsp::CodeActionContext {
694 diagnostics: doc
695 .diagnostics()
696 .iter()
697 .filter(|&diag| {
698 range.overlaps(&helix_core::Range::new(diag.range.start, diag.range.end))
699 })
700 .map(|diag| diagnostic_to_lsp_diagnostic(doc.text(), diag, offset_encoding))
701 .collect(),
702 only: only.clone(),
703 trigger_kind: Some(trigger_kind),
704 };
705 let code_action_request =
706 language_server.code_actions(doc.identifier(), lsp_range, code_action_context)?;
707 Some((code_action_request, language_server_id))
708 })
709 .collect::<Vec<_>>()
710 }
711
712 /// Build the job chain that runs a document's configured `code-actions-on-save`
713 /// kinds, in order, each against the latest document state, before running
714 /// `tail` (the auto-format / save job). Returns `tail` unchanged when nothing is
715 /// configured.
716 pub fn code_actions_on_save(
717 cx: &compositor::Context,
718 doc_id: DocumentId,
719 tail: Option<Job>,
720 ) -> Option<Job> {
721 let kinds = doc!(cx.editor, &doc_id)
722 .language_config()
723 .and_then(|config| config.code_actions_on_save.clone());
724 let Some(kinds) = kinds else {
725 return tail;
726 };
727 let kinds: VecDeque<CodeActionKind> = kinds.into_iter().map(CodeActionKind::from).collect();
728 code_action_on_save_step(doc_id, kinds, tail)
729 }
730
731 /// One link of the on-save chain: request the next kind's actions on the current
732 /// document, apply them, then recurse for the rest. Each link is built lazily (as
733 /// a `Followup`) so it reads the document after the previous link's edits, and
734 /// runs the configured kinds strictly in order.
735 fn code_action_on_save_step(
736 doc_id: DocumentId,
737 mut kinds: VecDeque<CodeActionKind>,
738 tail: Option<Job>,
739 ) -> Option<Job> {
740 let Some(kind) = kinds.pop_front() else {
741 // All kinds applied. Fall through to auto-format / save.
742 return tail;
743 };
744
745 let build_request = move |editor: &mut Editor| -> Option<Job> {
746 let doc = doc!(editor, &doc_id);
747 let version = doc.version();
748 let full_range = helix_core::Range::new(0, doc.text().len_chars());
749 let Some((request, ls_id)) = code_actions_for_range(
750 doc,
751 full_range,
752 Some(vec![kind.clone()]),
753 CodeActionTriggerKind::INVOKED,
754 )
755 .into_iter()
756 .next() else {
757 // No server offers this kind for the document: skip to the next.
758 return code_action_on_save_step(doc_id, kinds, tail);
759 };
760
761 let future = async move {
762 let actions = request.await?;
763 let resolve = move |editor: &mut Editor| -> Option<Job> {
764 resolve_and_apply_code_actions_of_kind(
765 editor, doc_id, version, ls_id, kind, kinds, tail, actions,
766 )
767 };
768 Ok(Callback::Followup(Box::new(resolve)))
769 };
770 Some(Job::with_callback(future).wait_before_exiting())
771 };
772
773 Some(
774 Job::with_callback(async move { Ok(Callback::Followup(Box::new(build_request))) })
775 .wait_before_exiting(),
776 )
777 }
778
779 /// An action matches a requested kind when its kind equals the request or is a
780 /// sub-kind (`source.fixAll.eslint` matches `source.fixAll`, per the LSP kind
781 /// hierarchy). Actions without a kind are skipped, so a server that ignores the
782 /// `only` filter can't slip an unrelated action into a save.
783 fn code_action_kind_matches(action: &CodeAction, requested: &CodeActionKind) -> bool {
784 action.kind.as_ref().is_some_and(|kind| {
785 let (kind, requested) = (kind.as_str(), requested.as_str());
786 kind == requested
787 || (kind.starts_with(requested) && kind[requested.len()..].starts_with('.'))
788 })
789 }
790
791 /// One matching action, in server order: an edit ready to apply, or a future
792 /// resolving the action's edit off the event loop.
793 ///
794 /// Keeping one ordered list preserves apply order, which matters when a kind yields
795 /// several edits.
796 type ResolveFuture =
797 std::pin::Pin<Box<dyn Future<Output = Result<lsp::CodeAction, helix_lsp::Error>> + Send>>;
798 enum ResolveStep {
799 Ready(lsp::WorkspaceEdit),
800 Resolve(ResolveFuture),
801 }
802
803 /// Resolve (off the event loop) and apply the actions matching `kind`, then
804 /// continue the on-save chain. The resolve is awaited in the returned job.
805 #[allow(clippy::too_many_arguments)]
806 fn resolve_and_apply_code_actions_of_kind(
807 editor: &mut Editor,
808 doc_id: DocumentId,
809 version: i32,
810 ls_id: LanguageServerId,
811 kind: CodeActionKind,
812 kinds: VecDeque<CodeActionKind>,
813 tail: Option<Job>,
814 actions: Option<Vec<CodeActionOrCommand>>,
815 ) -> Option<Job> {
816 // Build the matching actions, in order, while holding the language-server
817 // borrow, resolving only those the server left incomplete.
818 let prepared = (|| -> Option<(OffsetEncoding, Vec<ResolveStep>)> {
819 let actions = actions?;
820 if editor.documents.get(&doc_id)?.version() != version {
821 log::debug!("code-actions-on-save: document changed, skipping {kind:?}");
822 return None;
823 }
824 let ls = editor.language_server_by_id(ls_id)?;
825 let steps = actions
826 .iter()
827 .filter_map(|action| match action {
828 CodeActionOrCommand::CodeAction(ca) if ca.disabled.is_none() => Some(ca),
829 _ => None,
830 })
831 .filter(|ca| code_action_kind_matches(ca, &kind))
832 .filter_map(|ca| {
833 // Resolve only when the server left out the edit or command.
834 if ca.edit.is_none() || ca.command.is_none() {
835 if let Some(future) = ls.resolve_code_action(ca) {
836 return Some(ResolveStep::Resolve(Box::pin(future)));
837 }
838 }
839 ca.edit.clone().map(ResolveStep::Ready)
840 })
841 .collect();
842 Some((ls.offset_encoding(), steps))
843 })();
844 let Some((offset_encoding, steps)) = prepared else {
845 return code_action_on_save_step(doc_id, kinds, tail);
846 };
847
848 let future = async move {
849 let mut edits = Vec::new();
850 for step in steps {
851 match step {
852 ResolveStep::Ready(edit) => edits.push(edit),
853 ResolveStep::Resolve(future) => match future.await {
854 Ok(resolved) => edits.extend(resolved.edit),
855 Err(err) => log::error!("code-actions-on-save: resolve failed: {err:?}"),
856 },
857 }
858 }
859 let apply = move |editor: &mut Editor| -> Option<Job> {
860 // A plain :w runs this in the live event loop so the document can
861 // change while resolving: re-check the version and skip rather than
862 // applying a stale edit.
863 if editor
864 .documents
865 .get(&doc_id)
866 .is_some_and(|doc| doc.version() == version)
867 {
868 for edit in &edits {
869 if let Err(err) = editor.apply_workspace_edit(offset_encoding, edit) {
870 log::error!("code-actions-on-save: failed to apply edit: {err:?}");
871 }
872 }
873 } else {
874 log::debug!("code-actions-on-save: document changed, skipping {kind:?}");
875 }
876 code_action_on_save_step(doc_id, kinds, tail)
877 };
878 Ok(Callback::Followup(Box::new(apply)))
879 };
880 Some(Job::with_callback(future).wait_before_exiting())
881 }
882
883 #[derive(Debug)]
884 pub struct ApplyEditError {
885 pub kind: ApplyEditErrorKind,
886 pub failed_change_idx: usize,
887 }
888
889 #[derive(Debug)]
890 pub enum ApplyEditErrorKind {
891 DocumentChanged,
892 FileNotFound,
893 UnknownURISchema,
894 IoError(std::io::Error),
895 // TODO: check edits before applying and propagate failure
896 // InvalidEdit,
897 }
898
899 impl Display for ApplyEditErrorKind {
900 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
901 match self {
902 ApplyEditErrorKind::DocumentChanged => f.write_str("document has changed"),
903 ApplyEditErrorKind::FileNotFound => f.write_str("file not found"),
904 ApplyEditErrorKind::UnknownURISchema => f.write_str("URI schema not supported"),
905 ApplyEditErrorKind::IoError(err) => f.write_str(&format!("{err}")),
906 }
907 }
908 }
909
910 /// Precondition: `locations` should be non-empty.
911 fn goto_impl(editor: &mut Editor, compositor: &mut Compositor, locations: Vec<Location>) {
912 let cwdir = helix_stdx::env::current_working_dir();
913
914 match locations.as_slice() {
915 [location] => {
916 jump_to_location(editor, location, Action::Replace);
917 }
918 [] => unreachable!("`locations` should be non-empty for `goto_impl`"),
919 _locations => {
920 let columns = [ui::PickerColumn::new(
921 "location",
922 |item: &Location, cwdir: &std::path::PathBuf| {
923 let path = if let Some(path) = item.uri.as_path() {
924 path.strip_prefix(cwdir).unwrap_or(path).to_string_lossy()
925 } else {
926 item.uri.to_string().into()
927 };
928
929 format!("{path}:{}", item.range.start.line + 1).into()
930 },
931 )];
932
933 let picker = Picker::new(columns, 0, locations, cwdir, |cx, location, action| {
934 jump_to_location(cx.editor, location, action)
935 })
936 .with_preview(|_editor, location| location_to_file_location(location));
937 compositor.push(Box::new(overlaid(picker)));
938 }
939 }
940 }
941
942 fn goto_single_impl<P, F>(cx: &mut Context, feature: LanguageServerFeature, request_provider: P)
943 where
944 P: Fn(&Client, lsp::Position, lsp::TextDocumentIdentifier) -> Option<F>,
945 F: Future<Output = helix_lsp::Result<Option<lsp::GotoDefinitionResponse>>> + 'static + Send,
946 {
947 let (view, doc) = current_ref!(cx.editor);
948 let mut futures: FuturesUnordered<_> = doc
949 .language_servers_with_feature(feature)
950 .map(|language_server| {
951 let offset_encoding = language_server.offset_encoding();
952 let pos = doc.position(view.id, offset_encoding);
953 let future = request_provider(language_server, pos, doc.identifier()).unwrap();
954 async move { anyhow::Ok((future.await?, offset_encoding)) }
955 })
956 .collect();
957
958 cx.jobs.callback(async move {
959 let mut locations = Vec::new();
960 while let Some(response) = futures.next().await {
961 match response {
962 Ok((response, offset_encoding)) => match response {
963 Some(lsp::GotoDefinitionResponse::Scalar(lsp_location)) => {
964 locations.extend(lsp_location_to_location(lsp_location, offset_encoding));
965 }
966 Some(lsp::GotoDefinitionResponse::Array(lsp_locations)) => {
967 locations.extend(lsp_locations.into_iter().flat_map(|location| {
968 lsp_location_to_location(location, offset_encoding)
969 }));
970 }
971 Some(lsp::GotoDefinitionResponse::Link(lsp_locations)) => {
972 locations.extend(
973 lsp_locations
974 .into_iter()
975 .map(|location_link| {
976 lsp::Location::new(
977 location_link.target_uri,
978 location_link.target_range,
979 )
980 })
981 .flat_map(|location| {
982 lsp_location_to_location(location, offset_encoding)
983 }),
984 );
985 }
986 None => (),
987 },
988 Err(err) => log::error!("Error requesting locations: {err}"),
989 }
990 }
991 let call = move |editor: &mut Editor, compositor: &mut Compositor| {
992 if locations.is_empty() {
993 editor.set_error(match feature {
994 LanguageServerFeature::GotoDeclaration => "No declaration found.",
995 LanguageServerFeature::GotoDefinition => "No definition found.",
996 LanguageServerFeature::GotoTypeDefinition => "No type definition found.",
997 LanguageServerFeature::GotoImplementation => "No implementation found.",
998 _ => "No location found.",
999 });
1000 } else {
1001 goto_impl(editor, compositor, locations);
1002 }
1003 };
1004 Ok(Callback::EditorCompositor(Box::new(call)))
1005 });
1006 }
1007
1008 pub fn goto_declaration(cx: &mut Context) {
1009 goto_single_impl(
1010 cx,
1011 LanguageServerFeature::GotoDeclaration,
1012 |ls, pos, doc_id| ls.goto_declaration(doc_id, pos, None),
1013 );
1014 }
1015
1016 pub fn goto_definition(cx: &mut Context) {
1017 goto_single_impl(
1018 cx,
1019 LanguageServerFeature::GotoDefinition,
1020 |ls, pos, doc_id| ls.goto_definition(doc_id, pos, None),
1021 );
1022 }
1023
1024 pub fn goto_type_definition(cx: &mut Context) {
1025 goto_single_impl(
1026 cx,
1027 LanguageServerFeature::GotoTypeDefinition,
1028 |ls, pos, doc_id| ls.goto_type_definition(doc_id, pos, None),
1029 );
1030 }
1031
1032 pub fn goto_implementation(cx: &mut Context) {
1033 goto_single_impl(
1034 cx,
1035 LanguageServerFeature::GotoImplementation,
1036 |ls, pos, doc_id| ls.goto_implementation(doc_id, pos, None),
1037 );
1038 }
1039
1040 pub fn goto_reference(cx: &mut Context) {
1041 let config = cx.editor.config();
1042 let (view, doc) = current_ref!(cx.editor);
1043
1044 let mut futures: FuturesUnordered<_> = doc
1045 .language_servers_with_feature(LanguageServerFeature::GotoReference)
1046 .map(|language_server| {
1047 let offset_encoding = language_server.offset_encoding();
1048 let pos = doc.position(view.id, offset_encoding);
1049 let future = language_server
1050 .goto_reference(
1051 doc.identifier(),
1052 pos,
1053 config.lsp.goto_reference_include_declaration,
1054 None,
1055 )
1056 .unwrap();
1057 async move { anyhow::Ok((future.await?, offset_encoding)) }
1058 })
1059 .collect();
1060
1061 cx.jobs.callback(async move {
1062 let mut locations = Vec::new();
1063 while let Some(response) = futures.next().await {
1064 match response {
1065 Ok((lsp_locations, offset_encoding)) => locations.extend(
1066 lsp_locations
1067 .into_iter()
1068 .flatten()
1069 .flat_map(|location| lsp_location_to_location(location, offset_encoding)),
1070 ),
1071 Err(err) => log::error!("Error requesting references: {err}"),
1072 }
1073 }
1074 let call = move |editor: &mut Editor, compositor: &mut Compositor| {
1075 if locations.is_empty() {
1076 editor.set_error("No references found.");
1077 } else {
1078 goto_impl(editor, compositor, locations);
1079 }
1080 };
1081 Ok(Callback::EditorCompositor(Box::new(call)))
1082 });
1083 }
1084
1085 pub fn signature_help(cx: &mut Context) {
1086 cx.editor
1087 .handlers
1088 .trigger_signature_help(SignatureHelpInvoked::Manual, cx.editor)
1089 }
1090
1091 pub fn hover(cx: &mut Context) {
1092 use ui::lsp::hover::Hover;
1093
1094 let (view, doc) = current!(cx.editor);
1095 if doc
1096 .language_servers_with_feature(LanguageServerFeature::Hover)
1097 .count()
1098 == 0
1099 {
1100 cx.editor
1101 .set_error("No configured language server supports hover");
1102 return;
1103 }
1104
1105 let mut seen_language_servers = HashSet::new();
1106 let mut futures: FuturesUnordered<_> = doc
1107 .language_servers_with_feature(LanguageServerFeature::Hover)
1108 .filter(|ls| seen_language_servers.insert(ls.id()))
1109 .map(|language_server| {
1110 let server_name = language_server.name().to_string();
1111 // TODO: factor out a doc.position_identifier() that returns lsp::TextDocumentPositionIdentifier
1112 let pos = doc.position(view.id, language_server.offset_encoding());
1113 let request = language_server
1114 .text_document_hover(doc.identifier(), pos, None)
1115 .unwrap();
1116
1117 async move { anyhow::Ok((server_name, request.await?)) }
1118 })
1119 .collect();
1120
1121 cx.jobs.callback(async move {
1122 let mut hovers: Vec<(String, lsp::Hover)> = Vec::new();
1123
1124 while let Some(response) = futures.next().await {
1125 match response {
1126 Ok((server_name, Some(hover))) => hovers.push((server_name, hover)),
1127 Ok(_) => (),
1128 Err(err) => log::error!("Error requesting hover: {err}"),
1129 }
1130 }
1131
1132 let call = move |editor: &mut Editor, compositor: &mut Compositor| {
1133 if hovers.is_empty() {
1134 editor.set_status("No hover results available.");
1135 return;
1136 }
1137
1138 // create new popup
1139 let contents = Hover::new(hovers, editor.syn_loader.clone());
1140 let popup = Popup::new(Hover::ID, contents).auto_close(true);
1141 compositor.replace_or_push(Hover::ID, popup);
1142 };
1143 Ok(Callback::EditorCompositor(Box::new(call)))
1144 });
1145 }
1146
1147 pub fn rename_symbol(cx: &mut Context) {
1148 fn get_prefill_from_word_boundary(editor: &Editor) -> String {
1149 let (view, doc) = current_ref!(editor);
1150 let text = doc.text().slice(..);
1151 let primary_selection = doc.selection(view.id).primary();
1152 if primary_selection.len() > 1 {
1153 primary_selection
1154 } else {
1155 use helix_core::textobject::{textobject_word, TextObject};
1156 textobject_word(text, primary_selection, TextObject::Inside, 1, false)
1157 }
1158 .fragment(text)
1159 .into()
1160 }
1161
1162 fn get_prefill_from_lsp_response(
1163 editor: &Editor,
1164 offset_encoding: OffsetEncoding,
1165 response: Option<lsp::PrepareRenameResponse>,
1166 ) -> Result<String, &'static str> {
1167 match response {
1168 Some(lsp::PrepareRenameResponse::Range(range)) => {
1169 let text = doc!(editor).text();
1170
1171 Ok(lsp_range_to_range(text, range, offset_encoding)
1172 .ok_or("lsp sent invalid selection range for rename")?
1173 .fragment(text.slice(..))
1174 .into())
1175 }
1176 Some(lsp::PrepareRenameResponse::RangeWithPlaceholder { placeholder, .. }) => {
1177 Ok(placeholder)
1178 }
1179 Some(lsp::PrepareRenameResponse::DefaultBehavior { .. }) => {
1180 Ok(get_prefill_from_word_boundary(editor))
1181 }
1182 None => Err("lsp did not respond to prepare rename request"),
1183 }
1184 }
1185
1186 fn create_rename_prompt(
1187 editor: &Editor,
1188 prefill: String,
1189 history_register: Option<char>,
1190 language_server_id: Option<LanguageServerId>,
1191 ) -> Box<ui::Prompt> {
1192 let prompt = ui::Prompt::new(
1193 "rename-to:".into(),
1194 history_register,
1195 ui::completers::none,
1196 move |cx: &mut compositor::Context, input: &str, event: PromptEvent| {
1197 if event != PromptEvent::Validate {
1198 return;
1199 }
1200 let (view, doc) = current!(cx.editor);
1201
1202 let Some(language_server) = doc
1203 .language_servers_with_feature(LanguageServerFeature::RenameSymbol)
1204 .find(|ls| language_server_id.is_none_or(|id| id == ls.id()))
1205 else {
1206 cx.editor
1207 .set_error("No configured language server supports symbol renaming");
1208 return;
1209 };
1210
1211 let offset_encoding = language_server.offset_encoding();
1212 let pos = doc.position(view.id, offset_encoding);
1213 let future = language_server
1214 .rename_symbol(doc.identifier(), pos, input.to_string())
1215 .unwrap();
1216
1217 match block_on(future) {
1218 Ok(edits) => {
1219 let _ = cx
1220 .editor
1221 .apply_workspace_edit(offset_encoding, &edits.unwrap_or_default());
1222 }
1223 Err(err) => cx.editor.set_error(err.to_string()),
1224 }
1225 },
1226 )
1227 .with_line(prefill, editor);
1228
1229 Box::new(prompt)
1230 }
1231
1232 let (view, doc) = current_ref!(cx.editor);
1233 let history_register = cx.register;
1234
1235 if doc
1236 .language_servers_with_feature(LanguageServerFeature::RenameSymbol)
1237 .next()
1238 .is_none()
1239 {
1240 cx.editor
1241 .set_error("No configured language server supports symbol renaming");
1242 return;
1243 }
1244
1245 let language_server_with_prepare_rename_support = doc
1246 .language_servers_with_feature(LanguageServerFeature::RenameSymbol)
1247 .find(|ls| {
1248 matches!(
1249 ls.capabilities().rename_provider,
1250 Some(lsp::OneOf::Right(lsp::RenameOptions {
1251 prepare_provider: Some(true),
1252 ..
1253 }))
1254 )
1255 });
1256
1257 if let Some(language_server) = language_server_with_prepare_rename_support {
1258 let ls_id = language_server.id();
1259 let offset_encoding = language_server.offset_encoding();
1260 let pos = doc.position(view.id, offset_encoding);
1261 let future = language_server
1262 .prepare_rename(doc.identifier(), pos)
1263 .unwrap();
1264 cx.callback(
1265 future,
1266 move |editor, compositor, response: Option<lsp::PrepareRenameResponse>| {
1267 let prefill = match get_prefill_from_lsp_response(editor, offset_encoding, response)
1268 {
1269 Ok(p) => p,
1270 Err(e) => {
1271 editor.set_error(e);
1272 return;
1273 }
1274 };
1275
1276 let prompt = create_rename_prompt(editor, prefill, history_register, Some(ls_id));
1277
1278 compositor.push(prompt);
1279 },
1280 );
1281 } else {
1282 let prefill = get_prefill_from_word_boundary(cx.editor);
1283 let prompt = create_rename_prompt(cx.editor, prefill, history_register, None);
1284 cx.push_layer(prompt);
1285 }
1286 }
1287
1288 pub fn select_references_to_symbol_under_cursor(cx: &mut Context) {
1289 let (view, doc) = current!(cx.editor);
1290 let language_server =
1291 language_server_with_feature!(cx.editor, doc, LanguageServerFeature::DocumentHighlight);
1292 let offset_encoding = language_server.offset_encoding();
1293 let pos = doc.position(view.id, offset_encoding);
1294 let future = language_server
1295 .text_document_document_highlight(doc.identifier(), pos, None)
1296 .unwrap();
1297
1298 cx.callback(
1299 future,
1300 move |editor, _compositor, response: Option<Vec<lsp::DocumentHighlight>>| {
1301 let document_highlights = match response {
1302 Some(highlights) if !highlights.is_empty() => highlights,
1303 _ => return,
1304 };
1305 let (view, doc) = current!(editor);
1306 let text = doc.text();
1307 let pos = doc.selection(view.id).primary().cursor(text.slice(..));
1308
1309 // We must find the range that contains our primary cursor to prevent our primary cursor to move
1310 let mut primary_index = 0;
1311 let ranges = document_highlights
1312 .iter()
1313 .filter_map(|highlight| lsp_range_to_range(text, highlight.range, offset_encoding))
1314 .enumerate()
1315 .map(|(i, range)| {
1316 if range.contains(pos) {
1317 primary_index = i;
1318 }
1319 range
1320 })
1321 .collect();
1322 let selection = Selection::new(ranges, primary_index);
1323 doc.set_selection(view.id, selection);
1324 },
1325 );
1326 }
1327
1328 pub fn compute_inlay_hints_for_all_views(editor: &mut Editor, jobs: &mut crate::job::Jobs) {
1329 if !editor.config().lsp.display_inlay_hints {
1330 return;
1331 }
1332
1333 for (view, _) in editor.tree.views() {
1334 let doc = match editor.documents.get(&view.doc) {
1335 Some(doc) => doc,
1336 None => continue,
1337 };
1338 if let Some(callback) = compute_inlay_hints_for_view(view, doc) {
1339 jobs.callback(callback);
1340 }
1341 }
1342 }
1343
1344 fn compute_inlay_hints_for_view(
1345 view: &View,
1346 doc: &Document,
1347 ) -> Option<std::pin::Pin<Box<impl Future<Output = Result<crate::job::Callback, anyhow::Error>>>>> {
1348 let view_id = view.id;
1349 let doc_id = view.doc;
1350
1351 let language_server = doc
1352 .language_servers_with_feature(LanguageServerFeature::InlayHints)
1353 .next()?;
1354
1355 let doc_text = doc.text();
1356 let len_lines = doc_text.len_lines();
1357
1358 // Compute ~3 times the current view height of inlay hints, that way some scrolling
1359 // will not show half the view with hints and half without while still being faster
1360 // than computing all the hints for the full file (which could be dozens of time
1361 // longer than the view is).
1362 let view_height = view.inner_height();
1363 let first_visible_line =
1364 doc_text.char_to_line(doc.view_offset(view_id).anchor.min(doc_text.len_chars()));
1365 let first_line = first_visible_line.saturating_sub(view_height);
1366 let last_line = first_visible_line
1367 .saturating_add(view_height.saturating_mul(2))
1368 .min(len_lines);
1369
1370 let new_doc_inlay_hints_id = DocumentInlayHintsId {
1371 first_line,
1372 last_line,
1373 };
1374 // Don't recompute the annotations in case nothing has changed about the view
1375 if !doc.inlay_hints_oudated
1376 && doc
1377 .inlay_hints(view_id)
1378 .is_some_and(|dih| dih.id == new_doc_inlay_hints_id)
1379 {
1380 return None;
1381 }
1382
1383 let doc_slice = doc_text.slice(..);
1384 let first_char_in_range = doc_slice.line_to_char(first_line);
1385 let last_char_in_range = doc_slice.line_to_char(last_line);
1386
1387 let range = helix_lsp::util::range_to_lsp_range(
1388 doc_text,
1389 helix_core::Range::new(first_char_in_range, last_char_in_range),
1390 language_server.offset_encoding(),
1391 );
1392
1393 let offset_encoding = language_server.offset_encoding();
1394
1395 let callback = super::make_job_callback(
1396 language_server.text_document_range_inlay_hints(doc.identifier(), range, None)?,
1397 move |editor, _compositor, response: Option<Vec<lsp::InlayHint>>| {
1398 // The config was modified or the window was closed while the request was in flight
1399 if !editor.config().lsp.display_inlay_hints || editor.tree.try_get(view_id).is_none() {
1400 return;
1401 }
1402
1403 // Add annotations to relevant document, not the current one (it may have changed in between)
1404 let doc = match editor.documents.get_mut(&doc_id) {
1405 Some(doc) => doc,
1406 None => return,
1407 };
1408
1409 // If we have neither hints nor an LSP, empty the inlay hints since they're now oudated
1410 let mut hints = match response {
1411 Some(hints) if !hints.is_empty() => hints,
1412 _ => {
1413 doc.set_inlay_hints(
1414 view_id,
1415 DocumentInlayHints::empty_with_id(new_doc_inlay_hints_id),
1416 );
1417 doc.inlay_hints_oudated = false;
1418 return;
1419 }
1420 };
1421
1422 // Most language servers will already send them sorted but ensure this is the case to
1423 // avoid errors on our end.
1424 hints.sort_by_key(|inlay_hint| inlay_hint.position);
1425
1426 let mut padding_before_inlay_hints = Vec::new();
1427 let mut type_inlay_hints = Vec::new();
1428 let mut parameter_inlay_hints = Vec::new();
1429 let mut other_inlay_hints = Vec::new();
1430 let mut padding_after_inlay_hints = Vec::new();
1431
1432 let doc_text = doc.text();
1433 let inlay_hints_length_limit = doc.config.load().lsp.inlay_hints_length_limit;
1434
1435 for hint in hints {
1436 let char_idx =
1437 match helix_lsp::util::lsp_pos_to_pos(doc_text, hint.position, offset_encoding)
1438 {
1439 Some(pos) => pos,
1440 // Skip inlay hints that have no "real" position
1441 None => continue,
1442 };
1443
1444 let mut label = match hint.label {
1445 lsp::InlayHintLabel::String(s) => s,
1446 lsp::InlayHintLabel::LabelParts(parts) => parts
1447 .into_iter()
1448 .map(|p| p.value)
1449 .collect::<Vec<_>>()
1450 .join(""),
1451 };
1452 // Truncate the hint if too long
1453 if let Some(limit) = inlay_hints_length_limit {
1454 // Limit on displayed width
1455 use helix_core::unicode::{
1456 segmentation::UnicodeSegmentation, width::UnicodeWidthStr,
1457 };
1458
1459 let width = label.width();
1460 let limit = limit.get().into();
1461 if width > limit {
1462 let mut floor_boundary = 0;
1463 let mut acc = 0;
1464 for (i, grapheme_cluster) in label.grapheme_indices(true) {
1465 acc += grapheme_cluster.width();
1466
1467 if acc > limit {
1468 floor_boundary = i;
1469 break;
1470 }
1471 }
1472
1473 label.truncate(floor_boundary);
1474 label.push('…');
1475 }
1476 }
1477
1478 let inlay_hints_vec = match hint.kind {
1479 Some(lsp::InlayHintKind::TYPE) => &mut type_inlay_hints,
1480 Some(lsp::InlayHintKind::PARAMETER) => &mut parameter_inlay_hints,
1481 // We can't warn on unknown kind here since LSPs are free to set it or not, for
1482 // example Rust Analyzer does not: every kind will be `None`.
1483 _ => &mut other_inlay_hints,
1484 };
1485
1486 if let Some(true) = hint.padding_left {
1487 padding_before_inlay_hints.push(InlineAnnotation::new(char_idx, " "));
1488 }
1489
1490 inlay_hints_vec.push(InlineAnnotation::new(char_idx, label));
1491
1492 if let Some(true) = hint.padding_right {
1493 padding_after_inlay_hints.push(InlineAnnotation::new(char_idx, " "));
1494 }
1495 }
1496
1497 doc.set_inlay_hints(
1498 view_id,
1499 DocumentInlayHints {
1500 id: new_doc_inlay_hints_id,
1501 type_inlay_hints,
1502 parameter_inlay_hints,
1503 other_inlay_hints,
1504 padding_before_inlay_hints,
1505 padding_after_inlay_hints,
1506 },
1507 );
1508 doc.inlay_hints_oudated = false;
1509 },
1510 );
1511
1512 Some(callback)
1513 }