How to capture the line added / deleted / modified for the VSCode extension api
Answer a question
I am developing the extension for VS Code and i need to capture the line added / deleted in the editor. Basically the issue i have is. I have created a diagnostic collection for a opened document say on Line 5, Postiion 2.
When a user edits the text document say added a line, the position changes. But the diagnostic data that is displayed in problems is still points to the old line 5.
What is the way to solve this, was thinking is there any possibility to capture the line added / deleted events of editor and update the line numbers.
Answers
vscode.workspace.onDidChangeTextDocument(event => {
console.log(event);
})
will be fired when any TextDocument is changed (not just saved). It does so on a character-by-character basis though (except pastes/deletions which happen all at once).
There is the information you are looking for in the event object, like
event.document.filename // which document was changed
event.contentChanges // an array of changes
from which you can get the actual change(s) made to the document plus things like
event.contentChanges[0].range.start.line // the line where the change started on
On deletions, you are not given the actual text that was deleted, but the result, an empty string, but you still can get the range of the change - which has your two start and end Positions, each of which has a line number component to it.
I guess you could keep track of these changes and only do your calculations on a onDidSaveTextDocument(event) if you want to do them in bulk on a save.
更多推荐
所有评论(0)