问题
I wish to intercept assigning new values for the In variable.
I have tried to do this by defining UpValues for In but it does not help in this case:
Unprotect[In];
In /: Set[In[line_], expr_] /; ! TrueQ[$InsideSet] :=
Block[{$InsideSet = True},
Print[HoldForm@HoldForm[expr]; Set[In[line], expr]]]
In /: SetDelayed[In[line_], expr_] /; ! TrueQ[$InsideSet] :=
Block[{$InsideSet = True},
Print[HoldForm@HoldForm[expr]; SetDelayed[In[line], expr]]]
Is it possible to intercept it?
P.S. This question has arisen as a part of previous question on the stage when Mathematica creates new Symbols.
EDIT
I would wish to intercept explicitly the assignment new DownValue for the In variable. $Pre executes after this assignment and after creating all new Symbols in the current $Context:
In[1]:= $Pre := (Print[Names["`*"]];
Print[DownValues[In][[All, 1]]]; ##) &
In[2]:= a
During evaluation of In[2]:= {a}
During evaluation of In[2]:= {HoldPattern[In[1]],HoldPattern[In[2]]}
Out[2]= a
回答1:
Have you looked at $Pre and $PreRead?
$Pre is a global variable whose value, if set, is applied to every input expression.
$PreRead is a global variable whose value, if set, is applied to the text or box form of every input expression before it is fed to Mathematica.
UPDATE (now with better example)
In[1]:= $Pre =
Function[{x}, Print["In[",$Line,"] is: ", Unevaluated[x]]; x, HoldFirst];
In[2]:= 2 + 2
During evaluation of In[2]:= In[2] is: 2+2
Out[2]= 4
In[3]:= InString[2]
During evaluation of In[3]:= In[3] is: InString[2]
Out[3]= "\\(2 + 2\\)"
UPDATE 2
Replace $Pre with $PreRead in my code above and you get close to what you want, I believe:
In[1]:= $PreRead = Function[{x}, Print[Names["`*"]]; x, HoldFirst]
Out[1]= Function[{x}, Print[Names["`*"]]; x, HoldFirst]
In[2]:= a = 1
During evaluation of In[2]:= {x}
Out[2]= 1
In[3]:= b = 2
During evaluation of In[3]:= {a,x}
Out[3]= 2
It's not possible to intercept In at the *Value level because the Kernel is simply not interacting with In via value manipulation in "top-level" Mathematica code.
来源:https://stackoverflow.com/questions/5626387/how-to-intercept-assigning-new-value-for-the-in-variable