Порівняти коміти

..
Автор SHA1 Повідомлення Дата
l0ng-ai cd0ec7d107 fix(completion): leave items their server inserts to the server
kotlin-lsp completion items carry an empty text and a command
(jetbrains.kotlin.completion.apply) that inserts the item through a workspace
edit. We still added call parentheses for method items, so the server's text
went in before them (refreshName()(), an override's body followed by ()), and
the caret stayed in front of the inserted text. Items with an empty text get no
parentheses, and when the server's edit lands at the caret, the caret moves
past it.
2026-11-15 16:38:15 +08:00
15 змінених файлів з 90 додано та 82 видалено

No files matched your search

+28 -1
Переглянути файл
@@ -2,7 +2,7 @@ import { afterEach, describe, expect, it, vi } from "vitest";
import { EditorState, StateEffect, type Extension } from "@codemirror/state";
import { EditorView, runScopeHandlers } from "@codemirror/view";
import type { CompletionItem } from "@/bindings";
import type { EditorDocContext } from "@/editor/api";
import { remoteChange, type EditorDocContext } from "@/editor/api";
import { lspDoc } from "./lsp";
import { insertTab, tabOut, tabOutOfScope } from "@/editor/core/cm/smartKeys";
import {
@@ -294,6 +294,32 @@ describe("applying completions", () => {
await vi.waitFor(() => expect(view.state.selection.main.head).toBe(17));
});
it("leaves an item its server inserts to the server, and puts the caret after what it inserted", async () => {
const executed: string[] = [];
setInvokeRoute((cmd) => {
executed.push(cmd);
return Promise.resolve(null);
});
try {
const { view, req } = setup("p.ref|\n", "", [completionExtension()]);
view.dispatch({ effects: StateEffect.appendConfig.of(lspDoc.of({ doc: 1 } as EditorDocContext)) });
// kotlin-lsp: an empty text, inserted by `jetbrains.kotlin.completion.apply` as a workspace edit.
const command = { title: "Apply Completion", command: "jetbrains.kotlin.completion.apply", arguments: ["1"] };
const kotlin = item({ label: "refreshName", labelDetail: "()", insertText: "", command });
applyLspCompletion(view, makeCompletion(kotlin, req), 5, 5, "insert");
expect(view.state.doc.toString()).toBe("p.ref\n");
await vi.waitFor(() => expect(executed).toContain("lsp_execute_command"));
view.dispatch({ changes: { from: 5, insert: "reshName()" }, annotations: remoteChange.of(true) });
expect(view.state.doc.toString()).toBe("p.refreshName()\n");
expect(view.state.selection.main.head).toBe(15);
// Later edits from elsewhere leave the caret alone.
view.dispatch({ changes: { from: 15, insert: " " }, annotations: remoteChange.of(true) });
expect(view.state.selection.main.head).toBe(15);
} finally {
setInvokeRoute(null);
}
});
it("does not register a scope when jumping outside closing brackets is off", () => {
const { view, req } = setup("service.cr|");
applyLspCompletion(view, makeCompletion(item(), req), 8, 10, "insert");
@@ -532,6 +558,7 @@ describe("insert parentheses", () => {
expect(callParens(item({ kind: "field" }), line("a.cr"), 2, 4)).toBeNull();
expect(callParens(item({ isSnippet: true }), line("a.cr"), 2, 4)).toBeNull();
expect(callParens(item({ insertText: "create()" }), line("a.cr"), 2, 4)).toBeNull();
expect(callParens(item({ insertText: "" }), line("a.cr"), 4, 4)).toBeNull();
});
it("skips calls that already have parentheses and imports", () => {
+49 -5
Переглянути файл
@@ -24,7 +24,7 @@ import {
type CompletionResult,
type CompletionSource,
} from "@codemirror/autocomplete";
import { EditorSelection, Prec, type Text } from "@codemirror/state";
import { EditorSelection, EditorState, Prec, StateEffect, StateField, type Text } from "@codemirror/state";
import { EditorView, ViewPlugin, keymap, type ViewUpdate } from "@codemirror/view";
import {
call,
@@ -58,6 +58,7 @@ import { tx } from "@/platform/i18n";
import { showHint } from "./hint";
import { inplaceRenameActive } from "./inplaceRename";
import { languageSemantics } from "./semantic";
import { remoteChange } from "@/editor/api";
interface RequestContext {
doc: number;
@@ -297,7 +298,9 @@ export function callParens(
start: number,
end: number,
): "inside" | "after" | null {
if (item.isSnippet || !item.kind || !CALLABLE.has(item.kind) || /[(<[{]/.test(item.insertText)) return null;
// An empty text is inserted by the item's server command (kotlin-lsp), parentheses included.
if (item.isSnippet || !item.kind || !CALLABLE.has(item.kind) || !item.insertText || /[(<[{]/.test(item.insertText))
return null;
const next = line.text.charAt(end - line.from);
if (next && /[(\p{L}\p{N}_$'"`]/u.test(next)) return null;
if (IMPORT_LINE.test(line.text.slice(0, start - line.from))) return null;
@@ -322,6 +325,33 @@ async function applyLateEdits(view: EditorView, c: LspCompletion, insertedAt: nu
view.dispatch({ changes: edits, userEvent: "input.complete" });
}
/** Where the caret was when an item its server inserts was picked, until that edit lands (`null`: none). */
const awaitServerInsert = StateEffect.define<number | null>();
const serverInsertAt = StateField.define<number | null>({
create: () => null,
update(at, tr) {
for (const e of tr.effects) if (e.is(awaitServerInsert)) return e.value;
// The edit landed, or the caret moved on before it did.
if (at === null || tr.annotation(remoteChange) || tr.selection) return null;
return tr.changes.mapPos(at, -1);
},
});
/**
* The server's edit inserts the item at the caret: the caret goes after it, as after any other
* completion (a remote insertion at the caret would otherwise leave it in front).
*/
const caretAfterServerInsert = EditorState.transactionFilter.of((tr) => {
const at = tr.startState.field(serverInsertAt, false);
const caret = tr.startState.selection.main;
if (at == null || !tr.docChanged || !tr.annotation(remoteChange) || !caret.empty || caret.head !== at) return tr;
let inserted = false;
tr.changes.iterChangedRanges((fromA, toA) => {
if (fromA <= at && toA >= at) inserted = true;
});
return inserted ? [tr, { selection: EditorSelection.cursor(tr.changes.mapPos(at, 1)), sequential: true }] : tr;
});
/** Client-side commands handled by the editor itself (VS Code ids servers commonly send). */
const CLIENT_COMMANDS = new Set(["editor.action.triggerParameterHints", "editor.action.triggerSuggest"]);
@@ -329,18 +359,30 @@ function runCommand(view: EditorView, item: CompletionItem) {
const command = item.command;
if (!command?.command) return;
const cmd = command.command;
// kotlin-lsp inserts the item itself (`jetbrains.kotlin.completion.apply`): nothing went in here.
const serverInserted = !item.insertText && !CLIENT_COMMANDS.has(cmd) && !cmd.startsWith("editor.");
if (serverInserted) view.dispatch({ effects: awaitServerInsert.of(view.state.selection.main.head) });
if (cmd === "editor.action.triggerParameterHints") setTimeout(() => triggerSignatureHelp(view), 0);
else if (cmd === "editor.action.triggerSuggest") setTimeout(() => startCompletion(view), 0);
else if (!CLIENT_COMMANDS.has(cmd) && !cmd.startsWith("editor.")) {
const doc = docOf(view);
// Server commands (auto-import, postfix…); resulting edits come back as workspace/applyEdit.
if (doc)
void lspRequest(() => commands.lspExecuteCommand(doc.doc, command)).catch((e: unknown) =>
reportLspError(view, e, false),
);
void lspRequest(() => commands.lspExecuteCommand(doc.doc, command))
.catch((e: unknown) => reportLspError(view, e, false))
.finally(() => {
// The edit arrives before the command's answer; allow for the document update.
if (serverInserted)
setTimeout(() => {
if (view.dom.isConnected && view.state.field(serverInsertAt, false) != null)
view.dispatch({ effects: awaitServerInsert.of(null) });
}, SERVER_INSERT_WAIT_MS);
});
}
}
const SERVER_INSERT_WAIT_MS = 1000;
// ---------------------------------------------------------------------------
// Source
@@ -828,6 +870,8 @@ export function completionExtension() {
}),
completionFooter,
lookupTracker,
serverInsertAt,
caretAfterServerInsert,
Prec.highest(
keymap.of([
// macOS: ⌃N / ⌃P are line down / up in text, so they move through the lookup as ↓ / ↑ do.
+1 -1
Переглянути файл
@@ -303,6 +303,6 @@ describe("closing the hierarchy tab", () => {
useHierarchy.setState({ root: { name: "Number", path: "/p/Number.java", line: 0, col: 0 } as never });
closeHierarchy();
expect(useHierarchy.getState().root).toBeNull();
expect(hide).toHaveBeenCalledWith("hierarchy", { removeFromStripe: true });
expect(hide).toHaveBeenCalledWith("hierarchy");
});
});
+2 -2
Переглянути файл
@@ -92,10 +92,10 @@ export function resetHierarchy() {
}));
}
/** Closes the hierarchy's content tab; with no content left the tool window and its stripe button go. */
/** Closes the hierarchy's content tab; with no content left the tool window hides. */
export function closeHierarchy() {
resetHierarchy();
toolWindowService().hide("hierarchy", { removeFromStripe: true });
toolWindowService().hide("hierarchy");
}
/** The empty-result line of the hierarchy tree. */
+3 -24
Переглянути файл
@@ -1,10 +1,9 @@
import { describe, expect, it, vi } from "vitest";
const show = vi.fn();
const hide = vi.fn();
vi.mock("@/workbench/contributions", async (orig) => ({
...(await orig<typeof import("@/workbench/contributions")>()),
toolWindowService: () => ({ show, hide }),
toolWindowService: () => ({ show }),
}));
/** The editor at the caret (`null`: a search from outside an editor). */
let caretView: import("@codemirror/view").EditorView | null = null;
@@ -36,16 +35,8 @@ vi.mock("@tauri-apps/api/core", async (orig) => ({
const { registerDocumentIndexSync } = await import("@/workbench/contributions");
const {
activeUsageSearch,
closeUsageTab,
findUsages,
openUsageTab,
pinUsageTab,
resetUsages,
showUsageResults,
useUsages,
} = await import("./usages");
const { activeUsageSearch, findUsages, openUsageTab, pinUsageTab, resetUsages, showUsageResults, useUsages } =
await import("./usages");
describe("showUsageResults", () => {
it("shows given usages in the Find Usages tool window", async () => {
@@ -230,16 +221,4 @@ describe("usage tabs", () => {
openUsageTab(search(104));
expect(useUsages.getState().tabs.map((t) => t.id)).toEqual([102, 104]);
});
it("take the tool window and its stripe button away with the last one", () => {
resetUsages();
hide.mockClear();
openUsageTab(search(201));
pinUsageTab(201, true);
openUsageTab(search(202));
closeUsageTab(201);
expect(hide).not.toHaveBeenCalled();
closeUsageTab(202);
expect(hide).toHaveBeenCalledWith("usages", { removeFromStripe: true });
});
});
-8
Переглянути файл
@@ -168,14 +168,6 @@ export function closeUsageTab(id: number) {
const active = s.active === id ? (tabs[Math.min(i, tabs.length - 1)]?.id ?? null) : s.active;
return { tabs, active };
});
// As in IDEA, the tool window and its stripe button go away with its last tab.
if (!useUsages.getState().tabs.length) {
try {
toolWindowService().hide("usages", { removeFromStripe: true });
} catch {
// Workbench not ready (tests).
}
}
}
/** Rerun of the selected tab (⌘R in the Find Usages tool window). */
+1 -1
Переглянути файл
@@ -15,5 +15,5 @@ it("hides the Debug tool window once its last session tab is closed", async () =
expect(await closeSessionTab(1)).toBe(true);
expect(hide).not.toHaveBeenCalled();
expect(await closeSessionTab(2)).toBe(true);
expect(hide).toHaveBeenCalledWith("debug", { removeFromStripe: true });
expect(hide).toHaveBeenCalledWith("debug");
});
+2 -2
Переглянути файл
@@ -880,10 +880,10 @@ export async function closeSessionTab(id: DebugSessionId): Promise<boolean> {
await stopSession(s.id);
}
removeSession(s.id);
// As in IDEA, the tool window and its stripe button go away with its last tab.
// As in IDEA, the tool window goes away with its last tab.
if (!Object.keys(useDebug.getState().sessions).length) {
try {
toolWindowService().hide("debug", { removeFromStripe: true });
toolWindowService().hide("debug");
} catch {
// Workbench not ready (tests).
}
+1 -2
Переглянути файл
@@ -303,8 +303,7 @@ function currentTab(
export async function closeRunTab(id: string, traces: readonly StackTraceTab[]) {
if (traces.some((t) => t.id === id)) closeStackTrace(id);
else if (!(await closeSessionTab(id))) return;
if (!useRun.getState().sessions.length && !useStackTraces.getState().tabs.length)
toolWindowService().hide("run", { removeFromStripe: true });
if (!useRun.getState().sessions.length && !useStackTraces.getState().tabs.length) toolWindowService().hide("run");
}
/** Session (and stack trace) tabs in the tool window header. */
+1 -1
Переглянути файл
@@ -24,5 +24,5 @@ it("hides the Run tool window once its last tab is closed", async () => {
await closeRunTab("t", useStackTraces.getState().tabs);
expect(hide).not.toHaveBeenCalled();
await closeRunTab("b", useStackTraces.getState().tabs);
expect(hide).toHaveBeenCalledWith("run", { removeFromStripe: true });
expect(hide).toHaveBeenCalledWith("run");
});
-14
Переглянути файл
@@ -1,10 +1,8 @@
import { afterEach, describe, expect, it, vi } from "vitest";
import { provideToolWindowService, type ToolWindowService } from "@/workbench/contributions";
import type { FileMatches, SearchQuery } from "@/platform/ipc";
import { buildFindTree } from "../find/FindToolWindow";
import type { FindDeps } from "../find/session";
import {
closeFindTab,
disposeFindWindow,
openEditorResults,
openInFindWindow,
@@ -40,18 +38,6 @@ const file = (rel: string): FileMatches => ({
afterEach(disposeFindWindow);
describe("Find tool window tabs", () => {
it("take the tool window and its stripe button away with the last one", () => {
const hide = vi.fn();
provideToolWindowService({ show: vi.fn(), hide } as unknown as ToolWindowService);
const a = openInFindWindow(q("a"), "a", { deps });
pinFindTab(a, true);
const b = openInFindWindow(q("b"), "b", { deps });
closeFindTab(a);
expect(hide).not.toHaveBeenCalled();
closeFindTab(b);
expect(hide).toHaveBeenCalledWith("find", { removeFromStripe: true });
});
it("reuses the selected tab unless it is pinned", () => {
const a = openInFindWindow(q("a"), "a", { deps });
const b = openInFindWindow(q("b"), "b", { deps });
-2
Переглянути файл
@@ -134,8 +134,6 @@ export function closeFindTab(id: number) {
const active = s.active === id ? (tabs[Math.min(i, tabs.length - 1)]?.id ?? null) : s.active;
return { tabs, active };
});
// As in IDEA, the tool window and its stripe button go away with its last tab.
if (!useFindWindow.getState().tabs.length) maybeToolWindowService()?.hide("find", { removeFromStripe: true });
}
export function disposeFindWindow() {
+1 -5
Переглянути файл
@@ -709,11 +709,7 @@ export interface EditorCloseSession {
export interface ToolWindowService {
show(id: string, focus?: boolean): void;
/**
* `removeFromStripe`: a window whose content is its tabs (Find, Run, Hierarchy…) lost its last
* one: its stripe button goes too, until new content opens it again (IDEA).
*/
hide(id: string, options?: { removeFromStripe?: boolean }): void;
hide(id: string): void;
toggle(id: string): void;
isVisible(id: string): boolean;
}
-13
Переглянути файл
@@ -476,19 +476,6 @@ describe("stripe buttons", () => {
resetToolWindowPlacements();
expect(buttons()).toEqual({});
});
it("drops the button of a window that lost its last tab until new content opens it", () => {
disposers.push(registerToolWindow(find));
showToolWindow("find");
toolWindowServiceImpl.hide("find");
expect(hasStripeButton(find, buttons())).toBe(true);
showToolWindow("find");
toolWindowServiceImpl.hide("find", { removeFromStripe: true });
expect(isToolWindowVisible("find")).toBe(false);
expect(hasStripeButton(find, buttons())).toBe(false);
showToolWindow("find");
expect(hasStripeButton(find, buttons())).toBe(true);
});
});
describe("view modes", () => {
+1 -1
Переглянути файл
@@ -742,7 +742,7 @@ function isFocusWithinToolWindow(id: string): boolean {
export const toolWindowServiceImpl: ToolWindowService = {
show: (id, focus) => showToolWindow(id, focus),
hide: (id, options) => (options?.removeFromStripe ? removeFromStripe(id) : hideToolWindow(id)),
hide: hideToolWindow,
toggle: toggleToolWindow,
isVisible: isToolWindowVisible,
};