Skip to content

Instantly share code, notes, and snippets.

@koichiro
Created April 22, 2012 07:13
Show Gist options
  • Save koichiro/2462497 to your computer and use it in GitHub Desktop.
Save koichiro/2462497 to your computer and use it in GitHub Desktop.
# Source code embedded plugin for tDiary.
# Original Copyright (C) 2005 bashi <http://www.cc.ariake-nct.ac.jp/~bashi/d/?date=20051010#p01>
# Modified Copyright (C) 2007,2008 Koichiro Ohba <koichiro@meadowy.org>
# License under GPL2.
require 'langscan'
module LangScan
def self.choose_by_abbrev(hint)
::LangScan::LangScanRegistry.each_value {|scanner|
return scanner if hint.downcase == scanner.abbrev
}
::LangScan::Text
end
end
Highlight_type = [
:fundef, :funcall, :classdef, :moduledef, :comment, :string,
]
add_header_proc do
%Q[<link rel="stylesheet" href="#{theme_url}/codelist.css" type="text/css" media="all">\n]
end
def codelist(file)
scanner = LangScan.choose(file)
scanner = LangScan::Text unless scanner
code(File.open(file).readlines.join, scanner)
end
def line_number(content)
r = "<pre class='line_numbers'>\n"
n = 1
content.each_line do |line|
r += %[<span id='LID#{n}'>#{n}</span>\n]
n += 1
end
r += '</pre>'
end
def line_number_ref(code)
r = ""
n = 1
code.each_line do |line|
r += "<span class='line' id='L#{n}'>" + line + '</span>'
n += 1
end
r
end
def highlighting( content, scanner )
contents = []
scanner.scan(content) {|f|
text = if Highlight_type.include?(f.type)
"<span class='#{f.type}'>#{CGI.escapeHTML(f.text)}</span>"
else
CGI.escapeHTML(f.text)
end
f.text = text
contents.push(f)
}
contents
end
def code(content, scanner = ::LangScan::Text)
scanner = LangScan.choose_by_abbrev(scanner) if scanner.kind_of? String
contents = highlighting( content, scanner )
contents.sort! {|a, b| a.byteno <=> b.byteno }
r = <<-EOS
<div class="codelist">
<table cellpadding='0' cellspacing='0'>
<tr>
<td>
EOS
r += line_number(content)
r += <<EOS
</td>
<td width="100%"><pre class="code_data">
EOS
code = ""
contents.each {|f|
code << f.text
}
code.chomp!
r += line_number_ref(code)
r.chomp!
r += <<EOS
</pre></td>
</tr>
</table>
</div>
EOS
return r
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment