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
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
use crate::{
    compositor::{Component, Compositor, Context, EventResult},
    ctrl, key, shift,
    ui::{self, EditorView},
};
use crossterm::event::Event;
use tui::{
    buffer::Buffer as Surface,
    widgets::{Block, BorderType, Borders},
};

use fuzzy_matcher::skim::SkimMatcherV2 as Matcher;
use fuzzy_matcher::FuzzyMatcher;
use tui::widgets::Widget;

use std::time::Instant;
use std::{
    borrow::Cow,
    cmp::Reverse,
    collections::HashMap,
    io::Read,
    path::{Path, PathBuf},
};

use crate::ui::{Prompt, PromptEvent};
use helix_core::{movement::Direction, Position};
use helix_view::{
    editor::Action,
    graphics::{Color, CursorKind, Margin, Modifier, Rect, Style},
    Document, Editor,
};

pub const MIN_AREA_WIDTH_FOR_PREVIEW: u16 = 72;
/// Biggest file size to preview in bytes
pub const MAX_FILE_SIZE_FOR_PREVIEW: u64 = 10 * 1024 * 1024;

/// File path and range of lines (used to align and highlight lines)
pub type FileLocation = (PathBuf, Option<(usize, usize)>);

pub struct FilePicker<T> {
    picker: Picker<T>,
    pub truncate_start: bool,
    /// Caches paths to documents
    preview_cache: HashMap<PathBuf, CachedPreview>,
    read_buffer: Vec<u8>,
    /// Given an item in the picker, return the file path and line number to display.
    file_fn: Box<dyn Fn(&Editor, &T) -> Option<FileLocation>>,
}

pub enum CachedPreview {
    Document(Box<Document>),
    Binary,
    LargeFile,
    NotFound,
}

