问题
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