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.
Ctrl+Shift+Eform 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 doNotebookGet@ClipboardNotebook[]and get the correctly formatted data. I'm not sure what is going :| $\endgroup$CMD+8is not a good choice for you? This is the same as asright-click -> Insert New Cell -> Code. This type of cell preserves formatting on paste and was created for that. $\endgroup$