Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Teach SyntaxHighlightFilter about default highlights #81

Merged
merged 2 commits into from
Aug 30, 2013
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 8 additions & 3 deletions lib/html/pipeline/syntax_highlight_filter.rb
Original file line number Diff line number Diff line change
Expand Up @@ -11,14 +11,19 @@ class Pipeline
class SyntaxHighlightFilter < Filter
def call
doc.search('pre').each do |node|
next unless lang = node['lang']
default = context[:highlight] && context[:highlight].to_s
next unless lang = node['lang'] || default
next unless lexer = Pygments::Lexer[lang]
text = node.inner_text

html = highlight_with_timeout_handling(lexer, text)
next if html.nil?

node.replace(html)
node = node.replace(html).first
klass = node["class"]
klass = [klass, "highlight-#{lang}"].compact.join " "

node["class"] = klass
end
doc
end
Expand All @@ -30,4 +35,4 @@ def highlight_with_timeout_handling(lexer, text)
end
end
end
end
end
22 changes: 22 additions & 0 deletions test/html/pipeline/syntax_highlight_filter_test.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
require "test_helper"

SyntaxHighlightFilter = HTML::Pipeline::SyntaxHighlightFilter

class HTML::Pipeline::SyntaxHighlightFilterTest < Test::Unit::TestCase
def test_highlight_default
filter = SyntaxHighlightFilter.new \
"<pre>hello</pre>", :highlight => "coffeescript"

doc = filter.call
assert !doc.css(".highlight-coffeescript").empty?
end

def test_highlight_default_will_not_override
filter = SyntaxHighlightFilter.new \
"<pre lang='c'>hello</pre>", :highlight => "coffeescript"

doc = filter.call
assert doc.css(".highlight-coffeescript").empty?
assert !doc.css(".highlight-c").empty?
end
end