// We don't store this enum in the cache so as to avoid lifetime constraints
// from borrowing a document already opened in the editor.
pub enum Preview<'picker, 'editor> {
    Cached(&'picker CachedPreview),
    EditorDocument(&'editor Document),
}

impl Preview<'_, '_> {
    fn document(&self) -> Option<&Document> {
        match self {
            Preview::EditorDocument(doc) => Some(doc),
            Preview::Cached(CachedPreview::Document(doc)) => Some(doc),
            _ => None,
        }
    }

    /// Alternate text to show for the preview.
    fn placeholder(&self) -> &str {
        match *self {
            Self::EditorDocument(_) => "<File preview>",
            Self::Cached(preview) => match preview {
                CachedPreview::Document(_) => "<File preview>",
                CachedPreview::Binary => "<Binary file>",
                CachedPreview::LargeFile => "<File too large to preview>",
                CachedPreview::NotFound => "<File not found>",
            },
        }
    }
}

impl<T> FilePicker<T> {
    pub fn new(
        options: Vec<T>,
        format_fn: impl Fn(&T) -> Cow<str> + 'static,
        callback_fn: impl Fn(&mut Context, &T, Action) + 'static,
        preview_fn: impl Fn(&Editor, &T) -> Option<FileLocation> + 'static,
    ) -> Self {
        Self {
            picker: Picker::new(options, format_fn, callback_fn),
            truncate_start: true,
            preview_cache: HashMap::new(),
            read_buffer: Vec::with_capacity(1024),
            file_fn: Box::new(preview_fn),
        }
    }

    fn current_file(&self, editor: &Editor) -> Option<FileLocation> {
        self.picker
            .selection()
            .and_then(|current| (self.file_fn)(editor, current))
            .and_then(|(path, line)| {
                helix_core::path::get_canonicalized_path(&path)
                    .ok()
                    .zip(Some(line))
            })
    }

    /// Get (cached) preview for a given path. If a document corresponding
    /// to the path is already open in the editor, it is used instead.
    fn get_preview<'picker, 'editor>(
        &'picker mut self,
        path: &Path,
        editor: &'editor Editor,
    ) -> Preview<'picker, 'editor> {
        if let Some(doc) = editor.document_by_path(path) {
            return Preview::EditorDocument(doc);
        }

        if self.preview_cache.contains_key(path) {
            return Preview::Cached(&self.preview_cache[path]);
        }

        let data = std::fs::File::open(path).and_then(|file| {
            let metadata = file.metadata()?;
            // Read up to 1kb to detect the content type
            let n = file.take(1024).read_to_end(&mut self.read_buffer)?;
            let content_type = content_inspector::inspect(&self.read_buffer[..n]);
            self.read_buffer.clear();
            Ok((metadata, content_type))
        });
        let preview = data
            .map(
                |(metadata, content_type)| match (metadata.len(), content_type) {
                    (_, content_inspector::ContentType::BINARY) => CachedPreview::Binary,
                    (size, _) if size > MAX_FILE_SIZE_FOR_PREVIEW => CachedPreview::LargeFile,
                    _ => {
                        // TODO: enable syntax highlighting; blocked by async rendering
                        Document::open(path, None, None)
                            .map(|doc| CachedPreview::Document(Box::new(doc)))
                            .unwrap_or(CachedPreview::NotFound)
                    }
                },
            )
            .unwrap_or(CachedPreview::NotFound);
        self.preview_cache.insert(path.to_owned(), preview);
        Preview::Cached(&self.preview_cache[path])
    }
}

impl<T: 'static> Component for FilePicker<T> {
    fn render(&mut self, area: Rect, surface: &mut Surface, cx: &mut Context) {
        // +---------+ +---------+
        // |prompt   | |preview  |
        // +---------+ |         |
        // |picker   | |         |
        // |         | |         |
        // +---------+ +---------+

        let render_preview = area.width > MIN_AREA_WIDTH_FOR_PREVIEW;
        // -- Render the frame:
        // clear area
        let background = cx.editor.theme.get("ui.background");
        let text = cx.editor.theme.get("ui.text");
        surface.clear_with(area, background);

        let picker_width = if render_preview {
            area.width / 2
        } else {
            area.width
        };

        let picker_area = area.with_width(picker_width);
        self.picker.truncate_start = self.truncate_start;
        self.picker.render(picker_area, surface, cx);

        if !render_preview {
            return;
        }

        let preview_area = area.clip_left(picker_width);

        // don't like this but the lifetime sucks
        let block = Block::default().borders(Borders::ALL);

        // calculate the inner area inside the box
        let inner = block.inner(preview_area);
        // 1 column gap on either side
        let margin = Margin {
            vertical: 0,
            horizontal: 1,
        };
        let inner = inner.inner(&margin);
        block.render(preview_area, surface);

        if let Some((path, range)) = self.current_file(cx.editor) {
            let preview = self.get_preview(&path, cx.editor);
            let doc = match preview.document() {
                Some(doc) => doc,
                None => {
                    let alt_text = preview.placeholder();
                    let x = inner.x + inner.width.saturating_sub(alt_text.len() as u16) / 2;
                    let y = inner.y + inner.height / 2;
                    surface.set_stringn(x, y, alt_text, inner.width as usize, text);
                    return;
                }
            };

            // align to middle
            let first_line = range
                .map(|(start, end)| {
                    let height = end.saturating_sub(start) + 1;
                    let middle = start + (height.saturating_sub(1) / 2);
                    middle.saturating_sub(inner.height as usize / 2).min(start)
                })
                .unwrap_or(0);

            let offset = Position::new(first_line, 0);

            let highlights =
                EditorView::doc_syntax_highlights(doc, offset, area.height, &cx.editor.theme);
            EditorView::render_text_highlights(
                doc,
                offset,
                inner,
                surface,
                &cx.editor.theme,
                highlights,
            );

            // highlight the line
            if let Some((start, end)) = range {
                let offset = start.saturating_sub(first_line) as u16;
                surface.set_style(
                    Rect::new(
                        inner.x,
                        inner.y + offset,
                        inner.width,
                        (end.saturating_sub(start) as u16 + 1)
                            .min(inner.height.saturating_sub(offset)),
                    ),
                    cx.editor
                        .theme
                        .try_get("ui.highlight")
                        .unwrap_or_else(|| cx.editor.theme.get("ui.selection")),
                );
            }
        }
    }

    fn handle_event(&mut self, event: Event, ctx: &mut Context) -> EventResult {
        // TODO: keybinds for scrolling preview
        self.picker.handle_event(event, ctx)
    }

    fn cursor(&self, area: Rect, ctx: &Editor) -> (Option<Position>, CursorKind) {
        self.picker.cursor(area, ctx)
    }

    fn required_size(&mut self, (width, height): (u16, u16)) -> Option<(u16, u16)> {
        let picker_width = if width > MIN_AREA_WIDTH_FOR_PREVIEW {
            width / 2
        } else {
            width
        };
        self.picker.required_size((picker_width, height))?;
        Some((width, height))
    }
}

pub struct Picker<T> {
    options: Vec<T>,
    // filter: String,
    matcher: Box<Matcher>,
    /// (index, score)
    matches: Vec<(usize, i64)>,
    /// Filter over original options.
    filters: Vec<usize>, // could be optimized into bit but not worth it now

