Skip to content

Instantly share code, notes, and snippets.

@pdog18
Forked from zpao/code_highlight_lines.rb
Created January 16, 2020 15:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pdog18/b8edf2670229b5723a63860c865a42e8 to your computer and use it in GitHub Desktop.
Save pdog18/b8edf2670229b5723a63860c865a42e8 to your computer and use it in GitHub Desktop.
Highlight specific lines of code with Markdown + Jekyll + Redcarpet
# Replace Jekyll's handling of the Redcarpet code_block (which already adds
# support for highlighting, but needs support for the very non-standard
# "code fences with line highlights" extension).
# Since this is currently depending on Redcarpet to cooperate, we are going to
# be naive, and only allow line highlighting when a language is specified. If
# you don't want any syntax highlighting but want to highlight lines, then you
# need to specify text as your language (or it will break), like:
# ```text{4}
module Jekyll
module Converters
class Markdown
class RedcarpetParser
module WithPygments
def block_code(code, lang)
require 'pygments'
lang_parts = lang && lang.split('{')
lang = lang_parts && !lang_parts[0].empty? && lang_parts[0] || 'text'
hl_lines = ''
if lang_parts && lang_parts.size >= 2
hl_lines = lang_parts[1].gsub(/[{}]/, '').split(',').map do |ln|
if matches = /(\d+)-(\d+)/.match(ln)
ln = Range.new(matches[1], matches[2]).to_a.join(' ')
end
ln
end.join(' ')
end
output = add_code_tags(
Pygments.highlight(code, :lexer => lang,
:options => { :encoding => 'utf-8', :hl_lines => hl_lines }),
lang
)
end
end
end
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment