vscode:如何获取光标在文档中的偏移量?

Aym*_*rig 5 html javascript visual-studio-code

我正在开发 vscode 扩展..我想获取对整个文档的光标位置引用,例如,如果我有以下 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>
Run Code Online (Sandbox Code Playgroud)

并且cursur位于body标签内(上面代码中符号的位置|),我想要的结果是178,如果你从头开始计算文档中的所有字符(包括空格),它就是字符的索引。

我试过这段代码

    const position = editor.selection.active;
    console.log(position);
Run Code Online (Sandbox Code Playgroud)

但它给出了该行以及该行中角色的位置,这不是我需要的。

有什么办法可以得到想要的输出吗?

rio*_*oV8 6

使用以下调用

editor.document.offsetAt(editor.selection.active)
Run Code Online (Sandbox Code Playgroud)

ASelection有 4 个Position属性:

  • start, end: 相对于文件开头的位置
  • anchor, active: 光标进行选择的开始和停止位置