    /// Current height of the completions box
    completion_height: u16,

    cursor: usize,
    // pattern: String,
    prompt: Prompt,
    previous_pattern: String,
    /// Whether to truncate the start (default true)
    pub truncate_start: bool,

    format_fn: Box<dyn Fn(&T) -> Cow<str>>,
    callback_fn: Box<dyn Fn(&mut Context, &T, Action)>,
}

impl<T> Picker<T> {
    pub fn new(
        options: Vec<T>,
        format_fn: impl Fn(&T) -> Cow<str> + 'static,
        callback_fn: impl Fn(&mut Context, &T, Action) + 'static,
    ) -> Self {
        let prompt = Prompt::new(
            "".into(),
            None,
            ui::completers::none,
            |_editor: &mut Context, _pattern: &str, _event: PromptEvent| {},
        );

        let mut picker = Self {
            options,
            matcher: Box::new(Matcher::default()),
            matches: Vec::new(),
            filters: Vec::new(),
            cursor: 0,
            prompt,
            previous_pattern: String::new(),
            truncate_start: true,
            format_fn: Box::new(format_fn),
            callback_fn: Box::new(callback_fn),
            completion_height: 0,
        };

        // scoring on empty input:
        // TODO: just reuse score()
        picker.matches.extend(
            picker
                .options
                .iter()
                .enumerate()
                .map(|(index, _option)| (index, 0)),
        );

        picker
    }

    pub fn score(&mut self) {
        let now = Instant::now();

        let pattern = &self.prompt.line;

        if pattern == &self.previous_pattern {
            return;
        }

        if pattern.is_empty() {
            // Fast path for no pattern.
            self.matches.clear();
            self.matches.extend(
                self.options
                    .iter()
                    .enumerate()
                    .map(|(index, _option)| (index, 0)),
            );
        } else if pattern.starts_with(&self.previous_pattern) {
            // TODO: remove when retain_mut is in stable rust
            use retain_mut::RetainMut;

            // optimization: if the pattern is a more specific version of the previous one
            // then we can score the filtered set.
            #[allow(unstable_name_collisions)]
            self.matches.retain_mut(|(index, score)| {
                let option = &self.options[*index];
                // TODO: maybe using format_fn isn't the best idea here
                let text = (self.format_fn)(option);

                match self.matcher.fuzzy_match(&text, pattern) {
                    Some(s) => {
                        // Update the score
                        *score = s;
                        true
                    }
                    None => false,
                }
            });

            self.matches
                .sort_unstable_by_key(|(_, score)| Reverse(*score));
        } else {
            self.matches.clear();
            self.matches.extend(
                self.options
                    .iter()
                    .enumerate()
                    .filter_map(|(index, option)| {
                        // filter options first before matching
                        if !self.filters.is_empty() {
                            // TODO: this filters functionality seems inefficient,
                            // instead store and operate on filters if any
                            self.filters.binary_search(&index).ok()?;
                        }

                        // TODO: maybe using format_fn isn't the best idea here
                        let text = (self.format_fn)(option);

                        self.matcher
                            .fuzzy_match(&text, pattern)
                            .map(|score| (index, score))
                    }),
            );
            self.matches
                .sort_unstable_by_key(|(_, score)| Reverse(*score));
        }

        log::debug!("picker score {:?}", Instant::now().duration_since(now));

        // reset cursor position
        self.cursor = 0;
        self.previous_pattern.clone_from(pattern);
    }

