Convert Figma logo to code with AI

rouge-ruby logorouge

A pure Ruby code highlighter that is compatible with Pygments

3,330
735
3,330
226

Top Related Projects

4,301

A general purpose syntax highlighter in pure Go

JavaScript syntax highlighter with language auto-detection and zero dependencies.

12,288

Lightweight, robust, elegant syntax highlighting.

11,295

Syntax checking hacks for vim

48,640

A cat(1) clone with wings.

12,626

A Ruby static code analyzer and formatter, based on the community Ruby style guide.

Quick Overview

Rouge is a syntax highlighting library written in Ruby. It is designed to be a fast, pure-ruby, drop-in replacement for the classic syntax highlighter, Pygments. Rouge supports over 100 languages and output formats, making it a versatile tool for adding syntax highlighting to your projects.

Pros

  • Comprehensive Language Support: Rouge supports a wide range of programming languages, including popular ones like Ruby, Python, JavaScript, and more.
  • Customizable Styles: Rouge comes with a variety of built-in styles, and you can also create your own custom styles to match the branding and design of your project.
  • Performance: Rouge is written in pure Ruby and is designed to be fast and efficient, making it a suitable choice for real-time highlighting in web applications.
  • Actively Maintained: The Rouge project is actively maintained, with regular updates and bug fixes, ensuring its continued reliability and compatibility.

Cons

  • Ruby-Specific: As a Ruby library, Rouge may not be the best choice for projects that are not primarily written in Ruby or do not have a Ruby-based infrastructure.
  • Limited Ecosystem: Compared to some other syntax highlighting libraries, Rouge may have a smaller ecosystem of plugins, integrations, and community support.
  • Potential Performance Issues: While Rouge is designed to be fast, it may still struggle with very large code blocks or complex syntax highlighting requirements.
  • Dependency on Ruby: Using Rouge requires having Ruby installed and configured in your development environment, which may not be the case for all projects.

Code Examples

Here are a few examples of how to use Rouge in your Ruby projects:

Highlighting a code block:

require 'rouge'
require 'rouge/plugins/redcarpet'

markdown = Redcarpet::Markdown.new(Rouge::Plugins::Redcarpet)
puts markdown.render("```ruby\nputs 'Hello, Rouge!'\n```")

This code uses the rouge and rouge/plugins/redcarpet libraries to add syntax highlighting to a Markdown code block.

Highlighting a string of code:

require 'rouge'

lexer = Rouge::Lexer.find('ruby')
formatter = Rouge::Formatters::HTML.new
puts formatter.format(lexer.lex('puts "Hello, Rouge!"'))

This code uses the rouge library to highlight a string of Ruby code and output the HTML-formatted result.

Customizing the style:

require 'rouge'
require 'rouge/themes/github'

formatter = Rouge::Formatters::HTML.new(Rouge::Themes::Github)
puts formatter.format(lexer.lex('puts "Hello, Rouge!"'))

This code uses the rouge library to highlight a string of Ruby code, but with the "Github" style applied to the output.

Getting Started

To get started with Rouge, you can follow these steps:

  1. Add the rouge gem to your Gemfile:

    gem 'rouge'
    
  2. Require the rouge library in your Ruby code:

    require 'rouge'
    
  3. Choose a lexer (syntax highlighter) for the language you want to highlight:

    lexer = Rouge::Lexer.find('ruby')
    
  4. Create a formatter to generate the highlighted output:

    formatter = Rouge::Formatters::HTML.new
    
  5. Use the lexer and formatter to highlight your code:

    code = 'puts "Hello, Rouge!"'
    highlighted = formatter.format(lexer.lex(code))
    
  6. Output the highlighted code, for example, in an HTML document:

    <pre><code>
    <%= highlighted %>
    </code></pre>
    

That's the basic workflow for using Rouge in your Ruby projects. You can further customize the styles, integrate it with other libraries (like Redcarpet for Markdown), and explore the wide range of supported languages and output formats.

Competitor Comparisons

4,301

A general purpose syntax highlighter in pure Go

Pros of Chroma

  • Written in Go, offering potential performance benefits and easy deployment
  • Supports a wider range of languages out-of-the-box
  • Provides a command-line interface for easy integration into various workflows

Cons of Chroma

  • Smaller community and ecosystem compared to Rouge
  • Less mature project with potentially fewer edge cases handled
  • May require additional setup for Ruby-based projects

Code Comparison

Rouge (Ruby):

require 'rouge'
source = 'puts "Hello, world!"'
formatter = Rouge::Formatters::HTML.new
lexer = Rouge::Lexers::Ruby.new
formatter.format(lexer.lex(source))

Chroma (Go):

