Monday, May 25, 2009

Gedit API - how to replace selected text

Today's post is rather short. It is also a bit incomplete, as I don't understand one of the functions I use (even though the others seem very simple and obvious).


>>> v = window.get_active_view()
>>> b = v.get_buffer()
>>> b.insert_at_cursor("This is some sample text.\nHello, world!\n")


This is basic code to populate the editing buffer with some text to experiment on.


>>> sel0 = b.get_iter_at_offset(8)
>>> sel1 = b.get_iter_at_offset(12)
>>> b.select_range(sel0, sel1)


Selects the word "some" on the first line.


>>> b.delete_selection(0, 1)
>>> b.insert_at_cursor("emos")


The first line deletes the selected text. I don't know the meaning of the parameters - I tried several combinations and they delete the entire selection or seem to have no effect. So I just use (0, 1) as parameters without understanding.

The insert_at_cursor() call is already known and it inserts the string provided as parameter... at the current cursor position, obviously. Which is right where the selected text used to be, because we didn't move it.

No comments: