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

如何在Asciidoctor代码块中设置Pygments的stripnl=False保留末尾空行?

方案一:通过Ruby脚本强制设置stripnl=False

Asciidoctor默认未暴露Pygments的stripnl参数,需通过简单Ruby脚本修改高亮器调用逻辑:

  1. 创建名为preserve_newlines.rb的文件,内容如下:
require 'asciidoctor'
require 'pygments'

# 覆盖Pygments高亮器的highlight方法,添加换行保留控制
class Asciidoctor::SyntaxHighlighter::PygmentsHighlighter
  def highlight code, lang, opts
    # 优先读取代码块属性,其次读取全局文档属性
    strip_nl = !(opts[:preserve_newlines] || document.attr('pygments-preserve-newlines') == 'true')
    # 调用Pygments核心方法,传入stripnl参数
    Pygments.highlight code, {
      lexer: lang,
      options: {
        stripnl: strip_nl,
        linenos: opts[:linenos] ? (document.attr('pygments-linenums-mode') || 'table') : nil,
        style: document.attr('pygments-style', 'default'),
        encoding: 'utf-8',
        startinline: true
      }.compact
    }
  end
end
  1. 启用换行保留:

    • 全局生效:在文档开头添加属性:pygments-preserve-newlines: true
    • 单个代码块生效:给目标代码块追加属性,示例:
      void example(void)
      {
          printf("hello, world\n");
      }
      
      
  2. 编译时加载脚本:

asciidoctor -r ./preserve_newlines.rb example.adoc -o example.html

方案二:无需Ruby脚本的替代方法

若不想编写脚本,可在代码块末尾空行插入全角空格,同时给代码块添加:trim-trailing-spaces: false属性,示例:

void example(void)
{
    printf("hello, world\n");
}
 // 此处为全角空格,请勿删除

全角空格不会被Pygments判定为需移除的空行,且在主流IDE和HTML/PDF输出中不会产生乱码,适合对代码内容精度要求不高的场景。


内容的提问来源于stack exchange,提问作者wovano

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.18 09:45:45