Sha256: b72523211975852ac5b24734c06f22e49454825d6666faa49a0a3603e81a054c

Contents?: true

Size: 1.35 KB

Versions: 22

Compression:

Stored size: 1.35 KB

Contents

require "rouge"
require "htmlbeautifier"

module Lookbook
  module CodeFormatter
    class << self
      def highlight(source, language, opts = {})
        source&.strip! unless opts[:strip] == false
        source&.gsub!("&gt;", ">")&.gsub!("&lt;", "<")
        language ||= "ruby"
        formatter = Formatter.new(opts)
        lexer = Rouge::Lexer.find(language.to_s) || Rouge::Lexer.find("plaintext")
        formatter.format(lexer.lex(source)).html_safe
      end

      def beautify(source, language = "html")
        source = source.strip
        result = language.downcase == "html" ? HtmlBeautifier.beautify(source) : source
        result.strip.html_safe
      end
    end
  end

  class Formatter < Rouge::Formatters::HTML
    def initialize(opts = {})
      @opts = opts
      @highlight_lines = opts[:highlight_lines].to_a || []
      @start_line = opts[:start_line] || 0
    end

    def stream(tokens, &block)
      token_lines(tokens).each_with_index do |line_tokens, i|
        yield "<div class='line #{"highlighted-line" if @highlight_lines.include?(i + 1)}'>"
        yield "<span class='line-number'>#{@start_line + i}</span>" if @opts[:line_numbers]
        yield "<span class='line-content'>"
        line_tokens.each do |token, value|
          yield span(token, value)
        end
        yield "</span>"
        yield "</div>"
      end
    end
  end
end

Version data entries

22 entries across 22 versions & 1 rubygems

Version Path
lookbook-0.9.8 lib/lookbook/code_formatter.rb
lookbook-0.9.7 lib/lookbook/code_formatter.rb
lookbook-0.9.6 lib/lookbook/code_formatter.rb
lookbook-0.9.5 lib/lookbook/code_formatter.rb
lookbook-0.9.4 lib/lookbook/code_formatter.rb
lookbook-0.9.3 lib/lookbook/code_formatter.rb
lookbook-0.9.2 lib/lookbook/code_formatter.rb
lookbook-0.9.1 lib/lookbook/code_formatter.rb
lookbook-0.9.0 lib/lookbook/code_formatter.rb
lookbook-0.8.3 lib/lookbook/code_formatter.rb
lookbook-0.8.2 lib/lookbook/code_formatter.rb
lookbook-0.8.1 lib/lookbook/code_formatter.rb
lookbook-0.8.0 lib/lookbook/code_formatter.rb
lookbook-0.8.0.beta.0 lib/lookbook/code_formatter.rb
lookbook-0.7.4 lib/lookbook/code_formatter.rb
lookbook-0.7.3 lib/lookbook/code_formatter.rb
lookbook-0.7.2 lib/lookbook/code_formatter.rb
lookbook-0.7.2.beta.5 lib/lookbook/code_formatter.rb
lookbook-0.7.2.beta.4 lib/lookbook/code_formatter.rb
lookbook-0.7.2.beta.3 lib/lookbook/code_formatter.rb