You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

求助:如何在Jupyter Notebook中实现GLSL语法高亮?

在Jupyter Notebook中实现GLSL语法高亮的方法

方法1:利用Pygments内置的GLSL支持

Jupyter Notebook默认使用Pygments做语法高亮,而Pygments原生支持GLSL语言。你只需在Markdown单元格中,用指定语言为glsl的代码块编写代码即可:

attribute vec3 vertexPosition;
uniform mat4 projectionMatrix;
void main() {
    gl_Position = projectionMatrix * vec4(vertexPosition, 1.0);
}

只要你的Jupyter环境Pygments版本足够新(主流Anaconda或pip安装的Jupyter都满足),uniform、attribute等GLSL关键词会自动被高亮。

方法2:自定义代码单元格的GLSL魔法命令

如果需要在代码单元格里直接编写GLSL并实时高亮,可以注册自定义魔法命令:

  1. 在代码单元格中运行以下代码,注册%%glsl魔法命令:
from IPython.core.magic import register_cell_magic
from pygments import highlight
from pygments.lexers import GLSLLexer
from pygments.formatters import HtmlFormatter
from IPython.display import display, HTML

@register_cell_magic
def glsl(line, cell):
    highlighted_code = highlight(cell, GLSLLexer(), HtmlFormatter(style='github'))
    display(HTML(highlighted_code))
  1. 之后在代码单元格开头加上%%glsl,编写GLSL代码后运行,就能看到高亮效果:
%%glsl
uniform float elapsedTime;
attribute vec2 uvCoord;
void main() {
    gl_FragColor = vec4(uvCoord.x, uvCoord.y, sin(elapsedTime), 1.0);
}

关于VSCode扩展无效的说明

VSCode的扩展仅作用于VSCode编辑器本身,和Jupyter Notebook是完全独立的两个运行环境,所以你安装的VSCode相关扩展无法影响Jupyter的语法高亮,这是正常现象。

内容的提问来源于stack exchange,提问作者Moisés Dias

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.11 23:45:54