我正在尝试编写一个扩展名,该扩展名将自动选择光标下的单词,打开“在文件中查找”对话框,并使用该选择启动搜索。到目前为止,除了实际启动搜索之外,我已经能够获得扩展功能以执行所有操作。我仍然必须在“在文件中查找”对话框中按Enter才能真正执行搜索。这是到目前为止我拥有的扩展代码:
import * as vscode from 'vscode';
export function activate(context: vscode.ExtensionContext) {
let disposable = vscode.commands.registerCommand('extension.searchUnderCursor', () => {
// Get the current editor
let editor = vscode.window.activeTextEditor;
if (!editor) {
console.log('No active editor!');
return;
}
// Get word under cursor position
let wordRange = editor.document.getWordRangeAtPosition(editor.selection.start);
if (!wordRange) {
console.log('No word under the cursor!');
return;
}
// Select the word
editor.selection = new vscode.Selection(wordRange.start, wordRange.end);
// Initiate search
vscode.commands.executeCommand('workbench.action.findInFiles').then(() => {
vscode.commands.executeCommand('default:type', {text: '\n'});
});
});
context.subscriptions.push(disposable);
}
export function deactivate() {}
您可以看到我正在尝试找到一种在文件查找对话框中按Enter的方法来开始搜索。当然,那是行不通的。如何获得要在这里使用的功能?
答案 0 :(得分:1)
实际上,我知道了。这是我的解决方案:
import * as vscode from 'vscode';
export function activate(context: vscode.ExtensionContext) {
let disposable = vscode.commands.registerCommand('extension.searchUnderCursor', () => {
// Get the current editor
let editor = vscode.window.activeTextEditor;
if (!editor) {
console.log('No active editor!');
return;
}
// Get word under cursor position
let wordRange = editor.document.getWordRangeAtPosition(editor.selection.start);
if (!wordRange) {
console.log('No word under the cursor!');
return;
}
// Get word text
let wordText = editor.document.getText(wordRange);
// Initiate search
vscode.commands.executeCommand('workbench.action.findInFiles', {
query: wordText,
triggerSearch: true,
matchWholeWord: true,
isCaseSensitive: true,
});
});
context.subscriptions.push(disposable);
}
export function deactivate() {}
事实证明,findInFiles
操作具有许多可以接受的有用参数:https://github.com/microsoft/vscode/blob/9a987a1cd0d3413ffda4ed41268d9f9ee8b7565f/src/vs/workbench/contrib/search/browser/searchActions.ts#L163-L172