6

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

Tim McNamara
  • 18,019
  • 4
  • 52
  • 83
  • did you ever figure this out? I'm running into the same thing. – tmthyjames Aug 12 '16 at 16:55
  • For notebooks, I tend to either use inline dynamic SQL or read SQL in from files and then use it. However, something like this might be what you're looking for: https://github.com/catherinedevlin/ipython-sql –  Aug 12 '16 at 17:47

2 Answers2

3

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();
                        }
                    }) ;
            });
    });
cco
  • 5,873
  • 1
  • 16
  • 21
2

found this

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

worked for me.

Community
  • 1
  • 1
tmthyjames
  • 1,588
  • 2
  • 22
  • 30
  • Although, I discovered that it doesn't work if you put it in a startup file. You have to actually run it in a Jupyter notebook. – tmthyjames Aug 15 '16 at 02:10