PHP-GTK2 Newsletter

PHP-GTK2 Tips & Techniques
FREE Newsletter
by kksou



Sample Code 151: How to add numbering in front of selected text in GtkTextView?
Written by kksou   
Thursday, 25 January 2007
Problem

You want to add auto numbering in front of highlighted text in a GtkTextView as shown below:

How to add numbering in front of selected text in GtkTextView?


Solution

Sample Code
1   
2   
3   
4   
5   
6   
7   
8   
9   
10   
11   
12   
13   
14   
15   
16   
17   
18   
19   
20   
21   
22   
23   
24   
25   
26   
27   
28   
29   
30   
31   
32   
33   
34   
35   
36   
37   
38   
39   
40   
41   
<?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
  • Note that this is only 70% of the sample code. You have to be a registered member to see the entire sample code. Please login or register.
  • Registration is free and immediate.
  • Have some doubt about the registration? Please read this forum article.
Explanation
  1. Set up the "Add numbering" button.
  2. Get the start and end iter of the selection bounds.
  3. If user didn't select any text, use the current cursor position as start and end iter.
  4. Get the line number of the start and end iter.
  5. Move the iter to the start of the line.
  6. Move the iter to the first non-space character.
  7. Add the number.

Related Links

User reviews   Average user ratings:    4.0   (from 1 user)
  1. chris
    February 25, 2008 5:40pm

Note: You have to be a registered member to leave a comment. Free registration here.

 
< Prev   Next >

Copyright © 2006-2008. kksou.com. All Rights Reserved