This repository has been archived by the owner on Feb 28, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathattach_pre.rb
65 lines (56 loc) · 1.97 KB
/
attach_pre.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
## Usage: attach_pre('file.html', 'page=foo&linenum=1&inline=true')
def attach_pre(filename, option_str='page=nil&linenum=nil&inline=false')
# parse option string
#$stderr.puts "*** debug: option_str=#{option_str.inspect}"
page = @page
linenum = nil
inline = false
if option_str
options = {}
option_str.split(/\&/).each do |option|
if option =~ /\A(\w+)=(.*)/
key = $1; val = $2
case val
when 'true', 'yes' ; val = true
when 'false', 'no' ; val = false
when 'nil', 'null' ; val = nil
when /\A\d+\z/ ; val = val.to_i
end
else
key = option; val = true
end
options[key] = val
end
#$stderr.puts "*** debug: options=#{options.inspect}"
v = options['page']; page = v if v.is_a?(String)
v = options['linenum']; linenum = v if v.is_a?(Integer) || v == nil
v = options['inline']; inline = v if v == true || v == false
end
#if filename =~ /\.(txt|rd|rb|c|pl|py|sh|java|html|htm|css|xml|xsl|sql|yaml|rhtml|xhtml|php|eruby)\z/i
# read file content
filepath = "#{@conf.cache_path}/attach/#{escape(page.untaint)}/#{escape(filename.untaint)}"
content = File.read(filepath)
if content.respond_to?(:force_encoding)
content.force_encoding(Encoding::ASCII_8BIT)
end
# add line number, expand tab character, and escape HTML character
s = ''
n = linenum.is_a?(Integer) ? linenum - 1 : 0
content.each_line do |line|
s << "%03d| " % (n += 1) if linenum # add line number
s << line.gsub(/([^\t]{8})|([^\t]*)\t/n) { [$+].pack("A8") } # expand tab
end
s = escapeHTML(s.to_utf8)
# inline expantion
if inline
# '{{*...*}}' => '<strong>...</strong>'
s.gsub!(/\{\{\*/, '<strong>')
s.gsub!(/\*\}\}/, '</strong>')
# '{{/.../}}' => '<em>...</em>'
s.gsub!(/\{\{\//, '<em>')
s.gsub!(/\/\}\}/, '</em>')
end
# return value
"<pre>#{s}</pre>"
#end
end