diff --git a/src/contributes/commands.ts b/src/contributes/commands.ts index c98e9a2e..f6d45842 100644 --- a/src/contributes/commands.ts +++ b/src/contributes/commands.ts @@ -49,6 +49,48 @@ function registerAskForCodeCommand(context: vscode.ExtensionContext) { context.subscriptions.push(vscode.commands.registerCommand('devchat.askForCode_chinese', callback)); } +export function registerCodeLenses(context: vscode.ExtensionContext) { + // This is the list of commands that will be shown as code lenses + // whenever selection is non empty. + // TODO: Add more commands + const lensCommands = [ + { + title: '', + tooltip: 'Ask code', + command: 'devchat.askForCode', + }, + ]; + + const codeLensProvider = new class implements vscode.CodeLensProvider { + private _onDidChangeCodeLenses: vscode.EventEmitter = new vscode.EventEmitter(); + public readonly onDidChangeCodeLenses: vscode.Event = this._onDidChangeCodeLenses.event; + + constructor() { + // Update code lenses each time selection changes + vscode.window.onDidChangeTextEditorSelection((_) => { + this._onDidChangeCodeLenses.fire(); + }); + } + + async provideCodeLenses(_: vscode.TextDocument): Promise { + const editor = vscode.window.activeTextEditor; + if (!editor) { + return []; + } + + const selection = editor.selection; + if (selection.isEmpty) { + return []; + } + + return lensCommands.map(command => new vscode.CodeLens(selection, command)); + } + }; + + vscode.languages.registerCodeLensProvider("*", codeLensProvider); +} + + function registerAskForFileCommand(context: vscode.ExtensionContext) { const callback = async () => { const editor = vscode.window.activeTextEditor; diff --git a/src/extension.ts b/src/extension.ts index b1a4eb6d..77a34f6e 100644 --- a/src/extension.ts +++ b/src/extension.ts @@ -5,6 +5,7 @@ import { registerAddContextCommand, registerAskForCodeCommand, registerAskForFileCommand, + registerCodeLenses, registerOpenAiApiKeySettingCommand, registerDevChatApiKeySettingCommand, regTopicDeleteCommand, @@ -46,6 +47,8 @@ function activate(context: vscode.ExtensionContext) { registerAskForFileCommand(context); registerStatusBarItemClickCommand(context); + registerCodeLenses(context); + createStatusBarItem(context); regTopicDeleteCommand(context);