为 Jupyter notebook cell magic 添加语法高亮 [英] adding syntax highlighting to Jupyter notebook cell magic

查看:79
本文介绍了为 Jupyter notebook cell magic 添加语法高亮的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm trying to figure out how to activate CodeMirror syntax highlighting for a CodeMirror-supported language (cypher) within a cell for a custom Jupyter cell magic (%%mymagic). The magic isn't associated with a special kernel - it just runs Python commands that process the string entered into the cell that I want to highlight. From what I can tell, this ostensibly can be done using something like

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

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

within the class that implements the magic. I can't seem to get this to work, however; no change in highlighting occurs when I enter stuff in a cell that starts with %%mymagic. Is the above approach accurate? Does 'magic_cypher' need to have a specific format? Does the magic need to somehow specify the MIME type CodeMirror associates with the desired highlighting language? I'm using notebook 5.0.0, jupyter_core 4.3.0, and python 2.7.13.

推荐答案

以下代码适用于使用 notebook 5.x 放置在 ~/.jupyter/custom/custom.js 中的 SQL:

The following code works for SQL when placed in ~/.jupyter/custom/custom.js with notebook 5.x:

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

这篇关于为 Jupyter notebook cell magic 添加语法高亮的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