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"
.
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();
}
}) ;
}) ;
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();
}
}) ;
});
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With