0
$\begingroup$

I have multiple lines in a cell in mathematica created by pressing enter like:

In[12]:= 1 + 2
3 + 4
5 + 6

Out[12]= 3

Out[13]= 7

Out[14]= 11

I want to separate the input into multiple cells so that I can get the output as

In[18]:= 1 + 2

Out[18]= 3

In[19]:= 3 + 4

Out[19]= 7

In[20]:= 5 + 6

Out[20]= 11

Is there a way of doing this other than copying each line and pasting in a different cell and then running it. Actually, I have a file with a thousand of such input line and I want the output right after the inputs.

$\endgroup$
4
  • 1
    $\begingroup$ Put cursor where you wish to divide then Control+Shift+D for dividing. Control+Shift + M for merging $\endgroup$ – Hugh Jan 19 '18 at 14:55
  • $\begingroup$ @Hugh: Thanks. I know that. But if there are 100 lines say, is there a shortcut for doing that other than doing the step you mentioned 100 times? That is the problem... $\endgroup$ – anotherone Jan 19 '18 at 14:58
  • $\begingroup$ That is it, right? mathematica.stackexchange.com/q/87165/5478 $\endgroup$ – Kuba Jan 19 '18 at 17:08
  • $\begingroup$ Riffling in and out will be impossible in general as e.g. Scan[foo, {1, 2, 3}] produces no output so matching will break. $\endgroup$ – Kuba Jan 19 '18 at 19:59
1
$\begingroup$

You may use functions from the Low-Level Notebook Programming guide.

Module[{c = #, rows},
    rows = 
     Cases[
       FirstCase[NotebookRead@c, Cell[BoxData[r : {__}], __] :> r, {}, {0}],
       _RowBox, 1];
    If[
     MatchQ[rows, {_RowBox ..}],
     SelectionMove[c, After, Cell];
     NotebookWrite[ParentNotebook[c], Cell[BoxData[#], "Input"]] & /@ rows;
     NotebookDelete[c]
     ]
    ] & /@ Cells[CellStyle -> "Input"];

Evaluate the above in your notebook to split the cells. Be warned that it does delete cells so make a copy before doing so.

The above collects all of the input cells and splits those that contain rows of commands. It is very strict on the structure so you may need to loosen the conditions if the cells differ from the basic structure you provided in the question.

Hope this helps.

$\endgroup$
1
  • $\begingroup$ Thank you! It is working for me. $\endgroup$ – anotherone Jan 21 '18 at 18:56

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.