Rouge syntax highlighter 使用教程

Rouge syntax highlighter 使用教程

rouge A pure Ruby code highlighter that is compatible with Pygments rouge 项目地址: https://gitcode.com/gh_mirrors/ro/rouge

1. 项目介绍

Rouge 是一个纯 Ruby 编写的语法高亮器。它支持超过 200 种不同的语言,并且能够输出 HTML 或 ANSI 256 色文本。Rouge 的 HTML 输出与 Pygments 的样式表兼容。

2. 项目快速启动

首先,确保你的系统中已经安装了 Ruby。然后,可以通过以下方式安装 Rouge:

gem install rouge

或者,如果你使用的是 Bundler,可以在你的 Gemfile 中添加:

gem 'rouge'

然后执行 bundle install 命令。

使用 Rouge 作为 Ruby 库

以下是一个使用 Rouge 作为 Ruby 库的快速示例:

require 'rouge'

# 读取要高亮的源代码
source = File.read('/etc/bashrc')

# 创建一个 HTML 格式化器和一个 Shell 语法解析器
formatter = Rouge::Formatters::HTML.new
lexer = Rouge::Lexers::Shell.new

# 进行高亮处理并输出结果
highlighted_code = formatter.format(lexer.lex(source))
puts highlighted_code

使用 Rouge 作为命令行工具

Rouge 还提供了一个命令行工具 rougify,你可以通过以下方式高亮文件:

rougify foo.rb

或者输出 CSS 样式:

rougify style monokai.sublime > syntax.css

3. 应用案例和最佳实践

Jekyll 集成

Rouge 是 Jekyll 默认的语法高亮器。在 Jekyll 中,你可以使用 {% highlight %} 模板标签来高亮代码。例如:

{% highlight ruby %}
def hello
  puts "Hello, World!"
end
{% endhighlight %}

自定义 HTML 格式化器

如果你需要自定义 HTML 输出格式,可以创建一个继承自 Rouge::Formatters::HTML 的类,并覆盖相应的方法:

class MyFormatter < Rouge::Formatters::HTML
  def stream(tokens, &block)
    yield "<div class='my-outer-div'>"
    tokens.each do |token, value|
      yield span(token, value)
    end
    yield "</div>"
  end

  def safe_span(token, safe_value)
    if token == Token::Tokens::Text
      safe_value
    else
      "<span class=\"#{token.shortname}\">#{safe_value}</span>"
    end
  end
end

4. 典型生态项目

以下是一些与 Rouge 相关的生态项目:

以上是 Rouge 的基本使用教程,希望对你有所帮助。

rouge A pure Ruby code highlighter that is compatible with Pygments rouge 项目地址: https://gitcode.com/gh_mirrors/ro/rouge

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

段琳惟

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值