Take the 2-minute tour ×
Ask Ubuntu is a question and answer site for Ubuntu users and developers. It's 100% free, no registration required.

As in topic I have TextView() and TextBuffer() added to it, I also have Tags created so when I select text and click button it will make text BOLD or something. Up to this point all works well, now I need to be able to go through all text in TextView and find what Tag is applied and where, I need this so I can format text by adding stuff before and after tagged text.

here is part of the code:

    self.textview = Gtk.TextView()
    self.buffer = self.textview.get_buffer()
    self.scrolledwindow.add(self.textview)
    self.textview.show()

    self.tag_bold = self.buffer.create_tag("bold", weight=Pango.Weight.BOLD)

It would be best if I could get output like, "test text" is "bold".

Thanks for any help.

share|improve this question

1 Answer 1

up vote 2 down vote accepted

EDIT Here's the correct function to use: Gtk.TextIter.forward_to_tag_toggle()

here's an example that generates a list of all bolded words:

    start = self.textbuffer.get_start_iter()
    bolded=[]
    while start.forward_to_tag_toggle(self.tag_bold):
        begin=start.copy()
        start.forward_to_tag_toggle(self.tag_bold)
        bolded.append(self.textbuffer.get_text(begin,start,False))
    print bolded

While you are using pygi (not pyGTK; note the uppercase Gtk in your functions), many of the pyGTK functions are still valid though may require some tweaking. You can get documentation here for gtk.textiter in pygtk.

OLD ANSWER: Not sure if this is the optimal way, but I found that you could iterate over each character (maybe each word if you want) and test whether the character has the tag you want: Here's a simple function to do that:

    start = self.textbuffer.get_start_iter()
    plus = self.textbuffer.get_start_iter()
    bolded=''
    while plus.forward_char():
        if start.has_tag(self.tag_bold):
            bolded=bolded+(start.get_text(plus))
        start.forward_char()
    print bolded

you can also use the Gtk.TextIter get_tags() method to get what tags a character has.

Finally, what may work better is to store the bounds in some list when you apply the tags to begin with.

share|improve this answer
    
Thank you @Ian B. I have adopted your code to my program and it works for me. –  Majster-pl Mar 28 '13 at 19:00

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.