How do I set the cursor position in a GtkText object?

GTK+ FAQ
<<< Previous | Development with GTK+: widget specific questions | Next >>>

# How do I set the cursor position in a GtkText object?

Notice that the response is valid for any object that inherits from the GtkEditable class.

Are you sure that you want to move the cursor position? Most of the time, while the cursor position is good, the insertion point does not match the cursor position. If this apply to what you really want, then you should use the `gtk_text_set_point()` function. If you want to set the insertion point at the current cursor position, use the following:

      gtk_text_set_point(GTK_TEXT(text),
      gtk_editable_get_position(GTK_EDITABLE(text)));

If you want the insertion point to follow the cursor at all time, you should probably catch the button press event, and then move the insertion point. Be careful : you'll have to catch it after the widget has changed the cursor position though. Thomas Mailund Jensen proposed the following code:

    static void
    insert_bar (GtkWidget *text)
    {
      /* jump to cursor mark */
      gtk_text_set_point (GTK_TEXT (text),
      gtk_editable_get_position (GTK_EDITABLE  (text)));

      gtk_text_insert (GTK_TEXT (text), NULL, NULL, NULL,
         "bar", strlen ("bar"));
    }

    int
    main (int argc, char *argv[])
    {
      GtkWidget *window, *text;

      gtk_init (&argc, &argv);

      window = gtk_window_new (GTK_WINDOW_TOPLEVEL);
      text = gtk_text_new (NULL, NULL);
      gtk_text_set_editable (GTK_TEXT (text), TRUE);
      gtk_container_add (GTK_CONTAINER (window), text);

      /* connect after everything else */
      gtk_signal_connect_after (GTK_OBJECT(text), "button_press_event",
        GTK_SIGNAL_FUNC (insert_bar), NULL);

      gtk_widget_show_all(window);
      gtk_main();

      return 0;
    }

Now, if you really want to change the cursor position, you should use the `gtk_editable_set_position()` function.

<<< Previous | Home | Next >>>
How do I change the font of a GtkText widget? | Up | About GDK