Rouge
A pure Ruby code highlighter that is compatible with Pygments
Install / Use
/learn @rouge-ruby/RougeREADME
Rouge
Rouge is a pure Ruby syntax highlighter. It can highlight over 200 different languages, and output HTML or ANSI 256-color text. Its HTML output is compatible with stylesheets designed for Pygments.
Installation
In your Gemfile, add:
gem 'rouge'
or
gem install rouge
Usage
Rouge's most common uses are as a Ruby library, as part of Jekyll and as a command line tool.
Library
Here's a quick example of using Rouge as you would any other regular Ruby library:
require 'rouge'
# make some nice lexed html
source = File.read('/etc/bashrc')
formatter = Rouge::Formatters::HTML.new
lexer = Rouge::Lexers::Shell.new
formatter.format(lexer.lex(source))
# Get some CSS
Rouge::Themes::Base16.mode(:light).render(scope: '.highlight')
# Or use Theme#find with string input
Rouge::Theme.find('base16.light').render(scope: '.highlight')
Jekyll
Rouge is Jekyll's default syntax highlighter. Out of the box, Rouge will be
used to highlight text wrapped in the {% highlight %} template tags. The
{% highlight %} tag provides minimal options: you can specify the language to
use and whether to enable line numbers or not. More information is available in
the Jekyll docs.
Command Line
Rouge ships with a rougify command which allows you to easily highlight files
in your terminal:
$ rougify foo.rb
$ rougify foo.rb -t monokai.sublime
$ rougify style monokai.sublime > syntax.css
Configuration
Formatters
Rouge comes with a number of formatters built-in but as of Rouge 2.0, you are encouraged to write your own formatter if you need something custom.
The built-in formatters are:
-
Rouge::Formatters::HTML.newwill render your code with standard class names for tokens, with no div-wrapping or other bells or whistles. -
Rouge::Formatters::HTMLInline.new(theme)will render your code with no class names, but instead inline the styling options into thestyle=attribute. This is good for emails and other systems where CSS support is minimal. -
Rouge::Formatters::HTMLLinewise.new(formatter, class: 'line-%i')will split your code into lines, each contained in its own div. Theclassoption will be used to add a class name to the div, given the line number. -
Rouge::Formatters::HTMLLineHighlighter.new(formatter, highlight_lines: [3, 5])will split your code into lines and wrap the lines specified by thehighlight_linesoption in a span with a class name specified by thehighlight_line_classoption (default:hll). -
Rouge::Formatters::HTMLLineTable.new(formatter, opts={})will output an HTML table containing numbered lines, each contained in its own table-row. Options are:start_line: 1- the number of the first rowline_id: 'line-%i'- asprintftemplate foridattribute with current line numberline_class: 'lineno'- a CSS class for each table-rowtable_class: 'rouge-line-table'- a CSS class for the tablegutter_class: 'rouge-gutter'- a CSS class for the line-number cellcode_class: 'rouge-code'- a CSS class for the code cell
-
Rouge::Formatters::HTMLPygments.new(formatter, css_class='codehilite')wraps the given formatter with div wrappers generally expected by stylesheets designed for Pygments. -
Rouge::Formatters::HTMLTable.new(formatter, opts={})will output an HTML table containing numbered lines similar toRouge::Formatters::HTMLLineTable, except that the table from this formatter has just a single table-row. Therefore, while the table is more DOM-friendly for JavaScript scripting, long code lines will mess with the column alignment. Options are:start_line: 1- the number of the first lineline_format: '%i'- asprintftemplate for the line number itselftable_class: 'rouge-table'- a CSS class for the tablegutter_class: 'rouge-gutter'- a CSS class for the guttercode_class: 'rouge-code'- a CSS class for the code column
-
Rouge::Formatters::HTMLLegacy.new(opts={})is a backwards-compatibility class intended for users of Rouge 1.x, with options that were supported then. Options are:inline_theme: nil- use an HTMLInline formatter with the given themeline_numbers: false- use an HTMLTable formatterwrap: true- use an HTMLPygments wrappercss_class: 'codehilite'- a CSS class to use for the Pygments wrapper
-
Rouge::Formatters::Terminal256.new(theme)is a formatter for generating highlighted text for use in the terminal.thememust be an instance ofRouge::Theme, or aHashstructure with:themeentry. -
Rouge::Formatters::TerminalTruecolor.new(theme)is similar to the previous, except it outputs ANSI truecolor codes, instead of approximating with a 256-color scheme. -
Rouge::Formatters::Tex.newis a formatter for TeX systems which wraps each token with an\RG{toktype}{text}tag. You can then userougify style mystyle --texto generate definitions for these tags and the surrounding environment.
Writing your own HTML formatter
For the majority of applications, there are custom requirements for presenting highlighted text, as HTML or otherwise. In these cases, rather than patching or post-processing the output of Rouge, it is usually better to write your own formatter.
This may sound intimidating, but it is actually quite easy! All you have to do
is subclass Rouge::Formatter, define a tag, and implement a method
#stream(tokens, &block), which receives an Enumerable of token/value pairs,
and yields out chunks of strings which will be concatenated.
The Formatter base class contains the helper method #token_lines(stream, &block),
which separates tokens into distinct lines, and Rouge::Formatters::HTML
contains the helper #span(token, value) to escape and render
standard <span> tags for HTML.
Alternatively, if you want to override how individual spans are rendered,
you can override #safe_span(token, safe_value), which will be passed the
token type and pre-escaped content for the token.
class MyFormatter < Rouge::Formatters::HTML
# this is the main entry method. override this to customize the behavior of
# the HTML blob as a whole. it should receive an Enumerable of (token, value)
# pairs and yield out fragments of the resulting html string. see the docs
# for the methods available on Token.
def stream(tokens, &block)
yield "<div class='my-outer-div'>"
tokens.each do |token, value|
# for every token in the output, we render a span
yield span(token, value)
end
yield "</div>"
end
# or, if you need linewise processing, try:
def stream(tokens, &block)
token_lines(tokens).each do |line_tokens|
yield "<div class='my-cool-line'>"
line_tokens.each do |token, value|
yield span(token, value)
end
yield "</div>"
end
end
# Override this method to control how individual spans are rendered.
# The value `safe_value` will already be HTML-escaped.
def safe_span(token, safe_value)
# in this case, "text" tokens don't get surrounded by a span
if token == Token::Tokens::Text
safe_value
else
"<span class=\"#{token.shortname}\">#{safe_value}</span>"
end
end
end
Lexer Options
-
debug: truewill print a trace of the lex on stdout. For safety, this only works ifRouge::Lexer.enable_debug!has been called. -
parent: ''allows you to specify which language the template is inside.
Theme Options
-
scope: '.highlight'sets the CSS selector to which styles are applied, e.g.:Rouge::Themes::MonokaiSublime.render(scope: 'code')
Documentation
Rouge's documentation is available at rouge-ruby.github.io/docs/.
Requirements
Ruby
Rouge is compatible with all versions of Ruby from 3.0 onwards. It has no external dependencies.
Encodings
Rouge only supports UTF-8 strings. If you'd like to highlight a string with a different encoding, please convert it to UTF-8 first.
Integrations
- Middleman:
- middleman-syntax (@bhollis)
- middleman-rouge (@Linuus)
- RDoc: rdoc-rouge (@zzak)
- Rails: Rouge::Rails (@jacobsimeon)
Contributing
We're always excited to welcome new contributors to Rouge. By it's nature, a syntax highlighter relies for its success on submissions from users of the languages being highlighted. You can help Rouge by filing bug reports or developing new lexers.
Everyone interacting in Rouge and its sub-projects' code bases is expected to follow the Rouge Code of Conduct.
Bug Reports
Rouge uses GitHub's Issues to report bugs. You can [choose][issue-chooser] from one of our templates or create a custom issue. Issues that have not been active for a year are automatically closed by GitHub's [Probot][].
[issue-chooser]: https://github.com/rouge-ruby/rouge/issues/new/choose "Choose an
