Problem
You want to add auto numbering in front of highlighted text in a GtkTextView as shown below:
Solution
- Get the selection bounds with GtkTextbuffer::get_selection_bounds().
- Move the iter to the start of each line with GtkTextiter::set_line().
- Insert the numbering using GtkTextbuffer::insert().
Sample Code
1 2 3 4 5 6 7 8 9 10 11 12 13 14 16 18 19 20 21 22 23 24 25 26 27 28 29 34 35 36 37 38 39 41 42 43 44 45 47 48 49 50 51 52 53 54 56 57 58 59 60 61 62 63 64 65 66 67 68 | <?php $window = new GtkWindow(); $window->set_size_request(400, 240); $window->connect_simple('destroy', array('Gtk','main_quit')); $window->add($vbox = new GtkVBox()); // display title $title = new GtkLabel("Add numbering in front of highlighted text\n"); $title->modify_font(new PangoFontDescription("Times New Roman Italic 10")); $title->modify_fg(Gtk::STATE_NORMAL, GdkColor::parse("#0000ff")); $title->set_size_request(-1, 20); $title->set_justify(Gtk::JUSTIFY_CENTER); $alignment = new GtkAlignment(0.5, 0.5, 0, 0); $alignment->add($title); $vbox->pack_start($alignment); $hbox = new GtkHBox(); $hbox->pack_start($button = new GtkButton('Add numbering'), 0); $vbox->pack_start($hbox, 0); $button->connect('clicked', 'on_button'); // note 1 // Create a new buffer and a new view to show the buffer. $buffer = new GtkTextBuffer(); $view = new GtkTextView(); $view->set_buffer($buffer); $view->modify_font(new PangoFontDescription("Arial 10")); $view->set_wrap_mode(Gtk::WRAP_WORD); $scrolled_win = new GtkScrolledWindow(); $scrolled_win->set_policy( Gtk::POLICY_AUTOMATIC, Gtk::POLICY_AUTOMATIC); $vbox->pack_start($scrolled_win); $scrolled_win->add($view); $window->show_all(); Gtk::main(); function on_button($button) { global $view, $buffer; list($start_iter, $end_iter) = $buffer->get_selection_bounds(); // note 2 if ($start_iter==null || $end_iter==null) { $cursor_pos = $buffer->get_mark('insert'); // note 3 $start_iter = $end_iter = $buffer->get_iter_at_mark($cursor_pos); // note 3 } $start_line = $start_iter->get_line(); // note 4 $end_line = $end_iter->get_line(); // note 4 $n = 1; $iter = $start_iter; for ($i=$start_line; $i<=$end_line; ++$i) { $iter->set_line($i); // note 5 $iter->forward_word_end(); // note 6 $iter->backward_word_start(); // note 6 $buffer->insert($iter, "$n. ", -1); // note 7 ++$n; } } ?> |
Output
As shown above.Explanation
- Set up the "Add numbering" button.
- Get the start and end iter of the selection bounds.
- If user didn't select any text, use the current cursor position as start and end iter.
- Get the line number of the start and end iter.
- Move the iter to the start of the line.
- Move the iter to the first non-space character.
- Add the number.
Read more...