Skip to content

The IDE you know, rebuilt in Rust. IntelliJ IDEA–style keymap, tool windows and search-everywhere in a fast native app: editor, code insight, debugger, Git, terminal, database and HTTP clients for 60+ languages.

fix(editor): match quick fixes to their diagnostics (#2411)

l0ng-aibdb8ca554994
diff --git a/crates/ide-host/src/ops/lsp.rs b/crates/ide-host/src/ops/lsp.rs
index e632087f7..b13117653 100644
--- a/crates/ide-host/src/ops/lsp.rs
+++ b/crates/ide-host/src/ops/lsp.rs
@@ -823,6 +823,8 @@ fn plugin_code_action(plugin: &str, root: &Path, a: ide_plugin::CodeAction) -> C
.and_then(|r| serde_json::to_value(r).ok());
CodeAction {
title: a.title,
+ diagnostics: Vec::new(),
+ original_diagnostics: None,
kind: a.kind,
is_preferred: a.preferred,
disabled_reason,
diff --git a/crates/ide-host/tests/workspace_edits.rs b/crates/ide-host/tests/workspace_edits.rs
index 2994603d8..9cbfe90d3 100644
--- a/crates/ide-host/tests/workspace_edits.rs
+++ b/crates/ide-host/tests/workspace_edits.rs
@@ -197,6 +197,8 @@ async fn code_actions_skip_a_command_no_server_provides_after_their_edit() {
let info = ops::doc::open(&host, "main", file.clone()).await.unwrap();
// Optimize Imports as vtsls offers it: the edit, then a command its client runs itself.
let action = |edit: bool| CodeAction {
+ diagnostics: Vec::new(),
+ original_diagnostics: None,
title: "Organize Imports".into(),
kind: Some("source.organizeImports".into()),
is_preferred: false,
diff --git a/crates/ide-lsp/src/convert.rs b/crates/ide-lsp/src/convert.rs
index 9fdc609e4..601de40b1 100644
--- a/crates/ide-lsp/src/convert.rs
+++ b/crates/ide-lsp/src/convert.rs
@@ -568,10 +568,18 @@ pub fn lsp_command(c: &Command) -> lsp::Command {
}
}
-pub fn code_action(conv: &Conv, a: lsp::CodeActionOrCommand, server: ServerId) -> CodeAction {
+pub fn code_action(
+ conv: &Conv,
+ path: &Path,
+ a: lsp::CodeActionOrCommand,
+ server: ServerId,
+ server_name: &str,
+) -> CodeAction {
match a {
lsp::CodeActionOrCommand::Command(c) => CodeAction {
title: c.title.clone(),
+ diagnostics: Vec::new(),
+ original_diagnostics: None,
kind: None,
is_preferred: false,
disabled_reason: None,
@@ -582,6 +590,13 @@ pub fn code_action(conv: &Conv, a: lsp::CodeActionOrCommand, server: ServerId) -
},
lsp::CodeActionOrCommand::CodeAction(a) => CodeAction {
title: a.title,
+ original_diagnostics: a.diagnostics.as_ref().and_then(|d| serde_json::to_string(d).ok()),
+ diagnostics: a
+ .diagnostics
+ .unwrap_or_default()
+ .into_iter()
+ .map(|d| diagnostic(conv, path, d, server_name))
+ .collect(),
kind: a.kind.map(|k| k.as_str().to_owned()),
is_preferred: a.is_preferred.unwrap_or(false),
disabled_reason: a.disabled.map(|d| d.reason),
@@ -597,7 +612,7 @@ pub fn lsp_code_action(a: &CodeAction) -> lsp::CodeAction {
lsp::CodeAction {
title: a.title.clone(),
kind: a.kind.clone().map(lsp::CodeActionKind::from),
- diagnostics: None,
+ diagnostics: a.original_diagnostics.as_deref().and_then(|d| serde_json::from_str(d).ok()),
edit: None,
command: a.command.as_ref().map(lsp_command),
is_preferred: a.is_preferred.then_some(true),
@@ -1073,6 +1088,66 @@ mod tests {
use super::*;
use serde_json::json;
+ #[test]
+ fn code_action_diagnostics_use_ide_coordinates_and_round_trip_for_resolve() {
+ let path = Path::new("/go.mod");
+ let conv = Conv::new(Encoding::Utf8, |_| Some(Arc::new(DocText::new("😀 dependency"))));
+ let raw: lsp::Diagnostic = serde_json::from_value(json!({
+ "range": { "start": { "line": 0, "character": 5 }, "end": { "line": 0, "character": 15 } },
+ "message": "github.com/sergi/go-diff is not used in this module",
+ "severity": 2,
+ "code": 123,
+ "source": "go mod tidy",
+ "data": { "fix": "remove" }
+ }))
+ .unwrap();
+ let incoming = lsp::CodeAction {
+ title: "Remove dependency: github.com/sergi/go-diff".into(),
+ diagnostics: Some(vec![raw.clone()]),
+ ..Default::default()
+ };
+ let action = code_action(&conv, path, lsp::CodeActionOrCommand::CodeAction(incoming), ServerId(1), "gopls");
+ assert_eq!(action.diagnostics, vec![diagnostic(&conv, path, raw.clone(), "gopls")]);
+ assert_eq!(action.diagnostics[0].range, Range::new(Pos::new(0, 3), Pos::new(0, 13)));
+ assert_eq!(action.diagnostics[0].code.as_deref(), Some("123"));
+ let action: CodeAction = serde_json::from_value(serde_json::to_value(action).unwrap()).unwrap();
+ assert_eq!(lsp_code_action(&action).diagnostics, Some(vec![raw.clone()]));
+ let resolved = merge_code_action(&conv, action, lsp::CodeAction::default());
+ assert_eq!(lsp_code_action(&resolved).diagnostics, Some(vec![raw]));
+ assert_eq!(resolved.diagnostics.len(), 1);
+ }
+
+ #[test]
+ fn code_actions_without_diagnostics_keep_them_absent_for_resolve() {
+ let conv = Conv::utf16();
+ for incoming in [
+ lsp::CodeActionOrCommand::CodeAction(lsp::CodeAction { title: "Fix".into(), ..Default::default() }),
+ lsp::CodeActionOrCommand::Command(lsp::Command {
+ title: "Fix".into(),
+ command: "fix".into(),
+ arguments: None,
+ }),
+ ] {
+ let action = code_action(&conv, Path::new("/a"), incoming, ServerId(1), "srv");
+ assert!(action.diagnostics.is_empty());
+ assert!(lsp_code_action(&action).diagnostics.is_none());
+ }
+ let raw = lsp::Diagnostic::new_simple(lsp::Range::default(), "problem".into());
+ let expected = diagnostic(&conv, Path::new("/a"), raw.clone(), "srv");
+ let action = code_action(
+ &conv,
+ Path::new("/a"),
+ lsp::CodeActionOrCommand::CodeAction(lsp::CodeAction {
+ diagnostics: Some(vec![raw]),
+ ..Default::default()
+ }),
+ ServerId(1),
+ "srv",
+ );
+ assert_eq!(action.diagnostics, vec![expected]);
+ assert_eq!(action.diagnostics[0].source.as_deref(), Some("srv"));
+ }
+
#[test]
fn merged_rename_edits_keep_the_first_servers_ones() {
let edit = |l: u32, c: u32, text: &str| TextEdit {
diff --git a/crates/ide-lsp/src/lib.rs b/crates/ide-lsp/src/lib.rs
index 30cf477a9..c6b049db5 100644
--- a/crates/ide-lsp/src/lib.rs
+++ b/crates/ide-lsp/src/lib.rs
@@ -2074,7 +2074,8 @@ impl LspManager {
.unwrap_or_default()
.into_iter()
.map(|a| {
- let mut action = convert::code_action(&conv, a, t.server.id);
+ let mut action =
+ convert::code_action(&conv, &snap.path, a, t.server.id, &t.server.name);
self.tag_injected_origin(doc, &mut action.data);
self.tag_injected_command(doc, action.server, &mut action.command);
action
diff --git a/crates/ide-lsp/src/types.rs b/crates/ide-lsp/src/types.rs
index 042651bd9..7679da76b 100644
--- a/crates/ide-lsp/src/types.rs
+++ b/crates/ide-lsp/src/types.rs
@@ -2,7 +2,7 @@
use ide_core::event::ServerStatus;
use ide_core::settings::ExternalFormatter;
-use ide_core::{Location, Range, ServerId, SymbolKind, TextEdit, WorkspaceEdit};
+use ide_core::{Diagnostic, Location, Range, ServerId, SymbolKind, TextEdit, WorkspaceEdit};
use serde::{Deserialize, Serialize};
use specta::Type;
@@ -197,6 +197,14 @@ pub struct InlineCompletionItem {
#[serde(rename_all = "camelCase")]
pub struct CodeAction {
pub title: String,
+ /// Diagnostics this action fixes, in IDE coordinates.
+ #[serde(default)]
+ #[specta(optional)]
+ pub diagnostics: Vec<Diagnostic>,
+ /// Original server diagnostics, including encoding and data, for codeAction/resolve.
+ #[serde(default)]
+ #[specta(optional)]
+ pub original_diagnostics: Option<String>,
/// LSP kind, e.g. `quickfix`, `refactor.extract`, `source.organizeImports`.
pub kind: Option<String>,
pub is_preferred: bool,
diff --git a/crates/ide-lsp/tests/mock_server.rs b/crates/ide-lsp/tests/mock_server.rs
index 713427c2e..7fb399989 100644
--- a/crates/ide-lsp/tests/mock_server.rs
+++ b/crates/ide-lsp/tests/mock_server.rs
@@ -1449,7 +1449,7 @@ async fn diagnostics_become_events_and_feed_code_actions() {
s.respond(
"textDocument/codeAction",
json!([
- { "title": "Remove", "kind": "quickfix", "isPreferred": true, "data": { "id": 7 } },
+ { "title": "Remove", "kind": "quickfix", "isPreferred": true, "data": { "id": 7 }, "diagnostics": [diag(0)] },
{ "title": "Run", "command": "mock.run", "arguments": [1] }
]),
);
@@ -1464,6 +1464,9 @@ async fn diagnostics_become_events_and_feed_code_actions() {
assert_eq!(actions.len(), 2);
assert_eq!(actions[0].kind.as_deref(), Some("quickfix"));
assert!(actions[0].is_preferred);
+ assert_eq!(actions[0].diagnostics[0].range, rng(0, 4, 0, 10));
+ assert_eq!(actions[0].diagnostics[0].message, "unused variable");
+ assert!(actions[1].diagnostics.is_empty());
assert_eq!(actions[1].command.as_ref().unwrap().command, "mock.run");
let req = &s.requested("textDocument/codeAction")[0];
assert_eq!(req["context"]["only"], json!(["quickfix"]));
@@ -1473,6 +1476,8 @@ async fn diagnostics_become_events_and_feed_code_actions() {
let resolved = h.mgr.resolve_code_action(doc, actions[0].clone()).await.unwrap();
assert_eq!(s.requested("codeAction/resolve")[0]["data"], json!({ "id": 7 }));
+ assert_eq!(s.requested("codeAction/resolve")[0]["diagnostics"], json!([diag(0)]));
+ assert_eq!(resolved.diagnostics, actions[0].diagnostics);
let edit = resolved.edit.unwrap();
assert!(
matches!(&edit.files[0], FileEdit::Edit { path: p, edits, .. } if p == &path && edits[0].range == rng(0, 0, 1, 0))
diff --git a/src/bindings.ts b/src/bindings.ts
index 296ded8d0..0abfad6ef 100644
--- a/src/bindings.ts
+++ b/src/bindings.ts
@@ -2398,6 +2398,10 @@ export type CloseContext = {
export type CodeAction = {
title: string,
+ /** Diagnostics this action fixes, in IDE coordinates. */
+ diagnostics?: Diagnostic[],
+ /** Original server diagnostics, including encoding and data, for codeAction/resolve. */
+ originalDiagnostics?: string | null,
/** LSP kind, e.g. `quickfix`, `refactor.extract`, `source.organizeImports`. */
kind: string | null,
isPreferred: boolean,
diff --git a/src/editor/lsp/autoImport.ts b/src/editor/lsp/autoImport.ts
index 7a8321005..cf99dd7e4 100644
--- a/src/editor/lsp/autoImport.ts
+++ b/src/editor/lsp/autoImport.ts
@@ -11,7 +11,7 @@ import { commands, type CodeAction, type Diagnostic } from "@/platform/ipc";
import { editorPrefs } from "@/platform/editorSettings";
import { docOf, isUnavailable, lspRequest } from "./lsp";
import { diagnosticsFor, subscribeDiagnostics } from "./diagnostics";
-import { applyCodeAction } from "./intentions";
+import { actionsForDiagnostic, applyCodeAction } from "./intentions";
import { offsetsToRange, rangeToOffsets } from "./positions";
import { featureBackoff } from "./availability";
@@ -92,7 +92,7 @@ const autoImportPlugin = ViewPlugin.fromClass(
if (this.tried.has(key)) continue;
this.tried.add(key);
const actions = await lspRequest(() => commands.lspCodeActions(doc.doc, d.range, ["quickfix"]));
- const fix = unambiguousImport(actions);
+ const fix = unambiguousImport(actionsForDiagnostic(actions, d));
if (fix && !editTouchesLine(fix, doc.path, caretLine)) {
await applyCodeAction(this.view, fix);
return;
diff --git a/src/editor/lsp/diagnostics.test.ts b/src/editor/lsp/diagnostics.test.ts
index 0b9adc8f3..ce6b220e0 100644
--- a/src/editor/lsp/diagnostics.test.ts
+++ b/src/editor/lsp/diagnostics.test.ts
@@ -71,10 +71,19 @@ describe("toLintDiagnostics", () => {
d(0, 3, 7, "error", { deprecated: true }),
]);
expect(out).toEqual([
- { from: 3, to: 7, severity: "error", message: "m0:3", source: undefined, markClass: "cm-lsp-deprecated" },
+ {
+ from: 3,
+ to: 7,
+ problem: d(0, 3, 7, "error", { deprecated: true }),
+ severity: "error",
+ message: "m0:3",
+ source: undefined,
+ markClass: "cm-lsp-deprecated",
+ },
{
from: 18,
to: 19,
+ problem: d(1, 6, 7, "warning", { unnecessary: true, source: "rustc", code: "unused" }),
severity: "warning",
message: "m1:6",
source: "rustc unused",
diff --git a/src/editor/lsp/diagnostics.ts b/src/editor/lsp/diagnostics.ts
index 751b401f9..64c7edd2a 100644
--- a/src/editor/lsp/diagnostics.ts
+++ b/src/editor/lsp/diagnostics.ts
@@ -125,9 +125,13 @@ export function installDiagnosticsEvents(): () => void {
const SEVERITY_RANK: Record<Severity, number> = { error: 0, warning: 1, info: 2, hint: 3 };
+export interface EditorDiagnostic extends LintDiagnostic {
+ problem?: Diagnostic;
+}
+
/** Backend diagnostics → lint diagnostics for `doc` (empty ranges widened to one character). */
-export function toLintDiagnostics(doc: Text, items: readonly Diagnostic[]): LintDiagnostic[] {
- const out: LintDiagnostic[] = items.map((d) => {
+export function toLintDiagnostics(doc: Text, items: readonly Diagnostic[]): EditorDiagnostic[] {
+ const out: EditorDiagnostic[] = items.map((d) => {
let { from, to } = rangeToOffsets(doc, d.range);
if (from === to) {
const line = doc.lineAt(from);
@@ -142,6 +146,7 @@ export function toLintDiagnostics(doc: Text, items: readonly Diagnostic[]): Lint
return {
from,
to,
+ problem: d,
severity: d.severity,
message: d.message,
source: [d.source, isInternalCode(d.code) ? null : d.code].filter(Boolean).join(" ") || undefined,
@@ -282,7 +287,7 @@ export function diagnosticsExtension() {
export interface PlacedDiagnostic {
from: number;
to: number;
- diagnostic: LintDiagnostic;
+ diagnostic: EditorDiagnostic;
}
export function diagnosticsAt(view: EditorView, pos: number): PlacedDiagnostic[] {
diff --git a/src/editor/lsp/hover.ts b/src/editor/lsp/hover.ts
index f69594f39..ae9891d8b 100644
--- a/src/editor/lsp/hover.ts
+++ b/src/editor/lsp/hover.ts
@@ -18,7 +18,7 @@ import {
} from "@/platform/ipc";
import { executeAction } from "@/platform/actions";
import { shortcutLabel } from "@/platform/keymap";
-import { diagnosticsAt, type PlacedDiagnostic } from "./diagnostics";
+import { diagnosticsAt, type PlacedDiagnostic, type EditorDiagnostic } from "./diagnostics";
import { isEmptyMarkup, languageForPath, renderMarkup } from "./markdown";
import { selectableText } from "@/ui/selectableText";
import { docOf, lspRequest, reportLspError } from "./lsp";
@@ -104,7 +104,7 @@ function renderDiagnostics(view: EditorView, diags: PlacedDiagnostic[]): HTMLEle
fix.className = "cm-lsp-link-button";
const keys = shortcutLabel("code.showIntentions");
fix.textContent = keys ? `More actions… ${keys}` : "More actions…";
- if (d.severity !== "hint") offerQuickFix(view, meta, fix, from, to);
+ if (d.severity !== "hint") offerQuickFix(view, meta, fix, from, to, d);
fix.addEventListener("mousedown", (e) => e.preventDefault());
fix.addEventListener("click", () => {
view.dispatch({ selection: EditorSelection.cursor(from) });
@@ -119,9 +119,16 @@ function renderDiagnostics(view: EditorView, diags: PlacedDiagnostic[]): HTMLEle
}
/** IDEA's hover link to the problem's preferred quick fix, shown once the server named one. */
-function offerQuickFix(view: EditorView, meta: HTMLElement, before: HTMLElement, from: number, to: number) {
+function offerQuickFix(
+ view: EditorView,
+ meta: HTMLElement,
+ before: HTMLElement,
+ from: number,
+ to: number,
+ diagnostic: EditorDiagnostic,
+) {
const doc = view.state.doc;
- void quickFixesAt(view, from, to)
+ void quickFixesAt(view, from, to, diagnostic.problem)
.then(([action]) => {
if (!action || view.state.doc !== doc || !before.isConnected) return;
const link = document.createElement("button");
diff --git a/src/editor/lsp/importsOnPaste.ts b/src/editor/lsp/importsOnPaste.ts
index f0335ca4d..0f9594eba 100644
--- a/src/editor/lsp/importsOnPaste.ts
+++ b/src/editor/lsp/importsOnPaste.ts
@@ -10,6 +10,7 @@ import { subscribeDiagnostics, type DiagnosticPublication } from "./diagnostics"
import { docOf, lspRequest } from "./lsp";
import { comparePos, rangeToOffsets } from "./positions";
import { closePopup, openPopup, useLspPopup, type LspPopup } from "./popupStore";
+import { actionsForDiagnostic } from "./intentions";
const WAIT_MS = 8000;
const SETTLE_MS = 200;
@@ -281,7 +282,7 @@ const importsOnPastePlugin = ViewPlugin.fromClass(
const seen = new Set<string>();
try {
for (const d of diagnostics) {
- const key = JSON.stringify(d.range);
+ const key = JSON.stringify([d.range, d.message, d.code, d.source]);
if (seen.has(key)) continue;
seen.add(key);
const id = nextRequestId();
@@ -301,7 +302,7 @@ const importsOnPastePlugin = ViewPlugin.fromClass(
p.abort.signal.removeEventListener("abort", cancel);
}
if (!this.current(p)) return;
- let fix = pastedImport(actions);
+ let fix = pastedImport(actionsForDiagnostic(actions, d));
if (!fix) continue;
fix = withCommandEdit(fix, doc.path);
if (!fix.edit)
diff --git a/src/editor/lsp/intentions.test.ts b/src/editor/lsp/intentions.test.ts
index 1fe189199..4c639174e 100644
--- a/src/editor/lsp/intentions.test.ts
+++ b/src/editor/lsp/intentions.test.ts
@@ -2,7 +2,7 @@ import { afterEach, describe, expect, it, vi } from "vitest";
import { EditorState } from "@codemirror/state";
import { EditorView } from "@codemirror/view";
import { setDiagnostics } from "@codemirror/lint";
-import type { CodeAction } from "@/bindings";
+import type { CodeAction, Diagnostic } from "@/bindings";
const resolved: CodeAction = {
title: "Introduce local variable",
@@ -23,6 +23,8 @@ const resolved: CodeAction = {
data: null,
server: 1,
};
+const runInteractiveCodeAction = vi.fn(async () => false);
+vi.mock("./interactiveCommand", () => ({ runInteractiveCodeAction }));
const lspCodeActions = vi.fn();
const lspApplyCodeAction = vi.fn();
const lspResolveCodeAction = vi.fn(async () => ({ status: "ok" as const, data: resolved }));
@@ -36,6 +38,9 @@ vi.mock("@/platform/ipc", async (orig) => {
});
const {
+ actionsForDiagnostic,
+ applyQuickFix,
+ quickFixesAt,
applyKindSilently,
bulbLine,
changedLines,
@@ -46,7 +51,7 @@ const {
listedIntentions,
withInspectionControls,
} = await import("./intentions");
-const { setFileDiagnostics } = await import("./diagnostics");
+const { setFileDiagnostics, toLintDiagnostics } = await import("./diagnostics");
const { lspDoc } = await import("./lsp");
const views: EditorView[] = [];
@@ -259,3 +264,97 @@ describe("indentUnderBrace", () => {
expect(indentUnderBrace(text("class A:\npass\nx"), 2, 3, " ")).toEqual([]);
});
});
+
+describe("quick fixes for overlapping diagnostics", () => {
+ const unused: Diagnostic = {
+ range: { start: { line: 0, col: 1 }, end: { line: 0, col: 37 } },
+ severity: "warning",
+ message: "github.com/sergi/go-diff is not used in this module",
+ source: "go mod tidy",
+ code: null,
+ unnecessary: false,
+ deprecated: false,
+ };
+ const upgrade: Diagnostic = {
+ ...unused,
+ severity: "info",
+ message: "github.com/sergi/go-diff can be upgraded",
+ source: "upgrade available",
+ };
+ const remove: CodeAction = {
+ ...resolved,
+ title: "Remove dependency: github.com/sergi/go-diff",
+ kind: "quickfix",
+ isPreferred: true,
+ diagnostics: [unused],
+ };
+ const update: CodeAction = {
+ ...remove,
+ title: "Upgrade to v1.4.0",
+ isPreferred: false,
+ diagnostics: [upgrade],
+ };
+
+ it("keeps only actions for each problem even when another problem's fix is preferred", () => {
+ expect(actionsForDiagnostic([remove, update], unused)).toEqual([remove]);
+ expect(actionsForDiagnostic([remove, update], upgrade)).toEqual([update]);
+ expect(actionsForDiagnostic([remove], upgrade)).toEqual([]);
+ expect(actionsForDiagnostic([remove, { ...update, diagnostics: [] }], upgrade)).toEqual([]);
+ expect(actionsForDiagnostic([{ ...remove, diagnostics: [unused, upgrade] }], upgrade)).toHaveLength(1);
+ });
+
+ it("retains the range fallback only when every action omits diagnostics", () => {
+ const actions = [
+ { ...remove, diagnostics: [] },
+ { ...update, diagnostics: undefined },
+ ];
+ expect(actionsForDiagnostic(actions, unused)).toEqual(actions);
+ expect(actionsForDiagnostic(actions, upgrade)).toEqual(actions);
+ });
+
+ it.each([
+ { message: "another problem" },
+ { range: { ...unused.range, end: { line: 0, col: 38 } } },
+ { code: "other" },
+ { source: "other" },
+ ])("checks diagnostic identity: %j", (over) => {
+ const problem = { ...unused, code: "unused" };
+ expect(actionsForDiagnostic([{ ...remove, diagnostics: [{ ...problem, ...over }] }], problem)).toEqual([]);
+ });
+
+ it.each([unused, upgrade])("uses the matching fix for hover and Apply Quick Fix: $message", async (problem) => {
+ const view = new EditorView({
+ state: EditorState.create({
+ doc: " github.com/sergi/go-diff v1.3.1 ",
+ selection: { anchor: 3 },
+ extensions: [lspDoc.of({ doc: 1, path: "/p/go.mod", language: "go", uiMode: null, readOnly: false })],
+ }),
+ });
+ views.push(view);
+ view.dispatch(setDiagnostics(view.state, toLintDiagnostics(view.state.doc, [problem])));
+ const expected = problem === unused ? remove : update;
+ lspCodeActions.mockResolvedValue({ status: "ok", data: [remove, update] });
+ expect(await quickFixesAt(view, 1, 37, problem)).toEqual([expected]);
+ await applyQuickFix(view);
+ expect(runInteractiveCodeAction).toHaveBeenCalledWith(1, expected);
+ });
+
+ it("prefers a preferred matching fix and preserves empty ranges widened for display", async () => {
+ const problem = { ...upgrade, range: { start: { line: 0, col: 2 }, end: { line: 0, col: 2 } } };
+ const first = { ...update, diagnostics: [problem] };
+ const preferred = { ...first, title: "Preferred upgrade", isPreferred: true };
+ const view = new EditorView({
+ state: EditorState.create({
+ doc: " dependency",
+ selection: { anchor: 2 },
+ extensions: [lspDoc.of({ doc: 1, path: "/p/go.mod", language: "go", uiMode: null, readOnly: false })],
+ }),
+ });
+ views.push(view);
+ view.dispatch(setDiagnostics(view.state, toLintDiagnostics(view.state.doc, [problem])));
+ lspCodeActions.mockResolvedValue({ status: "ok", data: [remove, first, preferred] });
+ expect(await quickFixesAt(view, 2, 3, problem)).toEqual([preferred, first]);
+ await applyQuickFix(view);
+ expect(runInteractiveCodeAction).toHaveBeenCalledWith(1, preferred);
+ });
+});
diff --git a/src/editor/lsp/intentions.ts b/src/editor/lsp/intentions.ts
index dd953e1e3..6cdeebb65 100644
--- a/src/editor/lsp/intentions.ts
+++ b/src/editor/lsp/intentions.ts
@@ -8,7 +8,7 @@ import { EditorView, ViewPlugin, type ViewUpdate } from "@codemirror/view";
import { forEachDiagnostic } from "@codemirror/lint";
import { indentUnit } from "@codemirror/language";
import { diff } from "@codemirror/merge";
-import { commands, isCancelled, type CodeAction } from "@/platform/ipc";
+import { commands, isCancelled, type CodeAction, type Diagnostic } from "@/platform/ipc";
import {
contributedIntentions,
contributedQuickFixes,
@@ -28,7 +28,7 @@ import { featureBackoff } from "./availability";
import { iconNode } from "./iconMarkup";
import { editorPrefs } from "@/platform/editorSettings";
import { spellingIntentions } from "./spelling";
-import { inspectionsAt } from "./diagnostics";
+import { inspectionsAt, type EditorDiagnostic } from "./diagnostics";
import { SPELLING_INSPECTION } from "@/platform/inspections";
import { editInspectionSettings, intentionControls } from "@/platform/inspectionControls";
import { runInteractiveCodeAction } from "./interactiveCommand";
@@ -68,6 +68,23 @@ export function sortCodeActions(actions: readonly CodeAction[]): CodeAction[] {
.map((x) => x.a);
}
+/** Servers that omit diagnostic tags retain range-based actions. Tagged actions must match the problem. */
+export function actionsForDiagnostic(actions: readonly CodeAction[], problem: Diagnostic): CodeAction[] {
+ if (!actions.some((a) => a.diagnostics?.length)) return [...actions];
+ return actions.filter((a) =>
+ a.diagnostics?.some(
+ (d) =>
+ d.message === problem.message &&
+ d.range.start.line === problem.range.start.line &&
+ d.range.start.col === problem.range.start.col &&
+ d.range.end.line === problem.range.end.line &&
+ d.range.end.col === problem.range.end.col &&
+ (d.code == null || problem.code == null || d.code === problem.code) &&
+ (d.source == null || problem.source == null || d.source === problem.source),
+ ),
+ );
+}
+
async function fetchActions(view: EditorView, only: string[], whole = false): Promise<CodeAction[]> {
const doc = docOf(view);
if (!doc) return [];
@@ -134,7 +151,12 @@ async function fetchIntentions(view: EditorView): Promise<CodeAction[]> {
export type EditorQuickFix = CodeAction | { title: string; run: () => void | Promise<void> };
/** Enabled quick fixes of the problem at `from..to`, including local inspections. */
-export async function quickFixesAt(view: EditorView, from: number, to: number): Promise<EditorQuickFix[]> {
+export async function quickFixesAt(
+ view: EditorView,
+ from: number,
+ to: number,
+ problem?: Diagnostic,
+): Promise<EditorQuickFix[]> {
const local = contributedQuickFixes(view, from, to).map((fix) => ({ title: fix.label, run: fix.run }));
const doc = docOf(view);
if (!doc) return local;
@@ -143,7 +165,8 @@ export async function quickFixesAt(view: EditorView, from: number, to: number):
const actions = await lspRequest(() =>
commands.lspCodeActions(doc.doc, offsetsToRange(view.state.doc, from, to), ["quickfix"]),
);
- return [...local, ...sortCodeActions(actions.filter((a) => isQuickFix(a) && !a.disabledReason))];
+ const matching = problem ? actionsForDiagnostic(actions, problem) : actions;
+ return [...local, ...sortCodeActions(matching.filter((a) => isQuickFix(a) && !a.disabledReason))];
} catch (e) {
if (local.length) return local;
throw e;
@@ -158,17 +181,17 @@ export async function applyQuickFix(view: EditorView) {
const state = view.state;
const caret = state.selection.main.head;
const line = state.doc.lineAt(caret);
- const problems: Array<PlacedProblem & { rank: number }> = [];
+ const problems: Array<PlacedProblem & { rank: number; problem?: Diagnostic }> = [];
forEachDiagnostic(state, (d, from, to) => {
if (d.severity === "hint" || to < line.from || from > line.to) return;
const rank =
(d.severity === "error" ? 0 : d.severity === "warning" ? 1 : 2) + (from <= caret && caret <= to ? 0 : 3);
- problems.push({ from, to, severity: d.severity, rank });
+ problems.push({ from, to, severity: d.severity, rank, problem: (d as EditorDiagnostic).problem });
});
problems.sort((a, b) => a.rank - b.rank);
try {
for (const p of problems) {
- const fix = (await quickFixesAt(view, p.from, p.to))[0];
+ const fix = (await quickFixesAt(view, p.from, p.to, p.problem))[0];
if (view.state.doc !== state.doc) return;
if (fix) return applyCodeAction(view, fix);
}