3
$\begingroup$

After running the code

In[1]:= a = 2;
In[2]:= ++a

Out[2]= 3

if In[2] is evaluated repeatedly, a keeps increasing, so the unevaluated form is stored.
If, however, the cell is deleted from the notebook and ctrl+z doesn't reach sufficiently far, how to restore the unevaluated form?

$\endgroup$
2

2 Answers 2

3
$\begingroup$

You can use the fact that In is just a symbol, with DownValues you can inspect. For instance, with your inputs,

FirstCase[DownValues[In],
  HoldPattern[Verbatim[HoldPattern[In[2]]] :> _]]
(* HoldPattern[In[2]] :> ++a *)
$\endgroup$
3
$\begingroup$

In addition to looking at the DownValues of In, you could also make use of InString:

$Line = 0;
a = 2;
++a;

ToExpression[
    ToExpression[InString[1]],
    StandardForm,
    Defer
]

a = 2;

(I see that this answer is close to a duplicate of @JasonB's link in the comments. I will leave it, though, as I don't like using DisplayForm)

$\endgroup$
6
  • $\begingroup$ Your comment made me wonder why I used DisplayForm there (I don't really know what it does). I didn't notice your double use of ToExpression, which seems to have some evaluation if the original input is {{2}, {3}} // MatrixForm $\endgroup$
    – Jason B.
    Commented Jan 22, 2018 at 23:24
  • $\begingroup$ @JasonB. DisplayForm basically converts the parts of the input that are expressions into boxes, and then renders those boxes. I don't like DisplayForm because something like "1" could be either a string expression, or the box form of 1, so DisplayForm has to use heuristics to decide what to do. As for your example, what kind of evaluation are you talking of? When I use my code on that example, I get the expected Defer[MatrixForm[{{2}, {3}}]]. $\endgroup$
    – Carl Woll
    Commented Jan 23, 2018 at 1:20
  • $\begingroup$ When I run it, it still displays in MatrixForm - i.imgur.com/I7tNH8e.png. I don't know why my results are different from yours. I appreciate that the front end uses boxes for everything, but if it does it well then I don't ever have to think about them :-) I just prefer for everything box-related to be abstracted away. $\endgroup$
    – Jason B.
    Commented Jan 23, 2018 at 1:36
  • $\begingroup$ Isn't MatrixForm part of the input? Why would it go away? I see the same thing you do. $\endgroup$
    – Carl Woll
    Commented Jan 23, 2018 at 1:43
  • $\begingroup$ this may be off topic since it doesn't so much relate to this question. But take the XXXForm out of it. I took the other question to mean that if the input string was 1 // f // g then it would be wrong for the return to be g[ f[ 1] ]. Is your point that it isn't the evaluator that turns the former into the latter, and therefore no evaluation occurred? $\endgroup$
    – Jason B.
    Commented Jan 23, 2018 at 2:35

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