If I copy from an external editor to Mathematica notebook a block of lines (with a code)

line 1
line 2
line n

then whole text is copied to a single cell. I can now use n-1 times "Divide cell" and manually create n new cells for each line. If n is big, then this is a hard work. Exists some better method how do it ? For example before copying insert some special characters into text (representing an end of cell) ?

  • $\begingroup$ What cell style do you want the resulting cells to have? $\endgroup$ – m_goldberg Jun 21 '15 at 18:47
  • $\begingroup$ I need a InputForm. $\endgroup$ – Vaclav Kotesovec Jun 21 '15 at 19:07

I would do it this way. I would write a function

pasteLines[txt_, styl_] := (CellPrint @ Cell[#, styl] & /@ StringSplit[txt, "\n"];)

To use it, I would first write

pasteLines["", "Input"]

I would line copy the text I wanted from the external editor onto the clipboard and paste it between the quotes in the empty string (1st argument), getting

pasteLines["line 1
line 2
line n", "Input"]

Evaluating this last expression, gives

enter image description here

These are all normal input cells that can be edited and evaluated.

This can be made more user friendly. You could merge this MikeLimaOscar's answer, eliminating the txt argument, and getting the text from the clip board programatically. You could incorporate the function into paste button which you put on a palette, available for frequent use. (I'm sorry to say I don't have the time to develop this second idea.)

  • $\begingroup$ Great! Thank you very much! $\endgroup$ – Vaclav Kotesovec Jun 21 '15 at 19:55
  • $\begingroup$ For my purposes (always want an input cell, want to be able to delete all output, fix issues with output being placed at the bottom of a group of cells rather than underneath the cell), I use this variant: pasteLines[txt_] := (CellPrint[Cell[#, "Input" , CellAutoOverwrite -> False, GeneratedCell -> False]] & /@ Reverse@StringSplit[txt, "\n"];) $\endgroup$ – GenericAccountName Oct 27 '17 at 16:22

It is not straightforward to access the clipboard contents but one way, that doesn't involve writing and reading from temporary notebooks is to use the undocumented ClipboardNotebook function:

CellPrint /@ StringSplit[NotebookGet[ClipboardNotebook[]][[1, 1, 1]], "\n"];

See also this answer which mentions some caveats. This prints strings as text cells. See the documentation for CellPrint if you require another form.


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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