9
$\begingroup$

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) ?

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

2 Answers 2

8
$\begingroup$

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.)

$\endgroup$
2
  • $\begingroup$ Great! Thank you very much! $\endgroup$ Commented Jun 21, 2015 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$ Commented Oct 27, 2017 at 16:22
13
$\begingroup$

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.

$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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