Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Non-Python language syntax highlighting?

I am building an IPython cell magic to support interactive SQL queries and want the syntax highlighting of that cell to change from Python to SQL. What is the best way to achieve this?

Imagine an input cell of the following:

%%sqlite example.db

SELECT id,name FROM Users;

Currently, the query is parsed as Python code, with messy results.

In particular, is the language parameter of the Notebook format supported? None of the cell magics supported by the official documentation (R, Ruby, Octave, ..) seem to bother changing it from "python".

like image 998
Tim McNamara Avatar asked Jul 12 '14 05:07

Tim McNamara


1 Answers

I'm running Jupyter 4 (4.2.0, to be exact), and putting the following code in ~/.jupyter/custom/custom.js works very well for me.

IPython.notebook.events.one('kernel_ready.Kernel',
    function(){
        IPython.CodeCell.config_defaults
               .highlight_modes['magic_text/x-mssql'] = {'reg':[/^%%sql/]} ;
        IPython.notebook.get_cells().map(
            function(cell){
                if (cell.cell_type == 'code'){
                    cell.auto_highlight();
                }
            }) ;
    }) ;

Update

Newer versions of the notebook (I'm now using 5.2.2) use a slightly different key for configuration, codecell.CodeCell.options_default.highlight_modes.
The code I'm currently using (still in custom.js) looks like this:

require(['notebook/js/codecell'],
    function(codecell) {
        codecell.CodeCell.options_default
            .highlight_modes['magic_text/x-mssql'] = {'reg':[/^%%sql/]} ;
        Jupyter.notebook.events.one('kernel_ready.Kernel',
            function(){
                Jupyter.notebook.get_cells().map(
                    function(cell){
                        if (cell.cell_type == 'code'){
                            cell.auto_highlight();
                        }
                    }) ;
            });
    });
like image 130
cco Avatar answered Nov 07 '22 10:11

cco