Reputation: 221
I am working on a vscode extension .. I want to get the cursor position reference to the whole document, for example if I've the following html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<|body>
<div>
<p>Hello World</p>
</div>
</body>
</html>
and the cursur was inside the body tag (the place of the |
sign in the code above), the result I want is 178 which is the index of the character if you start counting all characters in the document (including white spaces) from the start.
I tried this code
const position = editor.selection.active;
console.log(position);
but it gives the line and the position of the character in that line, which is not what I need.
Is there any way to get the desired output ?
Upvotes: 5
Views: 5790
Reputation: 28673
Use the following call
editor.document.offsetAt(editor.selection.active)
A Selection
has 4 Position
properties:
start
, end
: position relative to begin of fileanchor
, active
: position of begin and stop of cursor making the selectionUpvotes: 6
Reputation: 181248
let activeEditor = vscode.window.activeTextEditor;
let document = activeEditor.document;
let curPos = activeEditor.selection.active;
let offset = document.offsetAt(curPos);
Upvotes: 3