The scanner of an editor is only responsible for lexical analysis, not for highlighting text. The scanner informs the editor of the different tokens that the different parts of the text represents, and the editor then displays the text with the properties (font and colour) that is associated to the different kinds of tokens.
Per default, all tokens are shown with the same properties, but this can be changed by associating tokens with a GtkText tag. A tag, associated with a given token, is created with the function gtk_editor_create_tag.
Example 3-1. Creating a tag associated with a token
tag = gtk_editor_create_tag (editor, "comments"); |
Text properties can then be set for the tag, and the associated tokens will be highlighted accordingly.
Example 3-2. Setting Text Properties
tag = gtk_editor_create_tag (editor, "comment"); gtk_object_set (GTK_OBJECT (tag), "foreground", "#ff0000", "font", "-adobe-courier-medium-i-normal-*-12-*-*-*-*-*-*-*", NULL); |
Example 3-3. Creating a GtkEditor, loading a scanner, and configure syntax highlighting.
#include <stdlib.h> #include <gtkeditor.h> static void setup_hilite (GtkEditor *editor) { GtkTextTag *tag; tag = gtk_editor_create_tag(editor, "keyword"); gtk_object_set(GTK_OBJECT(tag), "foreground", "blue", "font", "-adobe-courier-bold-r-normal-*-12-*-*-*-*-*-*-*", NULL); tag = gtk_editor_create_tag(editor, "type"); gtk_object_set(GTK_OBJECT(tag), "foreground", "#4ad822", NULL); tag = gtk_editor_create_tag(editor, "comment"); gtk_object_set(GTK_OBJECT(tag), "foreground", "#ff0000", "font", "-adobe-courier-medium-i-normal-*-12-*-*-*-*-*-*-*", NULL); tag = gtk_editor_create_tag(editor, "string"); gtk_object_set(GTK_OBJECT(tag), "foreground", "#cc901a", NULL); tag = gtk_editor_create_tag(editor, "function"); gtk_object_set(GTK_OBJECT(tag), "foreground", "blue", NULL); } int main (int argc, char *argv[]) { GtkWidget *window; GtkWidget *sw; GtkWidget *tkxt; GtkEditor *editor; gtk_init (&argc, &argv); window = gtk_window_new (GTK_WINDOW_TOPLEVEL); editor = gtk_editor_new (); /* load and install a C scanner */ cscanner = gtk_editor_load_scanner ("c-scanner"); gtk_editor_install_scanner (editor, cscanner); /* call hilite configuration */ setup_hilite (editor); sw = gtk_scrolled_window_new(NULL, NULL); gtk_scrolled_window_set_policy(GTK_SCROLLED_WINDOW(sw), GTK_POLICY_AUTOMATIC, GTK_POLICY_AUTOMATIC); tkxt = gtk_text_view_new_with_buffer(GTK_TEXT_BUFFER(editor)); gtk_container_add (GTK_CONTAINER (window), sw); gtk_container_add (GTK_CONTAINER(sw), tkxt); gtk_window_set_default_size(GTK_WINDOW(window), 300, 200); gtk_main (); return EXIT_SUCCESS; } |
Tokens are referred to by their name, and the association between tags and tokens depends very little on the scanner. So the highlighting configuration depends on the scanner only in the sense that it needs to know the names of the tokens, as defined by the scanner. With a little discipline in naming tokens, however, it is possible to write fairly generic highlight code.