【问题标题】:vscode - Is there any api to get search results?vscode - 是否有任何 api 来获取搜索结果?
【发布时间】:2021-06-11 09:23:38
【问题描述】:
当我尝试在文件中搜索文本时,我想知道我是否可以得到vscode搜索的结果。有没有我可以使用的api?
我在vscode提出的api中找到了一些类似TextSearchProvider的功能,但是这个api用于在整个工作场所搜索文本。我只想在一个文件中搜索结果。
example picture
例如,当我尝试搜索 Selection 时,我想要此搜索的结果。
【问题讨论】:
标签:
visual-studio-code
vscode-extensions
【解决方案1】:
我的扩展程序Find and Transform中的一些代码:
function _findAndSelect(editor, findValue, restrictFind) {
let foundSelections = [];
// get all the matches in the document
let fullText = editor.document.getText();
let matches = [...fullText.matchAll(new RegExp(findValue, "gm"))];
matches.forEach((match, index) => {
let startPos = editor.document.positionAt(match.index);
let endPos = editor.document.positionAt(match.index + match[0].length);
foundSelections[index] = new vscode.Selection(startPos, endPos);
});
editor.selections = foundSelections; // this will remove all the original selections
}
只需获取当前文档的文本,使用您的搜索词进行一些字符串搜索,例如matchAll。在上面的代码中,我想选择文档中的所有匹配项——您可能对此感兴趣,也可能不感兴趣。
您似乎希望您的搜索词成为当前选择:
// editor is the vscode.window.activeTextEditor
let selection = editor.selection;
let selectedRange = new vscode.Range(selection.start, selection.end);
let selectedText = editor.document.getText(selectedRange);