Text View#

The Gtk.TextView widget can be used to display and edit large amounts of formatted text. Like the Gtk.ListView, it has a model/view design. In this case the Gtk.TextBuffer is the model which represents the text being edited. This allows two or more Gtk.TextView widgets to share the same Gtk.TextBuffer, and allows those text buffers to be displayed slightly differently. Or you could maintain several text buffers and choose to display each one at different times in the same Gtk.TextView widget.

See also

Text Widget Overview in the GTK documentation.

The View#

The Gtk.TextView is the frontend with which the user can add, edit and delete textual data. They are commonly used to edit multiple lines of text. When creating a Gtk.TextView it contains its own default Gtk.TextBuffer, which is kept in the Gtk.TextView.props.buffer property.

By default, text can be added, edited and removed from the Gtk.TextView. You can disable this by changing Gtk.TextView.props.editable. If the text is not editable, you usually want to hide the text cursor with Gtk.TextView.props.cursor_visible as well. In some cases it may be useful to set the justification of the text with Gtk.TextView.props.justification. The text can be displayed at the left edge, (Gtk.Justification.LEFT), at the right edge (Gtk.Justification.RIGHT), centered (Gtk.Justification.CENTER), or distributed across the complete width (Gtk.Justification.FILL).

Another default setting of the Gtk.TextView widget is long lines of text will continue horizontally until a break is entered. To wrap the text and prevent it going off the edges of the screen set Gtk.TextView.props.wrap_mode similar to Label.

The Model#

The Gtk.TextBuffer is the core of the Gtk.TextView widget, and is used to hold whatever text is being displayed in the Gtk.TextView. Setting and retrieving the contents is possible with Gtk.TextBuffer.props.text. However, most text manipulation is accomplished with iterators, represented by a Gtk.TextIter. An iterator represents a position between two characters in the text buffer. Iterators are not valid indefinitely; whenever the buffer is modified in a way that affects the contents of the buffer, all outstanding iterators become invalid.

Because of this, iterators can’t be used to preserve positions across buffer modifications. To preserve a position, use Gtk.TextMark. A text buffer contains two built-in marks; an “insert” mark (which is the position of the cursor) and the “selection_bound” mark. Both of them can be retrieved using Gtk.TextBuffer.get_insert() and Gtk.TextBuffer.get_selection_bound(), respectively. By default, the location of a Gtk.TextMark is not shown. This can be changed by calling Gtk.TextMark.set_visible().

Many methods exist to retrieve a Gtk.TextIter. For instance, Gtk.TextBuffer.get_start_iter() returns an iterator pointing to the first position in the text buffer, whereas Gtk.TextBuffer.get_end_iter() returns an iterator pointing past the last valid character. Retrieving the bounds of the selected text can be achieved by calling Gtk.TextBuffer.get_selection_bounds().

To insert text at a specific position use Gtk.TextBuffer.insert(). Another useful method is Gtk.TextBuffer.insert_at_cursor() which inserts text wherever the cursor may be currently positioned. To remove portions of the text buffer use Gtk.TextBuffer.delete().

In addition, Gtk.TextIter can be used to locate textual matches in the buffer using Gtk.TextIter.forward_search() and Gtk.TextIter.backward_search(). The start and end iters are used as the starting point of the search and move forwards/backwards depending on requirements.

Tags#

Text in a buffer can be marked with tags. A tag is an attribute that can be applied to some range of text. For example, a tag might be called “bold” and make the text inside the tag bold. However, the tag concept is more general than that; tags don’t have to affect appearance. They can instead affect the behavior of mouse and key presses, “lock” a range of text so the user can’t edit it, or countless other things. A tag is represented by a Gtk.TextTag object. One Gtk.TextTag can be applied to any number of text ranges in any number of buffers.

Each tag is stored in a Gtk.TextTagTable. A tag table defines a set of tags that can be used together. Each buffer has one tag table associated with it; only tags from that tag table can be used with the buffer. A single tag table can be shared between multiple buffers, however.

To specify that some text in the buffer should have specific formatting, you must define a tag to hold that formatting information, and then apply that tag to the region of text using Gtk.TextBuffer.create_tag() and Gtk.TextBuffer.apply_tag():

tag = textbuffer.create_tag('orange_bg', background='orange')
textbuffer.apply_tag(tag, start_iter, end_iter)

