30.21 Yanking Media

If you choose, for instance, “Copy Image” in a web browser, that image is put onto the clipboard, and Emacs can access it via gui-get-selection. But in general, inserting image data into an arbitrary buffer isn’t very useful—you can’t really do much with it by default.

So Emacs has a system to let modes register handlers for these “complicated” selections.

Function: yank-media-handler types handler

types can be a MIME media type symbol, a regexp to match these, or a list of these symbols and regexps. For instance:

(yank-media-handler 'text/html #'my-html-handler)
(yank-media-handler "image/.*" #'my-image-handler)

A mode can register as many handlers as required.

The handler function is called with two parameters: The MIME media type symbol and the data (as a string). The handler should then insert the object into the buffer, or save it, or do whatever is appropriate for the mode.

The yank-media command will consult the registered handlers in the current buffer, compare that with the available media types on the clipboard, and then pass on the matching selection to the handler (if any). If there’s more than one matching selection, the user is queried first.

The yank-media-types command can be used to explore the clipboard/primary selection. It lists all the media types that are currently available, and can be handy when creating handlers—to see what data is actually available. Some applications put a surprising amount of different data types on the clipboard.