4

For example, if I do this:

In[42]:= {{2}, {3}} // MatrixForm

where In[42]:= is the notebook prompt, I am looking for some way to get back {{2}, {3}} // MatrixForm. (Which I guess would be a string? Or some kind of unevaluated expression?)

The closest I can find is In[42] // InputForm, which in this case gives me MatrixForm[{{2}, {3}}].

Is this possible, or is the actual tree structure of an entered input not recoverable?

billc
  • 684
  • 5
  • 16

3 Answers3

5

Edit: See here for a better answer.

Just a slight modification of Mechanical snail's answer here, (I need a more creative username...) to make the output match the input exactly.

In[1]:= {{2}, {3}} // MatrixForm

enter image description here

In[2]:= ToExpression[InString[1], StandardForm, Defer] // DisplayForm

enter image description here

Which you can copy/paste, or just append //CopyToClipboard to the command above and you can just paste it and use it. This will work with other automatically parsed expressions like 2+3 as well.

Jason B.
  • 68,381
  • 3
  • 139
  • 286
  • thanks JasonB! exactly what I was looking for! – billc Apr 06 '16 at 14:23
  • Note that this answer will not retain all the 2D input formatting that your original cell might have had. That means you cannot use this answer to recover exactly what you had in an input cell that you, say, accidentally deleted. To recover everything, use Carl Woll's answer below. – Jess Riedel Aug 08 '19 at 22:45
4

Another idea is to CellPrint the InString output:

reprintInput[n_] := CellPrint @ Cell[
    BoxData[ToExpression@InString[n]],
    "Input"
]

For your example:

$Line=41;
{{2}, {3}} //MatrixForm

enter image description here

Then, reprintInput produces an exact copy of the original input cell:

reprintInput[42]

{{2}, {3}} // MatrixForm

If you just want to store an unevaluated version of the input somewhere, you could use something like:

input = ToExpression[ToExpression@InString[42], StandardForm, Hold];
input //InputForm

Hold[MatrixForm[{{2}, {3}}]]

This is similar to @JasonB.'s answer, but there is no need to use copy/paste.

Carl Woll
  • 130,679
  • 6
  • 243
  • 355
  • Thank you! This actually recovered my complete input cell (which I had accidentally deleted, and mysteriously was undo-able). This saved me tremendous time. – Jess Riedel Aug 08 '19 at 22:36
2

I don't think it is possible by reading the In, since the information is stored in a list of HoldPattern expression, and your input is not preserved. But if you did not delete the input cell, it is possible to obtain your input by doing this:

CellPrint@
Cell[Cases[NotebookRead@Cells[], 
Cell[x_, _, _, CellLabel -> "In[42]:="] -> x][[1]], "Input"]

You can get exactly your input in a new cell.

vapor
  • 7,911
  • 2
  • 22
  • 55