Paste data into Mathematica with formatting
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.
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.