Debian Codegraph @

helix-view/src/action.rs

raw symbols SCIP
1 use std::{borrow::Cow, fmt};
2
3 use helix_lsp::{lsp, LanguageServerId};
4
5 use crate::Editor;
6
7 /// A titled action against the editor, shown in the code action menu.
8 ///
9 /// LSP code actions are converted into `Action`s, but the type is provider-agnostic: internal
10 /// features (for example the spell checker) produce `Action`s the same way, so they appear in the
11 /// same menu without the menu knowing where they came from.
12 pub struct Action {
13 title: Cow<'static, str>,
14 /// Sort key; higher priority actions are shown first. See `lsp_code_action_priority`.
15 pub priority: u8,
16 action: Box<dyn Fn(&mut Editor) + Send + Sync + 'static>,
17 }
18
19 impl fmt::Debug for Action {
20 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
21 f.debug_struct("Action")
22 .field("title", &self.title)
23 .field("priority", &self.priority)
24 .finish_non_exhaustive()
25 }
26 }
27
28 impl Action {
29 pub fn new<T: Into<Cow<'static, str>>, F: Fn(&mut Editor) + Send + Sync + 'static>(
30 title: T,
31 priority: u8,
32 action: F,
33 ) -> Self {
34 Self {
35 title: title.into(),
36 priority,
37 action: Box::new(action),
38 }
39 }
40
41 pub fn title(&self) -> &str {
42 &self.title
43 }
44
45 pub fn execute(&self, editor: &mut Editor) {
46 (self.action)(editor);
47 }
48
49 /// Builds an `Action` from an LSP code action or command.
50 pub fn lsp(server_id: LanguageServerId, action: lsp::CodeActionOrCommand) -> Self {
51 let title = match &action {
52 lsp::CodeActionOrCommand::CodeAction(action) => action.title.clone(),
53 lsp::CodeActionOrCommand::Command(command) => command.title.clone(),
54 };
55 let priority = lsp_code_action_priority(&action);
56
57 Self::new(title, priority, move |editor| {
58 let Some(language_server) = editor.language_server_by_id(server_id) else {
59 editor.set_error("Language Server disappeared");
60 return;
61 };
62 let offset_encoding = language_server.offset_encoding();
63 match &action {
64 lsp::CodeActionOrCommand::Command(command) => {
65 log::debug!("code action command: {:?}", command);
66 editor.execute_lsp_command(command.clone(), server_id);
67 }
68 lsp::CodeActionOrCommand::CodeAction(code_action) => {
69 log::debug!("code action: {:?}", code_action);
70 // We support lsp "codeAction/resolve" for `edit` and `command` fields.
71 let resolved;
72 let code_action = if code_action.edit.is_none() || code_action.command.is_none()
73 {
74 resolved = language_server
75 .resolve_code_action(code_action)
76 .and_then(|future| helix_lsp::block_on(future).ok());
77 resolved.as_ref().unwrap_or(code_action)
78 } else {
79 code_action
80 };
81
82 if let Some(ref workspace_edit) = code_action.edit {
83 let _ = editor.apply_workspace_edit(offset_encoding, workspace_edit);
84 }
85
86 // If a code action provides both an edit and a command the edit is applied
87 // first, then the command.
88 if let Some(command) = &code_action.command {
89 editor.execute_lsp_command(command.clone(), server_id);
90 }
91 }
92 }
93 })
94 }
95 }
96
97 /// Computes the sort priority for an LSP code action; higher is shown first.
98 ///
99 /// This roughly matches VSCode's ordering: code actions are sorted first by the category declared
100 /// on the `kind` field, then by whether they fix a diagnostic, then by whether they are marked
101 /// preferred. See <https://github.com/microsoft/vscode/blob/eaec601dd69aeb4abb63b9601a6f44308c8d8c6e/src/vs/editor/contrib/codeAction/browser/codeActionWidget.ts>.
102 fn lsp_code_action_priority(action: &lsp::CodeActionOrCommand) -> u8 {
103 // The `kind` field is open ended in the LSP spec, but in practice a closed set of common values
104 // (mostly suggested by the spec) is used. VSCode shows these as menu headers; we don't, but we
105 // sort by them the same way.
106 let category = if let lsp::CodeActionOrCommand::CodeAction(lsp::CodeAction {
107 kind: Some(kind),
108 ..
109 }) = action
110 {
111 let mut components = kind.as_str().split('.');
112 match components.next() {
113 Some("quickfix") => 7,
114 Some("refactor") => match components.next() {
115 Some("extract") => 6,
116 Some("inline") => 5,
117 Some("rewrite") => 4,
118 Some("move") => 3,
119 Some("surround") => 2,
120 _ => 1,
121 },
122 Some("source") => 1,
123 _ => 0,
124 }
125 } else {
126 0
127 };
128 let fixes_diagnostic = matches!(
129 action,
130 lsp::CodeActionOrCommand::CodeAction(lsp::CodeAction {
131 diagnostics: Some(diagnostics),
132 ..
133 }) if !diagnostics.is_empty()
134 );
135 let is_preferred = matches!(
136 action,
137 lsp::CodeActionOrCommand::CodeAction(lsp::CodeAction {
138 is_preferred: Some(true),
139 ..
140 })
141 );
142
143 // Weight the criteria so their scores can't overlap: two actions in the same category sort
144 // closer than actions in different categories, with `fixes_diagnostic` and `is_preferred`
145 // breaking ties.
146 let mut priority = category * 4;
147 if fixes_diagnostic {
148 priority += 2;
149 }
150 if is_preferred {
151 priority += 1;
152 }
153 priority
154 }