Detecting when a user presses enter/return at the end of a line

Hello there,

I’m working on an extension similar to vscode-endwise and endwise.vim that will add the ‘end’ keyword automatically in languages like Ruby and Crystal. You can see an example in the description of the vscode-endwise repo.

After doing some digging I’ve been able to find a way to get the contents of the line that the user is currently editing by using ranges and the getTextInRange method, but I haven’t found a way to detect when the user creates a newline. What would be the best way of going about that?

1 Like

You can use the TextEditor.onDidChange() event to detect when the user edits the text, which would include when they press enter.

Then you can use TextEditor.selectedRange to get the index of the current cursor position. The start property on the returned Range object should have the index of the current cursor position.

Then find which character is just before the current cursor position by using TextEditor. getTextInRange(range) and subtracting 1 from the current range. If the character just before is a newline character then they are on a new line.

1 Like