import "github.com/alecthomas/chroma"
source := `puts "Hello, world!"`
lexer := lexers.Get("ruby")
formatter := formatters.Get("html")
iterator, _ := lexer.Tokenise(nil, source)
formatter.Format(os.Stdout, styles.Get("monokai"), iterator)

Both libraries offer similar functionality for syntax highlighting, with Rouge being more Ruby-centric and Chroma providing a more language-agnostic approach. The choice between them often depends on the specific project requirements, language preferences, and integration needs.

JavaScript syntax highlighter with language auto-detection and zero dependencies.

Pros of highlight.js

  • Supports a wider range of languages (189+)
  • Client-side syntax highlighting, suitable for dynamic content
  • Easy integration with various frameworks and platforms

Cons of highlight.js

  • Larger file size, potentially impacting page load times
  • May require more processing power on the client-side
  • Less suitable for static site generation or server-side rendering

Code Comparison

highlight.js:

<pre><code class="language-python">
def greet(name):
    print(f"Hello, {name}!")
</code></pre>
<script>hljs.highlightAll();</script>

Rouge:

require 'rouge'
formatter = Rouge::Formatters::HTML.new
lexer = Rouge::Lexers::Python.new
highlighted = formatter.format(lexer.lex("def greet(name):\n    print(f\"Hello, {name}!\")"))

Key Differences

  • Implementation: highlight.js is JavaScript-based, while Rouge is Ruby-based
  • Usage: highlight.js is primarily used for client-side highlighting, Rouge for server-side
  • Performance: Rouge may be faster for static content, while highlight.js is more flexible for dynamic content
  • Integration: highlight.js is easier to integrate into web applications, while Rouge is commonly used in static site generators

Both libraries are actively maintained and have their strengths depending on the specific use case and development environment.

12,288

Lightweight, robust, elegant syntax highlighting.

Pros of Prism

  • Browser-based syntax highlighting, making it ideal for client-side applications
  • Extensive language support with plugins for additional languages and features
  • Easy integration with various web frameworks and content management systems

Cons of Prism

  • Limited server-side support, as it's primarily designed for client-side use
  • Potentially larger file size due to its JavaScript-based nature, which may impact page load times

Code Comparison

Rouge (Ruby):

require 'rouge'
source = 'puts "Hello, world!"'
formatter = Rouge::Formatters::HTML.new
lexer = Rouge::Lexers::Ruby.new
formatter.format(lexer.lex(source))

Prism (JavaScript):

const Prism = require('prismjs');
const source = 'console.log("Hello, world!");';
const html = Prism.highlight(source, Prism.languages.javascript, 'javascript');

Summary

Rouge is a Ruby-based syntax highlighter suitable for server-side applications, while Prism is a JavaScript-based solution ideal for client-side highlighting. Rouge offers better performance for server-side processing, whereas Prism provides more flexibility for web-based applications and supports a wider range of languages through its plugin system.

11,295

Syntax checking hacks for vim

Pros of syntastic

  • Integrated syntax checking for Vim, providing real-time error detection
  • Supports a wide range of programming languages and linters
  • Highly customizable with extensive configuration options

Cons of syntastic

  • Limited to Vim editor, while Rouge is a standalone syntax highlighter
  • Can potentially slow down Vim performance with heavy syntax checking
  • Requires external linters to be installed for full functionality

Code comparison

syntastic (Vim configuration):

let g:syntastic_always_populate_loc_list = 1
let g:syntastic_auto_loc_list = 1
let g:syntastic_check_on_open = 1
let g:syntastic_check_on_wq = 0

Rouge (Ruby code):

require 'rouge'
source = 'puts "Hello, world!"'
formatter = Rouge::Formatters::HTML.new
lexer = Rouge::Lexers::Ruby.new
formatter.format(lexer.lex(source))

Summary

syntastic is a powerful syntax checking plugin for Vim, offering real-time error detection across multiple languages. It's highly customizable but limited to Vim and may impact performance. Rouge, on the other hand, is a standalone syntax highlighter written in Ruby, providing language parsing and HTML output for various applications beyond text editors.

48,640

A cat(1) clone with wings.

Pros of bat

  • Built-in paging and file concatenation capabilities
  • Faster performance for large files due to Rust implementation
  • User-friendly interface with line numbers, git integration, and syntax highlighting

Cons of bat

  • Larger binary size and system-level installation required
  • Limited to command-line usage, not easily integrated into other applications
  • Fewer supported languages for syntax highlighting compared to Rouge

Code comparison

Rouge:

require 'rouge'
source = File.read('example.rb')
formatter = Rouge::Formatters::HTML.new
lexer = Rouge::Lexers::Ruby.new
formatter.format(lexer.lex(source))

bat:

bat example.rb

