I know how to get the position of the cursor:
editor.selection.active
This will yield something like: { _character: 4, _line 1 }
Now, I'd like to match a character or word (in the active editor) and get it's line number and character position:
const editor = vscode.window.activeTextEditor
let text = editor.document.getText()
const match = text.match(/match/)
// What should I write here?
How to get the line number and character position of the match (or first match)?
I couldn't find anything on Google or VS Code API's documentation.
CodePudding user response:
Use the methods from TextDocument
positionAt(offset: number): Position
Converts a zero-based offset to a position.
The match
has an offset (start of match).
CodePudding user response:
Iterate over the lines of your document, and count the line number:
const editor = vscode.window.activeTextEditor;
let lines = editor.document.getText().split(“\n”);
for (let i=0;i<lines.length;i )
{
const match = lines[i].match(/match/);
if (match)
{
let char = match[1].index;
let lineNb = i;
break;
}
}