为Jupyter笔记本单元格法术添加语法高亮

时间:2017-04-26 17:57:25

标签: ipython syntax-highlighting ipython-notebook jupyter codemirror

我正在尝试弄清楚如何为单元格内的CodeMirror支持的语言(cypher)激活CodeMirror语法高亮,以获得自定义Jupyter单元格魔术(%%mymagic)。魔法与特殊内核无关 - 它只运行Python命令来处理输入到我要突出显示的单元格中的字符串。据我所知,这表面上可以用

之类的东西来完成
from notebook.services.config.manager import ConfigManager
cm = ConfigManager()
cm.update('notebook', {'CodeCell': {'highlight_modes': {'magic_cypher': {'reg': '^%%mymagic'}}}})

在实现魔法的类中。 但是,我似乎无法让它工作;当我在以%%mymagic开头的单元格中输入内容时,没有突出显示的变化。上述方法准确吗? 'magic_cypher'需要具有特定格式吗?魔术是否需要以某种方式指定CodeMirror与所需突出显示语言关联的MIME类型?我使用的是笔记本5.0.0,jupyter_core 4.3.0和python 2.7.13。

2 个答案:

答案 0 :(得分:8)

以下代码适用于使用notebook 5.x放置在~/.jupyter/custom/custom.js中的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(); } }) ;
  });
});

此信息将转至Thomas K

答案 1 :(得分:0)

我成功做到这一点的情况是为%%sql魔法添加SQL突出显示。我通过将以下内容添加到~/.jupyter/custom/custom.js来完成此操作。第一行将模式添加到Codemirror配置,其余部分将样式应用于工作簿中需要它的任何现有单元格(稍后单元格将在创建时适当地设置样式)。

,虽然我希望安装魔法,但我没有成功地实现它
IPython.CodeCell.config_defaults.highlight_modes['magic_text/x-mssql'] = {'reg':[/^%%sql/]} ;
IPython.notebook.events.one('kernel_ready.Kernel', function(){
    IPython.notebook.get_cells().map(function(cell){
        if (cell.cell_type == 'code'){ cell.auto_highlight(); } }) ;
});
相关问题