Formatted Text in GtkTextView

GtkTextView can also be used to display formatted text. This usually involves creating tags which represent a group of attributes and then applying them to a range of text.

Tag objects are associated with a buffer and are created using the following function,

GtkTextTag* gtk_text_buffer_create_tag( GtkTextBuffer *buffer,
const gchar *tag_name,
const gchar *first_prop_name,
… );

Table 1. Common properties used for creating tags

Property Meaning Values
“style” Font style as PangoStyle.
“weight” Font weight as integer.
“editable” Text modifiable by user.
“justification” Justification of text.
“foreground” Foreground color of text. “#RRGGBB”
“background” Background color of text. “#RRGGBB”
“wrap-mode” Text wrapping mode
GTK_WRAP_NONE – Don’t wrap text
GTK_WRAP_CHAR – Wrap text, breaking in between characters
GTK_WRAP_WORD – Wrap text, breaking in between words
GTK_WRAP_WORD_CHAR – Wrap text, breaking in words, or if that is not enough, also between characters
“font” Text font specified by font description string. “[FAMILY-LIST] [STYLE-OPTIONS] [SIZE]”

Here is a brief description of the font description string from the GTK+ manual.

“[FAMILY-LIST] [STYLE-OPTIONS] [SIZE]”, where FAMILY-LIST is a comma separated list of families optionally terminated by a comma, STYLE_OPTIONS is a whitespace separated list of words where each WORD describes one of style, variant, weight, or stretch, and SIZE is an decimal number (size in points). Any one of the options may be absent. If FAMILY-LIST is absent, then the family_name field of the resulting font description will be initialized to NULL. If STYLE-OPTIONS is missing, then all style options will be set to the default values. If SIZE is missing, the size in the resulting font description will be set to 0.”

See the GTK+ manual, for a complete list of properties and their corresponding values.

The created tag can then be applied to a range of text using the following functions,

The first function specifies the tag to be applied by a tag object and the second function specifies the tag by it’s name. The range of text over with the tag is to applies is specified by the start and end iters.

Below is an extension of the previous example, that has a tool-bar to apply different tags to selected regions of text.

Tags can be optionally associated with a name tag_name. Thus, the tag could be referred using the returned pointer or using the tag_name. For anonymous tags, NULL is passed to tag_name. The group of properties represented by this tag is listed as name/value pairs after the tag_name. The list of property/value pairs is terminated with a NULL pointer. “style”, “weight”, “editable”, “justification” are some common property names. The following table lists their meaning and assignable values.