import rox
from rox import g, TRUE, FALSE
from EditWindow import Minibuffer

last = ""

class Process(Minibuffer):
	"A minibuffer used to process using python expressions."

	def setup(self, window):
		self.window = window
		self.buffer = window.buffer
		self.window.set_mini_label('Process:')

		window.mini_entry.set_text(last)
	
	info = 'Enter a python expression and press Return to process all selected '	\
		'lines (or the current line if nothing is selected). Press Escape to '	\
		'close the minibuffer.\n\n'						\
		'line is the current text on the line\n'				\
		'x is the numerical value of the line, or None if it\'s not a number\n'	\
		'n is the number of the line within the selection (1, 2, ...)\n'	\
		'\nExamples:\n'								\
		'line.upper()	converts to upper case\n'					\
		'"%d) %s" % (n, line)   numbers the lines\n'				\
		'x + 1			 increases the value of each line by 1'
	
	def activate(self):
		command = self.window.mini_entry.get_text()
		buffer = self.buffer
		global last
		last = command

		start, end = self.window.get_selection_range()
		if start.compare(end) == 0:
			start.set_line_offset(0)
			end = start.copy()
			end.forward_to_line_end()
		else:
			if start.compare(end) > 0:
				start, end = end, start

		line_start = start.copy()

		replacements = []
		locals = {'n': 0}
		while line_start.compare(end) <= 0:
			line_end = line_start.copy()
			line_end.forward_to_line_end()
			if line_end.compare(end) >= 0:
				line_end = end
			line = buffer.get_text(line_start, line_end, FALSE)
			locals['line'] = line
			try:
				try:
					locals['x'] = long(line)
				except:
					locals['x'] = float(line)
			except:
				locals['x'] = None
			locals['n'] += 1
			try:
				new = str(eval(command, locals))
			except:
				rox.report_exception()
				return
			replacements.append(new)
			if not line_start.forward_line():
				break
		buffer.delete(start, end)
		buffer.insert_at_cursor('\n'.join(replacements), -1)

		self.window.set_minibuffer(None)
