Sha256: b404f1180c3d73ae9c7cdad662f47065f7f931c6eeebb537e22f8c10ea5a613f

Contents?: true

Size: 1.98 KB

Versions: 1

Compression:

Stored size: 1.98 KB

Contents

module MdInc
  module Commands
    class << self
      def root(path)
        @root = path
      end

      def full_path(path)
        @root ? File.join(@root, path) : path
      end

      def process(content)
        output = process_lines(content.split("\n"))
        output.flatten.join("\n")
      end

      def process_lines(lines)
        lines.map do |line|
          (line[0] == '.') ? instance_eval(line[1..-1]) : line
        end
      end        

      def x(*args)
        []
      end

      def inc(path, recursive=true)
        lines = File.readlines(full_path(path))
        lines.map! &:rstrip
        recursive ? process_lines(lines) : lines
      end

      def code_inc(path, language=nil, re1=nil, re2=nil)
        if re1
          code(language, normalize_indent(between(re1, re2, inc(path))))
        else
          code(language, normalize_indent(inc(path)))
        end
      end

      def code(language, lines)
        if language.nil?
          lines.map {|l| l.rstrip.prepend('    ')}
        else
          ["```#{language}"] + lines + ["```"]          
        end
      end

      def between(re1, re2, lines)
        state = :outside
        output = []
        lines.each do |l|
          if state == :outside && re1 =~ l
            state = :inside
          elsif state == :inside && re2 =~ l
            state = :outside
          else
            output << l if state==:inside
          end
        end
        STDERR.puts "Warning: no output from included file" if output.empty?
        output
      end

      def skip(re, lines)
        output = []
        lines.each do |l|
          output << l unless l =~ re
        end
        output
      end

      def normalize_indent(lines)
        min_indent = min_indent(lines)
        lines.map {|l| l[min_indent..-1]}
      end

      private

      def min_indent(lines)
        indents = lines.map {|l| indent_depth(l)}
        indents.min
      end

      def indent_depth(s)
        /^ */.match(s).end(0)
      end
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
md_inc-0.2.8 lib/md_inc/md_inc_commands.rb