    /// Move the cursor by a number of lines, either down (`Forward`) or up (`Backward`)
    pub fn move_by(&mut self, amount: usize, direction: Direction) {
        let len = self.matches.len();

        match direction {
            Direction::Forward => {
                self.cursor = self.cursor.saturating_add(amount) % len;
            }
            Direction::Backward => {
                self.cursor = self.cursor.saturating_add(len).saturating_sub(amount) % len;
            }
        }
    }

    /// Move the cursor down by exactly one page. After the last page comes the first page.
    pub fn page_up(&mut self) {
        self.move_by(self.completion_height as usize, Direction::Backward);
    }

    /// Move the cursor up by exactly one page. After the first page comes the last page.
    pub fn page_down(&mut self) {
        self.move_by(self.completion_height as usize, Direction::Forward);
    }

    /// Move the cursor to the first entry
    pub fn to_start(&mut self) {
        self.cursor = 0;
    }

    /// Move the cursor to the last entry
    pub fn to_end(&mut self) {
        self.cursor = self.matches.len().saturating_sub(1);
    }

    pub fn selection(&self) -> Option<&T> {
        self.matches
            .get(self.cursor)
            .map(|(index, _score)| &self.options[*index])
    }

    pub fn save_filter(&mut self, cx: &Context) {
        self.filters.clear();
        self.filters
            .extend(self.matches.iter().map(|(index, _)| *index));
        self.filters.sort_unstable(); // used for binary search later
        self.prompt.clear(cx);
    }
}

// process:
// - read all the files into a list, maxed out at a large value
// - on input change:
//  - score all the names in relation to input

impl<T: 'static> Component for Picker<T> {
    fn required_size(&mut self, viewport: (u16, u16)) -> Option<(u16, u16)> {
        self.completion_height = viewport.1.saturating_sub(4);
        Some(viewport)
    }

    fn handle_event(&mut self, event: Event, cx: &mut Context) -> EventResult {
        let key_event = match event {
            Event::Key(event) => event,
            Event::Resize(..) => return EventResult::Consumed(None),
            _ => return EventResult::Ignored(None),
        };

        let close_fn = EventResult::Consumed(Some(Box::new(|compositor: &mut Compositor, _| {
            // remove the layer
            compositor.last_picker = compositor.pop();
        })));

        match key_event.into() {
            shift!(Tab) | key!(Up) | ctrl!('p') | ctrl!('k') => {
                self.move_by(1, Direction::Backward);
            }
            key!(Tab) | key!(Down) | ctrl!('n') | ctrl!('j') => {
                self.move_by(1, Direction::Forward);
            }
            key!(PageDown) | ctrl!('f') => {
                self.page_down();
            }
            key!(PageUp) | ctrl!('b') => {
                self.page_up();
            }
            key!(Home) => {
                self.to_start();
            }
            key!(End) => {
                self.to_end();
            }
            key!(Esc) | ctrl!('c') => {
                return close_fn;
            }
            key!(Enter) => {
                if let Some(option) = self.selection() {
                    (self.callback_fn)(cx, option, Action::Replace);
                }
                return close_fn;
            }
            ctrl!('s') => {
                if let Some(option) = self.selection() {
                    (self.callback_fn)(cx, option, Action::HorizontalSplit);
                }
                return close_fn;
            }
            ctrl!('v') => {
                if let Some(option) = self.selection() {
                    (self.callback_fn)(cx, option, Action::VerticalSplit);
                }
                return close_fn;
            }
            ctrl!(' ') => {
                self.save_filter(cx);
            }
            _ => {
                if let EventResult::Consumed(_) = self.prompt.handle_event(event, cx) {
                    // TODO: recalculate only if pattern changed
                    self.score();
                }
            }
        }

        EventResult::Consumed(None)
    }

