Unnamed repository; edit this file 'description' to name the repository.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
use std::{collections::HashSet, mem, time::Duration};

use crate::job;

use super::Handlers;

use helix_core::{syntax::LanguageServerFeature, text_annotations::InlineAnnotation};
use helix_event::{cancelable_future, register_hook, send_blocking};
use helix_lsp::lsp;
use helix_view::{
    document::{DocumentInlayHints, DocumentInlayHintsId},
    events::{
        DocumentDidChange, DocumentDidOpen, LanguageServerExited, LanguageServerInitialized,
        SelectionDidChange,
    },
    handlers::lsp::InlayHintEvent,
    DocumentId, Editor, ViewId,
};
use tokio::time::Instant;

#[derive(Debug, Default)]
pub(super) struct InlayHintHandler {
    views: HashSet<ViewId>,
    docs: HashSet<DocumentId>,
}

const DOCUMENT_CHANGE_DEBOUNCE: Duration = Duration::from_millis(500);
const VIEWPORT_SCROLL_DEBOUNCE: Duration = Duration::from_millis(100);

impl helix_event::AsyncHook for InlayHintHandler {
    type Event = InlayHintEvent;

    fn handle_event(&mut self, event: Self::Event, timeout: Option<Instant>) -> Option<Instant> {
        match event {
            InlayHintEvent::DocumentChanged(doc) => {
                self.docs.insert(doc);
                Some(Instant::now() + DOCUMENT_CHANGE_DEBOUNCE)
            }
            InlayHintEvent::ViewportScrolled(view) => {
                self.views.insert(view);
                let mut new_timeout = Instant::now() + VIEWPORT_SCROLL_DEBOUNCE;
                if let Some(timeout) = timeout {
                    new_timeout = new_timeout.max(timeout);
                }
                Some(new_timeout)
            }
        }
    }

    fn finish_debounce(&mut self) {
        let mut views = mem::take(&mut self.views);
        let docs = mem::take(&mut self.docs);

        job::dispatch_blocking(move |editor, _compositor| {
            // Drop any views which have been closed.
            views.retain(|&view| editor.tree.contains(view));
            // Add any views that show documents which changed.
            views.extend(
                editor
                    .tree
                    .views()
                    .filter_map(|(view, _)| docs.contains(&view.doc).then_some(view.id)),
            );

            for view in views {
                let doc = editor.tree.get(view).doc;
                let is_scroll = !docs.contains(&doc);
                request_inlay_hints_for_view(editor, view, doc, is_scroll);
            }
        });
    }
}

fn request_inlay_hints_for_view(
    editor: &mut Editor,
    view_id: ViewId,
    doc_id: DocumentId,
    is_scroll: bool,
) {
    if !editor.config().lsp.display_inlay_hints {
        return;
    }
    let Some(doc) = editor.documents.get_mut(&doc_id) else {
        return;
    };
    let Some(view) = editor.tree.try_get(view_id) else {
        return;
    };
    let Some(language_server) = doc
        .language_servers_with_feature(LanguageServerFeature::InlayHints)
        .next()
    else {
        return;
    };

    let rope = doc.text();
    let text = rope.slice(..);
    let len_lines = text.len_lines();
    let view_height = view.inner_height();
    let first_visible_line =
        text.char_to_line(doc.view_offset(view_id).anchor.min(text.len_chars()));
    let first_line = first_visible_line.saturating_sub(view_height);
    let last_line = first_visible_line
        .saturating_add(view_height.saturating_mul(2))
        .min(len_lines);
    let new_doc_inlay_hints_id = DocumentInlayHintsId {
        first_line,
        last_line,
    };
    // If the view was updated by scrolling (rather than changing) and the viewport still has the
    // the same position, we can reuse the hints.
    if is_scroll
        && doc
            .inlay_hints(view_id)
            .is_some_and(|hint| hint.id == new_doc_inlay_hints_id)
    {
        return;
    }
    let offset_encoding = language_server.offset_encoding();
    let range = helix_lsp::util::range_to_lsp_range(
        rope,
        helix_core::Range::new(text.line_to_char(first_line), text.line_to_char(last_line)),
        offset_encoding,
    );
    let future = language_server
        .text_document_range_inlay_hints(doc.identifier(), range, None)
        .expect("language server must return Some if it supports inlay hints");
    let controller = doc.inlay_hint_controllers.entry(view_id).or_default();
    let cancel = controller.restart();

    tokio::spawn(async move {
        match cancelable_future(future, cancel).await {
            Some(Ok(res)) => {
                job::dispatch(move |editor, _compositor| {
                    attach_inlay_hints(
                        editor,
                        view_id,
                        doc_id,
                        new_doc_inlay_hints_id,
                        offset_encoding,
                        res,
                    );
                })
                .await
            }
            Some(Err(err)) => log::error!("inlay hint request failed: {err}"),
            None => (),
        }
    });
}

