Seeking Better Approach of Pre-execution Hooks / Cell Event Listeners


There seems to be many ways around tracking real-time text changes in a Jupyter notebook cell. One approach I found is leveraging INotebookTracker’s activeCellChanged and currentChanged events. Then attach an event listener to the CodeMirror / IEditor instance in the currently active cell.

Something a long the lines of:

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
        effects: StateEffect.appendConfig.of(updateListenerExtension)

This approach works but feels somewhat hacky, especially the 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.

Thanks in advance!

Cross Link to Stack-Overflow