Skip to content

Commit

Permalink
Register command to show references (hashicorp#686)
Browse files Browse the repository at this point in the history
  • Loading branch information
radeksimko committed Jul 21, 2021
1 parent 8b38ec4 commit d8dca31
Show file tree
Hide file tree
Showing 2 changed files with 68 additions and 0 deletions.
3 changes: 3 additions & 0 deletions src/clientHandler.ts
Expand Up @@ -20,6 +20,7 @@ import {
sortedWorkspaceFolders
} from './vscodeUtils';
import TelemetryReporter from 'vscode-extension-telemetry';
import { ShowReferencesFeature } from './showReferences';
import { ServerPath, CUSTOM_BIN_PATH_OPTION_NAME } from './serverPath';

export interface TerraformLanguageClient {
Expand Down Expand Up @@ -177,6 +178,8 @@ export class ClientHandler {
clientOptions
);

client.registerFeature(new ShowReferencesFeature(client));

client.onDidChangeState((event) => {
if (event.newState === State.Stopped) {
clients.delete(location);
Expand Down
65 changes: 65 additions & 0 deletions src/showReferences.ts
@@ -0,0 +1,65 @@
import * as vscode from 'vscode';
import {
ClientCapabilities,
ServerCapabilities,
StaticFeature,
ReferencesRequest,
ReferenceContext,
BaseLanguageClient
} from 'vscode-languageclient';

type Position = {
line: number;
character: number;
}

type RefContext = {
includeDeclaration: boolean;
}

const CLIENT_CMD_ID = 'client.showReferences';
const VSCODE_SHOW_REFERENCES = 'editor.action.showReferences'

export class ShowReferencesFeature implements StaticFeature {
private registeredCommands: vscode.Disposable[] = [];

constructor(private _client: BaseLanguageClient) {
}

public fillClientCapabilities(capabilities: ClientCapabilities): void {
if (!capabilities['experimental']) {
capabilities['experimental'] = {};
}
capabilities['experimental']['showReferencesCommandId'] = CLIENT_CMD_ID;
}

public initialize(capabilities: ServerCapabilities): void {
if ( !capabilities.experimental?.referenceCountCodeLens ) {
return
}

const showRefs = vscode.commands.registerCommand(CLIENT_CMD_ID, async (pos: Position, refCtx: RefContext) => {
const client = this._client;

const doc = vscode.window.activeTextEditor.document;

const position = new vscode.Position(pos.line, pos.character);
const context: ReferenceContext = {includeDeclaration: refCtx.includeDeclaration}

const provider: vscode.ReferenceProvider = client.getFeature(ReferencesRequest.method).getProvider(doc);
const tokenSource: vscode.CancellationTokenSource = new vscode.CancellationTokenSource();

const locations = await provider.provideReferences(doc, position, context, tokenSource.token);

await vscode.commands.executeCommand(VSCODE_SHOW_REFERENCES, doc.uri, position, locations);
})
this.registeredCommands.push(showRefs);
}

public dispose(): void {
this.registeredCommands.forEach(function(cmd, index, commands) {
cmd.dispose();
commands.splice(index, 1);
})
}
}

0 comments on commit d8dca31

Please sign in to comment.