how to parse text in C from gtktextview/gtksourceview

968 views Asked by At

I am writing a text editor in C using gtk+-2.0 & gtksourceview-2.0. I'm trying to run a number of tests on the data I am extracting from the buffer. Currently I am moving a pair of iters then getting a block of text delimited by these iters. Then checking this string using strstr, strchr,... However, this process of moving the iters, then reading the data, then performing the tests is quite cumbersome.

I also have extracted the entire doc (using the previously described process) to a gchar *. Would it be easier to work on this data? I've tried to use fgets and getline on this data, but the compiler complains:

warning: passing argument 3 of ‘fgets’ from incompatible pointer type /usr/include/stdio.h:624:14: note: expected ‘struct FILE * __restrict__’ but argument is of type ‘gchar *’

or

warning: passing argument 1 of ‘getline’ from incompatible pointer type /usr/include/stdio.h:671:20: note: expected ‘char ** __restrict__’ but argument is of type ‘gchar *’

I tried :

  int bytes_read;
  int nbytes = 100;
  char *my_string;
  GtkTextIter start;
  GtkTextIter end;

  wholeDoc = gtk_text_buffer_get_text(tbuffer,&start,&end,TRUE);

  my_string = (char *) malloc (nbytes + 1);
  bytes_read = getline (&my_string, &nbytes, wholeDoc);

but got the following error:

warning: pointer targets in passing argument 2 of ‘getline’ differ in signedness /usr/include/stdio.h:671:20: note: expected ‘size_t * __restrict__’ but argument is of type ‘int *’

I'm looking for a way of checking, for example, the previous line by simply subtracting one from the loop index like each line is an element of an array. How can I get the data into this form? Please bear with me, I'm learning. Thanks.

2

There are 2 answers

1
ptomato On BEST ANSWER

You can split the string into an array of strings, one for each line. Use g_strsplit(). However, if you want to relate your data back to the position in the buffer, you're better off using buffer iterators.

1
Szilárd Pfeiffer On

Here is a simple example how to get lines from a GtkTexBuffer.

  GtkTextIter start_iter, next_iter;
  gchar *text;

  gtk_text_buffer_get_iter_at_offset (source_buffer, &start_iter, 0);

  next_iter = start_iter;
  while (gtk_text_iter_forward_line (&next_iter))
    {    
      text = gtk_text_iter_get_text (&start_iter, &next_iter);

      // line processing

      g_free (text);
      start_iter = next_iter;
    }    

For more details read the documentation of GtkTextIter.