How to programmatically create a markdown cell?

I am using this function to create a preformatted html div in a new cell:

def new_section(title='New section'):
    style = "text-align:center;background:#c2d3ef;padding:16px;color:#ffffff;font-size:2em;width:98%"
    div = f'<div style="{style}">{title}</div>'
    return get_ipython().set_next_input(div, replace=True)

I call the function new_section() in a new cell and after execution, the html replaces the call.
This is only a partial solution to what I want to accomplish, which is to create that cell with a cell_type of ‘markdown’ so that I do not have to manually change the cell type before running it to render the html.
Is that possible?
Thanks for you help.

The line between client and kernel is intentionally fairly austere: the linked code works today in e.g. JupyterLab and the IPython terminal app… but probably not nbconvert, for example. I would also probably not expect this to be extended in the future.

One approach to bridging the two is a client-specific tool such as ipylab: it can run any jupyterlab command… but there might not be one for “new markdown cell”.

1 Like

Thanks for your prompt response!
It seems to me that the outcome of get_ipython().set_next_input is to create a new CODE cell by default.
How difficult would it be to amend the set_next_input method to include a cell_type parameter, which would be ‘code_cell’ by default, along with markdown_cell and raw_cell as the other valid cell types?

put more simply: no. the kernel doesn’t know about being in a notebook.

1 Like