KxSystems / pyq

PyQ — Python for kdb+
http://code.kx.com/q/interfaces
Apache License 2.0
191 stars 49 forks source link

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

Open flcong opened 1 year ago

flcong commented 1 year ago

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 commented 1 year ago

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.

sashkab commented 1 year ago

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.