Adding new line for other users

Sorry I am new to using CodeMirror, and I’m running into what surely is an easy bug. I’m making an online collaborative IDE for a school project. Didn’t want to send entire documents and wanted to just do the updates, but the input event listener doesn’t catch the enter key. Using keydown I can get when the enter key was pressed, I have the index I want to put it but for some reason can’t get the replaceRange function to work, I keep getting “Uncaught (in promise) TypeError: editorView.replaceRange is not a function” in my web console of the receiving user. I’m assuming I’m missing something rather simple like not targeting the right object to call replaceRange on, or not having the correct index/position of where im adding the new line.

Below is the relevant code for this problem.

Javascript file

cmEditorElement.addEventListener('keydown', (e) => {
        if (e.key === 'Enter') {
            console.log("Enter key was pressed");
            list = cmEditorElement.querySelector(".cm-content").childNodes;
            let count = 1;
  , child => {
                if (child.className == "cm-line") {
                    // Name is not active line, move on
                else {
                    // Name matched, call socket to add new line to all other users
                    console.log('New line on ' + count)
                    socket.emit('newLine', count)

    socket.on('addingNewLine', (pos) => {
        console.log('Received new line')
        editorView.replaceRange("\n", pos)

Server File

  socket.on('newLine', (pos) => {
    console.log('Adding new line')
    socket.broadcast.emit('addingNewLine', pos)

Thank you for any help!

You’ll want to follow this example if you want robust collaborative editing. Input handlers are indeed a terrible place to try and capture document changes. Update listeners work better, but you’ll still have issues with concurrent edits if you use those the naive way. This is why @codemirror/collab exists.

1 Like

Hey, thank you for your response!

We originally were trying to implement our own OT approach, but since there have been so many bugs, and we undoubtedly won’t be able to implement our own conflict resolution we decided to try to implement the extension.

I’ve read over the collab extension example and went through the github a couple of times and I’m still not getting the hang of it, I’m going to be trying to implement it over the next few days using javascript and, hopefully I will make some progress on it, and I will likely ask more questions lol.