getting HTML source or rich text from the X clipboard

Viewed 6881

How can rich text or HTML source code be obtained from the X clipboard? For example, if you copy some text from a web browser and paste it into kompozer, it pastes as HTML, with links etc. preserved. However, xclip -o for the same selection just outputs plain text, reformatted in a way similar to that of elinks -dump. I'd like to pull the HTML out and into a text editor (specifically vim).

I asked the same question on superuser.com, because I was hoping there was a utility to do this, but I didn't get any informative responses. The X clipboard API is to me yet a mysterious beast; any tips on hacking something up to pull this information are most welcome. My language of choice these days is Python, but pretty much anything is okay.

3 Answers

Extending the ideas from Stephane Chazelas, you can:

  • Copy from the formatted source.
  • Run this command to extract from the clipboard, convert to HTML, and then (with a pipe |) put that HTML back in the clipboard, again using the same xclip:
xclip -selection clipboard -o -t text/html | xclip -selection clipboard
  • Next, when you paste with Ctrl+v, it will paste the HTML source.

Going further, you can make it a shortcut, so that you don't have to open the terminal and run the exact command each time. ✨

To do that:

  • Open the settings for your OS (in my case it's Ubuntu)
  • Find the section for the Keyboard
  • Then find the section for shortcuts
  • Create a new shortcut
  • Set a Name, e.g.: Copy as HTML
  • Then as the command for the shortcut, put:
bash -c "xclip -selection clipboard -o -t text/html | xclip -selection clipboard"

Note: notice that it's the same command as above, but put inside of an inline Bash script. This is necessary to be able to use the | (pipe) to send the output from one command as input to the next.

  • Set the shortcut to whatever combination you want, preferably not overwriting another shortcut you use. In my case, I set it to: Ctrl+Shift+c

  • After this, you can copy some formatted text as normally with: Ctrl+c
  • And then, before pasting it, convert it to HTML with: Ctrl+Shift+c
  • Next, when you paste it with: Ctrl+v, it will paste the contents as HTML. ✨

Shortcut edition window

Related