Rouge is a Ruby library for syntax highlighting, while bat is a command-line tool written in Rust. Rouge is more flexible and can be integrated into various applications, whereas bat provides a user-friendly interface for viewing files with syntax highlighting in the terminal. Rouge supports a wider range of languages, but bat offers additional features like git integration and built-in paging. The code comparison shows that Rouge requires more setup in code, while bat is simpler to use from the command line.

12,626

A Ruby static code analyzer and formatter, based on the community Ruby style guide.

Pros of RuboCop

  • Comprehensive Ruby style guide enforcement and linting
  • Highly configurable with extensive documentation
  • Integrates well with various editors and CI/CD pipelines

Cons of RuboCop

  • Can be resource-intensive for large codebases
  • Learning curve for configuration and customization
  • Occasionally produces false positives or overly strict rules

Code Comparison

Rouge (syntax highlighting):

class Example
  def method
    puts "Hello, world!"
  end
end

RuboCop (style checking):

# rubocop:disable Style/StringLiterals
class Example
  def method
    puts "Hello, world!"
  end
end
# rubocop:enable Style/StringLiterals

Key Differences

  • Rouge focuses on syntax highlighting for various languages
  • RuboCop specializes in Ruby code style enforcement and linting
  • Rouge is generally faster and lighter-weight
  • RuboCop provides more in-depth analysis of Ruby code quality
  • Rouge supports multiple languages, while RuboCop is Ruby-specific

Use Cases

  • Rouge: Documentation, code snippets, syntax highlighting in web applications
  • RuboCop: Ruby project development, code quality maintenance, enforcing team coding standards

Both tools serve different purposes in the Ruby ecosystem, with Rouge excelling at syntax highlighting and RuboCop focusing on code style and quality enforcement.

Convert Figma logo designs to code with AI

Visual Copilot

Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.

Try Visual Copilot

README

Rouge

Build Status Gem Version YARD Docs

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 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.new will 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 the style= 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. The class option 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 the highlight_lines option in a span with a class name specified by the highlight_line_class option (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 row
    • line_id: 'line-%i' - a sprintf template for id attribute with current line number
    • line_class: 'lineno' - a CSS class for each table-row
    • table_class: 'rouge-line-table' - a CSS class for the table
    • gutter_class: 'rouge-gutter' - a CSS class for the line-number cell
    • code_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 to Rouge::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 line
    • line_format: '%i' - a sprintf template for the line number itself
    • table_class: 'rouge-table' - a CSS class for the table
    • gutter_class: 'rouge-gutter' - a CSS class for the gutter
    • code_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 theme
    • line_numbers: false - use an HTMLTable formatter
    • wrap: true - use an HTMLPygments wrapper
    • css_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. theme must be an instance of Rouge::Theme, or a Hash structure with :theme entry.

Writing your own HTML formatter

If the above formatters are not sufficient, and you wish to customize the layout of the HTML document, we suggest writing your own HTML formatter. This can be accomplished by subclassing Rouge::Formatters::HTML and overriding specific methods:

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: false will print a trace of the lex on stdout.

  • parent: '' allows you to specify which language the template is inside.

CSS 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 2.0.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

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 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.

Developing Lexers

NOTE: Please don't submit lexers that are copy-pasted from other files. These submission will be rejected and we don't want you to waste your time.

We want to make it as easy as we can for anyone to contribute a lexer to Rouge. To help get you started, we have a shiny new guide on lexer development in the documentation. The best place is to start there.

If you get stuck and need help, submit a pull request with what you have and make it clear in your submission that the lexer isn't finished yet. We'll do our best to answer any questions you have and sometimes the best way to do that is with actual code.

Testing Rouge

Once you've cloned the repository from GitHub, you can test the core of Rouge simply by running rake (no bundle exec required). You can also run a single test file by setting the TEST environment variable to the path of the desired test. For example, to test just the ruby lexer (located at path spec/lexers/ruby_spec.rb) simply run the following:

TEST=spec/lexers/ruby_spec.rb rake

To test a lexer visually, run rackup from the top-level working directory and you should have a web server running and ready to go. Visit http://localhost:9292 to see the full list of Rouge's lexers.

Once you've selected a particular lexer, you can add ?debug=1 to your URL string to see a lot of helpful debugging info printed on stdout.

Versioning

Rouge uses Semantic Versioning 2.0.0.

Maintainers

Rouge is largely the result of the hard work of unpaid volunteers. It was originally developed by Jeanine Adkisson (@jneen) and is currently maintained by Jeanine Adkisson, Drew Blessing (@dblessing), Goro Fuji (@gfx) and Tan Le (@tancnle).

License

Rouge is released under the MIT license. Please see the LICENSE file for more information.