为 Jupyter notebook cell magic 添加语法高亮显示
adding syntax highlighting to Jupyter notebook cell magic
我正在尝试弄清楚如何在自定义 Jupyter 单元魔术 (%%mymagic
) 的单元格中为 CodeMirror 支持的语言(密码)激活 CodeMirror 语法突出显示。魔术与特殊内核无关 - 它只是运行 Python 命令来处理输入到我要突出显示的单元格中的字符串。据我所知,这表面上可以使用类似
的方法来完成
from notebook.services.config.manager import ConfigManager
cm = ConfigManager()
cm.update('notebook', {'CodeCell': {'highlight_modes': {'magic_cypher': {'reg': '^%%mymagic'}}}})
在实施魔法的 class 中。
但是,我似乎无法使它起作用;当我在以 %%mymagic
开头的单元格中输入内容时,突出显示不会发生任何变化。以上方法是否准确? 'magic_cypher' 是否需要特定格式?魔法是否需要以某种方式指定 CodeMirror 与所需突出显示语言关联的 MIME 类型?我正在使用笔记本 5.0.0、jupyter_core 4.3.0 和 python 2.7.13。
我成功做到这一点的案例是为 %%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/custom/custom.js
中与笔记本 5.x 一起放置时适用于 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!
我正在尝试弄清楚如何在自定义 Jupyter 单元魔术 (%%mymagic
) 的单元格中为 CodeMirror 支持的语言(密码)激活 CodeMirror 语法突出显示。魔术与特殊内核无关 - 它只是运行 Python 命令来处理输入到我要突出显示的单元格中的字符串。据我所知,这表面上可以使用类似
from notebook.services.config.manager import ConfigManager
cm = ConfigManager()
cm.update('notebook', {'CodeCell': {'highlight_modes': {'magic_cypher': {'reg': '^%%mymagic'}}}})
在实施魔法的 class 中。
但是,我似乎无法使它起作用;当我在以 %%mymagic
开头的单元格中输入内容时,突出显示不会发生任何变化。以上方法是否准确? 'magic_cypher' 是否需要特定格式?魔法是否需要以某种方式指定 CodeMirror 与所需突出显示语言关联的 MIME 类型?我正在使用笔记本 5.0.0、jupyter_core 4.3.0 和 python 2.7.13。
我成功做到这一点的案例是为 %%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/custom/custom.js
中与笔记本 5.x 一起放置时适用于 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!