/* Copyright (c) 2002 Mohammed Sameer.
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
*/

/* $ gcc -o text text.c `pkg-config gtk+-2.0 --cflags --libs` */

#include <gtk/gtk.h>

GtkTextBuffer *buffer;
gboolean first = TRUE;

void
search ()
{
  GtkTextIter from;
  GtkTextIter start;
  GtkTextIter end;
  gboolean foo;

  GtkTextSearchFlags search_flags =
    GTK_TEXT_SEARCH_VISIBLE_ONLY | GTK_TEXT_SEARCH_TEXT_ONLY;
  if (first)
    {
      gtk_text_buffer_get_start_iter (buffer, &from);
      gtk_text_iter_forward_search (&from, "a", search_flags, &start, &end,
				    NULL);
      gtk_text_buffer_move_mark_by_name (buffer, "selection_bound", &start);
      gtk_text_buffer_move_mark_by_name (buffer, "insert", &end);
      first = FALSE;
    }
  else
    {
      gtk_text_buffer_get_iter_at_mark (buffer, &from,
					gtk_text_buffer_get_mark
					(buffer, "insert"));
      foo =
	gtk_text_iter_forward_search (&from, "a", search_flags, &start, &end,
				      NULL);
      if (foo)
	{
	  gtk_text_buffer_move_mark_by_name (buffer, "selection_bound",
					     &start);
	  gtk_text_buffer_move_mark_by_name (buffer, "insert", &end);
	}
      else
	{
	  first = TRUE;
	  search ();
	}
    }
}

int
main (int argc, char *argv[])
{
  GtkWidget *window;
  GtkWidget *vbox;
  GtkWidget *scrolledwindow;
  GtkWidget *textview;
  GtkWidget *button;

  gtk_init (&argc, &argv);

  window = gtk_window_new (GTK_WINDOW_TOPLEVEL);
/* I know it's deprecated! */
  gtk_widget_set_usize (GTK_WIDGET (window), 200, 200);
  vbox = gtk_vbox_new (FALSE, 0);
  gtk_container_add (GTK_CONTAINER (window), vbox);

  scrolledwindow = gtk_scrolled_window_new (NULL, NULL);
  gtk_box_pack_start (GTK_BOX (vbox), scrolledwindow, TRUE, TRUE, 0);

  textview = gtk_text_view_new ();
  gtk_container_add (GTK_CONTAINER (scrolledwindow), textview);
  buffer = gtk_text_view_get_buffer (GTK_TEXT_VIEW (textview));
  gtk_text_buffer_set_text (buffer, "a\n\na\naa\na\n\na\n\na", -1);
  button = gtk_button_new_with_mnemonic ("Search");
  gtk_box_pack_start (GTK_BOX (vbox), button, FALSE, FALSE, 0);

  g_signal_connect (G_OBJECT (window), "delete_event",
		    G_CALLBACK (gtk_main_quit), NULL);
  g_signal_connect (G_OBJECT (window), "destroy_event",
		    G_CALLBACK (gtk_main_quit), NULL);
  g_signal_connect (G_OBJECT (button), "clicked", G_CALLBACK (search), NULL);

  gtk_widget_show_all (window);
  gtk_main ();
  return 0;
}
