module REXML
	# Represents text in an XML document
	class Text < Child
		include Comparable

		# string is String content, raw is a boolean
		attr_accessor :string, :raw
		PATTERN = /\A([^<]*)/m

		# Constructor
		# @param arg if a String, the content is set to the String.  If a Text,
		# the object is shallowly cloned.  If a Source, the source is parsed
		# for text content up to the next element.  If a parent, the parent of
		# this object is set to the argument.
		# @param whitespace (boolean, optional) if true, whitespace is respected
		# @param parent (Parent, optional) if given, the parent of this object
		# will be set to the argument
		def initialize arg, whitespace=false, parent=nil, pattern=PATTERN
			@raw = false
			if arg.kind_of? Source
				super( parent )
				@string = arg.match(pattern, true)[1]
				@string.squeeze!(" \n\t") unless whitespace
			elsif arg.kind_of? String
				super()
				@string = arg
			elsif arg.kind_of? Text
				super()
				@string = arg.string
				@raw = arg.raw
			elsif arg.kind_of? Parent
				super( arg )
			end
		end

		def clone
			return Text.new(self)
		end

		# @param other a String or a Text
		# @return true if the content of this object matches the supplied 
		# argument's content
		def <=>( other )
			@string <=> other.to_s
		end

		def to_s
		  @string
		end

		def write( writer, indent=0 ) 
			indent( writer, indent )
			if raw
				writer.printf @string
			else
				write_with_substitution( writer, @string )
			end
		end

		def Text.parse_stream source, listener
			listener.text source.match(PATTERN, true)[0]
		end
	end
 end
