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

		# string is String content, raw is a boolean
		attr_reader :string
		attr_accessor :raw
		PATTERN = /\A([^<]*)/um
		ILLEGAL = /<|&(?!#?[\w-]+;)/u

		# 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, respect_whitespace=false, parent=nil, pattern=PATTERN, raw=false)
			@raw = raw
			if parent
				if parent == true
					@raw = true
				elsif parent.kind_of? Parent
					super( parent )
					@raw = parent.raw
				end
			end
			if arg.kind_of? Source
				md = arg.match(pattern, true)
				raise "no text to add" if md[0].length == 0
				@string = md[1]
				@string.squeeze!(" \n\t") unless respect_whitespace
				@string = read_with_substitution(@string, ILLEGAL) unless @raw
			elsif arg.kind_of? String
				super()
				@string = arg.clone
				@string.squeeze!(" \n\t") unless respect_whitespace
				@string = read_with_substitution(@string) unless @raw
			elsif arg.kind_of? Text
				super()
				@string = arg.string
				@raw = arg.raw
			elsif arg.kind_of? Parent
				super( arg )
			elsif [true,false].include? arg
				@raw = arg
			end
		end

		def clone
			return Text.new(self)
		end

		# @param other a String or a Text
		# @return the result of (to_s <=> arg.to_s)
		def <=>( other )
			@string <=> other.to_s
		end

		def to_s
		  @string
		end

		def write( writer, indent=-1 ) 
			indent( writer, indent )
			if @raw
				writer << @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
