Capturing keystrokes in visual studio code extensi

2019-07-18 19:50发布

问题:

I would like to be able to capture keystrokes in a visual studio code extension. I need to know the new text that was either added or removed and the position of the change in the file.

I have registered a listener:

vscode.window.onDidChangeTextEditorSelection(handleChange)

and am getting updates on every single caret move but I am having a hard time getting added/removed text and positions from the event that is passed in. Currently, I am doing this in the handler:

function handleChange(event) {
    console.log("Change in the text editor");
    for(var i = 0;i < event.selections.length;i++)
    {
        var selection = event.selections[i];
        console.log("Start- Line: (" + selection.start.line + ") Col: (" + selection.start.character + ") End- Line: (" + selection.end.line + ") Col: (" + selection.end.character + ")");
    }
    console.log(event);
}

The documentation mentions something called a TextDocumentContentChangeEvent which seems like exactly what I need but I don't know how to register a handler to receive these.

回答1:

I discovered the problem in my original question. I was listening for the wrong event. To get TextDocumentChangeEvents which have a property called contentChanges which returns TextDocumentContentChangeEvents, use this code:

vscode.workspace.onDidChangeTextDocument(handleChange)

and pass in a function which will be called with a TextDocumentChangeEvent on every change to a file.