Update for new ROX-Lib.
[rox-edit.git] / search.py
blob67530b2f05014fc1ca804bad791b51331833216e
1 from rox import g
3 class Search:
4 "A minibuffer used to search for text."
6 def setup(self, window):
7 self.window = window
8 buffer = window.buffer
9 cursor = buffer.get_iter_at_mark(window.insert_mark)
10 buffer.move_mark_by_name('search_base', cursor)
11 self.dir = 1
12 self.set_label()
14 def set_label(self):
15 if self.dir == 1:
16 self.window.set_mini_label('Forward search:')
17 else:
18 self.window.set_mini_label('Backward search:')
20 def set_dir(self, dir):
21 assert dir == 1 or dir == -1
23 buffer = self.window.buffer
24 cursor = buffer.get_iter_at_mark(self.window.insert_mark)
25 buffer.move_mark_by_name('search_base', cursor)
27 if dir == self.dir:
28 if dir == 1:
29 cursor.forward_char()
30 else:
31 cursor.backward_char()
32 if self.search(cursor):
33 buffer.move_mark_by_name('search_base', cursor)
34 else:
35 g.gdk.beep()
36 else:
37 self.dir = dir
38 self.set_label()
39 self.changed()
41 def key_press(self, kev):
42 k = kev.keyval
43 if k == g.keysyms.Return:
44 self.window.set_minibuffer(None)
45 elif k == g.keysyms.Up:
46 self.set_dir(-1)
47 elif k == g.keysyms.Down:
48 self.set_dir(1)
49 else:
50 return 0
51 return 1
53 def search(self, start):
54 "Search forwards or backwards for the pattern. Matches at 'start'"
55 "are allowed in both directions. Returns (match_start, match_end) if"
56 "found."
57 iter = start.copy()
58 pattern = self.window.mini_entry.get_text()
59 if not pattern:
60 return (iter, iter)
61 if self.dir == 1:
62 found = iter.forward_search(pattern, 0, None)
63 else:
64 iter.forward_chars(len(pattern))
65 found = iter.backward_search(pattern, 0, None)
66 return found
68 def changed(self):
69 buffer = self.window.buffer
70 pos = buffer.get_iter_at_mark(self.window.search_base)
72 found = self.search(pos)
73 if found:
74 buffer.move_mark_by_name('insert', found[0])
75 buffer.move_mark_by_name('selection_bound', found[1])
76 self.window.text.scroll_to_iter(found[0], 0.05, g.FALSE)
77 else:
78 g.gdk.beep()