    fn render(&mut self, area: Rect, surface: &mut Surface, cx: &mut Context) {
        let text_style = cx.editor.theme.get("ui.text");
        let selected = cx.editor.theme.get("ui.text.focus");
        let highlighted = cx.editor.theme.get("special").add_modifier(Modifier::BOLD);

        // -- Render the frame:
        // clear area
        let background = cx.editor.theme.get("ui.background");
        surface.clear_with(area, background);

        // don't like this but the lifetime sucks
        let block = Block::default().borders(Borders::ALL);

        // calculate the inner area inside the box
        let inner = block.inner(area);

        block.render(area, surface);

        // -- Render the input bar:

        let area = inner.clip_left(1).with_height(1);

        let count = format!("{}/{}", self.matches.len(), self.options.len());
        surface.set_stringn(
            (area.x + area.width).saturating_sub(count.len() as u16 + 1),
            area.y,
            &count,
            (count.len()).min(area.width as usize),
            text_style,
        );

        self.prompt.render(area, surface, cx);

        // -- Separator
        let sep_style = Style::default().fg(Color::Rgb(90, 89, 119));
        let borders = BorderType::line_symbols(BorderType::Plain);
        for x in inner.left()..inner.right() {
            if let Some(cell) = surface.get_mut(x, inner.y + 1) {
                cell.set_symbol(borders.horizontal).set_style(sep_style);
            }
        }

        // -- Render the contents:
        // subtract area of prompt from top and current item marker " > " from left
        let inner = inner.clip_top(2).clip_left(3);

        let rows = inner.height;
        let offset = self.cursor - (self.cursor % std::cmp::max(1, rows as usize));

        let files = self
            .matches
            .iter_mut()
            .skip(offset)
            .map(|(index, _score)| (*index, self.options.get(*index).unwrap()));

        for (i, (_index, option)) in files.take(rows as usize).enumerate() {
            let is_active = i == (self.cursor - offset);
            if is_active {
                surface.set_string(inner.x.saturating_sub(2), inner.y + i as u16, ">", selected);
            }

            let formatted = (self.format_fn)(option);

            let (_score, highlights) = self
                .matcher
                .fuzzy_indices(&formatted, &self.prompt.line)
                .unwrap_or_default();

            surface.set_string_truncated(
                inner.x,
                inner.y + i as u16,
                &formatted,
                inner.width as usize,
                |idx| {
                    if highlights.contains(&idx) {
                        highlighted
                    } else if is_active {
                        selected
                    } else {
                        text_style
                    }
                },
                true,
                self.truncate_start,
            );
        }
    }

    fn cursor(&self, area: Rect, editor: &Editor) -> (Option<Position>, CursorKind) {
        let block = Block::default().borders(Borders::ALL);
        // calculate the inner area inside the box
        let inner = block.inner(area);

        // prompt area
        let area = inner.clip_left(1).with_height(1);

        self.prompt.cursor(area, editor)
    }
}
ass="c1">// (for example using one consistent name in the vscode's launch.json) so for any purpose // other than running tests this field should not be used. runnable?: Runnable | undefined; }; interface DiscoverTestResults { // The discovered tests. tests: TestItem[]; // For each test whose id is in this list, the response // contains all tests that are children of this test, and // client should remove old tests not included in the response. scope: string[] | undefined; // For each file whose uri is in this list, the response // contains all tests that are located in this file, and // client should remove old tests not included in the response. scopeFile: lc.TextDocumentIdentifier[] | undefined; }

Method: experimental/discoveredTests

Notification: DiscoverTestResults

This notification is sent from the server to the client when the server detects changes in the existing tests. The DiscoverTestResults is the same as the one in experimental/discoverTest response.

Method: experimental/runTest

Request: RunTestParams

interface RunTestParams {
    // Id of the tests to be run. If a test is included, all of its children are included implicitly. If
    // this property is undefined, then the server should simply run all tests.
    include?: string[] | undefined;
    // An array of test ids the user has marked as excluded from the test included in this run; exclusions
    // should apply after inclusions.
    // May be omitted if no exclusions were requested. Server should not run excluded tests or
    // any children of excluded tests.
    exclude?: string[] | undefined;
}

Response: void

Method: experimental/endRunTest

Notification:

This notification is sent from the server to the client when the current running session is finished. The server should not send any run notification after this.

