IPython change input cell syntax highlighting logic for entire session


You can use extensions or display helpers in IPython to make whatever syntax highlighting you’d like on output cells.

For some special cell magics, like %%javascript you can also see the input cell itself is rendered with that language’s natural syntax highlighting.

How can you cause every input cell to be displayed with some chosen, non-Python syntax highlighting (regardless of any magics used on a cell, regardless of whether the cell embodies Python code, some other language).

In my case I am working with a custom-made cell magic for a proprietary language. The %%javascript syntax highlighting works well for this language, but if I have my own %%proprietarylang magic function, I obviously can’t use %%javascript to help me with how the cell is displayed.

Is there a setting I can enable when I launch the notebook, or some property of the ipython object itself that can be programmatically set inside of my magic function, which will cause the same display logic to happen as if it was %%javascript.

I know that general-purpose on-the-fly syntax highlighting is not supported by the notebook currently. I’m asking specifically about how to make use of pre-existing syntax highlighting effects, such as that of %%javascript.

I’ve seen some documentation referring to IPython.config.cell_magic_highlight but this does not seem to exist anymore. Is there a standard replacement for it?


To replace IPython.config.cell_magic_highlight, you can use something like

import IPython
js = "IPython.CodeCell.config_defaults.highlight_modes['magic_fortran'] = {'reg':[/^%%fortran/]};"
IPython.core.display.display_javascript(js, raw=True)

so cells which begin with %%fortran will be syntax-highlighted like FORTRAN. (However, they will still be evaluated as python if you do only this.)

Answered By – Georg Sievelson

Answer Checked By – Dawn Plyler (AngularFixing Volunteer)

Leave a Reply

Your email address will not be published.