Skip to content

Instantly share code, notes, and snippets.

@nmanzi
Created August 17, 2009 18:30
Show Gist options
  • Save nmanzi/169292 to your computer and use it in GitHub Desktop.
Save nmanzi/169292 to your computer and use it in GitHub Desktop.
# Highlights code contained within the post according to a given language.
def highlight_code string
post_text = string.gsub(/\r\n/, "\n")
# From Markdown.pl by John Gruber
regex = /(?:\n\n|\A)((?:(?:[ ]{4} | \t).*\n+)+)((?=^[ ]{0,4}\S)|\Z)/ix
matches = post_text.scan(regex)
for match in matches
c = match[0].gsub(/^ /, '') # Removes the 4 leading spaces from Markdown text
lang = "plain_text" # Default Language
lines = c.split("\n") # Splits the lines by newline character
lang_def = lines[0].split(":") # Split the first line by colon to get the language param
if lang_def[0].downcase == 'l' || lang_def[0].downcase == 'lang'
if lang_def[1].strip.length > 0
lang = lang_def[1].strip.downcase
lines = lines[1..-1]
end
end
code_html = code(lines.join("\n"), :lang => lang, :theme => 'sunburst', :line_numbers => true)
linetoggle_html = div_to_function "Toggle Line Numbers", :onclick => "linetoggle()", :class => "linetoggle"
post_text = post_text.gsub(match[0], "\n" + linetoggle_html + "\n" + code_html + "\n\n")
end
return post_text
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment