diff --git a/src/features/templates/__tests__/editor.test.ts b/src/features/templates/__tests__/editor.test.ts index fb22e6603..a2fe4dc24 100644 --- a/src/features/templates/__tests__/editor.test.ts +++ b/src/features/templates/__tests__/editor.test.ts @@ -1,4 +1,5 @@ -import { afterEach, describe, expect, it } from "vitest"; +import { afterEach, describe, expect, it, vi } from "vitest"; +import { registerAction } from "@/platform/actions"; import { EditorSelection, EditorState, type Extension } from "@codemirror/state"; import { EditorView, runScopeHandlers } from "@codemirror/view"; import { completedSyntaxState } from "@/test/syntax"; @@ -94,6 +95,55 @@ describe("Tab expansion", () => { }); }); +describe("Java .var", () => { + it("runs Introduce Variable on the expression, ended as a statement", async () => { + let seen: { doc: string; selected: string } | null = null; + const dispose = registerAction({ + id: "refactor.extractVariable", + title: "Introduce Variable…", + run: () => { + const sel = view!.state.selection.main; + seen = { doc: view!.state.doc.toString(), selected: view!.state.sliceDoc(sel.from, sel.to) }; + }, + }); + try { + const v = await editor( + "java", + "class A { void f() {\n list.get(0).var\n} }", + "class A { void f() {\n list.get(0).var".length, + ); + expect(expandPostfixAtCaret(v)).toBe(true); + const req = useChooser.getState().request; + if (req) + req.onPick( + req.items.find((i) => i.label === "list.get(0)")!, + "", + ); + await vi.waitFor(() => expect(seen).not.toBeNull()); + expect(seen).toEqual({ doc: "class A { void f() {\n list.get(0);\n} }", selected: "list.get(0)" }); + } finally { + dispose(); + } + }); + + it("falls back to the var template without Introduce Variable", async () => { + const v = await editor( + "java", + "class A { void f() {\n name().var\n} }", + "class A { void f() {\n name().var".length, + ); + expect(expandPostfixAtCaret(v)).toBe(true); + const req = useChooser.getState().request; + if (req) + req.onPick( + req.items.find((i) => i.label === "name()")!, + "", + ); + await vi.waitFor(() => expect(v.state.doc.toString()).toContain("var name = name();")); + expect(v.state.doc.toString()).toBe("class A { void f() {\n var name = name();\n} }"); + }); +}); + describe("surround with", () => { it("wraps the selected lines", async () => { const doc = "def f():\n a()\n b()\n"; diff --git a/src/features/templates/editor.ts b/src/features/templates/editor.ts index 1e2d27026..acd3e712e 100644 --- a/src/features/templates/editor.ts +++ b/src/features/templates/editor.ts @@ -28,7 +28,7 @@ import { type Transaction, } from "@codemirror/state"; import { EditorView, keymap, type Command } from "@codemirror/view"; -import { executeAction } from "@/platform/actions"; +import { executeAction, getAction } from "@/platform/actions"; import { useProject } from "@/platform/project"; import { whenSynced, type EditorDocContext } from "@/editor/api"; import { structure, type StructuralRanges } from "@/editor/structure"; @@ -480,6 +480,12 @@ export function applyPostfix(view: EditorView, t: PostfixTemplate, target: Postf const expr = t.wrapCompound && isCompound(c.text) ? `(${c.text})` : c.text; // The key may have grown since the target was computed (completion). const end = Math.max(target.end, view.state.selection.main.head); + if (t.action && getAction(t.action)) { + void runPostfixAction(view, t.action, c.from, target.dot, end, !!t.statement).then(async (ran) => { + if (!ran) await expandInto(view, t, c.from, target.dot, { predefined: { EXPR: expr }, expression: c.text }); + }); + return; + } void expandInto(view, t, c.from, end, { predefined: { EXPR: expr }, expression: c.text }); }; if (candidates.length <= 1) { @@ -498,6 +504,28 @@ export function applyPostfix(view: EditorView, t: PostfixTemplate, target: Postf }); } +/** + * Removes the `.key`, selects the expression and runs `action` on it. A statement is + * ended with `;` first, so the language server sees complete code. False when the + * action is unavailable here (the expression stays selected for the template). + */ +async function runPostfixAction( + view: EditorView, + action: string, + from: number, + dot: number, + end: number, + statement: boolean, +): Promise { + const after = view.state.doc.sliceString(end, Math.min(view.state.doc.length, end + 80)); + const insert = statement && !/^[ \t]*;/.test(after) ? ";" : ""; + view.dispatch({ changes: { from: dot, to: end, insert }, selection: EditorSelection.range(from, dot) }); + if (await executeAction(action)) return true; + if (insert) + view.dispatch({ changes: { from: dot, to: dot + insert.length }, selection: EditorSelection.range(from, dot) }); + return false; +} + function postfixAt(state: EditorState, pos: number): { target: PostfixTarget; templates: PostfixTemplate[] } | null { const settings = usePostfixSettings.getState(); if (!settings.enabled) return null; diff --git a/src/features/templates/postfix/model.ts b/src/features/templates/postfix/model.ts index b7889d7cb..ebec23096 100644 --- a/src/features/templates/postfix/model.ts +++ b/src/features/templates/postfix/model.ts @@ -20,6 +20,11 @@ export interface PostfixTemplate { statement?: boolean; /** Wrap compound expressions (`a + b`) in parentheses for `$EXPR$`. */ wrapCompound?: boolean; + /** + * An editor action run on the selected expression instead of inserting `body` + * (IDEA's `.var` is Introduce Variable); `body` remains for when it isn't available. + */ + action?: string; } const NAME: TemplateVariable = { name: "NAME", expression: "suggestVariableName()", defaultValue: '"value"' }; @@ -220,10 +225,12 @@ const java = set( { key: "not", description: "!expr", body: "!$EXPR$$END$", wrapCompound: true }, { key: "var", - description: "var name = expr;", + description: "T name = expr;", body: "var $NAME$ = $EXPR$;$END$", statement: true, variables: [NAME], + // The server declares the expression's type, as IDEA does by default. + action: "refactor.extractVariable", }, { key: "return", description: "return expr;", body: "return $EXPR$;$END$", statement: true }, { key: "sout", description: "System.out.println(expr)", body: "System.out.println($EXPR$);$END$", statement: true },