class Samovar::Output::LineWrapping

def wrap(line)

def wrap(line)
	wrapping_offset = nil
	offset = 0
	buffer = String.new
	lines = []
	prefix = nil
	
	line.scan(ESCAPE_SEQUENCE) do |text, escape_sequence|
		width = printable_width(text)
		next_offset = offset + printable_width
		
		if next_offset > @wrapping_width
			if wrapping_offset
				text_wrap_offset = @wrapping_width - offset
				
				# This text flows past the end of the line and we have a valid wrapping offset. We need to wrap this text.
				if best_split_index = text.rindex(/\s/, text_wrap_offset) and best_split_index >= @minimum_width
					# We have enough space to wrap.
					buffer << text[0...best_split_index]
					lines << buffer
					buffer = String.new()
				else
					# In this case we can't really wrap on the current line. We fall back to letting the terminal wrap.
					return line
				end
			else
				# We don't have a specific wrapping offset, and the text flows longer than the wrapping width. We can't do anything - let the terminal wrap.
				return line
			end
		else
			buffer << text << escape_sequence
		end
		
		offset = next_offset
		
		if wrapping_offset.nil? and offset < @wrapping_width and escape_sequence == MARKER
			wrapping_offset = offset
		end
	end
end