Method: experimental/abortRunTest

Notification:

This notification is sent from the client to the server when the user is no longer interested in the test results. The server should clean up its resources and send a experimental/endRunTest when it is done.

Method: experimental/changeTestState

Notification: ChangeTestStateParams

type TestState = { tag: "passed" }
    | {
        tag: "failed";
        // The standard error of the test, containing the panic message. Clients should
        // render it similar to a terminal, and e.g. handle ansi colors.
        message: string;
    }
    | { tag: "started" }
    | { tag: "enqueued" }
    | { tag: "skipped" };

interface ChangeTestStateParams {
    testId: string;
    state: TestState;
}

Method: experimental/appendOutputToRunTest

Notification: string

This notification is used for reporting messages independent of any single test and related to the run session in general, e.g. cargo compiling progress messages or warnings.

Open External Documentation

This request is sent from the client to the server to obtain web and local URL(s) for documentation related to the symbol under the cursor, if available.

Method: experimental/externalDocs

Request: TextDocumentPositionParams

Response: string | null

Local Documentation

Experimental Client Capability: { "localDocs": boolean }

If this capability is set, the Open External Documentation request returned from the server will have the following structure:

interface ExternalDocsResponse {
    web?: string;
    local?: string;
}

Analyzer Status

Method: rust-analyzer/analyzerStatus

Request:

interface AnalyzerStatusParams {
    /// If specified, show dependencies of the current file.
    textDocument?: TextDocumentIdentifier;
}

Response: string

Returns internal status message, mostly for debugging purposes.

Reload Workspace

Method: rust-analyzer/reloadWorkspace

Request: null

Response: null

Reloads project information (that is, re-executes cargo metadata).

Rebuild proc-macros

Method: rust-analyzer/rebuildProcMacros

Request: null

Response: null

Rebuilds build scripts and proc-macros, and runs the build scripts to reseed the build data.

Server Status

Experimental Client Capability: { "serverStatusNotification": boolean }

Method: experimental/serverStatus

Notification:

interface ServerStatusParams {
    /// `ok` means that the server is completely functional.
    ///
    /// `warning` means that the server is partially functional.
    /// It can answer correctly to most requests, but some results
    /// might be wrong due to, for example, some missing dependencies.
    ///
    /// `error` means that the server is not functional. For example,
    /// there's a fatal build configuration problem. The server might
    /// still give correct answers to simple requests, but most results
    /// will be incomplete or wrong.
    health: "ok" | "warning" | "error",
    /// Is there any pending background work which might change the status?
    /// For example, are dependencies being downloaded?
    quiescent: boolean,
    /// Explanatory message to show on hover.
    message?: string,
}

This notification is sent from server to client. The client can use it to display persistent status to the user (in the mode line). It is similar to the showMessage, but is intended for status rather than point-in-time events.

Note that this functionality is intended primarily to inform the end user about the state of the server. In particular, it's valid for the client to completely ignore this extension. Clients are discouraged from but are allowed to use the health status to decide if it's worth sending a request to the server.

Controlling Flycheck

The flycheck/checkOnSave feature can be controlled via notifications sent by the client to the server.

Method: rust-analyzer/runFlycheck

Notification:

interface RunFlycheckParams {
    /// The text document whose cargo workspace flycheck process should be started.
    /// If the document is null or does not belong to a cargo workspace all flycheck processes will be started.
    textDocument: lc.TextDocumentIdentifier | null;
}

Triggers the flycheck processes.

Method: rust-analyzer/clearFlycheck

Notification:

interface ClearFlycheckParams {}

Clears the flycheck diagnostics.

Method: rust-analyzer/cancelFlycheck

Notification:

interface CancelFlycheckParams {}

Cancels all running flycheck processes.

View Syntax Tree

Method: rust-analyzer/viewSyntaxTree

Request:

interface ViewSyntaxTreeParams {
    textDocument: TextDocumentIdentifier,
}

Response: string

Returns json representation of the file's syntax tree. Used to create a treeView for debugging and working on rust-analyzer itself.

View Hir

Method: rust-analyzer/viewHir

