user414873
user414873

Reputation: 783

CodeMirror: Catching Enter Key prevents line breaks

I used the extraKeys-option of CodeMirror 3.12 to detect when the user starts a new line:

extraKeys: {
    "Enter": onNewLine
}

onNewLine() does nothing but a console.log(). Now CodeMirror ignores that key. You can't start a new line anymore. Is there a way to hook up additional functionality on a new-line-event without interfering CodeMirror internals? I just want to analyze the text of the recently closed line.

Upvotes: 4

Views: 4091

Answers (2)

bmode
bmode

Reputation: 770

I found that returning CodeMirror.Pass also works:

function onNewLine(e) {
    console.log("Enter key was pressed!");
    return CodeMirror.Pass;
}

From the documentation:

A key handler function may return CodeMirror.Pass to indicate that it has decided not to handle the key, and other handlers (or the default behavior) should be given a turn.

This seems to work even if the handler does perform an action. In my case I was using the editor.indentLine function to indent the current line when the user pressed the enter key.

Upvotes: 3

aljordan82
aljordan82

Reputation: 1720

Add a line break at the end of onNewLine function. This should work

 function onNewLine(e){
    console.log(e);
    editor.replaceSelection("\n" ,"end");
  }

Upvotes: 5

Related Questions