Question

I'm trying to keep dependencies to a minimum for a program I contribute to, it's a small text editor.

GTK Textview doesn't seem to come with a built-in undo function. Is there any reference implementation I've been missing on so far? Is everyone writing their own undo function for their TextView widgets?

I'll be happy about any sample code - most happy about python sample code, as our project is in python.

Was it helpful?

Solution

As far as I know, GTK TextView doesn't include an undo function. So while I am not familiar with Python's GTK library, I would think it doesn't have one.

The Ruby-GNOME2 project has a sample text editor that has undo/redo functionality. Basically they are connecting to the insert_text and delete_range signals of the TextView widget and recording the events and associated data in a list.

OTHER TIPS

as a follwow-up: I ported gtksourceview's undo mechanism to python: http://bitbucket.org/tiax/gtk-textbuffer-with-undo/

serves as a drop-in replacement for gtksourceview's undo

(OP here, but launchpad open-id doesn't work anymore)

Depending on just how dependency-averse you are, and what kind of text editor you're building, GtkSourceView adds undo/redo among many other things. Very worth looking at if you want some of the other features it offers.

Use GtkSource

.

  • [Cmnd] + [Z] for undo (default)
  • [Cmnd] + [Shift] + [Z] for redo (default)
  • [Cmnd] + [Y] for redo (added manually)

example:

#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import gi
gi.require_version('Gtk', '3.0')
from gi.repository import Gtk
from gi.repository import Gdk
gi.require_version('GtkSource', '3.0')
from gi.repository import GtkSource

import os


class TreeviewWindow(Gtk.Window):
    def __init__(self):
        Gtk.Window.__init__(self, title="TreeviewWindow")
        self.set_size_request(300, 300)
        self.connect("key-press-event", self._key_press_event)
        self.mainbox = Gtk.VBox(spacing=10)
        self.add(self.mainbox) 

        self.textbuffer = GtkSource.Buffer()
        textview = GtkSource.View(buffer=self.textbuffer)
        textview.set_editable(True)
        textview.set_cursor_visible(True)
        textview.set_show_line_numbers(True)
        self.mainbox.pack_start(textview, True, True, 0)
        self.show_all()  

    def _key_press_event(self, widget, event):
        keyval_name = Gdk.keyval_name(event.keyval)
        ctrl = (event.state & Gdk.ModifierType.CONTROL_MASK)
        if ctrl and keyval_name == 'y':
            if self.textbuffer.can_redo():
                self.textbuffer.do_redo(self.textbuffer)

    def main(self):
        Gtk.main()

if __name__ == "__main__":
    base = TreeviewWindow()
    base.main()
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top