Request: TextDocumentPositionParams

Response: string

Returns a textual representation of the HIR of the function containing the cursor. For debugging or when working on rust-analyzer itself.

View Mir

Method: rust-analyzer/viewMir

Request: TextDocumentPositionParams

Response: string

Returns a textual representation of the MIR of the function containing the cursor. For debugging or when working on rust-analyzer itself.

Get Failed Obligations

Method: rust-analyzer/getFailedObligations

Request: TextDocumentPositionParams

Response: string

Returns information about failed trait obligations at the given position. For debugging or when working on rust-analyzer itself.

Interpret Function

Method: rust-analyzer/interpretFunction

Request: TextDocumentPositionParams

Response: string

Tries to evaluate the function using internal rust analyzer knowledge, without compiling the code. Currently evaluates the function under cursor, but will give a runnable in future. Highly experimental.

View File Text

Method: rust-analyzer/viewFileText

Request: TextDocumentIdentifier

Response: string

Returns the text of a file as seen by the server. This is for debugging file sync problems.

View ItemTree

Method: rust-analyzer/viewItemTree

Request:

interface ViewItemTreeParams {
    textDocument: TextDocumentIdentifier,
}

Response: string

Returns a textual representation of the ItemTree of the currently open file, for debugging.

View Crate Graph

Method: rust-analyzer/viewCrateGraph

Request:

interface ViewCrateGraphParams {
    full: boolean,
}

Response: string

Renders rust-analyzer's crate graph as an SVG image.

If full is true, the graph includes non-workspace crates (crates.io dependencies as well as sysroot crates).

Expand Macro

Method: rust-analyzer/expandMacro

Request:

interface ExpandMacroParams {
    textDocument: TextDocumentIdentifier,
    position: Position,
}

Response:

interface ExpandedMacro {
    name: string,
    expansion: string,
}

Expands macro call at a given position.

Hover Actions

Experimental Client Capability: { "hoverActions": boolean }

If this capability is set, Hover request returned from the server might contain an additional field, actions:

interface Hover {
    ...
    actions?: CommandLinkGroup[];
}

interface CommandLink extends Command {
    /**
     * A tooltip for the command, when represented in the UI.
     */
    tooltip?: string;
}

interface CommandLinkGroup {
    title?: string;
    commands: CommandLink[];
}

Such actions on the client side are appended to a hover bottom as command links:

  +-----------------------------+
  | Hover content               |
  |                             |
  +-----------------------------+
  | _Action1_ | _Action2_       |  <- first group, no TITLE
  +-----------------------------+
  | TITLE _Action1_ | _Action2_ |  <- second group
  +-----------------------------+
  ...

Open Cargo.toml

Upstream Issue: https://github.com/rust-lang/rust-analyzer/issues/6462

Experimental Server Capability: { "openCargoToml": boolean }

This request is sent from client to server to open the current project's Cargo.toml

Method: experimental/openCargoToml

Request: OpenCargoTomlParams

Response: Location | null

Example

// Cargo.toml
[package]
// src/main.rs

/* cursor here*/

experimental/openCargoToml returns a single Link to the start of the [package] keyword.

This request is sent from client to server to get the list of tests for the specified position.

Method: rust-analyzer/relatedTests

Request: TextDocumentPositionParams

Response: TestInfo[]

interface TestInfo {
    runnable: Runnable;
}

Hover Range

Upstream Issue: https://github.com/microsoft/language-server-protocol/issues/377

Experimental Server Capability: { "hoverRange": boolean }

This extension allows passing a Range as a position field of HoverParams. The primary use-case is to use the hover request to show the type of the expression currently selected.

interface HoverParams extends WorkDoneProgressParams {
    textDocument: TextDocumentIdentifier;
    position: Range | Position;
}

Whenever the client sends a Range, it is understood as the current selection and any hover included in the range will show the type of the expression if possible.

Example

fn main() {
    let expression = $01 + 2 * 3$0;
}

Triggering a hover inside the selection above will show a result of i32.

Move Item

Upstream Issue: https://github.com/rust-lang/rust-analyzer/issues/6823

This request is sent from client to server to move item under cursor or selection in some direction.

