Skip to content

Commit e0fb058

Browse files
committed
Teach SyntaxHighlightFilter about a :highlight context attribute
This allows any code blocks without a language specified (indented blocks or fences with no language) to be highlighted with a default. For extra fun, add an additional class to the "highlight" div specifying the highlighted language.
1 parent a731d82 commit e0fb058

File tree

2 files changed

+30
-3
lines changed

2 files changed

+30
-3
lines changed

lib/html/pipeline/syntax_highlight_filter.rb

Lines changed: 8 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -11,14 +11,19 @@ class Pipeline
1111
class SyntaxHighlightFilter < Filter
1212
def call
1313
doc.search('pre').each do |node|
14-
next unless lang = node['lang']
14+
default = context[:highlight] && context[:highlight].to_s
15+
next unless lang = node['lang'] || default
1516
next unless lexer = Pygments::Lexer[lang]
1617
text = node.inner_text
1718

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

21-
node.replace(html)
22+
node = node.replace(html).first
23+
klass = node["class"]
24+
klass = [klass, "highlight-#{lang}"].compact.join " "
25+
26+
node["class"] = klass
2227
end
2328
doc
2429
end
@@ -30,4 +35,4 @@ def highlight_with_timeout_handling(lexer, text)
3035
end
3136
end
3237
end
33-
end
38+
end
Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
require "test_helper"
2+
3+
SyntaxHighlightFilter = HTML::Pipeline::SyntaxHighlightFilter
4+
5+
class HTML::Pipeline::SyntaxHighlightFilterTest < Test::Unit::TestCase
6+
def test_highlight_default
7+
filter = SyntaxHighlightFilter.new \
8+
"<pre>hello</pre>", :highlight => "coffeescript"
9+
10+
doc = filter.call
11+
assert_not_empty doc.css ".highlight-coffeescript"
12+
end
13+
14+
def test_highlight_default_will_not_override
15+
filter = SyntaxHighlightFilter.new \
16+
"<pre lang='c'>hello</pre>", :highlight => "coffeescript"
17+
18+
doc = filter.call
19+
assert_empty doc.css ".highlight-coffeescript"
20+
assert_not_empty doc.css ".highlight-c"
21+
end
22+
end

0 commit comments

Comments
 (0)