2

I am developing a little tool in GTK 3 (and Python), where you copy a snippet of code and using Pygments, it fills the system's clipboard with the highlighted code, so you can paste it to another RTF-aware application. The idea came from that piece of code: http://pastebin.geany.org/SnUSw/

Relevant piece of code:

clipboard = Gtk.Clipboard.get(Gdk.SELECTION_CLIPBOARD)
clipboard.set_text(formatted_rtf, -1)
clipboard.store()

Unfortunately, that doesn't really work. When you paste the text (i.e. into Word), you get the raw RTF code instead. Searching around, maybe there is a solution using gtk_clipboard_set_with_data, but I'm unable to find any example of how to use that. I don't know if it will work on Windows anyway. Any working example of how to copy RTF to clipboard using GTK would be welcome. (Not necessarily in Python, as long as it is easy to translate with GI).

Related question that did not help (links are broken): How to paste HTML to clipboard with GTK+

Update

I tried using set_with_data looking at a project I found on Github

def hightlight_text(self, data):
    text, lexer_name, style = data
    # (...)
    clipboard = Gtk.Clipboard.get(Gdk.SELECTION_CLIPBOARD)
    entries = [
        Gtk.TargetEntry.new("application/rtf", 0, 0),
        Gtk.TargetEntry.new("text/plain", 0, 1)
    ]
    clipboard.set_with_data(
        entries, 2,
        self.get_clipboard,
        None,
        (formatted_rtf, text)
    )

def get_clipboard(self, clipboard, selection_data, info, data):
    formatted_rtf, text = data
    if info == 1:
        requested_data = text
    else:
        requested_data = formatted_rtf
    selection_data.set(selection_data.get_target(), requested_data)

Unfortunately, GObject-Introspection doesn't seem to like that...

Traceback (most recent call last):
  File "highlight.py", line 72, in hightlight_text
    clipboard.set_with_data(
AttributeError: 'Clipboard' object has no attribute 'set_with_data'

So finally, I'm indeed interested in how to do this with Python (i.e. with GI).

Cilyan
  • 7,883
  • 1
  • 29
  • 37

1 Answers1

0

Don't think you can do it using GTK. I basically wrote that same tool you described for my own use using win32clipboard and referencing this guide.

Think the Windows API has certain clipboard formats that causes the application to handle them differently. GTK probably only deals with text which is why the raw RTF code appears when pasting into RTF aware applications.

welcomb
  • 79
  • 1
  • 5