lib/review/htmlutils.rb in review-2.1.0 vs lib/review/htmlutils.rb in review-2.2.0
- old
+ new
@@ -26,11 +26,11 @@
alias_method :escape, :escape_html
alias_method :h, :escape_html
def unescape_html(str)
- # FIXME better code
+ # FIXME: better code
str.gsub('"', '"').gsub('>', '>').gsub('<', '<').gsub('&', '&')
end
alias_method :unescape, :unescape_html
@@ -42,31 +42,45 @@
str.gsub('-', '-')
end
def highlight?
@book.config["highlight"] &&
- @book.config["highlight"]["html"] == "pygments"
+ @book.config["highlight"]["html"]
end
def highlight(ops)
if @book.config["pygments"].present?
raise ReVIEW::ConfigError, "'pygments:' in config.yml is obsoleted."
end
+ return ops[:body].to_s if !highlight?
+ if @book.config["highlight"]["html"] == "pygments"
+ highlight_pygments(ops)
+ elsif @book.config["highlight"]["html"] == "rouge"
+ highlight_rouge(ops)
+ else
+ raise ReVIEW::ConfigError, "unknown highlight method #{@book.config["highlight"]["html"]} in config.yml."
+ end
+ end
+
+ def highlight_pygments(ops)
body = ops[:body] || ''
if @book.config["highlight"] && @book.config["highlight"]["lang"]
lexer = @book.config["highlight"]["lang"] # default setting
else
lexer = 'text'
end
lexer = ops[:lexer] if ops[:lexer].present?
format = ops[:format] || ''
options = {:nowrap => true, :noclasses => true}
+ if ops[:linenum]
+ options[:nowrap] = false
+ options[:linenos] = 'inline'
+ end
if ops[:options] && ops[:options].kind_of?(Hash)
options.merge!(ops[:options])
end
- return body if !highlight?
begin
require 'pygments'
begin
Pygments.highlight(unescape_html(body),
@@ -75,11 +89,43 @@
:lexer => lexer)
rescue MentosError
body
end
rescue LoadError
- body
+ body
end
+ end
+
+ def highlight_rouge(ops)
+ body = ops[:body] || ''
+ if ops[:lexer].present?
+ lexer = ops[:lexer]
+ elsif @book.config["highlight"] && @book.config["highlight"]["lang"]
+ lexer = @book.config["highlight"]["lang"] # default setting
+ else
+ lexer = 'text'
+ end
+ format = ops[:format] || ''
+
+ first_line_num = 1 ## default
+ if ops[:options] && ops[:options][:linenostart]
+ first_line_num = ops[:options][:linenostart]
+ end
+
+ require 'rouge'
+ lexer = Rouge::Lexer.find(lexer)
+ raise "unknown lexer #{lexer}" unless lexer
+
+ formatter = Rouge::Formatters::HTML.new(:css_class => 'highlight')
+ if ops[:linenum]
+ formatter = Rouge::Formatters::HTMLTable.new(formatter,
+ :table_class => 'highlight rouge-table',
+ :start_line => first_line_num)
+ end
+ raise "unknown formatter #{formatter}" unless formatter
+
+ text = unescape_html(body)
+ formatter.format(lexer.lex(text))
end
def normalize_id(id)
if id =~ /\A[a-z][a-z0-9_.-]*\Z/i
return id