added start:LINENO/end:LINENO to include_code #478

Closed
wants to merge 3 commits into
from
@@ -36,6 +36,14 @@ def initialize(tag_name, markup, tokens)
@filetype = $1
markup = markup.strip.sub(/lang:\w+/i,'')
end
+ if markup.strip =~ /start:(\d+)/
+ @start_line = $1.to_i || 0
+ markup = markup.strip.sub(/start:(\d+)/, '')
+ end
+ if markup.strip =~ /end:(\d+)/
+ @end_line = $1.to_i || 0
+ markup = markup.strip.sub(/end:(\d+)/, '')
+ end
if markup.strip =~ /(.*)?(\s+|^)(\/*\S+)/i
@title = $1 || nil
@file = $3
@@ -57,12 +65,20 @@ def render(context)
end
Dir.chdir(code_path) do
- code = file.read
+ lines = file.readlines
+
+ start_line = @start_line || 1
+ end_line = @end_line && @end_line >= start_line ? @end_line : lines.size
+ code = lines[(start_line-1)..(end_line-1)].join("")
+
+ options = {:linenostart => start_line}
+
@filetype = file.extname.sub('.','') if @filetype.nil?
- title = @title ? "#{@title} (#{file.basename})" : file.basename
+ start_end_title = ", line #{start_line} to #{end_line}" if @start_line || @end_line
+ title = @title ? "#{@title} (#{file.basename}#{start_end_title})" : file.basename
url = "/#{code_dir}/#{@file}"
source = "<figure class='code'><figcaption><span>#{title}</span> <a href='#{url}'>download</a></figcaption>\n"
- source += " #{highlight(code, @filetype)}</figure>"
+ source += " #{highlight(code, @filetype, options)}</figure>"
safe_wrap(source)
end
end
@@ -6,13 +6,13 @@
FileUtils.mkdir_p(PYGMENTS_CACHE_DIR)
module HighlightCode
- def highlight(str, lang)
+ def highlight(str, lang, options={})
lang = 'ruby' if lang == 'ru'
lang = 'objc' if lang == 'm'
lang = 'perl' if lang == 'pl'
lang = 'yaml' if lang == 'yml'
str = pygments(str, lang).match(/<pre>(.+)<\/pre>/m)[1].to_s.gsub(/ *$/, '') #strip out divs <div class="highlight">
- tableize_code(str, lang)
+ tableize_code(str, lang, options)
end
def pygments(code, lang)
@@ -29,11 +29,12 @@ def pygments(code, lang)
end
highlighted_code
end
- def tableize_code (str, lang = '')
+ def tableize_code (str, lang = '', options={})
+ options = {:linenostart => 1}.merge(options)
table = '<div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers">'
code = ''
str.lines.each_with_index do |line,index|
- table += "<span class='line-number'>#{index+1}</span>\n"
+ table += "<span class='line-number'>#{index+options[:linenostart]}</span>\n"
code += "<span class='line'>#{line}</span>"
end
table += "</pre></td><td class='code'><pre><code class='#{lang}'>#{code}</code></pre></td></tr></table></div>"