Jupyter Pre-Execution Hook / Cell Change Listener

85 Views Asked by At

I've been exploring different ways to listen for text changes in a notebook cell within JupyterLab. My current approach involves using INotebookTracker's activeCellChanged and currentChanged events to attach an event listener to the CodeMirror / IEditor instance of the active cell. This approach does work. However, I am looking for a more direct/intended way.

The implementation looks something like this:

notebookTracker.activeCellChanged.connect(() => {
      const cell = notebookTracker.activeCell;
      const editor = cell.editor.editor. 
    
      // Create an update listener extension
      const updateListenerExtension = EditorView.updateListener.of((update: ViewUpdate) => {
        if (update.docChanged) {
          // The document content has changed
          const currentContent = update.view.state.doc.toString();
          console.log('Editor content changed:', currentContent);
        }
      });
  
      // Attatch event listener
      cmEditor.dispatch({
        effects: StateEffect.appendConfig.of(updateListenerExtension)
      });
  
    }
  });

As I mentioned, the approach seems hacky, especially editor.editor, as it feels like bypassing some layers of abstraction. I’m wondering if there’s a more elegant or intended way to achieve this, potentially through a deeper dive into the CodeMirror API?. Any guidance or experience shared in this area would be greatly appreciated.


Additionally, I've come across suggestions for a "pre-execution hook" using NotebookActions.executionScheduled:

NotebookActions.executionScheduled.connect((_, args) => {
  let cell: Cell;
  let notebook: Notebook;
  notebook = args["notebook"];
  cell = args ["cell"];
  // Additional logic here...
});

});

However, I'm looking for a solution that works in real-time as the user types, not just upon cell execution.

Cross Link to Jupyter's discourse

Thanks in advance!

0

There are 0 best solutions below