Skip to content

Commit 37a9b9a

Browse files
robstrykerclaude
andcommitted
Reveal the edited file after applying a code action
When a quick fix edits a document other than the active one (e.g. "Create method 'call()' in type 'Foo'"), VS Code applies the edit but leaves the active editor alone. Attach a java.reveal.edit command to code actions that carry an edit so the changed file is shown and the first change is revealed. The target is taken from the raw LSP edit since WorkspaceEdit.entries() does not include snippet edits, and any command the action already has is run first. Also move revealWorkspaceEdit next to applyWorkspaceEdit, make it open the document with showTextDocument instead of revealing in whichever editor is active, and use it for java.apply.workspaceEdit. Fixes #765 Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com> Signed-off-by: Rob Stryker <rob@oxbeef.net>
1 parent 68044a5 commit 37a9b9a

4 files changed

Lines changed: 93 additions & 25 deletions

File tree

‎src/commands.ts‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -74,6 +74,11 @@ export namespace Commands {
7474
*/
7575
export const APPLY_WORKSPACE_EDIT = 'java.apply.workspaceEdit';
7676

77+
/**
78+
* Reveal the change made by a code action if it is in a document other than the active one
79+
*/
80+
export const REVEAL_EDIT = 'java.reveal.edit';
81+
7782
/**
7883
* Execute Workspace Command
7984
*/

‎src/extension.ts‎

Lines changed: 39 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@ import * as os from 'os';
88
import * as path from 'path';
99
import * as semver from 'semver';
1010
import {
11-
CodeActionContext, commands, CompletionItem, ConfigurationTarget, Diagnostic, env, EventEmitter, ExtensionContext, extensions,
11+
CodeAction, CodeActionContext, commands, CompletionItem, ConfigurationTarget, Diagnostic, env, EventEmitter, ExtensionContext, extensions,
1212
InputBoxOptions, Location, MarkdownString, RelativePattern,
1313
SnippetString, SnippetTextEdit, TextDocument, TextEditorRevealType, UIKind, Uri, version, ViewColumn, window, workspace, WorkspaceConfiguration
1414
} from 'vscode';
@@ -326,7 +326,7 @@ export async function activate(context: ExtensionContext): Promise<ExtensionAPI>
326326
result.push(client.protocol2CodeConverter.asCommand(item));
327327
}
328328
else {
329-
result.push(await client.protocol2CodeConverter.asCodeAction(item));
329+
result.push(addRevealCommand(client, await client.protocol2CodeConverter.asCodeAction(item), item.edit));
330330
}
331331
}
332332
return result;
@@ -385,9 +385,9 @@ export async function activate(context: ExtensionContext): Promise<ExtensionAPI>
385385
codeAction.edit.set(uri, editList);
386386
}
387387
}
388-
return codeAction;
388+
return addRevealCommand(client, codeAction, result.edit);
389389
}
390-
return await client.protocol2CodeConverter.asCodeAction(result, token);
390+
return addRevealCommand(client, await client.protocol2CodeConverter.asCodeAction(result, token), result.edit);
391391
}, (error) => {
392392
return client.handleFailedRequest(CodeActionResolveRequest.type, token, error, item);
393393
});
@@ -1377,3 +1377,38 @@ export function escapeSnippetLiterals(value: string): string {
13771377
.replace(/\\(?!,)/g, '\\\\') // Escape backslashes, but preserve escaped commas
13781378
.replace(/\$(?!\{)/g, '\\$'); // Escape $ only if NOT followed by {
13791379
}
1380+
1381+
/**
1382+
* VS Code applies the edit of a code action itself and doesn't show the edited file.
1383+
* Attach a command, which VS Code runs after applying the edit, to reveal the change
1384+
* when it is made in a document other than the active one.
1385+
* Any command the action already has is passed along and run first.
1386+
*/
1387+
function addRevealCommand(client: LanguageClient, codeAction: CodeAction, lspEdit: { documentChanges?: any[], changes?: { [uri: string]: any[] } } | undefined): CodeAction {
1388+
if (lspEdit && codeAction.command?.command !== Commands.REVEAL_EDIT) {
1389+
// Taken from the raw edit because WorkspaceEdit.entries() doesn't include snippet edits
1390+
let target: { uri: string, range: any } | undefined;
1391+
for (const docChange of lspEdit.documentChanges ?? []) {
1392+
if ("textDocument" in docChange && docChange.edits.length > 0) {
1393+
target = { uri: docChange.textDocument.uri, range: docChange.edits[0].range };
1394+
break;
1395+
}
1396+
}
1397+
if (!target) {
1398+
for (const [uri, edits] of Object.entries(lspEdit.changes ?? {})) {
1399+
if (edits.length > 0) {
1400+
target = { uri, range: edits[0].range };
1401+
break;
1402+
}
1403+
}
1404+
}
1405+
if (target) {
1406+
codeAction.command = {
1407+
title: 'Reveal edit',
1408+
command: Commands.REVEAL_EDIT,
1409+
arguments: [Uri.parse(target.uri), client.protocol2CodeConverter.asRange(target.range), codeAction.command],
1410+
};
1411+
}
1412+
}
1413+
return codeAction;
1414+
}

‎src/sourceAction.ts‎

Lines changed: 3 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
'use strict';
22

3-
import { Disposable, ExtensionContext, TextEditorRevealType, Uri, ViewColumn, commands, window, workspace } from 'vscode';
4-
import { CodeActionParams, WorkspaceEdit } from 'vscode-languageclient';
3+
import { Disposable, ExtensionContext, Uri, ViewColumn, commands, window } from 'vscode';
4+
import { CodeActionParams } from 'vscode-languageclient';
55
import { LanguageClient } from 'vscode-languageclient/node';
66
import { Commands } from './commands';
77
import { getActiveLanguageClient } from './extension';
@@ -25,7 +25,7 @@ import {
2525
OrganizeImportsRequest,
2626
VariableBinding
2727
} from './protocol';
28-
import { applyWorkspaceEdit } from './standardLanguageClient';
28+
import { applyWorkspaceEdit, revealWorkspaceEdit } from './standardLanguageClient';
2929

3030
export function registerCommands(languageClient: LanguageClient, context: ExtensionContext) {
3131
registerOverrideMethodsCommand(languageClient, context);
@@ -412,18 +412,3 @@ function registerGenerateDelegateMethodsCommand(languageClient: LanguageClient,
412412
await revealWorkspaceEdit(workspaceEdit, languageClient);
413413
}));
414414
}
415-
416-
async function revealWorkspaceEdit(workspaceEdit: WorkspaceEdit, languageClient: LanguageClient): Promise<void> {
417-
const codeWorkspaceEdit = await languageClient.protocol2CodeConverter.asWorkspaceEdit(workspaceEdit);
418-
if (!codeWorkspaceEdit) {
419-
return;
420-
}
421-
for (const entry of codeWorkspaceEdit.entries()) {
422-
await workspace.openTextDocument(entry[0]);
423-
if (entry[1].length > 0) {
424-
// reveal first available change of the workspace edit
425-
window.activeTextEditor.revealRange(entry[1][0].range, TextEditorRevealType.InCenter);
426-
break;
427-
}
428-
}
429-
}

