How to intercept the assignment of a new value to the variable In?

I want to intercept the assignment of new values ​​for the variable In .

I tried to do this by specifying UpValues for In , but in this case it will not help:

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

PS This question arose as part of a previous question on the scene when Mathematica created the new Symbol s.

EDIT

I would like to explicitly intercept the purpose of new DownValue for the variable In . $Pre is executed after this assignment and after creating the whole new Symbol 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
source share
1 answer

Have you watched $Pre and $PreRead ?

$Pre is a global variable whose value, if set, is applied to each input expression.

$PreRead is a global variable whose value, if set, is applied to the text or rectangular shape of each input expression before it is sent to Mathematica.

UPDATE (now with a 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 closer 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 is impossible to intercept In at the *Value level, because the kernel simply does not interact with In by manipulating the values ​​in the top-level Mathematica code.

+4
source

Source: https://habr.com/ru/post/1347493/


All Articles