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