【问题标题】:vscode API: get Position of last character of linevscode API:获取行的最后一个字符的位置
【发布时间】:2021-02-10 03:58:11
【问题描述】:

使用VS Code API 跟进this still unanswered question 关于VS 代码扩展。我没有回答它,因为它专门要求使用Position 对象的with 方法的解决方案。我无法完成这项工作,也无法遍历对象以获取最后一个字符。尝试使用vscode.commands.executeCommand 操作选择也不起作用,因为一旦执行开发主机开始运行,vscode.window.activeTextEditor 似乎就不会反映窗口中的实际选择。我能找到的唯一解决方案是下面的跳圈练习,它获取一行的第一个字符和下一行的第一个字符,设置一个范围,获取该范围的文本,然后减少该文本字符串的长度加 1 得到上一行的最后一个字符。

function getCursorPosition() {
  const position = editor.selection.active;
  curPos = selection.start;
  return curPos;
}
curPos = getCursorPosition();
var curLineStart =  new vscode.Position(curPos.line, 0);
var nextLineStart = new vscode.Position(curPos.line + 1, 0);
var rangeWithFirstCharOfNextLine = new vscode.Range( curLineStart, nextLineStart);
var contentWithFirstCharOfNextLine = editor.document.getText(rangeWithFirstCharOfNextLine);
var firstLineLength = contentWithFirstCharOfNextLine.length - 1;
var curLinePos = new vscode.Position(curPos.line, firstLineLength);
var curLineEndPos = curLinePos.character;
console.log('curLineEndPos :>> ' + curLineEndPos);

我显然遗漏了一些东西 - 使用 VSCode API 获取一行的最后一个字符是不可能的,而无需像这样使用米老鼠鼠标。所以问题很简单,正确的方法是什么?

【问题讨论】:

    标签: visual-studio-code vscode-extensions


    【解决方案1】:

    一旦有了光标PositionTextDocument.lineAt() 函数就会返回TextLine。您可以从中获取其range,而range.end.character 将为您提供最后一个字符的字符号。 - 不包括换行符,如果你想包括,请参阅TextLine.rangeIncludingLineBreak()

    const editor = vscode.window.activeTextEditor;
    const document = editor.document;          
    const cursorPos = editor.selection.active;
    
    document.lineAt(cursorPos).range.end.character;
    

    注意(来自[TextDocument.lineAt documentation][1] ):

    返回由位置表示的文本行。注意返回的 对象未生效,对文档的更改未反映。

    【讨论】:

    • 谢谢@Mark,那是我一直在寻找但不知道去哪里找的桥。
    • @VanAlbert 如果您认为这回答了您的问题,您应该将其标记为已接受。 :)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-02-07
    • 2015-03-24
    • 2016-03-18
    • 2013-02-15
    • 2011-08-22
    相关资源
    最近更新 更多