The following are some of the common styles applied to text:

  • Background colour (“background” property)

  • Foreground colour (“foreground” property)

  • Underline (“underline” property)

  • Bold (“weight” property)

  • Italics (“style” property)

  • Strikethrough (“strikethrough” property)

  • Justification (“justification” property)

  • Size (“size” and “size-points” properties)

  • Text wrapping (“wrap-mode” property)

You can also delete particular tags later using Gtk.TextBuffer.remove_tag() or delete all tags in a given region by calling Gtk.TextBuffer.remove_all_tags().

Example#

../../_images/textview.png
  1import gi
  2
  3gi.require_version("Gtk", "4.0")
  4from gi.repository import Gtk, Pango
  5
  6
  7class SearchDialog(Gtk.Window):
  8    def __init__(self, parent):
  9        super().__init__(title="Search", modal=True, transient_for=parent)
 10
 11        box = Gtk.Box(orientation=Gtk.Orientation.VERTICAL, spacing=12)
 12        self.set_child(box)
 13
 14        label = Gtk.Label(label="Insert text you want to search for:")
 15        box.append(label)
 16
 17        self.entry = Gtk.Entry()
 18        box.append(self.entry)
 19
 20        self.button = Gtk.Button(label="Find")
 21        box.append(self.button)
 22
 23
 24class TextViewWindow(Gtk.ApplicationWindow):
 25    def __init__(self, **kargs):
 26        super().__init__(**kargs, title="TextView Demo")
 27
 28        self.set_default_size(500, 400)
 29
 30        self.box = Gtk.Box(orientation=Gtk.Orientation.VERTICAL, spacing=6)
 31        self.set_child(self.box)
 32
 33        self.create_textview()
 34        self.create_toolbar()
 35        self.create_buttons()
 36
 37    def create_toolbar(self):
 38        toolbar = Gtk.Box(spacing=6, margin_top=6, margin_start=6, margin_end=6)
 39        self.box.prepend(toolbar)
 40
 41        button_bold = Gtk.Button(icon_name="format-text-bold-symbolic")
 42        toolbar.append(button_bold)
 43
 44        button_italic = Gtk.Button(icon_name="format-text-italic-symbolic")
 45        toolbar.append(button_italic)
 46
 47        button_underline = Gtk.Button(icon_name="format-text-underline-symbolic")
 48        toolbar.append(button_underline)
 49
 50        button_bold.connect("clicked", self.on_button_clicked, self.tag_bold)
 51        button_italic.connect("clicked", self.on_button_clicked, self.tag_italic)
 52        button_underline.connect("clicked", self.on_button_clicked, self.tag_underline)
 53
 54        toolbar.append(Gtk.Separator())
 55
 56        justifyleft = Gtk.ToggleButton(icon_name="format-justify-left-symbolic")
 57        toolbar.append(justifyleft)
 58
 59        justifycenter = Gtk.ToggleButton(icon_name="format-justify-center-symbolic")
 60        justifycenter.set_group(justifyleft)
 61        toolbar.append(justifycenter)
 62
 63        justifyright = Gtk.ToggleButton(icon_name="format-justify-right-symbolic")
 64        justifyright.set_group(justifyleft)
 65        toolbar.append(justifyright)
 66
 67        justifyfill = Gtk.ToggleButton(icon_name="format-justify-fill-symbolic")
 68        justifyfill.set_group(justifyleft)
 69        toolbar.append(justifyfill)
 70
 71        justifyleft.connect("toggled", self.on_justify_toggled, Gtk.Justification.LEFT)
 72        justifycenter.connect(
 73            "toggled", self.on_justify_toggled, Gtk.Justification.CENTER
 74        )
 75        justifyright.connect(
 76            "toggled", self.on_justify_toggled, Gtk.Justification.RIGHT
 77        )
 78        justifyfill.connect("toggled", self.on_justify_toggled, Gtk.Justification.FILL)
 79
 80        toolbar.append(Gtk.Separator())
 81
 82        button_clear = Gtk.Button(icon_name="edit-clear-symbolic")
 83        button_clear.connect("clicked", self.on_clear_clicked)
 84        toolbar.append(button_clear)
 85
 86        toolbar.append(Gtk.Separator())
 87
 88        button_search = Gtk.Button(icon_name="system-search-symbolic")
 89        button_search.connect("clicked", self.on_search_clicked)
 90        toolbar.append(button_search)
 91
 92    def create_textview(self):
 93        scrolledwindow = Gtk.ScrolledWindow(hexpand=True, vexpand=True)
 94        self.box.append(scrolledwindow)
 95
 96        self.textview = Gtk.TextView()
 97        self.textbuffer = self.textview.get_buffer()
 98        self.textbuffer.set_text(
 99            "This is some text inside of a Gtk.TextView. "
100            'Select text and click one of the buttons "bold", "italic", '
101            'or "underline" to modify the text accordingly.'
102        )
103        scrolledwindow.set_child(self.textview)
104
105        self.tag_bold = self.textbuffer.create_tag("bold", weight=Pango.Weight.BOLD)
106        self.tag_italic = self.textbuffer.create_tag("italic", style=Pango.Style.ITALIC)
107        self.tag_underline = self.textbuffer.create_tag(
108            "underline", underline=Pango.Underline.SINGLE
109        )
110        self.tag_found = self.textbuffer.create_tag("found", background="yellow")
111
112    def create_buttons(self):
113        grid = Gtk.Grid()
114        self.box.append(grid)
115
116        check_editable = Gtk.CheckButton(label="Editable", active=True)
117        check_editable.bind_property("active", self.textview, "editable", 0)
118        grid.attach(check_editable, 0, 0, 1, 1)
119
120        check_cursor = Gtk.CheckButton(label="Cursor Visible", active=True)
121        check_cursor.bind_property("active", self.textview, "cursor_visible", 0)
122        grid.attach_next_to(check_cursor, check_editable, Gtk.PositionType.RIGHT, 1, 1)
123
124        radio_wrapnone = Gtk.CheckButton(label="No Wrapping", active=True)
125        grid.attach(radio_wrapnone, 0, 1, 1, 1)
126
127        radio_wrapchar = Gtk.CheckButton(
128            label="Character Wrapping", group=radio_wrapnone
129        )
130        grid.attach_next_to(
131            radio_wrapchar, radio_wrapnone, Gtk.PositionType.RIGHT, 1, 1
132        )
133
134        radio_wrapword = Gtk.CheckButton(label="Word Wrapping", group=radio_wrapnone)
135        grid.attach_next_to(
136            radio_wrapword, radio_wrapchar, Gtk.PositionType.RIGHT, 1, 1
137        )
138
139        radio_wrapnone.connect("toggled", self.on_wrap_toggled, Gtk.WrapMode.NONE)
140        radio_wrapchar.connect("toggled", self.on_wrap_toggled, Gtk.WrapMode.CHAR)
141        radio_wrapword.connect("toggled", self.on_wrap_toggled, Gtk.WrapMode.WORD)
142
143    def on_button_clicked(self, _widget, tag):
144        bounds = self.textbuffer.get_selection_bounds()
145        if len(bounds) != 0:
146            start, end = bounds
147            self.textbuffer.apply_tag(tag, start, end)
148
149    def on_clear_clicked(self, _widget):
150        start = self.textbuffer.get_start_iter()
151        end = self.textbuffer.get_end_iter()
152        self.textbuffer.remove_all_tags(start, end)
153
154    def on_wrap_toggled(self, _widget, mode):
155        self.textview.props.wrap_mode = mode
156
157    def on_justify_toggled(self, _widget, justification):
158        self.textview.props.justification = justification
159
160    def on_search_clicked(self, _widget):
161        self.search_dialog = SearchDialog(self)
162        self.search_dialog.button.connect("clicked", self.on_find_clicked)
163        self.search_dialog.present()
164
165    def on_find_clicked(self, _button):
166        cursor_mark = self.textbuffer.get_insert()
167        start = self.textbuffer.get_iter_at_mark(cursor_mark)
168        if start.get_offset() == self.textbuffer.get_char_count():
169            start = self.textbuffer.get_start_iter()
170
171        self.search_and_mark(self.search_dialog.entry.get_text(), start)
172
173    def search_and_mark(self, text, start):
174        end = self.textbuffer.get_end_iter()
175        match = start.forward_search(text, 0, end)
176
177        if match is not None:
178            match_start, match_end = match
179            self.textbuffer.apply_tag(self.tag_found, match_start, match_end)
180            self.search_and_mark(text, match_end)
181
182
183def on_activate(app):
184    win = TextViewWindow(application=app)
185    win.present()
186
187
188app = Gtk.Application(application_id="com.example.App")
189app.connect("activate", on_activate)
190
191app.run(None)