Update for new loading code.
[rox-edit.git] / process.py
blobf34d29119f65eca10e40ff55176f7089c6e0a8f4
1 import rox
2 from rox import g, TRUE, FALSE
3 from EditWindow import Minibuffer
5 class Process(Minibuffer):
6 "A minibuffer used to process using python expressions."
8 def setup(self, window):
9 self.window = window
10 self.buffer = window.buffer
11 self.window.set_mini_label('Process:')
13 info = 'Enter a python expression and press Return to process all selected ' \
14 'lines (or the current line if nothing is selected). Press Escape to ' \
15 'close the minibuffer.\n\n' \
16 'line is the current text on the line\n' \
17 'x is the numerical value of the line, or None if it\'s not a number\n' \
18 'n is the number of the line within the selection (1, 2, ...)\n' \
19 '\nExamples:\n' \
20 'line.upper() converts to upper case\n' \
21 '"%d) %s" % (n, line) numbers the lines\n' \
22 'x + 1 increases the value of each line by 1'
24 def activate(self):
25 command = self.window.mini_entry.get_text()
26 buffer = self.buffer
28 start, end = self.window.get_selection_range()
29 if start.compare(end) == 0:
30 start.set_line_offset(0)
31 end = start.copy()
32 end.forward_to_line_end()
33 else:
34 if start.compare(end) > 0:
35 start, end = end, start
37 line_start = start.copy()
39 replacements = []
40 locals = {'n': 0}
41 while line_start.compare(end) <= 0:
42 line_end = line_start.copy()
43 line_end.forward_to_line_end()
44 if line_end.compare(end) >= 0:
45 line_end = end
46 line = buffer.get_text(line_start, line_end, FALSE)
47 locals['line'] = line
48 try:
49 try:
50 locals['x'] = long(line)
51 except:
52 locals['x'] = float(line)
53 except:
54 locals['x'] = None
55 locals['n'] += 1
56 try:
57 new = str(eval(command, locals))
58 except:
59 rox.report_exception()
60 return
61 replacements.append(new)
62 if not line_start.forward_line():
63 break
64 buffer.delete(start, end)
65 buffer.insert_at_cursor('\n'.join(replacements), -1)
67 self.window.set_minibuffer(None)