Imported File#ftype spec from rubyspecs.
[rbx.git] / lib / rdoc / markup / preprocess.rb
blob760351d38605e1e71b47d78a2ea5b49734617fdd
1 require 'rdoc/markup'
3 ##
4 # Handle common directives that can occur in a block of text:
6 # : include : filename
8 class RDoc::Markup::PreProcess
10   def initialize(input_file_name, include_path)
11     @input_file_name = input_file_name
12     @include_path = include_path
13   end
15   ##
16   # Look for common options in a chunk of text. Options that we don't handle
17   # are passed back to our caller as |directive, param|
19   def handle(text)
20     text.gsub!(/^([ \t#]*):(\w+):\s*(.+)?\n/) do
21       prefix    = $1
22       directive = $2.downcase
23       param     = $3
25       case directive
26       when "include"
27         filename = param.split[0]
28         include_file(filename, prefix)
30       else
31         yield(directive, param)
32       end
33     end
34   end
36   private
38   ##
39   # Include a file, indenting it correctly.
41   def include_file(name, indent)
42     if full_name = find_include_file(name) then
43       content = File.open(full_name) {|f| f.read}
44       # strip leading '#'s, but only if all lines start with them
45       if content =~ /^[^#]/
46         content.gsub(/^/, indent)
47       else
48         content.gsub(/^#?/, indent)
49       end
50     else
51       $stderr.puts "Couldn't find file to include: '#{name}'"
52       ''
53     end
54   end
56   ##
57   # Look for the given file in the directory containing the current file,
58   # and then in each of the directories specified in the RDOC_INCLUDE path
60   def find_include_file(name)
61     to_search = [ File.dirname(@input_file_name) ].concat @include_path
62     to_search.each do |dir|
63       full_name = File.join(dir, name)
64       stat = File.stat(full_name) rescue next
65       return full_name if stat.readable?
66     end
67     nil
68   end
70 end