pyq icon indicating copy to clipboard operation
pyq copied to clipboard

Is there a way to have q syntax highlighting in cells starting with `%%q` in jupyter notebook?

Open flcong opened this issue 2 years ago • 2 comments

When using PyQ with python in jupyter notebook, all cells use syntax highlighting of Python by default. This makes q code written in cells starting with %%q very confusing (suppose you use ' somewhere, and all code following it is highlighted as string in python). Hence, I wonder if someone knows some way to use q syntax highlighting in cells starting with %%q.

I find a similar question on stackoverflow. There is an answer about SQL. They say adding the following code in ~/.jupyter/custom/custom.js to use SQL syntax highlighting in cells starting with %%sql.

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(); } }) ;
  });
});

Yet, I am not sure how to modify the code in the answer so it recognizes q, particularly what the highlight_modes should be used.

flcong avatar Jul 02 '23 22:07 flcong

After some experiments, I'm able to achieve the functionality using the following JS code:

require(['notebook/js/codecell'], function(codecell) {
  codecell.CodeCell.options_default.highlight_modes['magic_text/x-q'] = {'reg':[/^%%q/]} ;
  Jupyter.notebook.events.one('kernel_ready.Kernel', function(){
  Jupyter.notebook.get_cells().map(function(cell){
      if (cell.cell_type == 'code'){ cell.auto_highlight(); } }) ;
  });
});

This can be added either in ~/.jupyter/custom/custom.js or in a cell started with magic %%javascript. However, it seems that %%javascript cannot be used in Jupyter Lab. The mode name magic_text/x-q comes from jupyterq.

flcong avatar Jul 03 '23 01:07 flcong

If I recall correctly, you need to install pygments-q module. I recall there was one busted release of pygments-q, so if 0.5 doesn't work for you, please install version 0.4.

sashkab avatar Jul 03 '23 01:07 sashkab