Quarto中Python代码输出高亮适配问题问询
Quarto代码输出高亮适配Python的解决方法
当前问题是:output-line-highlight.lua滤镜仅对R代码输出生效,Python输出无法触发高亮。原因是原滤镜只针对R输出的HTML结构做了处理,未适配Python输出的类名标记。
修改Lua滤镜适配多语言输出
将output-line-highlight.lua的内容替换为以下代码,让滤镜同时识别R和Python的输出块:
function Div(el) -- 匹配带有highlight类且以-output结尾的输出块(覆盖r-output、python-output等) if el.classes:includes("highlight") and el.classes:find("%-output$") then local line_numbers = el.attributes["output-line-numbers"] if line_numbers then local lines = {} for num in string.gmatch(line_numbers, "%d+") do table.insert(lines, tonumber(num)) end -- 拆分输出内容并为指定行添加高亮 local content = el.content[1].text local new_lines = {} local line_count = 1 for line in string.gmatch(content, "[^\n]+") do if table.contains(lines, line_count) then table.insert(new_lines, pandoc.RawBlock("html", '<div class="highlight-line">' .. line .. '</div>')) else table.insert(new_lines, pandoc.RawBlock("html", '<div>' .. line .. '</div>')) end line_count = line_count + 1 end el.content = new_lines el.attributes.style = "white-space: pre-wrap;" return el end end end -- 辅助函数:检查数组是否包含目标值 function table.contains(tbl, value) for _, v in ipairs(tbl) do if v == value then return true end end return false end
关键修改说明
- 原滤镜可能仅匹配
div.r-output.highlight,现在改为匹配所有以-output结尾的类(如python-output),同时保留highlight类的判断 - 保持原有的行号解析和高亮逻辑,确保R和Python输出的处理逻辑一致
验证方法
替换滤镜文件后,重新渲染你的Quarto文档,Python代码块中指定的输出行(12-17行)应该会和R输出一样被高亮显示。
内容的提问来源于stack exchange,提问作者Frans Rodenburg
相关产品推荐
相关产品推荐

