8

How do I get unmodified text content from the clipboard? If you copy the following into the clipboard and use ClipboardNotebook[] \[IndentingNewLine] is interpreted as \n:

f[\[IndentingNewLine]]

and run

FullForm@Catch[
  NotebookGet@ClipboardNotebook[] /. 
   Cell[r_, ___] :> Block[{}, Throw[r, tag] /; True];
  $Failed, tag]

"f[\n]"

Apologies if there is something in alternative to ClipboardNotebook, I haven't found it.

William
  • 7,595
  • 2
  • 22
  • 70
  • So actually you need an analog of the MS Word command Paste Special ► Plain text, right? – Alexey Popkov Feb 26 '16 at 22:24
  • @AlexeyPopkov Ideally yes although this question is slightly different. – William Apr 05 '16 at 03:09
  • @Liam - what happens if you try to paste into a "Code" cell? If I create a code cell, and just hit Ctrl-v, then I get the same thing as if I manually type f[\[NewLine]] – Jason B. Nov 01 '16 at 22:06
  • @JasonB code cell works but it isn't what I am after. I would like to programatically modify the clipboard. – William Nov 01 '16 at 23:33
  • You say you need this for Linux but the question is tagged Windows. Can you correct this? – Szabolcs Nov 02 '16 at 08:58

3 Answers3

6

The following works for Windows borrowed mostly from here.

Needs["NETLink`"];
InstallNET[];
LoadNETType["System.Windows.Forms.Clipboard"];
LoadNETType["System.Windows.Forms.TextDataFormat"];
System`Windows`Forms`Clipboard`GetText[System`Windows`Forms`\
TextDataFormat`UnicodeText]
William
  • 7,595
  • 2
  • 22
  • 70
4

For completion here is how you do it in linux.

Import["!xsel --clipboard","Text"]
William
  • 7,595
  • 2
  • 22
  • 70
  • Note that xsel is not installed by default on Ubuntu. – Ruslan Nov 02 '16 at 18:34
  • @Ruslan do you have an alternative recommendation. – William Nov 02 '16 at 19:47
  • 1
    No, it seems all X11 clipboard-related utilities are not installed by default. So you have to just warn the user that he may need to install xsel via (for Ubuntu/Debian) sudo apt-get install xsel for your answer to work. – Ruslan Nov 02 '16 at 20:20
  • @Ruslan if you post answer I'll give you the bounty I can't give it to myself. – William Nov 02 '16 at 20:27
  • It wouldn't add anything new: I'm just suggesting you to improve this answer by adding a note about xsel (which you use here!) being not by default installed — it can still be easily installed, but the user must actually do this. – Ruslan Nov 02 '16 at 20:28
2

And lastly OSX I haven't tested this on OSX yet but believe it should work.

Import["!pbpaste","Text"]
William
  • 7,595
  • 2
  • 22
  • 70