【问题标题】:adding syntax highlighting to Jupyter notebook cell magic向 Jupyter 笔记本单元魔术添加语法高亮显示
【发布时间】:2017-09-24 06:42:34
【问题描述】:

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

from notebook.services.config.manager import ConfigManager
cm = ConfigManager()
cm.update('notebook', {'CodeCell': {'highlight_modes': {'magic_cypher': {'reg': '^%%mymagic'}}}})

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

【问题讨论】:

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


    【解决方案1】:

    以下代码适用于带有笔记本 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 获取此信息!

    【讨论】:

    • 我的测试表明这适用于 5.x 和 6.x - 谢谢!
    • @cco,除了sql之外,CodeMirror支持的其他语言你能激活语法高亮吗?
    • 我刚刚尝试过,将codecell.CodeCell.options_default.highlight_modes["application/x-cypher-query"] = {'reg':[/^%%cypher/]} ; 添加到 custom.js(就在 SQL 的类似行之后)似乎可以正常工作。 highlight_modes 中的键必须与 Codemirror 模式文件的 defineMIME 行中的 MIME 类型匹配。
    • 原来我有一个~/.jupyter/nbconfig/notebook.json,不管~/.jupyter/custom/custom.js如何,它都在默默地为%%cells激活密码模式。
    【解决方案2】:

    我成功的案例是为%%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(); } }) ;
    });
    

    【讨论】:

    • 你使用的是什么版本的 Jupyter?
    • 和你一样 - Notebook 5.0.5 和 Jupyter 4.3.0; Python 2.7.9,但这不应该有任何区别。
    • 对于您描述的custom.js,是否应该在以%%sql 开头的单元格中输入文本时实时设置文本样式?加载 ipython-sql 后,由于某种原因,我没有看到这种情况发生。
    • 此外,我通过在调试模式下运行笔记本服务器验证了 Jupyter 可以看到我的custom.js。
    • 我的错误 - 它适用于 4.x 笔记本,但我只是看了一下,它不适用于 5.0。如果我再次开始工作,我会通知你的。
    猜你喜欢
    • 2020-01-17
    • 1970-01-01
    • 1970-01-01
    • 2019-03-23
    • 1970-01-01
    • 2016-07-13
    • 2023-03-31
    • 2017-02-27
    • 2018-10-13
    相关资源
    最近更新 更多