‎src/standardLanguageClient.ts‎

Lines changed: 46 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@
22

33
import * as net from 'net';
44
import * as path from 'path';
5-
import { CancellationToken, CodeActionKind, commands, ConfigurationTarget, DocumentSelector, EventEmitter, ExtensionContext, extensions, languages, Location, ProgressLocation, TextEditor, Uri, ViewColumn, window, workspace, WorkspaceConfiguration } from "vscode";
5+
import { CancellationToken, CodeActionKind, Command, commands, ConfigurationTarget, DocumentSelector, EventEmitter, ExtensionContext, extensions, languages, Location, ProgressLocation, Range, TextEditor, TextEditorRevealType, Uri, ViewColumn, window, workspace, WorkspaceConfiguration } from "vscode";
66
import { ConfigurationParams, ConfigurationRequest, LanguageClientOptions, Location as LSLocation, MessageType, Position as LSPosition, TextDocumentPositionParams, WorkspaceEdit, StaticFeature, ClientCapabilities, FeatureState, TelemetryEventNotification } from "vscode-languageclient";
77
import { LanguageClient, StreamInfo } from "vscode-languageclient/node";
88
import { apiManager } from "./apiManager";
@@ -438,8 +438,30 @@ export class StandardLanguageClient {
438438

439439
context.subscriptions.push(commands.registerCommand(Commands.NULL_ANALYSIS_SET_MODE, (status) => setNullAnalysisStatus(status)));
440440

441-
context.subscriptions.push(commands.registerCommand(Commands.APPLY_WORKSPACE_EDIT, (obj) => {
442-
applyWorkspaceEdit(obj, this.languageClient);
441+
context.subscriptions.push(commands.registerCommand(Commands.APPLY_WORKSPACE_EDIT, async (obj) => {
442+
const activeUri = window.activeTextEditor?.document.uri.toString();
443+
await applyWorkspaceEdit(obj, this.languageClient);
444+
await revealWorkspaceEdit(obj, this.languageClient, activeUri);
445+
}));
446+
447+
context.subscriptions.push(commands.registerCommand(Commands.REVEAL_EDIT, async (uri: Uri, range: Range, originalCommand?: Command) => {
448+
if (originalCommand) {
449+
await commands.executeCommand(originalCommand.command, ...(originalCommand.arguments ?? []));
450+
}
451+
if (window.activeTextEditor?.document.uri.toString() === uri.toString()) {
452+
return;
453+
}
454+
// The edit may still be being applied (e.g. a snippet edit opens the file in the background),
455+
// so open the document and retry until its editor is the active one.
456+
const document = await workspace.openTextDocument(uri);
457+
for (let i = 0; i < 10; i++) {
458+
const editor = await window.showTextDocument(document, { preview: false });
459+
if (window.activeTextEditor?.document.uri.toString() === uri.toString()) {
460+
editor.revealRange(range, TextEditorRevealType.InCenter);
461+
return;
462+
}
463+
await new Promise(resolve => setTimeout(resolve, 100));
464+
}
443465
}));
444466

445467
context.subscriptions.push(commands.registerCommand(Commands.NAVIGATE_TO_SUPER_IMPLEMENTATION_COMMAND, async (location: LinkLocation | Uri) => {
@@ -927,6 +949,27 @@ export async function applyWorkspaceEdit(workspaceEdit: WorkspaceEdit, languageC
927949
}
928950
}
929951

952+
/**
953+
* Reveals the first change of the workspace edit in an editor.
954+
* If `onlyIfNotUri` is given, nothing happens when the change is in that document.
955+
*/
956+
export async function revealWorkspaceEdit(workspaceEdit: WorkspaceEdit, languageClient: LanguageClient, onlyIfNotUri?: string): Promise<void> {
957+
const codeWorkspaceEdit = await languageClient.protocol2CodeConverter.asWorkspaceEdit(workspaceEdit);
958+
if (!codeWorkspaceEdit) {
959+
return;
960+
}
961+
for (const [uri, edits] of codeWorkspaceEdit.entries()) {
962+
if (edits.length > 0) {
963+
if (uri.toString() !== onlyIfNotUri) {
964+
// reveal first available change of the workspace edit
965+
const editor = await window.showTextDocument(uri);
966+
editor.revealRange(edits[0].range, TextEditorRevealType.InCenter);
967+
}
968+
break;
969+
}
970+
}
971+
}
972+
930973
/**
931974
* 'workspace/willRenameFiles' already handled so we need to disable it.
932975
* @see fileEventHandler.registerFileEventHandlers

0 commit comments

Comments
 (0)