module SM
class Line
INFINITY = 9999
BLANK = :BLANK
HEADING = :HEADING
LIST = :LIST
RULE = :RULE
PARAGRAPH = :PARAGRAPH
VERBATIM = :VERBATIM
attr_accessor :type
attr_accessor :level
attr_accessor :text
attr_accessor :param
attr_accessor :flag
attr_accessor :leading_spaces
attr_accessor :deleted
def initialize(text)
@text = text.dup
@deleted = false
1 while @text.gsub!(/\t+/) { ' ' * (8*$&.length - $`.length % 8)} && $~
@text.sub!(/\s+$/, '')
if @text.length > 0
@text =~ /^(\s*)/
@leading_spaces = $1.length
else
@leading_spaces = INFINITY
end
end
def isBlank?
@text.length.zero?
end
def stamp(type, level, param="", flag=nil)
@type, @level, @param, @flag = type, level, param, flag
end
def strip_leading(size)
if @text.size > size
@text[0,size] = ""
else
@text = ""
end
end
def to_s
"#@type#@level: #@text"
end
end
class Lines
include Enumerable
attr_reader :lines
def initialize(lines)
@lines = lines
rewind
end
def empty?
@lines.size.zero?
end
def each
@lines.each do |line|
yield line unless line.deleted
end
end
def rewind
@nextline = 0
end
def next
begin
res = @lines[@nextline]
@nextline += 1 if @nextline < @lines.size
end while res and res.deleted and @nextline < @lines.size
res
end
def unget
@nextline -= 1
end
def delete(a_line)
a_line.deleted = true
end
def normalize
margin = @lines.collect{|l| l.leading_spaces}.min
margin = 0 if margin == Line::INFINITY
@lines.each {|line| line.strip_leading(margin) } if margin > 0
end
def as_text
@lines.map {|l| l.text}.join("\n")
end
def line_types
@lines.map {|l| l.type }
end
end
end