IPython change input cell syntax highlighting logi

2019-07-21 21:24发布

问题:

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?

回答1:

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.)



回答2:

For recent IPython version, the selected answer no longer works. The 'config_default' property was renamed options_default (Ipython 6.0.0). The following works:

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