Mathematica Stack Exchange is a question and answer site for users of Mathematica. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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.

share|improve this question
    
Prior question: mathematica.stackexchange.com/questions/29525/… – Mr.Wizard Aug 16 '13 at 23:35
    
@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. – Liam Aug 16 '13 at 23:39
1  
@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 :| – Liam Aug 19 '13 at 3:14
1  
@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. – Vitaliy Kaurov Feb 24 at 7:57
1  
@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. – Liam Feb 25 at 7:25
up vote 14 down vote accepted

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.

share|improve this answer
    
Thanks a lot for sharing this. This seems to solve one of my current problems. Big +1. – Leonid Shifrin Aug 16 '13 at 23:20
    
@LeonidShifrin Yes every time I copy data from stackexchange I begin the process of reformatting and adding linbreaks, etc.. Not anymore. ;) – Liam Aug 16 '13 at 23:21
1  
@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. – Leonid Shifrin Aug 16 '13 at 23:24
1  
@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). – Alexey Popkov Aug 17 '13 at 22:07
2  
@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/… – Liam Aug 18 '13 at 4:12

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.

share|improve this answer
1  
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] – Liam Aug 25 '13 at 3:18
    
@Liam I'll have to think about that; perhaps after the weekend. – Mr.Wizard Aug 25 '13 at 3:22
    
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. – Liam Oct 18 '14 at 8:54
    
@Liam Sorry that I never returned to this, but I am glad you solved your own problem. – Mr.Wizard Oct 18 '14 at 17:31

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.