20
$\begingroup$

Select the following Mathematica code and paste it into a notebook. In Windows 7(Mathematica 8) the line breaks are not interpreted in the expression. In fact any data copipasted from stackexchange loses it's formatting. How do I paste content from stackexchange into Mathematica while keeping the formatting?

Print[ "text" ] 

EDIT: I don't particularly like Code Cells because they don't auto format and don't wrap when over 80 characters naturally. Another option which I had forgotten is AutoSpacing->True although I'd like to preserve line breaks and not white spaces entirely.

$\endgroup$
10
  • $\begingroup$ Prior question: mathematica.stackexchange.com/questions/29525/… $\endgroup$ Commented Aug 16, 2013 at 23:35
  • $\begingroup$ @Mr.Wizard that's fair if you really want. The other question though I wouldn't mark as a duplicate. Formatting data in strings doesn't seem like an appropriate solution to the other issue IMO. I just wanted people to find the question if they search for formatting issues. I would mark this as duplicate mathematica.stackexchange.com/questions/13317/… But not the question I asked. $\endgroup$ Commented Aug 16, 2013 at 23:39
  • 1
    $\begingroup$ @amr Yes I am not sure why M doesn't respect spaces. You mean Ctrl+Shift+E form like BoxData form yes? The funny thing is that the clipboard holds the appropriate data and M even interprets it with spaces. For example you can do NotebookGet@ClipboardNotebook[] and get the correctly formatted data. I'm not sure what is going :| $\endgroup$ Commented Aug 19, 2013 at 3:14
  • 1
    $\begingroup$ @William Could you please explain why CMD+8 is not a good choice for you? This is the same as as right-click -> Insert New Cell -> Code. This type of cell preserves formatting on paste and was created for that. $\endgroup$ Commented Feb 24, 2016 at 7:57
  • 1
    $\begingroup$ @VitaliyKaurov I'm quit happy as how Mathematica works now. I don't particularly like Code Cells because they don't auto format and don't wrap when over 80 characters naturally. Another option which I had forgotten is AutoSpacing->True although I'd like to preserve line breaks and not white spaces entirely. $\endgroup$ Commented Feb 25, 2016 at 7:25

2 Answers 2

15
$\begingroup$

As Mr.Wizard showed me here. You use UndocumentedTestFEParserPacket to print the pasted data. For example:

FixSpacesAndLineBreaksFormatting[t_] := (StringReplace[t, { RegularExpression["^[ ]+$"] -> "", "\n" -> "\[IndentingNewLine]"}]); CellPrint@Cell[ Replace[ First@FrontEndExecute@UndocumentedTestFEParserPacket[ Catch[NotebookGet@ClipboardNotebook[] /. Cell[r_, ___] :> Block[{}, Throw[r, tag] /; True]; $Failed, tag] , False] , t_String :> FixSpacesAndLineBreaksFormatting[t], Infinity] , "Input"] 

If you want a shortcut you can run the following to assign it to Ctrl+Shift+V as described here.

FixSpacesAndLineBreaksFormatting[t_] := (StringReplace[t, { RegularExpression["^[ ]+$"] -> "", "\n" -> "\[IndentingNewLine]"}]); FrontEndExecute[ FrontEnd`AddMenuCommands[ "DuplicatePreviousOutput", {Delimiter, MenuItem["Raw Paste Clipboard", FrontEnd`KernelExecute[NotebookWrite[InputNotebook[], Replace[ First@FrontEndExecute@UndocumentedTestFEParserPacket[ Catch[NotebookGet@ClipboardNotebook[] /. Cell[r_, ___] :> Block[{}, Throw[r, tag] /; True]; $Failed, tag] , False] , t_String :> FixSpacesAndLineBreaksFormatting[t], Infinity] ]], MenuKey["v", Modifiers -> {"Control", "Shift"}], System`MenuEvaluator -> Automatic]}]] 

Or do the add the following to KeyEventTranslations as described here. EDIT: This doesn't seem to be working currently and advised fix would be great. You can the put the AddMenuCommands in init.m as workaround.

$\endgroup$
12
  • $\begingroup$ Thanks a lot for sharing this. This seems to solve one of my current problems. Big +1. $\endgroup$ Commented Aug 16, 2013 at 23:20
  • $\begingroup$ @LeonidShifrin Yes every time I copy data from stackexchange I begin the process of reformatting and adding linbreaks, etc.. Not anymore. ;) $\endgroup$ Commented Aug 16, 2013 at 23:21
  • 1
    $\begingroup$ @Mr.Wizard No, not the first time, but I did not realize before that it preserves spaces and linebreaks. I just thought that it is simply a direct parser to boxes (which it is too), which is by itself nice enough. $\endgroup$ Commented Aug 16, 2013 at 23:24
  • 1
    $\begingroup$ @Liam Have you tried your code for KeyEventTranslations.tr? It gives a warning message "Serious Startup Error" when Mathematica starts (I use v. 8.0.4). $\endgroup$ Commented Aug 17, 2013 at 22:07
  • 2
    $\begingroup$ @AlexeyPopkov I have to many windows open right now to want to mess with mathematica's internals but you could use this as a workaround for now mathematica.stackexchange.com/questions/1606/… $\endgroup$ Commented Aug 18, 2013 at 4:12
9
$\begingroup$

As a start we can create a basic paste function using the ClipboardNotebook as follows:

pasteRaw[] := NotebookGet[ClipboardNotebook[]] /. Notebook[{Cell[BoxData[data_] | data_, ___]}, ___] :> (CellPrint[Cell[BoxData[data], "Input"]];) 

After copying the desired text you can evaluate pasteRaw[] to paste it as input. At present no syntax checking is done and you will get an error box if the input is invalid or incomplete.

$\endgroup$
4
  • 1
    $\begingroup$ Do you know of anyway to force getting the string representation of data from the clipbaord instead of getting the parsed cell data from ClipboardNotebook[]? For example if you use both my code and yours extra spaces are added to the BoxData which wouldn't occur if you used UndocumentedTestFEParserPacket[str], False] $\endgroup$ Commented Aug 25, 2013 at 3:18
  • $\begingroup$ @Liam I'll have to think about that; perhaps after the weekend. $\endgroup$ Commented Aug 25, 2013 at 3:22
  • $\begingroup$ Figured out why Mathematica kept adding the additional spaces. I wasn't really aware of the differences between IndentingNewLine and \n and how it modified the the spaces and other outputs. Again thanks for the help with UndocumentedTestFEParserPacket. $\endgroup$ Commented Oct 18, 2014 at 8:54
  • $\begingroup$ @Liam Sorry that I never returned to this, but I am glad you solved your own problem. $\endgroup$ Commented Oct 18, 2014 at 17:31

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.