Method: experimental/moveItem

Request: MoveItemParams

Response: SnippetTextEdit[]

export interface MoveItemParams {
    textDocument: TextDocumentIdentifier,
    range: Range,
    direction: Direction
}

export const enum Direction {
    Up = "Up",
    Down = "Down"
}

Workspace Symbols Filtering

Upstream Issue: https://github.com/microsoft/language-server-protocol/issues/941

Experimental Server Capability: { "workspaceSymbolScopeKindFiltering": boolean }

Extends the existing workspace/symbol request with ability to filter symbols by broad scope and kind of symbol. If this capability is set, workspace/symbol parameter gains two new optional fields:

interface WorkspaceSymbolParams {
    /**
     * Return only the symbols defined in the specified scope.
     */
    searchScope?: WorkspaceSymbolSearchScope;
    /**
     * Return only the symbols of specified kinds.
     */
    searchKind?: WorkspaceSymbolSearchKind;
    ...
}

const enum WorkspaceSymbolSearchScope {
    Workspace = "workspace",
    WorkspaceAndDependencies = "workspaceAndDependencies"
}

const enum WorkspaceSymbolSearchKind {
    OnlyTypes = "onlyTypes",
    AllSymbols = "allSymbols"
}

Client Commands

Upstream Issue: https://github.com/microsoft/language-server-protocol/issues/642

Experimental Client Capability: { "commands?": ClientCommandOptions }

Certain LSP types originating on the server, notably code lenses, embed commands. Commands can be serviced either by the server or by the client. However, the server doesn't know which commands are available on the client.

This extensions allows the client to communicate this info.

export interface ClientCommandOptions {
    /**
     * The commands to be executed on the client
     */
    commands: string[];
}

Colored Diagnostic Output

Experimental Client Capability: { "colorDiagnosticOutput": boolean }

If this capability is set, the "full compiler diagnostics" provided by checkOnSave will include ANSI color and style codes to render the diagnostic in a similar manner as cargo. This is translated into --message-format=json-diagnostic-rendered-ansi when flycheck is run, instead of the default --message-format=json.

The full compiler rendered diagnostics are included in the server response regardless of this capability:

// https://microsoft.github.io/language-server-protocol/specifications/specification-current#diagnostic
export interface Diagnostic {
    ...
    data?: {
        /**
         * The human-readable compiler output as it would be printed to a terminal.
         * Includes ANSI color and style codes if the client has set the experimental
         * `colorDiagnosticOutput` capability.
         */
        rendered?: string;
    };
}

Dependency Tree

Method: rust-analyzer/fetchDependencyList

Request:

export interface FetchDependencyListParams {}

Response:

export interface FetchDependencyListResult {
    crates: {
        name: string;
        version: string;
        path: string;
    }[];
}

Returns all crates from this workspace, so it can be used create a viewTree to help navigate the dependency tree.

View Recursive Memory Layout

Method: rust-analyzer/viewRecursiveMemoryLayout

Request: TextDocumentPositionParams

Response:

export interface RecursiveMemoryLayoutNode = {
    /// Name of the item, or [ROOT], `.n` for tuples
    item_name: string;
    /// Full name of the type (type aliases are ignored)
    typename: string;
    /// Size of the type in bytes
    size: number;
    /// Alignment of the type in bytes
    alignment: number;
    /// Offset of the type relative to its parent (or 0 if it's the root)
    offset: number;
    /// Index of the node's parent (or -1 if it's the root)
    parent_idx: number;
    /// Index of the node's children (or -1 if it does not have children)
    children_start: number;
    /// Number of child nodes (unspecified if it does not have children)
    children_len: number;
};

export interface RecursiveMemoryLayout = {
    nodes: RecursiveMemoryLayoutNode[];
};

Returns a vector of nodes representing items in the datatype as a tree, RecursiveMemoryLayout::nodes[0] is the root node.

If RecursiveMemoryLayout::nodes::length == 0 we could not find a suitable type.

Generic Types do not give anything because they are incomplete. Fully specified generic types do not give anything if they are selected directly but do work when a child of other types this is consistent with other behavior.

Unresolved questions: