[pygtk] Find string within TextBuffer

Lupine thelupine.mailinglists at gmail.com
Fri Mar 13 21:46:15 WST 2009


On Fri, 2009-03-13 at 08:30 -0400, Steve McClure wrote:

> >> def on_find_dialog_ok_button_clicked(self, action):
> >> """This will highlight each found entry"""
> >> findentry = self.widgets.get_widget('find_entry').get_text()
> >> txtbuffer =  
> >> self.widgets.get_widget('pref_hosts_txtview').get_buffer()
> >> startiter = txtbuffer.get_start_iter()
> >> enditer = txtbuffer.get_end_iter()
> >> bufferlines = txtbuffer.get_text(startiter, enditer)
> >
> > I think the iterator points to characters in a string, not strings in
> > a list.  If so you would just need something like:
> >
> > bufferstr = txtbuffer.get_text(startiter, enditer)
> > if findentry in bufferstr:
> >    print 'found entry:'
> 
> Or how about:
> 
> start = txtbuffer.get_start_iter()
> first, last = start.forward_search(findentry)
> if first:
>      print 'found entry'
> 

Getting closer.  forward_search requires at least 2 arguments, so I had
to change it to this:

first, last = start.forward_search(findentry, gtk.TEXT_SEARCH_TEXT_ONLY)

...this returned the tuple of iterators, so I'm now able to place that
into the get_line method, and finally have it return (at least) the line
number of the found string.  The complete code looks like this:

findentry = self.widgets.get_widget('find_entry').get_text()
txtbuffer = self.widgets.get_widget('pref_hosts_txtview').get_buffer()
start = txtbuffer.get_start_iter()
first, last = start.forward_search(findentry, gtk.TEXT_SEARCH_TEXT_ONLY)
line_number = str(first.get_line())
if first:
  print 'found entry:' + line_number

So, finally, now that I have it actually finding the line number of the
searched for string, I should be able to figure out how to get the
gtk.TextView to scroll to that line number, and highlight the found
text.

Thanks so much for the help!
-Lup




More information about the pygtk mailing list