Reputation: 35
When I try to search text in a file,I wonder if I could get the results searched by vscode.Is there some api that I can use?
I found some functions like TextSearchProvider in vscode proposed api,but this api is used to search text in whole workplace.I just want the result searched in one file.
For example,When I try to search Selection,I want the result of this search.
Upvotes: 1
Views: 1673
Reputation: 180675
Some code from my extension 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
}
Just get the text of the current document, do some string search like matchAll
using your search term. In the code above I wanted to select all those matches in the document - you may or may not be interested in that.
It looks like you want your search term to be the current selection:
// 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);
Upvotes: 2