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.
Answer
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.
Comments
Post a Comment