VSCode Extenstion how to get Position of last character of line

删除回忆录丶 提交于 2021-01-28 02:19:22

问题


I am developing a VSCode plugin, and now want to get the position of the last character of a line. Now I want to get it through a known Position object, using "with" method.

The official reference is here: https://code.visualstudio.com/api/references/vscode-api#Position

You see "with" method has 2 overloads. Now I want to use the "with(change: {line: number, character:number})" method:

 const endPos = startPos.with({ line: 1, character: -1 });

startPos is a "Position" object.

But this code is wrong. It seems I misunderstood this method. It just sets the position with the given value, rather than adding the "difference" on it. So how to get the Position of the last character of one line, derived from a given Position? 🙂


回答1:


Get the line of the startPos and use it's length to get the last char

let curLineText = editor.document.lineAt(startPos);
let lastCharPos = new vscode.Position(curLinePos.line, Math.max(curLineText.text.length-1, 0));

Remove the -1 if you want a position after the last character



来源:https://stackoverflow.com/questions/57099341/vscode-extenstion-how-to-get-position-of-last-character-of-line

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!