fn attach_inlay_hints(
    editor: &mut Editor,
    view_id: ViewId,
    doc_id: DocumentId,
    id: DocumentInlayHintsId,
    offset_encoding: helix_lsp::OffsetEncoding,
    response: Option<Vec<lsp::InlayHint>>,
) {
    if !editor.config().lsp.display_inlay_hints || editor.tree.try_get(view_id).is_none() {
        return;
    }

    let Some(doc) = editor.documents.get_mut(&doc_id) else {
        return;
    };

    let mut hints = match response {
        Some(hints) if !hints.is_empty() => hints,
        _ => {
            doc.set_inlay_hints(view_id, DocumentInlayHints::empty_with_id(id));
            return;
        }
    };

    // Most language servers will already send them sorted but ensure this is the case to
    // avoid errors on our end.
    hints.sort_by_key(|inlay_hint| inlay_hint.position);

    let mut padding_before_inlay_hints = Vec::new();
    let mut type_inlay_hints = Vec::new();
    let mut parameter_inlay_hints = Vec::new();
    let mut other_inlay_hints = Vec::new();
    let mut padding_after_inlay_hints = Vec::new();

    let doc_text = doc.text();

    for hint in hints {
        let char_idx =
            match helix_lsp::util::lsp_pos_to_pos(doc_text, hint.position, offset_encoding) {
                Some(pos) => pos,
                // Skip inlay hints that have no "real" position
                None => continue,
            };

        let label = match hint.label {
            lsp::InlayHintLabel::String(s) => s,
            lsp::InlayHintLabel::LabelParts(parts) => parts
                .into_iter()
                .map(|p| p.value)
                .collect::<Vec<_>>()
                .join(""),
        };

        let inlay_hints_vec = match hint.kind {
            Some(lsp::InlayHintKind::TYPE) => &mut type_inlay_hints,
            Some(lsp::InlayHintKind::PARAMETER) => &mut parameter_inlay_hints,
            // We can't warn on unknown kind here since LSPs are free to set it or not, for
            // example Rust Analyzer does not: every kind will be `None`.
            _ => &mut other_inlay_hints,
        };

        if let Some(true) = hint.padding_left {
            padding_before_inlay_hints.push(InlineAnnotation::new(char_idx, " "));
        }

        inlay_hints_vec.push(InlineAnnotation::new(char_idx, label));

        if let Some(true) = hint.padding_right {
            padding_after_inlay_hints.push(InlineAnnotation::new(char_idx, " "));
        }
    }

    doc.set_inlay_hints(
        view_id,
        DocumentInlayHints {
            id,
            type_inlay_hints,
            parameter_inlay_hints,
            other_inlay_hints,
            padding_before_inlay_hints,
            padding_after_inlay_hints,
        },
    );
}

pub(super) fn register_hooks(handlers: &Handlers) {
    register_hook!(move |event: &mut DocumentDidOpen<'_>| {
        // When a document is initially opened, request inlay hints for it.
        let views: Vec<_> = event
            .editor
            .tree
            .views()
            .filter_map(|(view, _)| (view.doc == event.doc).then_some(view.id))
            .collect();
        for view in views {
            request_inlay_hints_for_view(event.editor, view, event.doc, false);
        }

        Ok(())
    });

    let tx = handlers.inlay_hints.clone();
    register_hook!(move |event: &mut DocumentDidChange<'_>| {
        // Update the inlay hint annotations' positions, helping ensure they are displayed in the
        // proper place.
        let apply_inlay_hint_changes = |annotations: &mut Vec<InlineAnnotation>| {
            event.changes.update_positions(
                annotations
                    .iter_mut()
                    .map(|annotation| (&mut annotation.char_idx, helix_core::Assoc::After)),
            );
        };

        for (_view_id, text_annotation) in event.doc.inlay_hints_mut() {
            let DocumentInlayHints {
                id: _,
                type_inlay_hints,
                parameter_inlay_hints,
                other_inlay_hints,
                padding_before_inlay_hints,
                padding_after_inlay_hints,
            } = text_annotation;

            apply_inlay_hint_changes(padding_before_inlay_hints);
            apply_inlay_hint_changes(type_inlay_hints);
            apply_inlay_hint_changes(parameter_inlay_hints);
            apply_inlay_hint_changes(other_inlay_hints);
            apply_inlay_hint_changes(padding_after_inlay_hints);
        }

        if !event.ghost_transaction {
            if let Some(controller) = event.doc.inlay_hint_controllers.get_mut(&event.view) {
                controller.cancel();
            }
            // TODO: ideally we should only send this if the document is visible.
            send_blocking(&tx, InlayHintEvent::DocumentChanged(event.doc.id()));
        }

        Ok(())
    });

    let tx = handlers.inlay_hints.clone();
    register_hook!(move |event: &mut SelectionDidChange<'_>| {
        if let Some(controller) = event.doc.inlay_hint_controllers.get_mut(&event.view) {
            controller.cancel();
        }
        // Ideally this would only trigger an update if the viewport changed...
        send_blocking(&tx, InlayHintEvent::ViewportScrolled(event.view));

        Ok(())
    });

    register_hook!(move |event: &mut LanguageServerInitialized<'_>| {
        let views: Vec<_> = event
            .editor
            .tree
            .views()
            .map(|(view, _)| (view.id, view.doc))
            .collect();
        for (view, doc) in views {
            request_inlay_hints_for_view(event.editor, view, doc, false);
        }

        Ok(())
    });

    register_hook!(move |event: &mut LanguageServerExited<'_>| {
        // Clear and re-request all annotations when a server exits.
        for doc in event.editor.documents_mut() {
            if doc.supports_language_server(event.server_id) {
                doc.reset_all_inlay_hints();
            }
        }

        let views: Vec<_> = event
            .editor
            .tree
            .views()
            .map(|(view, _)| (view.id, view.doc))
            .collect();
        for (view, doc) in views {
            request_inlay_hints_for_view(event.editor, view, doc, false);
        }

        Ok(())
    });
}