What's the correct way to create a markdown cell programmatically?

I’m trying to write a Jupyter lab 4 extension and want to add a markdown cell, but when I do it renders as a raw cell in the ui. Am I doing something wrong. This is my code:

const model = notebookTracker.currentWidget.content.model;
const rendermime: IRenderMimeRegistry = notebookPanel.content.rendermime;
const contentFactory = notebookPanel.content.contentFactory;
const markdownCellModel = new MarkdownCellModel({});

const cell = contentFactory.createMarkdownCell({ model: markdownCellModel, rendermime, contentFactory });
model.sharedModel.insertCell(activeCellIndex + 1, cell);
2 Likes

JupyterLab’s shortcuts, are also executable from an extension. You could begin with an insertion command notebook:insert-cell-below, then change it to a markdown cell notebook:change-cell-to-markdown.

Something like this:

... activate: (app: JupyterFrontEnd, notebookTracker: INotebookTracker) => {
  const addMarkdownCell = () => {
    const { commands } = app;
    const notebookPanel = notebookTracker.currentWidget;

    if (notebookPanel) {
      commands.execute('notebook:insert-cell-below').then(() => {
        commands.execute('notebook:change-cell-to-markdown');
      });
    }
  };

  addMarkdownCell();
}

Ran it now - seems to work.

1 Like